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 `---`, tolerating trailing whitespace (CR, but
1310 // also spaces/tabs) — matching the canonical parser (`parser.rs` /
1311 // `index.rs`'s `extract_frontmatter_block`). A strict `\r`-only trim missed a
1312 // `--- ` fence, so `read_updated` returned None and date-sharding silently
1313 // fell back, disagreeing with the sidecar the rest of the toolkit builds.
1314 let (first, after_first) = split_first_line(rest);
1315 if first.trim_end() != "---" {
1316 return None;
1317 }
1318 rest = after_first;
1319 let block_start = rest;
1320 let mut scanned = 0usize;
1321 loop {
1322 let (line, after) = split_first_line(rest);
1323 if line.trim_end() == "---" {
1324 return Some(&block_start[..scanned]);
1325 }
1326 if after.is_empty() && line.is_empty() {
1327 // Reached end of input without a closing fence.
1328 return None;
1329 }
1330 scanned += line.len() + 1; // +1 for the consumed '\n'
1331 if after.is_empty() {
1332 return None;
1333 }
1334 rest = after;
1335 }
1336}
1337
1338/// Split a string into (first line without its trailing `\n`, remainder after
1339/// the `\n`). If there is no newline, the whole string is the line and the
1340/// remainder is empty.
1341fn split_first_line(s: &str) -> (&str, &str) {
1342 match s.find('\n') {
1343 Some(i) => (&s[..i], &s[i + 1..]),
1344 None => (s, ""),
1345 }
1346}
1347
1348/// True if an [`IndexRecord`] has a field `key` equal to `value`, checking the
1349/// typed columns first and then the flattened `fields` map.
1350fn record_matches_field(record: &IndexRecord, key: &str, value: &str) -> bool {
1351 match key {
1352 "type" => record.type_ == value,
1353 "summary" => record.summary == value,
1354 "path" => record.path.to_string_lossy() == value,
1355 "created" => timestamp_matches(record.created, value),
1356 "updated" => timestamp_matches(record.updated, value),
1357 "tags" => record.tags.iter().any(|t| t == value),
1358 "links" => record.links.iter().any(|l| l == value),
1359 other => record
1360 .fields
1361 .get(other)
1362 .map(|v| json_value_matches(v, value))
1363 .unwrap_or(false),
1364 }
1365}
1366
1367/// Compare a record's `created`/`updated` instant against a query `value`.
1368///
1369/// db.md files write timestamps in several equivalent RFC3339 spellings — most
1370/// commonly the `Z` UTC designator (`2026-05-01T00:00:00Z`) but also an explicit
1371/// offset (`...+00:00`, `...-07:00`). A naive `record.created.to_rfc3339() ==
1372/// value` reformats only one side: chrono renders a UTC instant as `+00:00`, so
1373/// the `Z` form an agent reads straight out of the file would never match. We
1374/// instead parse `value` as RFC3339 and compare instants, where `Z` and `+00:00`
1375/// (and any same-instant offset) are equal. A `value` that is not valid RFC3339
1376/// can never equal a real timestamp, so it falls through to `false`.
1377fn timestamp_matches(stored: Option<DateTime<FixedOffset>>, value: &str) -> bool {
1378 match (stored, DateTime::parse_from_rfc3339(value)) {
1379 (Some(stored), Ok(queried)) => stored == queried,
1380 _ => false,
1381 }
1382}
1383
1384/// Match a JSON number against a query string.
1385///
1386/// A FLOAT-valued field is compared NUMERICALLY, not textually: the sidecar
1387/// stores a YAML float through serde_json's canonical f64 rendering, which
1388/// discards the file's source spelling (`1234.00` -> `1234.0`, `12.50` ->
1389/// `12.5`, `1e3` -> `1000.0`). A raw `to_string()` compare therefore made the
1390/// spelling a human reads in the file fail to match (and disagreed with
1391/// free-text `search`), while requiring a canonical form often absent from the
1392/// file. We parse the query as f64 and compare values. Restricted to the float
1393/// case so a large INTEGER field never loses exactness to f64 rounding (integers
1394/// render canonically and round-trip exactly through the textual compare).
1395/// Mirrors the parse-then-compare pattern [`timestamp_matches`] already uses.
1396fn number_matches(n: &serde_json::Number, value: &str) -> bool {
1397 if n.to_string() == value {
1398 return true;
1399 }
1400 if n.is_f64() {
1401 if let (Some(stored), Ok(q)) = (n.as_f64(), value.parse::<f64>()) {
1402 return stored == q;
1403 }
1404 }
1405 false
1406}
1407
1408/// Compare a JSON field value against a query string. A string matches
1409/// verbatim; scalars match their textual form; an array matches if any element
1410/// matches (so a list-valued frontmatter field is membership-queried).
1411fn json_value_matches(v: &serde_json::Value, value: &str) -> bool {
1412 match v {
1413 serde_json::Value::String(s) => s == value,
1414 serde_json::Value::Bool(b) => b.to_string() == value,
1415 serde_json::Value::Number(n) => number_matches(n, value),
1416 serde_json::Value::Array(items) => items.iter().any(|i| json_value_matches(i, value)),
1417 // A present-but-null field never matches — consistent with the in-memory
1418 // post-filter (`query::json_value_matches`, which the first `where`
1419 // clause is NOT re-checked against, so the two must agree here or a
1420 // `--where field=` query would return different rows than `--type X
1421 // --where field=`).
1422 serde_json::Value::Null => false,
1423 serde_json::Value::Object(_) => false,
1424 }
1425}
1426
1427#[cfg(test)]
1428mod tests {
1429 use super::*;
1430 use std::fs;
1431 use tempfile::{tempdir, TempDir};
1432
1433 // ── Fixtures ────────────────────────────────────────────────────────────
1434
1435 /// Write `contents` to `<root>/<rel>`, creating parent dirs. Returns the
1436 /// store-relative path for convenient assertions.
1437 fn write(root: &Path, rel: &str, contents: &str) -> PathBuf {
1438 let abs = root.join(rel);
1439 fs::create_dir_all(abs.parent().unwrap()).unwrap();
1440 fs::write(&abs, contents).unwrap();
1441 PathBuf::from(rel)
1442 }
1443
1444 /// A minimal content file with the given `updated` timestamp in frontmatter.
1445 fn content_md(updated: &str) -> String {
1446 format!(
1447 "---\ntype: note\ncreated: {updated}\nupdated: {updated}\nsummary: a note\n---\n\nbody\n"
1448 )
1449 }
1450
1451 /// A bare directory with a `DB.md` marker (valid `db-md` frontmatter so the
1452 /// real parser is exercised).
1453 fn empty_store() -> TempDir {
1454 let dir = tempdir().unwrap();
1455 fs::write(
1456 dir.path().join("DB.md"),
1457 "---\ntype: db-md\nscope: company\nowner: Test\n---\n\n# Store\n",
1458 )
1459 .unwrap();
1460 dir
1461 }
1462
1463 /// Open a store rooted at a TempDir; panics if `open` rejects it.
1464 fn open(dir: &TempDir) -> Store {
1465 Store::open(dir.path()).expect("fixture should be a valid store")
1466 }
1467
1468 fn rels(paths: &[PathBuf]) -> Vec<String> {
1469 paths
1470 .iter()
1471 .map(|p| p.to_string_lossy().replace('\\', "/"))
1472 .collect()
1473 }
1474
1475 // ── Layer ───────────────────────────────────────────────────────────────
1476
1477 #[test]
1478 fn layer_dir_name_and_parse_are_inverse() {
1479 for layer in Layer::all() {
1480 assert_eq!(Layer::from_dir_name(layer.dir_name()), Some(layer));
1481 }
1482 assert_eq!(Layer::Sources.dir_name(), "sources");
1483 assert_eq!(Layer::Records.dir_name(), "records");
1484 // `wiki` is no longer a layer (the wiki/ layer was removed); it parses to None.
1485 assert_eq!(Layer::from_dir_name("wiki"), None);
1486 assert_eq!(Layer::from_dir_name("log"), None);
1487 assert_eq!(Layer::from_dir_name("Sources"), None); // case-sensitive
1488 }
1489
1490 #[test]
1491 fn layer_order_is_canonical() {
1492 // stats keys a BTreeMap on Layer; the sort order must be sources<records.
1493 let mut v = [Layer::Records, Layer::Sources];
1494 v.sort();
1495 assert_eq!(v, [Layer::Sources, Layer::Records]);
1496 }
1497
1498 // ── is_db_md_store / open ────────────────────────────────────────────────
1499
1500 #[test]
1501 fn is_store_true_only_with_uppercase_marker() {
1502 let dir = tempdir().unwrap();
1503 assert!(
1504 !Store::is_db_md_store(dir.path()),
1505 "no marker → not a store"
1506 );
1507
1508 fs::write(dir.path().join("DB.md"), "---\ntype: db-md\n---\n").unwrap();
1509 assert!(Store::is_db_md_store(dir.path()), "uppercase DB.md → store");
1510 }
1511
1512 #[test]
1513 fn is_store_false_for_lowercase_db_md() {
1514 // The case-sensitivity contract: a lowercase db.md is the spec name, not
1515 // a marker — even on a case-insensitive filesystem where Path::exists
1516 // would lie. This test must pass on macOS (case-insensitive) too.
1517 let dir = tempdir().unwrap();
1518 fs::write(dir.path().join("db.md"), "---\ntype: db-md\n---\n").unwrap();
1519 assert!(
1520 !Store::is_db_md_store(dir.path()),
1521 "lowercase db.md must NOT be treated as a store marker"
1522 );
1523 assert!(Store::open(dir.path()).is_err());
1524 }
1525
1526 #[test]
1527 fn is_store_false_when_db_md_is_a_directory() {
1528 let dir = tempdir().unwrap();
1529 fs::create_dir(dir.path().join("DB.md")).unwrap();
1530 assert!(
1531 !Store::is_db_md_store(dir.path()),
1532 "a directory named DB.md is not the file marker"
1533 );
1534 }
1535
1536 #[test]
1537 fn open_rejects_non_store_with_path() {
1538 let dir = tempdir().unwrap();
1539 let err = Store::open(dir.path()).unwrap_err();
1540 assert_eq!(err.path, dir.path());
1541 }
1542
1543 #[test]
1544 fn open_succeeds_and_parses_config() {
1545 let dir = tempdir().unwrap();
1546 // A DB.md whose ## Policies declares a frozen page — proves open()
1547 // actually parsed the config rather than substituting a default.
1548 fs::write(
1549 dir.path().join("DB.md"),
1550 "---\ntype: db-md\nscope: company\nowner: Test\n---\n\n# Store\n\n\
1551 ## Policies\n\n### Frozen pages\n- records/decisions/q1.md\n",
1552 )
1553 .unwrap();
1554 let store = Store::open(dir.path()).unwrap();
1555 assert_eq!(store.root, dir.path());
1556 assert!(
1557 store
1558 .config
1559 .frozen_pages
1560 .iter()
1561 .any(|p| p == Path::new("records/decisions/q1.md")),
1562 "open() must surface DB.md ## Policies, got {:?}",
1563 store.config.frozen_pages
1564 );
1565 }
1566
1567 // ── walk / walk_layer / walk_type_folder ─────────────────────────────────
1568
1569 #[test]
1570 fn walk_collects_content_across_layers_skipping_meta_and_log() {
1571 let dir = empty_store();
1572 let root = dir.path();
1573 write(
1574 root,
1575 "sources/emails/2026/05/a.md",
1576 &content_md("2026-05-01T00:00:00Z"),
1577 );
1578 write(
1579 root,
1580 "records/contacts/sarah.md",
1581 &content_md("2026-05-02T00:00:00Z"),
1582 );
1583 write(
1584 root,
1585 "records/profiles/sarah.md",
1586 &content_md("2026-05-03T00:00:00Z"),
1587 );
1588 // Things walk() must SKIP:
1589 write(root, "sources/emails/index.md", "---\ntype: index\n---\n"); // catalog
1590 write(root, "index.md", "---\ntype: index\n---\n"); // root catalog
1591 write(root, "log.md", "---\ntype: log\n---\n"); // log
1592 write(root, "log/2026-04.md", "---\ntype: log\n---\n"); // rotated log archive
1593 write(
1594 root,
1595 "sources/.hidden/secret.md",
1596 &content_md("2026-05-09T00:00:00Z"),
1597 ); // hidden dir
1598 write(root, "records/contacts/notes.txt", "not markdown"); // non-md
1599
1600 let store = open(&dir);
1601 let got = rels(&store.walk().unwrap());
1602 assert_eq!(
1603 got,
1604 vec![
1605 "records/contacts/sarah.md".to_string(),
1606 "records/profiles/sarah.md".to_string(),
1607 "sources/emails/2026/05/a.md".to_string(),
1608 ]
1609 );
1610 }
1611
1612 #[test]
1613 fn walk_includes_content_named_log_md_or_db_md_inside_a_layer() {
1614 let dir = empty_store();
1615 let root = dir.path();
1616 // A content file that merely happens to be named log.md / DB.md INSIDE a
1617 // layer is real content — those names are reserved only at the store root.
1618 write(
1619 root,
1620 "records/configs/log.md",
1621 &content_md("2026-05-01T00:00:00Z"),
1622 );
1623 write(
1624 root,
1625 "sources/docs/DB.md",
1626 &content_md("2026-05-02T00:00:00Z"),
1627 );
1628 // The derived catalog twin is still skipped at any depth.
1629 write(root, "records/configs/index.md", "---\ntype: index\n---\n");
1630 let store = open(&dir);
1631 let got = rels(&store.walk().unwrap());
1632 assert!(
1633 got.contains(&"records/configs/log.md".to_string()),
1634 "layer-internal log.md is content: {got:?}"
1635 );
1636 assert!(
1637 got.contains(&"sources/docs/DB.md".to_string()),
1638 "layer-internal DB.md is content: {got:?}"
1639 );
1640 assert!(
1641 !got.iter().any(|p| p.ends_with("index.md")),
1642 "index.md is still skipped: {got:?}"
1643 );
1644 }
1645
1646 #[test]
1647 fn walk_layer_is_scoped() {
1648 let dir = empty_store();
1649 let root = dir.path();
1650 write(
1651 root,
1652 "sources/emails/2026/05/a.md",
1653 &content_md("2026-05-01T00:00:00Z"),
1654 );
1655 write(
1656 root,
1657 "records/contacts/sarah.md",
1658 &content_md("2026-05-02T00:00:00Z"),
1659 );
1660 let store = open(&dir);
1661
1662 assert_eq!(
1663 rels(&store.walk_layer(Layer::Sources).unwrap()),
1664 vec!["sources/emails/2026/05/a.md".to_string()]
1665 );
1666 assert_eq!(
1667 rels(&store.walk_layer(Layer::Records).unwrap()),
1668 vec!["records/contacts/sarah.md".to_string()]
1669 );
1670 // A layer with no directory is empty, not an error: a store with only a
1671 // sources/ tree has no records/ dir, so walking Records is empty.
1672 let only_sources = empty_store();
1673 write(
1674 only_sources.path(),
1675 "sources/emails/2026/05/a.md",
1676 &content_md("2026-05-01T00:00:00Z"),
1677 );
1678 let s2 = open(&only_sources);
1679 assert!(s2.walk_layer(Layer::Records).unwrap().is_empty());
1680 }
1681
1682 #[test]
1683 fn walk_type_folder_recurses_shards_and_accepts_abs_or_rel() {
1684 let dir = empty_store();
1685 let root = dir.path();
1686 write(
1687 root,
1688 "sources/emails/2026/05/a.md",
1689 &content_md("2026-05-01T00:00:00Z"),
1690 );
1691 write(
1692 root,
1693 "sources/emails/2026/06/b.md",
1694 &content_md("2026-06-01T00:00:00Z"),
1695 );
1696 write(root, "sources/emails/index.md", "---\ntype: index\n---\n"); // skipped
1697 // A different type folder must not leak in.
1698 write(
1699 root,
1700 "sources/docs/2026/05/c.md",
1701 &content_md("2026-05-04T00:00:00Z"),
1702 );
1703 let store = open(&dir);
1704
1705 let expected = vec![
1706 "sources/emails/2026/05/a.md".to_string(),
1707 "sources/emails/2026/06/b.md".to_string(),
1708 ];
1709 // Relative folder arg.
1710 assert_eq!(
1711 rels(&store.walk_type_folder(Path::new("sources/emails")).unwrap()),
1712 expected
1713 );
1714 // Absolute folder arg under the store resolves identically.
1715 assert_eq!(
1716 rels(
1717 &store
1718 .walk_type_folder(&root.join("sources/emails"))
1719 .unwrap()
1720 ),
1721 expected
1722 );
1723 }
1724
1725 // ── recent_in_type_folder ────────────────────────────────────────────────
1726
1727 #[test]
1728 fn recent_orders_by_updated_desc_then_path_and_caps() {
1729 let dir = empty_store();
1730 let root = dir.path();
1731 // newest
1732 write(
1733 root,
1734 "records/meetings/2026/05/c.md",
1735 &content_md("2026-05-03T00:00:00Z"),
1736 );
1737 // tie on updated — path asc decides (a before b)
1738 write(
1739 root,
1740 "records/meetings/2026/05/a.md",
1741 &content_md("2026-05-02T00:00:00Z"),
1742 );
1743 write(
1744 root,
1745 "records/meetings/2026/05/b.md",
1746 &content_md("2026-05-02T00:00:00Z"),
1747 );
1748 // oldest
1749 write(
1750 root,
1751 "records/meetings/2026/04/z.md",
1752 &content_md("2026-04-01T00:00:00Z"),
1753 );
1754 let store = open(&dir);
1755
1756 let all = rels(
1757 &store
1758 .recent_in_type_folder(Path::new("records/meetings"), 10)
1759 .unwrap(),
1760 );
1761 assert_eq!(
1762 all,
1763 vec![
1764 "records/meetings/2026/05/c.md".to_string(), // newest
1765 "records/meetings/2026/05/a.md".to_string(), // tie, path asc
1766 "records/meetings/2026/05/b.md".to_string(),
1767 "records/meetings/2026/04/z.md".to_string(), // oldest
1768 ]
1769 );
1770
1771 // Cap takes the n most-recent.
1772 let top2 = rels(
1773 &store
1774 .recent_in_type_folder(Path::new("records/meetings"), 2)
1775 .unwrap(),
1776 );
1777 assert_eq!(
1778 top2,
1779 vec![
1780 "records/meetings/2026/05/c.md".to_string(),
1781 "records/meetings/2026/05/a.md".to_string(),
1782 ]
1783 );
1784 }
1785
1786 #[test]
1787 fn recent_sorts_undated_files_last() {
1788 let dir = empty_store();
1789 let root = dir.path();
1790 write(
1791 root,
1792 "records/contacts/dated.md",
1793 &content_md("2026-05-01T00:00:00Z"),
1794 );
1795 // No `updated` field at all.
1796 write(
1797 root,
1798 "records/contacts/undated.md",
1799 "---\ntype: contact\nsummary: x\n---\nbody\n",
1800 );
1801 let store = open(&dir);
1802 let got = rels(
1803 &store
1804 .recent_in_type_folder(Path::new("records/contacts"), 10)
1805 .unwrap(),
1806 );
1807 assert_eq!(
1808 got,
1809 vec![
1810 "records/contacts/dated.md".to_string(),
1811 "records/contacts/undated.md".to_string(),
1812 ],
1813 "a file with a real `updated` must outrank one with none"
1814 );
1815 }
1816
1817 // ── type_shards ──────────────────────────────────────────────────────────
1818
1819 #[test]
1820 fn type_shards_classification() {
1821 let dir = empty_store();
1822 let store = open(&dir);
1823 for t in [
1824 "email",
1825 "transcript",
1826 "pdf-source",
1827 "expense",
1828 "invoice",
1829 "meeting",
1830 "order",
1831 "ticket",
1832 "transaction",
1833 ] {
1834 assert!(store.type_shards(t), "{t} should shard");
1835 }
1836 for t in [
1837 "contact", "company", "decision", "profile", "index", "log", "db-md", "proposal",
1838 ] {
1839 assert!(!store.type_shards(t), "{t} should stay flat");
1840 }
1841 }
1842
1843 #[test]
1844 fn type_shards_respects_schema_directive_both_directions() {
1845 use crate::parser::{Config, Schema};
1846 let dir = empty_store();
1847 let mut store = open(&dir);
1848 let mut config = Config::default();
1849 // A CUSTOM type (not in the built-in list) opts into date-sharding —
1850 // without the schema override `type_shards` would return false for it.
1851 config.schemas.insert(
1852 "shipment".to_string(),
1853 Schema {
1854 shard: Some(true),
1855 ..Schema::default()
1856 },
1857 );
1858 // A BUILT-IN event type opts OUT (flat) — the override wins over the
1859 // built-in default.
1860 config.schemas.insert(
1861 "expense".to_string(),
1862 Schema {
1863 shard: Some(false),
1864 ..Schema::default()
1865 },
1866 );
1867 // A schema with no `shard:` directive leaves the built-in default intact.
1868 config
1869 .schemas
1870 .insert("meeting".to_string(), Schema::default());
1871 store.config = config;
1872
1873 assert!(
1874 store.type_shards("shipment"),
1875 "custom type with `shard: by-date` must shard"
1876 );
1877 assert!(
1878 !store.type_shards("expense"),
1879 "built-in event type with `shard: flat` must go flat"
1880 );
1881 assert!(
1882 store.type_shards("meeting"),
1883 "schema without a `shard:` directive keeps the built-in default"
1884 );
1885 assert!(
1886 !store.type_shards("contact"),
1887 "unconfigured entity type stays flat"
1888 );
1889 }
1890
1891 // ── shard_path_for ───────────────────────────────────────────────────────
1892
1893 fn fm_with_extra(key: &str, value: &str) -> Frontmatter {
1894 let mut fm = Frontmatter::default();
1895 fm.extra.insert(
1896 key.to_string(),
1897 serde_norway::Value::String(value.to_string()),
1898 );
1899 fm
1900 }
1901
1902 fn fm_with_created(rfc3339: &str) -> Frontmatter {
1903 Frontmatter {
1904 created: Some(DateTime::parse_from_rfc3339(rfc3339).unwrap()),
1905 ..Default::default()
1906 }
1907 }
1908
1909 #[test]
1910 fn shard_path_uses_primary_date_field_per_type() {
1911 let dir = empty_store();
1912 let store = open(&dir);
1913
1914 // expense.date → records/expenses/<YYYY>/<MM>/
1915 let p = store
1916 .shard_path_for("expense", &fm_with_extra("date", "2026-05-22"), "lunch")
1917 .unwrap();
1918 assert_eq!(p, PathBuf::from("records/expenses/2026/05/lunch.md"));
1919
1920 // email.date → sources/emails/<YYYY>/<MM>/
1921 let p = store
1922 .shard_path_for(
1923 "email",
1924 &fm_with_extra("date", "2026-11-02T09:00:00-07:00"),
1925 "e1",
1926 )
1927 .unwrap();
1928 assert_eq!(p, PathBuf::from("sources/emails/2026/11/e1.md"));
1929
1930 // transcript.recorded_at → sources/transcripts/<YYYY>/<MM>/
1931 let p = store
1932 .shard_path_for(
1933 "transcript",
1934 &fm_with_extra("recorded_at", "2025-01-15T12:00:00Z"),
1935 "t1",
1936 )
1937 .unwrap();
1938 assert_eq!(p, PathBuf::from("sources/transcripts/2025/01/t1.md"));
1939 }
1940
1941 #[test]
1942 fn shard_path_falls_back_to_created() {
1943 let dir = empty_store();
1944 let store = open(&dir);
1945 // meeting with no `date` field but a `created` timestamp.
1946 let p = store
1947 .shard_path_for(
1948 "meeting",
1949 &fm_with_created("2024-07-09T08:30:00-04:00"),
1950 "sync",
1951 )
1952 .unwrap();
1953 assert_eq!(p, PathBuf::from("records/meetings/2024/07/sync.md"));
1954 }
1955
1956 #[test]
1957 fn shard_path_primary_field_wins_over_created() {
1958 let dir = empty_store();
1959 let store = open(&dir);
1960 let mut fm = fm_with_created("2020-01-01T00:00:00Z");
1961 fm.extra.insert(
1962 "date".into(),
1963 serde_norway::Value::String("2026-05-22".into()),
1964 );
1965 let p = store.shard_path_for("expense", &fm, "x").unwrap();
1966 // The primary `date` (2026/05), not `created` (2020/01), drives the shard.
1967 assert_eq!(p, PathBuf::from("records/expenses/2026/05/x.md"));
1968 }
1969
1970 #[test]
1971 fn shard_path_flat_types_have_no_shard_segment() {
1972 let dir = empty_store();
1973 let store = open(&dir);
1974 // A contact has a `created` date, but contacts stay flat.
1975 let p = store
1976 .shard_path_for(
1977 "contact",
1978 &fm_with_created("2026-05-22T00:00:00Z"),
1979 "sarah-chen",
1980 )
1981 .unwrap();
1982 assert_eq!(p, PathBuf::from("records/contacts/sarah-chen.md"));
1983
1984 // A conclusion `profile` is a custom (non-built-in) type: it is flat (no
1985 // date shard) and lands under the records-layer fallback folder
1986 // `records/<type>` — `records/profile/<name>.md`, a conforming 3-component
1987 // `<layer>/<type-folder>/<file>` path. A 2-component path would be
1988 // invisible to the index/validate type-folder model.
1989 let p = store
1990 .shard_path_for("profile", &Frontmatter::default(), "renewal-theme")
1991 .unwrap();
1992 assert_eq!(p, PathBuf::from("records/profile/renewal-theme.md"));
1993 }
1994
1995 /// Regression: a type written through the toolkit's own path computation
1996 /// must land at a path the index + validate type-folder model accepts. A
1997 /// 2-component `<layer>/<file>` path is one `type_folder_of` (in both `index`
1998 /// and `validate`) treats as "no type-folder" — it would either crash
1999 /// `Index::on_write` (it tried to create `index.md` inside a file) or be
2000 /// silently dropped from every catalog by `Index::rebuild_all`. A custom
2001 /// (non-built-in) type like a conclusion `profile` falls back to
2002 /// `records/<type>` — still a conforming 3-component
2003 /// `<layer>/<type-folder>/<file>` path.
2004 #[test]
2005 fn shard_path_custom_type_is_indexable_three_component_path() {
2006 let dir = empty_store();
2007 let store = open(&dir);
2008 let p = store
2009 .shard_path_for("profile", &Frontmatter::default(), "renewal-theme")
2010 .unwrap();
2011 // First two components are a layer + a non-empty type-folder segment;
2012 // the file is the third. This is exactly the shape `type_folder_of`
2013 // (`comps.len() >= 3`, `comps[0]` a known layer) requires.
2014 let comps: Vec<&str> = p.iter().filter_map(|c| c.to_str()).collect();
2015 assert_eq!(
2016 comps.len(),
2017 3,
2018 "custom-type path must be <layer>/<type-folder>/<file>, got {p:?}"
2019 );
2020 assert_eq!(
2021 comps[0], "records",
2022 "first component must be the records layer (a custom type is \
2023 filed under the records fallback)"
2024 );
2025 assert!(
2026 !comps[1].is_empty() && comps[1] != "renewal-theme.md",
2027 "second component must be a real type-folder, not the file: {p:?}"
2028 );
2029 assert!(
2030 comps[2].ends_with(".md"),
2031 "third component must be the .md file: {p:?}"
2032 );
2033 }
2034
2035 #[test]
2036 fn shard_path_preserves_and_adds_md_extension() {
2037 let dir = empty_store();
2038 let store = open(&dir);
2039 let with = store
2040 .shard_path_for("contact", &Frontmatter::default(), "sarah.md")
2041 .unwrap();
2042 let without = store
2043 .shard_path_for("contact", &Frontmatter::default(), "sarah")
2044 .unwrap();
2045 assert_eq!(with, PathBuf::from("records/contacts/sarah.md"));
2046 assert_eq!(without, PathBuf::from("records/contacts/sarah.md"));
2047 }
2048
2049 #[test]
2050 fn shard_path_errors_when_sharding_type_has_no_date() {
2051 let dir = empty_store();
2052 let store = open(&dir);
2053 // expense shards, but no `date` and no `created` → NoShardDate.
2054 let err = store
2055 .shard_path_for("expense", &Frontmatter::default(), "mystery")
2056 .unwrap_err();
2057 match err {
2058 StoreError::NoShardDate { file } => {
2059 assert_eq!(file, PathBuf::from("records/expenses/mystery.md"));
2060 }
2061 other => panic!("expected NoShardDate, got {other:?}"),
2062 }
2063 }
2064
2065 // ── find_links_to ────────────────────────────────────────────────────────
2066
2067 #[test]
2068 fn find_links_to_matches_all_accepted_spellings() {
2069 let dir = empty_store();
2070 let root = dir.path();
2071 let target = "records/contacts/sarah-chen";
2072
2073 // Plain link.
2074 write(
2075 root,
2076 "records/profiles/sarah.md",
2077 &format!(
2078 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[{target}]].\n"
2079 ),
2080 );
2081 // Link with display text.
2082 write(
2083 root,
2084 "records/meetings/2026/05/m.md",
2085 &format!("---\ntype: meeting\nsummary: s\n---\nWith [[{target}|Sarah]].\n"),
2086 );
2087 // Link with .md extension (accepted, warned by validate).
2088 write(
2089 root,
2090 "records/concepts/t.md",
2091 &format!(
2092 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[{target}.md]]\n"
2093 ),
2094 );
2095 // A catalog/index file also contains the link literally — included.
2096 write(
2097 root,
2098 "records/contacts/index.md",
2099 &format!("---\ntype: index\n---\n- [[{target}]] — Sarah\n"),
2100 );
2101 // No link to the target.
2102 write(
2103 root,
2104 "records/profiles/elena.md",
2105 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nNo links here.\n",
2106 );
2107 // Short-form link must NOT match the full-path target.
2108 write(
2109 root,
2110 "records/profiles/bob.md",
2111 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\n[[sarah-chen]]\n",
2112 );
2113 // A longer path that merely starts with the target must NOT match
2114 // (boundary correctness): target `sarah-chen` vs `sarah-chen-jr`.
2115 write(
2116 root,
2117 "records/profiles/jr.md",
2118 &format!(
2119 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\n[[{target}-jr]]\n"
2120 ),
2121 );
2122
2123 let store = open(&dir);
2124 let got = rels(&store.find_links_to(Path::new(target)).unwrap());
2125 assert_eq!(
2126 got,
2127 vec![
2128 "records/concepts/t.md".to_string(),
2129 "records/contacts/index.md".to_string(),
2130 "records/meetings/2026/05/m.md".to_string(),
2131 "records/profiles/sarah.md".to_string(),
2132 ]
2133 );
2134 }
2135
2136 #[test]
2137 fn find_links_to_distinguishes_sibling_paths() {
2138 // Two contacts whose paths share a prefix; a link to one must not be
2139 // reported as a link to the other.
2140 let dir = empty_store();
2141 let root = dir.path();
2142 write(
2143 root,
2144 "records/concepts/a.md",
2145 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah]]\n",
2146 );
2147 write(
2148 root,
2149 "records/concepts/b.md",
2150 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
2151 );
2152 let store = open(&dir);
2153
2154 assert_eq!(
2155 rels(
2156 &store
2157 .find_links_to(Path::new("records/contacts/sarah"))
2158 .unwrap()
2159 ),
2160 vec!["records/concepts/a.md".to_string()]
2161 );
2162 assert_eq!(
2163 rels(
2164 &store
2165 .find_links_to(Path::new("records/contacts/sarah-chen"))
2166 .unwrap()
2167 ),
2168 vec!["records/concepts/b.md".to_string()]
2169 );
2170 }
2171
2172 #[test]
2173 fn regression_find_links_to_tolerates_invalid_utf8_on_a_matched_line() {
2174 // Regression: a `.md` file can carry a stray non-UTF-8 byte on the SAME
2175 // line as a `[[target]]` link (a verbatim-ingested `sources/` artifact,
2176 // e.g. a mis-decoded Latin-1 import). The scan must still report the
2177 // link — `find_links_to` / `find_links_to_any` (and `graph backlinks` +
2178 // the working-set validate incoming-linker pass) must not error out and
2179 // drop the legitimate UTF-8 linkers. The content scan reads the file
2180 // with `String::from_utf8_lossy`, so the invalid byte becomes a
2181 // replacement char and the ASCII `[[target]]` link is still extracted.
2182 let dir = empty_store();
2183 let root = dir.path();
2184 let target = "records/contacts/sarah-chen";
2185
2186 // A clean, fully-UTF-8 linker that MUST be returned regardless.
2187 write(
2188 root,
2189 "records/profiles/clean.md",
2190 &format!(
2191 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[{target}]].\n"
2192 ),
2193 );
2194
2195 // A linker whose link line ALSO carries a stray 0xFF byte (a mis-decoded
2196 // Latin-1 import). Write raw bytes so the invalid byte survives — a
2197 // `&str` fixture could not express it. The byte-level regex still
2198 // matches `[[target]]` on this line; pre-fix the UTF8 sink aborted here.
2199 let mut bytes: Vec<u8> =
2200 b"---\ntype: email\nsummary: s\n---\nSee [[records/contacts/sarah-chen]] \xFF here\n"
2201 .to_vec();
2202 let dirty_abs = root.join("sources/emails/2026/05/raw.md");
2203 fs::create_dir_all(dirty_abs.parent().unwrap()).unwrap();
2204 fs::write(&dirty_abs, &bytes).unwrap();
2205 // Defensive: confirm the fixture really is invalid UTF-8 (so the test
2206 // exercises the bug, not a coincidentally-valid file).
2207 assert!(
2208 std::str::from_utf8(&bytes).is_err(),
2209 "fixture must contain invalid UTF-8 to exercise the regression"
2210 );
2211 bytes.clear();
2212
2213 let store = open(&dir);
2214 let got = rels(
2215 &store
2216 .find_links_to(Path::new(target))
2217 .expect("a stray non-UTF-8 byte must not abort the backlink scan"),
2218 );
2219 assert_eq!(
2220 got,
2221 vec![
2222 "records/profiles/clean.md".to_string(),
2223 "sources/emails/2026/05/raw.md".to_string(),
2224 ],
2225 "both the clean linker and the one with an invalid byte on the link \
2226 line are reported; the scan degrades, it does not fail"
2227 );
2228 }
2229
2230 // ── find_links_to_any (batch — the O(changed × store) fix) ─────────────────
2231
2232 /// The working-set validate's incoming-linker discovery runs through
2233 /// `find_links_to_any` over the WHOLE changed set in one pass. This pins the
2234 /// batch contract that makes that single-pass behavior correct: the result is
2235 /// the union of incoming linkers across every target, with per-target
2236 /// boundary correctness preserved (no alternation arm bleeds into a
2237 /// prefix-sharing sibling). If a regression reverts the batch finder to a
2238 /// per-object loop, the union below would still hold — but the boundary +
2239 /// union-equivalence assertions are what guard the *correctness* of folding N
2240 /// scans into one regex.
2241 #[test]
2242 fn find_links_to_any_returns_the_union_with_boundary_correctness() {
2243 let dir = empty_store();
2244 let root = dir.path();
2245
2246 // Two distinct targets, each with its own linker.
2247 write(
2248 root,
2249 "records/concepts/links-sarah.md",
2250 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
2251 );
2252 write(
2253 root,
2254 "records/concepts/links-acme.md",
2255 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\nDeal with [[records/companies/acme|Acme]].\n",
2256 );
2257 // One file links to BOTH targets — must appear exactly once (deduped),
2258 // proving the per-file early-exit folds multiple-target hits into a
2259 // single result row rather than one row per matched target.
2260 write(
2261 root,
2262 "records/meetings/2026/05/m.md",
2263 "---\ntype: meeting\nsummary: s\n---\n[[records/contacts/sarah-chen]] re \
2264 [[records/companies/acme]]\n",
2265 );
2266 // A prefix-sharing sibling of a target: a link to `sarah-chen-jr` must NOT
2267 // be reported as a link to `sarah-chen` even though the alternation now
2268 // carries `sarah-chen` as one arm.
2269 write(
2270 root,
2271 "records/concepts/links-jr.md",
2272 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen-jr]]\n",
2273 );
2274 // A file that links to neither requested target.
2275 write(
2276 root,
2277 "records/concepts/unrelated.md",
2278 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/concepts/spend]]\n",
2279 );
2280
2281 let store = open(&dir);
2282 let targets = vec![
2283 PathBuf::from("records/contacts/sarah-chen"),
2284 PathBuf::from("records/companies/acme"),
2285 ];
2286
2287 let got = rels(&store.find_links_to_any(&targets).unwrap());
2288 assert_eq!(
2289 got,
2290 vec![
2291 "records/concepts/links-acme.md".to_string(),
2292 "records/concepts/links-sarah.md".to_string(),
2293 "records/meetings/2026/05/m.md".to_string(),
2294 ],
2295 "batch finder must return the deduped union of linkers across all \
2296 targets, excluding the prefix-sibling and the unrelated file"
2297 );
2298
2299 // Equivalence: the batch result must equal the union of the per-target
2300 // single finder. This is the property the working-set path relies on
2301 // when it folds one-scan-per-object into one scan for the whole set.
2302 let mut union: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
2303 for t in &targets {
2304 for linker in store.find_links_to(t).unwrap() {
2305 union.insert(linker);
2306 }
2307 }
2308 assert_eq!(
2309 rels(&union.into_iter().collect::<Vec<_>>()),
2310 got,
2311 "find_links_to_any must equal the union of per-target find_links_to"
2312 );
2313 }
2314
2315 /// An empty target set must scan nothing and find nothing — and crucially
2316 /// must NOT compile to a match-everything empty regex (which would report
2317 /// every `.md` as a linker). This is the empty-working-set fast path the
2318 /// `validate` loop hits when nothing changed.
2319 #[test]
2320 fn find_links_to_any_empty_targets_matches_nothing() {
2321 let dir = empty_store();
2322 let root = dir.path();
2323 write(
2324 root,
2325 "records/concepts/a.md",
2326 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n[[records/contacts/sarah-chen]]\n",
2327 );
2328 let store = open(&dir);
2329
2330 assert!(
2331 store.find_links_to_any(&[]).unwrap().is_empty(),
2332 "no targets ⇒ no linkers (an empty pattern must not match every file)"
2333 );
2334 // A set of only empty/non-link targets is likewise a no-op, not a
2335 // match-everything.
2336 assert!(
2337 store
2338 .find_links_to_any(&[PathBuf::from(""), PathBuf::from("./")])
2339 .unwrap()
2340 .is_empty(),
2341 "targets that render to empty link text contribute no alternation arm"
2342 );
2343 }
2344
2345 // ── read_type_index ──────────────────────────────────────────────────────
2346
2347 #[test]
2348 fn read_type_index_parses_records_and_flattens_fields() {
2349 let dir = empty_store();
2350 let root = dir.path();
2351 let jsonl = "\
2352{\"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}
2353{\"path\":\"records/expenses/2026/05/b.md\",\"type\":\"expense\",\"summary\":\"taxi\",\"created\":null,\"updated\":null,\"vendor\":\"yellow\"}
2354";
2355 let p = write(root, "records/expenses/index.jsonl", jsonl);
2356 let store = open(&dir);
2357 let recs = store.read_type_index(&store.abs_path(&p)).unwrap();
2358
2359 assert_eq!(recs.len(), 2);
2360 // Sorted by path asc.
2361 assert_eq!(recs[0].path, PathBuf::from("records/expenses/2026/05/a.md"));
2362 assert_eq!(recs[0].type_, "expense");
2363 assert_eq!(recs[0].summary, "lunch");
2364 assert_eq!(recs[0].tags, vec!["meals".to_string()]);
2365 assert_eq!(recs[0].links, vec!["records/companies/acme".to_string()]);
2366 assert!(recs[0].created.is_some());
2367 // Extra (non-typed) frontmatter flattens into `fields`.
2368 assert_eq!(
2369 recs[0].fields.get("vendor"),
2370 Some(&serde_json::json!("acme"))
2371 );
2372 assert_eq!(recs[0].fields.get("amount"), Some(&serde_json::json!(42)));
2373 // Defaults: missing tags/links → empty.
2374 assert!(recs[1].tags.is_empty());
2375 assert!(recs[1].links.is_empty());
2376 }
2377
2378 #[test]
2379 fn read_type_index_last_write_wins_and_skips_blanks() {
2380 let dir = empty_store();
2381 let root = dir.path();
2382 // Same path twice; the second line supersedes the first. A blank line
2383 // in between must be ignored, not error.
2384 let jsonl = "\
2385{\"path\":\"records/contacts/sarah.md\",\"type\":\"contact\",\"summary\":\"old\",\"created\":null,\"updated\":null}
2386
2387{\"path\":\"records/contacts/sarah.md\",\"type\":\"contact\",\"summary\":\"new\",\"created\":null,\"updated\":null}
2388";
2389 let p = write(root, "records/contacts/index.jsonl", jsonl);
2390 let store = open(&dir);
2391 let recs = store.read_type_index(&store.abs_path(&p)).unwrap();
2392 assert_eq!(recs.len(), 1, "duplicate path collapses to one record");
2393 assert_eq!(recs[0].summary, "new", "later line must win");
2394 }
2395
2396 #[test]
2397 fn read_type_index_errors_on_malformed_line() {
2398 let dir = empty_store();
2399 let root = dir.path();
2400 let p = write(root, "records/contacts/index.jsonl", "{not valid json}\n");
2401 let store = open(&dir);
2402 let err = store.read_type_index(&store.abs_path(&p)).unwrap_err();
2403 assert!(matches!(err, StoreError::BadTypeIndex { .. }));
2404 }
2405
2406 // ── find_by_type / find_by_where ─────────────────────────────────────────
2407
2408 fn jsonl_line(path: &str, type_: &str, summary: &str, extra: &str) -> String {
2409 format!(
2410 "{{\"path\":\"{path}\",\"type\":\"{type_}\",\"summary\":\"{summary}\",\"created\":null,\"updated\":null{extra}}}\n"
2411 )
2412 }
2413
2414 #[test]
2415 fn find_by_type_reads_canonical_folder_sidecar() {
2416 let dir = empty_store();
2417 let root = dir.path();
2418 // Canonical folder for `contact` is records/contacts.
2419 write(
2420 root,
2421 "records/contacts/index.jsonl",
2422 &(jsonl_line("records/contacts/sarah.md", "contact", "Sarah", "")
2423 + &jsonl_line("records/contacts/elena.md", "contact", "Elena", "")),
2424 );
2425 // A different type's sidecar must not leak into a contact query.
2426 write(
2427 root,
2428 "records/companies/index.jsonl",
2429 &jsonl_line("records/companies/acme.md", "company", "Acme", ""),
2430 );
2431 let store = open(&dir);
2432 let recs = store.find_by_type("contact").unwrap();
2433 let names: Vec<_> = recs.iter().map(|r| r.summary.clone()).collect();
2434 assert_eq!(names, vec!["Elena".to_string(), "Sarah".to_string()]); // path-sorted
2435 assert!(recs.iter().all(|r| r.type_ == "contact"));
2436 }
2437
2438 #[test]
2439 fn regression_find_by_type_includes_non_canonical_folder_when_canonical_exists() {
2440 // Regression for the silent-incompleteness bug: once the canonical
2441 // type-folder sidecar exists, `find_by_type` used to read ONLY that
2442 // sidecar and drop same-type records filed in a non-canonical folder in
2443 // the SAME layer — so the result flipped to incomplete the moment a
2444 // canonical record was added. The write path actively enables such a
2445 // layout (`records/clients/` for a `contact`, any `records/<folder>/`
2446 // for a conclusion `profile`), so this is a reachable, dedup-breaking
2447 // omission.
2448 let dir = empty_store();
2449 let root = dir.path();
2450
2451 // CANONICAL folder sidecar exists (`records/contacts/` for `contact`),
2452 // which is exactly the condition that triggered the bug.
2453 write(
2454 root,
2455 "records/contacts/index.jsonl",
2456 &jsonl_line("records/contacts/sarah.md", "contact", "Sarah", ""),
2457 );
2458 // A `contact` filed in a NON-canonical folder within the same (Records)
2459 // layer. Pre-fix this was silently dropped because the canonical
2460 // sidecar existed; it must now come back.
2461 write(
2462 root,
2463 "records/clients/index.jsonl",
2464 &jsonl_line("records/clients/elena.md", "contact", "Elena", ""),
2465 );
2466 // A different type in the same layer must NOT leak in (proves the read
2467 // is type-filtered, not just a blind whole-layer dump).
2468 write(
2469 root,
2470 "records/companies/index.jsonl",
2471 &jsonl_line("records/companies/acme.md", "company", "Acme", ""),
2472 );
2473
2474 let store = open(&dir);
2475 let got: std::collections::BTreeSet<String> = store
2476 .find_by_type("contact")
2477 .unwrap()
2478 .into_iter()
2479 .map(|r| r.path.to_string_lossy().into_owned())
2480 .collect();
2481 assert_eq!(
2482 got,
2483 ["records/clients/elena.md", "records/contacts/sarah.md"]
2484 .into_iter()
2485 .map(String::from)
2486 .collect::<std::collections::BTreeSet<_>>(),
2487 "both the canonical-folder and the non-canonical-folder contact must \
2488 be returned; the company record must be excluded"
2489 );
2490 }
2491
2492 #[test]
2493 fn regression_find_by_type_profile_spans_multiple_topic_folders() {
2494 // Regression for the scoped-backlinks variant of the same bug
2495 // (`graph backlinks --type <conclusion-type>`): a conclusion type like
2496 // `profile` has the canonical fallback folder `records/profile`, but the
2497 // agent may file profiles under ANY records topic folder
2498 // (`records/people/`, `records/clients/`, …). With a
2499 // `records/profile/index.jsonl` present, the old code read only that
2500 // folder and dropped profiles in the other topic folders —
2501 // under-reporting dependents in a blast-radius check. The
2502 // whole-`records/`-layer read must surface all of them.
2503 let dir = empty_store();
2504 let root = dir.path();
2505 write(
2506 root,
2507 "records/profile/index.jsonl",
2508 &jsonl_line("records/profile/billing.md", "profile", "Billing", ""),
2509 );
2510 write(
2511 root,
2512 "records/people/index.jsonl",
2513 &jsonl_line("records/people/sarah-chen.md", "profile", "Sarah Chen", ""),
2514 );
2515 write(
2516 root,
2517 "records/clients/index.jsonl",
2518 &jsonl_line("records/clients/atlas.md", "profile", "Atlas", ""),
2519 );
2520
2521 let store = open(&dir);
2522 let got: std::collections::BTreeSet<String> = store
2523 .find_by_type("profile")
2524 .unwrap()
2525 .into_iter()
2526 .map(|r| r.path.to_string_lossy().into_owned())
2527 .collect();
2528 assert_eq!(
2529 got,
2530 [
2531 "records/clients/atlas.md",
2532 "records/people/sarah-chen.md",
2533 "records/profile/billing.md",
2534 ]
2535 .into_iter()
2536 .map(String::from)
2537 .collect::<std::collections::BTreeSet<_>>(),
2538 "a profile query must return records from every topic folder, not \
2539 just the canonical records/profile/"
2540 );
2541 }
2542
2543 #[test]
2544 fn find_by_type_canonical_absent_falls_back_within_the_layer_only() {
2545 let dir = empty_store();
2546 let root = dir.path();
2547 // A custom `proposal` record filed under a non-canonical folder NAME
2548 // (the natural plural `records/proposals/`) inside the records layer.
2549 // `default_type_folder("proposal")` = `records/proposal` (bare type, no
2550 // pluralization guess), so the canonical sidecar does not exist and
2551 // `find_by_type` falls back. The fallback is bounded to the type's
2552 // layer (records), so this record — same layer, non-canonical folder —
2553 // is still found: completeness within the layer holds.
2554 write(
2555 root,
2556 "records/proposals/index.jsonl",
2557 &jsonl_line("records/proposals/p1.md", "proposal", "Q3 proposal", ""),
2558 );
2559 // A DECOY of the SAME type sitting in a DIFFERENT layer (sources/). The
2560 // old whole-store fallback read every sidecar in the store and would
2561 // have leaked this into the result; the layer-bounded fallback must not.
2562 // It also pins that the fallback is O(entities-in-layer), never O(store).
2563 write(
2564 root,
2565 "sources/proposals/index.jsonl",
2566 &jsonl_line(
2567 "sources/proposals/leak.md",
2568 "proposal",
2569 "cross-layer decoy",
2570 "",
2571 ),
2572 );
2573 let store = open(&dir);
2574 let recs = store.find_by_type("proposal").unwrap();
2575 assert_eq!(
2576 recs.len(),
2577 1,
2578 "only the records-layer proposal, not the sources decoy"
2579 );
2580 assert_eq!(recs[0].summary, "Q3 proposal");
2581 assert_eq!(recs[0].path, PathBuf::from("records/proposals/p1.md"));
2582 }
2583
2584 #[test]
2585 fn find_by_type_canonical_absent_does_not_read_other_layers() {
2586 let dir = empty_store();
2587 let root = dir.path();
2588 // `email`'s canonical folder is `sources/emails` (layer Sources). No
2589 // sidecar there yet, so `find_by_type("email")` falls back — but only
2590 // within the Sources layer. A populated sidecar in the Records layer
2591 // must never be touched: the fallback is layer-bounded, not store-wide.
2592 // Under the old `read_all_type_indexes_in(None)` fallback this records
2593 // sidecar would have been read and filtered (wasted O(store) I/O); now
2594 // it is outside the walk root entirely.
2595 write(
2596 root,
2597 "records/contacts/index.jsonl",
2598 &jsonl_line("records/contacts/sarah.md", "contact", "Sarah", ""),
2599 );
2600 let store = open(&dir);
2601 // No email anywhere ⇒ empty, and the records layer was not in scope.
2602 assert!(store.find_by_type("email").unwrap().is_empty());
2603 }
2604
2605 #[test]
2606 fn find_by_where_matches_typed_columns_and_flat_fields() {
2607 let dir = empty_store();
2608 let root = dir.path();
2609 write(
2610 root,
2611 "records/expenses/index.jsonl",
2612 &(jsonl_line(
2613 "records/expenses/a.md",
2614 "expense",
2615 "lunch",
2616 ",\"vendor\":\"acme\",\"tags\":[\"meals\"]",
2617 ) + &jsonl_line(
2618 "records/expenses/b.md",
2619 "expense",
2620 "taxi",
2621 ",\"vendor\":\"yellow\"",
2622 )),
2623 );
2624 write(
2625 root,
2626 "records/contacts/index.jsonl",
2627 &jsonl_line(
2628 "records/contacts/sarah.md",
2629 "contact",
2630 "Sarah",
2631 ",\"tags\":[\"customer\"]",
2632 ),
2633 );
2634 let store = open(&dir);
2635
2636 // Flat field in `fields`.
2637 let by_vendor = store.find_by_where("vendor", "acme").unwrap();
2638 assert_eq!(by_vendor.len(), 1);
2639 assert_eq!(by_vendor[0].path, PathBuf::from("records/expenses/a.md"));
2640
2641 // Typed column: type (spans both expense records).
2642 assert_eq!(store.find_by_where("type", "expense").unwrap().len(), 2);
2643
2644 // Typed list column: tags membership.
2645 let customers = store.find_by_where("tags", "customer").unwrap();
2646 assert_eq!(customers.len(), 1);
2647 assert_eq!(
2648 customers[0].path,
2649 PathBuf::from("records/contacts/sarah.md")
2650 );
2651
2652 // No match → empty.
2653 assert!(store.find_by_where("vendor", "nobody").unwrap().is_empty());
2654 }
2655
2656 #[test]
2657 fn find_by_where_matches_timestamps_across_rfc3339_spellings() {
2658 let dir = empty_store();
2659 let root = dir.path();
2660 // db.md files most commonly carry the `Z` UTC spelling. The index.jsonl
2661 // serialized from such a file preserves it verbatim.
2662 write(
2663 root,
2664 "records/meetings/index.jsonl",
2665 "{\"path\":\"records/meetings/kickoff.md\",\"type\":\"meeting\",\
2666\"summary\":\"kickoff\",\"created\":\"2026-05-01T00:00:00Z\",\
2667\"updated\":\"2026-05-02T09:30:00-07:00\"}\n",
2668 );
2669 let store = open(&dir);
2670
2671 // The exact value an agent reads out of the file (`Z` form) must match.
2672 let by_z = store
2673 .find_by_where("created", "2026-05-01T00:00:00Z")
2674 .unwrap();
2675 assert_eq!(by_z.len(), 1);
2676 assert_eq!(by_z[0].path, PathBuf::from("records/meetings/kickoff.md"));
2677
2678 // The equivalent explicit-offset spelling of the same instant matches too.
2679 assert_eq!(
2680 store
2681 .find_by_where("created", "2026-05-01T00:00:00+00:00")
2682 .unwrap()
2683 .len(),
2684 1
2685 );
2686
2687 // A non-UTC stored value matches both its own offset spelling and the
2688 // same instant expressed as `Z` (instant comparison, not string compare).
2689 assert_eq!(
2690 store
2691 .find_by_where("updated", "2026-05-02T09:30:00-07:00")
2692 .unwrap()
2693 .len(),
2694 1
2695 );
2696 assert_eq!(
2697 store
2698 .find_by_where("updated", "2026-05-02T16:30:00Z")
2699 .unwrap()
2700 .len(),
2701 1
2702 );
2703
2704 // A different instant does not match.
2705 assert!(store
2706 .find_by_where("created", "2026-05-01T00:00:01Z")
2707 .unwrap()
2708 .is_empty());
2709 // A non-RFC3339 query value never matches a real timestamp.
2710 assert!(store
2711 .find_by_where("created", "2026-05-01")
2712 .unwrap()
2713 .is_empty());
2714 }
2715
2716 #[test]
2717 fn find_by_where_matches_floats_across_serialized_spellings() {
2718 // Adversarial review #5: a float field is stored in index.jsonl via
2719 // serde_json's canonical f64 render, which DISCARDS the file's source
2720 // spelling (`1234.00` -> `1234.0`, `1e3` -> `1000.0`). A textual compare
2721 // made the spelling a human reads in the file miss (and disagree with
2722 // free-text `search`); numeric compare fixes it. `fm query`/`index query`
2723 // is the SPEC pre-write dedup primitive, so a miss here silently writes a
2724 // duplicate record.
2725 let dir = empty_store();
2726 let root = dir.path();
2727 write(
2728 root,
2729 "records/invoices/index.jsonl",
2730 "{\"path\":\"records/invoices/inv.md\",\"type\":\"invoice\",\
2731\"summary\":\"inv\",\"amount\":1234.0,\"score\":1000.0,\"count\":42}\n",
2732 );
2733 let store = open(&dir);
2734
2735 // Every spelling of the same numeric value matches the canonical-f64 store.
2736 for spelling in ["1234.00", "1234.0", "1234"] {
2737 assert_eq!(
2738 store.find_by_where("amount", spelling).unwrap().len(),
2739 1,
2740 "amount spelling `{spelling}` must match the stored 1234.0"
2741 );
2742 }
2743 for spelling in ["1e3", "1000", "1000.0"] {
2744 assert_eq!(
2745 store.find_by_where("score", spelling).unwrap().len(),
2746 1,
2747 "score spelling `{spelling}` must match the stored 1000.0"
2748 );
2749 }
2750 // A genuinely different value does not match.
2751 assert!(store.find_by_where("amount", "1234.5").unwrap().is_empty());
2752 // Integer fields keep exact textual matching (unaffected by the fix).
2753 assert_eq!(store.find_by_where("count", "42").unwrap().len(), 1);
2754 }
2755
2756 #[test]
2757 fn number_matches_is_numeric_for_floats_but_exact_for_integers() {
2758 use serde_json::Number;
2759 // Float-valued field: any equal spelling matches (the bug fix).
2760 let f: Number = serde_json::from_str("1234.0").unwrap();
2761 assert!(number_matches(&f, "1234.00"));
2762 assert!(number_matches(&f, "1234"));
2763 assert!(number_matches(&f, "1234.0"));
2764 assert!(!number_matches(&f, "1234.5"));
2765 // Integer-valued field: EXACT textual compare, never f64-rounded — two
2766 // adjacent large integers that round to the same f64 must NOT collide
2767 // (the safety property that motivates restricting numeric compare to
2768 // floats).
2769 let big: Number = serde_json::from_str("18446744073709551615").unwrap(); // u64::MAX
2770 assert!(number_matches(&big, "18446744073709551615"));
2771 assert!(!number_matches(&big, "18446744073709551614"));
2772 }
2773
2774 #[test]
2775 fn find_by_where_in_layer_reads_only_that_layers_sidecars() {
2776 // The O(entities-in-layer) contract: a layer-scoped where read must walk
2777 // ONLY the named layer's subtree. Proven structurally — a *malformed*
2778 // sidecar in another layer would make `read_type_index` error if it were
2779 // read, so a scoped read that succeeds (and excludes that record) is
2780 // proof the other layer's I/O never happened.
2781 let dir = empty_store();
2782 let root = dir.path();
2783 write(
2784 root,
2785 "records/companies/index.jsonl",
2786 &jsonl_line(
2787 "records/companies/acme.md",
2788 "company",
2789 "Acme",
2790 ",\"domain\":\"acme.com\"",
2791 ),
2792 );
2793 // Same field/value in the sources layer — but the sidecar is corrupt.
2794 write(
2795 root,
2796 "sources/emails/index.jsonl",
2797 "{ this is not valid json and would error if read }\n",
2798 );
2799 let store = open(&dir);
2800
2801 // Scoped to records: the corrupt sources sidecar is out of scope, so the
2802 // read succeeds and returns only the records-layer match.
2803 let in_records = store
2804 .find_by_where_in("domain", "acme.com", Some(Layer::Records))
2805 .expect("a records-scoped read must not touch the sources sidecar");
2806 assert_eq!(
2807 rels(
2808 &in_records
2809 .iter()
2810 .map(|r| r.path.clone())
2811 .collect::<Vec<_>>()
2812 ),
2813 vec!["records/companies/acme.md".to_string()]
2814 );
2815
2816 // The store-wide read DOES reach the corrupt sidecar and surfaces it as
2817 // a parse error — confirming the corrupt file is genuinely in the tree
2818 // and that only the layer scope spares it.
2819 let store_wide = store.find_by_where("domain", "acme.com");
2820 assert!(
2821 matches!(store_wide, Err(StoreError::BadTypeIndex { .. })),
2822 "unscoped read walks every layer and hits the corrupt sidecar"
2823 );
2824
2825 // Scoping to the layer that holds only the corrupt sidecar still errors
2826 // (the scope includes it), proving the scope is a real subtree bound and
2827 // not a silent "skip anything that fails".
2828 let in_sources = store.find_by_where_in("domain", "acme.com", Some(Layer::Sources));
2829 assert!(matches!(in_sources, Err(StoreError::BadTypeIndex { .. })));
2830 }
2831
2832 #[test]
2833 fn find_by_where_in_missing_layer_is_empty_not_an_error() {
2834 // A layer-scoped read over a layer folder that does not exist yet must
2835 // return empty (mirrors `walk_layer`'s missing-dir guard), never a walk
2836 // error from `ignore` over a nonexistent path.
2837 let dir = empty_store();
2838 let root = dir.path();
2839 write(
2840 root,
2841 "records/contacts/index.jsonl",
2842 &jsonl_line(
2843 "records/contacts/sarah.md",
2844 "contact",
2845 "Sarah",
2846 ",\"city\":\"denver\"",
2847 ),
2848 );
2849 let store = open(&dir);
2850
2851 // `sources/` was never created.
2852 let in_sources = store
2853 .find_by_where_in("city", "denver", Some(Layer::Sources))
2854 .expect("missing layer subtree is empty, not an error");
2855 assert!(in_sources.is_empty());
2856
2857 // Same query scoped to the layer that has the record still finds it.
2858 let in_records = store
2859 .find_by_where_in("city", "denver", Some(Layer::Records))
2860 .unwrap();
2861 assert_eq!(in_records.len(), 1);
2862 }
2863
2864 // ── abs_path / rel_path ──────────────────────────────────────────────────
2865
2866 #[test]
2867 fn abs_and_rel_path_roundtrip() {
2868 let dir = empty_store();
2869 let store = open(&dir);
2870 let rel = Path::new("records/contacts/sarah.md");
2871 let abs = store.abs_path(rel);
2872 assert_eq!(abs, dir.path().join(rel));
2873 assert_eq!(store.rel_path(&abs).as_deref(), Some(rel));
2874
2875 // An absolute path is passed through unchanged by abs_path.
2876 assert_eq!(store.abs_path(&abs), abs);
2877
2878 // A path outside the store has no store-relative form.
2879 assert_eq!(store.rel_path(Path::new("/somewhere/else.md")), None);
2880 }
2881
2882 // ── infer_type_from_path (inverse of default_type_folder) ────────────────
2883
2884 #[test]
2885 fn infer_type_maps_every_recognized_folder_back_to_its_type() {
2886 let cases = [
2887 ("sources/emails/x.md", "email"),
2888 ("sources/transcripts/x.md", "transcript"),
2889 ("sources/docs/x.md", "pdf-source"),
2890 ("sources/notes/x.md", "note"),
2891 ("records/contacts/x.md", "contact"),
2892 ("records/companies/x.md", "company"),
2893 ("records/expenses/x.md", "expense"),
2894 ("records/meetings/x.md", "meeting"),
2895 ("records/decisions/x.md", "decision"),
2896 ("records/invoices/x.md", "invoice"),
2897 ];
2898 for (path, expected) in cases {
2899 assert_eq!(
2900 infer_type_from_path(Path::new(path)).as_deref(),
2901 Some(expected),
2902 "path {path} should infer type {expected}"
2903 );
2904 }
2905 }
2906
2907 #[test]
2908 fn infer_type_round_trips_with_default_type_folder() {
2909 // The canonical invariant: inference is the inverse of the forward map.
2910 // Every recognized type, routed through `default_type_folder` and then
2911 // back through `infer_type_from_path`, must return the original type.
2912 let recognized = [
2913 "email",
2914 "transcript",
2915 "pdf-source",
2916 "contact",
2917 "company",
2918 "expense",
2919 "meeting",
2920 "decision",
2921 "invoice",
2922 ];
2923 for type_ in recognized {
2924 let folder = default_type_folder(type_);
2925 let file = folder.join("x.md");
2926 assert_eq!(
2927 infer_type_from_path(&file).as_deref(),
2928 Some(type_),
2929 "recognized type {type_} (folder {folder:?}) must round-trip"
2930 );
2931 }
2932 }
2933
2934 #[test]
2935 fn infer_type_round_trips_custom_types_verbatim_no_singularization() {
2936 // Regression guard for the CLI/core divergence: `default_type_folder`'s
2937 // unrecognized fallback is the BARE type name (`task → records/task`,
2938 // `tasks → records/tasks`). Inference must NOT singularize, or a custom
2939 // type would not round-trip (e.g. `records/tasks` → `task` would clash
2940 // with `default_type_folder("task") → records/task`).
2941 for custom in ["task", "tasks", "playbook", "process", "okrs", "ticket"] {
2942 let folder = default_type_folder(custom);
2943 assert_eq!(folder, PathBuf::from("records").join(custom));
2944 let file = folder.join("x.md");
2945 assert_eq!(
2946 infer_type_from_path(&file).as_deref(),
2947 Some(custom),
2948 "custom type {custom} must round-trip verbatim (no singularization)"
2949 );
2950 }
2951
2952 // The specific case named in the finding: a plural custom folder keeps
2953 // its trailing `s`; it is NOT singularized to `task`.
2954 assert_eq!(
2955 infer_type_from_path(Path::new("records/tasks/x.md")).as_deref(),
2956 Some("tasks"),
2957 "records/tasks must infer `tasks`, not `task`"
2958 );
2959 }
2960
2961 #[test]
2962 fn infer_type_requires_three_component_layer_folder_file_shape() {
2963 // Fewer than 3 components: a file directly under a layer has no
2964 // type-folder, so inference yields None (matches the old CLI contract).
2965 assert_eq!(infer_type_from_path(Path::new("records/x.md")), None);
2966 assert_eq!(infer_type_from_path(Path::new("sources/x.md")), None);
2967 assert_eq!(infer_type_from_path(Path::new("x.md")), None);
2968 // Unknown leading layer is never inferred.
2969 assert_eq!(infer_type_from_path(Path::new("foo/bar/x.md")), None);
2970 // Deeper paths still infer from the first type-folder segment (e.g. a
2971 // sharded record under records/expenses/2026/05/x.md).
2972 assert_eq!(
2973 infer_type_from_path(Path::new("records/expenses/2026/05/x.md")).as_deref(),
2974 Some("expense"),
2975 );
2976 }
2977
2978 // ── ensure_path_within_store (containment) ───────────────────────────────
2979
2980 #[test]
2981 fn ensure_path_within_store_accepts_in_store_and_rejects_escape() {
2982 let dir = tempdir().unwrap();
2983 let root = dir.path();
2984 fs::create_dir_all(root.join("records/contacts")).unwrap();
2985 fs::write(root.join("records/contacts/sarah.md"), "x").unwrap();
2986
2987 // An existing in-store file resolves and is accepted.
2988 let inside = root.join("records/contacts/sarah.md");
2989 let got = ensure_path_within_store(root, &inside).expect("in-store path accepted");
2990 // Canonical, but still under the (canonical) root.
2991 assert!(got.starts_with(root.canonicalize().unwrap()));
2992
2993 // A not-yet-existing in-store leaf is accepted (rename destination).
2994 let new_leaf = root.join("records/contacts/sarah-chen.md");
2995 assert!(
2996 ensure_path_within_store(root, &new_leaf).is_ok(),
2997 "a non-existent in-store leaf must be accepted"
2998 );
2999
3000 // A `..`-escaping path is rejected even though its prefix exists.
3001 let escape = root.join("records/contacts/../../outside/secret.md");
3002 assert!(
3003 ensure_path_within_store(root, &escape).is_err(),
3004 "a `..`-escaping path must be rejected"
3005 );
3006 }
3007
3008 #[test]
3009 fn ensure_path_within_store_rejects_symlink_escape() {
3010 let dir = tempdir().unwrap();
3011 let root = dir.path().join("store");
3012 fs::create_dir_all(&root).unwrap();
3013 let outside_dir = dir.path().join("outside");
3014 fs::create_dir_all(&outside_dir).unwrap();
3015 let secret = outside_dir.join("secret.md");
3016 fs::write(&secret, "TOPSECRET").unwrap();
3017
3018 // A symlink inside the store that points OUTSIDE it must be rejected:
3019 // resolving the symlink lands outside the canonical root.
3020 #[cfg(unix)]
3021 {
3022 use std::os::unix::fs::symlink;
3023 let link = root.join("escape.md");
3024 symlink(&secret, &link).unwrap();
3025 assert!(
3026 ensure_path_within_store(&root, &link).is_err(),
3027 "a symlink resolving outside the store must be rejected"
3028 );
3029 }
3030 }
3031
3032 // ── shared link-edge notion (fence / whitespace / case) ──────────────────
3033
3034 #[test]
3035 fn extract_edge_targets_trims_inner_whitespace() {
3036 // Padded `[[ x ]]` is the same edge as `[[x]]`.
3037 assert_eq!(
3038 extract_edge_targets("See [[ records/contacts/sarah ]] today."),
3039 vec!["records/contacts/sarah".to_string()]
3040 );
3041 }
3042
3043 #[test]
3044 fn extract_edge_targets_skips_fenced_code_blocks() {
3045 // A `[[...]]` inside a ``` fence is a doc example, NOT an edge — matching
3046 // validate's body extractor.
3047 let body = "\
3048Real [[records/contacts/sarah]] link.
3049
3050```markdown
3051[[records/contacts/ghost-example]] is how you link.
3052```
3053
3054After fence [[records/companies/acme]].
3055";
3056 let got = extract_edge_targets(body);
3057 assert_eq!(
3058 got,
3059 vec![
3060 "records/contacts/sarah".to_string(),
3061 "records/companies/acme".to_string(),
3062 ],
3063 "fenced example link must not be an edge"
3064 );
3065 }
3066
3067 #[test]
3068 fn extract_edge_targets_handles_nested_indented_and_long_run_fences() {
3069 // Regression for the naive `starts_with("```")/("~~~")` toggle: a fence
3070 // nested inside another, an over-indented (>3 space) marker, and a
3071 // long-run fence wrapping a shorter inner one must all leave the block's
3072 // links un-extracted (validate treats the whole block as opaque). The
3073 // (char, run-length) tracker keys on the OPENING fence and closes only on
3074 // a matching char with run ≥ the opener.
3075
3076 // (a) A ```` ```` ````-run block (run 4) wrapping a ``` example (run 3).
3077 // The inner ``` does NOT close the outer run-4 fence, so both `[[...]]`
3078 // inside stay fenced.
3079 let nested = "\
3080Doc:
3081
3082````
3083```
3084[[records/contacts/bob]]
3085```
3086still fenced [[records/contacts/bob]]
3087````
3088
3089Real [[records/companies/acme]].
3090";
3091 assert_eq!(
3092 extract_edge_targets(nested),
3093 vec!["records/companies/acme".to_string()],
3094 "a nested ``` inside a ````-run fence must not leak the fenced links"
3095 );
3096
3097 // (b) A `~~~` block containing a ``` line (the standard way to document a
3098 // backtick fence). The inner backtick line must not flip the state.
3099 let tilde_wraps_backtick = "\
3100~~~
3101```
3102[[records/contacts/ghost]]
3103```
3104~~~
3105
3106After [[records/companies/acme]].
3107";
3108 assert_eq!(
3109 extract_edge_targets(tilde_wraps_backtick),
3110 vec!["records/companies/acme".to_string()],
3111 "a ``` line inside a ~~~ block must not invert the fence state"
3112 );
3113
3114 // (c) An over-indented ```` ``` ```` (4 spaces) is NOT a fence; the link
3115 // on the next line is live.
3116 let over_indented = " ```\nLive [[records/contacts/sarah]].\n";
3117 assert_eq!(
3118 extract_edge_targets(over_indented),
3119 vec!["records/contacts/sarah".to_string()],
3120 "a >3-space-indented ``` is not a fence opener"
3121 );
3122 }
3123
3124 #[test]
3125 fn canonical_link_target_strips_md_dotslash_and_trims() {
3126 assert_eq!(canonical_link_target(" records/x.md "), "records/x");
3127 assert_eq!(canonical_link_target("./records/y"), "records/y");
3128 assert_eq!(canonical_link_target("/records/z"), "records/z");
3129 }
3130
3131 #[test]
3132 fn link_edge_key_folds_case_only_on_case_insensitive_fs() {
3133 let a = link_edge_key("records/contacts/Sarah-Chen");
3134 let b = link_edge_key("records/contacts/sarah-chen");
3135 if fs_is_case_insensitive() {
3136 assert_eq!(a, b, "case-insensitive FS must fold the key");
3137 } else {
3138 assert_ne!(a, b, "case-sensitive FS must keep the key case-exact");
3139 }
3140 }
3141
3142 // ── walk follows symlinked content ───────────────────────────────────────
3143
3144 #[cfg(unix)]
3145 #[test]
3146 fn walk_includes_symlinked_content_file_and_symlinked_folder() {
3147 use std::os::unix::fs::symlink;
3148 let dir = empty_store();
3149 let root = dir.path();
3150 // A regular file (control).
3151 write(
3152 root,
3153 "records/contacts/sarah.md",
3154 &content_md("2026-05-01T00:00:00Z"),
3155 );
3156 // A symlinked .md content file inside a real folder.
3157 let external_file = root.join("external-elena.md");
3158 fs::write(&external_file, content_md("2026-05-02T00:00:00Z")).unwrap();
3159 symlink(&external_file, root.join("records/contacts/elena.md")).unwrap();
3160 // A symlinked type folder.
3161 let external_dir = dir.path().join("external-companies");
3162 fs::create_dir_all(&external_dir).unwrap();
3163 fs::write(
3164 external_dir.join("acme.md"),
3165 content_md("2026-05-03T00:00:00Z"),
3166 )
3167 .unwrap();
3168 symlink(&external_dir, root.join("records/companies")).unwrap();
3169
3170 let store = open(&dir);
3171 let got = rels(&store.walk().unwrap());
3172 assert!(
3173 got.contains(&"records/contacts/elena.md".to_string()),
3174 "a symlinked content file must be walked: {got:?}"
3175 );
3176 assert!(
3177 got.contains(&"records/companies/acme.md".to_string()),
3178 "a file inside a symlinked type folder must be walked: {got:?}"
3179 );
3180 }
3181
3182 // ── find_links_to: padded / fenced / case ────────────────────────────────
3183
3184 #[test]
3185 fn find_links_to_matches_whitespace_padded_link() {
3186 let dir = empty_store();
3187 let root = dir.path();
3188 write(
3189 root,
3190 "records/profiles/a.md",
3191 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[ records/contacts/sarah ]] today.\n",
3192 );
3193 let store = open(&dir);
3194 let got = rels(
3195 &store
3196 .find_links_to(Path::new("records/contacts/sarah"))
3197 .unwrap(),
3198 );
3199 assert_eq!(
3200 got,
3201 vec!["records/profiles/a.md".to_string()],
3202 "a padded `[[ x ]]` link must be found as a backward edge, matching forwardlinks"
3203 );
3204 }
3205
3206 #[test]
3207 fn find_links_to_ignores_fenced_example_link() {
3208 let dir = empty_store();
3209 let root = dir.path();
3210 write(
3211 root,
3212 "records/concepts/howto.md",
3213 "---\ntype: concept\nmeta-type: conclusion\nsummary: s\n---\n```markdown\n[[records/contacts/sarah]]\n```\n",
3214 );
3215 let store = open(&dir);
3216 let got = store
3217 .find_links_to(Path::new("records/contacts/sarah"))
3218 .unwrap();
3219 assert!(
3220 got.is_empty(),
3221 "a `[[...]]` only inside a fenced code block is not a backward edge: {got:?}"
3222 );
3223 }
3224
3225 #[cfg(unix)]
3226 #[test]
3227 fn find_links_to_matches_case_variant_on_case_insensitive_fs() {
3228 // Only meaningful on a case-insensitive filesystem; on a case-sensitive
3229 // one the case-variant link is genuinely a different target.
3230 if !fs_is_case_insensitive() {
3231 return;
3232 }
3233 let dir = empty_store();
3234 let root = dir.path();
3235 write(
3236 root,
3237 "records/profiles/bio.md",
3238 "---\ntype: profile\nmeta-type: conclusion\nsummary: s\n---\nSee [[records/contacts/Sarah-Chen]].\n",
3239 );
3240 let store = open(&dir);
3241 let got = rels(
3242 &store
3243 .find_links_to(Path::new("records/contacts/sarah-chen"))
3244 .unwrap(),
3245 );
3246 assert_eq!(
3247 got,
3248 vec!["records/profiles/bio.md".to_string()],
3249 "a case-variant link must be found on a case-insensitive filesystem"
3250 );
3251 }
3252}