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::path::{Path, PathBuf};
29use std::time::{SystemTime, UNIX_EPOCH};
30
31use chrono::{DateTime, Datelike, FixedOffset};
32use ignore::WalkBuilder;
33
34use crate::index::IndexRecord;
35use crate::parser::{parse_db_md, Config, Frontmatter};
36
37/// Basenames that are never content files: the config marker and the two
38/// curator-maintained catalogs. The store walks skip these so a SWEEP over the
39/// content layers never mistakes a catalog for a record.
40///
41/// Only `index.md` is excluded by basename, because the content walks traverse
42/// the layer dirs (`sources/`/`records/`) and `index.md` is the only
43/// meta file that appears INSIDE them. The root `DB.md` / `log.md` (and the
44/// `log/` archive) live at the store root, outside every layer, so they are
45/// never reached by these walks — and a content file that merely happens to be
46/// named `DB.md` or `log.md` inside a layer (e.g. `records/docs/DB.md`) is real
47/// content the SPEC does NOT reserve at type-folder depth.
48const NON_CONTENT_BASENAMES: [&str; 1] = ["index.md"];
49
50/// The complete machine-twin sidecar that backs every structured read.
51const TYPE_INDEX_FILE: &str = "index.jsonl";
52
53/// Returned when a path is opened as a store but has no `DB.md` at its root.
54/// Surfaced as the structured code `NOT_A_STORE` with a non-zero exit.
55#[derive(Debug, thiserror::Error)]
56#[error("not a db.md store: {path} has no DB.md")]
57pub struct NotAStore {
58    /// The path that was inspected.
59    pub path: PathBuf,
60}
61
62/// Errors from store-level operations (walk, locate, shard, sidecar read).
63#[derive(Debug, thiserror::Error)]
64pub enum StoreError {
65    /// A sidecar `index.jsonl` could not be read or parsed.
66    #[error("failed to read type index {path}: {message}")]
67    BadTypeIndex {
68        /// The sidecar file.
69        path: PathBuf,
70        /// What went wrong.
71        message: String,
72    },
73
74    /// A required date field for sharding was absent or unparseable, and there
75    /// was no usable fallback.
76    #[error("cannot compute shard path for {file}: no usable date field")]
77    NoShardDate {
78        /// The file being placed.
79        file: PathBuf,
80    },
81
82    /// An embedded-ripgrep scan failed to start or run.
83    #[error("search failed under {root}: {message}")]
84    Search {
85        /// The root the scan ran under.
86        root: PathBuf,
87        /// What went wrong.
88        message: String,
89    },
90
91    /// An underlying I/O failure.
92    #[error(transparent)]
93    Io(#[from] std::io::Error),
94}
95
96/// The three canonical layers of a db.md store.
97///
98/// `Ord`/`PartialOrd` are derived (additively) because sibling modules key
99/// `BTreeMap`s on `Layer` (e.g. `stats::Stats::files_per_layer`); the canonical
100/// declaration order (`Sources` < `Records`) is the sort order.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
102pub enum Layer {
103    /// `sources/` — raw evidence (documentary + testimonial); immutable; date-sharded at scale.
104    Sources,
105    /// `records/` — everything the agent authors; meta-typed fact/operational/conclusion; entity types flat, event types sharded.
106    Records,
107}
108
109impl Layer {
110    /// The on-disk folder name for this layer (`"sources"` / `"records"`).
111    pub fn dir_name(self) -> &'static str {
112        match self {
113            Layer::Sources => "sources",
114            Layer::Records => "records",
115        }
116    }
117
118    /// Parse a layer from its folder name; `None` for anything else.
119    pub fn from_dir_name(name: &str) -> Option<Self> {
120        match name {
121            "sources" => Some(Layer::Sources),
122            "records" => Some(Layer::Records),
123            _ => None,
124        }
125    }
126
127    /// Every layer, in canonical order.
128    pub fn all() -> [Layer; 2] {
129        [Layer::Sources, Layer::Records]
130    }
131}
132
133/// An opened db.md store: its root path plus the parsed `DB.md` [`Config`].
134///
135/// Construct via [`Store::open`]; that is the only path in, and it validates
136/// the `DB.md` marker so downstream code can assume a real store.
137#[derive(Debug, Clone)]
138pub struct Store {
139    /// The store root (the directory containing `DB.md`).
140    pub root: PathBuf,
141    /// The parsed `DB.md` config (agent instructions, policies, schemas).
142    pub config: Config,
143}
144
145impl Store {
146    /// True if `path` is a db.md store root: an uppercase `DB.md` file exists
147    /// at `path`. On case-sensitive filesystems a lowercase `db.md` must NOT
148    /// count (the lowercase name refers to the project/spec, not the marker).
149    pub fn is_db_md_store(path: &Path) -> bool {
150        // Read the directory and match the *stored* filename byte-for-byte.
151        // `path.join("DB.md").exists()` would lie on a case-insensitive
152        // filesystem (macOS default), where a lowercase `db.md` answers a
153        // `DB.md` probe. `read_dir` returns the real on-disk name, so the
154        // exact-match check is correct on both case-sensitive (Linux) and
155        // case-insensitive filesystems.
156        let entries = match std::fs::read_dir(path) {
157            Ok(entries) => entries,
158            Err(_) => return false,
159        };
160        for entry in entries.flatten() {
161            if entry.file_name() == "DB.md" {
162                // A directory literally named `DB.md` is not the marker.
163                match entry.file_type() {
164                    Ok(ft) if ft.is_dir() => return false,
165                    Ok(_) => return true,
166                    Err(_) => return false,
167                }
168            }
169        }
170        false
171    }
172
173    /// Open `path` as a db.md store and require `DB.md` to be readable and
174    /// parseable. Normal commands should enter through this strict gate so a
175    /// damaged config cannot silently disable schema or policy rules.
176    pub fn open_strict(path: &Path) -> crate::Result<Store> {
177        if !Store::is_db_md_store(path) {
178            return Err(NotAStore {
179                path: path.to_path_buf(),
180            }
181            .into());
182        }
183        let db_md = path.join("DB.md");
184        let text = std::fs::read_to_string(&db_md)?;
185        let config = parse_db_md(&text, &db_md)?;
186        Ok(Store {
187            root: path.to_path_buf(),
188            config,
189        })
190    }
191
192    /// Open `path` as a db.md store: confirm the `DB.md` marker (else
193    /// [`NotAStore`]) and parse the `DB.md` config when possible. This is the
194    /// lenient validation-oriented open path: a damaged `DB.md` still marks the
195    /// directory as a store so `dbmd validate` can report the config error as an
196    /// issue. Normal CLI commands should use [`Store::open_strict`] instead.
197    pub fn open(path: &Path) -> Result<Store, NotAStore> {
198        if !Store::is_db_md_store(path) {
199            return Err(NotAStore {
200                path: path.to_path_buf(),
201            });
202        }
203        let db_md = path.join("DB.md");
204        // The marker exists; parse its config. A read or parse failure leaves
205        // the store openable with default config rather than masquerading as
206        // NOT_A_STORE — the marker is present, so this *is* a store; a damaged
207        // DB.md is `dbmd validate`'s job to report, not `open`'s.
208        let config = match std::fs::read_to_string(&db_md) {
209            Ok(text) => parse_db_md(&text, &db_md).unwrap_or_default(),
210            Err(_) => Config::default(),
211        };
212        Ok(Store {
213            root: path.to_path_buf(),
214            config,
215        })
216    }
217
218    /// **SWEEP.** Recursively iterate every `.md` content file across
219    /// `sources/` and `records/`, skipping hidden dirs and `log/`.
220    /// Used only by `validate --all`, `index rebuild`, and `stats` — never on
221    /// the interactive loop.
222    pub fn walk(&self) -> Result<Vec<PathBuf>, StoreError> {
223        // Only the three content layers — never root meta files (`DB.md`,
224        // `index.md`, `log.md`) and never `log/`, which live at root and are
225        // outside every layer dir.
226        let mut out = Vec::new();
227        for layer in Layer::all() {
228            out.extend(self.walk_layer(layer)?);
229        }
230        out.sort();
231        Ok(out)
232    }
233
234    /// **SWEEP.** Like [`Store::walk`] but scoped to a single layer.
235    pub fn walk_layer(&self, layer: Layer) -> Result<Vec<PathBuf>, StoreError> {
236        let layer_root = self.root.join(layer.dir_name());
237        if !layer_root.is_dir() {
238            return Ok(Vec::new());
239        }
240        self.walk_content_md(&layer_root)
241    }
242
243    /// Enumerate every `.md` file in a single type-folder, **recursing through
244    /// its date-shards** (`sources/emails/**/*.md`). The unit the index builder
245    /// and per-folder rebuild operate on. SWEEP-class (scoped to one folder).
246    pub fn walk_type_folder(&self, type_folder: &Path) -> Result<Vec<PathBuf>, StoreError> {
247        let abs = self.resolve_under_root(type_folder);
248        if !abs.is_dir() {
249            return Ok(Vec::new());
250        }
251        self.walk_content_md(&abs)
252    }
253
254    /// The ≤`n` most-recent files in a type-folder by frontmatter `updated`
255    /// (descending), ties broken by store-relative path (ascending) — a total
256    /// order, so write-through and rebuild never disagree on #500 vs #501.
257    ///
258    /// Reads `updated` across the folder's shards — a SWEEP cost absorbed into
259    /// `index rebuild`. The write-through path never calls this. The
260    /// cap-selection primitive for the 500-entry `index.md` browse view.
261    pub fn recent_in_type_folder(
262        &self,
263        type_folder: &Path,
264        n: usize,
265    ) -> Result<Vec<PathBuf>, StoreError> {
266        let files = self.walk_type_folder(type_folder)?;
267        // (updated, rel-path) for each file. Files missing/unparseable
268        // `updated` sort *after* dated ones (None last), then by path — so they
269        // are deterministically the lowest-priority candidates for the cap, not
270        // dropped silently. The total order (updated desc, path asc) is what
271        // keeps write-through and rebuild agreeing on #500 vs #501.
272        let mut keyed: Vec<(Option<DateTime<FixedOffset>>, PathBuf)> = files
273            .into_iter()
274            .map(|rel| {
275                let updated = self.read_updated(&self.abs_path(&rel));
276                (updated, rel)
277            })
278            .collect();
279        keyed.sort_by(|a, b| {
280            // `updated` descending: newest first. `None` is treated as the
281            // oldest possible, so dated files always win a cap slot over
282            // undated ones.
283            let by_updated = b.0.cmp(&a.0);
284            by_updated.then_with(|| a.1.cmp(&b.1))
285        });
286        keyed.truncate(n);
287        Ok(keyed.into_iter().map(|(_, rel)| rel).collect())
288    }
289
290    /// The shard/flat predicate: true if the type date-shards, false if it
291    /// stays flat. True for source types and event record types
292    /// (`expense`/`invoice`/`meeting` + custom `order`/`ticket`/`transaction`),
293    /// or when `DB.md ## Schemas` declares `shard: by-date`. False for
294    /// dedup-bounded entity types (`contact`/`company`/`decision`) and
295    /// conclusion records (`profile`/`concept`/`synthesis`).
296    pub fn type_shards(&self, type_: &str) -> bool {
297        // A `DB.md ## Schemas` `### <type>` block with a `shard:` directive is
298        // authoritative — it is the v0.2 generic-model way to declare sharding,
299        // so it overrides the built-in default below (in either direction).
300        if let Some(shard) = self.config.schemas.get(type_).and_then(|s| s.shard) {
301            return shard;
302        }
303        // Built-in default for the example types. Sharding is a property of the
304        // *type*:
305        //  - source types carry a primary date field and shard;
306        //  - event record types track business volume and shard;
307        //  - dedup-bounded entity types and curation-bounded conclusion
308        //    records (`profile`/`concept`/`synthesis`) stay flat.
309        // Any type can override this via a `shard:` directive (above).
310        matches!(
311            type_,
312            // source types (documentary + testimonial)
313            "email" | "transcript" | "pdf-source" | "note"
314            // event record types (canonical)
315            | "expense" | "invoice" | "meeting"
316            // event record types (recognized custom, per the plan)
317            | "order" | "ticket" | "transaction"
318        )
319    }
320
321    /// Compute the canonical write path for a new file. For a sharding type
322    /// (per [`Store::type_shards`]) insert `<YYYY>/<MM>/` from the type's
323    /// primary date field (`email.date`, `expense.date`, … fallback `created`)
324    /// under the type folder; flat types (entity + conclusion records) get no
325    /// shard segment.
326    /// Deterministic + stable: same input → same path, so a record never moves
327    /// once written.
328    pub fn shard_path_for(
329        &self,
330        type_: &str,
331        frontmatter: &Frontmatter,
332        name: &str,
333    ) -> Result<PathBuf, StoreError> {
334        self.shard_path_in(&default_type_folder(type_), type_, frontmatter, name)
335    }
336
337    /// Like [`Store::shard_path_for`], but compute the path under an explicit,
338    /// caller-resolved type-folder rather than the canonical default. This lets a
339    /// write surface honour an agent-supplied conforming sub-folder — e.g. a
340    /// conclusion record filed under `records/profiles/`, `records/concepts/`, or
341    /// `records/synthesis/` (a conclusion record may be filed under ANY
342    /// `records/<folder>/`, not only its canonical one) — while still applying
343    /// date-sharding for sharding types. The folder must be a conforming
344    /// `<layer>/<type-folder>` (2
345    /// components, recognized layer); the caller is responsible for that (see the
346    /// CLI's `resolve_write_path`), so it is taken as given here.
347    ///
348    /// Sharding is still a property of the *type*: a sharding type gets the
349    /// `<YYYY>/<MM>` segment under `folder`; a flat type lands directly in it.
350    pub fn shard_path_in(
351        &self,
352        folder: &Path,
353        type_: &str,
354        frontmatter: &Frontmatter,
355        name: &str,
356    ) -> Result<PathBuf, StoreError> {
357        let folder = folder.to_path_buf();
358        let filename = ensure_md_extension(name);
359
360        if !self.type_shards(type_) {
361            // Flat type (entity records, conclusion records, decisions): no
362            // shard segment.
363            return Ok(folder.join(filename));
364        }
365
366        // Sharding type: derive <YYYY>/<MM> from the primary date field, with
367        // `created` as the universal fallback. Reading the public `Frontmatter`
368        // fields directly (typed `created`/`updated` + raw `extra`) avoids the
369        // not-yet-implemented `Frontmatter::get`/`parse` and keeps this pure.
370        let (year, month) = self
371            .primary_shard_segment(type_, frontmatter)
372            .ok_or_else(|| StoreError::NoShardDate {
373                file: folder.join(&filename),
374            })?;
375
376        Ok(folder.join(year).join(month).join(filename))
377    }
378
379    /// Find files with an incoming wiki-link to `target` via a **single
380    /// presence-only content scan** for an edge to `target` across all layers,
381    /// using the shared fence-aware/whitespace-trimmed/case-folded edge notion
382    /// ([`extract_edge_targets`]). Loop-fast; no whole-graph build. Returns
383    /// store-relative paths.
384    pub fn find_links_to(&self, target: &Path) -> Result<Vec<PathBuf>, StoreError> {
385        // A single target is just the degenerate batch case — one key, one store
386        // scan. Routing through `find_links_to_any` keeps the
387        // pattern construction and the scan loop in exactly one place. The
388        // batch API takes `&[PathBuf]`, so the one-element slice is owned (a
389        // single alloc on this single-target convenience path; the batch path
390        // validate.rs rides is untouched).
391        self.find_links_to_any(&[target.to_path_buf()])
392    }
393
394    /// Find every file with an incoming wiki-link to **any** of `targets`, in a
395    /// **single content pass** over the store (one `.md` walk, one presence-only
396    /// edge scan per file). This is the batch incoming-linker finder the
397    /// working-set [`crate::validate::validate_working_set`] sits on: it must find
398    /// the linkers for the *whole* changed set without paying a full store read
399    /// per changed object. Cost is therefore one store scan (O(store)), NOT
400    /// `targets.len() × store` — calling [`find_links_to`](Self::find_links_to)
401    /// in a loop would reread every `.md` once per target and is the exact
402    /// `O(changed × store)` blow-up this method exists to prevent. Returns
403    /// store-relative paths (deduped, sorted).
404    ///
405    /// **One edge notion with `forwardlinks`/`rename`/`validate`.** A file links
406    /// to a target iff [`extract_edge_targets`] (fence-aware, whitespace-trimmed)
407    /// of its content yields a target whose [`link_edge_key`] equals the target's
408    /// — the *same* definition the forward view and the rename rewriter use. The
409    /// previous implementation used a literal-adjacency ripgrep regex that (a)
410    /// matched `[[...]]` text inside fenced code examples (which validate treats
411    /// as non-edges), (b) missed inner-whitespace padding (`[[ x ]]`), and (c)
412    /// compared case-sensitively even where the filesystem resolves links
413    /// case-insensitively — so backlinks/links/rename silently disagreed with
414    /// forwardlinks and validate. Reading content and routing through the shared
415    /// extractor removes all three divergences.
416    ///
417    /// Why content scan and not the sidecar `links` field: the sidecar projects
418    /// only the frontmatter `links:` array, so it misses edges written in the
419    /// body or in typed fields (`company: [[…]]`). Finding an incoming link to an
420    /// arbitrary path therefore requires reading file content.
421    pub fn find_links_to_any(&self, targets: &[PathBuf]) -> Result<Vec<PathBuf>, StoreError> {
422        // Build the set of comparison keys for the requested targets, in the
423        // canonical (case-folded where the filesystem is case-insensitive) form
424        // the edge extractor emits. An empty key (a target that renders to no
425        // link text, e.g. `""` or `"./"`) contributes nothing — and crucially the
426        // empty set short-circuits below so we never report every file.
427        let want: std::collections::HashSet<String> = targets
428            .iter()
429            .filter_map(|t| {
430                let canonical = canonical_link_target(&t.to_string_lossy());
431                if canonical.is_empty() {
432                    None
433                } else {
434                    Some(link_edge_key(&canonical))
435                }
436            })
437            .collect();
438        if want.is_empty() {
439            return Ok(Vec::new());
440        }
441
442        let mut hits = std::collections::BTreeSet::new();
443        // Scan every `.md` file in the store (skip hidden + `log/`), including
444        // `index.md` catalogs — an incoming reference is wherever the link text
445        // lives; the caller decides relevance. ONE walk for the whole target set;
446        // per file we stop at the first matching edge (presence is all we need),
447        // so a file that links to several targets is read once, not once per
448        // target.
449        for rel in self.walk_all_md()? {
450            let abs = self.abs_path(&rel);
451            // Read lossily: a `.md` verbatim-ingested into `sources/` can carry a
452            // stray non-UTF-8 byte (a mis-decoded Latin-1 import). Decoding
453            // lossily substitutes replacement characters instead of erroring, so
454            // one bad byte on a link-bearing line no longer aborts the whole
455            // store scan (the historical `UTF8`-sink failure). The link syntax is
456            // ASCII, so a replacement char elsewhere on the line never hides a
457            // `[[...]]`. A read error (not a decode error) is genuine I/O trouble
458            // and propagates.
459            let bytes = match std::fs::read(&abs) {
460                Ok(b) => b,
461                Err(e) => {
462                    return Err(StoreError::Search {
463                        root: self.root.clone(),
464                        message: format!("read failed in {}: {e}", abs.display()),
465                    })
466                }
467            };
468            let text = String::from_utf8_lossy(&bytes);
469            for target in extract_edge_targets(&text) {
470                if want.contains(&link_edge_key(&target)) {
471                    hits.insert(rel);
472                    break;
473                }
474            }
475        }
476        Ok(hits.into_iter().collect())
477    }
478
479    /// Candidate set for a `type` query: read every type-folder `index.jsonl`
480    /// sidecar in the type's single layer and return the records of that
481    /// `type`. Complete and cold-cache-proof — NOT a walk-and-parse or a
482    /// frontmatter ripgrep scan, and **never a store-wide read**.
483    ///
484    /// The read is bounded to the type's one layer subtree
485    /// (O(entities-in-layer)): a type lives in exactly one layer, and
486    /// `default_type_folder` always encodes it (recognized → its SPEC layer;
487    /// unrecognized → `records/`), so the walk never fans out across every
488    /// sidecar in the store and stays inside the interactive loop's
489    /// O(entities) contract.
490    ///
491    /// The whole-layer read — rather than reading only the type's canonical
492    /// folder sidecar when it happens to exist — is what makes the result
493    /// *complete*. A single `type` can legitimately be filed across several
494    /// folders within its layer: a conclusion `profile` filed under any
495    /// `records/<folder>/`, or a `contact` filed in `records/clients/` alongside
496    /// the canonical `records/contacts/`. The previous code read only the
497    /// canonical-guess sidecar whenever it was a file, which silently dropped
498    /// those non-canonical records the moment the canonical sidecar existed —
499    /// returning an incomplete set, and a *different* set as the store grew
500    /// (the omission flipped on once one canonical record was added). That
501    /// broke the dedup/enumeration premise this primitive backs and disagreed
502    /// with `find_by_where_in`, which already walks the whole layer. Filtering
503    /// the layer read by `type` keeps the result complete regardless of how the
504    /// type's records are foldered.
505    pub fn find_by_type(&self, type_: &str) -> Result<Vec<IndexRecord>, StoreError> {
506        let canonical_folder = default_type_folder(type_);
507        let records = self.read_all_type_indexes_in(layer_of_folder(&canonical_folder))?;
508        Ok(records.into_iter().filter(|r| r.type_ == type_).collect())
509    }
510
511    /// Candidate set for a `key=value` frontmatter query, **store-wide**: read
512    /// every type-folder `index.jsonl` sidecar and filter their records. The
513    /// unscoped pre-write dedup primitive; prefer [`Store::find_by_where_in`]
514    /// with a layer scope to stay O(entities-in-layer) on the interactive loop.
515    pub fn find_by_where(&self, key: &str, value: &str) -> Result<Vec<IndexRecord>, StoreError> {
516        self.find_by_where_in(key, value, None)
517    }
518
519    /// Candidate set for a `key=value` frontmatter query, **scoped to one
520    /// layer** when `layer` is `Some`: the sidecar walk is confined to that
521    /// layer's subtree (`<root>/<layer>/`), so the I/O is O(entities-in-layer),
522    /// not O(store records). `None` keeps the store-wide read.
523    ///
524    /// This is what makes `--in <layer>` an I/O scope, not just a result
525    /// filter: a `--where`-only query (no `--type`) used to read every sidecar
526    /// in the store and narrow by layer in memory, breaking the O(entities)
527    /// contract the interactive loop depends on. With a layer in hand we walk
528    /// only that layer's sidecars.
529    pub fn find_by_where_in(
530        &self,
531        key: &str,
532        value: &str,
533        layer: Option<Layer>,
534    ) -> Result<Vec<IndexRecord>, StoreError> {
535        // A `key=value` query can target any frontmatter field across any type,
536        // so within the chosen subtree we still read every type-folder sidecar
537        // and filter. The layer (when given) bounds *which* subtree, turning a
538        // whole-store walk into a single-layer walk.
539        let records = self.read_all_type_indexes_in(layer)?;
540        Ok(records
541            .into_iter()
542            .filter(|r| record_matches_field(r, key, value))
543            .collect())
544    }
545
546    /// Every record across the type-folder `index.jsonl` sidecars, scoped to one
547    /// layer when `layer` is `Some` (the walk is confined to `<root>/<layer>/`)
548    /// else store-wide. Sequential, complete sidecar reads — never a
549    /// walk-and-parse of the content tree.
550    ///
551    /// This is the unfiltered sidecar-enumeration primitive the relationship
552    /// loop sits on: [`crate::graph::backlinks_filtered`] uses it to bound its
553    /// candidate set to the relevant layer (or the whole store) without opening
554    /// the content tree, then confirms each candidate's edge by parsing the file.
555    pub fn sidecar_records(&self, layer: Option<Layer>) -> Result<Vec<IndexRecord>, StoreError> {
556        self.read_all_type_indexes_in(layer)
557    }
558
559    /// Parse a type-folder's `index.jsonl` into [`IndexRecord`]s, applying
560    /// last-write-wins by `path` over any un-compacted lines. The sidecar-read
561    /// primitive every structured query sits on.
562    pub fn read_type_index(&self, index_jsonl: &Path) -> Result<Vec<IndexRecord>, StoreError> {
563        let text = std::fs::read_to_string(index_jsonl).map_err(|e| StoreError::BadTypeIndex {
564            path: index_jsonl.to_path_buf(),
565            message: e.to_string(),
566        })?;
567
568        // Last-write-wins by `path` over un-compacted lines: a later line for
569        // the same path supersedes an earlier one (the jsonl is append-mostly
570        // and only compacted on rebuild). Blank lines are skipped; a non-blank
571        // line that is not a valid IndexRecord is a hard parse error.
572        let mut by_path: BTreeMap<PathBuf, IndexRecord> = BTreeMap::new();
573        for (i, line) in text.lines().enumerate() {
574            let trimmed = line.trim();
575            if trimmed.is_empty() {
576                continue;
577            }
578            let record: IndexRecord =
579                serde_json::from_str(trimmed).map_err(|e| StoreError::BadTypeIndex {
580                    path: index_jsonl.to_path_buf(),
581                    message: format!("line {}: {e}", i + 1),
582                })?;
583            by_path.insert(record.path.clone(), record);
584        }
585        // BTreeMap keyed by path → records emerge sorted by path ascending,
586        // a deterministic order independent of line order in the file.
587        Ok(by_path.into_values().collect())
588    }
589
590    /// Resolve a store-relative path to its absolute on-disk path under
591    /// [`root`](Store::root).
592    pub fn abs_path(&self, store_relative: &Path) -> PathBuf {
593        // `Path::join` returns `store_relative` unchanged if it is already
594        // absolute, so passing an absolute path through is a no-op.
595        self.root.join(store_relative)
596    }
597
598    /// Convert an absolute path under the store into its store-relative form.
599    pub fn rel_path(&self, abs: &Path) -> Option<PathBuf> {
600        abs.strip_prefix(&self.root).ok().map(|p| p.to_path_buf())
601    }
602
603    // ── Private helpers ─────────────────────────────────────────────────────
604
605    /// Resolve a caller-supplied folder path (store-relative or absolute) to an
606    /// absolute path under the store root.
607    fn resolve_under_root(&self, folder: &Path) -> PathBuf {
608        if folder.is_absolute() {
609            folder.to_path_buf()
610        } else {
611            self.root.join(folder)
612        }
613    }
614
615    /// Walk a subtree for content `.md` files (skip hidden dirs, skip `index.md`
616    /// / `DB.md` / `log.md`), returning store-relative paths. Used by the layer
617    /// and type-folder walks.
618    fn walk_content_md(&self, root: &Path) -> Result<Vec<PathBuf>, StoreError> {
619        let mut out = Vec::new();
620        for entry in self.md_walker(root).build() {
621            let entry = entry.map_err(|e| StoreError::Search {
622                root: root.to_path_buf(),
623                message: e.to_string(),
624            })?;
625            if !is_file_entry(&entry) {
626                continue;
627            }
628            let path = entry.path();
629            if !has_md_extension(path) {
630                continue;
631            }
632            if is_non_content_basename(path) {
633                continue;
634            }
635            if let Some(rel) = self.rel_path(path) {
636                out.push(rel);
637            }
638        }
639        out.sort();
640        Ok(out)
641    }
642
643    /// Walk the whole store for **every** `.md` file (including `index.md`),
644    /// skipping hidden dirs and the `log/` archive tree. Used by the backlink
645    /// scan, where the literal link text can live in any markdown file.
646    fn walk_all_md(&self) -> Result<Vec<PathBuf>, StoreError> {
647        let mut out = Vec::new();
648        for entry in self.md_walker(&self.root).build() {
649            let entry = entry.map_err(|e| StoreError::Search {
650                root: self.root.clone(),
651                message: e.to_string(),
652            })?;
653            if !is_file_entry(&entry) {
654                continue;
655            }
656            let path = entry.path();
657            if !has_md_extension(path) {
658                continue;
659            }
660            if self.is_in_log_dir(path) {
661                continue;
662            }
663            if let Some(rel) = self.rel_path(path) {
664                out.push(rel);
665            }
666        }
667        out.sort();
668        Ok(out)
669    }
670
671    /// Read and merge every type-folder `index.jsonl` sidecar under `layer`
672    /// when given, else the whole store (skip hidden + `log/`). Each sidecar is
673    /// read with last-write-wins by path; across sidecars, paths are disjoint by
674    /// construction (one sidecar per folder), so a plain concatenation preserves
675    /// completeness. A layer scope confines the walk to `<root>/<layer>/`, which
676    /// is what keeps `find_by_where_in` O(entities-in-layer).
677    fn read_all_type_indexes_in(
678        &self,
679        layer: Option<Layer>,
680    ) -> Result<Vec<IndexRecord>, StoreError> {
681        let mut out = Vec::new();
682        for sidecar in self.find_type_index_files_in(layer)? {
683            out.extend(self.read_type_index(&self.abs_path(&sidecar))?);
684        }
685        Ok(out)
686    }
687
688    /// Locate every `index.jsonl` sidecar under `layer` (when given) else the
689    /// whole store (skip hidden + `log/`), returning store-relative paths. A
690    /// scoped read walks `<root>/<layer>/`; the store-wide read enumerates the
691    /// two canonical layer subtrees (`sources/`, `records/`) — the
692    /// same store model [`Store::walk`] uses — rather than walking from
693    /// `self.root`. Walking from root would descend into non-layer top-level
694    /// dirs (`EXPECTED/` test goldens, an `archive/` of frozen index copies,
695    /// any sibling folder holding store-relative `path`s), pulling their
696    /// sidecars in and returning every record twice. A non-existent layer
697    /// subtree yields no sidecars rather than walking a missing path.
698    fn find_type_index_files_in(&self, layer: Option<Layer>) -> Result<Vec<PathBuf>, StoreError> {
699        // Store-wide read: union the per-layer scoped reads so only the three
700        // content layers are walked (never root meta files or non-layer dirs),
701        // matching `Store::walk`. The per-layer paths are disjoint by folder, so
702        // a plain concatenation preserves completeness.
703        let Some(layer) = layer else {
704            let mut out = Vec::new();
705            for l in Layer::all() {
706                out.extend(self.find_type_index_files_in(Some(l))?);
707            }
708            out.sort();
709            return Ok(out);
710        };
711        let walk_root = self.root.join(layer.dir_name());
712        // A scoped walk over a layer folder that does not exist yet must be an
713        // empty result, mirroring `walk_layer`'s missing-dir guard — not a walk
714        // error from `ignore` over a nonexistent path.
715        if !walk_root.is_dir() {
716            return Ok(Vec::new());
717        }
718        let mut out = Vec::new();
719        let mut builder = WalkBuilder::new(&walk_root);
720        builder
721            .standard_filters(false)
722            .hidden(true)
723            .follow_links(true);
724        for entry in builder.build() {
725            let entry = entry.map_err(|e| StoreError::Search {
726                root: walk_root.clone(),
727                message: e.to_string(),
728            })?;
729            if !is_file_entry(&entry) {
730                continue;
731            }
732            let path = entry.path();
733            if path.file_name().and_then(|n| n.to_str()) != Some(TYPE_INDEX_FILE) {
734                continue;
735            }
736            if self.is_in_log_dir(path) {
737                continue;
738            }
739            if let Some(rel) = self.rel_path(path) {
740                out.push(rel);
741            }
742        }
743        out.sort();
744        Ok(out)
745    }
746
747    /// A `WalkBuilder` configured for db.md SWEEPs: gitignore/global-ignore are
748    /// OFF (a SWEEP must see every file even if the store is a git repo with a
749    /// `.gitignore`), but hidden files/dirs are skipped. Symlinks are
750    /// **followed** (`follow_links(true)`) so a symlinked `.md` content file or
751    /// a symlinked type folder (e.g. `records/companies -> /other/disk/...`) is
752    /// walked like any other content rather than silently vanishing; a symlinked
753    /// layer dir was already traversed (the walk root is followed), so following
754    /// symlinks one level deeper just removes that inconsistency.
755    fn md_walker(&self, root: &Path) -> WalkBuilder {
756        let mut builder = WalkBuilder::new(root);
757        builder
758            .standard_filters(false)
759            .hidden(true)
760            .follow_links(true);
761        builder
762    }
763
764    /// True if an absolute path lives under the store's root-level `log/`
765    /// rotation-archive directory.
766    fn is_in_log_dir(&self, abs: &Path) -> bool {
767        match self.rel_path(abs) {
768            Some(rel) => rel.components().next().map(|c| c.as_os_str()) == Some("log".as_ref()),
769            None => false,
770        }
771    }
772
773    /// Read a file's frontmatter `updated` field as an RFC3339 timestamp,
774    /// returning `None` when absent/unparseable. A self-contained reader (does
775    /// not depend on the not-yet-implemented `parser::read_file`); parses the
776    /// leading `---`-fenced YAML block with the same engine the parser uses.
777    fn read_updated(&self, abs: &Path) -> Option<DateTime<FixedOffset>> {
778        let text = std::fs::read_to_string(abs).ok()?;
779        let yaml = frontmatter_block(&text)?;
780        let value: serde_norway::Value = serde_norway::from_str(yaml).ok()?;
781        let raw = value.get("updated")?;
782        value_to_datetime(raw)
783    }
784
785    /// The `<YYYY>/<MM>` shard segment for a sharding type, from its primary
786    /// date field with a `created` fallback. Reads the public `Frontmatter`
787    /// fields directly. `None` when no usable date is present.
788    fn primary_shard_segment(&self, type_: &str, fm: &Frontmatter) -> Option<(String, String)> {
789        // Try the type's primary date field first.
790        if let Some(field) = primary_date_field(type_) {
791            if let Some(v) = fm.extra.get(field) {
792                if let Some(seg) = value_to_year_month(v) {
793                    return Some(seg);
794                }
795            }
796        }
797        // Universal fallback: the typed `created` timestamp.
798        fm.created
799            .map(|dt| (format!("{:04}", dt.year()), format!("{:02}", dt.month())))
800    }
801}
802
803// ── Path containment (security) ─────────────────────────────────────────────
804
805/// Canonicalize `candidate` (resolving symlinks; for a not-yet-existing leaf,
806/// canonicalize its existing parent chain and re-append the leaf) and return it
807/// only if it resolves inside `store_root`; otherwise `Err`.
808///
809/// This is the single within-store containment gate. A wiki-link target, a
810/// rename destination, or any other caller-influenced path must pass through
811/// here before it is read or traversed, so a `..`-laden or symlink-escaping
812/// target can never turn a store operation into a read of an arbitrary file
813/// outside the store. `store_root` itself is canonicalized first so the
814/// `starts_with` comparison is symlink-stable on both sides (e.g. macOS's
815/// `/tmp` → `/private/tmp`).
816pub fn ensure_path_within_store(store_root: &Path, candidate: &Path) -> std::io::Result<PathBuf> {
817    // The `..` rejection below must apply only to the *caller-influenced* tail of
818    // the candidate — never to a `..` the trusted `store_root` itself carries.
819    // Callers build the candidate as `store_root.join(rel)`, so a user-supplied
820    // `--dir ../../some/store` legitimately seeds every candidate with leading
821    // `..` components that belong to the root, not to the sidecar/link target.
822    // Strip the trusted `store_root` prefix lexically and scrutinize only what
823    // remains; the root's own `..` is resolved safely by `canonicalize()` just
824    // below. A candidate that does NOT begin with `store_root` (an absolute
825    // out-of-store path, a CWD-relative target) keeps the whole path under
826    // scrutiny — there is no trusted prefix to exempt.
827    let scrutinized = candidate.strip_prefix(store_root).unwrap_or(candidate);
828
829    // Reject any `..` component in the scrutinized tail. A `ParentDir` can never
830    // be resolved safely by lexical normalization: once a symlink sits earlier in
831    // the path, `foo/../bar` does NOT equal `bar`, and canonicalizing the existing
832    // prefix (below) would silently collapse `records/contacts/../../outside` down
833    // to a path that *appears* inside the root, masking the traversal. There is no
834    // legitimate in-store caller that needs `..` in the tail — wiki-link targets,
835    // rename destinations, and graph reads are all forward (`Normal`-only) paths —
836    // so a tail `..` is always either an escape attempt or a malformed target.
837    if scrutinized
838        .components()
839        .any(|c| matches!(c, std::path::Component::ParentDir))
840    {
841        return Err(std::io::Error::new(
842            std::io::ErrorKind::PermissionDenied,
843            format!(
844                "path {} contains a `..` component beyond the store root {} and cannot be contained",
845                candidate.display(),
846                store_root.display()
847            ),
848        ));
849    }
850
851    // Canonicalize the root so both sides of the containment check are in the
852    // same (fully-resolved) namespace. This also resolves any `..` the root
853    // itself carries (the user-supplied `--dir`), which the tail-only check above
854    // deliberately left in place.
855    let root = store_root.canonicalize()?;
856
857    // Resolve the candidate as far as it exists on disk. `canonicalize` fails on
858    // a not-yet-existing leaf, so peel trailing components until the remaining
859    // prefix exists, canonicalize that, then re-append the peeled tail. This
860    // resolves any symlink in the existing parent chain (an escape vector) while
861    // still working for a target that does not exist yet (a rename destination).
862    let mut existing = candidate.to_path_buf();
863    let mut tail: Vec<std::ffi::OsString> = Vec::new();
864    let resolved_prefix = loop {
865        match existing.canonicalize() {
866            Ok(p) => break p,
867            Err(_) => {
868                // No existing prefix left to canonicalize → resolve relative to
869                // the canonical root (the candidate is somewhere under, or
870                // escaping from, the store) and let the containment check below
871                // decide. Pop one component and keep peeling.
872                match existing.file_name() {
873                    Some(name) => {
874                        tail.push(name.to_os_string());
875                        if !existing.pop() {
876                            // Ran out of components without finding an existing
877                            // prefix: anchor the un-resolvable remainder at the
878                            // canonical root so a relative candidate is judged
879                            // against the store, not the process CWD.
880                            break root.clone();
881                        }
882                    }
883                    None => {
884                        // A root/prefix component with no file name and no
885                        // on-disk existence: anchor at the canonical root.
886                        break root.clone();
887                    }
888                }
889            }
890        }
891    };
892
893    // Reassemble: canonical existing prefix + the peeled (still-virtual) tail,
894    // in original order (the peel pushed them reversed).
895    let mut resolved = resolved_prefix;
896    for name in tail.into_iter().rev() {
897        resolved.push(name);
898    }
899
900    if resolved.starts_with(&root) {
901        Ok(resolved)
902    } else {
903        Err(std::io::Error::new(
904            std::io::ErrorKind::PermissionDenied,
905            format!(
906                "path {} resolves outside the store root {}",
907                candidate.display(),
908                store_root.display()
909            ),
910        ))
911    }
912}
913
914// ── The shared wiki-link edge notion (graph / stats / validate / rename) ─────
915//
916// One definition of "what `[[...]]` text is a real edge" that every relationship
917// op keys on, so `forwardlinks`, `backlinks`, `links`, `stats`, and `rename`
918// never disagree with each other (or with `validate`'s body extractor):
919//
920//   1. **Fence-aware.** A `[[...]]` inside a ``` / ~~~ fenced code block is a
921//      documentation example, not an edge — exactly `validate`'s rule. Counting
922//      it as an edge over-reports backlinks, falsely un-orphans the page, and
923//      (worst) lets `rename` rewrite verbatim example text.
924//   2. **Whitespace-trimmed.** `[[ records/contacts/sarah ]]` is the same edge
925//      as `[[records/contacts/sarah]]`. The inner padding is cosmetic; both the
926//      forward and the backward view must resolve it identically.
927//   3. **Case-folded to the filesystem.** Link *resolution* is `is_file()`,
928//      which is case-insensitive on macOS/Windows. So on a case-insensitive
929//      filesystem `[[records/contacts/Sarah-Chen]]` and the on-disk
930//      `sarah-chen.md` are the SAME edge; the comparison key must case-fold to
931//      match, or backlinks/rename silently miss the link while validate (which
932//      resolves via the filesystem) considers it fine.
933
934/// Canonicalize a raw `[[...]]` inner target into the wiki-link key: forward
935/// slashes, no leading `./` or `/`, no trailing `.md`, inner whitespace trimmed.
936/// The single key forward and backward edges are compared on. Pairs with
937/// [`link_edge_key`] for the case-fold step.
938pub fn canonical_link_target(raw: &str) -> String {
939    let mut s = raw.trim().replace('\\', "/");
940    while let Some(rest) = s.strip_prefix("./") {
941        s = rest.to_string();
942    }
943    let s = s.trim_start_matches('/');
944    let s = s.strip_suffix(".md").unwrap_or(s);
945    s.trim().to_string()
946}
947
948/// The comparison key for a canonical link target: identity on a case-sensitive
949/// filesystem, ASCII-lowercased on a case-insensitive one (macOS/Windows), so
950/// the string-keyed edge comparison agrees with the filesystem's case-folding
951/// `is_file()` resolution. Callers compare `link_edge_key(a) == link_edge_key(b)`.
952pub fn link_edge_key(canonical_target: &str) -> String {
953    if fs_is_case_insensitive() {
954        canonical_target.to_ascii_lowercase()
955    } else {
956        canonical_target.to_string()
957    }
958}
959
960/// Extract every wiki-link edge target from a markdown body, fence-aware and
961/// whitespace-trimmed, in document order (duplicates kept — callers dedup).
962/// Returns canonical targets (see [`canonical_link_target`]); the case-fold for
963/// comparison is applied separately via [`link_edge_key`] so the canonical form
964/// (used for rewrites/output) stays case-preserving.
965///
966/// Scans line-by-line tracking the fence state inline (no whole-body
967/// allocation), exactly mirroring validate's `extract_wiki_links`: the fence
968/// state is a `(fence char, run length)` tracked via [`fence_opens`] /
969/// [`fence_closes`] — NOT a bool toggled on any ``` / `~~~` line. The naive
970/// toggle inverts mid-block when a `~~~` block legally contains a ```` ``` ````
971/// line (the standard way to document a backtick fence), or when a `>3`-space-
972/// indented ``` is mistaken for a fence — both of which would let a fenced
973/// example `[[…]]` leak out as a live edge (a false dependent for
974/// backlinks/rename). Fenced lines never yield edges. Within a line, the text
975/// before the first `|` is the target; a target whose trimmed form starts with
976/// `[` is the rejected triple-bracket flow-form list mis-encoding
977/// (`[[[a]], [[b]]]`), not a real link — skipped, matching validate.
978pub fn extract_edge_targets(body: &str) -> Vec<String> {
979    let mut out = Vec::new();
980    let mut fence: Option<(u8, usize)> = None;
981    for line in body.lines() {
982        let content = line.trim_end_matches('\r');
983        if let Some(f) = fence {
984            if fence_closes(content, f) {
985                fence = None;
986            }
987            continue;
988        }
989        if let Some(opened) = fence_opens(content) {
990            fence = Some(opened);
991            continue;
992        }
993        let bytes = line.as_bytes();
994        let mut i = 0usize;
995        while i + 1 < bytes.len() {
996            if bytes[i] == b'[' && bytes[i + 1] == b'[' {
997                if let Some(close) = line[i + 2..].find("]]") {
998                    let inner = &line[i + 2..i + 2 + close];
999                    let raw_target = inner.split('|').next().unwrap_or(inner).trim();
1000                    if !raw_target.is_empty() && !raw_target.starts_with('[') {
1001                        let canonical = canonical_link_target(raw_target);
1002                        if !canonical.is_empty() {
1003                            out.push(canonical);
1004                        }
1005                    }
1006                    i = i + 2 + close + 2;
1007                    continue;
1008                }
1009            }
1010            i += 1;
1011        }
1012    }
1013    out
1014}
1015
1016/// If `line` opens a fenced code block, return `(fence byte, run length)`. The
1017/// single fence-open rule shared by [`extract_edge_targets`] and graph's
1018/// `rewrite_links_to`, mirroring validate's `fence_opens` and the parser's
1019/// `opening_fence` so every link op tracks fences identically: a fence is
1020/// ```` ``` ```` or `~~~` (run ≥ 3) at ≤ 3 spaces of indent, and a backtick
1021/// fence's info string may not itself contain a backtick.
1022pub fn fence_opens(line: &str) -> Option<(u8, usize)> {
1023    let indent = line.len() - line.trim_start_matches(' ').len();
1024    if indent > 3 {
1025        return None;
1026    }
1027    let rest = &line[indent..];
1028    let byte = rest.bytes().next()?;
1029    if byte != b'`' && byte != b'~' {
1030        return None;
1031    }
1032    let run = rest.len() - rest.trim_start_matches(byte as char).len();
1033    if run < 3 {
1034        return None;
1035    }
1036    // A backtick fence's info string may not itself contain a backtick.
1037    if byte == b'`' && rest[run..].contains('`') {
1038        return None;
1039    }
1040    Some((byte, run))
1041}
1042
1043/// True if `line` closes the currently open `fence`: same char, run at least as
1044/// long, nothing but trailing whitespace after. Mirrors validate's
1045/// `fence_closes` / the parser's `is_closing_fence`, so an inner fence of the
1046/// *other* character (a ```` ``` ```` line inside a `~~~` block) does NOT close
1047/// the outer fence.
1048pub fn fence_closes(line: &str, fence: (u8, usize)) -> bool {
1049    let (byte, open_len) = fence;
1050    let indent = line.len() - line.trim_start_matches(' ').len();
1051    if indent > 3 {
1052        return false;
1053    }
1054    let rest = &line[indent..];
1055    let run = rest.len() - rest.trim_start_matches(byte as char).len();
1056    if run < open_len {
1057        return false;
1058    }
1059    rest[run..].trim().is_empty()
1060}
1061
1062/// True when the host filesystem resolves paths case-insensitively (macOS/
1063/// Windows default). Probed once per process against the OS temp dir by creating
1064/// a lowercase marker and stat-ing its uppercase spelling. A probe failure
1065/// conservatively reports `false` (case-sensitive) — the historical behavior —
1066/// so a transient temp-dir issue never silently widens matching.
1067fn fs_is_case_insensitive() -> bool {
1068    use std::sync::OnceLock;
1069    static CASE_INSENSITIVE: OnceLock<bool> = OnceLock::new();
1070    *CASE_INSENSITIVE.get_or_init(|| {
1071        let dir = std::env::temp_dir();
1072        let pid = std::process::id();
1073        let nanos = SystemTime::now()
1074            .duration_since(UNIX_EPOCH)
1075            .map(|d| d.as_nanos())
1076            .unwrap_or(0);
1077        let lower = dir.join(format!(".dbmd-case-probe-{pid}-{nanos}"));
1078        let upper = dir.join(format!(".DBMD-CASE-PROBE-{pid}-{nanos}"));
1079        // Create the lowercase marker; if its uppercase spelling then resolves to
1080        // a file, the filesystem folded the case → case-insensitive.
1081        let result = match std::fs::File::create(&lower) {
1082            Ok(_) => upper.is_file(),
1083            Err(_) => false,
1084        };
1085        let _ = std::fs::remove_file(&lower);
1086        result
1087    })
1088}
1089
1090// ── Free helpers (no `self`) ────────────────────────────────────────────────
1091
1092/// True if a walk entry is a regular file, **following symlinks** so a
1093/// symlinked `.md` content file (or a file inside a symlinked type folder) is
1094/// counted like any other content file.
1095///
1096/// The store walks enable `follow_links(true)`, so a symlink entry's
1097/// `file_type()` still reports `is_symlink()` (the `ignore` walker does not
1098/// rewrite the entry's own type), not the followed target's type. Treat a
1099/// symlink whose target is a regular file as a file: `stat` (follow) the path
1100/// and check. A broken symlink (no target) is not a file.
1101fn is_file_entry(entry: &ignore::DirEntry) -> bool {
1102    match entry.file_type() {
1103        Some(ft) if ft.is_file() => true,
1104        Some(ft) if ft.is_symlink() => std::fs::metadata(entry.path())
1105            .map(|m| m.is_file())
1106            .unwrap_or(false),
1107        // A `None` file type (the walk root itself) or a non-file/non-symlink
1108        // entry is not a content file.
1109        _ => false,
1110    }
1111}
1112
1113/// True if the path ends in a `.md` extension (case-sensitive — db.md files are
1114/// lowercase `.md`).
1115fn has_md_extension(path: &Path) -> bool {
1116    path.extension().and_then(|e| e.to_str()) == Some("md")
1117}
1118
1119/// True if the basename is a non-content meta file (`DB.md`, `index.md`,
1120/// `log.md`) that the content walks must skip.
1121fn is_non_content_basename(path: &Path) -> bool {
1122    match path.file_name().and_then(|n| n.to_str()) {
1123        Some(name) => NON_CONTENT_BASENAMES.contains(&name),
1124        None => false,
1125    }
1126}
1127
1128/// Append `.md` to a bare name; leave an existing `.md` untouched.
1129fn ensure_md_extension(name: &str) -> String {
1130    if name.ends_with(".md") {
1131        name.to_string()
1132    } else {
1133        format!("{name}.md")
1134    }
1135}
1136
1137/// The canonical default folder for a recognized type, per the SPEC type table
1138/// (`email → sources/emails`, `expense → records/expenses`, …). Unrecognized
1139/// types fall back to `records/<type>` (the bare type name, no pluralization
1140/// guess) — see the store findings on the docstring's looser `<type>` phrasing.
1141fn default_type_folder(type_: &str) -> PathBuf {
1142    let path = match type_ {
1143        // sources — documentary
1144        "email" => "sources/emails",
1145        "transcript" => "sources/transcripts",
1146        "pdf-source" => "sources/docs",
1147        // sources — testimonial (a human told the agent X)
1148        "note" => "sources/notes",
1149        // records — entities
1150        "contact" => "records/contacts",
1151        "company" => "records/companies",
1152        // records — events
1153        "expense" => "records/expenses",
1154        "meeting" => "records/meetings",
1155        "decision" => "records/decisions",
1156        "invoice" => "records/invoices",
1157        // unrecognized: bare type name under records/ (conclusions and any
1158        // custom type land here, e.g. `concept` → `records/concept`).
1159        other => return PathBuf::from("records").join(other),
1160    };
1161    PathBuf::from(path)
1162}
1163
1164/// The canonical [`Layer`] a `type_` belongs to, derived from its default
1165/// type-folder (`email` → `Sources`, `contact` → `Records`, a conclusion
1166/// `profile` → `Records`, unrecognized → `Records`). The write path uses this to decide whether
1167/// an agent-supplied folder is in the *right* layer for the type before honouring
1168/// its sub-folder choice.
1169pub fn layer_for_type(type_: &str) -> Layer {
1170    layer_of_folder(&default_type_folder(type_)).unwrap_or(Layer::Records)
1171}
1172
1173/// The [`Layer`] a type-folder path lives in, read from its first component
1174/// (`sources/` → `Sources`, `records/` → `Records`). Used to
1175/// bound [`Store::find_by_type`]'s whole-layer sidecar read to a single layer
1176/// subtree. Returns `None` for a path with no recognized layer prefix; every
1177/// value [`default_type_folder`] produces has one, so in practice this is
1178/// always `Some` on the call path — `None` degrades to a store-wide read.
1179fn layer_of_folder(folder: &Path) -> Option<Layer> {
1180    let first = folder.components().next()?.as_os_str().to_str()?;
1181    Layer::from_dir_name(first)
1182}
1183
1184/// Infer a content file's canonical `type` from its store-relative path — the
1185/// inverse of [`default_type_folder`] and the single source of truth for
1186/// path→type inference (the CLI's `fm init` calls this, never re-derives it).
1187///
1188/// Requires the canonical `<layer>/<type-folder>/<file>` 3-component shape; a
1189/// shorter path (a file directly under a layer) or an unknown leading layer
1190/// yields `None`.
1191///
1192/// Recognized `(layer, folder)` pairs map back to their canonical type. For an
1193/// unrecognized folder the fallback is the **bare folder name verbatim** (no
1194/// pluralization/singularization) so it round-trips with `default_type_folder`,
1195/// whose unrecognized fallback is the bare type name (`task` ⇄ `records/task`).
1196/// Singularizing here would break that round-trip (`records/tasks` → `task`
1197/// while `default_type_folder("task")` → `records/task`). A conclusion record's
1198/// folder (e.g. `records/profiles/`) infers its bare folder name (`profiles`),
1199/// the same custom-type fallback as any other unrecognized folder.
1200pub fn infer_type_from_path(rel: &Path) -> Option<String> {
1201    let mut comps = rel.components().filter_map(|c| c.as_os_str().to_str());
1202    let layer = comps.next()?;
1203    if !matches!(layer, "sources" | "records") {
1204        return None;
1205    }
1206    let folder = comps.next()?;
1207    // The file itself must be a third component (a real type-folder, not the
1208    // file sitting directly under the layer).
1209    comps.next()?;
1210
1211    let mapped = match (layer, folder) {
1212        ("sources", "emails") => "email",
1213        ("sources", "transcripts") => "transcript",
1214        ("sources", "docs") => "pdf-source",
1215        ("sources", "notes") => "note",
1216        ("records", "contacts") => "contact",
1217        ("records", "companies") => "company",
1218        ("records", "expenses") => "expense",
1219        ("records", "meetings") => "meeting",
1220        ("records", "decisions") => "decision",
1221        ("records", "invoices") => "invoice",
1222        // Unrecognized folder: the bare name, verbatim. This is the inverse of
1223        // `default_type_folder`'s unrecognized fallback (`other → records/other`)
1224        // and the round-trip would break if we pluralized/singularized here.
1225        (_, other) => other,
1226    };
1227    Some(mapped.to_string())
1228}
1229
1230/// The primary date field name for a sharding type (the field whose value
1231/// drives `<YYYY>/<MM>`). `None` means "use the `created` fallback only".
1232fn primary_date_field(type_: &str) -> Option<&'static str> {
1233    match type_ {
1234        "email" => Some("date"),
1235        "transcript" => Some("recorded_at"),
1236        "pdf-source" => Some("received_at"),
1237        "note" => Some("told_at"),
1238        "expense" | "invoice" | "meeting" => Some("date"),
1239        // recognized custom event types have no canonical date field name; they
1240        // fall back to `created`.
1241        _ => None,
1242    }
1243}
1244
1245/// Parse a YAML value into an RFC3339 [`DateTime`], accepting both an explicit
1246/// string and a YAML-native scalar rendered to string.
1247fn value_to_datetime(value: &serde_norway::Value) -> Option<DateTime<FixedOffset>> {
1248    let s = yaml_scalar_string(value)?;
1249    DateTime::parse_from_rfc3339(s.trim()).ok()
1250}
1251
1252/// Extract `(YYYY, MM)` from a YAML date/timestamp value. Lenient: matches a
1253/// leading `YYYY-MM` so a bare `2026-05-22` date and a full
1254/// `2026-05-22T10:00:00-07:00` timestamp both work.
1255fn value_to_year_month(value: &serde_norway::Value) -> Option<(String, String)> {
1256    let s = yaml_scalar_string(value)?;
1257    year_month_from_str(s.trim())
1258}
1259
1260/// `(YYYY, MM)` from the leading `YYYY-MM` of a date string.
1261fn year_month_from_str(s: &str) -> Option<(String, String)> {
1262    // Hand-roll the leading-`YYYY-MM` parse to avoid a regex compile on the
1263    // write path. Require: 4 digits, '-', 2 digits.
1264    let bytes = s.as_bytes();
1265    if bytes.len() < 7 {
1266        return None;
1267    }
1268    let is_digit = |b: u8| b.is_ascii_digit();
1269    if !(is_digit(bytes[0])
1270        && is_digit(bytes[1])
1271        && is_digit(bytes[2])
1272        && is_digit(bytes[3])
1273        && bytes[4] == b'-'
1274        && is_digit(bytes[5])
1275        && is_digit(bytes[6]))
1276    {
1277        return None;
1278    }
1279    let month: u8 = (bytes[5] - b'0') * 10 + (bytes[6] - b'0');
1280    if !(1..=12).contains(&month) {
1281        return None;
1282    }
1283    Some((s[0..4].to_string(), s[5..7].to_string()))
1284}
1285
1286/// Render a YAML scalar as a string: a real `String` verbatim, otherwise the
1287/// value's compact YAML serialization (covers timestamps that the YAML engine
1288/// may surface as a non-string scalar).
1289fn yaml_scalar_string(value: &serde_norway::Value) -> Option<String> {
1290    if let Some(s) = value.as_str() {
1291        return Some(s.to_string());
1292    }
1293    match value {
1294        serde_norway::Value::Null => None,
1295        serde_norway::Value::Mapping(_) | serde_norway::Value::Sequence(_) => None,
1296        other => serde_norway::to_string(other)
1297            .ok()
1298            .map(|s| s.trim().to_string()),
1299    }
1300}
1301
1302/// The YAML frontmatter block of a file: the text between a leading `---` fence
1303/// and the next `---` fence, exclusive. `None` if the file does not open with a
1304/// `---` fence on its first line.
1305fn frontmatter_block(text: &str) -> Option<&str> {
1306    // Tolerate a UTF-8 BOM and CRLF, but the fence must be the very first line.
1307    let body = text.strip_prefix('\u{feff}').unwrap_or(text);
1308    let mut rest = body;
1309    // First line must be exactly `---` (allowing trailing CR).
1310    let (first, after_first) = split_first_line(rest);
1311    if first.trim_end_matches('\r') != "---" {
1312        return None;
1313    }
1314    rest = after_first;
1315    let block_start = rest;
1316    let mut scanned = 0usize;
1317    loop {
1318        let (line, after) = split_first_line(rest);
1319        if line.trim_end_matches('\r') == "---" {
1320            return Some(&block_start[..scanned]);
1321        }
1322        if after.is_empty() && line.is_empty() {
1323            // Reached end of input without a closing fence.
1324            return None;
1325        }
1326        scanned += line.len() + 1; // +1 for the consumed '\n'
1327        if after.is_empty() {
1328            return None;
1329        }
1330        rest = after;
1331    }
1332}
1333
1334/// Split a string into (first line without its trailing `\n`, remainder after
1335/// the `\n`). If there is no newline, the whole string is the line and the
1336/// remainder is empty.
1337fn split_first_line(s: &str) -> (&str, &str) {
1338    match s.find('\n') {
1339        Some(i) => (&s[..i], &s[i + 1..]),
1340        None => (s, ""),
1341    }
1342}
1343
1344/// True if an [`IndexRecord`] has a field `key` equal to `value`, checking the
1345/// typed columns first and then the flattened `fields` map.
1346fn record_matches_field(record: &IndexRecord, key: &str, value: &str) -> bool {
1347    match key {
1348        "type" => record.type_ == value,
1349        "summary" => record.summary == value,
1350        "path" => record.path.to_string_lossy() == value,
1351        "created" => timestamp_matches(record.created, value),
1352        "updated" => timestamp_matches(record.updated, value),
1353        "tags" => record.tags.iter().any(|t| t == value),
1354        "links" => record.links.iter().any(|l| l == value),
1355        other => record
1356            .fields
1357            .get(other)
1358            .map(|v| json_value_matches(v, value))
1359            .unwrap_or(false),
1360    }
1361}
1362
1363/// Compare a record's `created`/`updated` instant against a query `value`.
1364///
1365/// db.md files write timestamps in several equivalent RFC3339 spellings — most
1366/// commonly the `Z` UTC designator (`2026-05-01T00:00:00Z`) but also an explicit
1367/// offset (`...+00:00`, `...-07:00`). A naive `record.created.to_rfc3339() ==
1368/// value` reformats only one side: chrono renders a UTC instant as `+00:00`, so
1369/// the `Z` form an agent reads straight out of the file would never match. We
1370/// instead parse `value` as RFC3339 and compare instants, where `Z` and `+00:00`
1371/// (and any same-instant offset) are equal. A `value` that is not valid RFC3339
1372/// can never equal a real timestamp, so it falls through to `false`.
1373fn timestamp_matches(stored: Option<DateTime<FixedOffset>>, value: &str) -> bool {
1374    match (stored, DateTime::parse_from_rfc3339(value)) {
1375        (Some(stored), Ok(queried)) => stored == queried,
1376        _ => false,
1377    }
1378}
1379
1380/// Compare a JSON field value against a query string. A string matches
1381/// verbatim; scalars match their textual form; an array matches if any element
1382/// matches (so a list-valued frontmatter field is membership-queried).
1383fn json_value_matches(v: &serde_json::Value, value: &str) -> bool {
1384    match v {
1385        serde_json::Value::String(s) => s == value,
1386        serde_json::Value::Bool(b) => b.to_string() == value,
1387        serde_json::Value::Number(n) => n.to_string() == value,
1388        serde_json::Value::Array(items) => items.iter().any(|i| json_value_matches(i, value)),
1389        // A present-but-null field never matches — consistent with the in-memory
1390        // post-filter (`query::json_value_matches`, which the first `where`
1391        // clause is NOT re-checked against, so the two must agree here or a
1392        // `--where field=` query would return different rows than `--type X
1393        // --where field=`).
1394        serde_json::Value::Null => false,
1395        serde_json::Value::Object(_) => false,
1396    }
1397}
1398
1399#[cfg(test)]
1400mod tests {
1401    use super::*;
1402    use std::fs;
1403    use tempfile::{tempdir, TempDir};
1404
1405    // ── Fixtures ────────────────────────────────────────────────────────────
1406
1407    /// Write `contents` to `<root>/<rel>`, creating parent dirs. Returns the
1408    /// store-relative path for convenient assertions.
1409    fn write(root: &Path, rel: &str, contents: &str) -> PathBuf {
1410        let abs = root.join(rel);
1411        fs::create_dir_all(abs.parent().unwrap()).unwrap();
1412        fs::write(&abs, contents).unwrap();
1413        PathBuf::from(rel)
1414    }
1415
1416    /// A minimal content file with the given `updated` timestamp in frontmatter.
1417    fn content_md(updated: &str) -> String {
1418        format!(
1419            "---\ntype: note\ncreated: {updated}\nupdated: {updated}\nsummary: a note\n---\n\nbody\n"
1420        )
1421    }
1422
1423    /// A bare directory with a `DB.md` marker (valid `db-md` frontmatter so the
1424    /// real parser is exercised).
1425    fn empty_store() -> TempDir {
1426        let dir = tempdir().unwrap();
1427        fs::write(
1428            dir.path().join("DB.md"),
1429            "---\ntype: db-md\nscope: company\nowner: Test\n---\n\n# Store\n",
1430        )
1431        .unwrap();
1432        dir
1433    }
1434
1435    /// Open a store rooted at a TempDir; panics if `open` rejects it.
1436    fn open(dir: &TempDir) -> Store {
1437        Store::open(dir.path()).expect("fixture should be a valid store")
1438    }
1439
1440    fn rels(paths: &[PathBuf]) -> Vec<String> {
1441        paths
1442            .iter()
1443            .map(|p| p.to_string_lossy().replace('\\', "/"))
1444            .collect()
1445    }
1446
1447    // ── Layer ───────────────────────────────────────────────────────────────
1448
1449    #[test]
1450    fn layer_dir_name_and_parse_are_inverse() {
1451        for layer in Layer::all() {
1452            assert_eq!(Layer::from_dir_name(layer.dir_name()), Some(layer));
1453        }
1454        assert_eq!(Layer::Sources.dir_name(), "sources");
1455        assert_eq!(Layer::Records.dir_name(), "records");
1456        // `wiki` is no longer a layer (the wiki/ layer was removed); it parses to None.
1457        assert_eq!(Layer::from_dir_name("wiki"), None);
1458        assert_eq!(Layer::from_dir_name("log"), None);
1459        assert_eq!(Layer::from_dir_name("Sources"), None); // case-sensitive
1460    }
1461
1462    #[test]
1463    fn layer_order_is_canonical() {
1464        // stats keys a BTreeMap on Layer; the sort order must be sources<records.
1465        let mut v = [Layer::Records, Layer::Sources];
1466        v.sort();
1467        assert_eq!(v, [Layer::Sources, Layer::Records]);
1468    }
1469
1470    // ── is_db_md_store / open ────────────────────────────────────────────────
1471
1472    #[test]
1473    fn is_store_true_only_with_uppercase_marker() {
1474        let dir = tempdir().unwrap();
1475        assert!(
1476            !Store::is_db_md_store(dir.path()),
1477            "no marker → not a store"
1478        );
1479
1480        fs::write(dir.path().join("DB.md"), "---\ntype: db-md\n---\n").unwrap();
1481        assert!(Store::is_db_md_store(dir.path()), "uppercase DB.md → store");
1482    }
1483
1484    #[test]
1485    fn is_store_false_for_lowercase_db_md() {
1486        // The case-sensitivity contract: a lowercase db.md is the spec name, not
1487        // a marker — even on a case-insensitive filesystem where Path::exists
1488        // would lie. This test must pass on macOS (case-insensitive) too.
1489        let dir = tempdir().unwrap();
1490        fs::write(dir.path().join("db.md"), "---\ntype: db-md\n---\n").unwrap();
1491        assert!(
1492            !Store::is_db_md_store(dir.path()),
1493            "lowercase db.md must NOT be treated as a store marker"
1494        );
1495        assert!(Store::open(dir.path()).is_err());
1496    }
1497
1498    #[test]
1499    fn is_store_false_when_db_md_is_a_directory() {
1500        let dir = tempdir().unwrap();
1501        fs::create_dir(dir.path().join("DB.md")).unwrap();
1502        assert!(
1503            !Store::is_db_md_store(dir.path()),
1504            "a directory named DB.md is not the file marker"
1505        );
1506    }
1507
1508    #[test]
1509    fn open_rejects_non_store_with_path() {
1510        let dir = tempdir().unwrap();
1511        let err = Store::open(dir.path()).unwrap_err();
1512        assert_eq!(err.path, dir.path());
1513    }
1514
1515    #[test]
1516    fn open_succeeds_and_parses_config() {
1517        let dir = tempdir().unwrap();
1518        // A DB.md whose ## Policies declares a frozen page — proves open()
1519        // actually parsed the config rather than substituting a default.
1520        fs::write(
1521            dir.path().join("DB.md"),
1522            "---\ntype: db-md\nscope: company\nowner: Test\n---\n\n# Store\n\n\
1523             ## Policies\n\n### Frozen pages\n- records/decisions/q1.md\n",
1524        )
1525        .unwrap();
1526        let store = Store::open(dir.path()).unwrap();
1527        assert_eq!(store.root, dir.path());
1528        assert!(
1529            store
1530                .config
1531                .frozen_pages
1532                .iter()
1533                .any(|p| p == Path::new("records/decisions/q1.md")),
1534            "open() must surface DB.md ## Policies, got {:?}",
1535            store.config.frozen_pages
1536        );
1537    }
1538
1539    // ── walk / walk_layer / walk_type_folder ─────────────────────────────────
1540
1541    #[test]
1542    fn walk_collects_content_across_layers_skipping_meta_and_log() {
1543        let dir = empty_store();
1544        let root = dir.path();
1545        write(
1546            root,
1547            "sources/emails/2026/05/a.md",
1548            &content_md("2026-05-01T00:00:00Z"),
1549        );
1550        write(
1551            root,
1552            "records/contacts/sarah.md",
1553            &content_md("2026-05-02T00:00:00Z"),
1554        );
1555        write(
1556            root,
1557            "records/profiles/sarah.md",
1558            &content_md("2026-05-03T00:00:00Z"),
1559        );
1560        // Things walk() must SKIP:
1561        write(root, "sources/emails/index.md", "---\ntype: index\n---\n"); // catalog
1562        write(root, "index.md", "---\ntype: index\n---\n"); // root catalog
1563        write(root, "log.md", "---\ntype: log\n---\n"); // log
1564        write(root, "log/2026-04.md", "---\ntype: log\n---\n"); // rotated log archive
1565        write(
1566            root,
1567            "sources/.hidden/secret.md",
1568            &content_md("2026-05-09T00:00:00Z"),
1569        ); // hidden dir
1570        write(root, "records/contacts/notes.txt", "not markdown"); // non-md
1571
1572        let store = open(&dir);
1573        let got = rels(&store.walk().unwrap());
1574        assert_eq!(
1575            got,
1576            vec![
1577                "records/contacts/sarah.md".to_string(),
1578                "records/profiles/sarah.md".to_string(),
1579                "sources/emails/2026/05/a.md".to_string(),
1580            ]
1581        );
1582    }
1583
1584    #[test]
1585    fn walk_includes_content_named_log_md_or_db_md_inside_a_layer() {
1586        let dir = empty_store();
1587        let root = dir.path();
1588        // A content file that merely happens to be named log.md / DB.md INSIDE a
1589        // layer is real content — those names are reserved only at the store root.
1590        write(
1591            root,
1592            "records/configs/log.md",
1593            &content_md("2026-05-01T00:00:00Z"),
1594        );
1595        write(
1596            root,
1597            "sources/docs/DB.md",
1598            &content_md("2026-05-02T00:00:00Z"),
1599        );
1600        // The derived catalog twin is still skipped at any depth.
1601        write(root, "records/configs/index.md", "---\ntype: index\n---\n");
1602        let store = open(&dir);
1603        let got = rels(&store.walk().unwrap());
1604        assert!(
1605            got.contains(&"records/configs/log.md".to_string()),
1606            "layer-internal log.md is content: {got:?}"
1607        );
1608        assert!(
1609            got.contains(&"sources/docs/DB.md".to_string()),
1610            "layer-internal DB.md is content: {got:?}"
1611        );
1612        assert!(
1613            !got.iter().any(|p| p.ends_with("index.md")),
1614            "index.md is still skipped: {got:?}"
1615        );
1616    }
1617
1618    #[test]
1619    fn walk_layer_is_scoped() {
1620        let dir = empty_store();
1621        let root = dir.path();
1622        write(
1623            root,
1624            "sources/emails/2026/05/a.md",
1625            &content_md("2026-05-01T00:00:00Z"),
1626        );
1627        write(
1628            root,
1629            "records/contacts/sarah.md",
1630            &content_md("2026-05-02T00:00:00Z"),
1631        );
1632        let store = open(&dir);
1633
1634        assert_eq!(
1635            rels(&store.walk_layer(Layer::Sources).unwrap()),
1636            vec!["sources/emails/2026/05/a.md".to_string()]
1637        );
1638        assert_eq!(
1639            rels(&store.walk_layer(Layer::Records).unwrap()),
1640            vec!["records/contacts/sarah.md".to_string()]
1641        );
1642        // A layer with no directory is empty, not an error: a store with only a
1643        // sources/ tree has no records/ dir, so walking Records is empty.
1644        let only_sources = empty_store();
1645        write(
1646            only_sources.path(),
1647            "sources/emails/2026/05/a.md",
1648            &content_md("2026-05-01T00:00:00Z"),
1649        );
1650        let s2 = open(&only_sources);
1651        assert!(s2.walk_layer(Layer::Records).unwrap().is_empty());
1652    }
1653
1654    #[test]
1655    fn walk_type_folder_recurses_shards_and_accepts_abs_or_rel() {
1656        let dir = empty_store();
1657        let root = dir.path();
1658        write(
1659            root,
1660            "sources/emails/2026/05/a.md",
1661            &content_md("2026-05-01T00:00:00Z"),
1662        );
1663        write(
1664            root,
1665            "sources/emails/2026/06/b.md",
1666            &content_md("2026-06-01T00:00:00Z"),
1667        );
1668        write(root, "sources/emails/index.md", "---\ntype: index\n---\n"); // skipped
1669                                                                           // A different type folder must not leak in.
1670        write(
1671            root,
1672            "sources/docs/2026/05/c.md",
1673            &content_md("2026-05-04T00:00:00Z"),
1674        );
1675        let store = open(&dir);
1676
1677        let expected = vec![
1678            "sources/emails/2026/05/a.md".to_string(),
1679            "sources/emails/2026/06/b.md".to_string(),
1680        ];
1681        // Relative folder arg.
1682        assert_eq!(
1683            rels(&store.walk_type_folder(Path::new("sources/emails")).unwrap()),
1684            expected
1685        );
1686        // Absolute folder arg under the store resolves identically.
1687        assert_eq!(
1688            rels(
1689                &store
1690                    .walk_type_folder(&root.join("sources/emails"))
1691                    .unwrap()
1692            ),
1693            expected
1694        );
1695    }
1696
1697    // ── recent_in_type_folder ────────────────────────────────────────────────
1698
1699    #[test]
1700    fn recent_orders_by_updated_desc_then_path_and_caps() {
1701        let dir = empty_store();
1702        let root = dir.path();
1703        // newest
1704        write(
1705            root,
1706            "records/meetings/2026/05/c.md",
1707            &content_md("2026-05-03T00:00:00Z"),
1708        );
1709        // tie on updated — path asc decides (a before b)
1710        write(
1711            root,
1712            "records/meetings/2026/05/a.md",
1713            &content_md("2026-05-02T00:00:00Z"),
1714        );
1715        write(
1716            root,
1717            "records/meetings/2026/05/b.md",
1718            &content_md("2026-05-02T00:00:00Z"),
1719        );
1720        // oldest
1721        write(
1722            root,
1723            "records/meetings/2026/04/z.md",
1724            &content_md("2026-04-01T00:00:00Z"),
1725        );
1726        let store = open(&dir);
1727
1728        let all = rels(
1729            &store
1730                .recent_in_type_folder(Path::new("records/meetings"), 10)
1731                .unwrap(),
1732        );
1733        assert_eq!(
1734            all,
1735            vec![
1736                "records/meetings/2026/05/c.md".to_string(), // newest
1737                "records/meetings/2026/05/a.md".to_string(), // tie, path asc
1738                "records/meetings/2026/05/b.md".to_string(),
1739                "records/meetings/2026/04/z.md".to_string(), // oldest
1740            ]
1741        );
1742
1743        // Cap takes the n most-recent.
1744        let top2 = rels(
1745            &store
1746                .recent_in_type_folder(Path::new("records/meetings"), 2)
1747                .unwrap(),
1748        );
1749        assert_eq!(
1750            top2,
1751            vec![
1752                "records/meetings/2026/05/c.md".to_string(),
1753                "records/meetings/2026/05/a.md".to_string(),
1754            ]
1755        );
1756    }
1757
1758    #[test]
1759    fn recent_sorts_undated_files_last() {
1760        let dir = empty_store();
1761        let root = dir.path();
1762        write(
1763            root,
1764            "records/contacts/dated.md",
1765            &content_md("2026-05-01T00:00:00Z"),
1766        );
1767        // No `updated` field at all.
1768        write(
1769            root,
1770            "records/contacts/undated.md",
1771            "---\ntype: contact\nsummary: x\n---\nbody\n",
1772        );
1773        let store = open(&dir);
1774        let got = rels(
1775            &store
1776                .recent_in_type_folder(Path::new("records/contacts"), 10)
1777                .unwrap(),
1778        );
1779        assert_eq!(
1780            got,
1781            vec![
1782                "records/contacts/dated.md".to_string(),
1783                "records/contacts/undated.md".to_string(),
1784            ],
1785            "a file with a real `updated` must outrank one with none"
1786        );
1787    }
1788
1789    // ── type_shards ──────────────────────────────────────────────────────────
1790
1791    #[test]
1792    fn type_shards_classification() {
1793        let dir = empty_store();
1794        let store = open(&dir);
1795        for t in [
1796            "email",
1797            "transcript",
1798            "pdf-source",
1799            "expense",
1800            "invoice",
1801            "meeting",
1802            "order",
1803            "ticket",
1804            "transaction",
1805        ] {
1806            assert!(store.type_shards(t), "{t} should shard");
1807        }
1808        for t in [
1809            "contact", "company", "decision", "profile", "index", "log", "db-md", "proposal",
1810        ] {
1811            assert!(!store.type_shards(t), "{t} should stay flat");
1812        }
1813    }
1814
1815    #[test]
1816    fn type_shards_respects_schema_directive_both_directions() {
1817        use crate::parser::{Config, Schema};
1818        let dir = empty_store();
1819        let mut store = open(&dir);
1820        let mut config = Config::default();
1821        // A CUSTOM type (not in the built-in list) opts into date-sharding —
1822        // without the schema override `type_shards` would return false for it.
1823        config.schemas.insert(
1824            "shipment".to_string(),
1825            Schema {
1826                shard: Some(true),
1827                ..Schema::default()
1828            },
1829        );
1830        // A BUILT-IN event type opts OUT (flat) — the override wins over the
1831        // built-in default.
1832        config.schemas.insert(
1833            "expense".to_string(),
1834            Schema {
1835                shard: Some(false),
1836                ..Schema::default()
1837            },
1838        );
1839        // A schema with no `shard:` directive leaves the built-in default intact.
1840        config
1841            .schemas
1842            .insert("meeting".to_string(), Schema::default());
1843        store.config = config;
1844
1845        assert!(
1846            store.type_shards("shipment"),
1847            "custom type with `shard: by-date` must shard"
1848        );
1849        assert!(
1850            !store.type_shards("expense"),
1851            "built-in event type with `shard: flat` must go flat"
1852        );
1853        assert!(
1854            store.type_shards("meeting"),
1855            "schema without a `shard:` directive keeps the built-in default"
1856        );
1857        assert!(
1858            !store.type_shards("contact"),
1859            "unconfigured entity type stays flat"
1860        );
1861    }
1862
1863    // ── shard_path_for ───────────────────────────────────────────────────────
1864
1865    fn fm_with_extra(key: &str, value: &str) -> Frontmatter {
1866        let mut fm = Frontmatter::default();
1867        fm.extra.insert(
1868            key.to_string(),
1869            serde_norway::Value::String(value.to_string()),
1870        );
1871        fm
1872    }
1873
1874    fn fm_with_created(rfc3339: &str) -> Frontmatter {
1875        Frontmatter {
1876            created: Some(DateTime::parse_from_rfc3339(rfc3339).unwrap()),
1877            ..Default::default()
1878        }
1879    }
1880
1881    #[test]
1882    fn shard_path_uses_primary_date_field_per_type() {
1883        let dir = empty_store();
1884        let store = open(&dir);
1885
1886        // expense.date → records/expenses/<YYYY>/<MM>/
1887        let p = store
1888            .shard_path_for("expense", &fm_with_extra("date", "2026-05-22"), "lunch")
1889            .unwrap();
1890        assert_eq!(p, PathBuf::from("records/expenses/2026/05/lunch.md"));
1891
1892        // email.date → sources/emails/<YYYY>/<MM>/
1893        let p = store
1894            .shard_path_for(
1895                "email",
1896                &fm_with_extra("date", "2026-11-02T09:00:00-07:00"),
1897                "e1",
1898            )
1899            .unwrap();
1900        assert_eq!(p, PathBuf::from("sources/emails/2026/11/e1.md"));
1901
1902        // transcript.recorded_at → sources/transcripts/<YYYY>/<MM>/
1903        let p = store
1904            .shard_path_for(
1905                "transcript",
1906                &fm_with_extra("recorded_at", "2025-01-15T12:00:00Z"),
1907                "t1",
1908            )
1909            .unwrap();
1910        assert_eq!(p, PathBuf::from("sources/transcripts/2025/01/t1.md"));
1911    }
1912
1913    #[test]
1914    fn shard_path_falls_back_to_created() {
1915        let dir = empty_store();
1916        let store = open(&dir);
1917        // meeting with no `date` field but a `created` timestamp.
1918        let p = store
1919            .shard_path_for(
1920                "meeting",
1921                &fm_with_created("2024-07-09T08:30:00-04:00"),
1922                "sync",
1923            )
1924            .unwrap();
1925        assert_eq!(p, PathBuf::from("records/meetings/2024/07/sync.md"));
1926    }
1927
1928    #[test]
1929    fn shard_path_primary_field_wins_over_created() {
1930        let dir = empty_store();
1931        let store = open(&dir);
1932        let mut fm = fm_with_created("2020-01-01T00:00:00Z");
1933        fm.extra.insert(
1934            "date".into(),
1935            serde_norway::Value::String("2026-05-22".into()),
1936        );
1937        let p = store.shard_path_for("expense", &fm, "x").unwrap();
1938        // The primary `date` (2026/05), not `created` (2020/01), drives the shard.
1939        assert_eq!(p, PathBuf::from("records/expenses/2026/05/x.md"));
1940    }
1941
1942    #[test]
1943    fn shard_path_flat_types_have_no_shard_segment() {
1944        let dir = empty_store();
1945        let store = open(&dir);
1946        // A contact has a `created` date, but contacts stay flat.
1947        let p = store
1948            .shard_path_for(
1949                "contact",
1950                &fm_with_created("2026-05-22T00:00:00Z"),
1951                "sarah-chen",
1952            )
1953            .unwrap();
1954        assert_eq!(p, PathBuf::from("records/contacts/sarah-chen.md"));
1955
1956        // A conclusion `profile` is a custom (non-built-in) type: it is flat (no
1957        // date shard) and lands under the records-layer fallback folder
1958        // `records/<type>` — `records/profile/<name>.md`, a conforming 3-component
1959        // `<layer>/<type-folder>/<file>` path. A 2-component path would be
1960        // invisible to the index/validate type-folder model.
1961        let p = store
1962            .shard_path_for("profile", &Frontmatter::default(), "renewal-theme")
1963            .unwrap();
1964        assert_eq!(p, PathBuf::from("records/profile/renewal-theme.md"));
1965    }
1966
1967    /// Regression: a type written through the toolkit's own path computation
1968    /// must land at a path the index + validate type-folder model accepts. A
1969    /// 2-component `<layer>/<file>` path is one `type_folder_of` (in both `index`
1970    /// and `validate`) treats as "no type-folder" — it would either crash
1971    /// `Index::on_write` (it tried to create `index.md` inside a file) or be
1972    /// silently dropped from every catalog by `Index::rebuild_all`. A custom
1973    /// (non-built-in) type like a conclusion `profile` falls back to
1974    /// `records/<type>` — still a conforming 3-component
1975    /// `<layer>/<type-folder>/<file>` path.
1976    #[test]
1977    fn shard_path_custom_type_is_indexable_three_component_path() {
1978        let dir = empty_store();
1979        let store = open(&dir);
1980        let p = store
1981            .shard_path_for("profile", &Frontmatter::default(), "renewal-theme")
1982            .unwrap();
1983        // First two components are a layer + a non-empty type-folder segment;
1984        // the file is the third. This is exactly the shape `type_folder_of`
1985        // (`comps.len() >= 3`, `comps[0]` a known layer) requires.
1986        let comps: Vec<&str> = p.iter().filter_map(|c| c.to_str()).collect();
1987        assert_eq!(
1988            comps.len(),
1989            3,
1990            "custom-type path must be <layer>/<type-folder>/<file>, got {p:?}"
1991        );
1992        assert_eq!(
1993            comps[0], "records",
1994            "first component must be the records layer (a custom type is \
1995             filed under the records fallback)"
1996        );
1997        assert!(
1998            !comps[1].is_empty() && comps[1] != "renewal-theme.md",
1999            "second component must be a real type-folder, not the file: {p:?}"
2000        );
2001        assert!(
2002            comps[2].ends_with(".md"),
2003            "third component must be the .md file: {p:?}"
2004        );
2005    }
2006
2007    #[test]
2008    fn shard_path_preserves_and_adds_md_extension() {
2009        let dir = empty_store();
2010        let store = open(&dir);
2011        let with = store
2012            .shard_path_for("contact", &Frontmatter::default(), "sarah.md")
2013            .unwrap();
2014        let without = store
2015            .shard_path_for("contact", &Frontmatter::default(), "sarah")
2016            .unwrap();
2017        assert_eq!(with, PathBuf::from("records/contacts/sarah.md"));
2018        assert_eq!(without, PathBuf::from("records/contacts/sarah.md"));
2019    }
2020
2021    #[test]
2022    fn shard_path_errors_when_sharding_type_has_no_date() {
2023        let dir = empty_store();
2024        let store = open(&dir);
2025        // expense shards, but no `date` and no `created` → NoShardDate.
2026        let err = store
2027            .shard_path_for("expense", &Frontmatter::default(), "mystery")
2028            .unwrap_err();
2029        match err {
2030            StoreError::NoShardDate { file } => {
2031                assert_eq!(file, PathBuf::from("records/expenses/mystery.md"));
2032            }
2033            other => panic!("expected NoShardDate, got {other:?}"),
2034        }
2035    }
2036
2037    // ── find_links_to ────────────────────────────────────────────────────────
2038
2039    #[test]
2040    fn find_links_to_matches_all_accepted_spellings() {
2041        let dir = empty_store();
2042        let root = dir.path();
2043        let target = "records/contacts/sarah-chen";
2044
2045        // Plain link.
2046        write(
2047            root,
2048            "records/profiles/sarah.md",
2049            &format!(
2050                "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[{target}]].\n"
2051            ),
2052        );
2053        // Link with display text.
2054        write(
2055            root,
2056            "records/meetings/2026/05/m.md",
2057            &format!("---\ntype: meeting\nsummary: s\n---\nWith [[{target}|Sarah]].\n"),
2058        );
2059        // Link with .md extension (accepted, warned by validate).
2060        write(
2061            root,
2062            "records/concepts/t.md",
2063            &format!(
2064                "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[{target}.md]]\n"
2065            ),
2066        );
2067        // A catalog/index file also contains the link literally — included.
2068        write(
2069            root,
2070            "records/contacts/index.md",
2071            &format!("---\ntype: index\n---\n- [[{target}]] — Sarah\n"),
2072        );
2073        // No link to the target.
2074        write(
2075            root,
2076            "records/profiles/elena.md",
2077            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nNo links here.\n",
2078        );
2079        // Short-form link must NOT match the full-path target.
2080        write(
2081            root,
2082            "records/profiles/bob.md",
2083            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\n[[sarah-chen]]\n",
2084        );
2085        // A longer path that merely starts with the target must NOT match
2086        // (boundary correctness): target `sarah-chen` vs `sarah-chen-jr`.
2087        write(
2088            root,
2089            "records/profiles/jr.md",
2090            &format!(
2091                "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\n[[{target}-jr]]\n"
2092            ),
2093        );
2094
2095        let store = open(&dir);
2096        let got = rels(&store.find_links_to(Path::new(target)).unwrap());
2097        assert_eq!(
2098            got,
2099            vec![
2100                "records/concepts/t.md".to_string(),
2101                "records/contacts/index.md".to_string(),
2102                "records/meetings/2026/05/m.md".to_string(),
2103                "records/profiles/sarah.md".to_string(),
2104            ]
2105        );
2106    }
2107
2108    #[test]
2109    fn find_links_to_distinguishes_sibling_paths() {
2110        // Two contacts whose paths share a prefix; a link to one must not be
2111        // reported as a link to the other.
2112        let dir = empty_store();
2113        let root = dir.path();
2114        write(
2115            root,
2116            "records/concepts/a.md",
2117            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah]]\n",
2118        );
2119        write(
2120            root,
2121            "records/concepts/b.md",
2122            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
2123        );
2124        let store = open(&dir);
2125
2126        assert_eq!(
2127            rels(
2128                &store
2129                    .find_links_to(Path::new("records/contacts/sarah"))
2130                    .unwrap()
2131            ),
2132            vec!["records/concepts/a.md".to_string()]
2133        );
2134        assert_eq!(
2135            rels(
2136                &store
2137                    .find_links_to(Path::new("records/contacts/sarah-chen"))
2138                    .unwrap()
2139            ),
2140            vec!["records/concepts/b.md".to_string()]
2141        );
2142    }
2143
2144    #[test]
2145    fn regression_find_links_to_tolerates_invalid_utf8_on_a_matched_line() {
2146        // Regression: a `.md` file can carry a stray non-UTF-8 byte on the SAME
2147        // line as a `[[target]]` link (a verbatim-ingested `sources/` artifact,
2148        // e.g. a mis-decoded Latin-1 import). The scan must still report the
2149        // link — `find_links_to` / `find_links_to_any` (and `graph backlinks` +
2150        // the working-set validate incoming-linker pass) must not error out and
2151        // drop the legitimate UTF-8 linkers. The content scan reads the file
2152        // with `String::from_utf8_lossy`, so the invalid byte becomes a
2153        // replacement char and the ASCII `[[target]]` link is still extracted.
2154        let dir = empty_store();
2155        let root = dir.path();
2156        let target = "records/contacts/sarah-chen";
2157
2158        // A clean, fully-UTF-8 linker that MUST be returned regardless.
2159        write(
2160            root,
2161            "records/profiles/clean.md",
2162            &format!(
2163                "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[{target}]].\n"
2164            ),
2165        );
2166
2167        // A linker whose link line ALSO carries a stray 0xFF byte (a mis-decoded
2168        // Latin-1 import). Write raw bytes so the invalid byte survives — a
2169        // `&str` fixture could not express it. The byte-level regex still
2170        // matches `[[target]]` on this line; pre-fix the UTF8 sink aborted here.
2171        let mut bytes: Vec<u8> =
2172            b"---\ntype: email\nsummary: s\n---\nSee [[records/contacts/sarah-chen]] \xFF here\n"
2173                .to_vec();
2174        let dirty_abs = root.join("sources/emails/2026/05/raw.md");
2175        fs::create_dir_all(dirty_abs.parent().unwrap()).unwrap();
2176        fs::write(&dirty_abs, &bytes).unwrap();
2177        // Defensive: confirm the fixture really is invalid UTF-8 (so the test
2178        // exercises the bug, not a coincidentally-valid file).
2179        assert!(
2180            std::str::from_utf8(&bytes).is_err(),
2181            "fixture must contain invalid UTF-8 to exercise the regression"
2182        );
2183        bytes.clear();
2184
2185        let store = open(&dir);
2186        let got = rels(
2187            &store
2188                .find_links_to(Path::new(target))
2189                .expect("a stray non-UTF-8 byte must not abort the backlink scan"),
2190        );
2191        assert_eq!(
2192            got,
2193            vec![
2194                "records/profiles/clean.md".to_string(),
2195                "sources/emails/2026/05/raw.md".to_string(),
2196            ],
2197            "both the clean linker and the one with an invalid byte on the link \
2198             line are reported; the scan degrades, it does not fail"
2199        );
2200    }
2201
2202    // ── find_links_to_any (batch — the O(changed × store) fix) ─────────────────
2203
2204    /// The working-set validate's incoming-linker discovery runs through
2205    /// `find_links_to_any` over the WHOLE changed set in one pass. This pins the
2206    /// batch contract that makes that single-pass behavior correct: the result is
2207    /// the union of incoming linkers across every target, with per-target
2208    /// boundary correctness preserved (no alternation arm bleeds into a
2209    /// prefix-sharing sibling). If a regression reverts the batch finder to a
2210    /// per-object loop, the union below would still hold — but the boundary +
2211    /// union-equivalence assertions are what guard the *correctness* of folding N
2212    /// scans into one regex.
2213    #[test]
2214    fn find_links_to_any_returns_the_union_with_boundary_correctness() {
2215        let dir = empty_store();
2216        let root = dir.path();
2217
2218        // Two distinct targets, each with its own linker.
2219        write(
2220            root,
2221            "records/concepts/links-sarah.md",
2222            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
2223        );
2224        write(
2225            root,
2226            "records/concepts/links-acme.md",
2227            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\nDeal with [[records/companies/acme|Acme]].\n",
2228        );
2229        // One file links to BOTH targets — must appear exactly once (deduped),
2230        // proving the per-file early-exit folds multiple-target hits into a
2231        // single result row rather than one row per matched target.
2232        write(
2233            root,
2234            "records/meetings/2026/05/m.md",
2235            "---\ntype: meeting\nsummary: s\n---\n[[records/contacts/sarah-chen]] re \
2236             [[records/companies/acme]]\n",
2237        );
2238        // A prefix-sharing sibling of a target: a link to `sarah-chen-jr` must NOT
2239        // be reported as a link to `sarah-chen` even though the alternation now
2240        // carries `sarah-chen` as one arm.
2241        write(
2242            root,
2243            "records/concepts/links-jr.md",
2244            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen-jr]]\n",
2245        );
2246        // A file that links to neither requested target.
2247        write(
2248            root,
2249            "records/concepts/unrelated.md",
2250            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/concepts/spend]]\n",
2251        );
2252
2253        let store = open(&dir);
2254        let targets = vec![
2255            PathBuf::from("records/contacts/sarah-chen"),
2256            PathBuf::from("records/companies/acme"),
2257        ];
2258
2259        let got = rels(&store.find_links_to_any(&targets).unwrap());
2260        assert_eq!(
2261            got,
2262            vec![
2263                "records/concepts/links-acme.md".to_string(),
2264                "records/concepts/links-sarah.md".to_string(),
2265                "records/meetings/2026/05/m.md".to_string(),
2266            ],
2267            "batch finder must return the deduped union of linkers across all \
2268             targets, excluding the prefix-sibling and the unrelated file"
2269        );
2270
2271        // Equivalence: the batch result must equal the union of the per-target
2272        // single finder. This is the property the working-set path relies on
2273        // when it folds one-scan-per-object into one scan for the whole set.
2274        let mut union: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
2275        for t in &targets {
2276            for linker in store.find_links_to(t).unwrap() {
2277                union.insert(linker);
2278            }
2279        }
2280        assert_eq!(
2281            rels(&union.into_iter().collect::<Vec<_>>()),
2282            got,
2283            "find_links_to_any must equal the union of per-target find_links_to"
2284        );
2285    }
2286
2287    /// An empty target set must scan nothing and find nothing — and crucially
2288    /// must NOT compile to a match-everything empty regex (which would report
2289    /// every `.md` as a linker). This is the empty-working-set fast path the
2290    /// `validate` loop hits when nothing changed.
2291    #[test]
2292    fn find_links_to_any_empty_targets_matches_nothing() {
2293        let dir = empty_store();
2294        let root = dir.path();
2295        write(
2296            root,
2297            "records/concepts/a.md",
2298            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
2299        );
2300        let store = open(&dir);
2301
2302        assert!(
2303            store.find_links_to_any(&[]).unwrap().is_empty(),
2304            "no targets ⇒ no linkers (an empty pattern must not match every file)"
2305        );
2306        // A set of only empty/non-link targets is likewise a no-op, not a
2307        // match-everything.
2308        assert!(
2309            store
2310                .find_links_to_any(&[PathBuf::from(""), PathBuf::from("./")])
2311                .unwrap()
2312                .is_empty(),
2313            "targets that render to empty link text contribute no alternation arm"
2314        );
2315    }
2316
2317    // ── read_type_index ──────────────────────────────────────────────────────
2318
2319    #[test]
2320    fn read_type_index_parses_records_and_flattens_fields() {
2321        let dir = empty_store();
2322        let root = dir.path();
2323        let jsonl = "\
2324{\"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}
2325{\"path\":\"records/expenses/2026/05/b.md\",\"type\":\"expense\",\"summary\":\"taxi\",\"created\":null,\"updated\":null,\"vendor\":\"yellow\"}
2326";
2327        let p = write(root, "records/expenses/index.jsonl", jsonl);
2328        let store = open(&dir);
2329        let recs = store.read_type_index(&store.abs_path(&p)).unwrap();
2330
2331        assert_eq!(recs.len(), 2);
2332        // Sorted by path asc.
2333        assert_eq!(recs[0].path, PathBuf::from("records/expenses/2026/05/a.md"));
2334        assert_eq!(recs[0].type_, "expense");
2335        assert_eq!(recs[0].summary, "lunch");
2336        assert_eq!(recs[0].tags, vec!["meals".to_string()]);
2337        assert_eq!(recs[0].links, vec!["records/companies/acme".to_string()]);
2338        assert!(recs[0].created.is_some());
2339        // Extra (non-typed) frontmatter flattens into `fields`.
2340        assert_eq!(
2341            recs[0].fields.get("vendor"),
2342            Some(&serde_json::json!("acme"))
2343        );
2344        assert_eq!(recs[0].fields.get("amount"), Some(&serde_json::json!(42)));
2345        // Defaults: missing tags/links → empty.
2346        assert!(recs[1].tags.is_empty());
2347        assert!(recs[1].links.is_empty());
2348    }
2349
2350    #[test]
2351    fn read_type_index_last_write_wins_and_skips_blanks() {
2352        let dir = empty_store();
2353        let root = dir.path();
2354        // Same path twice; the second line supersedes the first. A blank line
2355        // in between must be ignored, not error.
2356        let jsonl = "\
2357{\"path\":\"records/contacts/sarah.md\",\"type\":\"contact\",\"summary\":\"old\",\"created\":null,\"updated\":null}
2358
2359{\"path\":\"records/contacts/sarah.md\",\"type\":\"contact\",\"summary\":\"new\",\"created\":null,\"updated\":null}
2360";
2361        let p = write(root, "records/contacts/index.jsonl", jsonl);
2362        let store = open(&dir);
2363        let recs = store.read_type_index(&store.abs_path(&p)).unwrap();
2364        assert_eq!(recs.len(), 1, "duplicate path collapses to one record");
2365        assert_eq!(recs[0].summary, "new", "later line must win");
2366    }
2367
2368    #[test]
2369    fn read_type_index_errors_on_malformed_line() {
2370        let dir = empty_store();
2371        let root = dir.path();
2372        let p = write(root, "records/contacts/index.jsonl", "{not valid json}\n");
2373        let store = open(&dir);
2374        let err = store.read_type_index(&store.abs_path(&p)).unwrap_err();
2375        assert!(matches!(err, StoreError::BadTypeIndex { .. }));
2376    }
2377
2378    // ── find_by_type / find_by_where ─────────────────────────────────────────
2379
2380    fn jsonl_line(path: &str, type_: &str, summary: &str, extra: &str) -> String {
2381        format!(
2382            "{{\"path\":\"{path}\",\"type\":\"{type_}\",\"summary\":\"{summary}\",\"created\":null,\"updated\":null{extra}}}\n"
2383        )
2384    }
2385
2386    #[test]
2387    fn find_by_type_reads_canonical_folder_sidecar() {
2388        let dir = empty_store();
2389        let root = dir.path();
2390        // Canonical folder for `contact` is records/contacts.
2391        write(
2392            root,
2393            "records/contacts/index.jsonl",
2394            &(jsonl_line("records/contacts/sarah.md", "contact", "Sarah", "")
2395                + &jsonl_line("records/contacts/elena.md", "contact", "Elena", "")),
2396        );
2397        // A different type's sidecar must not leak into a contact query.
2398        write(
2399            root,
2400            "records/companies/index.jsonl",
2401            &jsonl_line("records/companies/acme.md", "company", "Acme", ""),
2402        );
2403        let store = open(&dir);
2404        let recs = store.find_by_type("contact").unwrap();
2405        let names: Vec<_> = recs.iter().map(|r| r.summary.clone()).collect();
2406        assert_eq!(names, vec!["Elena".to_string(), "Sarah".to_string()]); // path-sorted
2407        assert!(recs.iter().all(|r| r.type_ == "contact"));
2408    }
2409
2410    #[test]
2411    fn regression_find_by_type_includes_non_canonical_folder_when_canonical_exists() {
2412        // Regression for the silent-incompleteness bug: once the canonical
2413        // type-folder sidecar exists, `find_by_type` used to read ONLY that
2414        // sidecar and drop same-type records filed in a non-canonical folder in
2415        // the SAME layer — so the result flipped to incomplete the moment a
2416        // canonical record was added. The write path actively enables such a
2417        // layout (`records/clients/` for a `contact`, any `records/<folder>/`
2418        // for a conclusion `profile`), so this is a reachable, dedup-breaking
2419        // omission.
2420        let dir = empty_store();
2421        let root = dir.path();
2422
2423        // CANONICAL folder sidecar exists (`records/contacts/` for `contact`),
2424        // which is exactly the condition that triggered the bug.
2425        write(
2426            root,
2427            "records/contacts/index.jsonl",
2428            &jsonl_line("records/contacts/sarah.md", "contact", "Sarah", ""),
2429        );
2430        // A `contact` filed in a NON-canonical folder within the same (Records)
2431        // layer. Pre-fix this was silently dropped because the canonical
2432        // sidecar existed; it must now come back.
2433        write(
2434            root,
2435            "records/clients/index.jsonl",
2436            &jsonl_line("records/clients/elena.md", "contact", "Elena", ""),
2437        );
2438        // A different type in the same layer must NOT leak in (proves the read
2439        // is type-filtered, not just a blind whole-layer dump).
2440        write(
2441            root,
2442            "records/companies/index.jsonl",
2443            &jsonl_line("records/companies/acme.md", "company", "Acme", ""),
2444        );
2445
2446        let store = open(&dir);
2447        let got: std::collections::BTreeSet<String> = store
2448            .find_by_type("contact")
2449            .unwrap()
2450            .into_iter()
2451            .map(|r| r.path.to_string_lossy().into_owned())
2452            .collect();
2453        assert_eq!(
2454            got,
2455            ["records/clients/elena.md", "records/contacts/sarah.md"]
2456                .into_iter()
2457                .map(String::from)
2458                .collect::<std::collections::BTreeSet<_>>(),
2459            "both the canonical-folder and the non-canonical-folder contact must \
2460             be returned; the company record must be excluded"
2461        );
2462    }
2463
2464    #[test]
2465    fn regression_find_by_type_profile_spans_multiple_topic_folders() {
2466        // Regression for the scoped-backlinks variant of the same bug
2467        // (`graph backlinks --type <conclusion-type>`): a conclusion type like
2468        // `profile` has the canonical fallback folder `records/profile`, but the
2469        // agent may file profiles under ANY records topic folder
2470        // (`records/people/`, `records/clients/`, …). With a
2471        // `records/profile/index.jsonl` present, the old code read only that
2472        // folder and dropped profiles in the other topic folders —
2473        // under-reporting dependents in a blast-radius check. The
2474        // whole-`records/`-layer read must surface all of them.
2475        let dir = empty_store();
2476        let root = dir.path();
2477        write(
2478            root,
2479            "records/profile/index.jsonl",
2480            &jsonl_line("records/profile/billing.md", "profile", "Billing", ""),
2481        );
2482        write(
2483            root,
2484            "records/people/index.jsonl",
2485            &jsonl_line("records/people/sarah-chen.md", "profile", "Sarah Chen", ""),
2486        );
2487        write(
2488            root,
2489            "records/clients/index.jsonl",
2490            &jsonl_line("records/clients/atlas.md", "profile", "Atlas", ""),
2491        );
2492
2493        let store = open(&dir);
2494        let got: std::collections::BTreeSet<String> = store
2495            .find_by_type("profile")
2496            .unwrap()
2497            .into_iter()
2498            .map(|r| r.path.to_string_lossy().into_owned())
2499            .collect();
2500        assert_eq!(
2501            got,
2502            [
2503                "records/clients/atlas.md",
2504                "records/people/sarah-chen.md",
2505                "records/profile/billing.md",
2506            ]
2507            .into_iter()
2508            .map(String::from)
2509            .collect::<std::collections::BTreeSet<_>>(),
2510            "a profile query must return records from every topic folder, not \
2511             just the canonical records/profile/"
2512        );
2513    }
2514
2515    #[test]
2516    fn find_by_type_canonical_absent_falls_back_within_the_layer_only() {
2517        let dir = empty_store();
2518        let root = dir.path();
2519        // A custom `proposal` record filed under a non-canonical folder NAME
2520        // (the natural plural `records/proposals/`) inside the records layer.
2521        // `default_type_folder("proposal")` = `records/proposal` (bare type, no
2522        // pluralization guess), so the canonical sidecar does not exist and
2523        // `find_by_type` falls back. The fallback is bounded to the type's
2524        // layer (records), so this record — same layer, non-canonical folder —
2525        // is still found: completeness within the layer holds.
2526        write(
2527            root,
2528            "records/proposals/index.jsonl",
2529            &jsonl_line("records/proposals/p1.md", "proposal", "Q3 proposal", ""),
2530        );
2531        // A DECOY of the SAME type sitting in a DIFFERENT layer (sources/). The
2532        // old whole-store fallback read every sidecar in the store and would
2533        // have leaked this into the result; the layer-bounded fallback must not.
2534        // It also pins that the fallback is O(entities-in-layer), never O(store).
2535        write(
2536            root,
2537            "sources/proposals/index.jsonl",
2538            &jsonl_line(
2539                "sources/proposals/leak.md",
2540                "proposal",
2541                "cross-layer decoy",
2542                "",
2543            ),
2544        );
2545        let store = open(&dir);
2546        let recs = store.find_by_type("proposal").unwrap();
2547        assert_eq!(
2548            recs.len(),
2549            1,
2550            "only the records-layer proposal, not the sources decoy"
2551        );
2552        assert_eq!(recs[0].summary, "Q3 proposal");
2553        assert_eq!(recs[0].path, PathBuf::from("records/proposals/p1.md"));
2554    }
2555
2556    #[test]
2557    fn find_by_type_canonical_absent_does_not_read_other_layers() {
2558        let dir = empty_store();
2559        let root = dir.path();
2560        // `email`'s canonical folder is `sources/emails` (layer Sources). No
2561        // sidecar there yet, so `find_by_type("email")` falls back — but only
2562        // within the Sources layer. A populated sidecar in the Records layer
2563        // must never be touched: the fallback is layer-bounded, not store-wide.
2564        // Under the old `read_all_type_indexes_in(None)` fallback this records
2565        // sidecar would have been read and filtered (wasted O(store) I/O); now
2566        // it is outside the walk root entirely.
2567        write(
2568            root,
2569            "records/contacts/index.jsonl",
2570            &jsonl_line("records/contacts/sarah.md", "contact", "Sarah", ""),
2571        );
2572        let store = open(&dir);
2573        // No email anywhere ⇒ empty, and the records layer was not in scope.
2574        assert!(store.find_by_type("email").unwrap().is_empty());
2575    }
2576
2577    #[test]
2578    fn find_by_where_matches_typed_columns_and_flat_fields() {
2579        let dir = empty_store();
2580        let root = dir.path();
2581        write(
2582            root,
2583            "records/expenses/index.jsonl",
2584            &(jsonl_line(
2585                "records/expenses/a.md",
2586                "expense",
2587                "lunch",
2588                ",\"vendor\":\"acme\",\"tags\":[\"meals\"]",
2589            ) + &jsonl_line(
2590                "records/expenses/b.md",
2591                "expense",
2592                "taxi",
2593                ",\"vendor\":\"yellow\"",
2594            )),
2595        );
2596        write(
2597            root,
2598            "records/contacts/index.jsonl",
2599            &jsonl_line(
2600                "records/contacts/sarah.md",
2601                "contact",
2602                "Sarah",
2603                ",\"tags\":[\"customer\"]",
2604            ),
2605        );
2606        let store = open(&dir);
2607
2608        // Flat field in `fields`.
2609        let by_vendor = store.find_by_where("vendor", "acme").unwrap();
2610        assert_eq!(by_vendor.len(), 1);
2611        assert_eq!(by_vendor[0].path, PathBuf::from("records/expenses/a.md"));
2612
2613        // Typed column: type (spans both expense records).
2614        assert_eq!(store.find_by_where("type", "expense").unwrap().len(), 2);
2615
2616        // Typed list column: tags membership.
2617        let customers = store.find_by_where("tags", "customer").unwrap();
2618        assert_eq!(customers.len(), 1);
2619        assert_eq!(
2620            customers[0].path,
2621            PathBuf::from("records/contacts/sarah.md")
2622        );
2623
2624        // No match → empty.
2625        assert!(store.find_by_where("vendor", "nobody").unwrap().is_empty());
2626    }
2627
2628    #[test]
2629    fn find_by_where_matches_timestamps_across_rfc3339_spellings() {
2630        let dir = empty_store();
2631        let root = dir.path();
2632        // db.md files most commonly carry the `Z` UTC spelling. The index.jsonl
2633        // serialized from such a file preserves it verbatim.
2634        write(
2635            root,
2636            "records/meetings/index.jsonl",
2637            "{\"path\":\"records/meetings/kickoff.md\",\"type\":\"meeting\",\
2638\"summary\":\"kickoff\",\"created\":\"2026-05-01T00:00:00Z\",\
2639\"updated\":\"2026-05-02T09:30:00-07:00\"}\n",
2640        );
2641        let store = open(&dir);
2642
2643        // The exact value an agent reads out of the file (`Z` form) must match.
2644        let by_z = store
2645            .find_by_where("created", "2026-05-01T00:00:00Z")
2646            .unwrap();
2647        assert_eq!(by_z.len(), 1);
2648        assert_eq!(by_z[0].path, PathBuf::from("records/meetings/kickoff.md"));
2649
2650        // The equivalent explicit-offset spelling of the same instant matches too.
2651        assert_eq!(
2652            store
2653                .find_by_where("created", "2026-05-01T00:00:00+00:00")
2654                .unwrap()
2655                .len(),
2656            1
2657        );
2658
2659        // A non-UTC stored value matches both its own offset spelling and the
2660        // same instant expressed as `Z` (instant comparison, not string compare).
2661        assert_eq!(
2662            store
2663                .find_by_where("updated", "2026-05-02T09:30:00-07:00")
2664                .unwrap()
2665                .len(),
2666            1
2667        );
2668        assert_eq!(
2669            store
2670                .find_by_where("updated", "2026-05-02T16:30:00Z")
2671                .unwrap()
2672                .len(),
2673            1
2674        );
2675
2676        // A different instant does not match.
2677        assert!(store
2678            .find_by_where("created", "2026-05-01T00:00:01Z")
2679            .unwrap()
2680            .is_empty());
2681        // A non-RFC3339 query value never matches a real timestamp.
2682        assert!(store
2683            .find_by_where("created", "2026-05-01")
2684            .unwrap()
2685            .is_empty());
2686    }
2687
2688    #[test]
2689    fn find_by_where_in_layer_reads_only_that_layers_sidecars() {
2690        // The O(entities-in-layer) contract: a layer-scoped where read must walk
2691        // ONLY the named layer's subtree. Proven structurally — a *malformed*
2692        // sidecar in another layer would make `read_type_index` error if it were
2693        // read, so a scoped read that succeeds (and excludes that record) is
2694        // proof the other layer's I/O never happened.
2695        let dir = empty_store();
2696        let root = dir.path();
2697        write(
2698            root,
2699            "records/companies/index.jsonl",
2700            &jsonl_line(
2701                "records/companies/acme.md",
2702                "company",
2703                "Acme",
2704                ",\"domain\":\"acme.com\"",
2705            ),
2706        );
2707        // Same field/value in the sources layer — but the sidecar is corrupt.
2708        write(
2709            root,
2710            "sources/emails/index.jsonl",
2711            "{ this is not valid json and would error if read }\n",
2712        );
2713        let store = open(&dir);
2714
2715        // Scoped to records: the corrupt sources sidecar is out of scope, so the
2716        // read succeeds and returns only the records-layer match.
2717        let in_records = store
2718            .find_by_where_in("domain", "acme.com", Some(Layer::Records))
2719            .expect("a records-scoped read must not touch the sources sidecar");
2720        assert_eq!(
2721            rels(
2722                &in_records
2723                    .iter()
2724                    .map(|r| r.path.clone())
2725                    .collect::<Vec<_>>()
2726            ),
2727            vec!["records/companies/acme.md".to_string()]
2728        );
2729
2730        // The store-wide read DOES reach the corrupt sidecar and surfaces it as
2731        // a parse error — confirming the corrupt file is genuinely in the tree
2732        // and that only the layer scope spares it.
2733        let store_wide = store.find_by_where("domain", "acme.com");
2734        assert!(
2735            matches!(store_wide, Err(StoreError::BadTypeIndex { .. })),
2736            "unscoped read walks every layer and hits the corrupt sidecar"
2737        );
2738
2739        // Scoping to the layer that holds only the corrupt sidecar still errors
2740        // (the scope includes it), proving the scope is a real subtree bound and
2741        // not a silent "skip anything that fails".
2742        let in_sources = store.find_by_where_in("domain", "acme.com", Some(Layer::Sources));
2743        assert!(matches!(in_sources, Err(StoreError::BadTypeIndex { .. })));
2744    }
2745
2746    #[test]
2747    fn find_by_where_in_missing_layer_is_empty_not_an_error() {
2748        // A layer-scoped read over a layer folder that does not exist yet must
2749        // return empty (mirrors `walk_layer`'s missing-dir guard), never a walk
2750        // error from `ignore` over a nonexistent path.
2751        let dir = empty_store();
2752        let root = dir.path();
2753        write(
2754            root,
2755            "records/contacts/index.jsonl",
2756            &jsonl_line(
2757                "records/contacts/sarah.md",
2758                "contact",
2759                "Sarah",
2760                ",\"city\":\"denver\"",
2761            ),
2762        );
2763        let store = open(&dir);
2764
2765        // `sources/` was never created.
2766        let in_sources = store
2767            .find_by_where_in("city", "denver", Some(Layer::Sources))
2768            .expect("missing layer subtree is empty, not an error");
2769        assert!(in_sources.is_empty());
2770
2771        // Same query scoped to the layer that has the record still finds it.
2772        let in_records = store
2773            .find_by_where_in("city", "denver", Some(Layer::Records))
2774            .unwrap();
2775        assert_eq!(in_records.len(), 1);
2776    }
2777
2778    // ── abs_path / rel_path ──────────────────────────────────────────────────
2779
2780    #[test]
2781    fn abs_and_rel_path_roundtrip() {
2782        let dir = empty_store();
2783        let store = open(&dir);
2784        let rel = Path::new("records/contacts/sarah.md");
2785        let abs = store.abs_path(rel);
2786        assert_eq!(abs, dir.path().join(rel));
2787        assert_eq!(store.rel_path(&abs).as_deref(), Some(rel));
2788
2789        // An absolute path is passed through unchanged by abs_path.
2790        assert_eq!(store.abs_path(&abs), abs);
2791
2792        // A path outside the store has no store-relative form.
2793        assert_eq!(store.rel_path(Path::new("/somewhere/else.md")), None);
2794    }
2795
2796    // ── infer_type_from_path (inverse of default_type_folder) ────────────────
2797
2798    #[test]
2799    fn infer_type_maps_every_recognized_folder_back_to_its_type() {
2800        let cases = [
2801            ("sources/emails/x.md", "email"),
2802            ("sources/transcripts/x.md", "transcript"),
2803            ("sources/docs/x.md", "pdf-source"),
2804            ("sources/notes/x.md", "note"),
2805            ("records/contacts/x.md", "contact"),
2806            ("records/companies/x.md", "company"),
2807            ("records/expenses/x.md", "expense"),
2808            ("records/meetings/x.md", "meeting"),
2809            ("records/decisions/x.md", "decision"),
2810            ("records/invoices/x.md", "invoice"),
2811        ];
2812        for (path, expected) in cases {
2813            assert_eq!(
2814                infer_type_from_path(Path::new(path)).as_deref(),
2815                Some(expected),
2816                "path {path} should infer type {expected}"
2817            );
2818        }
2819    }
2820
2821    #[test]
2822    fn infer_type_round_trips_with_default_type_folder() {
2823        // The canonical invariant: inference is the inverse of the forward map.
2824        // Every recognized type, routed through `default_type_folder` and then
2825        // back through `infer_type_from_path`, must return the original type.
2826        let recognized = [
2827            "email",
2828            "transcript",
2829            "pdf-source",
2830            "contact",
2831            "company",
2832            "expense",
2833            "meeting",
2834            "decision",
2835            "invoice",
2836        ];
2837        for type_ in recognized {
2838            let folder = default_type_folder(type_);
2839            let file = folder.join("x.md");
2840            assert_eq!(
2841                infer_type_from_path(&file).as_deref(),
2842                Some(type_),
2843                "recognized type {type_} (folder {folder:?}) must round-trip"
2844            );
2845        }
2846    }
2847
2848    #[test]
2849    fn infer_type_round_trips_custom_types_verbatim_no_singularization() {
2850        // Regression guard for the CLI/core divergence: `default_type_folder`'s
2851        // unrecognized fallback is the BARE type name (`task → records/task`,
2852        // `tasks → records/tasks`). Inference must NOT singularize, or a custom
2853        // type would not round-trip (e.g. `records/tasks` → `task` would clash
2854        // with `default_type_folder("task") → records/task`).
2855        for custom in ["task", "tasks", "playbook", "process", "okrs", "ticket"] {
2856            let folder = default_type_folder(custom);
2857            assert_eq!(folder, PathBuf::from("records").join(custom));
2858            let file = folder.join("x.md");
2859            assert_eq!(
2860                infer_type_from_path(&file).as_deref(),
2861                Some(custom),
2862                "custom type {custom} must round-trip verbatim (no singularization)"
2863            );
2864        }
2865
2866        // The specific case named in the finding: a plural custom folder keeps
2867        // its trailing `s`; it is NOT singularized to `task`.
2868        assert_eq!(
2869            infer_type_from_path(Path::new("records/tasks/x.md")).as_deref(),
2870            Some("tasks"),
2871            "records/tasks must infer `tasks`, not `task`"
2872        );
2873    }
2874
2875    #[test]
2876    fn infer_type_requires_three_component_layer_folder_file_shape() {
2877        // Fewer than 3 components: a file directly under a layer has no
2878        // type-folder, so inference yields None (matches the old CLI contract).
2879        assert_eq!(infer_type_from_path(Path::new("records/x.md")), None);
2880        assert_eq!(infer_type_from_path(Path::new("sources/x.md")), None);
2881        assert_eq!(infer_type_from_path(Path::new("x.md")), None);
2882        // Unknown leading layer is never inferred.
2883        assert_eq!(infer_type_from_path(Path::new("foo/bar/x.md")), None);
2884        // Deeper paths still infer from the first type-folder segment (e.g. a
2885        // sharded record under records/expenses/2026/05/x.md).
2886        assert_eq!(
2887            infer_type_from_path(Path::new("records/expenses/2026/05/x.md")).as_deref(),
2888            Some("expense"),
2889        );
2890    }
2891
2892    // ── ensure_path_within_store (containment) ───────────────────────────────
2893
2894    #[test]
2895    fn ensure_path_within_store_accepts_in_store_and_rejects_escape() {
2896        let dir = tempdir().unwrap();
2897        let root = dir.path();
2898        fs::create_dir_all(root.join("records/contacts")).unwrap();
2899        fs::write(root.join("records/contacts/sarah.md"), "x").unwrap();
2900
2901        // An existing in-store file resolves and is accepted.
2902        let inside = root.join("records/contacts/sarah.md");
2903        let got = ensure_path_within_store(root, &inside).expect("in-store path accepted");
2904        // Canonical, but still under the (canonical) root.
2905        assert!(got.starts_with(root.canonicalize().unwrap()));
2906
2907        // A not-yet-existing in-store leaf is accepted (rename destination).
2908        let new_leaf = root.join("records/contacts/sarah-chen.md");
2909        assert!(
2910            ensure_path_within_store(root, &new_leaf).is_ok(),
2911            "a non-existent in-store leaf must be accepted"
2912        );
2913
2914        // A `..`-escaping path is rejected even though its prefix exists.
2915        let escape = root.join("records/contacts/../../outside/secret.md");
2916        assert!(
2917            ensure_path_within_store(root, &escape).is_err(),
2918            "a `..`-escaping path must be rejected"
2919        );
2920    }
2921
2922    #[test]
2923    fn ensure_path_within_store_rejects_symlink_escape() {
2924        let dir = tempdir().unwrap();
2925        let root = dir.path().join("store");
2926        fs::create_dir_all(&root).unwrap();
2927        let outside_dir = dir.path().join("outside");
2928        fs::create_dir_all(&outside_dir).unwrap();
2929        let secret = outside_dir.join("secret.md");
2930        fs::write(&secret, "TOPSECRET").unwrap();
2931
2932        // A symlink inside the store that points OUTSIDE it must be rejected:
2933        // resolving the symlink lands outside the canonical root.
2934        #[cfg(unix)]
2935        {
2936            use std::os::unix::fs::symlink;
2937            let link = root.join("escape.md");
2938            symlink(&secret, &link).unwrap();
2939            assert!(
2940                ensure_path_within_store(&root, &link).is_err(),
2941                "a symlink resolving outside the store must be rejected"
2942            );
2943        }
2944    }
2945
2946    // ── shared link-edge notion (fence / whitespace / case) ──────────────────
2947
2948    #[test]
2949    fn extract_edge_targets_trims_inner_whitespace() {
2950        // Padded `[[ x ]]` is the same edge as `[[x]]`.
2951        assert_eq!(
2952            extract_edge_targets("See [[ records/contacts/sarah ]] today."),
2953            vec!["records/contacts/sarah".to_string()]
2954        );
2955    }
2956
2957    #[test]
2958    fn extract_edge_targets_skips_fenced_code_blocks() {
2959        // A `[[...]]` inside a ``` fence is a doc example, NOT an edge — matching
2960        // validate's body extractor.
2961        let body = "\
2962Real [[records/contacts/sarah]] link.
2963
2964```markdown
2965[[records/contacts/ghost-example]] is how you link.
2966```
2967
2968After fence [[records/companies/acme]].
2969";
2970        let got = extract_edge_targets(body);
2971        assert_eq!(
2972            got,
2973            vec![
2974                "records/contacts/sarah".to_string(),
2975                "records/companies/acme".to_string(),
2976            ],
2977            "fenced example link must not be an edge"
2978        );
2979    }
2980
2981    #[test]
2982    fn extract_edge_targets_handles_nested_indented_and_long_run_fences() {
2983        // Regression for the naive `starts_with("```")/("~~~")` toggle: a fence
2984        // nested inside another, an over-indented (>3 space) marker, and a
2985        // long-run fence wrapping a shorter inner one must all leave the block's
2986        // links un-extracted (validate treats the whole block as opaque). The
2987        // (char, run-length) tracker keys on the OPENING fence and closes only on
2988        // a matching char with run ≥ the opener.
2989
2990        // (a) A ```` ```` ````-run block (run 4) wrapping a ``` example (run 3).
2991        // The inner ``` does NOT close the outer run-4 fence, so both `[[...]]`
2992        // inside stay fenced.
2993        let nested = "\
2994Doc:
2995
2996````
2997```
2998[[records/contacts/bob]]
2999```
3000still fenced [[records/contacts/bob]]
3001````
3002
3003Real [[records/companies/acme]].
3004";
3005        assert_eq!(
3006            extract_edge_targets(nested),
3007            vec!["records/companies/acme".to_string()],
3008            "a nested ``` inside a ````-run fence must not leak the fenced links"
3009        );
3010
3011        // (b) A `~~~` block containing a ``` line (the standard way to document a
3012        // backtick fence). The inner backtick line must not flip the state.
3013        let tilde_wraps_backtick = "\
3014~~~
3015```
3016[[records/contacts/ghost]]
3017```
3018~~~
3019
3020After [[records/companies/acme]].
3021";
3022        assert_eq!(
3023            extract_edge_targets(tilde_wraps_backtick),
3024            vec!["records/companies/acme".to_string()],
3025            "a ``` line inside a ~~~ block must not invert the fence state"
3026        );
3027
3028        // (c) An over-indented ```` ``` ```` (4 spaces) is NOT a fence; the link
3029        // on the next line is live.
3030        let over_indented = "    ```\nLive [[records/contacts/sarah]].\n";
3031        assert_eq!(
3032            extract_edge_targets(over_indented),
3033            vec!["records/contacts/sarah".to_string()],
3034            "a >3-space-indented ``` is not a fence opener"
3035        );
3036    }
3037
3038    #[test]
3039    fn canonical_link_target_strips_md_dotslash_and_trims() {
3040        assert_eq!(canonical_link_target("  records/x.md  "), "records/x");
3041        assert_eq!(canonical_link_target("./records/y"), "records/y");
3042        assert_eq!(canonical_link_target("/records/z"), "records/z");
3043    }
3044
3045    #[test]
3046    fn link_edge_key_folds_case_only_on_case_insensitive_fs() {
3047        let a = link_edge_key("records/contacts/Sarah-Chen");
3048        let b = link_edge_key("records/contacts/sarah-chen");
3049        if fs_is_case_insensitive() {
3050            assert_eq!(a, b, "case-insensitive FS must fold the key");
3051        } else {
3052            assert_ne!(a, b, "case-sensitive FS must keep the key case-exact");
3053        }
3054    }
3055
3056    // ── walk follows symlinked content ───────────────────────────────────────
3057
3058    #[cfg(unix)]
3059    #[test]
3060    fn walk_includes_symlinked_content_file_and_symlinked_folder() {
3061        use std::os::unix::fs::symlink;
3062        let dir = empty_store();
3063        let root = dir.path();
3064        // A regular file (control).
3065        write(
3066            root,
3067            "records/contacts/sarah.md",
3068            &content_md("2026-05-01T00:00:00Z"),
3069        );
3070        // A symlinked .md content file inside a real folder.
3071        let external_file = root.join("external-elena.md");
3072        fs::write(&external_file, content_md("2026-05-02T00:00:00Z")).unwrap();
3073        symlink(&external_file, root.join("records/contacts/elena.md")).unwrap();
3074        // A symlinked type folder.
3075        let external_dir = dir.path().join("external-companies");
3076        fs::create_dir_all(&external_dir).unwrap();
3077        fs::write(
3078            external_dir.join("acme.md"),
3079            content_md("2026-05-03T00:00:00Z"),
3080        )
3081        .unwrap();
3082        symlink(&external_dir, root.join("records/companies")).unwrap();
3083
3084        let store = open(&dir);
3085        let got = rels(&store.walk().unwrap());
3086        assert!(
3087            got.contains(&"records/contacts/elena.md".to_string()),
3088            "a symlinked content file must be walked: {got:?}"
3089        );
3090        assert!(
3091            got.contains(&"records/companies/acme.md".to_string()),
3092            "a file inside a symlinked type folder must be walked: {got:?}"
3093        );
3094    }
3095
3096    // ── find_links_to: padded / fenced / case ────────────────────────────────
3097
3098    #[test]
3099    fn find_links_to_matches_whitespace_padded_link() {
3100        let dir = empty_store();
3101        let root = dir.path();
3102        write(
3103            root,
3104            "records/profiles/a.md",
3105            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[ records/contacts/sarah ]] today.\n",
3106        );
3107        let store = open(&dir);
3108        let got = rels(
3109            &store
3110                .find_links_to(Path::new("records/contacts/sarah"))
3111                .unwrap(),
3112        );
3113        assert_eq!(
3114            got,
3115            vec!["records/profiles/a.md".to_string()],
3116            "a padded `[[ x ]]` link must be found as a backward edge, matching forwardlinks"
3117        );
3118    }
3119
3120    #[test]
3121    fn find_links_to_ignores_fenced_example_link() {
3122        let dir = empty_store();
3123        let root = dir.path();
3124        write(
3125            root,
3126            "records/concepts/howto.md",
3127            "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n```markdown\n[[records/contacts/sarah]]\n```\n",
3128        );
3129        let store = open(&dir);
3130        let got = store
3131            .find_links_to(Path::new("records/contacts/sarah"))
3132            .unwrap();
3133        assert!(
3134            got.is_empty(),
3135            "a `[[...]]` only inside a fenced code block is not a backward edge: {got:?}"
3136        );
3137    }
3138
3139    #[cfg(unix)]
3140    #[test]
3141    fn find_links_to_matches_case_variant_on_case_insensitive_fs() {
3142        // Only meaningful on a case-insensitive filesystem; on a case-sensitive
3143        // one the case-variant link is genuinely a different target.
3144        if !fs_is_case_insensitive() {
3145            return;
3146        }
3147        let dir = empty_store();
3148        let root = dir.path();
3149        write(
3150            root,
3151            "records/profiles/bio.md",
3152            "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[records/contacts/Sarah-Chen]].\n",
3153        );
3154        let store = open(&dir);
3155        let got = rels(
3156            &store
3157                .find_links_to(Path::new("records/contacts/sarah-chen"))
3158                .unwrap(),
3159        );
3160        assert_eq!(
3161            got,
3162            vec!["records/profiles/bio.md".to_string()],
3163            "a case-variant link must be found on a case-insensitive filesystem"
3164        );
3165    }
3166}