Skip to main content

dbmd_core/
store.rs

1//! `store` — walk, locate, and shard a db.md store.
2//!
3//! A db.md store is one directory marked by an uppercase `DB.md` at its root.
4//! [`Store::open`] is the single gate every store-walking subcommand goes
5//! through; a missing `DB.md` is the [`NotAStore`] error (`NOT_A_STORE`). The
6//! toolkit never guesses a store root.
7//!
8//! Scale discipline lives here: [`Store::walk`] and the layer/type-folder
9//! walks are **SWEEP** primitives used only by `validate --all`,
10//! `index rebuild`, and `stats`. The interactive loop instead uses
11//! [`Store::find_links_to`] / [`Store::find_links_to_any`] (a single
12//! presence-only content scan) and the `index.jsonl` sidecar readers
13//! ([`Store::find_by_type`] / [`Store::find_by_where`] /
14//! [`Store::read_type_index`]) — never a whole-store parse. The batch
15//! [`Store::find_links_to_any`] is what keeps the working-set validate's
16//! incoming-linker discovery a single store scan rather than one scan per
17//! changed object.
18//!
19//! Link edges are defined once, here, by the shared [`extract_edge_targets`] /
20//! [`canonical_link_target`] / [`link_edge_key`] helpers (fence-aware,
21//! whitespace-trimmed, case-folded to the filesystem), so the forward view
22//! (`graph::forwardlinks`), the backward view ([`Store::find_links_to_any`]),
23//! `rename`, and `validate` all agree on exactly which `[[...]]` is an edge.
24//! [`ensure_path_within_store`] is the within-store containment gate every
25//! caller-influenced path passes through before it is read or traversed.
26
27use std::collections::BTreeMap;
28use std::fs::File;
29use std::path::{Path, PathBuf};
30use std::sync::Arc;
31use std::sync::{Mutex, MutexGuard};
32use std::time::{SystemTime, UNIX_EPOCH};
33
34use crate::index::IndexRecord;
35use crate::parser::{parse_db_md, Config, Frontmatter};
36use chrono::{DateTime, Datelike, FixedOffset};
37
38/// Basenames that are never content files: the config marker and the two
39/// curator-maintained catalogs. The store walks skip these so a SWEEP over the
40/// content layers never mistakes a catalog for a record.
41///
42/// Only `index.md` is excluded by basename. A descendant `DB.md` is not content:
43/// it marks a foreign nested-store boundary, and the walker prunes the entire
44/// directory before reaching that marker. The root `DB.md` / `log.md` (and the
45/// `log/` archive) live outside every layer walk.
46const NON_CONTENT_BASENAMES: [&str; 1] = ["index.md"];
47
48/// The complete machine-twin sidecar that backs every structured read.
49const TYPE_INDEX_FILE: &str = "index.jsonl";
50
51/// Returned when a path is opened as a store but has no `DB.md` at its root.
52/// Surfaced as the structured code `NOT_A_STORE` with a non-zero exit.
53#[derive(Debug, thiserror::Error)]
54#[error("not a db.md store: {path} has no DB.md")]
55pub struct NotAStore {
56    /// The path that was inspected.
57    pub path: PathBuf,
58}
59
60/// Errors from store-level operations (walk, locate, shard, sidecar read).
61#[derive(Debug, thiserror::Error)]
62pub enum StoreError {
63    /// A sidecar `index.jsonl` could not be read or parsed.
64    #[error("failed to read type index {path}: {message}")]
65    BadTypeIndex {
66        /// The sidecar file.
67        path: PathBuf,
68        /// What went wrong.
69        message: String,
70    },
71
72    /// A required date field for sharding was absent or unparseable, and there
73    /// was no usable fallback.
74    #[error("cannot compute shard path for {file}: no usable date field")]
75    NoShardDate {
76        /// The file being placed.
77        file: PathBuf,
78    },
79
80    /// An embedded-ripgrep scan failed to start or run.
81    #[error("search failed under {root}: {message}")]
82    Search {
83        /// The root the scan ran under.
84        root: PathBuf,
85        /// What went wrong.
86        message: String,
87    },
88
89    /// An underlying I/O failure.
90    #[error(transparent)]
91    Io(#[from] std::io::Error),
92}
93
94/// The three canonical layers of a db.md store.
95///
96/// `Ord`/`PartialOrd` are derived (additively) because sibling modules key
97/// `BTreeMap`s on `Layer` (e.g. `stats::Stats::files_per_layer`); the canonical
98/// declaration order (`Sources` < `Records`) is the sort order.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
100pub enum Layer {
101    /// `sources/` — raw evidence (documentary + testimonial); immutable; date-sharded at scale.
102    Sources,
103    /// `records/` — everything the agent authors; meta-typed fact/operational/conclusion; entity types flat, event types sharded.
104    Records,
105}
106
107impl Layer {
108    /// The on-disk folder name for this layer (`"sources"` / `"records"`).
109    pub fn dir_name(self) -> &'static str {
110        match self {
111            Layer::Sources => "sources",
112            Layer::Records => "records",
113        }
114    }
115
116    /// Parse a layer from its folder name; `None` for anything else.
117    pub fn from_dir_name(name: &str) -> Option<Self> {
118        match name {
119            "sources" => Some(Layer::Sources),
120            "records" => Some(Layer::Records),
121            _ => None,
122        }
123    }
124
125    /// Every layer, in canonical order.
126    pub fn all() -> [Layer; 2] {
127        [Layer::Sources, Layer::Records]
128    }
129}
130
131/// An opened db.md store: its root path plus the parsed `DB.md` [`Config`].
132///
133/// Construct via [`Store::open`]; that is the only path in, and it validates
134/// the `DB.md` marker so downstream code can assume a real store.
135#[derive(Debug, Clone)]
136pub struct Store {
137    /// The store root (the directory containing `DB.md`).
138    pub root: PathBuf,
139    /// Absolute lexical spelling frozen when the root capability is opened.
140    /// This is used only to translate absolute CLI arguments into relative
141    /// capability keys; no filesystem operation reopens it.
142    root_locator: PathBuf,
143    /// The parsed `DB.md` config (agent instructions, policies, schemas).
144    pub config: Config,
145    /// The directory inode selected when the store was opened. Every
146    /// store-relative read starts from this held descriptor, never from
147    /// `root`'s mutable pathname.
148    root_capability: Arc<File>,
149    /// Reused no-follow parent directory capabilities. Interactive operations
150    /// probe many files in the same type/shard folders; caching those held
151    /// parents preserves capability safety without retraversing and rescanning
152    /// every ancestor for every link or validation check.
153    reader: Arc<Mutex<crate::fsx::BoundedDirReader>>,
154}
155
156/// Cached descriptor-relative regular-file reader for one [`Store`].
157///
158/// Sweep callers should create one reader and reuse it across every candidate:
159/// parent directory capabilities are cached, so each file costs one no-follow
160/// `openat` rather than a repeated pathname canonicalization or ancestor walk.
161/// The reader refuses symlink components, non-regular leaves, and descendant
162/// db.md store boundaries.
163pub struct StoreReader {
164    reader: crate::fsx::BoundedDirReader,
165}
166
167impl StoreReader {
168    /// Open one regular store-relative file through the retained root.
169    pub fn open(&mut self, path: &Path) -> std::io::Result<File> {
170        self.reader.open(path)
171    }
172}
173
174/// Exclusive cooperative mutation gate for one opened store. The lock is tied
175/// to the held root inode, not the mutable pathname in [`Store::root`].
176pub struct StoreTransaction {
177    _lock: File,
178}
179
180fn absolute_store_locator(path: &Path) -> std::io::Result<PathBuf> {
181    if path.is_absolute() {
182        Ok(path.to_path_buf())
183    } else {
184        Ok(std::env::current_dir()?.join(path))
185    }
186}
187
188impl Store {
189    /// True if `path` is a db.md store root: an uppercase `DB.md` file exists
190    /// at `path`. On case-sensitive filesystems a lowercase `db.md` must NOT
191    /// count (the lowercase name refers to the project/spec, not the marker).
192    pub fn is_db_md_store(path: &Path) -> bool {
193        let Ok(root) = crate::fsx::open_directory_nofollow(path) else {
194            return false;
195        };
196        crate::fsx::directory_contains_exact_regular(&root, "DB.md".as_ref()).unwrap_or(false)
197    }
198
199    /// Open `path` as a db.md store and require `DB.md` to be readable and
200    /// parseable. Normal commands should enter through this strict gate so a
201    /// damaged config cannot silently disable schema or policy rules.
202    pub fn open_strict(path: &Path) -> crate::Result<Store> {
203        let root_capability = match crate::fsx::open_directory_nofollow(path) {
204            Ok(root) => root,
205            Err(_) => {
206                return Err(NotAStore {
207                    path: path.to_path_buf(),
208                }
209                .into())
210            }
211        };
212        if !crate::fsx::directory_contains_exact_regular(&root_capability, "DB.md".as_ref())? {
213            return Err(NotAStore {
214                path: path.to_path_buf(),
215            }
216            .into());
217        }
218        let db_md = path.join("DB.md");
219        let mut reader = crate::fsx::BoundedDirReader::from_root(&root_capability)?;
220        let bytes = reader.read(Path::new("DB.md"), crate::parser::MAX_DBMD_FILE_BYTES)?;
221        let text = String::from_utf8(bytes)
222            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
223        let config = parse_db_md(&text, &db_md)?;
224        Ok(Store {
225            root: path.to_path_buf(),
226            root_locator: absolute_store_locator(path)?,
227            config,
228            root_capability: Arc::new(root_capability),
229            reader: Arc::new(Mutex::new(reader)),
230        })
231    }
232
233    /// Open `path` as a db.md store: confirm the `DB.md` marker (else
234    /// [`NotAStore`]) and parse the `DB.md` config when possible. This is the
235    /// lenient validation-oriented open path: a damaged `DB.md` still marks the
236    /// directory as a store so `dbmd validate` can report the config error as an
237    /// issue. Normal CLI commands should use [`Store::open_strict`] instead.
238    pub fn open(path: &Path) -> Result<Store, NotAStore> {
239        let root_capability = crate::fsx::open_directory_nofollow(path).map_err(|_| NotAStore {
240            path: path.to_path_buf(),
241        })?;
242        if !crate::fsx::directory_contains_exact_regular(&root_capability, "DB.md".as_ref())
243            .unwrap_or(false)
244        {
245            return Err(NotAStore {
246                path: path.to_path_buf(),
247            });
248        }
249        let db_md = path.join("DB.md");
250        // The marker exists; parse its config. A read or parse failure leaves
251        // the store openable with default config rather than masquerading as
252        // NOT_A_STORE — the marker is present, so this *is* a store; a damaged
253        // DB.md is `dbmd validate`'s job to report, not `open`'s.
254        let mut reader = crate::fsx::BoundedDirReader::from_root(&root_capability)
255            .expect("held root descriptor can be cloned");
256        let config = match reader.read(Path::new("DB.md"), crate::parser::MAX_DBMD_FILE_BYTES) {
257            Ok(bytes) => String::from_utf8(bytes)
258                .ok()
259                .and_then(|text| parse_db_md(&text, &db_md).ok())
260                .unwrap_or_default(),
261            Err(_) => Config::default(),
262        };
263        Ok(Store {
264            root: path.to_path_buf(),
265            root_locator: absolute_store_locator(path).map_err(|_| NotAStore {
266                path: path.to_path_buf(),
267            })?,
268            config,
269            root_capability: Arc::new(root_capability),
270            reader: Arc::new(Mutex::new(reader)),
271        })
272    }
273
274    /// Construct a held-root store view with an explicitly supplied config.
275    ///
276    /// Validation uses this for a directory that may intentionally lack
277    /// `DB.md`, so the validation engine can report `NOT_A_STORE` as a normal
278    /// issue. Tests use it to isolate code from config parsing. The directory
279    /// itself must exist and is still opened with the same no-follow capability
280    /// as a normal store.
281    pub fn from_root_and_config(path: &Path, config: Config) -> std::io::Result<Store> {
282        let root_capability = crate::fsx::open_directory_nofollow(path)?;
283        let reader = crate::fsx::BoundedDirReader::from_root(&root_capability)?;
284        Ok(Store {
285            root: path.to_path_buf(),
286            root_locator: absolute_store_locator(path)?,
287            config,
288            root_capability: Arc::new(root_capability),
289            reader: Arc::new(Mutex::new(reader)),
290        })
291    }
292
293    fn cached_reader(&self) -> std::io::Result<MutexGuard<'_, crate::fsx::BoundedDirReader>> {
294        self.reader
295            .lock()
296            .map_err(|_| std::io::Error::other("store reader lock was poisoned"))
297    }
298
299    /// Open a regular store-relative file from the descriptor retained by this
300    /// `Store`. Absolute inputs are accepted only when they are lexically under
301    /// `self.root`; `..`, absolute escapes, symlink leaves and symlink ancestors
302    /// are rejected by the descriptor traversal.
303    pub fn open_regular(&self, path: &Path) -> std::io::Result<File> {
304        let relative = self.capability_relative(path)?;
305        self.cached_reader()?.open(relative)
306    }
307
308    /// Create a cached descriptor-relative reader for a multi-file sweep.
309    pub fn regular_reader(&self) -> std::io::Result<StoreReader> {
310        Ok(StoreReader {
311            reader: crate::fsx::BoundedDirReader::from_root(&self.root_capability)?,
312        })
313    }
314
315    /// Bounded counterpart to [`Store::open_regular`].
316    pub fn read_bounded(&self, path: &Path, max_bytes: u64) -> std::io::Result<Vec<u8>> {
317        let relative = self.capability_relative(path)?;
318        self.cached_reader()?.read(relative, max_bytes)
319    }
320
321    /// Bounded UTF-8 read from the held store root.
322    pub fn read_text_bounded(&self, path: &Path, max_bytes: u64) -> std::io::Result<String> {
323        String::from_utf8(self.read_bounded(path, max_bytes)?)
324            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
325    }
326
327    /// Atomically replace a regular file beneath the held store root.
328    pub fn write_atomic(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
329        let relative = self.capability_relative(path)?;
330        crate::fsx::write_atomic_beneath(&self.root_capability, relative, bytes, false, true)
331    }
332
333    /// Atomically create a new regular file beneath the held store root.
334    pub fn write_atomic_new(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
335        let relative = self.capability_relative(path)?;
336        crate::fsx::write_atomic_beneath(&self.root_capability, relative, bytes, true, true)
337    }
338
339    /// Atomically replace a derived/rebuildable file beneath the held store
340    /// root without forcing it to stable storage.
341    pub fn write_atomic_nondurable(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
342        let relative = self.capability_relative(path)?;
343        crate::fsx::write_atomic_nondurable_beneath(&self.root_capability, relative, bytes)
344    }
345
346    /// Parse one db.md file through the retained root capability.
347    pub fn read_file(
348        &self,
349        path: &Path,
350    ) -> Result<(crate::parser::Frontmatter, String), crate::parser::ParseError> {
351        let bytes = self
352            .read_bounded(path, crate::parser::MAX_DBMD_FILE_BYTES)
353            .map_err(crate::parser::ParseError::Io)?;
354        let text = String::from_utf8(bytes).map_err(|error| {
355            crate::parser::ParseError::Io(std::io::Error::new(
356                std::io::ErrorKind::InvalidData,
357                error,
358            ))
359        })?;
360        let parsed = crate::parser::split_frontmatter(&text, path)?;
361        let frontmatter = crate::parser::Frontmatter::parse(&parsed.frontmatter_yaml, path)?;
362        Ok((frontmatter, parsed.body))
363    }
364
365    /// Canonically render and atomically replace one db.md file through the
366    /// retained root capability.
367    pub fn write_file(
368        &self,
369        path: &Path,
370        frontmatter: &crate::parser::Frontmatter,
371        body: &str,
372    ) -> Result<(), crate::parser::ParseError> {
373        let contents = crate::parser::render_file(frontmatter, body);
374        self.write_atomic(path, contents.as_bytes())?;
375        Ok(())
376    }
377
378    /// Canonically render and atomically create one db.md file through the
379    /// retained root capability.
380    pub fn write_file_new(
381        &self,
382        path: &Path,
383        frontmatter: &crate::parser::Frontmatter,
384        body: &str,
385    ) -> Result<(), crate::parser::ParseError> {
386        let contents = crate::parser::render_file(frontmatter, body);
387        self.write_atomic_new(path, contents.as_bytes())?;
388        Ok(())
389    }
390
391    /// Metadata for an exact no-follow regular file under the held root.
392    pub fn regular_metadata(&self, path: &Path) -> std::io::Result<std::fs::Metadata> {
393        let relative = self.capability_relative(path)?;
394        self.cached_reader()?.open(relative)?.metadata()
395    }
396
397    /// True only when `path` names a no-follow regular file under the held root.
398    pub fn regular_file_exists(&self, path: &Path) -> std::io::Result<bool> {
399        match self.regular_metadata(path) {
400            Ok(_) => Ok(true),
401            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
402            Err(error) => Err(error),
403        }
404    }
405
406    /// True only when `path` names a no-follow directory under the held root.
407    pub fn directory_exists(&self, path: &Path) -> std::io::Result<bool> {
408        let relative = self.capability_relative(path)?;
409        crate::fsx::directory_exists_beneath(&self.root_capability, relative)
410    }
411
412    /// Confirm exact on-disk component casing through the retained root.
413    pub fn path_case_matches(&self, path: &Path) -> std::io::Result<bool> {
414        let relative = self.capability_relative(path)?;
415        crate::fsx::path_case_matches_beneath(&self.root_capability, relative)
416    }
417
418    /// Ensure a directory hierarchy exists beneath the held root.
419    pub fn create_dir_all(&self, path: &Path) -> std::io::Result<()> {
420        let relative = self.capability_relative(path)?;
421        crate::fsx::open_directory_beneath(&self.root_capability, relative, true).map(drop)
422    }
423
424    /// Immediate visible child directory names, no-follow and nested-store
425    /// pruned.
426    pub fn directory_names(&self, path: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
427        let relative = self.capability_relative(path)?;
428        crate::fsx::directory_names_beneath(&self.root_capability, relative)
429    }
430
431    /// Take the cooperative store-wide mutation gate.
432    pub fn transaction(&self) -> std::io::Result<StoreTransaction> {
433        Ok(StoreTransaction {
434            _lock: crate::fsx::lock_exclusive_beneath(
435                &self.root_capability,
436                Path::new(".dbmd.transaction.lock"),
437            )?,
438        })
439    }
440
441    /// Take a descriptor-relative advisory lock at `path`.
442    pub(crate) fn lock_file(&self, path: &Path) -> std::io::Result<File> {
443        let relative = self.capability_relative(path)?;
444        crate::fsx::lock_exclusive_beneath(&self.root_capability, relative)
445    }
446
447    /// Atomic no-replace rename resolved from the held store root.
448    pub fn rename_noreplace(&self, old: &Path, new: &Path) -> std::io::Result<()> {
449        let old = self.capability_relative(old)?;
450        let new = self.capability_relative(new)?;
451        crate::fsx::rename_beneath(&self.root_capability, old, new)
452    }
453
454    /// Remove one regular file beneath the held store root and sync its parent.
455    pub fn remove_file(&self, path: &Path) -> std::io::Result<()> {
456        let relative = self.capability_relative(path)?;
457        crate::fsx::remove_file_beneath(&self.root_capability, relative)
458    }
459
460    /// List immediate regular-file basenames in a store-relative directory.
461    /// Symlinks and nested-store paths are refused by descriptor traversal.
462    pub fn regular_file_names(&self, directory: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
463        let relative = self.capability_relative(directory)?;
464        crate::fsx::regular_file_names_beneath(&self.root_capability, relative)
465    }
466
467    /// Recursively enumerate regular files beneath a store-relative directory.
468    /// The walk stays rooted at the descriptor retained by this `Store`, skips
469    /// symlinks/hidden entries/nested stores, and never reopens `self.root`.
470    pub fn walk_regular_files(&self, directory: &Path) -> std::io::Result<Vec<PathBuf>> {
471        let relative = self.capability_relative(directory)?;
472        crate::fsx::walk_regular_files_beneath(&self.root_capability, relative)
473    }
474
475    pub fn capability_relative<'a>(&self, path: &'a Path) -> std::io::Result<&'a Path> {
476        let relative = if path.is_absolute() {
477            if let Ok(relative) = path.strip_prefix(&self.root_locator) {
478                relative
479            } else {
480                // macOS exposes the same temporary/system directory through both
481                // `/var` and `/private/var` (likewise `/tmp` and `/private/tmp`).
482                // A containment helper may return the canonical spelling while the
483                // held capability was opened through the alias. Match only these
484                // fixed OS aliases lexically; never canonicalize/reopen the root.
485                #[cfg(target_os = "macos")]
486                {
487                    let mut matched = None;
488                    for (alias, canonical) in [("/var", "/private/var"), ("/tmp", "/private/tmp")] {
489                        if let Ok(suffix) = self.root_locator.strip_prefix(alias) {
490                            let equivalent_root = Path::new(canonical).join(suffix);
491                            if let Ok(relative) = path.strip_prefix(equivalent_root) {
492                                matched = Some(relative);
493                                break;
494                            }
495                        }
496                        if let Ok(suffix) = self.root_locator.strip_prefix(canonical) {
497                            let equivalent_root = Path::new(alias).join(suffix);
498                            if let Ok(relative) = path.strip_prefix(equivalent_root) {
499                                matched = Some(relative);
500                                break;
501                            }
502                        }
503                    }
504                    matched.ok_or_else(|| {
505                        std::io::Error::new(
506                            std::io::ErrorKind::PermissionDenied,
507                            format!(
508                                "path {} is outside store {}",
509                                path.display(),
510                                self.root_locator.display()
511                            ),
512                        )
513                    })?
514                }
515                #[cfg(not(target_os = "macos"))]
516                {
517                    return Err(std::io::Error::new(
518                        std::io::ErrorKind::PermissionDenied,
519                        format!(
520                            "path {} is outside store {}",
521                            path.display(),
522                            self.root_locator.display()
523                        ),
524                    ));
525                }
526            }
527        } else {
528            path
529        };
530        if relative.components().any(|component| {
531            matches!(
532                component,
533                std::path::Component::ParentDir
534                    | std::path::Component::RootDir
535                    | std::path::Component::Prefix(_)
536            )
537        }) {
538            return Err(std::io::Error::new(
539                std::io::ErrorKind::PermissionDenied,
540                "store capability requires a contained relative path",
541            ));
542        }
543        Ok(relative)
544    }
545
546    /// **SWEEP.** Recursively iterate every `.md` content file across
547    /// `sources/` and `records/`, skipping hidden dirs and `log/`.
548    /// Used only by `validate --all`, `index rebuild`, and `stats` — never on
549    /// the interactive loop.
550    pub fn walk(&self) -> Result<Vec<PathBuf>, StoreError> {
551        // Only the three content layers — never root meta files (`DB.md`,
552        // `index.md`, `log.md`) and never `log/`, which live at root and are
553        // outside every layer dir.
554        let mut out = Vec::new();
555        for layer in Layer::all() {
556            out.extend(self.walk_layer(layer)?);
557        }
558        out.sort();
559        Ok(out)
560    }
561
562    /// **SWEEP.** Like [`Store::walk`] but scoped to a single layer.
563    pub fn walk_layer(&self, layer: Layer) -> Result<Vec<PathBuf>, StoreError> {
564        self.walk_content_md(Path::new(layer.dir_name()))
565    }
566
567    /// Enumerate every `.md` file in a single type-folder, **recursing through
568    /// its date-shards** (`sources/emails/**/*.md`). The unit the index builder
569    /// and per-folder rebuild operate on. SWEEP-class (scoped to one folder).
570    pub fn walk_type_folder(&self, type_folder: &Path) -> Result<Vec<PathBuf>, StoreError> {
571        let relative = self.capability_relative(type_folder)?;
572        self.walk_content_md(relative)
573    }
574
575    /// Return visible descendant db.md store roots, stopping at each boundary.
576    ///
577    /// A db.md store cannot own another store. This discovery primitive exists
578    /// for validation: normal walkers prune the boundary and never read through
579    /// it, while `validate` reports the structural error against its `DB.md`.
580    /// Hidden directories stay outside the db.md content model and are skipped.
581    pub fn nested_store_roots(&self) -> Result<Vec<PathBuf>, StoreError> {
582        Ok(crate::fsx::ownership_boundaries_beneath(&self.root_capability)?.1)
583    }
584
585    /// Whether `candidate` resolves to content owned by this store.
586    ///
587    /// Ownership requires both filesystem containment and that the path does
588    /// not cross a descendant store boundary.
589    pub fn owns_path(&self, candidate: &Path) -> bool {
590        self.capability_relative(candidate)
591            .and_then(|relative| {
592                if self.regular_file_exists(relative)? || self.directory_exists(relative)? {
593                    Ok(())
594                } else {
595                    Err(std::io::Error::new(
596                        std::io::ErrorKind::NotFound,
597                        "store path does not exist",
598                    ))
599                }
600            })
601            .is_ok()
602    }
603
604    /// Visible symlinks, all outside the no-follow store ownership model. The
605    /// scan never follows a link or reads its target bytes; mutating callers use
606    /// it to surface that ignored content exists instead of silently implying
607    /// the whole visible tree was processed.
608    pub fn unowned_symlinks(&self) -> Result<Vec<PathBuf>, StoreError> {
609        Ok(crate::fsx::ownership_boundaries_beneath(&self.root_capability)?.0)
610    }
611
612    /// The ≤`n` most-recent files in a type-folder by frontmatter `updated`
613    /// (descending), ties broken by store-relative path (ascending) — a total
614    /// order, so write-through and rebuild never disagree on #500 vs #501.
615    ///
616    /// Reads `updated` across the folder's shards — a SWEEP cost absorbed into
617    /// `index rebuild`. The write-through path never calls this. The
618    /// cap-selection primitive for the 500-entry `index.md` browse view.
619    pub fn recent_in_type_folder(
620        &self,
621        type_folder: &Path,
622        n: usize,
623    ) -> Result<Vec<PathBuf>, StoreError> {
624        let files = self.walk_type_folder(type_folder)?;
625        // (updated, rel-path) for each file. Files missing/unparseable
626        // `updated` sort *after* dated ones (None last), then by path — so they
627        // are deterministically the lowest-priority candidates for the cap, not
628        // dropped silently. The total order (updated desc, path asc) is what
629        // keeps write-through and rebuild agreeing on #500 vs #501.
630        let mut keyed: Vec<(Option<DateTime<FixedOffset>>, PathBuf)> = files
631            .into_iter()
632            .map(|rel| {
633                let updated = self.read_updated(&rel);
634                (updated, rel)
635            })
636            .collect();
637        keyed.sort_by(|a, b| {
638            // `updated` descending: newest first. `None` is treated as the
639            // oldest possible, so dated files always win a cap slot over
640            // undated ones.
641            let by_updated = b.0.cmp(&a.0);
642            by_updated.then_with(|| a.1.cmp(&b.1))
643        });
644        keyed.truncate(n);
645        Ok(keyed.into_iter().map(|(_, rel)| rel).collect())
646    }
647
648    /// The shard/flat predicate: true if the type date-shards, false if it
649    /// stays flat. True for source types and event record types
650    /// (`expense`/`invoice`/`meeting` + custom `order`/`ticket`/`transaction`),
651    /// or when `DB.md ## Schemas` declares `shard: by-date`. False for
652    /// dedup-bounded entity types (`contact`/`company`/`decision`) and
653    /// conclusion records (`profile`/`concept`/`synthesis`).
654    pub fn type_shards(&self, type_: &str) -> bool {
655        // A `DB.md ## Schemas` `### <type>` block with a `shard:` directive is
656        // authoritative — it is the v0.2 generic-model way to declare sharding,
657        // so it overrides the built-in default below (in either direction).
658        if let Some(shard) = self.config.schemas.get(type_).and_then(|s| s.shard) {
659            return shard;
660        }
661        // Built-in default for the example types. Sharding is a property of the
662        // *type*:
663        //  - source types carry a primary date field and shard;
664        //  - event record types track business volume and shard;
665        //  - dedup-bounded entity types and curation-bounded conclusion
666        //    records (`profile`/`concept`/`synthesis`) stay flat.
667        // Any type can override this via a `shard:` directive (above).
668        matches!(
669            type_,
670            // source types (documentary + testimonial)
671            "email" | "transcript" | "pdf-source" | "note"
672            // event record types (canonical)
673            | "expense" | "invoice" | "meeting"
674            // event record types (recognized custom, per the plan)
675            | "order" | "ticket" | "transaction"
676        )
677    }
678
679    /// Compute the canonical write path for a new file. For a sharding type
680    /// (per [`Store::type_shards`]) insert `<YYYY>/<MM>/` from the type's
681    /// primary date field (`email.date`, `expense.date`, … fallback `created`)
682    /// under the type folder; flat types (entity + conclusion records) get no
683    /// shard segment.
684    /// Deterministic + stable: same input → same path, so a record never moves
685    /// once written.
686    pub fn shard_path_for(
687        &self,
688        type_: &str,
689        frontmatter: &Frontmatter,
690        name: &str,
691    ) -> Result<PathBuf, StoreError> {
692        self.shard_path_in(&default_type_folder(type_), type_, frontmatter, name)
693    }
694
695    /// Like [`Store::shard_path_for`], but compute the path under an explicit,
696    /// caller-resolved type-folder rather than the canonical default. This lets a
697    /// write surface honour an agent-supplied conforming sub-folder — e.g. a
698    /// conclusion record filed under `records/profiles/`, `records/concepts/`, or
699    /// `records/synthesis/` (a conclusion record may be filed under ANY
700    /// `records/<folder>/`, not only its canonical one) — while still applying
701    /// date-sharding for sharding types. The folder must be a conforming
702    /// `<layer>/<type-folder>` (2
703    /// components, recognized layer); the caller is responsible for that (see the
704    /// CLI's `resolve_write_path`), so it is taken as given here.
705    ///
706    /// Sharding is still a property of the *type*: a sharding type gets the
707    /// `<YYYY>/<MM>` segment under `folder`; a flat type lands directly in it.
708    pub fn shard_path_in(
709        &self,
710        folder: &Path,
711        type_: &str,
712        frontmatter: &Frontmatter,
713        name: &str,
714    ) -> Result<PathBuf, StoreError> {
715        let folder = folder.to_path_buf();
716        let filename = ensure_md_extension(name);
717
718        if !self.type_shards(type_) {
719            // Flat type (entity records, conclusion records, decisions): no
720            // shard segment.
721            return Ok(folder.join(filename));
722        }
723
724        // Sharding type: derive <YYYY>/<MM> from the primary date field, with
725        // `created` as the universal fallback. Reading the public `Frontmatter`
726        // fields directly (typed `created`/`updated` + raw `extra`) avoids the
727        // not-yet-implemented `Frontmatter::get`/`parse` and keeps this pure.
728        let (year, month) = self
729            .primary_shard_segment(type_, frontmatter)
730            .ok_or_else(|| StoreError::NoShardDate {
731                file: folder.join(&filename),
732            })?;
733
734        Ok(folder.join(year).join(month).join(filename))
735    }
736
737    /// Find files with an incoming wiki-link to `target` via a **single
738    /// presence-only content scan** for an edge to `target` across all layers,
739    /// using the shared fence-aware/whitespace-trimmed/case-folded edge notion
740    /// ([`extract_edge_targets`]). Loop-fast; no whole-graph build. Returns
741    /// store-relative paths.
742    pub fn find_links_to(&self, target: &Path) -> Result<Vec<PathBuf>, StoreError> {
743        // A single target is just the degenerate batch case — one key, one store
744        // scan. Routing through `find_links_to_any` keeps the
745        // pattern construction and the scan loop in exactly one place. The
746        // batch API takes `&[PathBuf]`, so the one-element slice is owned (a
747        // single alloc on this single-target convenience path; the batch path
748        // validate.rs rides is untouched).
749        self.find_links_to_any(&[target.to_path_buf()])
750    }
751
752    /// Find every file with an incoming wiki-link to **any** of `targets`, in a
753    /// **single content pass** over the store (one `.md` walk, one presence-only
754    /// edge scan per file). This is the batch incoming-linker finder the
755    /// working-set [`crate::validate::validate_working_set`] sits on: it must find
756    /// the linkers for the *whole* changed set without paying a full store read
757    /// per changed object. Cost is therefore one store scan (O(store)), NOT
758    /// `targets.len() × store` — calling [`find_links_to`](Self::find_links_to)
759    /// in a loop would reread every `.md` once per target and is the exact
760    /// `O(changed × store)` blow-up this method exists to prevent. Returns
761    /// store-relative paths (deduped, sorted).
762    ///
763    /// **One edge notion with `forwardlinks`/`rename`/`validate`.** A file links
764    /// to a target iff [`extract_edge_targets`] (fence-aware, whitespace-trimmed)
765    /// of its content yields a target whose [`link_edge_key`] equals the target's
766    /// — the *same* definition the forward view and the rename rewriter use. The
767    /// previous implementation used a literal-adjacency ripgrep regex that (a)
768    /// matched `[[...]]` text inside fenced code examples (which validate treats
769    /// as non-edges), (b) missed inner-whitespace padding (`[[ x ]]`), and (c)
770    /// compared case-sensitively even where the filesystem resolves links
771    /// case-insensitively — so backlinks/links/rename silently disagreed with
772    /// forwardlinks and validate. Reading content and routing through the shared
773    /// extractor removes all three divergences.
774    ///
775    /// Why content scan and not the sidecar `links` field: the sidecar projects
776    /// only the frontmatter `links:` array, so it misses edges written in the
777    /// body or in typed fields (`company: [[…]]`). Finding an incoming link to an
778    /// arbitrary path therefore requires reading file content.
779    pub fn find_links_to_any(&self, targets: &[PathBuf]) -> Result<Vec<PathBuf>, StoreError> {
780        // Build the set of comparison keys for the requested targets, in the
781        // canonical (case-folded where the filesystem is case-insensitive) form
782        // the edge extractor emits. An empty key (a target that renders to no
783        // link text, e.g. `""` or `"./"`) contributes nothing — and crucially the
784        // empty set short-circuits below so we never report every file.
785        let want: std::collections::HashSet<String> = targets
786            .iter()
787            .filter_map(|t| {
788                let canonical = canonical_link_target(&t.to_string_lossy());
789                if canonical.is_empty() {
790                    None
791                } else {
792                    Some(link_edge_key(&canonical))
793                }
794            })
795            .collect();
796        if want.is_empty() {
797            return Ok(Vec::new());
798        }
799
800        let mut hits = std::collections::BTreeSet::new();
801        let mut reader =
802            crate::fsx::BoundedDirReader::from_root(&self.root_capability).map_err(|error| {
803                StoreError::Search {
804                    root: self.root.clone(),
805                    message: format!("could not hold the store read capability: {error}"),
806                }
807            })?;
808        // Scan every `.md` file in the store (skip hidden + `log/`), including
809        // `index.md` catalogs — an incoming reference is wherever the link text
810        // lives; the caller decides relevance. ONE walk for the whole target set;
811        // per file we stop at the first matching edge (presence is all we need),
812        // so a file that links to several targets is read once, not once per
813        // target.
814        for rel in self.walk_all_md()? {
815            // Read lossily: a `.md` verbatim-ingested into `sources/` can carry a
816            // stray non-UTF-8 byte (a mis-decoded Latin-1 import). Decoding
817            // lossily substitutes replacement characters instead of erroring, so
818            // one bad byte on a link-bearing line no longer aborts the whole
819            // store scan (the historical `UTF8`-sink failure). The link syntax is
820            // ASCII, so a replacement char elsewhere on the line never hides a
821            // `[[...]]`. A read error (not a decode error) is genuine I/O trouble
822            // and propagates.
823            let bytes = match reader.read(&rel, crate::parser::MAX_DBMD_FILE_BYTES) {
824                Ok(bytes) => bytes,
825                Err(error) => {
826                    return Err(StoreError::Search {
827                        root: self.root.clone(),
828                        message: format!("read failed in {}: {error}", rel.display()),
829                    })
830                }
831            };
832            let text = String::from_utf8_lossy(&bytes);
833            for target in extract_edge_targets(&text) {
834                if want.contains(&link_edge_key(&target)) {
835                    hits.insert(rel);
836                    break;
837                }
838            }
839        }
840        Ok(hits.into_iter().collect())
841    }
842
843    /// Candidate set for a `type` query: read every type-folder `index.jsonl`
844    /// sidecar in the type's single layer and return the records of that
845    /// `type`. Complete and cold-cache-proof — NOT a walk-and-parse or a
846    /// frontmatter ripgrep scan, and **never a store-wide read**.
847    ///
848    /// The read is bounded to the type's one layer subtree
849    /// (O(entities-in-layer)): a type lives in exactly one layer, and
850    /// `default_type_folder` always encodes it (recognized → its SPEC layer;
851    /// unrecognized → `records/`), so the walk never fans out across every
852    /// sidecar in the store and stays inside the interactive loop's
853    /// O(entities) contract.
854    ///
855    /// The whole-layer read — rather than reading only the type's canonical
856    /// folder sidecar when it happens to exist — is what makes the result
857    /// *complete*. A single `type` can legitimately be filed across several
858    /// folders within its layer: a conclusion `profile` filed under any
859    /// `records/<folder>/`, or a `contact` filed in `records/clients/` alongside
860    /// the canonical `records/contacts/`. The previous code read only the
861    /// canonical-guess sidecar whenever it was a file, which silently dropped
862    /// those non-canonical records the moment the canonical sidecar existed —
863    /// returning an incomplete set, and a *different* set as the store grew
864    /// (the omission flipped on once one canonical record was added). That
865    /// broke the dedup/enumeration premise this primitive backs and disagreed
866    /// with `find_by_where_in`, which already walks the whole layer. Filtering
867    /// the layer read by `type` keeps the result complete regardless of how the
868    /// type's records are foldered.
869    pub fn find_by_type(&self, type_: &str) -> Result<Vec<IndexRecord>, StoreError> {
870        let canonical_folder = default_type_folder(type_);
871        let records = self.read_all_type_indexes_in(layer_of_folder(&canonical_folder))?;
872        Ok(records.into_iter().filter(|r| r.type_ == type_).collect())
873    }
874
875    /// Candidate set for a `key=value` frontmatter query, **store-wide**: read
876    /// every type-folder `index.jsonl` sidecar and filter their records. The
877    /// unscoped pre-write dedup primitive; prefer [`Store::find_by_where_in`]
878    /// with a layer scope to stay O(entities-in-layer) on the interactive loop.
879    pub fn find_by_where(&self, key: &str, value: &str) -> Result<Vec<IndexRecord>, StoreError> {
880        self.find_by_where_in(key, value, None)
881    }
882
883    /// Candidate set for a `key=value` frontmatter query, **scoped to one
884    /// layer** when `layer` is `Some`: the sidecar walk is confined to that
885    /// layer's subtree (`<root>/<layer>/`), so the I/O is O(entities-in-layer),
886    /// not O(store records). `None` keeps the store-wide read.
887    ///
888    /// This is what makes `--in <layer>` an I/O scope, not just a result
889    /// filter: a `--where`-only query (no `--type`) used to read every sidecar
890    /// in the store and narrow by layer in memory, breaking the O(entities)
891    /// contract the interactive loop depends on. With a layer in hand we walk
892    /// only that layer's sidecars.
893    pub fn find_by_where_in(
894        &self,
895        key: &str,
896        value: &str,
897        layer: Option<Layer>,
898    ) -> Result<Vec<IndexRecord>, StoreError> {
899        // A `key=value` query can target any frontmatter field across any type,
900        // so within the chosen subtree we still read every type-folder sidecar
901        // and filter. The layer (when given) bounds *which* subtree, turning a
902        // whole-store walk into a single-layer walk.
903        let records = self.read_all_type_indexes_in(layer)?;
904        Ok(records
905            .into_iter()
906            .filter(|r| record_matches_field(r, key, value))
907            .collect())
908    }
909
910    /// Every record across the type-folder `index.jsonl` sidecars, scoped to one
911    /// layer when `layer` is `Some` (the walk is confined to `<root>/<layer>/`)
912    /// else store-wide. Sequential, complete sidecar reads — never a
913    /// walk-and-parse of the content tree.
914    ///
915    /// This is the unfiltered sidecar-enumeration primitive the relationship
916    /// loop sits on: [`crate::graph::backlinks_filtered`] uses it to bound its
917    /// candidate set to the relevant layer (or the whole store) without opening
918    /// the content tree, then confirms each candidate's edge by parsing the file.
919    pub fn sidecar_records(&self, layer: Option<Layer>) -> Result<Vec<IndexRecord>, StoreError> {
920        self.read_all_type_indexes_in(layer)
921    }
922
923    /// Parse a type-folder's `index.jsonl` into [`IndexRecord`]s, applying
924    /// last-write-wins by `path` over any un-compacted lines. The sidecar-read
925    /// primitive every structured query sits on.
926    pub fn read_type_index(&self, index_jsonl: &Path) -> Result<Vec<IndexRecord>, StoreError> {
927        let bytes = self
928            .read_bounded(index_jsonl, crate::parser::MAX_DBMD_FILE_BYTES)
929            .map_err(|e| StoreError::BadTypeIndex {
930                path: index_jsonl.to_path_buf(),
931                message: e.to_string(),
932            })?;
933        let text = String::from_utf8(bytes).map_err(|e| StoreError::BadTypeIndex {
934            path: index_jsonl.to_path_buf(),
935            message: e.to_string(),
936        })?;
937
938        // Last-write-wins by `path` over un-compacted lines: a later line for
939        // the same path supersedes an earlier one (the jsonl is append-mostly
940        // and only compacted on rebuild). Blank lines are skipped; a non-blank
941        // line that is not a valid IndexRecord is a hard parse error.
942        let mut by_path: BTreeMap<PathBuf, IndexRecord> = BTreeMap::new();
943        for (i, line) in text.lines().enumerate() {
944            let trimmed = line.trim();
945            if trimmed.is_empty() {
946                continue;
947            }
948            let record: IndexRecord =
949                serde_json::from_str(trimmed).map_err(|e| StoreError::BadTypeIndex {
950                    path: index_jsonl.to_path_buf(),
951                    message: format!("line {}: {e}", i + 1),
952                })?;
953            by_path.insert(record.path.clone(), record);
954        }
955        // BTreeMap keyed by path → records emerge sorted by path ascending,
956        // a deterministic order independent of line order in the file.
957        Ok(by_path.into_values().collect())
958    }
959
960    /// Resolve a store-relative path to its absolute on-disk path under
961    /// [`root`](Store::root).
962    pub fn abs_path(&self, store_relative: &Path) -> PathBuf {
963        // `Path::join` returns `store_relative` unchanged if it is already
964        // absolute, so passing an absolute path through is a no-op.
965        self.root.join(store_relative)
966    }
967
968    /// Convert an absolute path under the store into its store-relative form.
969    pub fn rel_path(&self, abs: &Path) -> Option<PathBuf> {
970        abs.strip_prefix(&self.root).ok().map(|p| p.to_path_buf())
971    }
972
973    // ── Private helpers ─────────────────────────────────────────────────────
974
975    /// Walk a subtree for content `.md` files (skip hidden dirs, skip `index.md`
976    /// / `DB.md` / `log.md`), returning store-relative paths. Used by the layer
977    /// and type-folder walks.
978    fn walk_content_md(&self, root: &Path) -> Result<Vec<PathBuf>, StoreError> {
979        let mut out = Vec::new();
980        let files = match crate::fsx::walk_regular_files_beneath(&self.root_capability, root) {
981            Ok(files) => files,
982            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(out),
983            Err(error) => return Err(StoreError::Io(error)),
984        };
985        for path in files {
986            if !has_md_extension(&path) {
987                continue;
988            }
989            if is_non_content_basename(&path) {
990                continue;
991            }
992            out.push(path);
993        }
994        out.sort();
995        Ok(out)
996    }
997
998    /// Walk the whole store for **every** `.md` file (including `index.md`),
999    /// skipping hidden dirs and the `log/` archive tree. Used by the backlink
1000    /// scan, where the literal link text can live in any markdown file.
1001    fn walk_all_md(&self) -> Result<Vec<PathBuf>, StoreError> {
1002        let mut out = Vec::new();
1003        for path in crate::fsx::walk_regular_files_beneath(&self.root_capability, Path::new(""))? {
1004            if !has_md_extension(&path) {
1005                continue;
1006            }
1007            if path.components().next().map(|c| c.as_os_str()) == Some("log".as_ref()) {
1008                continue;
1009            }
1010            out.push(path);
1011        }
1012        out.sort();
1013        Ok(out)
1014    }
1015
1016    /// Read and merge every type-folder `index.jsonl` sidecar under `layer`
1017    /// when given, else the whole store (skip hidden + `log/`). Each sidecar is
1018    /// read with last-write-wins by path; across sidecars, paths are disjoint by
1019    /// construction (one sidecar per folder), so a plain concatenation preserves
1020    /// completeness. A layer scope confines the walk to `<root>/<layer>/`, which
1021    /// is what keeps `find_by_where_in` O(entities-in-layer).
1022    fn read_all_type_indexes_in(
1023        &self,
1024        layer: Option<Layer>,
1025    ) -> Result<Vec<IndexRecord>, StoreError> {
1026        let mut out = Vec::new();
1027        for sidecar in self.find_type_index_files_in(layer)? {
1028            out.extend(self.read_type_index(&sidecar)?);
1029        }
1030        Ok(out)
1031    }
1032
1033    /// Locate every `index.jsonl` sidecar under `layer` (when given) else the
1034    /// whole store (skip hidden + `log/`), returning store-relative paths. A
1035    /// scoped read walks `<root>/<layer>/`; the store-wide read enumerates the
1036    /// two canonical layer subtrees (`sources/`, `records/`) — the
1037    /// same store model [`Store::walk`] uses — rather than walking from
1038    /// `self.root`. Walking from root would descend into non-layer top-level
1039    /// dirs (`EXPECTED/` test goldens, an `archive/` of frozen index copies,
1040    /// any sibling folder holding store-relative `path`s), pulling their
1041    /// sidecars in and returning every record twice. A non-existent layer
1042    /// subtree yields no sidecars rather than walking a missing path.
1043    fn find_type_index_files_in(&self, layer: Option<Layer>) -> Result<Vec<PathBuf>, StoreError> {
1044        // Store-wide read: union the per-layer scoped reads so only the three
1045        // content layers are walked (never root meta files or non-layer dirs),
1046        // matching `Store::walk`. The per-layer paths are disjoint by folder, so
1047        // a plain concatenation preserves completeness.
1048        let Some(layer) = layer else {
1049            let mut out = Vec::new();
1050            for l in Layer::all() {
1051                out.extend(self.find_type_index_files_in(Some(l))?);
1052            }
1053            out.sort();
1054            return Ok(out);
1055        };
1056        let mut out = Vec::new();
1057        let paths = match crate::fsx::walk_regular_files_beneath(
1058            &self.root_capability,
1059            Path::new(layer.dir_name()),
1060        ) {
1061            Ok(paths) => paths,
1062            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(out),
1063            Err(error) => return Err(StoreError::Io(error)),
1064        };
1065        for path in paths {
1066            if path.file_name().and_then(|n| n.to_str()) != Some(TYPE_INDEX_FILE) {
1067                continue;
1068            }
1069            out.push(path);
1070        }
1071        out.sort();
1072        Ok(out)
1073    }
1074
1075    /// Read a file's frontmatter `updated` field as an RFC3339 timestamp,
1076    /// returning `None` when absent/unparseable. A self-contained reader (does
1077    /// not depend on the not-yet-implemented `parser::read_file`); parses the
1078    /// leading `---`-fenced YAML block with the same engine the parser uses.
1079    fn read_updated(&self, path: &Path) -> Option<DateTime<FixedOffset>> {
1080        let bytes = self
1081            .read_bounded(path, crate::parser::MAX_DBMD_FILE_BYTES)
1082            .ok()?;
1083        let text = String::from_utf8(bytes).ok()?;
1084        let yaml = frontmatter_block(&text)?;
1085        let value: serde_norway::Value = serde_norway::from_str(yaml).ok()?;
1086        let raw = value.get("updated")?;
1087        value_to_datetime(raw)
1088    }
1089
1090    /// The `<YYYY>/<MM>` shard segment for a sharding type, from its primary
1091    /// date field with a `created` fallback. Reads the public `Frontmatter`
1092    /// fields directly. `None` when no usable date is present.
1093    fn primary_shard_segment(&self, type_: &str, fm: &Frontmatter) -> Option<(String, String)> {
1094        // Try the type's primary date field first.
1095        if let Some(field) = primary_date_field(type_) {
1096            if let Some(v) = fm.extra.get(field) {
1097                if let Some(seg) = value_to_year_month(v) {
1098                    return Some(seg);
1099                }
1100            }
1101        }
1102        // Universal fallback: the typed `created` timestamp.
1103        fm.created
1104            .map(|dt| (format!("{:04}", dt.year()), format!("{:02}", dt.month())))
1105    }
1106}
1107
1108// ── Path containment (security) ─────────────────────────────────────────────
1109
1110/// Canonicalize `candidate` (resolving symlinks; for a not-yet-existing leaf,
1111/// canonicalize its existing parent chain and re-append the leaf) and return it
1112/// only if it resolves inside `store_root`; otherwise `Err`.
1113///
1114/// This is the single within-store containment gate. A wiki-link target, a
1115/// rename destination, or any other caller-influenced path must pass through
1116/// here before it is read or traversed, so a `..`-laden or symlink-escaping
1117/// target can never turn a store operation into a read of an arbitrary file
1118/// outside the store. `store_root` itself is canonicalized first so the
1119/// `starts_with` comparison is symlink-stable on both sides (e.g. macOS's
1120/// `/tmp` → `/private/tmp`).
1121pub fn ensure_path_within_store(store_root: &Path, candidate: &Path) -> std::io::Result<PathBuf> {
1122    reject_parent_components(store_root, candidate)?;
1123    reject_symlink_tail(store_root, candidate)?;
1124
1125    // Canonicalize the root so both sides of the containment check are in the
1126    // same (fully-resolved) namespace. This also resolves any `..` the root
1127    // itself carries (the user-supplied `--dir`), which the tail-only lexical
1128    // check deliberately leaves in place.
1129    let root = store_root.canonicalize()?;
1130    let resolved = resolve_within(&root, store_root, candidate)?;
1131    reject_nested_store_boundary(&root, &resolved, candidate, store_root)?;
1132    Ok(resolved)
1133}
1134
1135/// Reject every existing symlink in the caller-influenced path below the store
1136/// root. Canonical containment alone is check-then-reopen: an in-root symlink
1137/// may validate, then select different bytes before a later path open. Actual
1138/// reads/writes also use handle-relative `O_NOFOLLOW`; this lexical pass gives
1139/// callers an early, explicit containment refusal while the open is the
1140/// race-proof enforcement.
1141fn reject_symlink_tail(store_root: &Path, candidate: &Path) -> std::io::Result<()> {
1142    // macOS exposes `/var` and `/tmp` as stable system symlink aliases for
1143    // `/private/var` and `/private/tmp`. A store locator may return the
1144    // canonical spelling while an absolute CLI argument retains the alias.
1145    // Normalize only those OS-owned prefixes; caller-controlled symlinks below
1146    // the store root remain forbidden.
1147    let lexical_root = platform_lexical_path(store_root);
1148    let lexical_candidate = platform_lexical_path(candidate);
1149    let tail = lexical_candidate
1150        .strip_prefix(&lexical_root)
1151        .unwrap_or(&lexical_candidate);
1152    let mut cursor = if lexical_candidate.starts_with(&lexical_root) {
1153        lexical_root
1154    } else if lexical_candidate.is_absolute() {
1155        PathBuf::from(std::path::MAIN_SEPARATOR.to_string())
1156    } else {
1157        PathBuf::new()
1158    };
1159    for component in tail.components() {
1160        match component {
1161            std::path::Component::Prefix(_) | std::path::Component::RootDir => continue,
1162            std::path::Component::CurDir => continue,
1163            std::path::Component::ParentDir => {
1164                // The lexical containment gate reports the more specific error.
1165                continue;
1166            }
1167            std::path::Component::Normal(name) => cursor.push(name),
1168        }
1169        match std::fs::symlink_metadata(&cursor) {
1170            Ok(metadata) if metadata.file_type().is_symlink() => {
1171                return Err(std::io::Error::new(
1172                    std::io::ErrorKind::PermissionDenied,
1173                    format!(
1174                        "path {} crosses symlink component {}",
1175                        candidate.display(),
1176                        cursor.display()
1177                    ),
1178                ));
1179            }
1180            Ok(_) => {}
1181            Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
1182            Err(error) => return Err(error),
1183        }
1184    }
1185    Ok(())
1186}
1187
1188#[cfg(target_os = "macos")]
1189fn platform_lexical_path(path: &Path) -> PathBuf {
1190    for (alias, canonical) in [("/var", "/private/var"), ("/tmp", "/private/tmp")] {
1191        if let Ok(tail) = path.strip_prefix(alias) {
1192            return Path::new(canonical).join(tail);
1193        }
1194    }
1195    path.to_path_buf()
1196}
1197
1198#[cfg(not(target_os = "macos"))]
1199fn platform_lexical_path(path: &Path) -> PathBuf {
1200    path.to_path_buf()
1201}
1202
1203/// Reject a path owned by a descendant store. Every directory between the
1204/// canonical root and the resolved candidate is checked, including the
1205/// candidate itself when it is a directory.
1206fn reject_nested_store_boundary(
1207    root: &Path,
1208    resolved: &Path,
1209    candidate: &Path,
1210    store_root: &Path,
1211) -> std::io::Result<()> {
1212    let Ok(rel) = resolved.strip_prefix(root) else {
1213        return Err(outside_store_err(candidate, store_root));
1214    };
1215    if rel != Path::new("DB.md")
1216        && resolved.file_name().and_then(|name| name.to_str()) == Some("DB.md")
1217    {
1218        return Err(std::io::Error::new(
1219            std::io::ErrorKind::PermissionDenied,
1220            format!(
1221                "path {} would create or address a nested db.md store marker",
1222                candidate.display()
1223            ),
1224        ));
1225    }
1226    let mut cursor = root.to_path_buf();
1227    for component in rel.components() {
1228        cursor.push(component.as_os_str());
1229        if cursor.is_dir() && Store::is_db_md_store(&cursor) {
1230            return Err(std::io::Error::new(
1231                std::io::ErrorKind::PermissionDenied,
1232                format!(
1233                    "path {} crosses nested db.md store boundary {}",
1234                    candidate.display(),
1235                    cursor.display()
1236                ),
1237            ));
1238        }
1239    }
1240    Ok(())
1241}
1242
1243/// The lexical half of the containment gate: reject any `..` component in the
1244/// caller-influenced tail of `candidate` (the part beyond the trusted
1245/// `store_root` prefix).
1246fn reject_parent_components(store_root: &Path, candidate: &Path) -> std::io::Result<()> {
1247    // The `..` rejection below must apply only to the *caller-influenced* tail of
1248    // the candidate — never to a `..` the trusted `store_root` itself carries.
1249    // Callers build the candidate as `store_root.join(rel)`, so a user-supplied
1250    // `--dir ../../some/store` legitimately seeds every candidate with leading
1251    // `..` components that belong to the root, not to the sidecar/link target.
1252    // Strip the trusted `store_root` prefix lexically and scrutinize only what
1253    // remains; the root's own `..` is resolved safely by `canonicalize()` just
1254    // below. A candidate that does NOT begin with `store_root` (an absolute
1255    // out-of-store path, a CWD-relative target) keeps the whole path under
1256    // scrutiny — there is no trusted prefix to exempt.
1257    let scrutinized = candidate.strip_prefix(store_root).unwrap_or(candidate);
1258
1259    // Reject any `..` component in the scrutinized tail. A `ParentDir` can never
1260    // be resolved safely by lexical normalization: once a symlink sits earlier in
1261    // the path, `foo/../bar` does NOT equal `bar`, and canonicalizing the existing
1262    // prefix (below) would silently collapse `records/contacts/../../outside` down
1263    // to a path that *appears* inside the root, masking the traversal. There is no
1264    // legitimate in-store caller that needs `..` in the tail — wiki-link targets,
1265    // rename destinations, and graph reads are all forward (`Normal`-only) paths —
1266    // so a tail `..` is always either an escape attempt or a malformed target.
1267    if scrutinized
1268        .components()
1269        .any(|c| matches!(c, std::path::Component::ParentDir))
1270    {
1271        return Err(std::io::Error::new(
1272            std::io::ErrorKind::PermissionDenied,
1273            format!(
1274                "path {} contains a `..` component beyond the store root {} and cannot be contained",
1275                candidate.display(),
1276                store_root.display()
1277            ),
1278        ));
1279    }
1280    Ok(())
1281}
1282
1283/// The resolution half of the containment gate, against a pre-canonicalized
1284/// `root`: canonicalize `candidate` as far as it exists (peeling a virtual
1285/// tail), reassemble, and require the result to stay under `root`.
1286fn resolve_within(root: &Path, store_root: &Path, candidate: &Path) -> std::io::Result<PathBuf> {
1287    // Resolve the candidate as far as it exists on disk. `canonicalize` fails on
1288    // a not-yet-existing leaf, so peel trailing components until the remaining
1289    // prefix exists, canonicalize that, then re-append the peeled tail. This
1290    // resolves any symlink in the existing parent chain (an escape vector) while
1291    // still working for a target that does not exist yet (a rename destination).
1292    let mut existing = candidate.to_path_buf();
1293    let mut tail: Vec<std::ffi::OsString> = Vec::new();
1294    let resolved_prefix = loop {
1295        match existing.canonicalize() {
1296            Ok(p) => break p,
1297            Err(_) => {
1298                // No existing prefix left to canonicalize → resolve relative to
1299                // the canonical root (the candidate is somewhere under, or
1300                // escaping from, the store) and let the containment check below
1301                // decide. Pop one component and keep peeling.
1302                match existing.file_name() {
1303                    Some(name) => {
1304                        tail.push(name.to_os_string());
1305                        if !existing.pop() {
1306                            // Ran out of components without finding an existing
1307                            // prefix: anchor the un-resolvable remainder at the
1308                            // canonical root so a relative candidate is judged
1309                            // against the store, not the process CWD.
1310                            break root.to_path_buf();
1311                        }
1312                    }
1313                    None => {
1314                        // A root/prefix component with no file name and no
1315                        // on-disk existence: anchor at the canonical root.
1316                        break root.to_path_buf();
1317                    }
1318                }
1319            }
1320        }
1321    };
1322
1323    // Reassemble: canonical existing prefix + the peeled (still-virtual) tail,
1324    // in original order (the peel pushed them reversed).
1325    let mut resolved = resolved_prefix;
1326    for name in tail.into_iter().rev() {
1327        resolved.push(name);
1328    }
1329
1330    if resolved.starts_with(root) {
1331        Ok(resolved)
1332    } else {
1333        Err(outside_store_err(candidate, store_root))
1334    }
1335}
1336
1337fn outside_store_err(candidate: &Path, store_root: &Path) -> std::io::Error {
1338    std::io::Error::new(
1339        std::io::ErrorKind::PermissionDenied,
1340        format!(
1341            "path {} resolves outside the store root {}",
1342            candidate.display(),
1343            store_root.display()
1344        ),
1345    )
1346}
1347
1348/// Hot-loop companion to [`ensure_path_within_store`]: identical per-candidate
1349/// semantics, amortized cost. The single-shot gate re-canonicalizes the store
1350/// root and walks the candidate's whole parent chain via `canonicalize` on
1351/// every call — two realpath(3) chains per candidate, which at a 10k-file scan
1352/// set dominates the scan itself. This helper canonicalizes the root ONCE at
1353/// construction and memoizes each distinct parent directory's canonical form
1354/// (scan candidates cluster into a few dozen type/shard folders), so the
1355/// common candidate — an existing, non-symlink file in a known folder — costs
1356/// one `lstat(2)` and a prefix check. Symlink leaves, missing files, and other
1357/// corners fall back to the same full peel-resolution the single-shot gate
1358/// runs, so no candidate gets a weaker check: a poisoned path still resolves
1359/// (or fails) exactly as before.
1360pub struct StoreContainment {
1361    store_root: PathBuf,
1362    /// The store root, canonicalized once at construction.
1363    root: PathBuf,
1364    /// Parent dir → its canonical form (memoized realpath).
1365    dirs: BTreeMap<PathBuf, PathBuf>,
1366}
1367
1368impl StoreContainment {
1369    /// Canonicalize the store root once. Errs only if the root itself cannot
1370    /// resolve (deleted mid-operation) — the same condition that would fail
1371    /// every single-shot gate call.
1372    pub fn new(store_root: &Path) -> std::io::Result<Self> {
1373        Ok(Self {
1374            store_root: store_root.to_path_buf(),
1375            root: store_root.canonicalize()?,
1376            dirs: BTreeMap::new(),
1377        })
1378    }
1379
1380    /// [`ensure_path_within_store`], amortized: same acceptance set, same
1381    /// rejection set (see the struct doc).
1382    pub fn resolve(&mut self, candidate: &Path) -> std::io::Result<PathBuf> {
1383        reject_parent_components(&self.store_root, candidate)?;
1384
1385        // Fast path: an existing, non-symlink leaf under a memoizable parent.
1386        // `symlink_metadata` (lstat, no path resolution) both proves existence
1387        // and rules out a symlink leaf; the parent's canonical form resolves
1388        // every symlink earlier in the chain, so `canonical(parent) + leaf` is
1389        // exactly what `canonicalize(candidate)` would return.
1390        if let (Ok(meta), Some(parent), Some(name)) = (
1391            std::fs::symlink_metadata(candidate),
1392            candidate.parent(),
1393            candidate.file_name(),
1394        ) {
1395            if !meta.file_type().is_symlink() {
1396                let canon_parent = match self.dirs.get(parent) {
1397                    Some(p) => p.clone(),
1398                    None => {
1399                        // Check each distinct parent chain once. The actual file
1400                        // open remains handle-relative and no-follow, so this
1401                        // cache affects diagnostics/performance, not the
1402                        // race-proof enforcement at the I/O boundary.
1403                        reject_symlink_tail(&self.store_root, parent)?;
1404                        let p = parent.canonicalize()?;
1405                        self.dirs.insert(parent.to_path_buf(), p.clone());
1406                        p
1407                    }
1408                };
1409                let resolved = canon_parent.join(name);
1410                if !resolved.starts_with(&self.root) {
1411                    return Err(outside_store_err(candidate, &self.store_root));
1412                }
1413                reject_nested_store_boundary(&self.root, &resolved, candidate, &self.store_root)?;
1414                return Ok(resolved);
1415            }
1416        }
1417
1418        // Slow path — symlink leaf, missing file, no parent: the full peel,
1419        // against the already-canonical root.
1420        reject_symlink_tail(&self.store_root, candidate)?;
1421        let resolved = resolve_within(&self.root, &self.store_root, candidate)?;
1422        reject_nested_store_boundary(&self.root, &resolved, candidate, &self.store_root)?;
1423        Ok(resolved)
1424    }
1425}
1426
1427// ── The shared wiki-link edge notion (graph / stats / validate / rename) ─────
1428//
1429// One definition of "what `[[...]]` text is a real edge" that every relationship
1430// op keys on, so `forwardlinks`, `backlinks`, `links`, `stats`, and `rename`
1431// never disagree with each other (or with `validate`'s body extractor):
1432//
1433//   1. **Fence-aware.** A `[[...]]` inside a ``` / ~~~ fenced code block is a
1434//      documentation example, not an edge — exactly `validate`'s rule. Counting
1435//      it as an edge over-reports backlinks, falsely un-orphans the page, and
1436//      (worst) lets `rename` rewrite verbatim example text.
1437//   2. **Whitespace-trimmed.** `[[ records/contacts/sarah ]]` is the same edge
1438//      as `[[records/contacts/sarah]]`. The inner padding is cosmetic; both the
1439//      forward and the backward view must resolve it identically.
1440//   3. **Case-folded to the filesystem.** Link *resolution* is `is_file()`,
1441//      which is case-insensitive on macOS/Windows. So on a case-insensitive
1442//      filesystem `[[records/contacts/Sarah-Chen]]` and the on-disk
1443//      `sarah-chen.md` are the SAME edge; the comparison key must case-fold to
1444//      match, or backlinks/rename silently miss the link while validate (which
1445//      resolves via the filesystem) considers it fine.
1446
1447/// Canonicalize a raw `[[...]]` inner target into the wiki-link key: forward
1448/// slashes, no leading `./` or `/`, no trailing `.md`, inner whitespace trimmed.
1449/// The single key forward and backward edges are compared on. Pairs with
1450/// [`link_edge_key`] for the case-fold step.
1451pub fn canonical_link_target(raw: &str) -> String {
1452    let mut s = raw.trim().replace('\\', "/");
1453    while let Some(rest) = s.strip_prefix("./") {
1454        s = rest.to_string();
1455    }
1456    let s = s.trim_start_matches('/');
1457    let s = s.strip_suffix(".md").unwrap_or(s);
1458    s.trim().to_string()
1459}
1460
1461/// The comparison key for a canonical link target. Two normalizations, applied
1462/// in order, so the string-keyed edge comparison agrees with how the filesystem
1463/// resolves the same link:
1464///
1465///   1. **Unicode NFC, always.** macOS/APFS folds NFC and NFD forms of a name to
1466///      the same file, so a file `records/contacts/josé.md` written NFC
1467///      (`é` = U+00E9) and a link `[[records/contacts/josé]]` written NFD
1468///      (`e` + U+0301) name the *same* file on disk — yet their raw UTF-8 bytes
1469///      differ. Without normalization the graph keys them as two different
1470///      targets, so `backlinks`/`forwardlinks` miss the edge and `orphans` flags
1471///      a linked-to file as an orphan, while `validate` (which resolves through
1472///      the filesystem) sees the link as live: the surfaces silently disagree.
1473///      Normalizing BOTH sides to NFC here makes the comparison
1474///      normalization-insensitive, matching the filesystem. This lives in the
1475///      comparison key — not in [`canonical_link_target`] — so the canonical
1476///      form stays byte/normalization-preserving (rename REWRITE output is never
1477///      silently re-normalized); both the link target and the file path pass
1478///      through this function, so NFC here is sufficient to unify them.
1479///   2. **ASCII case-fold on a case-insensitive filesystem.** Identity on a
1480///      case-sensitive FS, ASCII-lowercased on macOS/Windows, so the comparison
1481///      also agrees with the filesystem's case-folding `is_file()` resolution.
1482///
1483/// Callers compare `link_edge_key(a) == link_edge_key(b)`.
1484pub fn link_edge_key(canonical_target: &str) -> String {
1485    use unicode_normalization::UnicodeNormalization;
1486    // NFC first — always, on every platform: the graph must agree across hosts,
1487    // and the comparison must be normalization-insensitive regardless of which
1488    // host's filesystem folded the on-disk name.
1489    let nfc: String = canonical_target.nfc().collect();
1490    if fs_is_case_insensitive() {
1491        nfc.to_ascii_lowercase()
1492    } else {
1493        nfc
1494    }
1495}
1496
1497/// Extract every wiki-link edge target from a markdown body, fence-aware and
1498/// whitespace-trimmed, in document order (duplicates kept — callers dedup).
1499/// Returns canonical targets (see [`canonical_link_target`]); the case-fold for
1500/// comparison is applied separately via [`link_edge_key`] so the canonical form
1501/// (used for rewrites/output) stays case-preserving.
1502///
1503/// Scans line-by-line tracking the fence state inline (no whole-body
1504/// allocation), exactly mirroring validate's `extract_wiki_links`: the fence
1505/// state is a `(fence char, run length)` tracked via [`fence_opens`] /
1506/// [`fence_closes`] — NOT a bool toggled on any ``` / `~~~` line. The naive
1507/// toggle inverts mid-block when a `~~~` block legally contains a ```` ``` ````
1508/// line (the standard way to document a backtick fence), or when a `>3`-space-
1509/// indented ``` is mistaken for a fence — both of which would let a fenced
1510/// example `[[…]]` leak out as a live edge (a false dependent for
1511/// backlinks/rename). Fenced lines never yield edges. Within a line, the text
1512/// before the first `|` is the target; a target whose trimmed form starts with
1513/// `[` is the rejected triple-bracket flow-form list mis-encoding
1514/// (`[[[a]], [[b]]]`), not a real link — skipped, matching validate.
1515///
1516/// Accepts a whole file's text *or* a body-only fragment. A leading `---`
1517/// frontmatter block is YAML, not markdown: it has no code fences, and a
1518/// `[[…]]` in any frontmatter field is a real edge. The frontmatter is therefore
1519/// scanned WITHOUT fence tracking, and the body is scanned with a FRESH fence
1520/// state — so a stray ``` / `~~~` inside a frontmatter value can never open a
1521/// fence that swallows the body's real wiki-links. (Callers `search_by_link`,
1522/// `forwardlinks`, and `dbmd graph backlinks` all pass full file text; without this
1523/// boundary reset a fenced frontmatter value silently dropped every subsequent
1524/// body edge — under-reporting backlinks/forwardlinks/`links`.) A fragment with
1525/// no leading frontmatter takes the body path unchanged.
1526pub fn extract_edge_targets(text: &str) -> Vec<String> {
1527    let mut out = Vec::new();
1528    // Split off a leading `---`…`---` frontmatter block (raw — no YAML parse, so
1529    // a malformed file is still fully scanned). Frontmatter links are edges but
1530    // must not participate in code-fence state.
1531    let body = match split_frontmatter_raw(text) {
1532        Some((frontmatter, body)) => {
1533            for line in frontmatter.lines() {
1534                push_edges_in_line(line, &mut out);
1535            }
1536            body
1537        }
1538        None => text,
1539    };
1540    let mut fence: Option<(u8, usize)> = None;
1541    for line in body.lines() {
1542        let content = line.trim_end_matches('\r');
1543        if let Some(f) = fence {
1544            if fence_closes(content, f) {
1545                fence = None;
1546            }
1547            continue;
1548        }
1549        if let Some(opened) = fence_opens(content) {
1550            fence = Some(opened);
1551            continue;
1552        }
1553        push_edges_in_line(line, &mut out);
1554    }
1555    out
1556}
1557
1558/// Push every `[[target]]` on one line into `out`, alias-stripped (`[[a|b]]` →
1559/// `a`), trimmed, and canonicalized. The triple-bracket flow-form mis-encoding
1560/// (`[[[a]], …]`) is skipped, matching validate. Shared by both the frontmatter
1561/// and body scans in [`extract_edge_targets`] so they honor one link grammar.
1562/// One wiki-link OCCURRENCE in a body, with the byte span it covers.
1563///
1564/// [`extract_edge_targets`] answers "what does this file link to" — deduped,
1565/// order-insensitive, the graph's view. This answers "where, exactly, are the
1566/// link tokens" — the view a RENDERER needs, because rewriting `[[…]]` into
1567/// presentation markup is a splice at a position, not a set operation.
1568///
1569/// Exposing it is what keeps the grammar in one place. A host that must render
1570/// wiki-links otherwise has to re-find the tokens itself, which means a second
1571/// implementation of `[[`/`]]`/`|` scanning and — the part that always rots —
1572/// a second implementation of fence tracking. (Observed in the wild: a hub
1573/// whose renderer rewrote fenced example links into live links, corrupting the
1574/// code samples on exactly the pages that documented the syntax.)
1575#[derive(Debug, Clone, PartialEq, Eq)]
1576pub struct EdgeSpan {
1577    /// The canonical target, byte-identical to the string
1578    /// [`extract_edge_targets`] yields for this occurrence — so the extension
1579    /// is NOT appended here (callers that want a store path add `.md`, exactly
1580    /// as `emit` does).
1581    pub target: String,
1582    /// The inner text verbatim (between `[[` and `]]`), untrimmed and unsplit,
1583    /// so a host with its own conventions can reinterpret it.
1584    pub raw: String,
1585    /// The `|alias` label, if the occurrence carries one.
1586    ///
1587    /// A `#fragment` is deliberately NOT split out: fragments are not in the
1588    /// format (they ride inside the target — see `canonical_link_target`), so
1589    /// splitting one is a host convention, not db.md grammar.
1590    pub alias: Option<String>,
1591    /// Byte offsets into the body passed in — `[start, end)` covers the whole
1592    /// `[[…]]` token including both bracket pairs.
1593    pub start: usize,
1594    pub end: usize,
1595}
1596
1597/// Every wiki-link occurrence in a BODY, in document order, with byte spans.
1598///
1599/// Body-only by design: this exists for renderers, which format bodies. A
1600/// `[[…]]` in a frontmatter VALUE is a real edge (and
1601/// [`extract_edge_targets`] reports it), but it is data being displayed by a
1602/// field, never markdown being rendered in place, so it has no useful span
1603/// here. Pass the body — a full file's text works too, but its frontmatter
1604/// block is then treated as body text.
1605///
1606/// Fence tracking is identical to [`extract_edge_targets`]'s body pass: a
1607/// `[[…]]` inside ``` or `~~~` is a documentation example and yields nothing.
1608pub fn extract_edge_spans(body: &str) -> Vec<EdgeSpan> {
1609    let mut out = Vec::new();
1610    let mut fence: Option<(u8, usize)> = None;
1611    // `lines()` discards offsets, so walk the byte ranges directly and keep the
1612    // running base — spans must index the caller's original string.
1613    let mut base = 0usize;
1614    for line in body.split_inclusive('\n') {
1615        let trimmed_len = line.trim_end_matches('\n').len();
1616        let content = line[..trimmed_len].trim_end_matches('\r');
1617        if let Some(f) = fence {
1618            if fence_closes(content, f) {
1619                fence = None;
1620            }
1621        } else if let Some(opened) = fence_opens(content) {
1622            fence = Some(opened);
1623        } else {
1624            push_edge_spans_in_line(content, base, &mut out);
1625        }
1626        base += line.len();
1627    }
1628    out
1629}
1630
1631fn push_edge_spans_in_line(line: &str, base: usize, out: &mut Vec<EdgeSpan>) {
1632    let bytes = line.as_bytes();
1633    let mut i = 0usize;
1634    while i + 1 < bytes.len() {
1635        if bytes[i] == b'[' && bytes[i + 1] == b'[' {
1636            if let Some(close) = line[i + 2..].find("]]") {
1637                let inner = &line[i + 2..i + 2 + close];
1638                let end = i + 2 + close + 2;
1639                let mut parts = inner.splitn(2, '|');
1640                let raw_target = parts.next().unwrap_or(inner).trim();
1641                let alias = parts.next().map(str::trim).filter(|a| !a.is_empty());
1642                if !raw_target.is_empty() && !raw_target.starts_with('[') {
1643                    let canonical = canonical_link_target(raw_target);
1644                    if !canonical.is_empty() {
1645                        out.push(EdgeSpan {
1646                            target: canonical,
1647                            raw: inner.to_string(),
1648                            alias: alias.map(str::to_string),
1649                            start: base + i,
1650                            end: base + end,
1651                        });
1652                    }
1653                }
1654                i = end;
1655                continue;
1656            }
1657        }
1658        i += 1;
1659    }
1660}
1661
1662fn push_edges_in_line(line: &str, out: &mut Vec<String>) {
1663    let bytes = line.as_bytes();
1664    let mut i = 0usize;
1665    while i + 1 < bytes.len() {
1666        if bytes[i] == b'[' && bytes[i + 1] == b'[' {
1667            if let Some(close) = line[i + 2..].find("]]") {
1668                let inner = &line[i + 2..i + 2 + close];
1669                let raw_target = inner.split('|').next().unwrap_or(inner).trim();
1670                if !raw_target.is_empty() && !raw_target.starts_with('[') {
1671                    let canonical = canonical_link_target(raw_target);
1672                    if !canonical.is_empty() {
1673                        out.push(canonical);
1674                    }
1675                }
1676                i = i + 2 + close + 2;
1677                continue;
1678            }
1679        }
1680        i += 1;
1681    }
1682}
1683
1684/// If `line` opens a fenced code block, return `(fence byte, run length)`. The
1685/// single fence-open rule shared by [`extract_edge_targets`] and graph's
1686/// `rewrite_links_to`, mirroring validate's `fence_opens` and the parser's
1687/// `opening_fence` so every link op tracks fences identically: a fence is
1688/// ```` ``` ```` or `~~~` (run ≥ 3) at ≤ 3 spaces of indent, and a backtick
1689/// fence's info string may not itself contain a backtick.
1690pub fn fence_opens(line: &str) -> Option<(u8, usize)> {
1691    let indent = line.len() - line.trim_start_matches(' ').len();
1692    if indent > 3 {
1693        return None;
1694    }
1695    let rest = &line[indent..];
1696    let byte = rest.bytes().next()?;
1697    if byte != b'`' && byte != b'~' {
1698        return None;
1699    }
1700    let run = rest.len() - rest.trim_start_matches(byte as char).len();
1701    if run < 3 {
1702        return None;
1703    }
1704    // A backtick fence's info string may not itself contain a backtick.
1705    if byte == b'`' && rest[run..].contains('`') {
1706        return None;
1707    }
1708    Some((byte, run))
1709}
1710
1711/// True if `line` closes the currently open `fence`: same char, run at least as
1712/// long, nothing but trailing whitespace after. Mirrors validate's
1713/// `fence_closes` / the parser's `is_closing_fence`, so an inner fence of the
1714/// *other* character (a ```` ``` ```` line inside a `~~~` block) does NOT close
1715/// the outer fence.
1716pub fn fence_closes(line: &str, fence: (u8, usize)) -> bool {
1717    let (byte, open_len) = fence;
1718    let indent = line.len() - line.trim_start_matches(' ').len();
1719    if indent > 3 {
1720        return false;
1721    }
1722    let rest = &line[indent..];
1723    let run = rest.len() - rest.trim_start_matches(byte as char).len();
1724    if run < open_len {
1725        return false;
1726    }
1727    rest[run..].trim().is_empty()
1728}
1729
1730/// True when the host filesystem resolves paths case-insensitively (macOS/
1731/// Windows default). Probed once per process against the OS temp dir by creating
1732/// a lowercase marker and stat-ing its uppercase spelling. A probe failure
1733/// conservatively reports `false` (case-sensitive) — the historical behavior —
1734/// so a transient temp-dir issue never silently widens matching.
1735fn fs_is_case_insensitive() -> bool {
1736    use std::sync::OnceLock;
1737    static CASE_INSENSITIVE: OnceLock<bool> = OnceLock::new();
1738    *CASE_INSENSITIVE.get_or_init(|| {
1739        let dir = std::env::temp_dir();
1740        let pid = std::process::id();
1741        let nanos = SystemTime::now()
1742            .duration_since(UNIX_EPOCH)
1743            .map(|d| d.as_nanos())
1744            .unwrap_or(0);
1745        let lower = dir.join(format!(".dbmd-case-probe-{pid}-{nanos}"));
1746        let upper = dir.join(format!(".DBMD-CASE-PROBE-{pid}-{nanos}"));
1747        // Create the lowercase marker; if its uppercase spelling then resolves to
1748        // a file, the filesystem folded the case → case-insensitive.
1749        let result = match std::fs::File::create(&lower) {
1750            Ok(_) => upper.is_file(),
1751            Err(_) => false,
1752        };
1753        let _ = std::fs::remove_file(&lower);
1754        result
1755    })
1756}
1757
1758// ── Free helpers (no `self`) ────────────────────────────────────────────────
1759
1760/// True if the path ends in a `.md` extension (case-sensitive — db.md files are
1761/// lowercase `.md`).
1762fn has_md_extension(path: &Path) -> bool {
1763    path.extension().and_then(|e| e.to_str()) == Some("md")
1764}
1765
1766/// True if the basename is a non-content meta file (`DB.md`, `index.md`,
1767/// `log.md`) that the content walks must skip.
1768fn is_non_content_basename(path: &Path) -> bool {
1769    match path.file_name().and_then(|n| n.to_str()) {
1770        Some(name) => NON_CONTENT_BASENAMES.contains(&name),
1771        None => false,
1772    }
1773}
1774
1775/// Append `.md` to a bare name; leave an existing `.md` untouched.
1776fn ensure_md_extension(name: &str) -> String {
1777    if name.ends_with(".md") {
1778        name.to_string()
1779    } else {
1780        format!("{name}.md")
1781    }
1782}
1783
1784/// The canonical default folder for a recognized type, per the SPEC type table
1785/// (`email → sources/emails`, `expense → records/expenses`, …). Unrecognized
1786/// types fall back to `records/<type>` (the bare type name, no pluralization
1787/// guess) — see the store findings on the docstring's looser `<type>` phrasing.
1788fn default_type_folder(type_: &str) -> PathBuf {
1789    let path = match type_ {
1790        // sources — documentary
1791        "email" => "sources/emails",
1792        "transcript" => "sources/transcripts",
1793        "pdf-source" => "sources/docs",
1794        // sources — testimonial (a human told the agent X)
1795        "note" => "sources/notes",
1796        // records — entities
1797        "contact" => "records/contacts",
1798        "company" => "records/companies",
1799        // records — events
1800        "expense" => "records/expenses",
1801        "meeting" => "records/meetings",
1802        "decision" => "records/decisions",
1803        "invoice" => "records/invoices",
1804        // unrecognized: bare type name under records/ (conclusions and any
1805        // custom type land here, e.g. `concept` → `records/concept`).
1806        other => return PathBuf::from("records").join(other),
1807    };
1808    PathBuf::from(path)
1809}
1810
1811/// The canonical [`Layer`] a `type_` belongs to, derived from its default
1812/// type-folder (`email` → `Sources`, `contact` → `Records`, a conclusion
1813/// `profile` → `Records`, unrecognized → `Records`). The write path uses this to decide whether
1814/// an agent-supplied folder is in the *right* layer for the type before honouring
1815/// its sub-folder choice.
1816pub fn layer_for_type(type_: &str) -> Layer {
1817    layer_of_folder(&default_type_folder(type_)).unwrap_or(Layer::Records)
1818}
1819
1820/// The [`Layer`] a type-folder path lives in, read from its first component
1821/// (`sources/` → `Sources`, `records/` → `Records`). Used to
1822/// bound [`Store::find_by_type`]'s whole-layer sidecar read to a single layer
1823/// subtree. Returns `None` for a path with no recognized layer prefix; every
1824/// value [`default_type_folder`] produces has one, so in practice this is
1825/// always `Some` on the call path — `None` degrades to a store-wide read.
1826fn layer_of_folder(folder: &Path) -> Option<Layer> {
1827    let first = folder.components().next()?.as_os_str().to_str()?;
1828    Layer::from_dir_name(first)
1829}
1830
1831/// True if a store-relative path is a db.md **content** file: rooted in a real
1832/// layer (`sources/` or `records/` as its FIRST component), with a `.md`
1833/// extension, and not an `index.md` sidecar. This is the SPEC's "content files =
1834/// everything under `sources/` and `records/` only" predicate (SPEC § content
1835/// files), keyed on the *first* component so a non-layer top-level dir is never
1836/// content even if a deeper component happens to be named `records`/`sources`
1837/// (e.g. `EXPECTED/records/x.md`, `archive/sources/y.md`).
1838///
1839/// It mirrors the graph engine's content filter so the surfaces that READ the
1840/// store (`graph backlinks`) and the surface that MUTATES it (`rename`) agree on
1841/// exactly which files are content. `rename` uses it to restrict its
1842/// link-rewrite set: a store-root file, a non-layer dir (`scratch/`,
1843/// `EXPECTED/`, `archive/`), or an `index.md` is NEVER rewritten — `rename` does
1844/// not own those bytes. The broad store scan ([`Store::find_links_to_any`],
1845/// shared with the read-only working-set validate) is left untouched; the filter
1846/// is applied at the point of mutation.
1847pub fn is_content_path(rel: &Path) -> bool {
1848    if layer_of_folder(rel).is_none() {
1849        return false;
1850    }
1851    if rel.extension().and_then(|e| e.to_str()) != Some("md") {
1852        return false;
1853    }
1854    rel.file_name().and_then(|n| n.to_str()) != Some("index.md")
1855}
1856
1857/// Infer a content file's canonical `type` from its store-relative path — the
1858/// inverse of [`default_type_folder`] and the single source of truth for
1859/// path→type inference (the CLI's `fm init` calls this, never re-derives it).
1860///
1861/// Requires the canonical `<layer>/<type-folder>/<file>` 3-component shape; a
1862/// shorter path (a file directly under a layer) or an unknown leading layer
1863/// yields `None`.
1864///
1865/// Recognized `(layer, folder)` pairs map back to their canonical type. For an
1866/// unrecognized folder the fallback is the **bare folder name verbatim** (no
1867/// pluralization/singularization) so it round-trips with `default_type_folder`,
1868/// whose unrecognized fallback is the bare type name (`task` ⇄ `records/task`).
1869/// Singularizing here would break that round-trip (`records/tasks` → `task`
1870/// while `default_type_folder("task")` → `records/task`). A conclusion record's
1871/// folder (e.g. `records/profiles/`) infers its bare folder name (`profiles`),
1872/// the same custom-type fallback as any other unrecognized folder.
1873pub fn infer_type_from_path(rel: &Path) -> Option<String> {
1874    let mut comps = rel.components().filter_map(|c| c.as_os_str().to_str());
1875    let layer = comps.next()?;
1876    if !matches!(layer, "sources" | "records") {
1877        return None;
1878    }
1879    let folder = comps.next()?;
1880    // The file itself must be a third component (a real type-folder, not the
1881    // file sitting directly under the layer).
1882    comps.next()?;
1883
1884    let mapped = match (layer, folder) {
1885        ("sources", "emails") => "email",
1886        ("sources", "transcripts") => "transcript",
1887        ("sources", "docs") => "pdf-source",
1888        ("sources", "notes") => "note",
1889        ("records", "contacts") => "contact",
1890        ("records", "companies") => "company",
1891        ("records", "expenses") => "expense",
1892        ("records", "meetings") => "meeting",
1893        ("records", "decisions") => "decision",
1894        ("records", "invoices") => "invoice",
1895        // Unrecognized folder: the bare name, verbatim. This is the inverse of
1896        // `default_type_folder`'s unrecognized fallback (`other → records/other`)
1897        // and the round-trip would break if we pluralized/singularized here.
1898        (_, other) => other,
1899    };
1900    Some(mapped.to_string())
1901}
1902
1903/// The primary date field name for a sharding type (the field whose value
1904/// drives `<YYYY>/<MM>`). `None` means "use the `created` fallback only".
1905fn primary_date_field(type_: &str) -> Option<&'static str> {
1906    match type_ {
1907        "email" => Some("date"),
1908        "transcript" => Some("recorded_at"),
1909        "pdf-source" => Some("received_at"),
1910        "note" => Some("told_at"),
1911        "expense" | "invoice" | "meeting" => Some("date"),
1912        // recognized custom event types have no canonical date field name; they
1913        // fall back to `created`.
1914        _ => None,
1915    }
1916}
1917
1918/// Parse a YAML value into an RFC3339 [`DateTime`], accepting both an explicit
1919/// string and a YAML-native scalar rendered to string.
1920fn value_to_datetime(value: &serde_norway::Value) -> Option<DateTime<FixedOffset>> {
1921    let s = yaml_scalar_string(value)?;
1922    DateTime::parse_from_rfc3339(s.trim()).ok()
1923}
1924
1925/// Extract `(YYYY, MM)` from a YAML date/timestamp value. Lenient: matches a
1926/// leading `YYYY-MM` so a bare `2026-05-22` date and a full
1927/// `2026-05-22T10:00:00-07:00` timestamp both work.
1928fn value_to_year_month(value: &serde_norway::Value) -> Option<(String, String)> {
1929    let s = yaml_scalar_string(value)?;
1930    year_month_from_str(s.trim())
1931}
1932
1933/// `(YYYY, MM)` from the leading `YYYY-M` or `YYYY-MM` of a date string, with
1934/// the month returned zero-padded to two digits.
1935///
1936/// The month may be single- OR double-digit so that `2026-1-15` and its
1937/// zero-padded twin `2026-01-15` shard to the *same* `2026/01` folder. This
1938/// matches the lenient `date`-shape validator (`is_iso8601_date_or_datetime`,
1939/// chrono `%Y-%m-%d`), which accepts an unpadded month — without this, a value
1940/// the validator treats as a valid date is silently mis-filed under the
1941/// `created`-fallback month. Genuinely non-date input still returns `None`.
1942fn year_month_from_str(s: &str) -> Option<(String, String)> {
1943    // Hand-roll the leading-`YYYY-M[M]` parse to avoid a regex compile on the
1944    // write path. Split on '-': require a 4-digit year, then a 1-or-2-digit
1945    // numeric month in 1..=12. Anything after the month (a `-DD` day, a `T...`
1946    // time) is ignored — the day field never separates the leading date.
1947    let mut parts = s.splitn(3, '-');
1948    let year = parts.next()?;
1949    let month_part = parts.next()?;
1950
1951    // Year: exactly 4 ASCII digits.
1952    if year.len() != 4 || !year.bytes().all(|b| b.is_ascii_digit()) {
1953        return None;
1954    }
1955
1956    // Month: 1 or 2 ASCII digits, value 1..=12. Padded to two digits on output.
1957    if month_part.is_empty()
1958        || month_part.len() > 2
1959        || !month_part.bytes().all(|b| b.is_ascii_digit())
1960    {
1961        return None;
1962    }
1963    let month: u8 = month_part.parse().ok()?;
1964    if !(1..=12).contains(&month) {
1965        return None;
1966    }
1967
1968    Some((year.to_string(), format!("{month:02}")))
1969}
1970
1971/// Render a YAML scalar as a string: a real `String` verbatim, otherwise the
1972/// value's compact YAML serialization (covers timestamps that the YAML engine
1973/// may surface as a non-string scalar).
1974fn yaml_scalar_string(value: &serde_norway::Value) -> Option<String> {
1975    if let Some(s) = value.as_str() {
1976        return Some(s.to_string());
1977    }
1978    match value {
1979        serde_norway::Value::Null => None,
1980        serde_norway::Value::Mapping(_) | serde_norway::Value::Sequence(_) => None,
1981        other => serde_norway::to_string(other)
1982            .ok()
1983            .map(|s| s.trim().to_string()),
1984    }
1985}
1986
1987/// The YAML frontmatter block of a file: the text between a leading `---` fence
1988/// and the next `---` fence, exclusive. `None` if the file does not open with a
1989/// `---` fence on its first line.
1990fn frontmatter_block(text: &str) -> Option<&str> {
1991    // Tolerate a UTF-8 BOM and CRLF, but the fence must be the very first line.
1992    let body = text.strip_prefix('\u{feff}').unwrap_or(text);
1993    let mut rest = body;
1994    // First line must be exactly `---`, tolerating trailing whitespace (CR, but
1995    // also spaces/tabs) — matching the canonical parser (`parser.rs` /
1996    // `index.rs`'s `extract_frontmatter_block`). A strict `\r`-only trim missed a
1997    // `--- ` fence, so `read_updated` returned None and date-sharding silently
1998    // fell back, disagreeing with the sidecar the rest of the toolkit builds.
1999    let (first, after_first) = split_first_line(rest);
2000    if first.trim_end() != "---" {
2001        return None;
2002    }
2003    rest = after_first;
2004    let block_start = rest;
2005    let mut scanned = 0usize;
2006    loop {
2007        let (line, after) = split_first_line(rest);
2008        if line.trim_end() == "---" {
2009            return Some(&block_start[..scanned]);
2010        }
2011        if after.is_empty() && line.is_empty() {
2012            // Reached end of input without a closing fence.
2013            return None;
2014        }
2015        scanned += line.len() + 1; // +1 for the consumed '\n'
2016        if after.is_empty() {
2017            return None;
2018        }
2019        rest = after;
2020    }
2021}
2022
2023/// Split a file's text into `(frontmatter, body)` at the leading `---`…`---`
2024/// fence — raw (no YAML parse), so a file with malformed frontmatter is still
2025/// split and fully scanned. `frontmatter` is the text between the fences
2026/// (exclusive); `body` is everything after the closing fence's line. Returns
2027/// `None` when the text does not open with a `---` fence or has no closing
2028/// fence — the caller then treats the whole text as body. Mirrors
2029/// [`frontmatter_block`]'s boundary detection (BOM- and CRLF-tolerant).
2030fn split_frontmatter_raw(text: &str) -> Option<(&str, &str)> {
2031    let stripped = text.strip_prefix('\u{feff}').unwrap_or(text);
2032    let (first, after_first) = split_first_line(stripped);
2033    if first.trim_end() != "---" {
2034        return None;
2035    }
2036    let block_start = after_first;
2037    let mut scanned = 0usize;
2038    let mut rest = after_first;
2039    loop {
2040        let (line, after) = split_first_line(rest);
2041        if line.trim_end() == "---" {
2042            // `after` is the body: everything past the closing fence line.
2043            return Some((&block_start[..scanned], after));
2044        }
2045        if after.is_empty() && line.is_empty() {
2046            return None; // reached EOF with no closing fence
2047        }
2048        scanned += line.len() + 1; // +1 for the consumed '\n'
2049        if after.is_empty() {
2050            return None; // closing fence never found
2051        }
2052        rest = after;
2053    }
2054}
2055
2056/// Split a string into (first line without its trailing `\n`, remainder after
2057/// the `\n`). If there is no newline, the whole string is the line and the
2058/// remainder is empty.
2059fn split_first_line(s: &str) -> (&str, &str) {
2060    match s.find('\n') {
2061        Some(i) => (&s[..i], &s[i + 1..]),
2062        None => (s, ""),
2063    }
2064}
2065
2066/// True if an [`IndexRecord`] has a field `key` equal to `value`, checking the
2067/// typed columns first and then the flattened `fields` map.
2068fn record_matches_field(record: &IndexRecord, key: &str, value: &str) -> bool {
2069    match key {
2070        "type" => record.type_ == value,
2071        "summary" => record.summary == value,
2072        "path" => record.path.to_string_lossy() == value,
2073        "created" => timestamp_matches(record.created, value),
2074        "updated" => timestamp_matches(record.updated, value),
2075        "tags" => record.tags.iter().any(|t| t == value),
2076        "links" => record.links.iter().any(|l| l == value),
2077        other => record
2078            .fields
2079            .get(other)
2080            .map(|v| json_value_matches(v, value))
2081            .unwrap_or(false),
2082    }
2083}
2084
2085/// Compare a record's `created`/`updated` instant against a query `value`.
2086///
2087/// db.md files write timestamps in several equivalent RFC3339 spellings — most
2088/// commonly the `Z` UTC designator (`2026-05-01T00:00:00Z`) but also an explicit
2089/// offset (`...+00:00`, `...-07:00`). A naive `record.created.to_rfc3339() ==
2090/// value` reformats only one side: chrono renders a UTC instant as `+00:00`, so
2091/// the `Z` form an agent reads straight out of the file would never match. We
2092/// instead parse `value` as RFC3339 and compare instants, where `Z` and `+00:00`
2093/// (and any same-instant offset) are equal. A `value` that is not valid RFC3339
2094/// can never equal a real timestamp, so it falls through to `false`.
2095fn timestamp_matches(stored: Option<DateTime<FixedOffset>>, value: &str) -> bool {
2096    match (stored, DateTime::parse_from_rfc3339(value)) {
2097        (Some(stored), Ok(queried)) => stored == queried,
2098        _ => false,
2099    }
2100}
2101
2102/// Match a JSON number against a query string.
2103///
2104/// A FLOAT-valued field is compared NUMERICALLY, not textually: the sidecar
2105/// stores a YAML float through serde_json's canonical f64 rendering, which
2106/// discards the file's source spelling (`1234.00` -> `1234.0`, `12.50` ->
2107/// `12.5`, `1e3` -> `1000.0`). A raw `to_string()` compare therefore made the
2108/// spelling a human reads in the file fail to match (and disagreed with
2109/// free-text `search`), while requiring a canonical form often absent from the
2110/// file. We parse the query as f64 and compare values. Restricted to the float
2111/// case so a large INTEGER field never loses exactness to f64 rounding (integers
2112/// render canonically and round-trip exactly through the textual compare).
2113/// Mirrors the parse-then-compare pattern [`timestamp_matches`] already uses.
2114fn number_matches(n: &serde_json::Number, value: &str) -> bool {
2115    if n.to_string() == value {
2116        return true;
2117    }
2118    if n.is_f64() {
2119        if let (Some(stored), Ok(q)) = (n.as_f64(), value.parse::<f64>()) {
2120            return stored == q;
2121        }
2122    }
2123    false
2124}
2125
2126/// Compare a JSON field value against a query string. A string matches
2127/// verbatim; scalars match their textual form; an array matches if any element
2128/// matches (so a list-valued frontmatter field is membership-queried).
2129fn json_value_matches(v: &serde_json::Value, value: &str) -> bool {
2130    match v {
2131        serde_json::Value::String(s) => s == value,
2132        serde_json::Value::Bool(b) => b.to_string() == value,
2133        serde_json::Value::Number(n) => number_matches(n, value),
2134        serde_json::Value::Array(items) => items.iter().any(|i| json_value_matches(i, value)),
2135        // A present-but-null field never matches — consistent with the in-memory
2136        // post-filter (`query::json_value_matches`, which the first `where`
2137        // clause is NOT re-checked against, so the two must agree here or a
2138        // `--where field=` query would return different rows than `--type X
2139        // --where field=`).
2140        serde_json::Value::Null => false,
2141        serde_json::Value::Object(_) => false,
2142    }
2143}
2144
2145#[cfg(test)]
2146mod tests {
2147    use super::*;
2148    use std::fs;
2149    use tempfile::{tempdir, TempDir};
2150
2151    // ── Fixtures ────────────────────────────────────────────────────────────
2152
2153    /// Write `contents` to `<root>/<rel>`, creating parent dirs. Returns the
2154    /// store-relative path for convenient assertions.
2155    fn write(root: &Path, rel: &str, contents: &str) -> PathBuf {
2156        let abs = root.join(rel);
2157        fs::create_dir_all(abs.parent().unwrap()).unwrap();
2158        fs::write(&abs, contents).unwrap();
2159        PathBuf::from(rel)
2160    }
2161
2162    /// A minimal content file with the given `updated` timestamp in frontmatter.
2163    fn content_md(updated: &str) -> String {
2164        format!(
2165            "---\ntype: note\ncreated: {updated}\nupdated: {updated}\nsummary: a note\n---\n\nbody\n"
2166        )
2167    }
2168
2169    /// A bare directory with a `DB.md` marker (valid `db-md` frontmatter so the
2170    /// real parser is exercised).
2171    fn empty_store() -> TempDir {
2172        let dir = tempdir().unwrap();
2173        fs::write(
2174            dir.path().join("DB.md"),
2175            "---\ntype: db-md\nscope: company\nowner: Test\n---\n\n# Store\n",
2176        )
2177        .unwrap();
2178        dir
2179    }
2180
2181    /// Open a store rooted at a TempDir; panics if `open` rejects it.
2182    fn open(dir: &TempDir) -> Store {
2183        Store::open(dir.path()).expect("fixture should be a valid store")
2184    }
2185
2186    fn rels(paths: &[PathBuf]) -> Vec<String> {
2187        paths
2188            .iter()
2189            .map(|p| p.to_string_lossy().replace('\\', "/"))
2190            .collect()
2191    }
2192
2193    // ── Layer ───────────────────────────────────────────────────────────────
2194
2195    #[test]
2196    fn layer_dir_name_and_parse_are_inverse() {
2197        for layer in Layer::all() {
2198            assert_eq!(Layer::from_dir_name(layer.dir_name()), Some(layer));
2199        }
2200        assert_eq!(Layer::Sources.dir_name(), "sources");
2201        assert_eq!(Layer::Records.dir_name(), "records");
2202        // `wiki` is no longer a layer (the wiki/ layer was removed); it parses to None.
2203        assert_eq!(Layer::from_dir_name("wiki"), None);
2204        assert_eq!(Layer::from_dir_name("log"), None);
2205        assert_eq!(Layer::from_dir_name("Sources"), None); // case-sensitive
2206    }
2207
2208    #[test]
2209    fn layer_order_is_canonical() {
2210        // stats keys a BTreeMap on Layer; the sort order must be sources<records.
2211        let mut v = [Layer::Records, Layer::Sources];
2212        v.sort();
2213        assert_eq!(v, [Layer::Sources, Layer::Records]);
2214    }
2215
2216    #[test]
2217    fn is_content_path_is_layer_rooted_and_excludes_non_layer_files() {
2218        // Real content: a `.md` file rooted in a layer's FIRST component.
2219        assert!(is_content_path(Path::new("records/contacts/alice.md")));
2220        assert!(is_content_path(Path::new("sources/emails/2026/05/x.md")));
2221        // Store-root meta files and a bare top-level note are NOT content.
2222        assert!(!is_content_path(Path::new("DB.md")));
2223        assert!(!is_content_path(Path::new("log.md")));
2224        assert!(!is_content_path(Path::new("NOTES.md")));
2225        // Non-layer top-level dirs are NEVER content — even if a DEEPER
2226        // component is named `records`/`sources` (the rename data-loss case).
2227        assert!(!is_content_path(Path::new("scratch/draft.md")));
2228        assert!(!is_content_path(Path::new("EXPECTED/snapshot.md")));
2229        assert!(!is_content_path(Path::new("archive/old.md")));
2230        assert!(!is_content_path(Path::new(
2231            "EXPECTED/records/contacts/x.md"
2232        )));
2233        assert!(!is_content_path(Path::new("archive/sources/emails/y.md")));
2234        // An `index.md` sidecar inside a layer is a catalog, not content.
2235        assert!(!is_content_path(Path::new("records/contacts/index.md")));
2236        // A non-`.md` file inside a layer (e.g. the jsonl sidecar) is not content.
2237        assert!(!is_content_path(Path::new("records/contacts/index.jsonl")));
2238    }
2239
2240    // ── is_db_md_store / open ────────────────────────────────────────────────
2241
2242    #[test]
2243    fn is_store_true_only_with_uppercase_marker() {
2244        let dir = tempdir().unwrap();
2245        assert!(
2246            !Store::is_db_md_store(dir.path()),
2247            "no marker → not a store"
2248        );
2249
2250        fs::write(dir.path().join("DB.md"), "---\ntype: db-md\n---\n").unwrap();
2251        assert!(Store::is_db_md_store(dir.path()), "uppercase DB.md → store");
2252    }
2253
2254    #[test]
2255    fn is_store_false_for_lowercase_db_md() {
2256        // The case-sensitivity contract: a lowercase db.md is the spec name, not
2257        // a marker — even on a case-insensitive filesystem where Path::exists
2258        // would lie. This test must pass on macOS (case-insensitive) too.
2259        let dir = tempdir().unwrap();
2260        fs::write(dir.path().join("db.md"), "---\ntype: db-md\n---\n").unwrap();
2261        assert!(
2262            !Store::is_db_md_store(dir.path()),
2263            "lowercase db.md must NOT be treated as a store marker"
2264        );
2265        assert!(Store::open(dir.path()).is_err());
2266    }
2267
2268    #[test]
2269    fn is_store_false_when_db_md_is_a_directory() {
2270        let dir = tempdir().unwrap();
2271        fs::create_dir(dir.path().join("DB.md")).unwrap();
2272        assert!(
2273            !Store::is_db_md_store(dir.path()),
2274            "a directory named DB.md is not the file marker"
2275        );
2276    }
2277
2278    #[cfg(unix)]
2279    #[test]
2280    fn is_store_false_when_db_md_symlink_escapes_root() {
2281        use std::os::unix::fs::symlink;
2282
2283        let dir = tempdir().unwrap();
2284        let external = tempdir().unwrap();
2285        let marker = external.path().join("outside.md");
2286        fs::write(
2287            &marker,
2288            "---\ntype: db-md\nscope: personal\nowner: Outside\n---\n",
2289        )
2290        .unwrap();
2291        symlink(&marker, dir.path().join("DB.md")).unwrap();
2292
2293        assert!(
2294            !Store::is_db_md_store(dir.path()),
2295            "opening a store must not read an external DB.md symlink"
2296        );
2297    }
2298
2299    #[test]
2300    fn open_rejects_non_store_with_path() {
2301        let dir = tempdir().unwrap();
2302        let err = Store::open(dir.path()).unwrap_err();
2303        assert_eq!(err.path, dir.path());
2304    }
2305
2306    #[test]
2307    fn open_succeeds_and_parses_config() {
2308        let dir = tempdir().unwrap();
2309        // A DB.md whose ## Policies declares a frozen page — proves open()
2310        // actually parsed the config rather than substituting a default.
2311        fs::write(
2312            dir.path().join("DB.md"),
2313            "---\ntype: db-md\nscope: company\nowner: Test\n---\n\n# Store\n\n\
2314             ## Policies\n\n### Frozen pages\n- records/decisions/q1.md\n",
2315        )
2316        .unwrap();
2317        let store = Store::open(dir.path()).unwrap();
2318        assert_eq!(store.root, dir.path());
2319        assert!(
2320            store
2321                .config
2322                .frozen_pages
2323                .iter()
2324                .any(|p| p == Path::new("records/decisions/q1.md")),
2325            "open() must surface DB.md ## Policies, got {:?}",
2326            store.config.frozen_pages
2327        );
2328    }
2329
2330    #[cfg(unix)]
2331    #[test]
2332    fn opened_store_keeps_original_root_capability_after_path_swap() {
2333        use std::os::unix::fs::symlink;
2334
2335        let sandbox = tempdir().unwrap();
2336        let root = sandbox.path().join("store");
2337        fs::create_dir_all(root.join("records/notes")).unwrap();
2338        fs::write(root.join("DB.md"), "---\ntype: db-md\n---\n").unwrap();
2339        fs::write(root.join("records/notes/owned.md"), b"owned").unwrap();
2340
2341        let outside = sandbox.path().join("outside");
2342        fs::create_dir_all(outside.join("records/notes")).unwrap();
2343        fs::write(outside.join("records/notes/owned.md"), b"outside secret").unwrap();
2344        fs::write(
2345            outside.join("records/notes/external-only.md"),
2346            b"must never be enumerated",
2347        )
2348        .unwrap();
2349
2350        let store = Store::open_strict(&root).unwrap();
2351        let detached = sandbox.path().join("detached-store");
2352        fs::rename(&root, &detached).unwrap();
2353        symlink(&outside, &root).unwrap();
2354
2355        assert_eq!(
2356            store
2357                .read_bounded(Path::new("records/notes/owned.md"), 1024)
2358                .unwrap(),
2359            b"owned",
2360            "reads must remain rooted at the directory selected by open()"
2361        );
2362        store
2363            .write_atomic(
2364                Path::new("records/notes/created.md"),
2365                b"created in held store",
2366            )
2367            .unwrap();
2368        assert_eq!(
2369            fs::read(detached.join("records/notes/created.md")).unwrap(),
2370            b"created in held store"
2371        );
2372        assert!(
2373            !outside.join("records/notes/created.md").exists(),
2374            "writes must not follow a swapped store pathname"
2375        );
2376        assert_eq!(
2377            fs::read(outside.join("records/notes/owned.md")).unwrap(),
2378            b"outside secret"
2379        );
2380        let walked = store.walk().unwrap();
2381        assert!(
2382            walked.contains(&PathBuf::from("records/notes/owned.md"))
2383                && walked.contains(&PathBuf::from("records/notes/created.md")),
2384            "sweeps must enumerate the held original directory"
2385        );
2386        assert!(
2387            !walked.contains(&PathBuf::from("records/notes/external-only.md")),
2388            "sweeps must not enumerate a replacement at the old root pathname"
2389        );
2390    }
2391
2392    #[cfg(unix)]
2393    #[test]
2394    fn transaction_gate_serializes_cooperative_mutators() {
2395        let dir = empty_store();
2396        let first_store = Store::open_strict(dir.path()).unwrap();
2397        let second_store = Store::open_strict(dir.path()).unwrap();
2398        let first = first_store.transaction().unwrap();
2399        let (sent, received) = std::sync::mpsc::channel();
2400
2401        let waiter = std::thread::spawn(move || {
2402            let _second = second_store.transaction().unwrap();
2403            sent.send(()).unwrap();
2404        });
2405        assert!(
2406            received
2407                .recv_timeout(std::time::Duration::from_millis(100))
2408                .is_err(),
2409            "a second cooperative mutator must wait while rename owns the gate"
2410        );
2411        drop(first);
2412        received
2413            .recv_timeout(std::time::Duration::from_secs(2))
2414            .expect("waiter acquires immediately after the first transaction ends");
2415        waiter.join().unwrap();
2416    }
2417
2418    // ── walk / walk_layer / walk_type_folder ─────────────────────────────────
2419
2420    #[test]
2421    fn walk_collects_content_across_layers_skipping_meta_and_log() {
2422        let dir = empty_store();
2423        let root = dir.path();
2424        write(
2425            root,
2426            "sources/emails/2026/05/a.md",
2427            &content_md("2026-05-01T00:00:00Z"),
2428        );
2429        write(
2430            root,
2431            "records/contacts/sarah.md",
2432            &content_md("2026-05-02T00:00:00Z"),
2433        );
2434        write(
2435            root,
2436            "records/profiles/sarah.md",
2437            &content_md("2026-05-03T00:00:00Z"),
2438        );
2439        // Things walk() must SKIP:
2440        write(root, "sources/emails/index.md", "---\ntype: index\n---\n"); // catalog
2441        write(root, "index.md", "---\ntype: index\n---\n"); // root catalog
2442        write(root, "log.md", "---\ntype: log\n---\n"); // log
2443        write(root, "log/2026-04.md", "---\ntype: log\n---\n"); // rotated log archive
2444        write(
2445            root,
2446            "sources/.hidden/secret.md",
2447            &content_md("2026-05-09T00:00:00Z"),
2448        ); // hidden dir
2449        write(root, "records/contacts/notes.txt", "not markdown"); // non-md
2450
2451        let store = open(&dir);
2452        let got = rels(&store.walk().unwrap());
2453        assert_eq!(
2454            got,
2455            vec![
2456                "records/contacts/sarah.md".to_string(),
2457                "records/profiles/sarah.md".to_string(),
2458                "sources/emails/2026/05/a.md".to_string(),
2459            ]
2460        );
2461    }
2462
2463    #[test]
2464    fn walk_includes_log_md_but_prunes_nested_store() {
2465        let dir = empty_store();
2466        let root = dir.path();
2467        // log.md is reserved only at the store root.
2468        write(
2469            root,
2470            "records/configs/log.md",
2471            &content_md("2026-05-01T00:00:00Z"),
2472        );
2473        // A descendant DB.md starts a foreign store boundary. Nothing beneath
2474        // it belongs to the outer store.
2475        write(
2476            root,
2477            "sources/docs/DB.md",
2478            "---\ntype: db-md\nscope: research\nowner: Nested\n---\n",
2479        );
2480        write(
2481            root,
2482            "sources/docs/records/notes/secret.md",
2483            &content_md("2026-05-02T00:00:00Z"),
2484        );
2485        // The derived catalog twin is still skipped at any depth.
2486        write(root, "records/configs/index.md", "---\ntype: index\n---\n");
2487        let store = open(&dir);
2488        let got = rels(&store.walk().unwrap());
2489        assert!(
2490            got.contains(&"records/configs/log.md".to_string()),
2491            "layer-internal log.md is content: {got:?}"
2492        );
2493        assert!(
2494            !got.iter().any(|path| path.starts_with("sources/docs/")),
2495            "nested store content must be pruned: {got:?}"
2496        );
2497        assert!(
2498            !got.iter().any(|p| p.ends_with("index.md")),
2499            "index.md is still skipped: {got:?}"
2500        );
2501        assert_eq!(
2502            store.nested_store_roots().unwrap(),
2503            vec![PathBuf::from("sources/docs")]
2504        );
2505        assert!(
2506            ensure_path_within_store(root, &root.join("sources/docs/records/notes/secret.md"))
2507                .is_err(),
2508            "outer-store containment must reject a nested-store path"
2509        );
2510        let nested = Store::open_strict(&root.join("sources/docs")).unwrap();
2511        assert!(
2512            nested.owns_path(&root.join("sources/docs/records/notes/secret.md")),
2513            "the same path is owned when the nested store is opened directly"
2514        );
2515    }
2516
2517    #[cfg(unix)]
2518    #[test]
2519    fn walk_never_reads_external_file_or_directory_symlinks() {
2520        use std::os::unix::fs::symlink;
2521
2522        let dir = empty_store();
2523        let external = tempdir().unwrap();
2524        fs::write(
2525            external.path().join("secret.md"),
2526            content_md("2026-05-03T00:00:00Z"),
2527        )
2528        .unwrap();
2529        fs::create_dir(external.path().join("folder")).unwrap();
2530        fs::write(
2531            external.path().join("folder").join("deeper.md"),
2532            content_md("2026-05-04T00:00:00Z"),
2533        )
2534        .unwrap();
2535
2536        fs::create_dir_all(dir.path().join("records/notes")).unwrap();
2537        symlink(
2538            external.path().join("secret.md"),
2539            dir.path().join("records/notes/aliased.md"),
2540        )
2541        .unwrap();
2542        symlink(
2543            external.path().join("folder"),
2544            dir.path().join("records/external"),
2545        )
2546        .unwrap();
2547
2548        let store = open(&dir);
2549        assert!(
2550            store.walk().unwrap().is_empty(),
2551            "external symlink targets must be pruned from every store sweep"
2552        );
2553        assert!(!store.owns_path(&dir.path().join("records/notes/aliased.md")));
2554        assert!(!store.owns_path(&dir.path().join("records/external")));
2555        assert_eq!(
2556            rels(&store.unowned_symlinks().unwrap()),
2557            vec![
2558                "records/external".to_string(),
2559                "records/notes/aliased.md".to_string(),
2560            ],
2561            "ignored external aliases remain observable without reading targets"
2562        );
2563    }
2564
2565    #[test]
2566    fn walk_layer_is_scoped() {
2567        let dir = empty_store();
2568        let root = dir.path();
2569        write(
2570            root,
2571            "sources/emails/2026/05/a.md",
2572            &content_md("2026-05-01T00:00:00Z"),
2573        );
2574        write(
2575            root,
2576            "records/contacts/sarah.md",
2577            &content_md("2026-05-02T00:00:00Z"),
2578        );
2579        let store = open(&dir);
2580
2581        assert_eq!(
2582            rels(&store.walk_layer(Layer::Sources).unwrap()),
2583            vec!["sources/emails/2026/05/a.md".to_string()]
2584        );
2585        assert_eq!(
2586            rels(&store.walk_layer(Layer::Records).unwrap()),
2587            vec!["records/contacts/sarah.md".to_string()]
2588        );
2589        // A layer with no directory is empty, not an error: a store with only a
2590        // sources/ tree has no records/ dir, so walking Records is empty.
2591        let only_sources = empty_store();
2592        write(
2593            only_sources.path(),
2594            "sources/emails/2026/05/a.md",
2595            &content_md("2026-05-01T00:00:00Z"),
2596        );
2597        let s2 = open(&only_sources);
2598        assert!(s2.walk_layer(Layer::Records).unwrap().is_empty());
2599    }
2600
2601    #[test]
2602    fn walk_type_folder_recurses_shards_and_accepts_abs_or_rel() {
2603        let dir = empty_store();
2604        let root = dir.path();
2605        write(
2606            root,
2607            "sources/emails/2026/05/a.md",
2608            &content_md("2026-05-01T00:00:00Z"),
2609        );
2610        write(
2611            root,
2612            "sources/emails/2026/06/b.md",
2613            &content_md("2026-06-01T00:00:00Z"),
2614        );
2615        write(root, "sources/emails/index.md", "---\ntype: index\n---\n"); // skipped
2616                                                                           // A different type folder must not leak in.
2617        write(
2618            root,
2619            "sources/docs/2026/05/c.md",
2620            &content_md("2026-05-04T00:00:00Z"),
2621        );
2622        let store = open(&dir);
2623
2624        let expected = vec![
2625            "sources/emails/2026/05/a.md".to_string(),
2626            "sources/emails/2026/06/b.md".to_string(),
2627        ];
2628        // Relative folder arg.
2629        assert_eq!(
2630            rels(&store.walk_type_folder(Path::new("sources/emails")).unwrap()),
2631            expected
2632        );
2633        // Absolute folder arg under the store resolves identically.
2634        assert_eq!(
2635            rels(
2636                &store
2637                    .walk_type_folder(&root.join("sources/emails"))
2638                    .unwrap()
2639            ),
2640            expected
2641        );
2642    }
2643
2644    // ── recent_in_type_folder ────────────────────────────────────────────────
2645
2646    #[test]
2647    fn recent_orders_by_updated_desc_then_path_and_caps() {
2648        let dir = empty_store();
2649        let root = dir.path();
2650        // newest
2651        write(
2652            root,
2653            "records/meetings/2026/05/c.md",
2654            &content_md("2026-05-03T00:00:00Z"),
2655        );
2656        // tie on updated — path asc decides (a before b)
2657        write(
2658            root,
2659            "records/meetings/2026/05/a.md",
2660            &content_md("2026-05-02T00:00:00Z"),
2661        );
2662        write(
2663            root,
2664            "records/meetings/2026/05/b.md",
2665            &content_md("2026-05-02T00:00:00Z"),
2666        );
2667        // oldest
2668        write(
2669            root,
2670            "records/meetings/2026/04/z.md",
2671            &content_md("2026-04-01T00:00:00Z"),
2672        );
2673        let store = open(&dir);
2674
2675        let all = rels(
2676            &store
2677                .recent_in_type_folder(Path::new("records/meetings"), 10)
2678                .unwrap(),
2679        );
2680        assert_eq!(
2681            all,
2682            vec![
2683                "records/meetings/2026/05/c.md".to_string(), // newest
2684                "records/meetings/2026/05/a.md".to_string(), // tie, path asc
2685                "records/meetings/2026/05/b.md".to_string(),
2686                "records/meetings/2026/04/z.md".to_string(), // oldest
2687            ]
2688        );
2689
2690        // Cap takes the n most-recent.
2691        let top2 = rels(
2692            &store
2693                .recent_in_type_folder(Path::new("records/meetings"), 2)
2694                .unwrap(),
2695        );
2696        assert_eq!(
2697            top2,
2698            vec![
2699                "records/meetings/2026/05/c.md".to_string(),
2700                "records/meetings/2026/05/a.md".to_string(),
2701            ]
2702        );
2703    }
2704
2705    #[test]
2706    fn recent_sorts_undated_files_last() {
2707        let dir = empty_store();
2708        let root = dir.path();
2709        write(
2710            root,
2711            "records/contacts/dated.md",
2712            &content_md("2026-05-01T00:00:00Z"),
2713        );
2714        // No `updated` field at all.
2715        write(
2716            root,
2717            "records/contacts/undated.md",
2718            "---\ntype: contact\nsummary: x\n---\nbody\n",
2719        );
2720        let store = open(&dir);
2721        let got = rels(
2722            &store
2723                .recent_in_type_folder(Path::new("records/contacts"), 10)
2724                .unwrap(),
2725        );
2726        assert_eq!(
2727            got,
2728            vec![
2729                "records/contacts/dated.md".to_string(),
2730                "records/contacts/undated.md".to_string(),
2731            ],
2732            "a file with a real `updated` must outrank one with none"
2733        );
2734    }
2735
2736    // ── type_shards ──────────────────────────────────────────────────────────
2737
2738    #[test]
2739    fn type_shards_classification() {
2740        let dir = empty_store();
2741        let store = open(&dir);
2742        for t in [
2743            "email",
2744            "transcript",
2745            "pdf-source",
2746            "expense",
2747            "invoice",
2748            "meeting",
2749            "order",
2750            "ticket",
2751            "transaction",
2752        ] {
2753            assert!(store.type_shards(t), "{t} should shard");
2754        }
2755        for t in [
2756            "contact", "company", "decision", "profile", "index", "log", "db-md", "proposal",
2757        ] {
2758            assert!(!store.type_shards(t), "{t} should stay flat");
2759        }
2760    }
2761
2762    #[test]
2763    fn type_shards_respects_schema_directive_both_directions() {
2764        use crate::parser::{Config, Schema};
2765        let dir = empty_store();
2766        let mut store = open(&dir);
2767        let mut config = Config::default();
2768        // A CUSTOM type (not in the built-in list) opts into date-sharding —
2769        // without the schema override `type_shards` would return false for it.
2770        config.schemas.insert(
2771            "shipment".to_string(),
2772            Schema {
2773                shard: Some(true),
2774                ..Schema::default()
2775            },
2776        );
2777        // A BUILT-IN event type opts OUT (flat) — the override wins over the
2778        // built-in default.
2779        config.schemas.insert(
2780            "expense".to_string(),
2781            Schema {
2782                shard: Some(false),
2783                ..Schema::default()
2784            },
2785        );
2786        // A schema with no `shard:` directive leaves the built-in default intact.
2787        config
2788            .schemas
2789            .insert("meeting".to_string(), Schema::default());
2790        store.config = config;
2791
2792        assert!(
2793            store.type_shards("shipment"),
2794            "custom type with `shard: by-date` must shard"
2795        );
2796        assert!(
2797            !store.type_shards("expense"),
2798            "built-in event type with `shard: flat` must go flat"
2799        );
2800        assert!(
2801            store.type_shards("meeting"),
2802            "schema without a `shard:` directive keeps the built-in default"
2803        );
2804        assert!(
2805            !store.type_shards("contact"),
2806            "unconfigured entity type stays flat"
2807        );
2808    }
2809
2810    // ── year_month_from_str ──────────────────────────────────────────────────
2811
2812    #[test]
2813    fn year_month_from_str_accepts_unpadded_month() {
2814        // A single-digit month shards to the same zero-padded folder as its twin,
2815        // matching the lenient `date`-shape validator (chrono `%Y-%m-%d`).
2816        let ym = year_month_from_str;
2817        assert_eq!(
2818            ym("2026-1-15"),
2819            Some(("2026".to_string(), "01".to_string())),
2820        );
2821        assert_eq!(
2822            ym("2026-01-15"),
2823            Some(("2026".to_string(), "01".to_string())),
2824        );
2825        assert_eq!(
2826            ym("2026-12-5"),
2827            Some(("2026".to_string(), "12".to_string())),
2828        );
2829        assert_eq!(ym("2026-1"), Some(("2026".to_string(), "01".to_string())));
2830        // Full timestamps still parse off the leading date.
2831        assert_eq!(
2832            ym("2026-3-22T10:00:00-07:00"),
2833            Some(("2026".to_string(), "03".to_string())),
2834        );
2835    }
2836
2837    #[test]
2838    fn year_month_from_str_rejects_non_dates() {
2839        // Genuinely non-date input still returns None (behavior unchanged).
2840        assert_eq!(year_month_from_str(""), None);
2841        assert_eq!(year_month_from_str("not-a-date"), None);
2842        assert_eq!(year_month_from_str("2026"), None); // no month part
2843        assert_eq!(year_month_from_str("26-1-15"), None); // year not 4 digits
2844        assert_eq!(year_month_from_str("2026-13-01"), None); // month out of range
2845        assert_eq!(year_month_from_str("2026-0-01"), None); // month zero
2846        assert_eq!(year_month_from_str("2026-001-01"), None); // month over 2 digits
2847        assert_eq!(year_month_from_str("2026-x-01"), None); // non-numeric month
2848        assert_eq!(year_month_from_str("20a6-1-15"), None); // non-numeric year
2849    }
2850
2851    #[test]
2852    fn shard_path_accepts_unpadded_month_same_as_padded() {
2853        // End-to-end: an unpadded `date` shards to its real month, identically to
2854        // its zero-padded twin — not to the `created`-fallback month.
2855        let dir = empty_store();
2856        let store = open(&dir);
2857
2858        let padded = store
2859            .shard_path_for("expense", &fm_with_extra("date", "2026-01-15"), "padded")
2860            .unwrap();
2861        assert_eq!(padded, PathBuf::from("records/expenses/2026/01/padded.md"));
2862
2863        let single = store
2864            .shard_path_for("expense", &fm_with_extra("date", "2026-1-15"), "single")
2865            .unwrap();
2866        assert_eq!(single, PathBuf::from("records/expenses/2026/01/single.md"));
2867    }
2868
2869    // ── shard_path_for ───────────────────────────────────────────────────────
2870
2871    fn fm_with_extra(key: &str, value: &str) -> Frontmatter {
2872        let mut fm = Frontmatter::default();
2873        fm.extra.insert(
2874            key.to_string(),
2875            serde_norway::Value::String(value.to_string()),
2876        );
2877        fm
2878    }
2879
2880    fn fm_with_created(rfc3339: &str) -> Frontmatter {
2881        Frontmatter {
2882            created: Some(DateTime::parse_from_rfc3339(rfc3339).unwrap()),
2883            ..Default::default()
2884        }
2885    }
2886
2887    #[test]
2888    fn shard_path_uses_primary_date_field_per_type() {
2889        let dir = empty_store();
2890        let store = open(&dir);
2891
2892        // expense.date → records/expenses/<YYYY>/<MM>/
2893        let p = store
2894            .shard_path_for("expense", &fm_with_extra("date", "2026-05-22"), "lunch")
2895            .unwrap();
2896        assert_eq!(p, PathBuf::from("records/expenses/2026/05/lunch.md"));
2897
2898        // email.date → sources/emails/<YYYY>/<MM>/
2899        let p = store
2900            .shard_path_for(
2901                "email",
2902                &fm_with_extra("date", "2026-11-02T09:00:00-07:00"),
2903                "e1",
2904            )
2905            .unwrap();
2906        assert_eq!(p, PathBuf::from("sources/emails/2026/11/e1.md"));
2907
2908        // transcript.recorded_at → sources/transcripts/<YYYY>/<MM>/
2909        let p = store
2910            .shard_path_for(
2911                "transcript",
2912                &fm_with_extra("recorded_at", "2025-01-15T12:00:00Z"),
2913                "t1",
2914            )
2915            .unwrap();
2916        assert_eq!(p, PathBuf::from("sources/transcripts/2025/01/t1.md"));
2917    }
2918
2919    #[test]
2920    fn shard_path_falls_back_to_created() {
2921        let dir = empty_store();
2922        let store = open(&dir);
2923        // meeting with no `date` field but a `created` timestamp.
2924        let p = store
2925            .shard_path_for(
2926                "meeting",
2927                &fm_with_created("2024-07-09T08:30:00-04:00"),
2928                "sync",
2929            )
2930            .unwrap();
2931        assert_eq!(p, PathBuf::from("records/meetings/2024/07/sync.md"));
2932    }
2933
2934    #[test]
2935    fn shard_path_primary_field_wins_over_created() {
2936        let dir = empty_store();
2937        let store = open(&dir);
2938        let mut fm = fm_with_created("2020-01-01T00:00:00Z");
2939        fm.extra.insert(
2940            "date".into(),
2941            serde_norway::Value::String("2026-05-22".into()),
2942        );
2943        let p = store.shard_path_for("expense", &fm, "x").unwrap();
2944        // The primary `date` (2026/05), not `created` (2020/01), drives the shard.
2945        assert_eq!(p, PathBuf::from("records/expenses/2026/05/x.md"));
2946    }
2947
2948    #[test]
2949    fn shard_path_flat_types_have_no_shard_segment() {
2950        let dir = empty_store();
2951        let store = open(&dir);
2952        // A contact has a `created` date, but contacts stay flat.
2953        let p = store
2954            .shard_path_for(
2955                "contact",
2956                &fm_with_created("2026-05-22T00:00:00Z"),
2957                "sarah-chen",
2958            )
2959            .unwrap();
2960        assert_eq!(p, PathBuf::from("records/contacts/sarah-chen.md"));
2961
2962        // A conclusion `profile` is a custom (non-built-in) type: it is flat (no
2963        // date shard) and lands under the records-layer fallback folder
2964        // `records/<type>` — `records/profile/<name>.md`, a conforming 3-component
2965        // `<layer>/<type-folder>/<file>` path. A 2-component path would be
2966        // invisible to the index/validate type-folder model.
2967        let p = store
2968            .shard_path_for("profile", &Frontmatter::default(), "renewal-theme")
2969            .unwrap();
2970        assert_eq!(p, PathBuf::from("records/profile/renewal-theme.md"));
2971    }
2972
2973    /// Regression: a type written through the toolkit's own path computation
2974    /// must land at a path the index + validate type-folder model accepts. A
2975    /// 2-component `<layer>/<file>` path is one `type_folder_of` (in both `index`
2976    /// and `validate`) treats as "no type-folder" — it would either crash
2977    /// `Index::on_write` (it tried to create `index.md` inside a file) or be
2978    /// silently dropped from every catalog by `Index::rebuild_all`. A custom
2979    /// (non-built-in) type like a conclusion `profile` falls back to
2980    /// `records/<type>` — still a conforming 3-component
2981    /// `<layer>/<type-folder>/<file>` path.
2982    #[test]
2983    fn shard_path_custom_type_is_indexable_three_component_path() {
2984        let dir = empty_store();
2985        let store = open(&dir);
2986        let p = store
2987            .shard_path_for("profile", &Frontmatter::default(), "renewal-theme")
2988            .unwrap();
2989        // First two components are a layer + a non-empty type-folder segment;
2990        // the file is the third. This is exactly the shape `type_folder_of`
2991        // (`comps.len() >= 3`, `comps[0]` a known layer) requires.
2992        let comps: Vec<&str> = p.iter().filter_map(|c| c.to_str()).collect();
2993        assert_eq!(
2994            comps.len(),
2995            3,
2996            "custom-type path must be <layer>/<type-folder>/<file>, got {p:?}"
2997        );
2998        assert_eq!(
2999            comps[0], "records",
3000            "first component must be the records layer (a custom type is \
3001             filed under the records fallback)"
3002        );
3003        assert!(
3004            !comps[1].is_empty() && comps[1] != "renewal-theme.md",
3005            "second component must be a real type-folder, not the file: {p:?}"
3006        );
3007        assert!(
3008            comps[2].ends_with(".md"),
3009            "third component must be the .md file: {p:?}"
3010        );
3011    }
3012
3013    #[test]
3014    fn shard_path_preserves_and_adds_md_extension() {
3015        let dir = empty_store();
3016        let store = open(&dir);
3017        let with = store
3018            .shard_path_for("contact", &Frontmatter::default(), "sarah.md")
3019            .unwrap();
3020        let without = store
3021            .shard_path_for("contact", &Frontmatter::default(), "sarah")
3022            .unwrap();
3023        assert_eq!(with, PathBuf::from("records/contacts/sarah.md"));
3024        assert_eq!(without, PathBuf::from("records/contacts/sarah.md"));
3025    }
3026
3027    #[test]
3028    fn shard_path_errors_when_sharding_type_has_no_date() {
3029        let dir = empty_store();
3030        let store = open(&dir);
3031        // expense shards, but no `date` and no `created` → NoShardDate.
3032        let err = store
3033            .shard_path_for("expense", &Frontmatter::default(), "mystery")
3034            .unwrap_err();
3035        match err {
3036            StoreError::NoShardDate { file } => {
3037                assert_eq!(file, PathBuf::from("records/expenses/mystery.md"));
3038            }
3039            other => panic!("expected NoShardDate, got {other:?}"),
3040        }
3041    }
3042
3043    // ── find_links_to ────────────────────────────────────────────────────────
3044
3045    #[test]
3046    fn find_links_to_matches_all_accepted_spellings() {
3047        let dir = empty_store();
3048        let root = dir.path();
3049        let target = "records/contacts/sarah-chen";
3050
3051        // Plain link.
3052        write(
3053            root,
3054            "records/profiles/sarah.md",
3055            &format!(
3056                "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[{target}]].\n"
3057            ),
3058        );
3059        // Link with display text.
3060        write(
3061            root,
3062            "records/meetings/2026/05/m.md",
3063            &format!("---\ntype: meeting\nsummary: s\n---\nWith [[{target}|Sarah]].\n"),
3064        );
3065        // Link with .md extension (accepted, warned by validate).
3066        write(
3067            root,
3068            "records/concepts/t.md",
3069            &format!(
3070                "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[{target}.md]]\n"
3071            ),
3072        );
3073        // A catalog/index file also contains the link literally — included.
3074        write(
3075            root,
3076            "records/contacts/index.md",
3077            &format!("---\ntype: index\n---\n- [[{target}]] — Sarah\n"),
3078        );
3079        // No link to the target.
3080        write(
3081            root,
3082            "records/profiles/elena.md",
3083            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nNo links here.\n",
3084        );
3085        // Short-form link must NOT match the full-path target.
3086        write(
3087            root,
3088            "records/profiles/bob.md",
3089            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\n[[sarah-chen]]\n",
3090        );
3091        // A longer path that merely starts with the target must NOT match
3092        // (boundary correctness): target `sarah-chen` vs `sarah-chen-jr`.
3093        write(
3094            root,
3095            "records/profiles/jr.md",
3096            &format!(
3097                "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\n[[{target}-jr]]\n"
3098            ),
3099        );
3100
3101        let store = open(&dir);
3102        let got = rels(&store.find_links_to(Path::new(target)).unwrap());
3103        assert_eq!(
3104            got,
3105            vec![
3106                "records/concepts/t.md".to_string(),
3107                "records/contacts/index.md".to_string(),
3108                "records/meetings/2026/05/m.md".to_string(),
3109                "records/profiles/sarah.md".to_string(),
3110            ]
3111        );
3112    }
3113
3114    #[test]
3115    fn find_links_to_distinguishes_sibling_paths() {
3116        // Two contacts whose paths share a prefix; a link to one must not be
3117        // reported as a link to the other.
3118        let dir = empty_store();
3119        let root = dir.path();
3120        write(
3121            root,
3122            "records/concepts/a.md",
3123            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah]]\n",
3124        );
3125        write(
3126            root,
3127            "records/concepts/b.md",
3128            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
3129        );
3130        let store = open(&dir);
3131
3132        assert_eq!(
3133            rels(
3134                &store
3135                    .find_links_to(Path::new("records/contacts/sarah"))
3136                    .unwrap()
3137            ),
3138            vec!["records/concepts/a.md".to_string()]
3139        );
3140        assert_eq!(
3141            rels(
3142                &store
3143                    .find_links_to(Path::new("records/contacts/sarah-chen"))
3144                    .unwrap()
3145            ),
3146            vec!["records/concepts/b.md".to_string()]
3147        );
3148    }
3149
3150    #[test]
3151    fn regression_find_links_to_tolerates_invalid_utf8_on_a_matched_line() {
3152        // Regression: a `.md` file can carry a stray non-UTF-8 byte on the SAME
3153        // line as a `[[target]]` link (a verbatim-ingested `sources/` artifact,
3154        // e.g. a mis-decoded Latin-1 import). The scan must still report the
3155        // link — `find_links_to` / `find_links_to_any` (and `graph backlinks` +
3156        // the working-set validate incoming-linker pass) must not error out and
3157        // drop the legitimate UTF-8 linkers. The content scan reads the file
3158        // with `String::from_utf8_lossy`, so the invalid byte becomes a
3159        // replacement char and the ASCII `[[target]]` link is still extracted.
3160        let dir = empty_store();
3161        let root = dir.path();
3162        let target = "records/contacts/sarah-chen";
3163
3164        // A clean, fully-UTF-8 linker that MUST be returned regardless.
3165        write(
3166            root,
3167            "records/profiles/clean.md",
3168            &format!(
3169                "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[{target}]].\n"
3170            ),
3171        );
3172
3173        // A linker whose link line ALSO carries a stray 0xFF byte (a mis-decoded
3174        // Latin-1 import). Write raw bytes so the invalid byte survives — a
3175        // `&str` fixture could not express it. The byte-level regex still
3176        // matches `[[target]]` on this line; pre-fix the UTF8 sink aborted here.
3177        let mut bytes: Vec<u8> =
3178            b"---\ntype: email\nsummary: s\n---\nSee [[records/contacts/sarah-chen]] \xFF here\n"
3179                .to_vec();
3180        let dirty_abs = root.join("sources/emails/2026/05/raw.md");
3181        fs::create_dir_all(dirty_abs.parent().unwrap()).unwrap();
3182        fs::write(&dirty_abs, &bytes).unwrap();
3183        // Defensive: confirm the fixture really is invalid UTF-8 (so the test
3184        // exercises the bug, not a coincidentally-valid file).
3185        assert!(
3186            std::str::from_utf8(&bytes).is_err(),
3187            "fixture must contain invalid UTF-8 to exercise the regression"
3188        );
3189        bytes.clear();
3190
3191        let store = open(&dir);
3192        let got = rels(
3193            &store
3194                .find_links_to(Path::new(target))
3195                .expect("a stray non-UTF-8 byte must not abort the backlink scan"),
3196        );
3197        assert_eq!(
3198            got,
3199            vec![
3200                "records/profiles/clean.md".to_string(),
3201                "sources/emails/2026/05/raw.md".to_string(),
3202            ],
3203            "both the clean linker and the one with an invalid byte on the link \
3204             line are reported; the scan degrades, it does not fail"
3205        );
3206    }
3207
3208    // ── find_links_to_any (batch — the O(changed × store) fix) ─────────────────
3209
3210    /// The working-set validate's incoming-linker discovery runs through
3211    /// `find_links_to_any` over the WHOLE changed set in one pass. This pins the
3212    /// batch contract that makes that single-pass behavior correct: the result is
3213    /// the union of incoming linkers across every target, with per-target
3214    /// boundary correctness preserved (no alternation arm bleeds into a
3215    /// prefix-sharing sibling). If a regression reverts the batch finder to a
3216    /// per-object loop, the union below would still hold — but the boundary +
3217    /// union-equivalence assertions are what guard the *correctness* of folding N
3218    /// scans into one regex.
3219    #[test]
3220    fn find_links_to_any_returns_the_union_with_boundary_correctness() {
3221        let dir = empty_store();
3222        let root = dir.path();
3223
3224        // Two distinct targets, each with its own linker.
3225        write(
3226            root,
3227            "records/concepts/links-sarah.md",
3228            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
3229        );
3230        write(
3231            root,
3232            "records/concepts/links-acme.md",
3233            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\nDeal with [[records/companies/acme|Acme]].\n",
3234        );
3235        // One file links to BOTH targets — must appear exactly once (deduped),
3236        // proving the per-file early-exit folds multiple-target hits into a
3237        // single result row rather than one row per matched target.
3238        write(
3239            root,
3240            "records/meetings/2026/05/m.md",
3241            "---\ntype: meeting\nsummary: s\n---\n[[records/contacts/sarah-chen]] re \
3242             [[records/companies/acme]]\n",
3243        );
3244        // A prefix-sharing sibling of a target: a link to `sarah-chen-jr` must NOT
3245        // be reported as a link to `sarah-chen` even though the alternation now
3246        // carries `sarah-chen` as one arm.
3247        write(
3248            root,
3249            "records/concepts/links-jr.md",
3250            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen-jr]]\n",
3251        );
3252        // A file that links to neither requested target.
3253        write(
3254            root,
3255            "records/concepts/unrelated.md",
3256            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/concepts/spend]]\n",
3257        );
3258
3259        let store = open(&dir);
3260        let targets = vec![
3261            PathBuf::from("records/contacts/sarah-chen"),
3262            PathBuf::from("records/companies/acme"),
3263        ];
3264
3265        let got = rels(&store.find_links_to_any(&targets).unwrap());
3266        assert_eq!(
3267            got,
3268            vec![
3269                "records/concepts/links-acme.md".to_string(),
3270                "records/concepts/links-sarah.md".to_string(),
3271                "records/meetings/2026/05/m.md".to_string(),
3272            ],
3273            "batch finder must return the deduped union of linkers across all \
3274             targets, excluding the prefix-sibling and the unrelated file"
3275        );
3276
3277        // Equivalence: the batch result must equal the union of the per-target
3278        // single finder. This is the property the working-set path relies on
3279        // when it folds one-scan-per-object into one scan for the whole set.
3280        let mut union: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
3281        for t in &targets {
3282            for linker in store.find_links_to(t).unwrap() {
3283                union.insert(linker);
3284            }
3285        }
3286        assert_eq!(
3287            rels(&union.into_iter().collect::<Vec<_>>()),
3288            got,
3289            "find_links_to_any must equal the union of per-target find_links_to"
3290        );
3291    }
3292
3293    /// An empty target set must scan nothing and find nothing — and crucially
3294    /// must NOT compile to a match-everything empty regex (which would report
3295    /// every `.md` as a linker). This is the empty-working-set fast path the
3296    /// `validate` loop hits when nothing changed.
3297    #[test]
3298    fn find_links_to_any_empty_targets_matches_nothing() {
3299        let dir = empty_store();
3300        let root = dir.path();
3301        write(
3302            root,
3303            "records/concepts/a.md",
3304            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
3305        );
3306        let store = open(&dir);
3307
3308        assert!(
3309            store.find_links_to_any(&[]).unwrap().is_empty(),
3310            "no targets ⇒ no linkers (an empty pattern must not match every file)"
3311        );
3312        // A set of only empty/non-link targets is likewise a no-op, not a
3313        // match-everything.
3314        assert!(
3315            store
3316                .find_links_to_any(&[PathBuf::from(""), PathBuf::from("./")])
3317                .unwrap()
3318                .is_empty(),
3319            "targets that render to empty link text contribute no alternation arm"
3320        );
3321    }
3322
3323    // ── read_type_index ──────────────────────────────────────────────────────
3324
3325    #[test]
3326    fn read_type_index_parses_records_and_flattens_fields() {
3327        let dir = empty_store();
3328        let root = dir.path();
3329        let jsonl = "\
3330{\"path\":\"records/expenses/2026/05/a.md\",\"type\":\"expense\",\"summary\":\"lunch\",\"tags\":[\"meals\"],\"links\":[\"records/companies/acme\"],\"created\":\"2026-05-01T00:00:00Z\",\"updated\":\"2026-05-01T00:00:00Z\",\"vendor\":\"acme\",\"amount\":42}
3331{\"path\":\"records/expenses/2026/05/b.md\",\"type\":\"expense\",\"summary\":\"taxi\",\"created\":null,\"updated\":null,\"vendor\":\"yellow\"}
3332";
3333        let p = write(root, "records/expenses/index.jsonl", jsonl);
3334        let store = open(&dir);
3335        let recs = store.read_type_index(&store.abs_path(&p)).unwrap();
3336
3337        assert_eq!(recs.len(), 2);
3338        // Sorted by path asc.
3339        assert_eq!(recs[0].path, PathBuf::from("records/expenses/2026/05/a.md"));
3340        assert_eq!(recs[0].type_, "expense");
3341        assert_eq!(recs[0].summary, "lunch");
3342        assert_eq!(recs[0].tags, vec!["meals".to_string()]);
3343        assert_eq!(recs[0].links, vec!["records/companies/acme".to_string()]);
3344        assert!(recs[0].created.is_some());
3345        // Extra (non-typed) frontmatter flattens into `fields`.
3346        assert_eq!(
3347            recs[0].fields.get("vendor"),
3348            Some(&serde_json::json!("acme"))
3349        );
3350        assert_eq!(recs[0].fields.get("amount"), Some(&serde_json::json!(42)));
3351        // Defaults: missing tags/links → empty.
3352        assert!(recs[1].tags.is_empty());
3353        assert!(recs[1].links.is_empty());
3354    }
3355
3356    #[test]
3357    fn read_type_index_last_write_wins_and_skips_blanks() {
3358        let dir = empty_store();
3359        let root = dir.path();
3360        // Same path twice; the second line supersedes the first. A blank line
3361        // in between must be ignored, not error.
3362        let jsonl = "\
3363{\"path\":\"records/contacts/sarah.md\",\"type\":\"contact\",\"summary\":\"old\",\"created\":null,\"updated\":null}
3364
3365{\"path\":\"records/contacts/sarah.md\",\"type\":\"contact\",\"summary\":\"new\",\"created\":null,\"updated\":null}
3366";
3367        let p = write(root, "records/contacts/index.jsonl", jsonl);
3368        let store = open(&dir);
3369        let recs = store.read_type_index(&store.abs_path(&p)).unwrap();
3370        assert_eq!(recs.len(), 1, "duplicate path collapses to one record");
3371        assert_eq!(recs[0].summary, "new", "later line must win");
3372    }
3373
3374    #[test]
3375    fn read_type_index_errors_on_malformed_line() {
3376        let dir = empty_store();
3377        let root = dir.path();
3378        let p = write(root, "records/contacts/index.jsonl", "{not valid json}\n");
3379        let store = open(&dir);
3380        let err = store.read_type_index(&store.abs_path(&p)).unwrap_err();
3381        assert!(matches!(err, StoreError::BadTypeIndex { .. }));
3382    }
3383
3384    // ── find_by_type / find_by_where ─────────────────────────────────────────
3385
3386    fn jsonl_line(path: &str, type_: &str, summary: &str, extra: &str) -> String {
3387        format!(
3388            "{{\"path\":\"{path}\",\"type\":\"{type_}\",\"summary\":\"{summary}\",\"created\":null,\"updated\":null{extra}}}\n"
3389        )
3390    }
3391
3392    #[test]
3393    fn find_by_type_reads_canonical_folder_sidecar() {
3394        let dir = empty_store();
3395        let root = dir.path();
3396        // Canonical folder for `contact` is records/contacts.
3397        write(
3398            root,
3399            "records/contacts/index.jsonl",
3400            &(jsonl_line("records/contacts/sarah.md", "contact", "Sarah", "")
3401                + &jsonl_line("records/contacts/elena.md", "contact", "Elena", "")),
3402        );
3403        // A different type's sidecar must not leak into a contact query.
3404        write(
3405            root,
3406            "records/companies/index.jsonl",
3407            &jsonl_line("records/companies/acme.md", "company", "Acme", ""),
3408        );
3409        let store = open(&dir);
3410        let recs = store.find_by_type("contact").unwrap();
3411        let names: Vec<_> = recs.iter().map(|r| r.summary.clone()).collect();
3412        assert_eq!(names, vec!["Elena".to_string(), "Sarah".to_string()]); // path-sorted
3413        assert!(recs.iter().all(|r| r.type_ == "contact"));
3414    }
3415
3416    #[test]
3417    fn regression_find_by_type_includes_non_canonical_folder_when_canonical_exists() {
3418        // Regression for the silent-incompleteness bug: once the canonical
3419        // type-folder sidecar exists, `find_by_type` used to read ONLY that
3420        // sidecar and drop same-type records filed in a non-canonical folder in
3421        // the SAME layer — so the result flipped to incomplete the moment a
3422        // canonical record was added. The write path actively enables such a
3423        // layout (`records/clients/` for a `contact`, any `records/<folder>/`
3424        // for a conclusion `profile`), so this is a reachable, dedup-breaking
3425        // omission.
3426        let dir = empty_store();
3427        let root = dir.path();
3428
3429        // CANONICAL folder sidecar exists (`records/contacts/` for `contact`),
3430        // which is exactly the condition that triggered the bug.
3431        write(
3432            root,
3433            "records/contacts/index.jsonl",
3434            &jsonl_line("records/contacts/sarah.md", "contact", "Sarah", ""),
3435        );
3436        // A `contact` filed in a NON-canonical folder within the same (Records)
3437        // layer. Pre-fix this was silently dropped because the canonical
3438        // sidecar existed; it must now come back.
3439        write(
3440            root,
3441            "records/clients/index.jsonl",
3442            &jsonl_line("records/clients/elena.md", "contact", "Elena", ""),
3443        );
3444        // A different type in the same layer must NOT leak in (proves the read
3445        // is type-filtered, not just a blind whole-layer dump).
3446        write(
3447            root,
3448            "records/companies/index.jsonl",
3449            &jsonl_line("records/companies/acme.md", "company", "Acme", ""),
3450        );
3451
3452        let store = open(&dir);
3453        let got: std::collections::BTreeSet<String> = store
3454            .find_by_type("contact")
3455            .unwrap()
3456            .into_iter()
3457            .map(|r| r.path.to_string_lossy().into_owned())
3458            .collect();
3459        assert_eq!(
3460            got,
3461            ["records/clients/elena.md", "records/contacts/sarah.md"]
3462                .into_iter()
3463                .map(String::from)
3464                .collect::<std::collections::BTreeSet<_>>(),
3465            "both the canonical-folder and the non-canonical-folder contact must \
3466             be returned; the company record must be excluded"
3467        );
3468    }
3469
3470    #[test]
3471    fn regression_find_by_type_profile_spans_multiple_topic_folders() {
3472        // Regression for the scoped-backlinks variant of the same bug
3473        // (`graph backlinks --type <conclusion-type>`): a conclusion type like
3474        // `profile` has the canonical fallback folder `records/profile`, but the
3475        // agent may file profiles under ANY records topic folder
3476        // (`records/people/`, `records/clients/`, …). With a
3477        // `records/profile/index.jsonl` present, the old code read only that
3478        // folder and dropped profiles in the other topic folders —
3479        // under-reporting dependents in a blast-radius check. The
3480        // whole-`records/`-layer read must surface all of them.
3481        let dir = empty_store();
3482        let root = dir.path();
3483        write(
3484            root,
3485            "records/profile/index.jsonl",
3486            &jsonl_line("records/profile/billing.md", "profile", "Billing", ""),
3487        );
3488        write(
3489            root,
3490            "records/people/index.jsonl",
3491            &jsonl_line("records/people/sarah-chen.md", "profile", "Sarah Chen", ""),
3492        );
3493        write(
3494            root,
3495            "records/clients/index.jsonl",
3496            &jsonl_line("records/clients/atlas.md", "profile", "Atlas", ""),
3497        );
3498
3499        let store = open(&dir);
3500        let got: std::collections::BTreeSet<String> = store
3501            .find_by_type("profile")
3502            .unwrap()
3503            .into_iter()
3504            .map(|r| r.path.to_string_lossy().into_owned())
3505            .collect();
3506        assert_eq!(
3507            got,
3508            [
3509                "records/clients/atlas.md",
3510                "records/people/sarah-chen.md",
3511                "records/profile/billing.md",
3512            ]
3513            .into_iter()
3514            .map(String::from)
3515            .collect::<std::collections::BTreeSet<_>>(),
3516            "a profile query must return records from every topic folder, not \
3517             just the canonical records/profile/"
3518        );
3519    }
3520
3521    #[test]
3522    fn find_by_type_canonical_absent_falls_back_within_the_layer_only() {
3523        let dir = empty_store();
3524        let root = dir.path();
3525        // A custom `proposal` record filed under a non-canonical folder NAME
3526        // (the natural plural `records/proposals/`) inside the records layer.
3527        // `default_type_folder("proposal")` = `records/proposal` (bare type, no
3528        // pluralization guess), so the canonical sidecar does not exist and
3529        // `find_by_type` falls back. The fallback is bounded to the type's
3530        // layer (records), so this record — same layer, non-canonical folder —
3531        // is still found: completeness within the layer holds.
3532        write(
3533            root,
3534            "records/proposals/index.jsonl",
3535            &jsonl_line("records/proposals/p1.md", "proposal", "Q3 proposal", ""),
3536        );
3537        // A DECOY of the SAME type sitting in a DIFFERENT layer (sources/). The
3538        // old whole-store fallback read every sidecar in the store and would
3539        // have leaked this into the result; the layer-bounded fallback must not.
3540        // It also pins that the fallback is O(entities-in-layer), never O(store).
3541        write(
3542            root,
3543            "sources/proposals/index.jsonl",
3544            &jsonl_line(
3545                "sources/proposals/leak.md",
3546                "proposal",
3547                "cross-layer decoy",
3548                "",
3549            ),
3550        );
3551        let store = open(&dir);
3552        let recs = store.find_by_type("proposal").unwrap();
3553        assert_eq!(
3554            recs.len(),
3555            1,
3556            "only the records-layer proposal, not the sources decoy"
3557        );
3558        assert_eq!(recs[0].summary, "Q3 proposal");
3559        assert_eq!(recs[0].path, PathBuf::from("records/proposals/p1.md"));
3560    }
3561
3562    #[test]
3563    fn find_by_type_canonical_absent_does_not_read_other_layers() {
3564        let dir = empty_store();
3565        let root = dir.path();
3566        // `email`'s canonical folder is `sources/emails` (layer Sources). No
3567        // sidecar there yet, so `find_by_type("email")` falls back — but only
3568        // within the Sources layer. A populated sidecar in the Records layer
3569        // must never be touched: the fallback is layer-bounded, not store-wide.
3570        // Under the old `read_all_type_indexes_in(None)` fallback this records
3571        // sidecar would have been read and filtered (wasted O(store) I/O); now
3572        // it is outside the walk root entirely.
3573        write(
3574            root,
3575            "records/contacts/index.jsonl",
3576            &jsonl_line("records/contacts/sarah.md", "contact", "Sarah", ""),
3577        );
3578        let store = open(&dir);
3579        // No email anywhere ⇒ empty, and the records layer was not in scope.
3580        assert!(store.find_by_type("email").unwrap().is_empty());
3581    }
3582
3583    #[test]
3584    fn find_by_where_matches_typed_columns_and_flat_fields() {
3585        let dir = empty_store();
3586        let root = dir.path();
3587        write(
3588            root,
3589            "records/expenses/index.jsonl",
3590            &(jsonl_line(
3591                "records/expenses/a.md",
3592                "expense",
3593                "lunch",
3594                ",\"vendor\":\"acme\",\"tags\":[\"meals\"]",
3595            ) + &jsonl_line(
3596                "records/expenses/b.md",
3597                "expense",
3598                "taxi",
3599                ",\"vendor\":\"yellow\"",
3600            )),
3601        );
3602        write(
3603            root,
3604            "records/contacts/index.jsonl",
3605            &jsonl_line(
3606                "records/contacts/sarah.md",
3607                "contact",
3608                "Sarah",
3609                ",\"tags\":[\"customer\"]",
3610            ),
3611        );
3612        let store = open(&dir);
3613
3614        // Flat field in `fields`.
3615        let by_vendor = store.find_by_where("vendor", "acme").unwrap();
3616        assert_eq!(by_vendor.len(), 1);
3617        assert_eq!(by_vendor[0].path, PathBuf::from("records/expenses/a.md"));
3618
3619        // Typed column: type (spans both expense records).
3620        assert_eq!(store.find_by_where("type", "expense").unwrap().len(), 2);
3621
3622        // Typed list column: tags membership.
3623        let customers = store.find_by_where("tags", "customer").unwrap();
3624        assert_eq!(customers.len(), 1);
3625        assert_eq!(
3626            customers[0].path,
3627            PathBuf::from("records/contacts/sarah.md")
3628        );
3629
3630        // No match → empty.
3631        assert!(store.find_by_where("vendor", "nobody").unwrap().is_empty());
3632    }
3633
3634    #[test]
3635    fn find_by_where_matches_timestamps_across_rfc3339_spellings() {
3636        let dir = empty_store();
3637        let root = dir.path();
3638        // db.md files most commonly carry the `Z` UTC spelling. The index.jsonl
3639        // serialized from such a file preserves it verbatim.
3640        write(
3641            root,
3642            "records/meetings/index.jsonl",
3643            "{\"path\":\"records/meetings/kickoff.md\",\"type\":\"meeting\",\
3644\"summary\":\"kickoff\",\"created\":\"2026-05-01T00:00:00Z\",\
3645\"updated\":\"2026-05-02T09:30:00-07:00\"}\n",
3646        );
3647        let store = open(&dir);
3648
3649        // The exact value an agent reads out of the file (`Z` form) must match.
3650        let by_z = store
3651            .find_by_where("created", "2026-05-01T00:00:00Z")
3652            .unwrap();
3653        assert_eq!(by_z.len(), 1);
3654        assert_eq!(by_z[0].path, PathBuf::from("records/meetings/kickoff.md"));
3655
3656        // The equivalent explicit-offset spelling of the same instant matches too.
3657        assert_eq!(
3658            store
3659                .find_by_where("created", "2026-05-01T00:00:00+00:00")
3660                .unwrap()
3661                .len(),
3662            1
3663        );
3664
3665        // A non-UTC stored value matches both its own offset spelling and the
3666        // same instant expressed as `Z` (instant comparison, not string compare).
3667        assert_eq!(
3668            store
3669                .find_by_where("updated", "2026-05-02T09:30:00-07:00")
3670                .unwrap()
3671                .len(),
3672            1
3673        );
3674        assert_eq!(
3675            store
3676                .find_by_where("updated", "2026-05-02T16:30:00Z")
3677                .unwrap()
3678                .len(),
3679            1
3680        );
3681
3682        // A different instant does not match.
3683        assert!(store
3684            .find_by_where("created", "2026-05-01T00:00:01Z")
3685            .unwrap()
3686            .is_empty());
3687        // A non-RFC3339 query value never matches a real timestamp.
3688        assert!(store
3689            .find_by_where("created", "2026-05-01")
3690            .unwrap()
3691            .is_empty());
3692    }
3693
3694    #[test]
3695    fn find_by_where_matches_floats_across_serialized_spellings() {
3696        // Adversarial review #5: a float field is stored in index.jsonl via
3697        // serde_json's canonical f64 render, which DISCARDS the file's source
3698        // spelling (`1234.00` -> `1234.0`, `1e3` -> `1000.0`). A textual compare
3699        // made the spelling a human reads in the file miss (and disagree with
3700        // free-text `search`); numeric compare fixes it. `query`
3701        // is the SPEC pre-write dedup primitive, so a miss here silently writes a
3702        // duplicate record.
3703        let dir = empty_store();
3704        let root = dir.path();
3705        write(
3706            root,
3707            "records/invoices/index.jsonl",
3708            "{\"path\":\"records/invoices/inv.md\",\"type\":\"invoice\",\
3709\"summary\":\"inv\",\"amount\":1234.0,\"score\":1000.0,\"count\":42}\n",
3710        );
3711        let store = open(&dir);
3712
3713        // Every spelling of the same numeric value matches the canonical-f64 store.
3714        for spelling in ["1234.00", "1234.0", "1234"] {
3715            assert_eq!(
3716                store.find_by_where("amount", spelling).unwrap().len(),
3717                1,
3718                "amount spelling `{spelling}` must match the stored 1234.0"
3719            );
3720        }
3721        for spelling in ["1e3", "1000", "1000.0"] {
3722            assert_eq!(
3723                store.find_by_where("score", spelling).unwrap().len(),
3724                1,
3725                "score spelling `{spelling}` must match the stored 1000.0"
3726            );
3727        }
3728        // A genuinely different value does not match.
3729        assert!(store.find_by_where("amount", "1234.5").unwrap().is_empty());
3730        // Integer fields keep exact textual matching (unaffected by the fix).
3731        assert_eq!(store.find_by_where("count", "42").unwrap().len(), 1);
3732    }
3733
3734    #[test]
3735    fn number_matches_is_numeric_for_floats_but_exact_for_integers() {
3736        use serde_json::Number;
3737        // Float-valued field: any equal spelling matches (the bug fix).
3738        let f: Number = serde_json::from_str("1234.0").unwrap();
3739        assert!(number_matches(&f, "1234.00"));
3740        assert!(number_matches(&f, "1234"));
3741        assert!(number_matches(&f, "1234.0"));
3742        assert!(!number_matches(&f, "1234.5"));
3743        // Integer-valued field: EXACT textual compare, never f64-rounded — two
3744        // adjacent large integers that round to the same f64 must NOT collide
3745        // (the safety property that motivates restricting numeric compare to
3746        // floats).
3747        let big: Number = serde_json::from_str("18446744073709551615").unwrap(); // u64::MAX
3748        assert!(number_matches(&big, "18446744073709551615"));
3749        assert!(!number_matches(&big, "18446744073709551614"));
3750    }
3751
3752    #[test]
3753    fn find_by_where_in_layer_reads_only_that_layers_sidecars() {
3754        // The O(entities-in-layer) contract: a layer-scoped where read must walk
3755        // ONLY the named layer's subtree. Proven structurally — a *malformed*
3756        // sidecar in another layer would make `read_type_index` error if it were
3757        // read, so a scoped read that succeeds (and excludes that record) is
3758        // proof the other layer's I/O never happened.
3759        let dir = empty_store();
3760        let root = dir.path();
3761        write(
3762            root,
3763            "records/companies/index.jsonl",
3764            &jsonl_line(
3765                "records/companies/acme.md",
3766                "company",
3767                "Acme",
3768                ",\"domain\":\"acme.com\"",
3769            ),
3770        );
3771        // Same field/value in the sources layer — but the sidecar is corrupt.
3772        write(
3773            root,
3774            "sources/emails/index.jsonl",
3775            "{ this is not valid json and would error if read }\n",
3776        );
3777        let store = open(&dir);
3778
3779        // Scoped to records: the corrupt sources sidecar is out of scope, so the
3780        // read succeeds and returns only the records-layer match.
3781        let in_records = store
3782            .find_by_where_in("domain", "acme.com", Some(Layer::Records))
3783            .expect("a records-scoped read must not touch the sources sidecar");
3784        assert_eq!(
3785            rels(
3786                &in_records
3787                    .iter()
3788                    .map(|r| r.path.clone())
3789                    .collect::<Vec<_>>()
3790            ),
3791            vec!["records/companies/acme.md".to_string()]
3792        );
3793
3794        // The store-wide read DOES reach the corrupt sidecar and surfaces it as
3795        // a parse error — confirming the corrupt file is genuinely in the tree
3796        // and that only the layer scope spares it.
3797        let store_wide = store.find_by_where("domain", "acme.com");
3798        assert!(
3799            matches!(store_wide, Err(StoreError::BadTypeIndex { .. })),
3800            "unscoped read walks every layer and hits the corrupt sidecar"
3801        );
3802
3803        // Scoping to the layer that holds only the corrupt sidecar still errors
3804        // (the scope includes it), proving the scope is a real subtree bound and
3805        // not a silent "skip anything that fails".
3806        let in_sources = store.find_by_where_in("domain", "acme.com", Some(Layer::Sources));
3807        assert!(matches!(in_sources, Err(StoreError::BadTypeIndex { .. })));
3808    }
3809
3810    #[test]
3811    fn find_by_where_in_missing_layer_is_empty_not_an_error() {
3812        // A layer-scoped read over a layer folder that does not exist yet must
3813        // return empty (mirrors `walk_layer`'s missing-dir guard), never a walk
3814        // error from `ignore` over a nonexistent path.
3815        let dir = empty_store();
3816        let root = dir.path();
3817        write(
3818            root,
3819            "records/contacts/index.jsonl",
3820            &jsonl_line(
3821                "records/contacts/sarah.md",
3822                "contact",
3823                "Sarah",
3824                ",\"city\":\"denver\"",
3825            ),
3826        );
3827        let store = open(&dir);
3828
3829        // `sources/` was never created.
3830        let in_sources = store
3831            .find_by_where_in("city", "denver", Some(Layer::Sources))
3832            .expect("missing layer subtree is empty, not an error");
3833        assert!(in_sources.is_empty());
3834
3835        // Same query scoped to the layer that has the record still finds it.
3836        let in_records = store
3837            .find_by_where_in("city", "denver", Some(Layer::Records))
3838            .unwrap();
3839        assert_eq!(in_records.len(), 1);
3840    }
3841
3842    // ── abs_path / rel_path ──────────────────────────────────────────────────
3843
3844    #[test]
3845    fn abs_and_rel_path_roundtrip() {
3846        let dir = empty_store();
3847        let store = open(&dir);
3848        let rel = Path::new("records/contacts/sarah.md");
3849        let abs = store.abs_path(rel);
3850        assert_eq!(abs, dir.path().join(rel));
3851        assert_eq!(store.rel_path(&abs).as_deref(), Some(rel));
3852
3853        // An absolute path is passed through unchanged by abs_path.
3854        assert_eq!(store.abs_path(&abs), abs);
3855
3856        // A path outside the store has no store-relative form.
3857        assert_eq!(store.rel_path(Path::new("/somewhere/else.md")), None);
3858    }
3859
3860    // ── infer_type_from_path (inverse of default_type_folder) ────────────────
3861
3862    #[test]
3863    fn infer_type_maps_every_recognized_folder_back_to_its_type() {
3864        let cases = [
3865            ("sources/emails/x.md", "email"),
3866            ("sources/transcripts/x.md", "transcript"),
3867            ("sources/docs/x.md", "pdf-source"),
3868            ("sources/notes/x.md", "note"),
3869            ("records/contacts/x.md", "contact"),
3870            ("records/companies/x.md", "company"),
3871            ("records/expenses/x.md", "expense"),
3872            ("records/meetings/x.md", "meeting"),
3873            ("records/decisions/x.md", "decision"),
3874            ("records/invoices/x.md", "invoice"),
3875        ];
3876        for (path, expected) in cases {
3877            assert_eq!(
3878                infer_type_from_path(Path::new(path)).as_deref(),
3879                Some(expected),
3880                "path {path} should infer type {expected}"
3881            );
3882        }
3883    }
3884
3885    #[test]
3886    fn infer_type_round_trips_with_default_type_folder() {
3887        // The canonical invariant: inference is the inverse of the forward map.
3888        // Every recognized type, routed through `default_type_folder` and then
3889        // back through `infer_type_from_path`, must return the original type.
3890        let recognized = [
3891            "email",
3892            "transcript",
3893            "pdf-source",
3894            "contact",
3895            "company",
3896            "expense",
3897            "meeting",
3898            "decision",
3899            "invoice",
3900        ];
3901        for type_ in recognized {
3902            let folder = default_type_folder(type_);
3903            let file = folder.join("x.md");
3904            assert_eq!(
3905                infer_type_from_path(&file).as_deref(),
3906                Some(type_),
3907                "recognized type {type_} (folder {folder:?}) must round-trip"
3908            );
3909        }
3910    }
3911
3912    #[test]
3913    fn infer_type_round_trips_custom_types_verbatim_no_singularization() {
3914        // Regression guard for the CLI/core divergence: `default_type_folder`'s
3915        // unrecognized fallback is the BARE type name (`task → records/task`,
3916        // `tasks → records/tasks`). Inference must NOT singularize, or a custom
3917        // type would not round-trip (e.g. `records/tasks` → `task` would clash
3918        // with `default_type_folder("task") → records/task`).
3919        for custom in ["task", "tasks", "playbook", "process", "okrs", "ticket"] {
3920            let folder = default_type_folder(custom);
3921            assert_eq!(folder, PathBuf::from("records").join(custom));
3922            let file = folder.join("x.md");
3923            assert_eq!(
3924                infer_type_from_path(&file).as_deref(),
3925                Some(custom),
3926                "custom type {custom} must round-trip verbatim (no singularization)"
3927            );
3928        }
3929
3930        // The specific case named in the finding: a plural custom folder keeps
3931        // its trailing `s`; it is NOT singularized to `task`.
3932        assert_eq!(
3933            infer_type_from_path(Path::new("records/tasks/x.md")).as_deref(),
3934            Some("tasks"),
3935            "records/tasks must infer `tasks`, not `task`"
3936        );
3937    }
3938
3939    #[test]
3940    fn infer_type_requires_three_component_layer_folder_file_shape() {
3941        // Fewer than 3 components: a file directly under a layer has no
3942        // type-folder, so inference yields None (matches the old CLI contract).
3943        assert_eq!(infer_type_from_path(Path::new("records/x.md")), None);
3944        assert_eq!(infer_type_from_path(Path::new("sources/x.md")), None);
3945        assert_eq!(infer_type_from_path(Path::new("x.md")), None);
3946        // Unknown leading layer is never inferred.
3947        assert_eq!(infer_type_from_path(Path::new("foo/bar/x.md")), None);
3948        // Deeper paths still infer from the first type-folder segment (e.g. a
3949        // sharded record under records/expenses/2026/05/x.md).
3950        assert_eq!(
3951            infer_type_from_path(Path::new("records/expenses/2026/05/x.md")).as_deref(),
3952            Some("expense"),
3953        );
3954    }
3955
3956    // ── ensure_path_within_store (containment) ───────────────────────────────
3957
3958    #[test]
3959    fn ensure_path_within_store_accepts_in_store_and_rejects_escape() {
3960        let dir = tempdir().unwrap();
3961        let root = dir.path();
3962        fs::create_dir_all(root.join("records/contacts")).unwrap();
3963        fs::write(root.join("records/contacts/sarah.md"), "x").unwrap();
3964
3965        // An existing in-store file resolves and is accepted.
3966        let inside = root.join("records/contacts/sarah.md");
3967        let got = ensure_path_within_store(root, &inside).expect("in-store path accepted");
3968        // Canonical, but still under the (canonical) root.
3969        assert!(got.starts_with(root.canonicalize().unwrap()));
3970
3971        // A not-yet-existing in-store leaf is accepted (rename destination).
3972        let new_leaf = root.join("records/contacts/sarah-chen.md");
3973        assert!(
3974            ensure_path_within_store(root, &new_leaf).is_ok(),
3975            "a non-existent in-store leaf must be accepted"
3976        );
3977
3978        // A `..`-escaping path is rejected even though its prefix exists.
3979        let escape = root.join("records/contacts/../../outside/secret.md");
3980        assert!(
3981            ensure_path_within_store(root, &escape).is_err(),
3982            "a `..`-escaping path must be rejected"
3983        );
3984    }
3985
3986    #[test]
3987    fn ensure_path_within_store_rejects_symlink_escape() {
3988        let dir = tempdir().unwrap();
3989        let root = dir.path().join("store");
3990        fs::create_dir_all(&root).unwrap();
3991        let outside_dir = dir.path().join("outside");
3992        fs::create_dir_all(&outside_dir).unwrap();
3993        let secret = outside_dir.join("secret.md");
3994        fs::write(&secret, "TOPSECRET").unwrap();
3995
3996        // A symlink inside the store that points OUTSIDE it must be rejected:
3997        // resolving the symlink lands outside the canonical root.
3998        #[cfg(unix)]
3999        {
4000            use std::os::unix::fs::symlink;
4001            let link = root.join("escape.md");
4002            symlink(&secret, &link).unwrap();
4003            assert!(
4004                ensure_path_within_store(&root, &link).is_err(),
4005                "a symlink resolving outside the store must be rejected"
4006            );
4007        }
4008    }
4009
4010    /// The amortized gate accepts and rejects exactly what the single-shot
4011    /// gate does — same resolved paths, same failures — across every candidate
4012    /// class: existing file (fast path), second file in the same folder
4013    /// (memoized parent), missing leaf (slow-path peel), `..` tail, symlink
4014    /// leaf escaping the store, and a symlinked PARENT dir escaping the store.
4015    #[test]
4016    fn store_containment_matches_single_shot_gate() {
4017        let dir = tempdir().unwrap();
4018        let root = dir.path().join("store");
4019        fs::create_dir_all(root.join("records/contacts")).unwrap();
4020        fs::write(root.join("records/contacts/sarah.md"), "x").unwrap();
4021        fs::write(root.join("records/contacts/jules.md"), "y").unwrap();
4022        let outside_dir = dir.path().join("outside");
4023        fs::create_dir_all(&outside_dir).unwrap();
4024        fs::write(outside_dir.join("secret.md"), "TOPSECRET").unwrap();
4025
4026        let mut gate = StoreContainment::new(&root).expect("root canonicalizes");
4027        let same = |cand: &Path, label: &str, gate: &mut StoreContainment| {
4028            let single = ensure_path_within_store(&root, cand);
4029            let amortized = gate.resolve(cand);
4030            match (single, amortized) {
4031                (Ok(a), Ok(b)) => assert_eq!(a, b, "{label}: resolved paths differ"),
4032                (Err(_), Err(_)) => {}
4033                (s, a) => panic!("{label}: verdicts differ — single-shot {s:?} vs amortized {a:?}"),
4034            }
4035        };
4036
4037        same(
4038            &root.join("records/contacts/sarah.md"),
4039            "existing file",
4040            &mut gate,
4041        );
4042        same(
4043            &root.join("records/contacts/jules.md"),
4044            "memoized parent",
4045            &mut gate,
4046        );
4047        same(
4048            &root.join("records/contacts/new-leaf.md"),
4049            "missing leaf",
4050            &mut gate,
4051        );
4052        same(
4053            &root.join("records/contacts/../../outside/secret.md"),
4054            "`..` tail",
4055            &mut gate,
4056        );
4057
4058        #[cfg(unix)]
4059        {
4060            use std::os::unix::fs::symlink;
4061            // Symlink LEAF out of the store: slow path, rejected by both.
4062            let link = root.join("records/contacts/escape.md");
4063            symlink(outside_dir.join("secret.md"), &link).unwrap();
4064            same(&link, "symlink leaf escape", &mut gate);
4065            assert!(
4066                gate.resolve(&link).is_err(),
4067                "symlink leaf must be rejected"
4068            );
4069
4070            // Symlinked PARENT dir out of the store: the fast path's parent
4071            // canonicalize resolves it outside the root — rejected by both.
4072            let linked_dir = root.join("records/linked");
4073            symlink(&outside_dir, &linked_dir).unwrap();
4074            let through = linked_dir.join("secret.md");
4075            same(&through, "symlinked parent escape", &mut gate);
4076            assert!(
4077                gate.resolve(&through).is_err(),
4078                "a candidate under a symlinked-out parent must be rejected"
4079            );
4080        }
4081    }
4082
4083    // ── shared link-edge notion (fence / whitespace / case) ──────────────────
4084
4085    #[test]
4086    fn extract_edge_targets_trims_inner_whitespace() {
4087        // Padded `[[ x ]]` is the same edge as `[[x]]`.
4088        assert_eq!(
4089            extract_edge_targets("See [[ records/contacts/sarah ]] today."),
4090            vec!["records/contacts/sarah".to_string()]
4091        );
4092    }
4093
4094    #[test]
4095    fn extract_edge_targets_skips_fenced_code_blocks() {
4096        // A `[[...]]` inside a ``` fence is a doc example, NOT an edge — matching
4097        // validate's body extractor.
4098        let body = "\
4099Real [[records/contacts/sarah]] link.
4100
4101```markdown
4102[[records/contacts/ghost-example]] is how you link.
4103```
4104
4105After fence [[records/companies/acme]].
4106";
4107        let got = extract_edge_targets(body);
4108        assert_eq!(
4109            got,
4110            vec![
4111                "records/contacts/sarah".to_string(),
4112                "records/companies/acme".to_string(),
4113            ],
4114            "fenced example link must not be an edge"
4115        );
4116    }
4117
4118    #[test]
4119    fn edge_spans_agree_with_edge_targets_on_every_body_shape() {
4120        // THE anti-drift guarantee. Two extractors over one grammar is exactly
4121        // the duplication this type exists to prevent elsewhere, so the pair
4122        // must never disagree: same links, same order, same fence decisions.
4123        // Every hostile body shape the target tests cover, in one corpus.
4124        let bodies = [
4125            "Plain [[records/contacts/sarah]] link.",
4126            "See [[ records/contacts/sarah ]] and [[records/companies/acme|Acme Inc]].",
4127            "Fenced:\n\n```markdown\n[[records/ghost]]\n```\n\nAfter [[records/real]].",
4128            "~~~\n[[records/tilde-ghost]]\n~~~\n[[records/after-tilde]]",
4129            "   ```\n[[records/indented-fence-ghost]]\n   ```\n[[records/after]]",
4130            "````\n```\n[[records/nested-ghost]]\n```\n````\n[[records/after-long]]",
4131            "Mis-encoded [[[a]], [[b]]] and real [[records/x]].",
4132            "Unclosed [[records/never-closed and then [[records/ok]].",
4133            "Empty [[]] and blank [[   ]] and real [[records/y]].",
4134            "Multi [[a]] on [[b]] one [[c]] line.",
4135            "Anchored [[records/x#section]] and aliased [[records/y#s|Label]].",
4136            "Trailing newline body [[records/z]]\n",
4137            "", // degenerate
4138        ];
4139        for body in bodies {
4140            let spans = extract_edge_spans(body);
4141            let targets = extract_edge_targets(body);
4142            assert_eq!(
4143                spans.iter().map(|s| s.target.clone()).collect::<Vec<_>>(),
4144                targets,
4145                "span targets diverged from edge targets for body:\n{body}"
4146            );
4147            // And every span must actually index the `[[…]]` token it claims.
4148            for s in &spans {
4149                let slice = &body[s.start..s.end];
4150                assert!(
4151                    slice.starts_with("[[") && slice.ends_with("]]"),
4152                    "span {}..{} is not a wiki-link token (got {slice:?}) in:\n{body}",
4153                    s.start,
4154                    s.end
4155                );
4156                assert_eq!(
4157                    &slice[2..slice.len() - 2],
4158                    s.raw,
4159                    "span raw text must be the token's inner text"
4160                );
4161            }
4162        }
4163    }
4164
4165    #[test]
4166    fn edge_spans_carry_alias_and_keep_fragments_in_the_target() {
4167        let spans = extract_edge_spans("Go [[records/notes/x#setup|Read the setup]] now.");
4168        assert_eq!(spans.len(), 1);
4169        assert_eq!(spans[0].alias.as_deref(), Some("Read the setup"));
4170        // The fragment stays IN the target — fragments are not in the format.
4171        assert_eq!(spans[0].target, "records/notes/x#setup");
4172        assert_eq!(spans[0].raw, "records/notes/x#setup|Read the setup");
4173        // A splice over the span replaces exactly the token.
4174        let body = "Go [[records/notes/x#setup|Read the setup]] now.";
4175        let out = format!("{}LINK{}", &body[..spans[0].start], &body[spans[0].end..]);
4176        assert_eq!(out, "Go LINK now.");
4177    }
4178
4179    #[test]
4180    fn extract_edge_targets_frontmatter_fence_does_not_swallow_body_links() {
4181        // Regression: `search_by_link` / `forwardlinks` / `dbmd graph backlinks` feed the
4182        // WHOLE file (frontmatter + body) here. A stray code-fence run inside a
4183        // frontmatter value must NOT open a markdown fence that swallows the
4184        // body's real wiki-links. Frontmatter links are still edges; a link
4185        // genuinely inside a BODY fence is still ignored.
4186        let file = "\
4187---
4188type: note
4189summary: \"a note\"
4190ref: \"[[records/contacts/sarah]]\"
4191snippet: \"```\"
4192---
4193
4194Body mentions [[records/companies/acme]].
4195
4196```
4197[[records/contacts/ghost-example]] inside a body fence.
4198```
4199
4200After fence [[records/contacts/dave]].
4201";
4202        let got = extract_edge_targets(file);
4203        assert_eq!(
4204            got,
4205            vec![
4206                "records/contacts/sarah".to_string(), // frontmatter edge
4207                "records/companies/acme".to_string(), // body edge AFTER the frontmatter ```
4208                "records/contacts/dave".to_string(),  // body edge after a real body fence
4209            ],
4210            "a code fence inside frontmatter must not suppress body wiki-links, \
4211             and a real body-fenced link must still be ignored"
4212        );
4213    }
4214
4215    #[test]
4216    fn extract_edge_targets_handles_nested_indented_and_long_run_fences() {
4217        // Regression for the naive `starts_with("```")/("~~~")` toggle: a fence
4218        // nested inside another, an over-indented (>3 space) marker, and a
4219        // long-run fence wrapping a shorter inner one must all leave the block's
4220        // links un-extracted (validate treats the whole block as opaque). The
4221        // (char, run-length) tracker keys on the OPENING fence and closes only on
4222        // a matching char with run ≥ the opener.
4223
4224        // (a) A ```` ```` ````-run block (run 4) wrapping a ``` example (run 3).
4225        // The inner ``` does NOT close the outer run-4 fence, so both `[[...]]`
4226        // inside stay fenced.
4227        let nested = "\
4228Doc:
4229
4230````
4231```
4232[[records/contacts/bob]]
4233```
4234still fenced [[records/contacts/bob]]
4235````
4236
4237Real [[records/companies/acme]].
4238";
4239        assert_eq!(
4240            extract_edge_targets(nested),
4241            vec!["records/companies/acme".to_string()],
4242            "a nested ``` inside a ````-run fence must not leak the fenced links"
4243        );
4244
4245        // (b) A `~~~` block containing a ``` line (the standard way to document a
4246        // backtick fence). The inner backtick line must not flip the state.
4247        let tilde_wraps_backtick = "\
4248~~~
4249```
4250[[records/contacts/ghost]]
4251```
4252~~~
4253
4254After [[records/companies/acme]].
4255";
4256        assert_eq!(
4257            extract_edge_targets(tilde_wraps_backtick),
4258            vec!["records/companies/acme".to_string()],
4259            "a ``` line inside a ~~~ block must not invert the fence state"
4260        );
4261
4262        // (c) An over-indented ```` ``` ```` (4 spaces) is NOT a fence; the link
4263        // on the next line is live.
4264        let over_indented = "    ```\nLive [[records/contacts/sarah]].\n";
4265        assert_eq!(
4266            extract_edge_targets(over_indented),
4267            vec!["records/contacts/sarah".to_string()],
4268            "a >3-space-indented ``` is not a fence opener"
4269        );
4270    }
4271
4272    #[test]
4273    fn canonical_link_target_strips_md_dotslash_and_trims() {
4274        assert_eq!(canonical_link_target("  records/x.md  "), "records/x");
4275        assert_eq!(canonical_link_target("./records/y"), "records/y");
4276        assert_eq!(canonical_link_target("/records/z"), "records/z");
4277    }
4278
4279    #[test]
4280    fn link_edge_key_folds_case_only_on_case_insensitive_fs() {
4281        let a = link_edge_key("records/contacts/Sarah-Chen");
4282        let b = link_edge_key("records/contacts/sarah-chen");
4283        if fs_is_case_insensitive() {
4284            assert_eq!(a, b, "case-insensitive FS must fold the key");
4285        } else {
4286            assert_ne!(a, b, "case-sensitive FS must keep the key case-exact");
4287        }
4288    }
4289
4290    #[test]
4291    fn link_edge_key_unifies_nfc_and_nfd_normalization_forms() {
4292        // REGRESSION (Unicode encoding / silent graph break): on macOS/APFS a
4293        // file written in one Unicode normalization form and a link written in
4294        // the other name the SAME file (the FS folds NFC/NFD), but their raw
4295        // bytes differ. The edge comparison key must fold them to one key on
4296        // every platform, or the graph (backlinks/forwardlinks/orphans) keys the
4297        // two as different targets and silently misses the edge.
4298        let nfc = "records/contacts/jos\u{00e9}"; // é = U+00E9 (NFC)
4299        let nfd = "records/contacts/jose\u{0301}"; // e + U+0301 (NFD)
4300                                                   // The two inputs are genuinely byte-different (the test would be vacuous
4301                                                   // otherwise).
4302        assert_ne!(nfc, nfd, "test inputs must be byte-distinct NFC vs NFD");
4303        assert_eq!(
4304            link_edge_key(nfc),
4305            link_edge_key(nfd),
4306            "NFC and NFD spellings of the same name must produce one edge key"
4307        );
4308    }
4309
4310    // ── walk refuses symlinked content ───────────────────────────────────────
4311
4312    #[cfg(unix)]
4313    #[test]
4314    fn walk_skips_symlinked_content_file_and_symlinked_folder() {
4315        use std::os::unix::fs::symlink;
4316        let dir = empty_store();
4317        let root = dir.path();
4318        // A regular file (control).
4319        write(
4320            root,
4321            "records/contacts/sarah.md",
4322            &content_md("2026-05-01T00:00:00Z"),
4323        );
4324        // A symlinked .md content file inside a real folder.
4325        let external_file = root.join("external-elena.md");
4326        fs::write(&external_file, content_md("2026-05-02T00:00:00Z")).unwrap();
4327        symlink(&external_file, root.join("records/contacts/elena.md")).unwrap();
4328        // A symlinked type folder.
4329        let external_dir = dir.path().join("external-companies");
4330        fs::create_dir_all(&external_dir).unwrap();
4331        fs::write(
4332            external_dir.join("acme.md"),
4333            content_md("2026-05-03T00:00:00Z"),
4334        )
4335        .unwrap();
4336        symlink(&external_dir, root.join("records/companies")).unwrap();
4337
4338        let store = open(&dir);
4339        let got = rels(&store.walk().unwrap());
4340        assert_eq!(
4341            got,
4342            vec!["records/contacts/sarah.md".to_string()],
4343            "store sweeps must not follow symlink leaves or ancestors: {got:?}"
4344        );
4345    }
4346
4347    // ── find_links_to: padded / fenced / case ────────────────────────────────
4348
4349    #[test]
4350    fn find_links_to_matches_whitespace_padded_link() {
4351        let dir = empty_store();
4352        let root = dir.path();
4353        write(
4354            root,
4355            "records/profiles/a.md",
4356            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[ records/contacts/sarah ]] today.\n",
4357        );
4358        let store = open(&dir);
4359        let got = rels(
4360            &store
4361                .find_links_to(Path::new("records/contacts/sarah"))
4362                .unwrap(),
4363        );
4364        assert_eq!(
4365            got,
4366            vec!["records/profiles/a.md".to_string()],
4367            "a padded `[[ x ]]` link must be found as a backward edge, matching forwardlinks"
4368        );
4369    }
4370
4371    #[test]
4372    fn find_links_to_ignores_fenced_example_link() {
4373        let dir = empty_store();
4374        let root = dir.path();
4375        write(
4376            root,
4377            "records/concepts/howto.md",
4378            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n```markdown\n[[records/contacts/sarah]]\n```\n",
4379        );
4380        let store = open(&dir);
4381        let got = store
4382            .find_links_to(Path::new("records/contacts/sarah"))
4383            .unwrap();
4384        assert!(
4385            got.is_empty(),
4386            "a `[[...]]` only inside a fenced code block is not a backward edge: {got:?}"
4387        );
4388    }
4389
4390    #[cfg(unix)]
4391    #[test]
4392    fn find_links_to_matches_case_variant_on_case_insensitive_fs() {
4393        // Only meaningful on a case-insensitive filesystem; on a case-sensitive
4394        // one the case-variant link is genuinely a different target.
4395        if !fs_is_case_insensitive() {
4396            return;
4397        }
4398        let dir = empty_store();
4399        let root = dir.path();
4400        write(
4401            root,
4402            "records/profiles/bio.md",
4403            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[records/contacts/Sarah-Chen]].\n",
4404        );
4405        let store = open(&dir);
4406        let got = rels(
4407            &store
4408                .find_links_to(Path::new("records/contacts/sarah-chen"))
4409                .unwrap(),
4410        );
4411        assert_eq!(
4412            got,
4413            vec!["records/profiles/bio.md".to_string()],
4414            "a case-variant link must be found on a case-insensitive filesystem"
4415        );
4416    }
4417}