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