Skip to main content

dbmd_core/
parser.rs

1//! `parser` — read and write db.md markdown files.
2//!
3//! Parses the YAML frontmatter block, the markdown body, wiki-links, standard
4//! markdown links, `##` sections, and the structured sections of the `DB.md`
5//! config file. Also the atomic writer that round-trips a file while
6//! preserving the operator-edited body verbatim and emitting frontmatter in
7//! canonical key order.
8//!
9//! Strict on required fields, lenient on unknowns: any frontmatter key the
10//! spec doesn't recognize is preserved in [`Frontmatter::extra`] as ambient
11//! context and round-tripped untouched.
12
13use std::collections::BTreeMap;
14use std::path::{Path, PathBuf};
15
16use chrono::{DateTime, FixedOffset};
17use serde_norway::{Mapping, Value};
18
19/// One db.md text file is bounded before allocation/YAML parsing. Interactive
20/// records are intentionally small; a larger blob belongs in the asset layer.
21/// This prevents a hostile path or imported store from making every read,
22/// validate, or format operation allocate an unbounded string.
23pub const MAX_DBMD_FILE_BYTES: u64 = 64 * 1024 * 1024;
24
25/// The two canonical layer folder names. A path is "content" / a wiki-link is
26/// "full-path" only when it resolves under one of these.
27const LAYER_DIRS: [&str; 2] = ["sources", "records"];
28
29/// Errors produced while parsing a markdown file or the `DB.md` config.
30#[derive(Debug, thiserror::Error)]
31pub enum ParseError {
32    /// The frontmatter block was not valid YAML. Maps to validate code
33    /// `FM_MALFORMED_YAML`.
34    #[error("malformed YAML frontmatter in {file}: {source}")]
35    MalformedYaml {
36        /// The file whose frontmatter failed to parse.
37        file: PathBuf,
38        /// The underlying YAML error.
39        source: serde_norway::Error,
40    },
41
42    /// The file has no `---`-delimited frontmatter block at its very start.
43    #[error("missing frontmatter block in {file}")]
44    MissingFrontmatter {
45        /// The offending file.
46        file: PathBuf,
47    },
48
49    /// A required field was absent. Maps to validate code `FM_MISSING_TYPE`
50    /// (for `type`) and the per-type required-field codes.
51    #[error("missing required field '{key}' in {file}")]
52    MissingField {
53        /// The file missing the field.
54        file: PathBuf,
55        /// The required key.
56        key: String,
57    },
58
59    /// A timestamp field was not ISO-8601 / RFC3339. Maps to `FM_BAD_TIMESTAMP`.
60    #[error("bad timestamp in field '{key}' of {file}: {value}")]
61    BadTimestamp {
62        /// The file.
63        file: PathBuf,
64        /// The frontmatter key.
65        key: String,
66        /// The unparseable value.
67        value: String,
68    },
69
70    /// An I/O error reading the file.
71    #[error(transparent)]
72    Io(#[from] std::io::Error),
73}
74
75/// The parsed YAML frontmatter of a db.md file.
76///
77/// The universal-contract fields are typed accessors; everything else lands in
78/// [`extra`](Frontmatter::extra) as ambient context (unknown-field passthrough)
79/// and is round-tripped verbatim. The atomic writer re-emits keys in canonical
80/// order: `type`, `id`, `created`, `updated`, `summary` first, then
81/// type-specific fields, then `status` / `tags`.
82#[derive(Debug, Clone, Default, PartialEq)]
83pub struct Frontmatter {
84    /// `type` — required on content files; the primary query key.
85    pub type_: Option<String>,
86    /// `meta-type` — records-only; the epistemic class `fact`/`operational`/
87    /// `conclusion`. Absent ⇒ `fact` (the effective default is applied by the
88    /// index/query layer for record-layer files; sources carry none).
89    pub meta_type: Option<String>,
90    /// `id` — optional; derived from the file path when absent.
91    pub id: Option<String>,
92    /// `created` — RFC3339; required and auto-set on content-file create.
93    pub created: Option<DateTime<FixedOffset>>,
94    /// `updated` — RFC3339; required and auto-maintained on content files.
95    pub updated: Option<DateTime<FixedOffset>>,
96    /// `summary` — the one-line catalog line; required on every content file.
97    pub summary: Option<String>,
98    /// `status` — optional lifecycle state.
99    pub status: Option<String>,
100    /// `tags` — optional flat list of short scalar labels.
101    pub tags: Vec<String>,
102    /// All other frontmatter keys (type-specific + custom), preserved verbatim
103    /// in insertion-stable sorted order. Wiki-link-valued fields keep their raw
104    /// YAML form here; [`Frontmatter::link_fields`] surfaces them as
105    /// [`WikiLink`]s.
106    pub extra: BTreeMap<String, Value>,
107}
108
109/// Does `s` contain a run of at least `min` consecutive ASCII digits? A cheap
110/// guard so [`quote_oversized_integers`] only does real work when an oversized
111/// literal is even possible (`i64::MAX` is 19 digits, `u64::MAX` is 20).
112fn has_long_digit_run(s: &str, min: usize) -> bool {
113    let mut run = 0usize;
114    for b in s.bytes() {
115        if b.is_ascii_digit() {
116            run += 1;
117            if run >= min {
118                return true;
119            }
120        } else {
121            run = 0;
122        }
123    }
124    false
125}
126
127/// True if `s` is a bare decimal integer literal whose magnitude exceeds the
128/// `i64`/`u64` range `serde_norway` can represent losslessly — exactly the
129/// literals it either rejects (`(u64::MAX, u128::MAX]`) or silently truncates to
130/// `f64` (`> u128::MAX`). A canonical (no leading zero) decimal only, so an
131/// octal/leading-zero/typed scalar is never reinterpreted.
132fn is_oversized_int_literal(s: &str) -> bool {
133    let t = s.trim();
134    if t.is_empty() {
135        return false;
136    }
137    let (neg, body) = match t.strip_prefix('-') {
138        Some(b) => (true, b),
139        None => (false, t.strip_prefix('+').unwrap_or(t)),
140    };
141    if body.is_empty() || !body.bytes().all(|b| b.is_ascii_digit() || b == b'_') {
142        return false;
143    }
144    let digits: String = body
145        .bytes()
146        .filter(|b| *b != b'_')
147        .map(|b| b as char)
148        .collect();
149    if digits.is_empty() {
150        return false; // all underscores
151    }
152    // Leading-zero decimals (`007`) are version-ambiguous (octal vs int vs
153    // string); never touch them.
154    if digits.len() > 1 && digits.starts_with('0') {
155        return false;
156    }
157    let canon = if neg { format!("-{digits}") } else { digits };
158    // Fits i64 / u64 → handled losslessly; leave untouched.
159    if canon.parse::<i64>().is_ok() || (!neg && canon.parse::<u64>().is_ok()) {
160        return false;
161    }
162    true
163}
164
165/// Byte index where the scalar VALUE begins on a simple block line
166/// (`key: <value>`, `- <value>`, or `- key: <value>`), or `None` when the line
167/// bears no inline value (a bare `key:` / lone `-` / indent-only line).
168fn scalar_value_start(content: &str) -> Option<usize> {
169    let mut base = content.len() - content.trim_start().len();
170    let mut rest = &content[base..];
171    // Consume leading `- ` block-sequence markers (possibly nested: `- - x`).
172    while let Some(after) = rest.strip_prefix("- ") {
173        base += rest.len() - after.len();
174        let trimmed = after.trim_start_matches(' ');
175        base += after.len() - trimmed.len();
176        rest = trimmed;
177    }
178    if rest.is_empty() || rest == "-" {
179        return None;
180    }
181    // `key: value` — first `:` followed by a space/tab introduces the value.
182    if let Some(colon) = rest.find(':') {
183        let after = &rest[colon + 1..];
184        if after.starts_with(' ') || after.starts_with('\t') {
185            let val = after.trim_start_matches([' ', '\t']);
186            return Some(base + colon + 1 + (after.len() - val.len()));
187        }
188        if after.is_empty() {
189            return None; // `key:` with the value on following (block) lines
190        }
191    }
192    // A bare sequence-item scalar: the value is the whole remainder.
193    Some(base)
194}
195
196/// True if `content` introduces a YAML block scalar (`key: |`, `- >2`, …): the
197/// value region begins with a `|` or `>` indicator. Its body must be skipped by
198/// [`quote_oversized_integers`] so a digit line inside literal text is untouched.
199fn introduces_block_scalar(content: &str) -> bool {
200    match scalar_value_start(content) {
201        Some(start) => {
202            let v = content[start..].trim_start();
203            v.starts_with('|') || v.starts_with('>')
204        }
205        None => false,
206    }
207}
208
209/// Quote an oversized bare-integer value on a single block line, returning the
210/// rewritten line, or `None` if the line carries no such value.
211///
212/// Handles two value shapes:
213/// - a bare scalar value (`key: <int>`, `- <int>`, `- key: <int>`), and
214/// - a single-line flow collection value (`key: [ … ]` / `key: { … }`) holding
215///   one or more oversized integer literals (possibly mixed with in-range ints,
216///   strings, and nested flow collections) — see [`quote_oversized_ints_in_flow`].
217///
218/// In both cases only the offending integer scalar(s) are single-quoted; every
219/// other byte is preserved exactly.
220fn quote_int_value_in_line(content: &str) -> Option<String> {
221    let value_start = scalar_value_start(content)?;
222    let region = &content[value_start..];
223    let value = region.trim_end();
224
225    // Single-line flow collection: scan inside it for oversized int literals.
226    // (A bare scalar never starts with `[`/`{`, so these arms are disjoint.)
227    if value.starts_with('[') || value.starts_with('{') {
228        let trailing = &region[value.len()..];
229        let rewritten = quote_oversized_ints_in_flow(value)?;
230        return Some(format!(
231            "{}{}{}",
232            &content[..value_start],
233            rewritten,
234            trailing
235        ));
236    }
237
238    if !is_oversized_int_literal(value) {
239        return None;
240    }
241    // A pure digit literal contains no `'`, so single-quoting needs no escaping.
242    let trailing = &region[value.len()..];
243    Some(format!(
244        "{}'{}'{}",
245        &content[..value_start],
246        value,
247        trailing
248    ))
249}
250
251/// Scan a single-line YAML flow collection (`[ … ]` / `{ … }`) and single-quote
252/// each oversized bare-integer literal it contains, returning the rewritten flow
253/// text, or `None` when it holds no such literal (so the caller can leave the
254/// line untouched and `changed` stays false for an unaffected file).
255///
256/// The flow grammar is tokenized by its structural characters — `[ ] { } , :` —
257/// at the top level: text between two structural characters (and outside any
258/// single/double quoted scalar) is one plain scalar. A plain scalar whose trimmed
259/// form is an oversized canonical decimal integer (per [`is_oversized_int_literal`])
260/// is wrapped in single quotes; everything else — in-range ints, quoted strings,
261/// floats, booleans, nested collections, the structural punctuation and all
262/// surrounding whitespace — is emitted verbatim. Nested collections and multiple
263/// literals on one line are handled by the same single left-to-right pass.
264fn quote_oversized_ints_in_flow(flow: &str) -> Option<String> {
265    let mut out = String::with_capacity(flow.len() + 2);
266    let mut changed = false;
267    // Byte offset where the current plain-scalar token began (None ⇒ not inside
268    // a plain scalar, e.g. just after a structural char or inside a quote).
269    let mut scalar_start: Option<usize> = None;
270    let bytes = flow.as_bytes();
271    let mut i = 0usize;
272
273    // Flush the plain scalar spanning `[start, end)`: quote it iff it is an
274    // oversized integer literal, otherwise copy it through verbatim.
275    fn flush(out: &mut String, flow: &str, start: usize, end: usize, changed: &mut bool) {
276        let raw = &flow[start..end];
277        let trimmed = raw.trim();
278        if !trimmed.is_empty() && is_oversized_int_literal(trimmed) {
279            // Preserve the token's incidental leading/trailing whitespace; only
280            // the literal itself is quoted. A pure-digit literal contains no `'`,
281            // so single-quoting needs no escaping.
282            let lead = &raw[..raw.len() - raw.trim_start().len()];
283            let tail = &raw[raw.trim_end().len()..];
284            out.push_str(lead);
285            out.push('\'');
286            out.push_str(trimmed);
287            out.push('\'');
288            out.push_str(tail);
289            *changed = true;
290        } else {
291            out.push_str(raw);
292        }
293    }
294
295    while i < bytes.len() {
296        let b = bytes[i];
297        match b {
298            // Quoted scalars: copy through verbatim, skipping their contents so a
299            // structural char or digit run inside a string is never reinterpreted.
300            b'\'' | b'"' => {
301                if let Some(start) = scalar_start.take() {
302                    flush(&mut out, flow, start, i, &mut changed);
303                }
304                let quote = b;
305                let str_start = i;
306                i += 1;
307                while i < bytes.len() {
308                    if bytes[i] == quote {
309                        // A doubled single-quote (`''`) is an escaped quote inside
310                        // a single-quoted YAML scalar, not the closing delimiter.
311                        if quote == b'\'' && i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
312                            i += 2;
313                            continue;
314                        }
315                        // A backslash-escaped quote inside a double-quoted scalar
316                        // does not close it.
317                        if quote == b'"' && bytes[i - 1] == b'\\' {
318                            i += 1;
319                            continue;
320                        }
321                        i += 1;
322                        break;
323                    }
324                    i += 1;
325                }
326                out.push_str(&flow[str_start..i]);
327            }
328            // Structural characters end the current plain scalar and are copied
329            // through. `:` separates a flow-mapping key from its value; `,`
330            // separates entries; brackets/braces open or close a (possibly
331            // nested) collection.
332            b'[' | b']' | b'{' | b'}' | b',' | b':' => {
333                if let Some(start) = scalar_start.take() {
334                    flush(&mut out, flow, start, i, &mut changed);
335                }
336                out.push(b as char);
337                i += 1;
338            }
339            _ => {
340                if scalar_start.is_none() {
341                    scalar_start = Some(i);
342                }
343                i += 1;
344            }
345        }
346    }
347    if let Some(start) = scalar_start.take() {
348        flush(&mut out, flow, start, bytes.len(), &mut changed);
349    }
350
351    if changed {
352        Some(out)
353    } else {
354        None
355    }
356}
357
358/// Pre-quote bare integer literals beyond the `i64`/`u64` range so they parse as
359/// STRING scalars and round-trip verbatim.
360///
361/// `serde_norway` (no arbitrary-precision) cannot represent such an integer: it
362/// rejects `(u64::MAX, u128::MAX]` as a hard parse error and silently truncates
363/// `> u128::MAX` to `f64` (`999…9` → `1e39` on the next re-emit) — corrupting an
364/// imported numeric ID and breaking the SPEC guarantee that unknown fields
365/// round-trip byte-for-byte. Quoting them up front makes them string-valued (the
366/// type narrows from number to string, but no data is destroyed).
367///
368/// Conservative: only a canonical decimal integer beyond `i64`/`u64` is quoted —
369/// whether it appears as a bare value (`key: <int>` / `- <int>` / `- key: <int>`)
370/// or as a scalar inside a single-line flow collection (`key: [ … ]` /
371/// `key: { … }`, including nested collections and mixed/multiple literals); block
372/// scalars are tracked and never touched; anything already in range, quoted, or
373/// not a bare integer is left exactly as written.
374fn quote_oversized_integers(yaml: &str) -> std::borrow::Cow<'_, str> {
375    if !has_long_digit_run(yaml, 19) {
376        return std::borrow::Cow::Borrowed(yaml);
377    }
378    let mut out = String::with_capacity(yaml.len());
379    let mut changed = false;
380    let mut block_indent: Option<usize> = None;
381    for line in yaml.split_inclusive('\n') {
382        let content = line.trim_end_matches(['\r', '\n']);
383        let term = &line[content.len()..];
384        let indent = content.len() - content.trim_start().len();
385
386        // Inside a block scalar: emit verbatim until a non-blank line dedents to
387        // at or before the introducer's key indent.
388        if let Some(key_indent) = block_indent {
389            if content.trim().is_empty() || indent > key_indent {
390                out.push_str(line);
391                continue;
392            }
393            block_indent = None; // block ended; process this line normally
394        }
395        if introduces_block_scalar(content) {
396            block_indent = Some(indent);
397            out.push_str(line);
398            continue;
399        }
400        match quote_int_value_in_line(content) {
401            Some(rewritten) => {
402                out.push_str(&rewritten);
403                out.push_str(term);
404                changed = true;
405            }
406            None => out.push_str(line),
407        }
408    }
409    if changed {
410        std::borrow::Cow::Owned(out)
411    } else {
412        std::borrow::Cow::Borrowed(yaml)
413    }
414}
415
416impl Frontmatter {
417    /// Parse a YAML frontmatter block (the text between the opening and closing
418    /// `---` fences, exclusive) into a [`Frontmatter`].
419    ///
420    /// Lenient on unknown keys (they go to [`extra`](Frontmatter::extra));
421    /// returns [`ParseError::MalformedYaml`] only on YAML that doesn't parse.
422    pub fn parse(yaml: &str, file: &Path) -> Result<Self, ParseError> {
423        // An empty (or whitespace-only) frontmatter block is a valid, empty
424        // mapping — not a YAML error.
425        let value: Value = if yaml.trim().is_empty() {
426            Value::Mapping(Mapping::new())
427        } else {
428            // Preserve integer literals beyond i64/u64 range: serde_norway would
429            // otherwise reject `(u64,u128]` or silently truncate `>u128` to f64,
430            // corrupting imported numeric IDs. Quoting them up front makes them
431            // round-trip verbatim as strings.
432            let prepared = quote_oversized_integers(yaml);
433            serde_norway::from_str(&prepared).map_err(|source| ParseError::MalformedYaml {
434                file: file.to_path_buf(),
435                source,
436            })?
437        };
438
439        // Top-level frontmatter must be a mapping. A scalar or sequence at the
440        // top level is malformed for our purposes; surface it as such.
441        let map = match value {
442            Value::Mapping(m) => m,
443            Value::Null => Mapping::new(),
444            other => {
445                // serde_norway::Error has no public constructor, so let the
446                // deserializer decide: a value that coerces to a Mapping (e.g. a
447                // YAML-tagged mapping `!tag\n k: v`, where the tag is ambient) is
448                // accepted as that mapping; a genuine scalar or sequence top
449                // level fails to coerce and IS the malformed case. (Using a
450                // match here, not `expect_err`, avoids a panic on the
451                // tagged-mapping case, which deserializes to a Mapping just
452                // fine.)
453                match serde_norway::from_value::<Mapping>(other) {
454                    Ok(m) => m,
455                    Err(source) => {
456                        return Err(ParseError::MalformedYaml {
457                            file: file.to_path_buf(),
458                            source,
459                        });
460                    }
461                }
462            }
463        };
464
465        let mut fm = Frontmatter::default();
466        for (k, v) in map {
467            let key = match k.as_str() {
468                Some(s) => s.to_string(),
469                // Non-string keys (`2026:`, `true:`, `3.14:`) are unusual but
470                // valid YAML; per SPEC § "Unknown fields pass through" they must
471                // not be corrupted on re-emit. Stringify them through the YAML
472                // scalar emitter — `2026`, `true`, `3.14` — NOT the Rust `Debug`
473                // formatter (which produced `Number(2026)`, `Bool(true)`, …), so
474                // the key text survives. `extra` is `String`-keyed, so on the
475                // write side the key re-emits as a quoted-string key carrying that
476                // text (e.g. `'2026':`) — the type narrows from number to string,
477                // but the data is no longer destroyed and ordinary string keys are
478                // wholly unaffected.
479                None => yaml_scalar_key(&k),
480            };
481            match key.as_str() {
482                // Coerce scalar values rather than `v.as_str()` (which is None
483                // for Number/Bool/Null). A bare scalar that YAML reads as a
484                // non-string — `summary: 2026`, `id: 100`, `status: 0` — would
485                // otherwise be set to None AND dropped (it is a matched arm, so
486                // the raw value never reaches `extra`), and `to_yaml` then omits
487                // the None field, so `dbmd format` (read_file -> write_file)
488                // silently deletes the line from disk. `scalar_string` mirrors
489                // the coercion `validate`/`store` already apply to these fields,
490                // so a numeric/bool-looking scalar is preserved as its string
491                // form and round-trips instead of being destroyed.
492                //
493                // A sequence/mapping value on a universal key (`status: [a, b]`,
494                // a nested-mapping `summary:`) is NOT a valid scalar; rather than
495                // let the matched arm consume-and-drop it (silent data loss on
496                // the next re-emit), `scalar_string` returns None and we fall
497                // through to preserving the raw value in `extra` so `to_yaml`
498                // re-emits it verbatim. The universal accessors stay None (the
499                // value was never a valid scalar for that field), but the
500                // operator's bytes are never destroyed.
501                "type" => match scalar_string(&v) {
502                    Some(s) => fm.type_ = Some(s),
503                    None => {
504                        fm.extra.insert(key, v);
505                    }
506                },
507                "meta-type" => match scalar_string(&v) {
508                    Some(s) => fm.meta_type = Some(s),
509                    None => {
510                        fm.extra.insert(key, v);
511                    }
512                },
513                "id" => match scalar_string(&v) {
514                    Some(s) => fm.id = Some(s),
515                    None => {
516                        fm.extra.insert(key, v);
517                    }
518                },
519                // Same preserve-don't-destroy rule as the scalar keys above,
520                // applied to the two typed ones. A value that is not RFC3339
521                // has nowhere to live in the typed `Option<DateTime>`, so it
522                // rides in `extra` verbatim and `to_yaml` re-emits it byte-for-
523                // byte; the typed accessor stays None because there is no
524                // timestamp to offer.
525                //
526                // The READ path is deliberately tolerant while `set` (the write
527                // path) stays strict: a store is whatever it already is —
528                // date-only stamps are the single most common legacy spelling
529                // in migrated stores — and refusing to PARSE one made every
530                // file-touching command (`format`, `fm`, `link`, `rename`)
531                // unusable on exactly the imperfect stores that most need them.
532                // Reporting the defect is `validate`'s job, and it still does:
533                // `FM_BAD_TIMESTAMP` is raised from the raw YAML value, never
534                // from this parse (validate.rs — `is_iso8601` over
535                // `scalar_string`), so leniency here costs no enforcement.
536                "created" => match parse_timestamp(&v, "created", file) {
537                    Ok(ts) => fm.created = ts,
538                    Err(_) => {
539                        fm.extra.insert(key, v);
540                    }
541                },
542                "updated" => match parse_timestamp(&v, "updated", file) {
543                    Ok(ts) => fm.updated = ts,
544                    Err(_) => {
545                        fm.extra.insert(key, v);
546                    }
547                },
548                "summary" => match scalar_string(&v) {
549                    Some(s) => fm.summary = Some(s),
550                    None => {
551                        fm.extra.insert(key, v);
552                    }
553                },
554                "status" => match scalar_string(&v) {
555                    Some(s) => fm.status = Some(s),
556                    None => {
557                        fm.extra.insert(key, v);
558                    }
559                },
560                "tags" => match parse_tags_preserving(&v) {
561                    Ok(tags) => fm.tags = tags,
562                    // A `tags` value with a non-scalar item (`tags: [[vip]]`,
563                    // `tags: [a, [b]]`) is preserved verbatim in `extra` rather
564                    // than silently filtered down / erased on re-emit. The typed
565                    // `tags` vec stays empty (no valid scalar list was present),
566                    // so `to_yaml` won't ALSO emit a `tags:` from the vec.
567                    Err(raw) => {
568                        fm.extra.insert(key, raw);
569                    }
570                },
571                _ => {
572                    fm.extra.insert(key, v);
573                }
574            }
575        }
576
577        // Disambiguate the one YAML shape `serde_norway` cannot tell apart on its
578        // own: an *inline scalar* wiki-link `field: [[x]]` and a *genuine 2D
579        // array* `field:`\n`- - x` BOTH parse to the identical
580        // `Seq[ Seq[String("x")] ]`. The parsed `Value` has lost which one the
581        // source wrote, but the source text has not — so we resolve it here, the
582        // only place the original spelling is still visible. For every `extra`
583        // key the source wrote in the inline `[[…]]` form, store the canonical
584        // quoted scalar `String("[[x]]")` instead of the ambiguous nested
585        // sequence. `to_yaml`/`canonicalize_extra_value` then emit it inline and
586        // round-trip it (SPEC § Linking, `company: [[…]]`), while a real nested
587        // array — which never appears in inline-link source form — stays a
588        // sequence and is preserved verbatim rather than silently retyped.
589        for key in inline_scalar_link_keys(yaml) {
590            if let Some(value) = fm.extra.get_mut(&key) {
591                // The parsed value of an inline `key: [[x]]` is the one-element
592                // outer `Seq[ Seq[String(x)] ]`; `unquoted_inline_link` reads the
593                // inner `Seq[String(x)]`, so unwrap the lone outer item first.
594                if let Value::Sequence(items) = value {
595                    if items.len() == 1 {
596                        if let Some(link) = unquoted_inline_link(&items[0]) {
597                            *value = Value::String(wiki_link_literal(&link));
598                        }
599                    }
600                }
601            }
602        }
603
604        Ok(fm)
605    }
606
607    /// Serialize the frontmatter back to a YAML block (no `---` fences) in
608    /// canonical key order. Round-trips [`extra`](Frontmatter::extra) verbatim.
609    pub fn to_yaml(&self) -> String {
610        // Build an order-preserving mapping in canonical key order:
611        //   type, meta-type, id, created, updated, summary  (universal head)
612        //   <type-specific extra, BTreeMap-sorted>
613        //   status, tags                          (universal tail)
614        // serde_norway::Mapping preserves insertion order, so one serialize call
615        // emits the block in exactly this order with correct YAML quoting.
616        let mut map = Mapping::new();
617
618        if let Some(t) = &self.type_ {
619            map.insert(Value::String("type".into()), Value::String(t.clone()));
620        }
621        if let Some(mt) = &self.meta_type {
622            map.insert(Value::String("meta-type".into()), Value::String(mt.clone()));
623        }
624        if let Some(id) = &self.id {
625            map.insert(Value::String("id".into()), Value::String(id.clone()));
626        }
627        if let Some(created) = &self.created {
628            map.insert(
629                Value::String("created".into()),
630                Value::String(created.to_rfc3339()),
631            );
632        }
633        if let Some(updated) = &self.updated {
634            map.insert(
635                Value::String("updated".into()),
636                Value::String(updated.to_rfc3339()),
637            );
638        }
639        if let Some(summary) = &self.summary {
640            map.insert(
641                Value::String("summary".into()),
642                Value::String(summary.clone()),
643            );
644        }
645
646        // Type-specific + custom fields, in BTreeMap (sorted) order. Each value
647        // is canonicalized so a wiki-link round-trips to the form the writer and
648        // `dbmd validate` agree on — critically, the SPEC-canonical *unquoted*
649        // scalar `field: [[x]]` (which YAML parses to a nested `Seq[Seq[String]]`)
650        // is re-emitted as a quoted scalar `'[[x]]'` instead of the bracket-less
651        // block sequence `- - x` that a verbatim re-emit would produce and that
652        // destroys the link. See [`canonicalize_extra_value`].
653        for (k, v) in &self.extra {
654            map.insert(Value::String(k.clone()), canonicalize_extra_value(v));
655        }
656
657        if let Some(status) = &self.status {
658            map.insert(
659                Value::String("status".into()),
660                Value::String(status.clone()),
661            );
662        }
663        if !self.tags.is_empty() {
664            map.insert(
665                Value::String("tags".into()),
666                Value::Sequence(self.tags.iter().cloned().map(Value::String).collect()),
667            );
668        }
669
670        if map.is_empty() {
671            return String::new();
672        }
673        serde_norway::to_string(&Value::Mapping(map)).unwrap_or_default()
674    }
675
676    /// True if the file is content (under `sources/` or `records/`)
677    /// and not an `index.md`. Used by validate to decide which files require a
678    /// `summary`. Meta files (`DB.md`, `index.md`, `log.md`) return false.
679    pub fn is_content_file(path: &Path) -> bool {
680        // index.md is a meta file at every level, never content.
681        if path.file_name().and_then(|n| n.to_str()) == Some("index.md") {
682            return false;
683        }
684        // Content iff some path component is one of the two layer dirs. This
685        // works for both store-relative (`sources/emails/x.md`) and absolute
686        // (`/home/db/sources/emails/x.md`) paths. DB.md / log.md sit at the
687        // root, under no layer, so they fall through to false.
688        path.components().any(|c| {
689            c.as_os_str()
690                .to_str()
691                .is_some_and(|s| LAYER_DIRS.contains(&s))
692        })
693    }
694
695    /// Resolve the file's effective `id`: the explicit `id` field if present,
696    /// otherwise derived from the store-relative path (filename without `.md`).
697    pub fn effective_id(&self, store_relative_path: &Path) -> String {
698        if let Some(id) = &self.id {
699            if !id.is_empty() {
700                return id.clone();
701            }
702        }
703        // Derived id = filename without the `.md` extension.
704        store_relative_path
705            .file_stem()
706            .and_then(|s| s.to_str())
707            .unwrap_or_default()
708            .to_string()
709    }
710
711    /// The effective `meta-type` for a record: the declared value, or `fact`
712    /// when absent. Records only — sources carry no meta-type; callers apply
713    /// this only to record-layer files.
714    pub fn effective_meta_type(&self) -> &str {
715        self.meta_type.as_deref().unwrap_or("fact")
716    }
717
718    /// Read a single frontmatter key as a raw YAML [`Value`], looking in the
719    /// typed fields first and then [`extra`](Frontmatter::extra).
720    pub fn get(&self, key: &str) -> Option<Value> {
721        match key {
722            "type" => self.type_.clone().map(Value::String),
723            "meta-type" => self.meta_type.clone().map(Value::String),
724            "id" => self.id.clone().map(Value::String),
725            "created" => self.created.map(|d| Value::String(d.to_rfc3339())),
726            "updated" => self.updated.map(|d| Value::String(d.to_rfc3339())),
727            "summary" => self.summary.clone().map(Value::String),
728            "status" => self.status.clone().map(Value::String),
729            "tags" => {
730                if self.tags.is_empty() {
731                    None
732                } else {
733                    Some(Value::Sequence(
734                        self.tags.iter().cloned().map(Value::String).collect(),
735                    ))
736                }
737            }
738            _ => self.extra.get(key).cloned(),
739        }
740    }
741
742    /// Set a single frontmatter key from a string value, routing universal-
743    /// contract keys to their typed fields and everything else to
744    /// [`extra`](Frontmatter::extra). Used by `dbmd fm set`.
745    pub fn set(&mut self, key: &str, value: &str) -> Result<(), ParseError> {
746        match key {
747            "type" => self.type_ = Some(value.to_string()),
748            "meta-type" => self.meta_type = Some(value.to_string()),
749            "id" => self.id = Some(value.to_string()),
750            "created" => {
751                self.created = Some(parse_rfc3339(value, "created", Path::new("<fm set>"))?)
752            }
753            "updated" => {
754                self.updated = Some(parse_rfc3339(value, "updated", Path::new("<fm set>"))?)
755            }
756            "summary" => self.summary = Some(value.to_string()),
757            "status" => self.status = Some(value.to_string()),
758            "tags" => {
759                // Accept either a YAML flow list (`[a, b]`) or a single scalar
760                // tag. Anything that parses to a sequence becomes the tag list;
761                // otherwise the whole string is one tag.
762                self.tags = match serde_norway::from_str::<Value>(value) {
763                    Ok(Value::Sequence(seq)) => parse_tags(&Value::Sequence(seq)),
764                    _ => vec![value.to_string()],
765                };
766            }
767            _ => {
768                // A custom / type-specific field. The value is a scalar string by
769                // default, but the spec's list-valued link fields (e.g.
770                // `meeting.attendees`, SPEC § Linking) must serialize as a YAML
771                // block sequence of quoted wiki-links — never the flow-form string
772                // `"[[[a]], [[b]]]"`, which `dbmd validate` rejects as
773                // `WIKI_LINK_FLOW_FORM_LIST`. When the value parses as a YAML
774                // sequence whose every item is a clean single wiki-link, store the
775                // canonical sequence so `to_yaml` emits block form. Everything else
776                // — plain text, and a single inline `[[x]]` (which YAML reads as a
777                // nested `Seq[Seq[String]]`, not a list of link strings) — stays a
778                // verbatim scalar string, preserving the prior behavior.
779                let stored = parse_link_list_value(value)
780                    .unwrap_or_else(|| Value::String(value.to_string()));
781                self.extra.insert(key.to_string(), stored);
782            }
783        }
784        Ok(())
785    }
786
787    /// Extract every frontmatter field whose value is a wiki-link (scalar
788    /// inline form or a block-sequence list), pairing each with its key. The
789    /// validate engine checks these against `(link)` schema annotations.
790    pub fn link_fields(&self) -> Vec<(String, WikiLink)> {
791        let mut out = Vec::new();
792        // `summary` may carry navigational wiki-links (spec encourages it).
793        if let Some(summary) = &self.summary {
794            for link in extract_wiki_links(summary, Path::new("")) {
795                out.push(("summary".to_string(), link));
796            }
797        }
798        // Every type-specific / custom field: a scalar wiki-link or a list of
799        // wiki-links, in either the quoted (`"[[x]]"`) or the canonical unquoted
800        // (`[[x]]`) form. See [`links_in_field_value`] for the YAML shapes.
801        for (key, value) in &self.extra {
802            for link in links_in_field_value(value) {
803                out.push((key.clone(), link));
804            }
805        }
806        out
807    }
808}
809
810/// A wiki-link reference inside the store: `[[target]]` or `[[target|display]]`.
811///
812/// `target` is always recorded as written; [`is_full_path`](WikiLink::is_full_path)
813/// flags whether it's a full store-relative path (the doctrine) versus a
814/// short-form (a validation error).
815#[derive(Debug, Clone, PartialEq, Eq)]
816pub struct WikiLink {
817    /// The link target as written, without the `[[ ]]` and without `|display`.
818    pub target: String,
819    /// The optional `|display` text override.
820    pub display: Option<String>,
821    /// True when `target` is a full store-relative path (contains a `/` and
822    /// resolves under a known layer); false for short-form targets like
823    /// `sarah-chen` — which validate reports as `WIKI_LINK_SHORT_FORM`.
824    pub is_full_path: bool,
825    /// True when `target` carries a trailing `.md` extension — validate warns
826    /// `WIKI_LINK_HAS_EXTENSION`; the canonical writers emit the bare form.
827    pub has_md_extension: bool,
828    /// Where the link appears: `(file, line, col)`, 1-based line and column.
829    pub location: (PathBuf, u32, u32),
830}
831
832/// A standard markdown link `[text](url)` — an external reference, kept in a
833/// stream separate from [`WikiLink`] so external targets are visible to the
834/// toolkit without being conflated with in-store edges. Not graph-validated.
835#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct MarkdownLink {
837    /// The link text inside `[ ]`.
838    pub text: String,
839    /// The URL or path inside `( )`.
840    pub url: String,
841    /// Where the link appears: `(file, line, col)`, 1-based.
842    pub location: (PathBuf, u32, u32),
843}
844
845/// A `##`/`###` section of a markdown body: the heading text plus the byte
846/// slice of the body it spans (heading line through the line before the next
847/// heading of equal-or-shallower depth).
848#[derive(Debug, Clone, PartialEq, Eq)]
849pub struct Section {
850    /// The heading text (without the leading `#`s).
851    pub heading: String,
852    /// Heading depth (number of leading `#`s).
853    pub level: u8,
854    /// The 1-based line where the heading appears.
855    pub line: u32,
856    /// The section body, from the heading line to the next sibling-or-shallower
857    /// heading (exclusive), as a slice of the original body.
858    pub body: String,
859}
860
861/// The parsed structured content of a store's `DB.md` config file.
862///
863/// All four parts are optional in the source; absent parts fall back to spec
864/// defaults. Produced by [`parse_db_md`].
865#[derive(Debug, Clone, Default, PartialEq)]
866pub struct Config {
867    /// Body of the `## Agent instructions` section — free-form prose passed to
868    /// the agent's system prompt.
869    pub agent_instructions: Option<String>,
870    /// `## Policies` → `### Frozen pages`: store-relative paths the toolkit
871    /// refuses to write (`POLICY_FROZEN_PAGE`).
872    pub frozen_pages: Vec<PathBuf>,
873    /// `## Policies` → `### Ignored types`: type names the curator never
874    /// synthesizes (still readable as ambient context).
875    pub ignored_types: Vec<String>,
876    /// `## Schemas` → one entry per `### <type>` sub-section.
877    pub schemas: BTreeMap<String, Schema>,
878    /// `## Folders` → optional per-folder display + description, surfaced in the
879    /// root + layer `index.md` rollups. Agent-authored; the tool never invents a
880    /// folder's description (absent ⇒ the rollup shows counts only). Keyed by the
881    /// store-relative, unix-slash folder path (e.g. `records/contacts`).
882    pub folders: BTreeMap<String, FolderMeta>,
883}
884
885/// Agent-authored display + description for one type-folder, declared in
886/// `DB.md ## Folders` and surfaced in the root/layer `index.md` rollups. Both
887/// fields are optional: `display` overrides the rollup's derived folder name
888/// (for casing the tool can't guess, e.g. acronyms like HubSpot); `description`
889/// is the one-line "what's in here" the rollup shows. The tool only ever
890/// *surfaces* these — it never composes a folder description from the folder's
891/// contents (that would be the tool inventing the curator's judgment).
892#[derive(Debug, Clone, Default, PartialEq, Eq)]
893pub struct FolderMeta {
894    /// Display-name override (absent ⇒ derived from the folder basename).
895    pub display: Option<String>,
896    /// One-line folder description shown in the rollup (absent ⇒ counts only).
897    pub description: Option<String>,
898}
899
900impl Config {
901    /// The `### Frozen pages` entry that matches a store-relative `target`, if
902    /// any. The **single** frozen-page matcher every write surface must funnel
903    /// through so the policy is enforced identically on `write` / `fm set` /
904    /// `fm init` / `link` / `rename` / `format`.
905    ///
906    /// Comparison is normalized so a policy line and a write target match
907    /// regardless of incidental spelling differences:
908    /// - `/` path separators on every OS,
909    /// - a single leading `./` dropped,
910    /// - a trailing `.md` dropped on **both** sides — `parse_db_md` stores
911    ///   frozen entries verbatim, so an operator who writes the natural
912    ///   extensionless spelling (`records/decisions/q1`) must protect the file
913    ///   (`records/decisions/q1.md`) exactly as the `.md` spelling does.
914    ///
915    /// Returns the matched config entry verbatim (its original spelling) so the
916    /// caller can name it in the `POLICY_FROZEN_PAGE` refusal.
917    pub fn frozen_match(&self, target: &Path) -> Option<PathBuf> {
918        let want = normalize_frozen_path(target);
919        self.frozen_pages
920            .iter()
921            .find(|frozen| {
922                let pat = normalize_frozen_path(frozen);
923                // A literal entry matches by exact normalized equality; an entry
924                // carrying a `*`/`**` glob matches by segment-wise glob so a
925                // pattern like `records/decisions/*` actually protects the
926                // concrete files under it instead of silently failing open.
927                if pat.contains('*') {
928                    frozen_glob_matches(&pat, &want)
929                } else {
930                    pat == want
931                }
932            })
933            .cloned()
934    }
935
936    /// True if `target` (store-relative) is a frozen page. Convenience wrapper
937    /// over [`Config::frozen_match`] for callers that only need presence.
938    pub fn is_frozen(&self, target: &Path) -> bool {
939        self.frozen_match(target).is_some()
940    }
941}
942
943/// Normalize a path for frozen-page comparison: `/` separators, a leading `./`
944/// or `/` dropped, and a trailing `.md` dropped. Both the policy entry and the
945/// write target pass through this before equality/glob, so the match is
946/// separator-, `./`-, leading-`/`-, and `.md`-insensitive. Without the leading
947/// `/` drop, an operator who wrote `/records/decisions/q1.md` normalized to a
948/// path that never equals the target's `records/decisions/q1`, silently failing
949/// the freeze OPEN.
950fn normalize_frozen_path(p: &Path) -> String {
951    use std::path::Component;
952    // Keep only the `Normal` path segments, dropping `RootDir`/`Prefix` (a
953    // leading `/` or drive prefix) and `CurDir` (`.`). This is what makes a
954    // leading-slash entry (`/records/decisions/q1.md`) normalize to the same
955    // `records/decisions/q1` as the store-relative target, instead of the
956    // doubled-`//` prefix `Path::components` + naive join produced — which never
957    // equalled the target and silently failed the freeze OPEN.
958    let unix: String = p
959        .components()
960        .filter_map(|c| match c {
961            Component::Normal(s) => s.to_str(),
962            _ => None,
963        })
964        .collect::<Vec<_>>()
965        .join("/");
966    unix.strip_suffix(".md").unwrap_or(&unix).to_string()
967}
968
969/// Match a normalized frozen-page glob `pat` against a normalized target `path`,
970/// segment by segment. `*` matches any run of characters *within a single path
971/// segment* (never crossing `/`); `**` as a whole segment matches zero or more
972/// whole segments. Both sides are already `normalize_frozen_path`-normalized, so
973/// this only deals with `/`-joined segment text. Keeps the substrate dependency-
974/// free (no glob crate) while making `records/decisions/*` actually freeze the
975/// files beneath it instead of failing open.
976fn frozen_glob_matches(pat: &str, path: &str) -> bool {
977    // Collapse runs of consecutive `**` segments into a single `**` before
978    // matching: `**/**` matches exactly the same set of paths as `**`, so the
979    // duplicates carry no semantics — they only multiply the number of
980    // (star-index, path-index) splits the matcher must consider. Dropping them
981    // up front is the first half of keeping the match polynomial (the
982    // two-pointer matcher below is the second); without it, a DB.md bullet like
983    // `**/**/…/zzz` against a deep non-matching target made the old recursive
984    // matcher explore exponentially many splits and hang the entire write path.
985    let pat_segs: Vec<&str> = collapse_double_stars(pat.split('/'));
986    let path_segs: Vec<&str> = path.split('/').collect();
987    glob_segments(&pat_segs, &path_segs)
988}
989
990/// Drop every `**` segment that immediately follows another `**`, leaving at most
991/// one `**` per run. Consecutive `**` are semantically identical to a single `**`
992/// (each matches "zero or more whole segments"), so this never changes the set of
993/// matched paths — it only removes the redundant pattern positions that otherwise
994/// fuel catastrophic backtracking.
995fn collapse_double_stars<'a>(segs: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
996    let mut out: Vec<&str> = Vec::new();
997    for seg in segs {
998        if seg == "**" && out.last() == Some(&"**") {
999            continue;
1000        }
1001        out.push(seg);
1002    }
1003    out
1004}
1005
1006/// Segment matcher for [`frozen_glob_matches`]. `**` consumes any number of path
1007/// segments; every other pattern segment must match exactly one path segment
1008/// (with `*` wildcards inside it).
1009///
1010/// Implemented as the classic linear wildcard match: a single forward scan with a
1011/// remembered "last `**`" backtrack point, never the two-way recursion the old
1012/// version used. The old `glob_segments(rest, path)` OR `glob_segments(pat,
1013/// &path[1..])` recursion had no memoization, so N consecutive `**` against a
1014/// deep target that ultimately fails to match explored an exponential number of
1015/// (star-index, path-index) splits — one DB.md frozen-page bullet could hang the
1016/// store's whole write path. This greedy scan with backtrack is O(pat × path) in
1017/// the worst case while matching exactly the same set of paths.
1018fn glob_segments(pat: &[&str], path: &[&str]) -> bool {
1019    let mut pi = 0usize; // cursor into pattern segments
1020    let mut si = 0usize; // cursor into path segments
1021                         // Backtrack point: where in the pattern the last `**` sat, and the path
1022                         // position to resume from if a later literal mismatch forces the `**` to
1023                         // swallow one more segment. `None` until we have seen a `**`.
1024    let mut star_pi: Option<usize> = None;
1025    let mut star_si = 0usize;
1026
1027    while si < path.len() {
1028        if pi < pat.len() && pat[pi] == "**" {
1029            // Record this `**` as the resume point and tentatively let it match
1030            // zero segments (advance past it). If a later segment fails, we come
1031            // back here and let the `**` swallow one more path segment.
1032            star_pi = Some(pi);
1033            star_si = si;
1034            pi += 1;
1035        } else if pi < pat.len() && glob_segment_text(pat[pi], path[si]) {
1036            // Ordinary segment match: advance both cursors.
1037            pi += 1;
1038            si += 1;
1039        } else if let Some(sp) = star_pi {
1040            // Mismatch (or pattern exhausted) but an earlier `**` can absorb more:
1041            // resume just after that `**`, having it consume one extra segment.
1042            pi = sp + 1;
1043            star_si += 1;
1044            si = star_si;
1045        } else {
1046            // Mismatch with no `**` to fall back on.
1047            return false;
1048        }
1049    }
1050
1051    // Path consumed; any trailing pattern must be all `**` (each matching zero
1052    // segments) for a full match.
1053    while pi < pat.len() && pat[pi] == "**" {
1054        pi += 1;
1055    }
1056    pi == pat.len()
1057}
1058
1059/// Match a single glob segment against a single path segment. `*` matches any
1060/// run of characters within the segment; all other characters are literal.
1061fn glob_segment_text(pat: &str, seg: &str) -> bool {
1062    if !pat.contains('*') {
1063        return pat == seg;
1064    }
1065    // Split on `*` into literal fragments. The first fragment must be a prefix,
1066    // the last a suffix, and the middle fragments must appear in order.
1067    let parts: Vec<&str> = pat.split('*').collect();
1068    let mut pos = 0usize;
1069    for (idx, part) in parts.iter().enumerate() {
1070        if part.is_empty() {
1071            continue;
1072        }
1073        if idx == 0 {
1074            // Leading literal must be a prefix.
1075            if !seg[pos..].starts_with(part) {
1076                return false;
1077            }
1078            pos += part.len();
1079        } else if idx == parts.len() - 1 {
1080            // Trailing literal must be a suffix at or after the current cursor.
1081            return seg[pos..].ends_with(part);
1082        } else {
1083            // Interior literal: find it at or after the cursor.
1084            match seg[pos..].find(part) {
1085                Some(off) => pos += off + part.len(),
1086                None => return false,
1087            }
1088        }
1089    }
1090    true
1091}
1092
1093/// A user-declared type schema parsed from a `DB.md` `### <type>` sub-section.
1094/// The store's `## Schemas` is the **only** source of schema enforcement — the
1095/// toolkit ships no built-in or implicit per-type schema (see SPEC § Schemas).
1096#[derive(Debug, Clone, Default, PartialEq)]
1097pub struct Schema {
1098    /// One [`FieldSpec`] per bulleted field line, in source order.
1099    pub fields: Vec<FieldSpec>,
1100    /// `- unique: <field>[, <field> …]` directives — each inner vec is one
1101    /// uniqueness constraint over the listed field(s) (compound when >1). Two
1102    /// records of this type whose listed values collide warn as
1103    /// `DUP_UNIQUE_KEY`.
1104    pub unique_keys: Vec<Vec<String>>,
1105    /// `- summary_template: <template>` directive — the `{field}` interpolation
1106    /// pattern `dbmd fm init` / `dbmd write` use to compose a default `summary`
1107    /// for this type. `None` falls back to the body's first paragraph.
1108    pub summary_template: Option<String>,
1109    /// `- shard: by-date | flat` directive — whether records of this type are
1110    /// date-sharded on disk (`records/<type>/<YYYY>/<MM>/…`) or kept flat.
1111    /// `None` = no directive declared, so the store's built-in default for the
1112    /// type applies ([`crate::store::Store::type_shards`]); `Some(true)` forces
1113    /// date-sharding (e.g. a custom event type the toolkit has no built-in for);
1114    /// `Some(false)` forces flat. This is the v0.2 generic-model way to declare
1115    /// sharding — the toolkit ships no implicit per-type behavior beyond the
1116    /// example-type defaults.
1117    pub shard: Option<bool>,
1118}
1119
1120/// One field declaration inside a [`Schema`]: `- <name> (<modifiers>)`.
1121///
1122/// Modifiers are comma-separated inside the parens; this captures the
1123/// recognized ones as typed fields and stashes anything unrecognized in
1124/// [`unknown_modifiers`](FieldSpec::unknown_modifiers) (surfaced as `Info`).
1125#[derive(Debug, Clone, Default, PartialEq)]
1126pub struct FieldSpec {
1127    /// The field name.
1128    pub name: String,
1129    /// `required` modifier present.
1130    pub required: bool,
1131    /// The shape modifier (`string`/`int`/`bool`/`date`/`email`/`currency`/
1132    /// `url`), if any.
1133    pub shape: Option<Shape>,
1134    /// `link to <prefix>/` — the store-relative prefix a wiki-link target must
1135    /// start with. The trailing slash is required in the source syntax.
1136    pub link_prefix: Option<PathBuf>,
1137    /// `default <value>` — the value written when the field is absent.
1138    pub default: Option<Value>,
1139    /// `enum: <v1>, <v2>, ...` — the allowed values (must be the last modifier
1140    /// on the line because of its own commas).
1141    pub enum_values: Option<Vec<String>>,
1142    /// Any modifiers not in the recognized vocabulary, preserved verbatim;
1143    /// validate surfaces these as `Info`, never errors.
1144    pub unknown_modifiers: Vec<String>,
1145}
1146
1147/// A recognized shape modifier for a schema field. Validate enforces the
1148/// corresponding value shape (`SCHEMA_SHAPE_MISMATCH` on violation).
1149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1150pub enum Shape {
1151    /// Any scalar string.
1152    String,
1153    /// Integer.
1154    Int,
1155    /// Boolean.
1156    Bool,
1157    /// RFC3339 / ISO-8601 date.
1158    Date,
1159    /// `<local>@<domain>` email address.
1160    Email,
1161    /// A currency amount.
1162    Currency,
1163    /// A URL.
1164    Url,
1165}
1166
1167/// The result of splitting a raw file into its frontmatter block and body.
1168///
1169/// `body` is the verbatim remainder after the closing `---` fence — the writer
1170/// preserves it byte-for-byte so operator edits are never reflowed.
1171#[derive(Debug, Clone, PartialEq, Eq)]
1172pub struct ParsedFile {
1173    /// The raw frontmatter YAML (between the fences, exclusive of them).
1174    pub frontmatter_yaml: String,
1175    /// The verbatim body (everything after the closing `---`).
1176    pub body: String,
1177}
1178
1179/// Split a file's full text into its frontmatter block and body. The
1180/// frontmatter block must be the very first thing in the file, delimited by
1181/// `---` on its own line at start and end. Returns
1182/// [`ParseError::MissingFrontmatter`] if absent.
1183pub fn split_frontmatter(text: &str, file: &Path) -> Result<ParsedFile, ParseError> {
1184    // Tolerate a single leading UTF-8 BOM (U+FEFF) before the opening fence,
1185    // matching `store::frontmatter_block` and `index::extract_frontmatter_block`
1186    // which already strip it. Without this, a BOM-prefixed file (common from
1187    // Windows / exported markdown dropped into `sources/`) gets walked and
1188    // indexed by `dbmd index` yet hard-fails every write/edit surface that
1189    // routes through `read_file` (`fm get/set`, `format`, `link`, `write`). The
1190    // BOM is dropped from the emitted body so the canonical writer never carries
1191    // it forward.
1192    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
1193
1194    // The opening fence must be the very first line: `---`, no leading
1195    // whitespace, nothing before it. Trailing whitespace on the fence line is
1196    // tolerated via `trim_end()` (which strips spaces/tabs as well as CR/LF) so
1197    // this matches `index::extract_frontmatter_block` and
1198    // `validate::split_frontmatter`, both of which use `trim_end()`. Without this
1199    // agreement a fence written `--- ` (a single trailing space — invisible in an
1200    // editor, easily produced by hand edits or exporters) was indexed and
1201    // validated clean by those scanners yet hard-failed every write/edit surface
1202    // routed through `read_file` (`fm get/set`, `format`, `link`, `write`) — the
1203    // same cross-scanner drift class already fixed for the UTF-8 BOM above.
1204    let mut lines = text.split_inclusive('\n');
1205    let first = lines.next().unwrap_or("");
1206    if first.trim_end() != "---" {
1207        return Err(ParseError::MissingFrontmatter {
1208            file: file.to_path_buf(),
1209        });
1210    }
1211
1212    // Scan for the closing fence line. Track byte offsets so we can slice the
1213    // YAML (between fences, exclusive) and the body (verbatim, after the
1214    // closing fence's line terminator).
1215    let opening_len = first.len();
1216    let mut offset = opening_len;
1217    for line in lines {
1218        if line.trim_end() == "---" {
1219            let yaml = &text[opening_len..offset];
1220            let body_start = offset + line.len();
1221            let body = &text[body_start..];
1222            return Ok(ParsedFile {
1223                frontmatter_yaml: yaml.to_string(),
1224                body: body.to_string(),
1225            });
1226        }
1227        offset += line.len();
1228    }
1229
1230    // Opening fence present but no closing fence: malformed frontmatter block.
1231    Err(ParseError::MissingFrontmatter {
1232        file: file.to_path_buf(),
1233    })
1234}
1235
1236/// Read a file from disk and parse it into typed [`Frontmatter`] plus the
1237/// verbatim body string.
1238pub fn read_file(path: &Path) -> Result<(Frontmatter, String), ParseError> {
1239    let bytes = crate::fsx::read_bounded_nofollow(path, MAX_DBMD_FILE_BYTES).map_err(|error| {
1240        ParseError::Io(std::io::Error::new(
1241            error.kind(),
1242            format!(
1243                "could not read a bounded regular db.md file ({} MiB cap): {error}",
1244                MAX_DBMD_FILE_BYTES / (1024 * 1024)
1245            ),
1246        ))
1247    })?;
1248    let text = String::from_utf8(bytes).map_err(|error| {
1249        ParseError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, error))
1250    })?;
1251    let parsed = split_frontmatter(&text, path)?;
1252    let fm = Frontmatter::parse(&parsed.frontmatter_yaml, path)?;
1253    Ok((fm, parsed.body))
1254}
1255
1256/// Atomically write a markdown file from frontmatter + body: emit the
1257/// frontmatter in canonical key order, then the body verbatim, via a
1258/// temp-file-rename so a reader never sees a half-written file. Preserves the
1259/// operator-edited body exactly as given.
1260pub fn write_file(path: &Path, frontmatter: &Frontmatter, body: &str) -> Result<(), ParseError> {
1261    let contents = render_file(frontmatter, body);
1262
1263    // One durable, atomic write for all primary data (see `crate::fsx`):
1264    // temp-file + fsync + rename + parent-fsync. Content records are primary
1265    // data, so they get the durable path (unlike the rebuildable index).
1266    crate::fsx::write_atomic(path, contents.as_bytes())?;
1267    Ok(())
1268}
1269
1270/// Atomically create a markdown file from frontmatter + body, refusing with
1271/// [`std::io::ErrorKind::AlreadyExists`] if the destination already exists.
1272///
1273/// This is the create-new sibling of [`write_file`]: same canonical rendering
1274/// and durable temp-file path, but backed by [`crate::fsx::write_atomic_new`] so
1275/// two concurrent creators for the same path cannot both succeed.
1276pub fn write_file_new(
1277    path: &Path,
1278    frontmatter: &Frontmatter,
1279    body: &str,
1280) -> Result<(), ParseError> {
1281    let contents = render_file(frontmatter, body);
1282    crate::fsx::write_atomic_new(path, contents.as_bytes())?;
1283    Ok(())
1284}
1285
1286/// Render canonical file bytes without performing I/O. Transactional callers
1287/// use this to stage the exact bytes that [`write_file`] would commit.
1288pub fn render_file(frontmatter: &Frontmatter, body: &str) -> String {
1289    let yaml = frontmatter.to_yaml();
1290    // `to_yaml` already terminates each block with a newline. Compose the file
1291    // as: opening fence, frontmatter YAML, closing fence, then body verbatim.
1292    let mut contents = String::with_capacity(yaml.len() + body.len() + 8);
1293    contents.push_str("---\n");
1294    contents.push_str(&yaml);
1295    contents.push_str("---\n");
1296    contents.push_str(body);
1297    contents
1298}
1299
1300/// Extract every wiki-link from a body (and inline frontmatter), returning the
1301/// structured [`WikiLink`] stream with short-form / `.md`-extension flags and
1302/// `(file, line, col)` locations set.
1303pub fn extract_wiki_links(body: &str, file: &Path) -> Vec<WikiLink> {
1304    static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1305    let re = RE.get_or_init(|| {
1306        // [[target]] or [[target|display]]; target/display exclude brackets and
1307        // (for target) the `|` separator so nested forms don't over-match.
1308        regex::Regex::new(r"\[\[([^\[\]|]+?)(?:\|([^\[\]]*))?\]\]").expect("valid wiki-link regex")
1309    });
1310
1311    let mut out = Vec::new();
1312    for (line_idx, line) in body.lines().enumerate() {
1313        // Running (byte, char) cursor: derive each match's column in ONE linear
1314        // pass over the line instead of recomputing it from the line start per
1315        // match. `captures_iter` yields non-overlapping matches in increasing
1316        // byte order, so advancing the char count by the gap since the previous
1317        // match keeps the whole line O(line_len) rather than O(matches × len).
1318        let mut cursor = ColCursor::new();
1319        for caps in re.captures_iter(line) {
1320            let whole = caps.get(0).expect("group 0 always present");
1321            let col = cursor.column_at(line, whole.start());
1322            let target = caps.get(1).map(|m| m.as_str()).unwrap_or("").to_string();
1323            let display = caps.get(2).map(|m| m.as_str().to_string());
1324            out.push(WikiLink {
1325                is_full_path: target_is_full_path(&target),
1326                has_md_extension: target_has_md_extension(&target),
1327                target,
1328                display,
1329                location: (file.to_path_buf(), (line_idx as u32) + 1, col),
1330            });
1331        }
1332    }
1333    out
1334}
1335
1336/// Extract every standard markdown link `[text](url)` from a body into a
1337/// separate stream, kept distinct from wiki-links.
1338pub fn extract_markdown_links(body: &str, file: &Path) -> Vec<MarkdownLink> {
1339    static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1340    let re = RE.get_or_init(|| {
1341        // [text](url). `text` excludes brackets so a wiki-link `[[x]]` (which
1342        // has `]]`, not `](`) never matches; `url` excludes `)` and whitespace.
1343        regex::Regex::new(r"\[([^\[\]]*)\]\(([^)\s]*)\)").expect("valid markdown-link regex")
1344    });
1345
1346    let mut out = Vec::new();
1347    for (line_idx, line) in body.lines().enumerate() {
1348        // One linear column cursor per line (see `extract_wiki_links`): avoids the
1349        // O(matches × line_len) recompute on a link-dense line.
1350        let mut cursor = ColCursor::new();
1351        for caps in re.captures_iter(line) {
1352            let whole = caps.get(0).expect("group 0 always present");
1353            let col = cursor.column_at(line, whole.start());
1354            out.push(MarkdownLink {
1355                text: caps.get(1).map(|m| m.as_str()).unwrap_or("").to_string(),
1356                url: caps.get(2).map(|m| m.as_str()).unwrap_or("").to_string(),
1357                location: (file.to_path_buf(), (line_idx as u32) + 1, col),
1358            });
1359        }
1360    }
1361    out
1362}
1363
1364/// Detect the frontmatter wiki-link-list mis-encoding: a wiki-link *list*
1365/// written so YAML parses it as nested sequences instead of a clean list of
1366/// strings. Returns the offending keys so validate can emit
1367/// `WIKI_LINK_FLOW_FORM_LIST`.
1368///
1369/// The subtlety is that `[[x]]` is YAML for "a list containing `[x]`", so the
1370/// shapes nest:
1371///
1372/// - **Scalar inline** `company: [[records/x]]` → `Seq[ Seq[String] ]`
1373///   (double-nested). This is the spec's scalar wiki-link form — NOT flagged.
1374/// - **Flow list** `attendees: [[[a]], [[b]]]` → `Seq[ Seq[Seq[String]], … ]`
1375///   (triple-nested). The list mis-encoding — flagged.
1376/// - **Unquoted block list** (`- [[a]]` per line) → also triple-nested, so it
1377///   is flagged too; the canonical list form must quote each item
1378///   (`- "[[a]]"`), which parses to a clean `Seq[String, …]` and is NOT flagged.
1379///
1380/// So the discriminator is nesting depth: a *list* mis-encoding has at least one
1381/// item that is itself a sequence-of-sequences, whereas a scalar inline link's
1382/// single item is a sequence-of-scalars.
1383pub fn detect_flow_form_link_lists(frontmatter_yaml: &str) -> Vec<String> {
1384    let value: Value = match serde_norway::from_str(frontmatter_yaml) {
1385        Ok(v) => v,
1386        // Malformed YAML is FM_MALFORMED_YAML's job, not ours; report nothing.
1387        Err(_) => return Vec::new(),
1388    };
1389    let Value::Mapping(map) = value else {
1390        return Vec::new();
1391    };
1392
1393    let mut out = Vec::new();
1394    for (k, v) in &map {
1395        if let Value::Sequence(items) = v {
1396            // Triple-nesting: some outer item is a sequence that itself holds a
1397            // sequence. Scalar inline `[[x]]` is only double-nested, so it
1398            // never matches.
1399            let is_link_list = items.iter().any(|item| match item {
1400                Value::Sequence(inner) => inner.iter().any(|x| matches!(x, Value::Sequence(_))),
1401                _ => false,
1402            });
1403            if is_link_list {
1404                if let Some(key) = k.as_str() {
1405                    out.push(key.to_string());
1406                }
1407            }
1408        }
1409    }
1410    out
1411}
1412
1413/// Extract the `##`/`###` sections of a markdown body into a flat list with
1414/// body slices.
1415pub fn extract_sections(body: &str) -> Vec<Section> {
1416    // Keep each line's start so we can slice the body verbatim (exact newlines).
1417    let lines: Vec<&str> = body.split_inclusive('\n').collect();
1418
1419    // First pass: classify heading levels (0 = not a heading), honoring fenced
1420    // code blocks so a `## x` inside a ``` fence is not treated as a heading.
1421    let mut levels: Vec<u8> = Vec::with_capacity(lines.len());
1422    let mut fence: Option<(u8, usize)> = None;
1423    for line in &lines {
1424        let content = line.trim_end_matches(['\n', '\r']);
1425        if let Some(f) = fence {
1426            if is_closing_fence(content, f) {
1427                fence = None;
1428            }
1429            levels.push(0);
1430            continue;
1431        }
1432        if let Some(opened) = opening_fence(content) {
1433            fence = Some(opened);
1434            levels.push(0);
1435            continue;
1436        }
1437        levels.push(heading_level(content));
1438    }
1439
1440    // Second pass: emit `##`+ headings; each section body runs from its heading
1441    // line to the next heading at an equal-or-shallower level (exclusive).
1442    let mut sections = Vec::new();
1443    for (i, &lvl) in levels.iter().enumerate() {
1444        if lvl < 2 {
1445            continue;
1446        }
1447        let heading_line = lines[i].trim_end_matches(['\n', '\r']);
1448        let heading = heading_text(heading_line, lvl);
1449
1450        let mut end = lines.len();
1451        for (j, &other) in levels.iter().enumerate().skip(i + 1) {
1452            if other != 0 && other <= lvl {
1453                end = j;
1454                break;
1455            }
1456        }
1457
1458        sections.push(Section {
1459            heading,
1460            level: lvl,
1461            line: (i + 1) as u32,
1462            body: lines[i..end].concat(),
1463        });
1464    }
1465    sections
1466}
1467
1468/// Extract the `##`/`###` sections of a **whole file** (frontmatter + body),
1469/// returning each [`Section`] with `line` numbered against the *source file*,
1470/// not the body.
1471///
1472/// [`extract_sections`] numbers headings 1-based within the body it is handed —
1473/// the right frame for callers that already track the frontmatter offset
1474/// (`validate` adds `fm_end_line`). But the single-file views (`dbmd sections`,
1475/// `dbmd outline`) present `Section::line` as a source line an agent can jump to;
1476/// because every db.md file opens with a frontmatter block, the body-relative
1477/// number is off by the block's length (`opening fence + frontmatter lines +
1478/// closing fence`) for every file. This helper does the offset once, in the
1479/// parser, so those surfaces report true file lines. A file with no leading
1480/// frontmatter block is treated as all-body (offset 0), so the function never
1481/// fails just because a file lacks frontmatter.
1482pub fn extract_sections_in_file(text: &str) -> Vec<Section> {
1483    // Tolerate a leading BOM the same way `split_frontmatter` does, so the line
1484    // count and the body slice agree with the read path.
1485    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
1486
1487    // Find the body and how many source lines precede it. The body begins right
1488    // after the closing fence; the number of lines consumed by the frontmatter
1489    // block (both fences + the YAML between) is the offset to add to each
1490    // body-relative heading line.
1491    let (body, offset) = match split_frontmatter(text, Path::new("<sections>")) {
1492        Ok(parsed) => {
1493            // Lines before the body = total lines in `text` minus lines in body.
1494            let total_lines = count_lines(text);
1495            let body_lines = count_lines(&parsed.body);
1496            (parsed.body, total_lines.saturating_sub(body_lines))
1497        }
1498        // No frontmatter block: the whole text is body, no offset.
1499        Err(_) => (text.to_string(), 0),
1500    };
1501
1502    let mut sections = extract_sections(&body);
1503    for s in &mut sections {
1504        s.line += offset;
1505    }
1506    sections
1507}
1508
1509/// Count the number of lines a string spans for line-number offsetting: one line
1510/// per `\n`, plus one more for a final line with no trailing newline. An empty
1511/// string is zero lines.
1512fn count_lines(s: &str) -> u32 {
1513    if s.is_empty() {
1514        return 0;
1515    }
1516    let newlines = s.bytes().filter(|&b| b == b'\n').count() as u32;
1517    if s.ends_with('\n') {
1518        newlines
1519    } else {
1520        newlines + 1
1521    }
1522}
1523
1524/// Parse a store's `DB.md` file into a [`Config`]: the `## Agent instructions`
1525/// prose, `## Policies` (`### Frozen pages` + `### Ignored types`), and
1526/// `## Schemas` (`### <type>` field-bullet blocks). Unrecognized sections are
1527/// ignored; absent sections leave their [`Config`] fields at default.
1528pub fn parse_db_md(text: &str, file: &Path) -> Result<Config, ParseError> {
1529    // The structured sections live in the body (after frontmatter). DB.md must
1530    // still start with a valid `---` block (`type: db-md`); if it's missing we
1531    // surface MissingFrontmatter like any other file.
1532    let parsed = split_frontmatter(text, file)?;
1533    let _frontmatter = Frontmatter::parse(&parsed.frontmatter_yaml, file)?;
1534    let sections = extract_sections(&parsed.body);
1535
1536    let mut config = Config::default();
1537    // Track which H2 region each H3 belongs to as we walk the flat list.
1538    let mut current_h2: Option<String> = None;
1539
1540    for section in &sections {
1541        match section.level {
1542            2 => {
1543                let name = section.heading.trim().to_ascii_lowercase();
1544                current_h2 = Some(name.clone());
1545                if name == "agent instructions" {
1546                    let prose = section_prose(&section.body);
1547                    if !prose.is_empty() {
1548                        config.agent_instructions = Some(prose);
1549                    }
1550                } else if name == "folders" {
1551                    // `## Folders` carries its bullets directly under the H2 (no
1552                    // `### <type>` sub-sections), like `## Agent instructions`.
1553                    for b in bullet_lines(&section.body) {
1554                        if let Some((path, meta)) = parse_folder_bullet(&b) {
1555                            config.folders.insert(path, meta);
1556                        }
1557                    }
1558                }
1559            }
1560            3 => {
1561                let h2 = current_h2.as_deref().unwrap_or("");
1562                let h3 = section.heading.trim().to_ascii_lowercase();
1563                match (h2, h3.as_str()) {
1564                    ("policies", "frozen pages") => {
1565                        config.frozen_pages = bullet_lines(&section.body)
1566                            .into_iter()
1567                            .map(|b| PathBuf::from(extract_path_bullet(&b)))
1568                            .collect();
1569                    }
1570                    ("policies", "ignored types") => {
1571                        config.ignored_types = bullet_lines(&section.body)
1572                            .into_iter()
1573                            .flat_map(|b| extract_type_list_bullet(&b))
1574                            .collect();
1575                    }
1576                    ("schemas", _) => {
1577                        // The H3 heading text (as written) is the type name.
1578                        let type_name = section.heading.trim().to_string();
1579                        let mut schema = Schema::default();
1580                        for b in bullet_lines(&section.body) {
1581                            match parse_schema_bullet(&b) {
1582                                SchemaBullet::Field(f) => schema.fields.push(f),
1583                                SchemaBullet::Unique(k) if !k.is_empty() => {
1584                                    schema.unique_keys.push(k)
1585                                }
1586                                SchemaBullet::SummaryTemplate(t) if !t.is_empty() => {
1587                                    schema.summary_template = Some(t)
1588                                }
1589                                SchemaBullet::Shard(Some(b)) => schema.shard = Some(b),
1590                                // Empty `unique:`/`summary_template:`, or a `shard:`
1591                                // with an unrecognized value — ignored.
1592                                SchemaBullet::Unique(_)
1593                                | SchemaBullet::SummaryTemplate(_)
1594                                | SchemaBullet::Shard(None) => {}
1595                            }
1596                        }
1597                        config.schemas.insert(type_name, schema);
1598                    }
1599                    _ => {}
1600                }
1601            }
1602            _ => {}
1603        }
1604    }
1605
1606    Ok(config)
1607}
1608
1609/// One parsed bullet inside a `### <type>` schema block: an ordinary field, or a
1610/// reserved directive (`unique:` / `summary_template:` / `shard:`). The names
1611/// `unique`, `summary_template`, and `shard` are reserved and cannot be used as
1612/// field names.
1613#[derive(Debug)]
1614enum SchemaBullet {
1615    /// An ordinary `- <name> (<modifiers>)` field.
1616    Field(FieldSpec),
1617    /// `- unique: <field>[, <field> …]` — a (possibly compound) uniqueness key.
1618    Unique(Vec<String>),
1619    /// `- summary_template: <template>` — the default-`summary` pattern.
1620    SummaryTemplate(String),
1621    /// `- shard: by-date | flat` — date-shard records of this type, or keep them
1622    /// flat. `None` = an unrecognized value, ignored like an unknown modifier.
1623    Shard(Option<bool>),
1624}
1625
1626/// Classify one `## Schemas` bullet as a directive or a field. The directive
1627/// forms are `- unique: a, b, …` and `- summary_template: …`; the keyword check
1628/// guards against false positives — a field like `- status (enum: a, b)` has a
1629/// `(` before any `:`, so its head isn't a bare reserved keyword and it parses
1630/// as a [`FieldSpec`].
1631fn parse_schema_bullet(bullet_line: &str) -> SchemaBullet {
1632    let line = bullet_line.trim();
1633    let line = line
1634        .strip_prefix("- ")
1635        .or_else(|| line.strip_prefix("* "))
1636        .or_else(|| line.strip_prefix("+ "))
1637        .or_else(|| line.strip_prefix('-'))
1638        .unwrap_or(line)
1639        .trim();
1640
1641    if let Some((head, rest)) = line.split_once(':') {
1642        match head.trim().to_ascii_lowercase().as_str() {
1643            "unique" => {
1644                let fields = rest
1645                    .split(',')
1646                    .map(|f| f.trim().to_string())
1647                    .filter(|f| !f.is_empty())
1648                    .collect();
1649                return SchemaBullet::Unique(fields);
1650            }
1651            "summary_template" => {
1652                return SchemaBullet::SummaryTemplate(rest.trim().to_string());
1653            }
1654            "shard" => {
1655                // `by-date` (synonyms: date/sharded/true) enables date-sharding;
1656                // `flat` (none/false) forces flat; anything else is ignored.
1657                let v = match rest.trim().to_ascii_lowercase().as_str() {
1658                    "by-date" | "date" | "sharded" | "true" => Some(true),
1659                    "flat" | "none" | "false" => Some(false),
1660                    _ => None,
1661                };
1662                return SchemaBullet::Shard(v);
1663            }
1664            _ => {}
1665        }
1666    }
1667
1668    SchemaBullet::Field(parse_field_spec(bullet_line))
1669}
1670
1671/// Parse one `## Folders` bullet — `- <path>[|<display>] — <description>` — into
1672/// the folder path (store-relative, unix-slash, no trailing slash) and its
1673/// [`FolderMeta`]. The optional `|<display>` overrides the rollup's derived
1674/// folder name (mirroring the wiki-link `|display` convention); the text after
1675/// the first em-dash (`—`), or ` - `, is the description. Backticks around the
1676/// path are tolerated (matching the `### Frozen pages` spelling). Returns `None`
1677/// for a bullet with no usable path.
1678fn parse_folder_bullet(bullet_line: &str) -> Option<(String, FolderMeta)> {
1679    let line = bullet_line.trim();
1680    let line = line
1681        .strip_prefix("- ")
1682        .or_else(|| line.strip_prefix("* "))
1683        .or_else(|| line.strip_prefix("+ "))
1684        .or_else(|| line.strip_prefix('-'))
1685        .unwrap_or(line)
1686        .trim();
1687
1688    // Split off the description at the first em-dash (preferred, matching the
1689    // rollup's own ` — ` separator) or a ` - ` fallback.
1690    let (pathspec, description) = match line.find('—') {
1691        Some(i) => (line[..i].trim(), Some(line[i + '—'.len_utf8()..].trim())),
1692        None => match line.find(" - ") {
1693            Some(i) => (line[..i].trim(), Some(line[i + 3..].trim())),
1694            None => (line, None),
1695        },
1696    };
1697
1698    // Optional `|display` override lives on the path side.
1699    let (path_raw, display) = match pathspec.split_once('|') {
1700        Some((p, d)) => (p.trim(), Some(d.trim())),
1701        None => (pathspec, None),
1702    };
1703
1704    // Normalize the path: drop surrounding backticks, a leading `./`, a trailing `/`.
1705    let path = path_raw.trim().trim_matches('`').trim();
1706    let path = path.strip_prefix("./").unwrap_or(path);
1707    let path = path.strip_suffix('/').unwrap_or(path).trim();
1708    if path.is_empty() {
1709        return None;
1710    }
1711
1712    let non_empty = |s: &str| {
1713        let t = s.trim();
1714        (!t.is_empty()).then(|| t.to_string())
1715    };
1716    Some((
1717        path.to_string(),
1718        FolderMeta {
1719            display: display.and_then(non_empty),
1720            description: description.and_then(non_empty),
1721        },
1722    ))
1723}
1724
1725/// Parse a single `## Schemas` field-bullet line — `- <name> (<modifiers>)` —
1726/// into a [`FieldSpec`], capturing recognized modifiers and stashing the rest
1727/// in [`FieldSpec::unknown_modifiers`].
1728pub fn parse_field_spec(bullet_line: &str) -> FieldSpec {
1729    // Strip the leading bullet marker (`- ` / `* ` / `+ `) and surrounding ws.
1730    let line = bullet_line.trim();
1731    let line = line
1732        .strip_prefix("- ")
1733        .or_else(|| line.strip_prefix("* "))
1734        .or_else(|| line.strip_prefix("+ "))
1735        .or_else(|| line.strip_prefix('-'))
1736        .unwrap_or(line)
1737        .trim();
1738
1739    // Split `<name> (<modifiers>)` — the canonical paren form — OR the natural
1740    // mis-spelling `<name>: <modifiers>` (colon instead of parens). The two
1741    // delimiters are interchangeable for the field head; whichever appears FIRST
1742    // wins, so a paren form whose modifiers contain a colon (`status (enum: a,
1743    // b)`) still parses by parens (the `(` precedes the `:`), while a bare
1744    // `title: string, required` parses by colon instead of being swallowed whole
1745    // into the field name with every modifier silently dropped.
1746    let paren = line.find('(');
1747    let colon = line.find(':');
1748    // Choose the head delimiter. The paren form wins when its `(` precedes any
1749    // `:` (so `status (enum: a, b)` parses by parens, the colon being inside the
1750    // modifiers); otherwise a `:` before the paren — or with no paren at all —
1751    // selects the colon form `<name>: <modifiers>`, the natural mis-spelling that
1752    // must NOT be swallowed whole into the field name with every modifier lost.
1753    let use_paren = matches!((paren, colon), (Some(p), c) if c.is_none_or(|c| p < c));
1754    let (name, modifiers) = if use_paren {
1755        let open = paren.expect("use_paren implies a paren");
1756        let name = line[..open].trim().to_string();
1757        let after = &line[open + 1..];
1758        let mods = match after.rfind(')') {
1759            Some(close) => &after[..close],
1760            None => after, // tolerate a missing close paren
1761        };
1762        (name, mods.trim())
1763    } else if let Some(c) = colon {
1764        // Colon form: everything after the first colon is the modifier list,
1765        // parsed identically to the parenthesized modifiers below.
1766        let name = line[..c].trim().to_string();
1767        (name, line[c + 1..].trim())
1768    } else {
1769        // Neither delimiter: a free-form optional field of any shape — name only.
1770        (line.to_string(), "")
1771    };
1772
1773    let mut spec = FieldSpec {
1774        name,
1775        ..FieldSpec::default()
1776    };
1777
1778    if modifiers.is_empty() {
1779        return spec;
1780    }
1781
1782    // Modifiers are comma-separated. `enum` and `default` are special: their own
1783    // values may contain commas, so each is a *greedy* clause that runs from its
1784    // keyword to the start of the next recognized greedy clause (or end of line).
1785    // This lets `default North America, EMEA fallback` keep its comma and lets a
1786    // `default …` written after an `enum …` still be recognized, instead of the
1787    // value being truncated at the first comma or absorbed into the enum list.
1788    let raw: Vec<&str> = modifiers.split(',').collect();
1789    let mut i = 0;
1790    while i < raw.len() {
1791        let token = raw[i].trim();
1792        if token.is_empty() {
1793            i += 1;
1794            continue;
1795        }
1796        let lower = token.to_ascii_lowercase();
1797
1798        if lower == "required" {
1799            spec.required = true;
1800            i += 1;
1801        } else if let Some(shape) = shape_from_str(&lower) {
1802            spec.shape = Some(shape);
1803            i += 1;
1804        } else if let Some(rest) = lower.strip_prefix("link to ") {
1805            // The trailing slash is required in the source; store the prefix
1806            // without it so `Path::starts_with` comparisons are clean.
1807            let prefix = token["link to ".len()..].trim().trim_end_matches('/');
1808            let _ = rest; // lowercase form only used for the keyword match
1809            spec.link_prefix = Some(PathBuf::from(prefix));
1810            i += 1;
1811        } else if token.len() >= "default ".len() && lower.starts_with("default ") {
1812            // Greedy `default <value>`: the value is this token (after the
1813            // keyword) plus every following comma-token up to the next greedy
1814            // clause, rejoined with the commas the split removed — so a comma
1815            // inside the default value is preserved. Original case is kept.
1816            let end = next_greedy_clause(&raw, i + 1);
1817            let mut value = token["default ".len()..].to_string();
1818            for tok in &raw[i + 1..end] {
1819                value.push(',');
1820                value.push_str(tok);
1821            }
1822            spec.default = Some(Value::String(value.trim().to_string()));
1823            i = end;
1824        } else if lower == "enum" || lower.starts_with("enum:") {
1825            // Greedy `enum` (bare `enum, a, b` or `enum: a, b`): the values run
1826            // from here to the next greedy clause (e.g. a trailing `default …`),
1827            // NOT unconditionally to end-of-line — so a `default` after `enum` is
1828            // parsed instead of swallowed as a bogus enum member.
1829            let end = next_greedy_clause(&raw, i + 1);
1830            // Rejoin this clause's tokens (trimmed so the `enum` head sits at the
1831            // start), drop the leading `enum`/`enum:` head, then re-split the
1832            // remainder into values.
1833            let joined = raw[i..end].join(",");
1834            let joined = joined.trim();
1835            let after_kw = match joined.find(':') {
1836                // `enum: a, b` — values follow the colon.
1837                Some(colon) => &joined[colon + 1..],
1838                // bare `enum, a, b` — values follow the keyword itself.
1839                None => joined.get("enum".len()..).unwrap_or(""),
1840            };
1841            let values: Vec<String> = after_kw
1842                .split(',')
1843                .map(|v| v.trim().to_string())
1844                .filter(|v| !v.is_empty())
1845                .collect();
1846            spec.enum_values = Some(values);
1847            i = end;
1848        } else {
1849            // Unrecognized modifier — captured verbatim, surfaced as Info.
1850            spec.unknown_modifiers.push(token.to_string());
1851            i += 1;
1852        }
1853    }
1854
1855    spec
1856}
1857
1858// ── Private helpers ─────────────────────────────────────────────────────────
1859
1860/// Parse a frontmatter timestamp value into a `DateTime<FixedOffset>`. A `null`
1861/// is treated as absent; anything else must be an RFC3339 string.
1862fn parse_timestamp(
1863    value: &Value,
1864    key: &str,
1865    file: &Path,
1866) -> Result<Option<DateTime<FixedOffset>>, ParseError> {
1867    match value {
1868        Value::Null => Ok(None),
1869        Value::String(s) => parse_rfc3339(s, key, file).map(Some),
1870        other => Err(ParseError::BadTimestamp {
1871            file: file.to_path_buf(),
1872            key: key.to_string(),
1873            value: format!("{other:?}"),
1874        }),
1875    }
1876}
1877
1878/// Parse an RFC3339 timestamp string, mapping failure to [`ParseError::BadTimestamp`].
1879fn parse_rfc3339(s: &str, key: &str, file: &Path) -> Result<DateTime<FixedOffset>, ParseError> {
1880    DateTime::parse_from_rfc3339(s.trim()).map_err(|_| ParseError::BadTimestamp {
1881        file: file.to_path_buf(),
1882        key: key.to_string(),
1883        value: s.to_string(),
1884    })
1885}
1886
1887/// Coerce a YAML scalar value to its string form for the universal-contract
1888/// fields (`type`/`id`/`summary`/`status`). Mirrors `validate::scalar_string`
1889/// and `store::yaml_scalar_string` so the four modules agree on one coercion
1890/// rule: a bare numeric/bool scalar (`id: 100`, `summary: 2026`, `status: 0`)
1891/// is preserved as its string form rather than being read as None and silently
1892/// dropped on the next `to_yaml` re-emit. Returns `None` only for genuinely
1893/// non-scalar values (sequences, mappings, null), which were never a valid
1894/// shape for these fields.
1895fn scalar_string(value: &Value) -> Option<String> {
1896    match value {
1897        Value::String(s) => Some(s.clone()),
1898        Value::Number(n) => Some(n.to_string()),
1899        Value::Bool(b) => Some(b.to_string()),
1900        _ => None,
1901    }
1902}
1903
1904/// Read a `tags` value into a flat `Vec<String>`. Accepts a sequence of scalars
1905/// (the canonical form) or a single scalar (coerced to a one-element list).
1906fn parse_tags(value: &Value) -> Vec<String> {
1907    match value {
1908        Value::Sequence(items) => items
1909            .iter()
1910            .filter_map(|v| match v {
1911                Value::String(s) => Some(s.clone()),
1912                Value::Number(n) => Some(n.to_string()),
1913                Value::Bool(b) => Some(b.to_string()),
1914                _ => None,
1915            })
1916            .collect(),
1917        Value::String(s) => vec![s.clone()],
1918        _ => Vec::new(),
1919    }
1920}
1921
1922/// Read a `tags` value into a flat `Vec<String>` **without losing data**: a
1923/// sequence of clean scalars (the canonical form) or a single scalar coerce to a
1924/// string list. Any other shape — a sequence with a non-scalar item
1925/// (`tags: [[vip]]` → `Seq[Seq[String]]`, `tags: [a, [b]]`), or a mapping — is
1926/// rejected as `Err(value.clone())` so the caller preserves the raw value in
1927/// `extra` rather than silently filtering items out / erasing the field on the
1928/// next re-emit. This is the `tags` analog of routing a non-scalar universal
1929/// value to pass-through instead of the destroy path.
1930fn parse_tags_preserving(value: &Value) -> Result<Vec<String>, Value> {
1931    match value {
1932        Value::Sequence(items) => {
1933            let mut out = Vec::with_capacity(items.len());
1934            for item in items {
1935                match item {
1936                    Value::String(s) => out.push(s.clone()),
1937                    Value::Number(n) => out.push(n.to_string()),
1938                    Value::Bool(b) => out.push(b.to_string()),
1939                    // A non-scalar item (nested sequence/mapping/null) means this
1940                    // is not a clean tag list; preserve the whole value verbatim.
1941                    _ => return Err(value.clone()),
1942                }
1943            }
1944            Ok(out)
1945        }
1946        Value::String(s) => Ok(vec![s.clone()]),
1947        Value::Number(n) => Ok(vec![n.to_string()]),
1948        Value::Bool(b) => Ok(vec![b.to_string()]),
1949        // A mapping / null `tags` value is not a list; preserve it verbatim.
1950        _ => Err(value.clone()),
1951    }
1952}
1953
1954/// Render a non-string YAML mapping key as the scalar text YAML would emit for
1955/// it (`2026`, `true`, `3.14`, …), so a numeric/bool/float frontmatter key
1956/// preserves its key *text* on round-trip instead of being rewritten to its Rust
1957/// `Debug` form (`Number(2026)`, `Bool(true)`, `'Null'`). The key re-emits as a
1958/// string-typed key carrying the original text (`'2026':`) — the type narrows to
1959/// string, but the operator's data is no longer corrupted, and ordinary string
1960/// keys are wholly unaffected. Falls back to `Debug` only for a key shape that
1961/// cannot be a scalar (a sequence/mapping key — not expressible in our
1962/// `String`-keyed `extra`), which never occurs in practice.
1963fn yaml_scalar_key(key: &Value) -> String {
1964    match key {
1965        Value::String(s) => s.clone(),
1966        Value::Number(n) => n.to_string(),
1967        Value::Bool(b) => b.to_string(),
1968        Value::Null => "null".to_string(),
1969        // Non-scalar key: not representable as a plain `extra` string key; keep
1970        // the defensive Debug form so nothing panics (unreachable in practice).
1971        other => format!("{other:?}"),
1972    }
1973}
1974
1975/// Parse a single `[[target|display]]` string into a [`WikiLink`] with no
1976/// location, or `None` if the string is not a bare wiki-link. Used for
1977/// frontmatter-valued links where there is no body position to report.
1978fn parse_wiki_link_str(s: &str) -> Option<WikiLink> {
1979    let s = s.trim();
1980    let inner = s.strip_prefix("[[")?.strip_suffix("]]")?;
1981    // Reject anything with further brackets (e.g. the nested flow-form item),
1982    // which is not a clean single wiki-link.
1983    if inner.contains('[') || inner.contains(']') {
1984        return None;
1985    }
1986    let (target, display) = match inner.split_once('|') {
1987        Some((t, d)) => (t.to_string(), Some(d.to_string())),
1988        None => (inner.to_string(), None),
1989    };
1990    Some(WikiLink {
1991        is_full_path: target_is_full_path(&target),
1992        has_md_extension: target_has_md_extension(&target),
1993        target,
1994        display,
1995        location: (PathBuf::new(), 0, 0),
1996    })
1997}
1998
1999/// Extract every wiki-link from a single frontmatter field value, accepting the
2000/// two canonical forms the spec defines (SPEC § Linking):
2001///
2002/// - a **scalar** wiki-link field, in either the quoted (`f: "[[x]]"`) or the
2003///   canonical unquoted inline (`f: [[x]]`) form, and
2004/// - a **list** field whose items are quoted wiki-link strings
2005///   (`- "[[x]]"`).
2006///
2007/// YAML eats the brackets of an unquoted `[[x]]`, leaving a flow-list-in-a-list,
2008/// so the parsed [`Value`] shapes are not what one would naively expect:
2009///
2010/// | source                         | parsed `Value`                     | here |
2011/// |--------------------------------|------------------------------------|------|
2012/// | `f: "[[x]]"`       (quoted)    | `String("[[x]]")`                  | link |
2013/// | `f: [[x]]`         (unquoted)  | `Seq[ Seq[String("x")] ]`          | link |
2014/// | `f:`\n`  - "[[x]]"`(quoted)    | `Seq[ String("[[x]]"), … ]`        | link |
2015/// | `f:`\n`  - [[x]]`  (unquoted)  | `Seq[ Seq[Seq[String("x")]], … ]`  | —    |
2016///
2017/// The last row — an *unquoted list* — parses identically to the flow-form list
2018/// `f: [[a], [b]]` and is a mis-encoding the canonical writer never emits;
2019/// `dbmd validate` reports it as `WIKI_LINK_FLOW_FORM_LIST` (see
2020/// [`detect_flow_form_link_lists`]). It is deliberately NOT surfaced here, so an
2021/// edge enumerator only ever sees the valid canonical forms.
2022///
2023/// The unquoted scalar (`Seq[Seq[String]]`, one element) is told apart from a
2024/// plain one-item flow list (`f: [x]` → `Seq[String]`, one fewer nesting level)
2025/// by [`unquoted_inline_link`] requiring its argument to be a `Sequence`.
2026fn links_in_field_value(value: &Value) -> Vec<WikiLink> {
2027    // Quoted scalar: `field: "[[x]]"`.
2028    if let Value::String(s) = value {
2029        return parse_wiki_link_str(s).into_iter().collect();
2030    }
2031    let Value::Sequence(items) = value else {
2032        return Vec::new();
2033    };
2034    // Unquoted scalar inline form `field: [[x]]` → `Seq[ Seq[String(x)] ]`.
2035    // (A quoted single-item list `["[[x]]"]` is `Seq[String]`, so its lone item
2036    // is a `String`, not a `Sequence`, and falls through to the list path below.)
2037    if items.len() == 1 {
2038        if let Some(link) = unquoted_inline_link(&items[0]) {
2039            return vec![link];
2040        }
2041    }
2042    // Otherwise a list of quoted wiki-link strings; non-string items (the
2043    // unquoted-list mis-encoding) are left for validate to flag.
2044    items
2045        .iter()
2046        .filter_map(|item| parse_wiki_link_str(item.as_str()?))
2047        .collect()
2048}
2049
2050/// Canonicalize one `extra` frontmatter value for emission by [`Frontmatter::to_yaml`].
2051///
2052/// The read path ([`Frontmatter::parse`]) stores every unknown key's raw parsed
2053/// [`Value`] verbatim, so a SPEC-canonical *unquoted* inline scalar wiki-link
2054/// (`company: [[records/companies/northstar]]`) lands in `extra` as the nested
2055/// shape YAML produces for it — `Seq[ Seq[String("records/companies/northstar")] ]`.
2056/// Re-emitting that verbatim yields the block sequence
2057///
2058/// ```text
2059/// company:
2060/// - - records/companies/northstar
2061/// ```
2062///
2063/// which has lost the `[[ ]]` brackets entirely: the link is destroyed, and every
2064/// reader (validate, graph, backlinks) stops seeing the edge. This normalizes such
2065/// a value back into the canonical emitted form before it is written:
2066///
2067/// - a **scalar** wiki-link (quoted `String("[[x]]")` or unquoted `Seq[Seq[String]]`,
2068///   one element) → a quoted scalar `Value::String("[[x]]")`, which serde_norway emits
2069///   inline as `'[[x]]'` — the form the finding confirms survives a round-trip and
2070///   that [`links_in_field_value`] reads back as the same scalar link;
2071/// - a **list** of wiki-links (in any spelling [`links_in_field_value`] accepts) →
2072///   a block `Value::Sequence` of quoted-link strings (`- "[[x]]"`), matching the
2073///   `set` write-in path and the canonical list form;
2074/// - everything else → returned verbatim (the common no-op for non-link values).
2075///
2076/// `|display` is preserved in both link branches. This is the single point that
2077/// keeps all three curator-loop writers (`format`, `fm set`, `link`) from
2078/// corrupting a pre-existing canonical link, since they all funnel through
2079/// `to_yaml`.
2080fn canonicalize_extra_value(value: &Value) -> Value {
2081    match value {
2082        // Scalar wiki-link, quoted form: `field: "[[x]]"` → `String("[[x]]")`.
2083        // Re-emit as a quoted scalar so it stays a string (never the brackets-as-
2084        // YAML nested sequence). Non-link strings are returned untouched.
2085        Value::String(s) => match parse_wiki_link_str(s) {
2086            Some(link) => Value::String(wiki_link_literal(&link)),
2087            None => value.clone(),
2088        },
2089        Value::Sequence(items) => {
2090            // NOTE: we deliberately do NOT collapse a one-element
2091            // `Seq[ Seq[String(x)] ]` to the scalar `String("[[x]]")` here. That
2092            // shape is ambiguous — `serde_norway` parses BOTH an inline scalar
2093            // wiki-link `field: [[x]]` AND a genuine 2D array `field:`\n`- - x`
2094            // to exactly that value, so collapsing it silently retyped a real
2095            // nested array (`matrix: [["cell"]]`) into the string `'[[cell]]'`
2096            // and the file stopped round-tripping. The two cases ARE
2097            // distinguishable, but only from the source text, so the genuine
2098            // inline-link case is resolved at parse time
2099            // ([`Frontmatter::parse`] → [`inline_scalar_link_keys`]), where it is
2100            // stored as a `String("[[x]]")` and handled by the arm above. By the
2101            // time a `Seq[Seq[String]]` reaches here it is a real nested array and
2102            // must pass through verbatim (SPEC § "Unknown fields pass through").
2103            // List of wiki-links: re-emit as a block sequence of quoted-link
2104            // strings, the canonical list form `to_yaml` renders block-style and
2105            // `links_in_field_value` accepts. Only canonicalize when *every* item
2106            // is a clean single wiki-link; a list with any non-link item is left
2107            // verbatim so unrelated sequences (and the unquoted-list mis-encoding
2108            // validate flags) are untouched.
2109            let mut links = Vec::with_capacity(items.len());
2110            for item in items {
2111                match link_from_flow_list_item(item) {
2112                    Some(link) => links.push(link),
2113                    None => return value.clone(),
2114                }
2115            }
2116            if links.is_empty() {
2117                return value.clone();
2118            }
2119            Value::Sequence(
2120                links
2121                    .iter()
2122                    .map(|l| Value::String(wiki_link_literal(l)))
2123                    .collect(),
2124            )
2125        }
2126        // Mappings, scalars other than strings, nulls: nothing to canonicalize.
2127        _ => value.clone(),
2128    }
2129}
2130
2131/// Render a [`WikiLink`] back to its `[[target]]` / `[[target|display]]` literal,
2132/// the inner form the canonical writer emits and `links_in_field_value` accepts.
2133fn wiki_link_literal(link: &WikiLink) -> String {
2134    match &link.display {
2135        Some(d) => format!("[[{}|{}]]", link.target, d),
2136        None => format!("[[{}]]", link.target),
2137    }
2138}
2139
2140/// Recognize the inner token of an unquoted scalar `[[x]]`: after YAML strips the
2141/// outer brackets, the inner `[x]` is a single-element sequence `Seq[String(x)]`.
2142/// Reconstructs `[[x]]` (preserving any `|display`) and parses it, or returns
2143/// `None` when `v` is not that shape. Requiring a `Sequence` here is what keeps a
2144/// plain one-item flow list (`field: [x]` → `Seq[String]`, not `Seq[Seq[String]]`)
2145/// from being mistaken for a wiki-link.
2146fn unquoted_inline_link(v: &Value) -> Option<WikiLink> {
2147    let Value::Sequence(items) = v else {
2148        return None;
2149    };
2150    if items.len() != 1 {
2151        return None;
2152    }
2153    let s = items[0].as_str()?;
2154    // A clean unquoted wiki-link has no further brackets inside it.
2155    if s.contains('[') || s.contains(']') {
2156        return None;
2157    }
2158    parse_wiki_link_str(&format!("[[{s}]]"))
2159}
2160
2161/// Scan raw frontmatter YAML for top-level keys whose value is written in the
2162/// **inline scalar wiki-link** form `key: [[target]]` (optionally
2163/// `[[target|display]]`).
2164///
2165/// This is the one disambiguation the parsed [`Value`] cannot supply on its own:
2166/// `serde_norway` parses BOTH
2167///
2168/// ```yaml
2169/// field: [[x]]
2170/// ```
2171///
2172/// and
2173///
2174/// ```yaml
2175/// field:
2176/// - - x
2177/// ```
2178///
2179/// to the identical `Seq[ Seq[String("x")] ]`. Only the source text says which one
2180/// the operator wrote. [`Frontmatter::parse`] calls this and rewrites the inline
2181/// cases to the canonical scalar `String("[[x]]")`, leaving every genuine nested
2182/// array a sequence (preserved verbatim per SPEC § "Unknown fields pass through").
2183///
2184/// Conservative by construction: a key is reported only when, on a single
2185/// top-level (zero-indent) line, the value after the first `:` is *exactly* one
2186/// `[[…]]` token (whitespace and an optional trailing `# comment` aside) with no
2187/// nested brackets inside. A quoted value (`field: "[[x]]"`), a flow list
2188/// (`field: [[a], [b]]`), a block sequence, or any indented/multi-token value is
2189/// left for the normal parse path. Duplicate keys (last-wins in YAML) are handled
2190/// by the caller looking up the final stored value.
2191fn inline_scalar_link_keys(yaml: &str) -> Vec<String> {
2192    let mut keys = Vec::new();
2193    for line in yaml.lines() {
2194        // Only top-level keys: an indented line is a nested mapping/sequence
2195        // entry, never a top-level `key: [[x]]` scalar.
2196        if line.starts_with(' ') || line.starts_with('\t') {
2197            continue;
2198        }
2199        let Some((raw_key, raw_val)) = line.split_once(':') else {
2200            continue;
2201        };
2202        let key = raw_key.trim();
2203        if key.is_empty() {
2204            continue;
2205        }
2206        // Drop a trailing `# comment` (YAML allows one after a plain scalar on the
2207        // same line). A `#` inside the bracketed link target is not a comment, but
2208        // such a target is rejected below anyway (it would not be a clean link).
2209        let val = match raw_val.split_once(" #") {
2210            Some((before, _)) => before.trim(),
2211            None => raw_val.trim(),
2212        };
2213        // The value must be exactly one bracket-delimited `[[…]]` token: starts
2214        // with `[[`, ends with `]]`, and the inner text carries no further
2215        // brackets (which would make it a flow list / nested collection, not a
2216        // single inline wiki-link).
2217        let Some(inner) = val.strip_prefix("[[").and_then(|s| s.strip_suffix("]]")) else {
2218            continue;
2219        };
2220        if inner.contains('[') || inner.contains(']') {
2221            continue;
2222        }
2223        // Confirm it is actually a parseable wiki-link, not e.g. an empty `[[]]`.
2224        if parse_wiki_link_str(val).is_some() {
2225            keys.push(key.to_string());
2226        }
2227    }
2228    keys
2229}
2230
2231/// Decide whether a `dbmd fm set` / `--fm` value string is a **list of
2232/// wiki-links** that should be stored as a YAML block sequence, returning the
2233/// canonical `Value::Sequence` of quoted-link strings when so.
2234///
2235/// The value path of every write surface stringifies its argument; without this
2236/// a required list-of-links field (`meeting.attendees`) was unwritable in valid
2237/// form — passing `[[[a]], [[b]]]` stored a single scalar string that mis-parses
2238/// and trips `WIKI_LINK_FLOW_FORM_LIST` / `WIKI_LINK_BROKEN`. This recognizes the
2239/// two list spellings an agent naturally types and normalizes both to the block
2240/// form the canonical writer emits and `dbmd validate` accepts:
2241///
2242/// - flow list of quoted links — `["[[a]]", "[[b]]"]`
2243/// - flow list of unquoted links — `[[[a]], [[b]]]` (YAML: `Seq[Seq[String], …]`)
2244///
2245/// Returns `None` (⇒ caller stores a verbatim scalar string) for everything that
2246/// is not unambiguously a list of clean wiki-links — plain text, a single inline
2247/// `[[x]]` (YAML reads it as a one-item `Seq[Seq[String]]`, kept scalar so it
2248/// renders inline), an empty list, or a list with any non-link item. A single
2249/// link must stay scalar; only genuine multi-item-or-explicit lists become
2250/// sequences, matching `links_in_field_value`'s acceptance rule so writer and
2251/// validator never disagree.
2252fn parse_link_list_value(value: &str) -> Option<Value> {
2253    let trimmed = value.trim();
2254    // Only a YAML *flow sequence* literal is a list candidate; anything not
2255    // wrapped in `[ … ]` is a scalar (a bare `[[x]]` is wrapped, and handled by
2256    // the single-inline-link guard below).
2257    if !(trimmed.starts_with('[') && trimmed.ends_with(']')) {
2258        return None;
2259    }
2260    let Ok(Value::Sequence(items)) = serde_norway::from_str::<Value>(trimmed) else {
2261        return None;
2262    };
2263    // A single inline `[[x]]` parses to `Seq[ Seq[String(x)] ]` (one item, itself
2264    // a sequence) — that is the unquoted *scalar* form, not a list. Keep it scalar
2265    // so it round-trips to the inline `field: [[x]]` rather than a one-item block
2266    // list. `links_in_field_value` reads it back as a scalar link either way.
2267    if items.len() == 1 && unquoted_inline_link(&items[0]).is_some() {
2268        return None;
2269    }
2270    // Every item must resolve to exactly one clean wiki-link, in any of the flow
2271    // spellings an agent types (see [`link_from_flow_list_item`]).
2272    let mut links = Vec::with_capacity(items.len());
2273    for item in &items {
2274        links.push(link_from_flow_list_item(item)?);
2275    }
2276    if links.is_empty() {
2277        return None;
2278    }
2279    // Normalize to a block sequence of quoted-link strings — the form `to_yaml`
2280    // renders block-style and `links_in_field_value` accepts. `|display` is
2281    // preserved.
2282    let normalized = links
2283        .iter()
2284        .map(|l| Value::String(wiki_link_literal(l)))
2285        .collect();
2286    Some(Value::Sequence(normalized))
2287}
2288
2289/// Recognize one clean wiki-link from a single **item** of a YAML flow sequence,
2290/// across the spellings an agent types for a list. After top-level flow parsing,
2291/// a list item arrives in one of:
2292///
2293/// - quoted — `"[[x]]"` ⇒ `String("[[x]]")`
2294/// - unquoted in a flow list — `[[x]]` inside `[…]` ⇒ `Seq[ Seq[String(x)] ]`
2295///   (one level deeper than a bare unquoted scalar, because the surrounding list
2296///   adds a wrapper); unwrap the single-element wrapper, then read the inline
2297///   `Seq[String(x)]` with [`unquoted_inline_link`].
2298///
2299/// Returns `None` for any item that is not exactly one clean wiki-link, so the
2300/// caller falls back to a scalar string and never fabricates a partial list.
2301fn link_from_flow_list_item(item: &Value) -> Option<WikiLink> {
2302    match item {
2303        Value::String(s) => parse_wiki_link_str(s),
2304        Value::Sequence(inner) => {
2305            // Unquoted list item `[[x]]` → `Seq[ Seq[String(x)] ]`: peel the lone
2306            // wrapper to expose the inline-link shape `Seq[String(x)]`.
2307            //
2308            // Only this triple-nested shape is a wiki-link. We deliberately do
2309            // NOT fall back to `unquoted_inline_link(item)` on the bare double
2310            // nesting `Seq[String(x)]` (a plain one-element string list `[x]`):
2311            // that fallback fabricated a wiki-link out of an ordinary nested
2312            // string list — `groups: [[alpha], [beta]]` (data `[["alpha"],
2313            // ["beta"]]`) was rewritten to `- '[[alpha]]'` / `- '[[beta]]'`,
2314            // silently changing the field's type and manufacturing short-form
2315            // links the tool then flags as `WIKI_LINK_SHORT_FORM`. An unknown
2316            // nested string list must pass through verbatim (SPEC § "Unknown
2317            // fields pass through").
2318            if inner.len() == 1 {
2319                if let Some(link) = unquoted_inline_link(&inner[0]) {
2320                    return Some(link);
2321                }
2322            }
2323            None
2324        }
2325        _ => None,
2326    }
2327}
2328
2329/// A target is a full store-relative path when its first path segment is one of
2330/// the three canonical layer dirs and at least one `/` separator follows. A
2331/// trailing `.md` does not affect this classification.
2332fn target_is_full_path(target: &str) -> bool {
2333    let target = target.trim();
2334    match target.split_once('/') {
2335        Some((head, _rest)) => LAYER_DIRS.contains(&head),
2336        None => false,
2337    }
2338}
2339
2340/// True when the target carries a trailing `.md` extension (validate warns
2341/// `WIKI_LINK_HAS_EXTENSION`).
2342fn target_has_md_extension(target: &str) -> bool {
2343    target.trim().ends_with(".md")
2344}
2345
2346/// A forward-only cursor that yields the 1-based character (Unicode scalar)
2347/// column of successive byte offsets within a single line in ONE linear pass.
2348///
2349/// The previous helper recomputed `line[..offset].chars().count()` from the line
2350/// start for every match, so a line with N matches cost O(N × line_len) — a
2351/// quadratic blowup on a link-dense line. Because regex matches arrive in
2352/// non-decreasing byte order, this cursor advances the char count only across the
2353/// gap since the last queried offset, giving O(line_len) total per line.
2354///
2355/// Offsets MUST be queried in non-decreasing order and must fall on UTF-8
2356/// character boundaries (regex match starts always do).
2357struct ColCursor {
2358    byte: usize,
2359    chars: u32,
2360}
2361
2362impl ColCursor {
2363    fn new() -> Self {
2364        ColCursor { byte: 0, chars: 0 }
2365    }
2366
2367    /// 1-based character column of `byte_offset` in `line`. `byte_offset` must be
2368    /// `>=` every previously queried offset (debug-asserted).
2369    fn column_at(&mut self, line: &str, byte_offset: usize) -> u32 {
2370        debug_assert!(byte_offset >= self.byte, "ColCursor queried out of order");
2371        self.chars += line[self.byte..byte_offset].chars().count() as u32;
2372        self.byte = byte_offset;
2373        self.chars + 1
2374    }
2375}
2376
2377/// Index of the first comma-token in `raw[from..]` that *starts a greedy
2378/// modifier clause* (`enum`, `enum:…`, or `default …`), or `raw.len()` when none
2379/// remain. Used to bound a greedy `default`/`enum` value so it stops at the next
2380/// such clause instead of either truncating at the first comma or swallowing a
2381/// following greedy clause whole.
2382fn next_greedy_clause(raw: &[&str], from: usize) -> usize {
2383    let mut j = from;
2384    while j < raw.len() {
2385        let lower = raw[j].trim().to_ascii_lowercase();
2386        if lower == "enum" || lower.starts_with("enum:") || lower.starts_with("default ") {
2387            return j;
2388        }
2389        j += 1;
2390    }
2391    raw.len()
2392}
2393
2394/// Map a lowercase shape keyword to its [`Shape`].
2395fn shape_from_str(s: &str) -> Option<Shape> {
2396    match s {
2397        "string" => Some(Shape::String),
2398        "int" => Some(Shape::Int),
2399        "bool" => Some(Shape::Bool),
2400        "date" => Some(Shape::Date),
2401        "email" => Some(Shape::Email),
2402        "currency" => Some(Shape::Currency),
2403        "url" => Some(Shape::Url),
2404        _ => None,
2405    }
2406}
2407
2408/// The ATX heading level of a line (number of leading `#`), or 0 if not a
2409/// heading. Up to three leading spaces (CommonMark), requires a space/tab (or
2410/// end-of-line) after the `#` run, caps the run at six.
2411fn heading_level(line: &str) -> u8 {
2412    let indent = line.len() - line.trim_start_matches(' ').len();
2413    if indent > 3 {
2414        return 0;
2415    }
2416    let rest = &line[indent..];
2417    let hashes = rest.len() - rest.trim_start_matches('#').len();
2418    if hashes == 0 || hashes > 6 {
2419        return 0;
2420    }
2421    let after = &rest[hashes..];
2422    if after.is_empty() || after.starts_with(' ') || after.starts_with('\t') {
2423        hashes as u8
2424    } else {
2425        0
2426    }
2427}
2428
2429/// The heading text after the `#` run, trimmed, with a trailing ATX *closing*
2430/// `#` sequence removed per CommonMark (`## Title ##` → `Title`).
2431///
2432/// CommonMark only treats a trailing run of `#` as a closing sequence when it is
2433/// **preceded by a space or tab** (or the content is empty). A `#` that abuts the
2434/// preceding word is literal heading text: `## C#` → `C#`, `## F#` → `F#`,
2435/// `## issue-123#` → `issue-123#`. The old unconditional `trim_end_matches('#')`
2436/// stripped those, corrupting `dbmd sections`/`outline` heading text and — via
2437/// `parse_db_md` using the heading verbatim as the schema type key — silently
2438/// binding a `### c#` schema to `type: c` instead of `type: c#`.
2439fn heading_text(line: &str, level: u8) -> String {
2440    let indent = line.len() - line.trim_start_matches(' ').len();
2441    let after_hashes = &line[indent + level as usize..];
2442    let trimmed = after_hashes.trim();
2443
2444    // Peel a trailing run of `#`. It is a closing sequence only if what precedes
2445    // it (within `trimmed`) is empty or ends in a space/tab; otherwise the `#`s
2446    // are literal content.
2447    let without_hashes = trimmed.trim_end_matches('#');
2448    if without_hashes.len() == trimmed.len() {
2449        // No trailing `#` at all.
2450        return trimmed.to_string();
2451    }
2452    if without_hashes.is_empty() || without_hashes.ends_with([' ', '\t']) {
2453        // A genuine closing sequence (`## Title ##`, `## ##`): drop it and the
2454        // whitespace before it.
2455        without_hashes.trim_end().to_string()
2456    } else {
2457        // The `#` run abuts content (`## C#`): keep it as literal heading text.
2458        trimmed.to_string()
2459    }
2460}
2461
2462/// If `line` opens a fenced code block, return `(fence byte, run length)`.
2463fn opening_fence(line: &str) -> Option<(u8, usize)> {
2464    let indent = line.len() - line.trim_start_matches(' ').len();
2465    if indent > 3 {
2466        return None;
2467    }
2468    let rest = &line[indent..];
2469    let byte = rest.bytes().next()?;
2470    if byte != b'`' && byte != b'~' {
2471        return None;
2472    }
2473    let run = rest.len() - rest.trim_start_matches(byte as char).len();
2474    if run < 3 {
2475        return None;
2476    }
2477    // A backtick fence's info string may not itself contain a backtick.
2478    if byte == b'`' && rest[run..].contains('`') {
2479        return None;
2480    }
2481    Some((byte, run))
2482}
2483
2484/// True if `line` closes the currently open fence: same char, run at least as
2485/// long, nothing but trailing whitespace after.
2486fn is_closing_fence(line: &str, fence: (u8, usize)) -> bool {
2487    let (byte, open_len) = fence;
2488    let indent = line.len() - line.trim_start_matches(' ').len();
2489    if indent > 3 {
2490        return false;
2491    }
2492    let rest = &line[indent..];
2493    let run = rest.len() - rest.trim_start_matches(byte as char).len();
2494    if run < open_len {
2495        return false;
2496    }
2497    rest[run..].trim().is_empty()
2498}
2499
2500/// The prose body of a section: everything after the heading line, trimmed.
2501fn section_prose(section_body: &str) -> String {
2502    match section_body.split_once('\n') {
2503        Some((_heading, rest)) => rest.trim().to_string(),
2504        None => String::new(),
2505    }
2506}
2507
2508/// The bullet lines (`-`/`*`/`+`) of a section body, excluding the heading
2509/// line, each returned with its leading whitespace trimmed.
2510fn bullet_lines(section_body: &str) -> Vec<String> {
2511    section_body
2512        .lines()
2513        .skip(1) // the heading line
2514        .map(str::trim)
2515        .filter(|l| l.starts_with("- ") || l.starts_with("* ") || l.starts_with("+ "))
2516        .map(|l| l.to_string())
2517        .collect()
2518}
2519
2520/// Cut a bullet's content at the first comment separator, returning only the
2521/// meaningful prefix. Recognizes the em-dash (` — `), en-dash (` – `), double-
2522/// hyphen (` -- `), and the plain single-ASCII-hyphen (` - `) spellings an
2523/// operator naturally types — without the single-hyphen form, a comment like
2524/// `records/decisions/q3.md - finalized` left the whole line (comment included)
2525/// as the frozen path, so the entry never matched and the freeze failed OPEN.
2526/// A store-relative path never contains a ` - ` (paths are `/`-joined, spaceless),
2527/// so this does not truncate legitimate path text.
2528fn strip_bullet_comment(content: &str) -> &str {
2529    let mut cut = content.len();
2530    for sep in [" — ", " -- ", " – ", " - "] {
2531        if let Some(idx) = content.find(sep) {
2532            cut = cut.min(idx);
2533        }
2534    }
2535    content[..cut].trim()
2536}
2537
2538/// Strip the leading bullet marker, returning the trimmed content after it.
2539fn bullet_content(bullet: &str) -> &str {
2540    let t = bullet.trim();
2541    t.strip_prefix("- ")
2542        .or_else(|| t.strip_prefix("* "))
2543        .or_else(|| t.strip_prefix("+ "))
2544        .unwrap_or(t)
2545        .trim()
2546}
2547
2548/// Extract a store-relative path from a Frozen-pages bullet. The path may be
2549/// wrapped in backticks and followed by an em-dash comment.
2550fn extract_path_bullet(bullet: &str) -> String {
2551    let content = bullet_content(bullet);
2552    // Prefer a backtick-delimited span if present.
2553    if let Some(start) = content.find('`') {
2554        if let Some(end_rel) = content[start + 1..].find('`') {
2555            return content[start + 1..start + 1 + end_rel].trim().to_string();
2556        }
2557    }
2558    // Otherwise take the text up to a comment separator, stripping quotes.
2559    strip_bullet_comment(content)
2560        .trim_matches('"')
2561        .trim_matches('\'')
2562        .trim()
2563        .to_string()
2564}
2565
2566/// Extract a comma-separated type list from an Ignored-types bullet, stripping
2567/// backticks/quotes and any trailing em-dash comment.
2568fn extract_type_list_bullet(bullet: &str) -> Vec<String> {
2569    let content = strip_bullet_comment(bullet_content(bullet));
2570    content
2571        .split(',')
2572        .map(|t| {
2573            t.trim()
2574                .trim_matches('`')
2575                .trim_matches('"')
2576                .trim_matches('\'')
2577                .trim()
2578                .to_string()
2579        })
2580        .filter(|t| !t.is_empty())
2581        .collect()
2582}
2583
2584#[cfg(test)]
2585mod tests {
2586    use super::*;
2587
2588    #[test]
2589    fn read_file_refuses_oversized_sparse_input_before_allocating() {
2590        let dir = tempfile::tempdir().unwrap();
2591        let path = dir.path().join("hostile.md");
2592        let file = std::fs::File::create(&path).unwrap();
2593        file.set_len(MAX_DBMD_FILE_BYTES + 1).unwrap();
2594
2595        let err = read_file(&path).unwrap_err();
2596        assert!(
2597            matches!(err, ParseError::Io(ref io) if io.kind() == std::io::ErrorKind::InvalidData),
2598            "oversized file must fail at the metadata gate: {err:?}"
2599        );
2600    }
2601    use std::path::Path;
2602    use tempfile::tempdir;
2603
2604    // ── Config::frozen_match (the single write-surface policy matcher) ───────
2605
2606    #[test]
2607    fn frozen_match_is_md_insensitive_both_directions() {
2608        // A policy entry stored WITHOUT `.md` (the natural extensionless
2609        // spelling `parse_db_md` keeps verbatim) must still match a `.md`
2610        // write target — the regression every write surface had.
2611        let cfg = Config {
2612            frozen_pages: vec![PathBuf::from("records/decisions/q1")],
2613            ..Config::default()
2614        };
2615        assert_eq!(
2616            cfg.frozen_match(Path::new("records/decisions/q1.md")),
2617            Some(PathBuf::from("records/decisions/q1")),
2618            "extensionless policy entry must freeze the .md file"
2619        );
2620        assert!(cfg.is_frozen(Path::new("records/decisions/q1.md")));
2621
2622        // The symmetric case: a policy entry WITH `.md` matches a bare target.
2623        let cfg = Config {
2624            frozen_pages: vec![PathBuf::from("records/decisions/q1.md")],
2625            ..Config::default()
2626        };
2627        assert_eq!(
2628            cfg.frozen_match(Path::new("records/decisions/q1")),
2629            Some(PathBuf::from("records/decisions/q1.md")),
2630        );
2631        // And the same-spelling cases still match.
2632        assert!(cfg.is_frozen(Path::new("records/decisions/q1.md")));
2633    }
2634
2635    #[test]
2636    fn frozen_match_drops_leading_dot_slash() {
2637        let cfg = Config {
2638            frozen_pages: vec![PathBuf::from("records/decisions/q1.md")],
2639            ..Config::default()
2640        };
2641        assert!(cfg.is_frozen(Path::new("./records/decisions/q1.md")));
2642        assert!(cfg.is_frozen(Path::new("./records/decisions/q1")));
2643    }
2644
2645    #[test]
2646    fn frozen_match_returns_none_for_unlisted_and_prefix_paths() {
2647        let cfg = Config {
2648            frozen_pages: vec![PathBuf::from("records/decisions/q1")],
2649            ..Config::default()
2650        };
2651        assert!(cfg
2652            .frozen_match(Path::new("records/decisions/q2.md"))
2653            .is_none());
2654        // A prefix is not a match: `q1` must not freeze `q1-draft`.
2655        assert!(cfg
2656            .frozen_match(Path::new("records/decisions/q1-draft.md"))
2657            .is_none());
2658        assert!(!cfg.is_frozen(Path::new("records/decisions/q11.md")));
2659    }
2660
2661    // ── split_frontmatter ───────────────────────────────────────────────────
2662
2663    #[test]
2664    fn split_frontmatter_separates_yaml_and_verbatim_body() {
2665        let text = "---\ntype: contact\nsummary: x\n---\n# Heading\n\nBody line.\n";
2666        let p = split_frontmatter(text, Path::new("f.md")).unwrap();
2667        assert_eq!(p.frontmatter_yaml, "type: contact\nsummary: x\n");
2668        // Body is everything after the closing fence's newline, byte-for-byte.
2669        assert_eq!(p.body, "# Heading\n\nBody line.\n");
2670    }
2671
2672    #[test]
2673    fn split_frontmatter_preserves_body_without_trailing_newline() {
2674        let text = "---\ntype: x\n---\nno trailing newline";
2675        let p = split_frontmatter(text, Path::new("f.md")).unwrap();
2676        assert_eq!(p.body, "no trailing newline");
2677    }
2678
2679    #[test]
2680    fn split_frontmatter_empty_body_when_nothing_after_fence() {
2681        let text = "---\ntype: x\n---\n";
2682        let p = split_frontmatter(text, Path::new("f.md")).unwrap();
2683        assert_eq!(p.body, "");
2684    }
2685
2686    #[test]
2687    fn split_frontmatter_missing_opening_fence_errors() {
2688        let text = "# No frontmatter here\ntype: x\n";
2689        let err = split_frontmatter(text, Path::new("f.md")).unwrap_err();
2690        assert!(matches!(err, ParseError::MissingFrontmatter { .. }));
2691    }
2692
2693    #[test]
2694    fn split_frontmatter_leading_content_before_fence_rejected() {
2695        // The opening fence must be the very first line; a blank line first is
2696        // not allowed.
2697        let text = "\n---\ntype: x\n---\nbody";
2698        let err = split_frontmatter(text, Path::new("f.md")).unwrap_err();
2699        assert!(matches!(err, ParseError::MissingFrontmatter { .. }));
2700    }
2701
2702    #[test]
2703    fn split_frontmatter_unterminated_block_errors() {
2704        let text = "---\ntype: x\nsummary: y\n";
2705        let err = split_frontmatter(text, Path::new("f.md")).unwrap_err();
2706        assert!(matches!(err, ParseError::MissingFrontmatter { .. }));
2707    }
2708
2709    // ── Frontmatter::parse ───────────────────────────────────────────────────
2710
2711    #[test]
2712    fn parse_populates_typed_fields_and_routes_unknowns_to_extra() {
2713        let yaml = "type: contact\nid: sarah-chen\nsummary: Director of Ops\nstatus: active\ntags: [vip, renewal]\nemail: sarah@northstar.io\nrole: Director";
2714        let fm = Frontmatter::parse(yaml, Path::new("f.md")).unwrap();
2715        assert_eq!(fm.type_.as_deref(), Some("contact"));
2716        assert_eq!(fm.id.as_deref(), Some("sarah-chen"));
2717        assert_eq!(fm.summary.as_deref(), Some("Director of Ops"));
2718        assert_eq!(fm.status.as_deref(), Some("active"));
2719        assert_eq!(fm.tags, vec!["vip".to_string(), "renewal".to_string()]);
2720        // Type-specific fields are NOT promoted to typed slots.
2721        assert!(fm.type_.is_some() && !fm.extra.contains_key("type"));
2722        assert!(!fm.extra.contains_key("tags"));
2723        assert_eq!(
2724            fm.extra.get("email").and_then(|v| v.as_str()),
2725            Some("sarah@northstar.io")
2726        );
2727        assert_eq!(
2728            fm.extra.get("role").and_then(|v| v.as_str()),
2729            Some("Director")
2730        );
2731    }
2732
2733    #[test]
2734    fn parse_reads_rfc3339_timestamps() {
2735        let yaml =
2736            "type: email\ncreated: 2026-05-27T08:00:00-07:00\nupdated: 2026-05-28T09:30:00-07:00";
2737        let fm = Frontmatter::parse(yaml, Path::new("f.md")).unwrap();
2738        let created = fm.created.expect("created parsed");
2739        // -07:00 offset is 7 * 3600 seconds west.
2740        assert_eq!(created.offset().utc_minus_local(), 7 * 3600);
2741        assert_eq!(created.to_rfc3339(), "2026-05-27T08:00:00-07:00");
2742        assert!(fm.updated.is_some());
2743    }
2744
2745    #[test]
2746    fn parse_preserves_non_rfc3339_timestamp_verbatim() {
2747        // A date-only value is not a full RFC3339 timestamp, so the typed
2748        // accessor stays None — but the READ path must never destroy it or
2749        // refuse the file. It rides in `extra` and round-trips byte-for-byte,
2750        // exactly like a non-scalar `type`/`summary`. `validate` is what
2751        // reports it (FM_BAD_TIMESTAMP, raised from the raw YAML value).
2752        //
2753        // Regression: erroring here made `dbmd format` (and `fm`/`link`/
2754        // `rename`, all of which go through `read_file`) fail outright on any
2755        // store carrying a legacy date-only stamp — the common migrated shape.
2756        let yaml = "type: email\ncreated: 2026-05-27";
2757        let fm = Frontmatter::parse(yaml, Path::new("bad.md")).unwrap();
2758        assert!(
2759            fm.created.is_none(),
2760            "unparseable stamp offers no typed value"
2761        );
2762        assert_eq!(
2763            fm.extra.get("created").and_then(Value::as_str),
2764            Some("2026-05-27"),
2765            "the operator's bytes must survive the read"
2766        );
2767        assert!(
2768            fm.to_yaml().contains("created: 2026-05-27"),
2769            "and must re-emit verbatim; got:\n{}",
2770            fm.to_yaml()
2771        );
2772    }
2773
2774    #[test]
2775    fn set_still_refuses_to_author_a_bad_timestamp() {
2776        // The read/write asymmetry is the point: tolerate what a store already
2777        // contains, never CREATE a malformed value. (`set_timestamp_validates_
2778        // rfc3339` covers the same boundary from the write side.)
2779        let mut fm = Frontmatter::parse("type: email\ncreated: 2026-05-27", Path::new("b.md"))
2780            .expect("read tolerates the legacy stamp");
2781        assert!(matches!(
2782            fm.set("created", "still-not-a-date").unwrap_err(),
2783            ParseError::BadTimestamp { .. }
2784        ));
2785    }
2786
2787    #[test]
2788    fn parse_malformed_yaml_errors() {
2789        // Unclosed flow mapping is invalid YAML.
2790        let yaml = "type: contact\n  bad: : :\n- nope";
2791        let err = Frontmatter::parse(yaml, Path::new("bad.md")).unwrap_err();
2792        assert!(matches!(err, ParseError::MalformedYaml { .. }));
2793    }
2794
2795    #[test]
2796    fn frontmatter_with_yaml_tag_on_mapping_does_not_panic() {
2797        // Regression: a YAML tag on the top-level mapping made the old
2798        // `expect_err` path PANIC, because a tagged mapping deserializes to a
2799        // `Mapping` just fine. It must now be handled — accepted as the inner
2800        // mapping, never a panic.
2801        let fm = Frontmatter::parse("!mytag\ntype: contact\nsummary: hi\n", Path::new("x.md"))
2802            .expect("tagged-mapping frontmatter must parse, not panic");
2803        assert_eq!(fm.type_.as_deref(), Some("contact"));
2804        // A genuine scalar/sequence top level is still malformed (and still
2805        // doesn't panic).
2806        assert!(Frontmatter::parse("- a\n- b\n", Path::new("x.md")).is_err());
2807    }
2808
2809    #[test]
2810    fn parse_empty_block_is_empty_frontmatter() {
2811        let fm = Frontmatter::parse("", Path::new("f.md")).unwrap();
2812        assert_eq!(fm, Frontmatter::default());
2813    }
2814
2815    #[test]
2816    fn parse_scalar_top_level_is_malformed() {
2817        // A bare scalar at the top level is not a frontmatter mapping.
2818        let err = Frontmatter::parse("just a string", Path::new("f.md")).unwrap_err();
2819        assert!(matches!(err, ParseError::MalformedYaml { .. }));
2820    }
2821
2822    // ── to_yaml canonical order ──────────────────────────────────────────────
2823
2824    #[test]
2825    fn to_yaml_emits_canonical_key_order() {
2826        let mut fm = Frontmatter {
2827            type_: Some("contact".into()),
2828            id: Some("sarah-chen".into()),
2829            summary: Some("Director of Ops".into()),
2830            status: Some("active".into()),
2831            tags: vec!["vip".into()],
2832            created: Some(DateTime::parse_from_rfc3339("2026-05-27T08:00:00-07:00").unwrap()),
2833            updated: Some(DateTime::parse_from_rfc3339("2026-05-28T09:30:00-07:00").unwrap()),
2834            ..Default::default()
2835        };
2836        // Two type-specific fields, inserted in NON-alphabetical order to prove
2837        // the writer sorts them (BTreeMap) between the universal head and tail.
2838        fm.extra
2839            .insert("role".into(), Value::String("Director".into()));
2840        fm.extra.insert(
2841            "company".into(),
2842            Value::String("[[records/companies/northstar]]".into()),
2843        );
2844
2845        let yaml = fm.to_yaml();
2846        let keys: Vec<&str> = yaml
2847            .lines()
2848            .filter(|l| !l.starts_with(['-', ' ']) && l.contains(':'))
2849            .map(|l| l.split(':').next().unwrap())
2850            .collect();
2851        assert_eq!(
2852            keys,
2853            vec![
2854                "type", "id", "created", "updated", "summary", // universal head
2855                "company", "role",   // type-specific, sorted
2856                "status", // universal tail
2857                "tags",
2858            ],
2859            "canonical order violated; got:\n{yaml}"
2860        );
2861        // Timestamps round-trip as RFC3339 strings (YAML may quote them).
2862        assert!(
2863            yaml.contains("2026-05-27T08:00:00-07:00"),
2864            "created timestamp missing; got:\n{yaml}"
2865        );
2866        // The value re-parses to the same instant regardless of quoting.
2867        let reparsed = Frontmatter::parse(&yaml, Path::new("rt.md")).unwrap();
2868        assert_eq!(reparsed.created, fm.created);
2869        assert_eq!(reparsed.updated, fm.updated);
2870    }
2871
2872    /// Format v0.4: a minted-form (lowercase ULID) `id` round-trips verbatim
2873    /// through parse → to_yaml → parse and holds its canonical head slot —
2874    /// directly after `type` (and after `meta-type` when one is present),
2875    /// before `created`. Pins the emit order for the id-carrying record shape
2876    /// `dbmd write` produces.
2877    #[test]
2878    fn ulid_id_roundtrips_verbatim_in_head_position() {
2879        let ulid = "01j5qc3v9k4ym8rwbn2tqe6f7d";
2880        let yaml = format!(
2881            "type: profile\nmeta-type: conclusion\nid: {ulid}\ncreated: 2026-05-27T08:00:00-07:00\nupdated: 2026-05-27T08:00:00-07:00\nsummary: x\n"
2882        );
2883        let fm = Frontmatter::parse(&yaml, Path::new("rt.md")).unwrap();
2884        assert_eq!(
2885            fm.id.as_deref(),
2886            Some(ulid),
2887            "id must parse into the typed field"
2888        );
2889
2890        let emitted = fm.to_yaml();
2891        let keys: Vec<&str> = emitted
2892            .lines()
2893            .filter(|l| !l.starts_with(['-', ' ']) && l.contains(':'))
2894            .map(|l| l.split(':').next().unwrap())
2895            .collect();
2896        assert_eq!(
2897            keys,
2898            vec!["type", "meta-type", "id", "created", "updated", "summary"],
2899            "id must sit in the universal head; got:\n{emitted}"
2900        );
2901        assert!(
2902            emitted.contains(&format!("id: {ulid}")),
2903            "ULID must emit unquoted and verbatim; got:\n{emitted}"
2904        );
2905        let reparsed = Frontmatter::parse(&emitted, Path::new("rt.md")).unwrap();
2906        assert_eq!(reparsed.id.as_deref(), Some(ulid));
2907        assert_eq!(reparsed, fm, "round-trip must be lossless");
2908    }
2909
2910    #[test]
2911    fn to_yaml_omits_absent_optional_fields() {
2912        let fm = Frontmatter {
2913            type_: Some("note".into()),
2914            ..Default::default()
2915        };
2916        let yaml = fm.to_yaml();
2917        assert!(yaml.contains("type: note"));
2918        assert!(!yaml.contains("status"));
2919        assert!(!yaml.contains("tags"));
2920        assert!(!yaml.contains("summary"));
2921    }
2922
2923    // ── Regression: non-string scalar universal fields round-trip (finding #1) ─
2924
2925    #[test]
2926    fn regression_parse_preserves_non_string_scalar_universal_fields() {
2927        // A hand/externally-authored file whose universal fields are bare
2928        // scalars YAML reads as Number/Bool — `id: 100`, `summary: 2026`,
2929        // `status: 0`, `type: 42` — must be PRESERVED as their string form, not
2930        // read as None. Before the fix, `v.as_str()` returned None for these and
2931        // the matched arm discarded the value entirely (never reaching `extra`).
2932        let yaml = "type: 42\nid: 100\nsummary: 2026\nstatus: 0";
2933        let fm = Frontmatter::parse(yaml, Path::new("x.md")).unwrap();
2934        assert_eq!(fm.type_.as_deref(), Some("42"), "type scalar dropped");
2935        assert_eq!(fm.id.as_deref(), Some("100"), "id scalar dropped");
2936        assert_eq!(
2937            fm.summary.as_deref(),
2938            Some("2026"),
2939            "summary scalar dropped"
2940        );
2941        assert_eq!(fm.status.as_deref(), Some("0"), "status scalar dropped");
2942        // The values must surface through the public `get` accessor too.
2943        assert_eq!(
2944            fm.get("summary")
2945                .and_then(|v| v.as_str().map(str::to_string)),
2946            Some("2026".to_string())
2947        );
2948    }
2949
2950    #[test]
2951    fn regression_format_round_trip_does_not_delete_numeric_frontmatter() {
2952        // The exact finding-#1 trigger: `dbmd format` is read_file -> write_file.
2953        // A file whose `id`/`summary`/`status` are bare numeric scalars must
2954        // still carry those fields after the canonical re-emit. Before the fix,
2955        // the lines were silently deleted from disk (only `type` survived).
2956        let dir = tempdir().unwrap();
2957        let path = dir.path().join("x.md");
2958        let original = "---\ntype: contact\nid: 100\nsummary: 2026\nstatus: 0\n---\nbody\n";
2959        std::fs::write(&path, original).unwrap();
2960
2961        // Re-emit through the canonical writer, exactly as `dbmd format` does.
2962        let (fm, body) = read_file(&path).unwrap();
2963        write_file(&path, &fm, &body).unwrap();
2964
2965        let after = std::fs::read_to_string(&path).unwrap();
2966        // None of the four fields may vanish; they survive as string scalars.
2967        let reparsed = Frontmatter::parse(
2968            &split_frontmatter(&after, &path).unwrap().frontmatter_yaml,
2969            &path,
2970        )
2971        .unwrap();
2972        assert_eq!(reparsed.type_.as_deref(), Some("contact"));
2973        assert_eq!(reparsed.id.as_deref(), Some("100"), "id deleted by format");
2974        assert_eq!(
2975            reparsed.summary.as_deref(),
2976            Some("2026"),
2977            "summary deleted by format"
2978        );
2979        assert_eq!(
2980            reparsed.status.as_deref(),
2981            Some("0"),
2982            "status deleted by format"
2983        );
2984        // The body is preserved verbatim.
2985        assert_eq!(body, "body\n");
2986    }
2987
2988    #[test]
2989    fn regression_format_round_trip_preserves_oversized_integer_frontmatter() {
2990        // Adversarial review #6: a bare integer literal beyond i64/u64 range must
2991        // survive `dbmd format` (read_file -> write_file) byte-for-byte. Before
2992        // the fix, serde_norway silently truncated `> u128::MAX` to f64 (`999…9`
2993        // -> `1e39`) and hard-rejected `(u64::MAX, u128::MAX]` — corrupting an
2994        // imported numeric ID and breaking the unknown-field round-trip contract.
2995        let dir = tempdir().unwrap();
2996        let path = dir.path().join("x.md");
2997        let big = "999999999999999999999999999999999999999"; // 39 digits, > u128::MAX
2998        let mid = "99999999999999999999"; // 20 digits, in (u64::MAX, u128::MAX]
2999        let original = format!(
3000            "---\ntype: contact\nsummary: x\naccount_number: {big}\nid_num: {mid}\n---\nbody\n"
3001        );
3002        std::fs::write(&path, &original).unwrap();
3003
3004        // Two round-trips: the value must survive verbatim AND be idempotent.
3005        for _ in 0..2 {
3006            let (fm, body) = read_file(&path).expect("oversized-int frontmatter must parse");
3007            write_file(&path, &fm, &body).unwrap();
3008            let after = std::fs::read_to_string(&path).unwrap();
3009            assert!(
3010                after.contains(big),
3011                "39-digit integer corrupted by format:\n{after}"
3012            );
3013            assert!(
3014                after.contains(mid),
3015                "20-digit integer corrupted by format:\n{after}"
3016            );
3017            assert!(
3018                !after.to_lowercase().contains("1e39"),
3019                "integer was truncated to a float:\n{after}"
3020            );
3021            assert_eq!(body, "body\n", "body must be preserved verbatim");
3022        }
3023    }
3024
3025    #[test]
3026    fn oversized_int_literal_detection_is_precise() {
3027        // In range (serde_norway handles losslessly) → never quoted.
3028        for ok in [
3029            "0",
3030            "42",
3031            "-17",
3032            "9223372036854775807",
3033            "18446744073709551615",
3034            "12.5",
3035            "007",
3036            "abc",
3037            "",
3038        ] {
3039            assert!(
3040                !is_oversized_int_literal(ok),
3041                "must NOT be flagged oversized: {ok:?}"
3042            );
3043        }
3044        // Beyond i64/u64 → quoted to preserve the literal.
3045        for big in [
3046            "18446744073709551616",                    // u64::MAX + 1
3047            "99999999999999999999",                    // 20 digits
3048            "999999999999999999999999999999999999999", // 39 digits
3049            "-9999999999999999999999",                 // very negative
3050        ] {
3051            assert!(
3052                is_oversized_int_literal(big),
3053                "must be flagged oversized: {big:?}"
3054            );
3055        }
3056    }
3057
3058    #[test]
3059    fn regression_oversized_int_in_flow_sequence_round_trips() {
3060        // The single-line flow SEQUENCE form regressed: an oversized int inside
3061        // `ids: [123…]` reached serde_norway un-quoted and hard-failed the whole
3062        // block as MalformedYaml (`as u128`), making every read surface
3063        // (format / fm get/set / link / validate) unable to read the file at all.
3064        // It must now parse, preserve the literal verbatim, and be idempotent.
3065        let dir = tempdir().unwrap();
3066        let path = dir.path().join("f.md");
3067        let big = "123456789012345678901234567890"; // 30 digits, > u128::MAX
3068        let original = format!("---\ntype: note\nsummary: x\nids: [{big}]\n---\nbody\n");
3069        std::fs::write(&path, &original).unwrap();
3070
3071        for _ in 0..2 {
3072            let (fm, body) = read_file(&path).expect("flow-sequence oversized int must parse");
3073            // The list value survives in `extra`, holding the literal as a string.
3074            let ids = fm.extra.get("ids").expect("ids field preserved");
3075            assert!(
3076                matches!(ids, Value::Sequence(_)),
3077                "ids should stay a sequence, got: {ids:?}"
3078            );
3079            write_file(&path, &fm, &body).unwrap();
3080            let after = std::fs::read_to_string(&path).unwrap();
3081            assert!(
3082                after.contains(big),
3083                "30-digit integer in flow sequence corrupted by format:\n{after}"
3084            );
3085            assert!(
3086                !after.to_lowercase().contains("1.234"),
3087                "integer was truncated to a float:\n{after}"
3088            );
3089            assert_eq!(body, "body\n", "body must be preserved verbatim");
3090        }
3091    }
3092
3093    #[test]
3094    fn regression_oversized_int_in_flow_mapping_round_trips() {
3095        // The single-line flow MAPPING form regressed identically:
3096        // `meta: {ext: 123…}` hard-failed the block. It must now parse and the
3097        // oversized value must survive verbatim.
3098        let dir = tempdir().unwrap();
3099        let path = dir.path().join("m.md");
3100        let big = "123456789012345678901234567890";
3101        let original = format!("---\ntype: note\nsummary: x\nmeta: {{ext: {big}}}\n---\nbody\n");
3102        std::fs::write(&path, &original).unwrap();
3103
3104        for _ in 0..2 {
3105            let (fm, body) = read_file(&path).expect("flow-mapping oversized int must parse");
3106            let meta = fm.extra.get("meta").expect("meta field preserved");
3107            assert!(
3108                matches!(meta, Value::Mapping(_)),
3109                "meta should stay a mapping, got: {meta:?}"
3110            );
3111            write_file(&path, &fm, &body).unwrap();
3112            let after = std::fs::read_to_string(&path).unwrap();
3113            assert!(
3114                after.contains(big),
3115                "oversized integer in flow mapping corrupted by format:\n{after}"
3116            );
3117            assert_eq!(body, "body\n", "body must be preserved verbatim");
3118        }
3119    }
3120
3121    #[test]
3122    fn regression_oversized_int_in_mixed_flow_collection_round_trips() {
3123        // A flow collection mixing an oversized int with an in-range int and a
3124        // string: only the oversized int is quoted; the in-range int stays a
3125        // number, the string stays a string, and the whole thing parses.
3126        let dir = tempdir().unwrap();
3127        let path = dir.path().join("mix.md");
3128        let big = "123456789012345678901234567890";
3129        let original = format!(
3130            "---\ntype: note\nsummary: x\nvals: [{big}, 42, hello, \"world\"]\n---\nbody\n"
3131        );
3132        std::fs::write(&path, &original).unwrap();
3133
3134        let (fm, body) = read_file(&path).expect("mixed flow collection must parse");
3135        let Value::Sequence(seq) = fm.extra.get("vals").expect("vals preserved") else {
3136            panic!("vals should be a sequence");
3137        };
3138        assert_eq!(seq.len(), 4, "all four entries preserved");
3139        // The oversized literal narrows to a string; the in-range int stays a
3140        // number; the bare and quoted strings stay strings.
3141        assert_eq!(seq[0].as_str(), Some(big), "oversized int -> string");
3142        assert_eq!(seq[1].as_i64(), Some(42), "in-range int stays a number");
3143        assert_eq!(seq[2].as_str(), Some("hello"));
3144        assert_eq!(seq[3].as_str(), Some("world"));
3145
3146        write_file(&path, &fm, &body).unwrap();
3147        let after = std::fs::read_to_string(&path).unwrap();
3148        assert!(after.contains(big), "oversized int lost:\n{after}");
3149        assert_eq!(body, "body\n");
3150    }
3151
3152    #[test]
3153    fn regression_multiple_oversized_ints_in_one_flow_line_round_trip() {
3154        // Two oversized literals on the same flow line — and a nested collection —
3155        // must each be quoted in the single left-to-right pass.
3156        let dir = tempdir().unwrap();
3157        let path = dir.path().join("multi.md");
3158        let a = "99999999999999999999"; // 20 digits
3159        let b = "123456789012345678901234567890"; // 30 digits
3160        let original =
3161            format!("---\ntype: note\nsummary: x\nm: {{a: {a}, nested: [{b}, 7]}}\n---\nbody\n");
3162        std::fs::write(&path, &original).unwrap();
3163
3164        let (fm, body) = read_file(&path).expect("multi oversized flow must parse");
3165        write_file(&path, &fm, &body).unwrap();
3166        let after = std::fs::read_to_string(&path).unwrap();
3167        assert!(after.contains(a), "first oversized int lost:\n{after}");
3168        assert!(after.contains(b), "second oversized int lost:\n{after}");
3169        assert_eq!(body, "body\n");
3170    }
3171
3172    #[test]
3173    fn regression_flow_with_only_in_range_and_strings_is_byte_exact() {
3174        // A flow collection with NO oversized int must round-trip byte-for-byte:
3175        // the pre-quoter must not touch in-range ints, strings, or floats. We
3176        // assert on the prepared-YAML stage so an unaffected line is left as the
3177        // borrowed input (no rewrite, no quoting drift).
3178        let yaml = "type: note\nids: [1, 2, 3]\nmeta: {ext: 42, name: bob}\nf: [1.5, 2.5]\n";
3179        let prepared = quote_oversized_integers(yaml);
3180        assert_eq!(
3181            prepared.as_ref(),
3182            yaml,
3183            "in-range flow collections must be left byte-exact"
3184        );
3185        // And it still parses cleanly with the expected numeric types intact.
3186        let fm = Frontmatter::parse(yaml, Path::new("n.md")).unwrap();
3187        let Value::Sequence(ids) = fm.extra.get("ids").unwrap() else {
3188            panic!("ids should be a sequence");
3189        };
3190        assert_eq!(ids[0].as_i64(), Some(1));
3191    }
3192
3193    #[test]
3194    fn quote_oversized_ints_in_flow_skips_quoted_and_digit_strings() {
3195        // A quoted scalar whose contents happen to be a long digit run must NOT
3196        // be re-quoted or otherwise altered — it is already a string. A flow with
3197        // only such strings yields no change (None).
3198        let flow = "[\"123456789012345678901234567890\", '99999999999999999999']";
3199        assert_eq!(
3200            quote_oversized_ints_in_flow(flow),
3201            None,
3202            "already-quoted digit strings must be left untouched"
3203        );
3204        // A bare oversized int alongside a quoted one: only the bare one is quoted.
3205        let flow2 = "[123456789012345678901234567890, \"already\"]";
3206        let out = quote_oversized_ints_in_flow(flow2).expect("bare int should be quoted");
3207        assert_eq!(out, "['123456789012345678901234567890', \"already\"]");
3208    }
3209
3210    // ── Regression: BOM-prefixed files parse like store/index (finding #19) ────
3211
3212    #[test]
3213    fn regression_split_frontmatter_tolerates_leading_utf8_bom() {
3214        // A BOM-prefixed file (EF BB BF + `---\n...`) is walked and indexed by
3215        // `dbmd index` (store/index strip the BOM) but, before the fix, every
3216        // write/edit surface routed through `read_file` hard-failed with
3217        // MissingFrontmatter. `split_frontmatter` must now strip a single leading
3218        // U+FEFF and emit a BOM-free body.
3219        let text = "\u{feff}---\ntype: note\nsummary: x\n---\nbody\n";
3220        let parsed = split_frontmatter(text, Path::new("note.md")).unwrap();
3221        assert_eq!(parsed.frontmatter_yaml, "type: note\nsummary: x\n");
3222        // Body never carries the BOM forward into the canonical writer.
3223        assert_eq!(parsed.body, "body\n");
3224        assert!(!parsed.body.starts_with('\u{feff}'));
3225    }
3226
3227    #[test]
3228    fn regression_read_file_parses_bom_prefixed_file() {
3229        // End-to-end through the same `read_file` path `dbmd fm get/set`,
3230        // `format`, `link`, and `write` use. Before the fix this returned
3231        // Err(MissingFrontmatter) on a file the catalog had already indexed.
3232        let dir = tempdir().unwrap();
3233        let path = dir.path().join("note.md");
3234        std::fs::write(&path, "\u{feff}---\ntype: note\nsummary: x\n---\nbody\n").unwrap();
3235
3236        let (fm, body) = read_file(&path).expect("BOM-prefixed file must parse");
3237        assert_eq!(fm.type_.as_deref(), Some("note"));
3238        assert_eq!(fm.summary.as_deref(), Some("x"));
3239        assert_eq!(body, "body\n");
3240    }
3241
3242    #[test]
3243    fn to_yaml_preserves_unquoted_scalar_wiki_link_round_trip() {
3244        // Regression (PRIMARY): the SPEC-canonical scalar wiki-link is the
3245        // *unquoted* inline `company: [[records/companies/northstar]]`
3246        // (SPEC § Linking, the worked `contact` example). YAML parses it to the
3247        // nested `Seq[Seq[String]]` shape. Before the fix, `to_yaml` re-emitted
3248        // it block-style as
3249        //     company:
3250        //     - - records/companies/northstar
3251        // — the `[[ ]]` brackets GONE — so a no-op re-emit (`dbmd format`, and
3252        // any `fm set` / `link` write) silently destroyed the link.
3253        let yaml = "type: contact\ncompany: [[records/companies/northstar]]";
3254        let fm = Frontmatter::parse(yaml, Path::new("c.md")).unwrap();
3255        // Sanity: `parse` now disambiguates the inline-link source form at read
3256        // time (the genuine `Seq[Seq[String]]` of a 2D array no longer gets
3257        // collapsed at emit), so the inline link is stored as the canonical
3258        // scalar `String("[[x]]")`.
3259        assert_eq!(
3260            fm.extra.get("company").and_then(|v| v.as_str()),
3261            Some("[[records/companies/northstar]]")
3262        );
3263
3264        let out = fm.to_yaml();
3265        // The link must survive as a quoted inline scalar — brackets intact, and
3266        // never the bracket-less block sequence `- - records/...`.
3267        assert!(
3268            out.contains("[[records/companies/northstar]]"),
3269            "canonical writer dropped the wiki-link brackets; got:\n{out}"
3270        );
3271        assert!(
3272            !out.contains("- - "),
3273            "canonical writer emitted a nested block sequence (link corrupted); got:\n{out}"
3274        );
3275
3276        // And it round-trips: re-parsing the emitted YAML still surfaces exactly
3277        // one link with the right target (the edge graph/backlinks rely on).
3278        let reparsed = Frontmatter::parse(&out, Path::new("c.md")).unwrap();
3279        let fields = reparsed.link_fields();
3280        let links: Vec<(&str, &str, Option<&str>)> = fields
3281            .iter()
3282            .map(|(k, l)| (k.as_str(), l.target.as_str(), l.display.as_deref()))
3283            .collect();
3284        assert_eq!(
3285            links,
3286            vec![("company", "records/companies/northstar", None)]
3287        );
3288
3289        // A second re-emit is a fixed point — no progressive corruption across
3290        // repeated curator-loop writes.
3291        assert_eq!(
3292            reparsed.to_yaml(),
3293            out,
3294            "to_yaml is not idempotent on links"
3295        );
3296    }
3297
3298    #[test]
3299    fn to_yaml_preserves_unquoted_scalar_link_with_display() {
3300        // The `|display` segment must survive the unquoted-inline round-trip too.
3301        let yaml = "type: contact\ncompany: [[records/companies/northstar|Northstar]]";
3302        let fm = Frontmatter::parse(yaml, Path::new("c.md")).unwrap();
3303        let out = fm.to_yaml();
3304        assert!(
3305            out.contains("[[records/companies/northstar|Northstar]]"),
3306            "display segment lost on round-trip; got:\n{out}"
3307        );
3308        let reparsed = Frontmatter::parse(&out, Path::new("c.md")).unwrap();
3309        let f = reparsed.link_fields();
3310        assert_eq!(f.len(), 1);
3311        assert_eq!(f[0].1.target, "records/companies/northstar");
3312        assert_eq!(f[0].1.display.as_deref(), Some("Northstar"));
3313    }
3314
3315    #[test]
3316    fn to_yaml_does_not_mangle_link_list_or_plain_nested_sequence() {
3317        // A genuine quoted block list of links round-trips as a clean string
3318        // list — never collapsed to a scalar — and a plain nested sequence that
3319        // is NOT a wiki-link is left exactly as written (no false conversion).
3320        let yaml = "type: meeting\nattendees:\n  - \"[[records/contacts/elena]]\"\n  - \"[[records/contacts/sarah]]\"\nmatrix:\n  - - 1\n    - 2";
3321        let fm = Frontmatter::parse(yaml, Path::new("m.md")).unwrap();
3322        let out = fm.to_yaml();
3323
3324        // Both attendee links survive as quoted strings.
3325        assert!(out.contains("[[records/contacts/elena]]"), "got:\n{out}");
3326        assert!(out.contains("[[records/contacts/sarah]]"), "got:\n{out}");
3327
3328        let reparsed = Frontmatter::parse(&out, Path::new("m.md")).unwrap();
3329        let fields = reparsed.link_fields();
3330        let attendees: Vec<&str> = fields
3331            .iter()
3332            .filter(|(k, _)| k == "attendees")
3333            .map(|(_, l)| l.target.as_str())
3334            .collect();
3335        assert_eq!(
3336            attendees,
3337            vec!["records/contacts/elena", "records/contacts/sarah"]
3338        );
3339        // The non-link nested sequence is preserved verbatim, not touched.
3340        assert_eq!(reparsed.extra.get("matrix"), fm.extra.get("matrix"));
3341    }
3342
3343    // ── read_file / write_file round-trip ────────────────────────────────────
3344
3345    #[test]
3346    fn write_then_read_roundtrips_and_preserves_body_verbatim() {
3347        let dir = tempdir().unwrap();
3348        let path = dir.path().join("sources/emails/x.md");
3349        let body = "# Subject\n\nHello,\n\nSee [[records/contacts/sarah-chen]].\n";
3350        let mut fm = Frontmatter {
3351            type_: Some("email".into()),
3352            summary: Some("renewal note".into()),
3353            created: Some(DateTime::parse_from_rfc3339("2026-05-27T08:00:00-07:00").unwrap()),
3354            ..Default::default()
3355        };
3356        fm.extra
3357            .insert("from".into(), Value::String("elena@northstar.io".into()));
3358
3359        write_file(&path, &fm, body).unwrap();
3360
3361        let (read_fm, read_body) = read_file(&path).unwrap();
3362        assert_eq!(read_body, body, "body must be preserved byte-for-byte");
3363        assert_eq!(read_fm.type_.as_deref(), Some("email"));
3364        assert_eq!(read_fm.summary.as_deref(), Some("renewal note"));
3365        assert_eq!(
3366            read_fm.extra.get("from").and_then(|v| v.as_str()),
3367            Some("elena@northstar.io")
3368        );
3369        // The on-disk file starts with a fence and ends with the verbatim body.
3370        let raw = std::fs::read_to_string(&path).unwrap();
3371        assert!(raw.starts_with("---\n"));
3372        assert!(raw.ends_with(body));
3373    }
3374
3375    #[test]
3376    fn roundtrip_modify_summary_then_write_changes_only_summary() {
3377        let dir = tempdir().unwrap();
3378        let path = dir.path().join("records/contacts/sarah.md");
3379        let body = "Long-form operator notes about Sarah.\n";
3380        let fm = Frontmatter {
3381            type_: Some("contact".into()),
3382            summary: Some("old summary".into()),
3383            ..Default::default()
3384        };
3385        write_file(&path, &fm, body).unwrap();
3386
3387        // Read → modify summary → write back.
3388        let (mut fm2, body2) = read_file(&path).unwrap();
3389        fm2.summary = Some("new summary".into());
3390        write_file(&path, &fm2, &body2).unwrap();
3391
3392        let (fm3, body3) = read_file(&path).unwrap();
3393        assert_eq!(fm3.summary.as_deref(), Some("new summary"));
3394        assert_eq!(fm3.type_.as_deref(), Some("contact"));
3395        assert_eq!(body3, body, "body unchanged across the round-trip");
3396    }
3397
3398    #[test]
3399    fn roundtrip_preserves_handwritten_unquoted_scalar_wiki_link_on_disk() {
3400        // End-to-end analog of `dbmd format` on the verbatim SPEC worked example:
3401        // a hand-written file carrying the canonical UNQUOTED scalar link
3402        // `company: [[records/companies/northstar]]`, read from disk then written
3403        // back unchanged. Before the fix this no-op re-emit rewrote the on-disk
3404        // value to the bracket-less block sequence `company:\n- - records/...`,
3405        // and every reader (validate/graph/backlinks) then lost the edge.
3406        let dir = tempdir().unwrap();
3407        let path = dir.path().join("records/contacts/sarah-chen.md");
3408        let file = "---\ntype: contact\nid: sarah-chen\nsummary: Director of Ops\ncompany: [[records/companies/northstar]]\n---\n# Sarah Chen\n\nNotes.\n";
3409        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3410        std::fs::write(&path, file).unwrap();
3411
3412        // Read → write back unchanged (the canonical no-op re-emit).
3413        let (fm, body) = read_file(&path).unwrap();
3414        write_file(&path, &fm, &body).unwrap();
3415
3416        // On-disk bytes still carry the bracketed link, never `- - records/...`.
3417        let raw = std::fs::read_to_string(&path).unwrap();
3418        assert!(
3419            raw.contains("[[records/companies/northstar]]"),
3420            "on-disk wiki-link brackets were destroyed; got:\n{raw}"
3421        );
3422        assert!(
3423            !raw.contains("- - "),
3424            "on-disk value became a nested block sequence; got:\n{raw}"
3425        );
3426
3427        // And the edge is still readable after the round-trip.
3428        let (fm2, _) = read_file(&path).unwrap();
3429        let fields = fm2.link_fields();
3430        let links: Vec<(&str, &str)> = fields
3431            .iter()
3432            .map(|(k, l)| (k.as_str(), l.target.as_str()))
3433            .collect();
3434        assert_eq!(links, vec![("company", "records/companies/northstar")]);
3435    }
3436
3437    #[test]
3438    fn write_file_does_not_leave_temp_files_behind() {
3439        let dir = tempdir().unwrap();
3440        let path = dir.path().join("records/x.md");
3441        let fm = Frontmatter {
3442            type_: Some("note".into()),
3443            ..Default::default()
3444        };
3445        write_file(&path, &fm, "body\n").unwrap();
3446        // The directory should contain only the target file, no `.x.md.tmp.*`.
3447        let entries: Vec<String> = std::fs::read_dir(path.parent().unwrap())
3448            .unwrap()
3449            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3450            .collect();
3451        assert_eq!(entries, vec!["x.md".to_string()]);
3452    }
3453
3454    // ── is_content_file ──────────────────────────────────────────────────────
3455
3456    #[test]
3457    fn is_content_file_recognizes_layers_and_excludes_meta() {
3458        assert!(Frontmatter::is_content_file(Path::new(
3459            "sources/emails/2026-05-22.md"
3460        )));
3461        assert!(Frontmatter::is_content_file(Path::new(
3462            "records/contacts/sarah-chen.md"
3463        )));
3464        // A synthesis profile the agent authored lives under `records/` (the
3465        // old `wiki/` layer is gone, so a `wiki/...` path is NOT content).
3466        assert!(Frontmatter::is_content_file(Path::new(
3467            "records/profiles/sarah-chen.md"
3468        )));
3469        assert!(!Frontmatter::is_content_file(Path::new(
3470            "wiki/people/sarah-chen.md"
3471        )));
3472        // Absolute paths under a layer are still content.
3473        assert!(Frontmatter::is_content_file(Path::new(
3474            "/home/db/records/companies/northstar.md"
3475        )));
3476        // index.md at any level is meta.
3477        assert!(!Frontmatter::is_content_file(Path::new(
3478            "records/contacts/index.md"
3479        )));
3480        assert!(!Frontmatter::is_content_file(Path::new("index.md")));
3481        // Root meta files.
3482        assert!(!Frontmatter::is_content_file(Path::new("DB.md")));
3483        assert!(!Frontmatter::is_content_file(Path::new("log.md")));
3484    }
3485
3486    // ── effective_id ─────────────────────────────────────────────────────────
3487
3488    #[test]
3489    fn effective_id_prefers_explicit_then_derives_from_path() {
3490        let with_id = Frontmatter {
3491            id: Some("explicit-id".into()),
3492            ..Default::default()
3493        };
3494        assert_eq!(
3495            with_id.effective_id(Path::new("records/profiles/sarah-chen.md")),
3496            "explicit-id"
3497        );
3498        let no_id = Frontmatter::default();
3499        assert_eq!(
3500            no_id.effective_id(Path::new("records/profiles/sarah-chen.md")),
3501            "sarah-chen"
3502        );
3503    }
3504
3505    // ── get / set ────────────────────────────────────────────────────────────
3506
3507    #[test]
3508    fn set_routes_universal_and_custom_keys() {
3509        let mut fm = Frontmatter::default();
3510        fm.set("type", "contact").unwrap();
3511        fm.set("summary", "hi").unwrap();
3512        fm.set("company", "[[records/companies/northstar]]")
3513            .unwrap();
3514        assert_eq!(fm.type_.as_deref(), Some("contact"));
3515        assert_eq!(fm.summary.as_deref(), Some("hi"));
3516        // Custom key landed in extra, not a typed slot.
3517        assert_eq!(
3518            fm.extra.get("company").and_then(|v| v.as_str()),
3519            Some("[[records/companies/northstar]]")
3520        );
3521        // get reads from both typed fields and extra.
3522        assert_eq!(
3523            fm.get("type").and_then(|v| v.as_str().map(String::from)),
3524            Some("contact".into())
3525        );
3526        assert_eq!(
3527            fm.get("company").and_then(|v| v.as_str().map(String::from)),
3528            Some("[[records/companies/northstar]]".into())
3529        );
3530        assert!(fm.get("nonexistent").is_none());
3531    }
3532
3533    #[test]
3534    fn set_timestamp_validates_rfc3339() {
3535        let mut fm = Frontmatter::default();
3536        fm.set("created", "2026-05-27T08:00:00-07:00").unwrap();
3537        assert!(fm.created.is_some());
3538        let err = fm.set("updated", "not-a-date").unwrap_err();
3539        assert!(matches!(err, ParseError::BadTimestamp { .. }));
3540    }
3541
3542    // ── extract_wiki_links ───────────────────────────────────────────────────
3543
3544    #[test]
3545    fn extract_wiki_links_flags_full_path_short_form_and_extension() {
3546        let body = "See [[records/contacts/sarah-chen]] and [[sarah-chen]].\nAlso [[records/profiles/sarah-chen.md|Sarah]].\n";
3547        let links = extract_wiki_links(body, Path::new("doc.md"));
3548        assert_eq!(links.len(), 3);
3549
3550        // Full path, no extension, no display.
3551        assert_eq!(links[0].target, "records/contacts/sarah-chen");
3552        assert!(links[0].is_full_path);
3553        assert!(!links[0].has_md_extension);
3554        assert_eq!(links[0].display, None);
3555        assert_eq!(links[0].location.1, 1, "first link on line 1");
3556
3557        // Short form: not a full path.
3558        assert_eq!(links[1].target, "sarah-chen");
3559        assert!(!links[1].is_full_path, "bare target is short-form");
3560
3561        // Full path WITH .md extension and a display override on line 2.
3562        assert_eq!(links[2].target, "records/profiles/sarah-chen.md");
3563        assert!(links[2].is_full_path);
3564        assert!(links[2].has_md_extension);
3565        assert_eq!(links[2].display.as_deref(), Some("Sarah"));
3566        assert_eq!(links[2].location.1, 2);
3567    }
3568
3569    #[test]
3570    fn extract_wiki_links_reports_1_based_column_counting_chars() {
3571        // A multi-byte prefix (é is 2 bytes) must not skew the char column.
3572        let body = "café [[records/x/y]]";
3573        let links = extract_wiki_links(body, Path::new("d.md"));
3574        assert_eq!(links.len(), 1);
3575        // "café " is 5 chars, so the `[[` starts at char column 6 (1-based).
3576        assert_eq!(links[0].location.2, 6);
3577    }
3578
3579    #[test]
3580    fn extract_wiki_links_columns_are_correct_for_multiple_links_on_one_line() {
3581        // Locks the single-pass column cursor (the O(n²)→O(n) fix): each `[[`
3582        // reports the right 1-based CHAR column even with multi-byte prefixes and
3583        // several links per line.
3584        let body = "café [[a]] · [[records/x/y]] end";
3585        let links = extract_wiki_links(body, Path::new("d.md"));
3586        assert_eq!(links.len(), 2);
3587        // "café " = 5 chars → first `[[` at col 6.
3588        assert_eq!(links[0].location.2, 6);
3589        // "café [[a]] · " = 5 + 5 (`[[a]]`) + 3 (` · `, `·` is 1 char) = 13 chars
3590        // → second `[[` at col 14.
3591        assert_eq!(links[1].location.2, 14);
3592    }
3593
3594    #[test]
3595    fn extract_wiki_links_ignores_a_lone_path_without_brackets() {
3596        let links = extract_wiki_links(
3597            "records/contacts/sarah-chen is not a link",
3598            Path::new("d.md"),
3599        );
3600        assert!(links.is_empty());
3601    }
3602
3603    // ── extract_markdown_links ───────────────────────────────────────────────
3604
3605    #[test]
3606    fn extract_markdown_links_captures_external_and_not_wiki_links() {
3607        let body =
3608            "See [the thread](https://x.com/a) and [[records/contacts/sarah-chen]] internally.\n";
3609        let md = extract_markdown_links(body, Path::new("d.md"));
3610        assert_eq!(
3611            md.len(),
3612            1,
3613            "wiki-link must not be captured as a markdown link"
3614        );
3615        assert_eq!(md[0].text, "the thread");
3616        assert_eq!(md[0].url, "https://x.com/a");
3617        assert_eq!(md[0].location.1, 1);
3618
3619        // And the wiki-link extractor must not pick up the markdown link.
3620        let wl = extract_wiki_links(body, Path::new("d.md"));
3621        assert_eq!(wl.len(), 1);
3622        assert_eq!(wl[0].target, "records/contacts/sarah-chen");
3623    }
3624
3625    // ── link_fields ──────────────────────────────────────────────────────────
3626
3627    #[test]
3628    fn link_fields_extracts_scalar_list_and_summary_links() {
3629        // The canonical list form quotes each item so YAML parses it as clean
3630        // strings; a scalar field may be quoted OR written in the canonical
3631        // unquoted inline form `company: [[x]]` (SPEC § Linking).
3632        let yaml = "type: meeting\nsummary: with [[records/contacts/elena]]\ncompany: \"[[records/companies/northstar]]\"\nattendees:\n  - \"[[records/contacts/elena]]\"\n  - \"[[records/contacts/sarah]]\"\nnotes: just plain text";
3633        let fm = Frontmatter::parse(yaml, Path::new("m.md")).unwrap();
3634        // Sanity: company really did parse as a scalar string here.
3635        assert!(fm.extra.get("company").and_then(|v| v.as_str()).is_some());
3636        let fields = fm.link_fields();
3637
3638        // company (scalar) once, with the right target.
3639        let company: Vec<&str> = fields
3640            .iter()
3641            .filter(|(k, _)| k == "company")
3642            .map(|(_, l)| l.target.as_str())
3643            .collect();
3644        assert_eq!(company, vec!["records/companies/northstar"]);
3645        // attendees (block list) twice.
3646        let attendees: Vec<&str> = fields
3647            .iter()
3648            .filter(|(k, _)| k == "attendees")
3649            .map(|(_, l)| l.target.as_str())
3650            .collect();
3651        assert_eq!(
3652            attendees,
3653            vec!["records/contacts/elena", "records/contacts/sarah"]
3654        );
3655        // summary link surfaced.
3656        assert_eq!(fields.iter().filter(|(k, _)| k == "summary").count(), 1);
3657        // Plain-text field is not a link.
3658        assert_eq!(fields.iter().filter(|(k, _)| k == "notes").count(), 0);
3659    }
3660
3661    #[test]
3662    fn link_fields_surfaces_canonical_unquoted_scalar_link() {
3663        // Regression: the canonical scalar wiki-link form is the *unquoted*
3664        // inline `company: [[records/companies/northstar]]` (SPEC § Linking).
3665        // YAML parses `[[x]]` as a flow-list-in-a-list (`Seq[Seq[String]]`), so
3666        // a naive `as_str()`-only walk drops it. link_fields() must still
3667        // surface exactly one link with the correct target.
3668        let yaml = "type: meeting\ncompany: [[records/companies/northstar]]";
3669        let fm = Frontmatter::parse(yaml, Path::new("m.md")).unwrap();
3670        // Sanity: `parse` disambiguates the inline-link source form at read time,
3671        // storing it as the canonical scalar `String("[[x]]")` (so a genuine
3672        // `Seq[Seq[String]]` 2D array is never collapsed/retyped). link_fields()
3673        // reads either spelling back as the same link.
3674        assert_eq!(
3675            fm.extra.get("company").and_then(|v| v.as_str()),
3676            Some("[[records/companies/northstar]]")
3677        );
3678
3679        let fields = fm.link_fields();
3680        let links: Vec<(&str, &str, Option<&str>)> = fields
3681            .iter()
3682            .map(|(k, l)| (k.as_str(), l.target.as_str(), l.display.as_deref()))
3683            .collect();
3684        assert_eq!(
3685            links,
3686            vec![("company", "records/companies/northstar", None)]
3687        );
3688
3689        // The `|display` segment survives the unquoted inline form too.
3690        let fm2 = Frontmatter::parse(
3691            "type: meeting\ncompany: [[records/companies/northstar|Northstar]]",
3692            Path::new("m.md"),
3693        )
3694        .unwrap();
3695        let f2 = fm2.link_fields();
3696        assert_eq!(f2.len(), 1);
3697        assert_eq!(f2[0].0, "company");
3698        assert_eq!(f2[0].1.target, "records/companies/northstar");
3699        assert_eq!(f2[0].1.display.as_deref(), Some("Northstar"));
3700    }
3701
3702    #[test]
3703    fn link_fields_ignores_plain_one_item_flow_list() {
3704        // A plain one-item flow list `aliases: [foo]` parses to `Seq[String]`
3705        // — one nesting level shallower than an unquoted `[[foo]]` — and must
3706        // NOT be mistaken for a wiki-link.
3707        let yaml = "type: contact\naliases: [foo]";
3708        let fm = Frontmatter::parse(yaml, Path::new("c.md")).unwrap();
3709        assert_eq!(fm.link_fields(), Vec::new());
3710    }
3711
3712    // ── detect_flow_form_link_lists ──────────────────────────────────────────
3713
3714    #[test]
3715    fn detect_flow_form_flags_list_misencodings_not_scalars() {
3716        // The flow-form list mis-encoding (triple-nested) IS flagged; a scalar
3717        // inline wiki-link (double-nested) is NOT.
3718        let bad = "attendees: [[[records/x]], [[records/y]]]\nscalar_inline: [[records/z]]";
3719        let flagged = detect_flow_form_link_lists(bad);
3720        assert_eq!(flagged, vec!["attendees".to_string()]);
3721
3722        // An UNquoted block list is also a mis-encoding (parses triple-nested).
3723        let unquoted_block = "attendees:\n  - [[records/x]]\n  - [[records/y]]";
3724        assert_eq!(
3725            detect_flow_form_link_lists(unquoted_block),
3726            vec!["attendees".to_string()]
3727        );
3728
3729        // The canonical QUOTED block form parses to clean strings — NOT flagged.
3730        let good = "attendees:\n  - \"[[records/x]]\"\n  - \"[[records/y]]\"";
3731        assert!(detect_flow_form_link_lists(good).is_empty());
3732
3733        // A plain scalar list of strings is not flagged.
3734        let plain = "tags: [a, b, c]";
3735        assert!(detect_flow_form_link_lists(plain).is_empty());
3736    }
3737
3738    // ── extract_sections ─────────────────────────────────────────────────────
3739
3740    #[test]
3741    fn extract_sections_levels_nesting_and_boundaries() {
3742        let body = "intro text\n## First\nalpha\n### Sub\nbeta\n## Second\ngamma\n";
3743        let secs = extract_sections(body);
3744        let headings: Vec<(&str, u8)> =
3745            secs.iter().map(|s| (s.heading.as_str(), s.level)).collect();
3746        assert_eq!(headings, vec![("First", 2), ("Sub", 3), ("Second", 2)]);
3747
3748        // "First" (H2) body extends through its H3 child, stopping at "Second".
3749        let first = &secs[0];
3750        assert!(first.body.contains("alpha"));
3751        assert!(first.body.contains("### Sub"));
3752        assert!(first.body.contains("beta"));
3753        assert!(!first.body.contains("Second"));
3754
3755        // "Sub" (H3) stops at the next equal-or-shallower heading ("Second").
3756        let sub = &secs[1];
3757        assert!(sub.body.contains("beta"));
3758        assert!(!sub.body.contains("gamma"));
3759
3760        // 1-based line numbers within the body.
3761        assert_eq!(first.line, 2);
3762        assert_eq!(secs[2].line, 6);
3763    }
3764
3765    #[test]
3766    fn extract_sections_ignores_headings_in_fenced_code() {
3767        let body = "## Real\n```\n## Fake heading in code\n```\nafter\n";
3768        let secs = extract_sections(body);
3769        assert_eq!(secs.len(), 1);
3770        assert_eq!(secs[0].heading, "Real");
3771        // The fenced "## Fake" is part of Real's body, not its own section.
3772        assert!(secs[0].body.contains("## Fake heading in code"));
3773    }
3774
3775    // ── parse_field_spec ─────────────────────────────────────────────────────
3776
3777    #[test]
3778    fn parse_field_spec_required_and_shape() {
3779        let f = parse_field_spec("- email (required, email)");
3780        assert_eq!(f.name, "email");
3781        assert!(f.required);
3782        assert_eq!(f.shape, Some(Shape::Email));
3783        assert!(f.unknown_modifiers.is_empty());
3784    }
3785
3786    #[test]
3787    fn parse_field_spec_link_prefix_strips_trailing_slash() {
3788        let f = parse_field_spec("- company (required, link to records/companies/)");
3789        assert!(f.required);
3790        assert_eq!(f.link_prefix, Some(PathBuf::from("records/companies")));
3791        assert_eq!(f.shape, None);
3792    }
3793
3794    #[test]
3795    fn parse_field_spec_default_preserves_case_and_value() {
3796        let f = parse_field_spec("- currency (default USD)");
3797        assert_eq!(f.name, "currency");
3798        assert_eq!(f.default, Some(Value::String("USD".into())));
3799    }
3800
3801    #[test]
3802    fn parse_field_spec_enum_captures_comma_list_as_last_modifier() {
3803        let f = parse_field_spec("- status (required, enum: open, closed, pending)");
3804        assert!(f.required);
3805        assert_eq!(
3806            f.enum_values,
3807            Some(vec![
3808                "open".to_string(),
3809                "closed".to_string(),
3810                "pending".to_string()
3811            ])
3812        );
3813    }
3814
3815    #[test]
3816    fn parse_field_spec_bare_enum_keyword_is_not_itself_a_value() {
3817        // `enum` with no colon: the values are the remaining tokens; the keyword
3818        // itself must NOT leak in as an allowed value.
3819        let f = parse_field_spec("- status (required, enum, open, closed)");
3820        assert!(f.required);
3821        assert_eq!(
3822            f.enum_values,
3823            Some(vec!["open".to_string(), "closed".to_string()])
3824        );
3825    }
3826
3827    #[test]
3828    fn parse_field_spec_unknown_modifier_is_captured_not_errored() {
3829        let f = parse_field_spec("- weird (required, frobnicate, string)");
3830        assert!(f.required);
3831        assert_eq!(f.shape, Some(Shape::String));
3832        assert_eq!(f.unknown_modifiers, vec!["frobnicate".to_string()]);
3833    }
3834
3835    #[test]
3836    fn parse_field_spec_no_parens_is_freeform_optional() {
3837        let f = parse_field_spec("- nickname");
3838        assert_eq!(f.name, "nickname");
3839        assert!(!f.required);
3840        assert_eq!(f.shape, None);
3841        assert!(f.link_prefix.is_none());
3842        assert!(f.enum_values.is_none());
3843        assert!(f.unknown_modifiers.is_empty());
3844    }
3845
3846    // ── parse_schema_bullet (directives) ─────────────────────────────────────
3847
3848    #[test]
3849    fn schema_bullet_unique_single_field() {
3850        match parse_schema_bullet("- unique: email") {
3851            SchemaBullet::Unique(fields) => assert_eq!(fields, vec!["email".to_string()]),
3852            other => panic!("expected Unique, got {other:?}"),
3853        }
3854    }
3855
3856    #[test]
3857    fn schema_bullet_unique_compound_trims_and_splits() {
3858        match parse_schema_bullet("- unique: date, amount , vendor") {
3859            SchemaBullet::Unique(fields) => assert_eq!(
3860                fields,
3861                vec![
3862                    "date".to_string(),
3863                    "amount".to_string(),
3864                    "vendor".to_string()
3865                ]
3866            ),
3867            other => panic!("expected Unique, got {other:?}"),
3868        }
3869    }
3870
3871    #[test]
3872    fn schema_bullet_summary_template_keeps_braces_and_inner_colons() {
3873        match parse_schema_bullet("- summary_template: {role} at {company} (x: y)") {
3874            SchemaBullet::SummaryTemplate(t) => assert_eq!(t, "{role} at {company} (x: y)"),
3875            other => panic!("expected SummaryTemplate, got {other:?}"),
3876        }
3877    }
3878
3879    #[test]
3880    fn schema_bullet_field_with_enum_modifier_is_not_a_directive() {
3881        // A field whose modifiers contain a colon (`enum:`) parses as a field, not
3882        // a directive — its head has a `(` before any `:`.
3883        match parse_schema_bullet("- status (enum: open, closed)") {
3884            SchemaBullet::Field(f) => {
3885                assert_eq!(f.name, "status");
3886                assert_eq!(
3887                    f.enum_values,
3888                    Some(vec!["open".to_string(), "closed".to_string()])
3889                );
3890            }
3891            other => panic!("expected Field, got {other:?}"),
3892        }
3893    }
3894
3895    #[test]
3896    fn parse_db_md_schema_captures_unique_and_summary_template() {
3897        let db = "---\ntype: db-md\nscope: x\nowner: y\n---\n\n## Schemas\n\n### contact\n- email (required, email)\n- unique: email\n- summary_template: {role} at {company}\n";
3898        let config = parse_db_md(db, Path::new("DB.md")).unwrap();
3899        let s = config.schemas.get("contact").expect("contact schema");
3900        assert_eq!(s.fields.len(), 1, "directives are not parsed as fields");
3901        assert_eq!(s.unique_keys, vec![vec!["email".to_string()]]);
3902        assert_eq!(s.summary_template.as_deref(), Some("{role} at {company}"));
3903    }
3904
3905    #[test]
3906    fn schema_bullet_shard_directive_parses_values() {
3907        assert!(matches!(
3908            parse_schema_bullet("- shard: by-date"),
3909            SchemaBullet::Shard(Some(true))
3910        ));
3911        assert!(matches!(
3912            parse_schema_bullet("- shard: flat"),
3913            SchemaBullet::Shard(Some(false))
3914        ));
3915        // An unrecognized value is ignored (None), like an unknown modifier.
3916        assert!(matches!(
3917            parse_schema_bullet("- shard: weekly"),
3918            SchemaBullet::Shard(None)
3919        ));
3920        // A field whose name has a `(` before any `:` is still a field — the same
3921        // guard that keeps `- status (enum: a, b)` a field, not a directive.
3922        assert!(matches!(
3923            parse_schema_bullet("- shardiness (string)"),
3924            SchemaBullet::Field(_)
3925        ));
3926    }
3927
3928    #[test]
3929    fn parse_db_md_schema_captures_shard_directive() {
3930        let db = "---\ntype: db-md\nscope: x\nowner: y\n---\n\n## Schemas\n\n### shipment\n- carrier (string)\n- shard: by-date\n\n### contact\n- shard: flat\n";
3931        let config = parse_db_md(db, Path::new("DB.md")).unwrap();
3932        let shipment = config.schemas.get("shipment").expect("shipment schema");
3933        assert_eq!(shipment.shard, Some(true));
3934        assert_eq!(
3935            shipment.fields.len(),
3936            1,
3937            "`shard:` is a directive, not a field"
3938        );
3939        assert_eq!(config.schemas.get("contact").unwrap().shard, Some(false));
3940    }
3941
3942    // ── parse_db_md ──────────────────────────────────────────────────────────
3943
3944    const CANONICAL_DB_MD: &str = "---\ntype: db-md\nscope: company\nowner: Sarah Chen\n---\n\n# Acme operations knowledge base\n\nCompany-scale institutional memory for Acme.\n\n## Agent instructions\n\nPrioritize creating `contact` records from new-sender emails. Use British English.\n\n## Policies\n\n### Frozen pages\n- `records/decisions/2026-q1-strategy.md` — finalized, do not modify.\n- `records/synthesis/2026-annual-plan.md` — signed-off plan.\n\n### Ignored types\n- `test`, `temp` — read but never synthesize.\n\n## Schemas\n\n### contact\n- name (required)\n- email (required, email)\n- company (required, link to records/companies/)\n- role (string)\n\n### expense\n- date (required, date)\n- amount (required)\n- currency (default USD)\n";
3945
3946    #[test]
3947    fn parse_db_md_extracts_all_canonical_sections() {
3948        let config = parse_db_md(CANONICAL_DB_MD, Path::new("DB.md")).unwrap();
3949
3950        // Agent instructions: free-form prose, heading line stripped.
3951        let ai = config
3952            .agent_instructions
3953            .expect("agent instructions present");
3954        assert!(ai.starts_with("Prioritize creating"));
3955        assert!(!ai.contains("## Agent instructions"));
3956
3957        // Frozen pages: paths extracted from backticked bullets, comments dropped.
3958        assert_eq!(
3959            config.frozen_pages,
3960            vec![
3961                PathBuf::from("records/decisions/2026-q1-strategy.md"),
3962                PathBuf::from("records/synthesis/2026-annual-plan.md"),
3963            ]
3964        );
3965
3966        // Ignored types: comma list, backticks/comment stripped.
3967        assert_eq!(
3968            config.ignored_types,
3969            vec!["test".to_string(), "temp".to_string()]
3970        );
3971
3972        // Schemas: two types, each with its fields in source order.
3973        assert_eq!(config.schemas.len(), 2);
3974        let contact = config.schemas.get("contact").expect("contact schema");
3975        let names: Vec<&str> = contact.fields.iter().map(|f| f.name.as_str()).collect();
3976        assert_eq!(names, vec!["name", "email", "company", "role"]);
3977        assert!(contact.fields[0].required); // name
3978        assert_eq!(contact.fields[1].shape, Some(Shape::Email)); // email
3979        assert_eq!(
3980            contact.fields[2].link_prefix,
3981            Some(PathBuf::from("records/companies"))
3982        ); // company
3983
3984        let expense = config.schemas.get("expense").expect("expense schema");
3985        let cur = expense
3986            .fields
3987            .iter()
3988            .find(|f| f.name == "currency")
3989            .unwrap();
3990        assert_eq!(cur.default, Some(Value::String("USD".into())));
3991    }
3992
3993    #[test]
3994    fn parse_db_md_handles_malformed_and_unknown_modifiers() {
3995        // corpus-b shape: a `## Schemas` section with a malformed bullet, an
3996        // unknown modifier, and bullets that appear with NO `### <type>`
3997        // heading (so they belong to no schema and are dropped).
3998        let text = "---\ntype: db-md\n---\n\n## Schemas\n- orphan (required)\n\n### ticket\n- priority (required, mystery, enum: low, high)\n- broken (\n";
3999        let config = parse_db_md(text, Path::new("DB.md")).unwrap();
4000
4001        // The orphan bullet under `## Schemas` with no `### type` heading is not
4002        // captured as a schema.
4003        assert_eq!(config.schemas.len(), 1);
4004        let ticket = config.schemas.get("ticket").expect("ticket schema");
4005        assert_eq!(ticket.fields.len(), 2);
4006
4007        let priority = &ticket.fields[0];
4008        assert!(priority.required);
4009        assert_eq!(priority.unknown_modifiers, vec!["mystery".to_string()]);
4010        assert_eq!(
4011            priority.enum_values,
4012            Some(vec!["low".to_string(), "high".to_string()])
4013        );
4014
4015        // A bullet with an unclosed paren still yields a usable name.
4016        let broken = &ticket.fields[1];
4017        assert_eq!(broken.name, "broken");
4018    }
4019
4020    #[test]
4021    fn parse_db_md_missing_frontmatter_errors() {
4022        let text = "# No frontmatter\n\n## Agent instructions\nhi\n";
4023        let err = parse_db_md(text, Path::new("DB.md")).unwrap_err();
4024        assert!(matches!(err, ParseError::MissingFrontmatter { .. }));
4025    }
4026
4027    #[test]
4028    fn parse_db_md_absent_sections_default_empty() {
4029        let text = "---\ntype: db-md\n---\n\n# Title only\n";
4030        let config = parse_db_md(text, Path::new("DB.md")).unwrap();
4031        assert_eq!(config, Config::default());
4032    }
4033
4034    // ── fm set / --fm list-valued link fields (meeting.attendees & friends) ──
4035
4036    /// `Frontmatter::set` is the value path every write surface (`fm set`,
4037    /// `write --fm`) funnels through. A list-of-wiki-links value (the SPEC's
4038    /// `meeting.attendees` shape) must serialize as a YAML **block sequence** of
4039    /// quoted links — readable back by [`links_in_field_value`] and accepted by
4040    /// `dbmd validate` — never the flow-form scalar string that trips
4041    /// `WIKI_LINK_FLOW_FORM_LIST`. Both the unquoted (`[[[a]], [[b]]]`) and
4042    /// quoted (`["[[a]]", "[[b]]"]`) spellings an agent types must normalize.
4043    #[test]
4044    fn set_list_of_wiki_links_becomes_block_sequence_both_spellings() {
4045        for value in [
4046            "[[[records/contacts/a]], [[records/contacts/b]]]",
4047            r#"["[[records/contacts/a]]", "[[records/contacts/b]]"]"#,
4048        ] {
4049            let mut fm = Frontmatter::default();
4050            fm.set("attendees", value).unwrap();
4051
4052            // Stored as a 2-element sequence of clean quoted links.
4053            let stored = fm.extra.get("attendees").expect("attendees set");
4054            let Value::Sequence(items) = stored else {
4055                panic!("attendees must be a Sequence, got {stored:?} for input {value}");
4056            };
4057            assert_eq!(items.len(), 2, "input {value}");
4058            assert_eq!(items[0], Value::String("[[records/contacts/a]]".into()));
4059            assert_eq!(items[1], Value::String("[[records/contacts/b]]".into()));
4060
4061            // The edge enumerator reads exactly the two links back (no stray
4062            // bracket targets, the flow-form-string symptom).
4063            let links: Vec<_> = links_in_field_value(stored)
4064                .into_iter()
4065                .map(|l| l.target)
4066                .collect();
4067            assert_eq!(
4068                links,
4069                vec!["records/contacts/a", "records/contacts/b"],
4070                "input {value}"
4071            );
4072
4073            // And the canonical writer renders it block-style, not as a scalar.
4074            let yaml = fm.to_yaml();
4075            assert!(
4076                yaml.contains("attendees:\n"),
4077                "expected block list in:\n{yaml}"
4078            );
4079            assert!(
4080                !yaml.contains("attendees: '[["),
4081                "must not be a flow-form scalar string in:\n{yaml}"
4082            );
4083        }
4084    }
4085
4086    /// A *single* inline wiki-link stays a scalar string (renders inline
4087    /// `field: [[x]]`), and a single link must never be widened to a one-item
4088    /// list — preserving the common `contact.company` / `expense.vendor` shape.
4089    #[test]
4090    fn set_single_inline_wiki_link_stays_scalar() {
4091        let mut fm = Frontmatter::default();
4092        fm.set("company", "[[records/companies/tideform]]").unwrap();
4093        assert_eq!(
4094            fm.extra.get("company"),
4095            Some(&Value::String("[[records/companies/tideform]]".into())),
4096        );
4097        // Still recognized as one link.
4098        let links: Vec<_> = links_in_field_value(fm.extra.get("company").unwrap())
4099            .into_iter()
4100            .map(|l| l.target)
4101            .collect();
4102        assert_eq!(links, vec!["records/companies/tideform"]);
4103    }
4104
4105    /// Plain text and a non-link flow list are left as verbatim scalar strings —
4106    /// the list normalization only triggers when every item is a clean wiki-link.
4107    #[test]
4108    fn set_non_link_values_stay_scalar_strings() {
4109        let mut fm = Frontmatter::default();
4110        fm.set("location", "Video call (remote)").unwrap();
4111        assert_eq!(
4112            fm.extra.get("location"),
4113            Some(&Value::String("Video call (remote)".into())),
4114        );
4115
4116        // A flow list whose items are NOT wiki-links must not be reinterpreted as
4117        // a link sequence; it stays the scalar string the agent passed.
4118        fm.set("note", "[draft, wip]").unwrap();
4119        assert_eq!(
4120            fm.extra.get("note"),
4121            Some(&Value::String("[draft, wip]".into()))
4122        );
4123    }
4124
4125    // ── Regression: non-string YAML keys round-trip (no Rust Debug corruption) ─
4126
4127    #[test]
4128    fn regression_non_string_yaml_keys_keep_their_text_on_round_trip() {
4129        // A numeric/bool/null/float frontmatter key is valid YAML and must NOT be
4130        // rewritten to its Rust `Debug` form (`Number(2026)`, `Bool(true)`,
4131        // `'Null'`). After the fix the key text survives (the key narrows to a
4132        // string-typed key, but the operator's data is no longer corrupted).
4133        let yaml = "type: note\n2026: planning notes\ntrue: yes-key\n3.14: f\n";
4134        let fm = Frontmatter::parse(yaml, Path::new("x.md")).unwrap();
4135        // Keys are stored as their scalar text, not the Debug string.
4136        assert!(fm.extra.contains_key("2026"), "numeric key text lost");
4137        assert!(fm.extra.contains_key("true"), "bool key text lost");
4138        assert!(fm.extra.contains_key("3.14"), "float key text lost");
4139        assert!(!fm.extra.keys().any(|k| k.starts_with("Number(")));
4140        assert!(!fm.extra.keys().any(|k| k.starts_with("Bool(")));
4141
4142        // And a re-emit never produces the Debug forms on disk.
4143        let out = fm.to_yaml();
4144        assert!(!out.contains("Number("), "Debug-form key emitted:\n{out}");
4145        assert!(!out.contains("Bool("), "Debug-form key emitted:\n{out}");
4146        // The key text is still present (quoted, since it now reads as a string).
4147        assert!(out.contains("2026"), "numeric key dropped:\n{out}");
4148        assert!(out.contains("planning notes"), "value dropped:\n{out}");
4149    }
4150
4151    // ── Regression: universal-key sequence/mapping values are preserved (#2) ───
4152
4153    #[test]
4154    fn regression_universal_key_non_scalar_value_is_preserved_not_deleted() {
4155        // A universal key carrying a sequence/mapping (`status: [active, draft]`)
4156        // is not a valid scalar for that field. Before the fix, the matched arm
4157        // consumed-and-dropped it (scalar_string -> None) and `to_yaml` then
4158        // omitted the field — `dbmd format` silently DELETED it. It must now pass
4159        // through `extra` and re-emit verbatim.
4160        let yaml = "type: note\nstatus:\n  - active\n  - draft\nsummary:\n  a: 1\n  b: 2\n";
4161        let fm = Frontmatter::parse(yaml, Path::new("x.md")).unwrap();
4162        // The typed accessors stay None (no valid scalar), but the data lives in
4163        // extra so nothing is lost.
4164        assert!(fm.status.is_none());
4165        assert!(fm.summary.is_none());
4166        assert!(fm.extra.contains_key("status"), "status value destroyed");
4167        assert!(fm.extra.contains_key("summary"), "summary value destroyed");
4168
4169        // A re-emit keeps both fields' data on disk.
4170        let out = fm.to_yaml();
4171        assert!(out.contains("status"), "status deleted on re-emit:\n{out}");
4172        assert!(out.contains("active"), "status items deleted:\n{out}");
4173        assert!(
4174            out.contains("summary"),
4175            "summary deleted on re-emit:\n{out}"
4176        );
4177
4178        // Round-trips as a fixed point — repeated curator-loop writes don't lose
4179        // the data.
4180        let reparsed = Frontmatter::parse(&out, Path::new("x.md")).unwrap();
4181        assert!(reparsed.extra.contains_key("status"));
4182        assert!(reparsed.extra.contains_key("summary"));
4183    }
4184
4185    // ── Regression: non-scalar tags items don't erase the tags field (#5) ──────
4186
4187    #[test]
4188    fn regression_non_scalar_tags_value_is_preserved_not_erased() {
4189        // `tags: [[vip]]` (an authoring slip — wiki-link brackets around a tag)
4190        // parses to a nested sequence; before the fix `parse_tags` filtered the
4191        // non-scalar item out and `to_yaml` then omitted the now-empty tags vec,
4192        // silently DELETING the tags line. It must now survive the re-emit (the
4193        // key data is preserved; the field is never dropped).
4194        let yaml = "type: note\ntags: [[vip]]\n";
4195        let fm = Frontmatter::parse(yaml, Path::new("x.md")).unwrap();
4196        // The typed tags vec is empty (no clean scalar list), but the raw value
4197        // is preserved in extra so nothing is destroyed.
4198        assert!(fm.tags.is_empty());
4199        assert!(fm.extra.contains_key("tags"), "tags value destroyed");
4200
4201        let out = fm.to_yaml();
4202        assert!(out.contains("tags"), "tags deleted on re-emit:\n{out}");
4203        // The `vip` text survives on disk in some form (never erased).
4204        assert!(out.contains("vip"), "tag content erased:\n{out}");
4205
4206        // A clean tag list still parses to the typed vec (not regressed).
4207        let clean =
4208            Frontmatter::parse("type: note\ntags: [vip, renewal]\n", Path::new("x.md")).unwrap();
4209        assert_eq!(clean.tags, vec!["vip".to_string(), "renewal".to_string()]);
4210        assert!(!clean.extra.contains_key("tags"));
4211    }
4212
4213    // ── Regression: plain nested string lists are NOT fabricated into links (#3) ─
4214
4215    #[test]
4216    fn regression_plain_nested_string_list_is_not_turned_into_wiki_links() {
4217        // `groups: [[alpha], [beta]]` is the data [["alpha"],["beta"]] — an
4218        // unknown nested string list that must pass through verbatim. Before the
4219        // fix, canonicalize_extra_value fabricated `- '[[alpha]]'` / `- '[[beta]]'`
4220        // (short-form links the tool then flagged), changing the field's type.
4221        let yaml = "type: note\ngroups: [[alpha], [beta]]\n";
4222        let fm = Frontmatter::parse(yaml, Path::new("x.md")).unwrap();
4223        let before = fm.extra.get("groups").cloned();
4224
4225        let out = fm.to_yaml();
4226        // No fabricated wiki-link brackets in the emitted YAML.
4227        assert!(!out.contains("[[alpha]]"), "fabricated a wiki-link:\n{out}");
4228        assert!(!out.contains("[[beta]]"), "fabricated a wiki-link:\n{out}");
4229
4230        // The value is unchanged across the canonical re-emit.
4231        let reparsed = Frontmatter::parse(&out, Path::new("x.md")).unwrap();
4232        assert_eq!(
4233            reparsed.extra.get("groups"),
4234            before.as_ref(),
4235            "nested string list mutated by canonicalize_extra_value"
4236        );
4237        // And it surfaces no links.
4238        assert!(reparsed.link_fields().is_empty());
4239    }
4240
4241    #[test]
4242    fn regression_genuine_nested_array_is_not_retyped_to_scalar_string() {
4243        // BUG: `dbmd format` silently retyped a genuine 2D array
4244        //     matrix:
4245        //     - - cell
4246        // (data `[["cell"]]`) into the scalar string `matrix: '[[cell]]'`. The
4247        // root cause is the irreducible YAML ambiguity: serde parses BOTH the
4248        // inline scalar wiki-link `field: [[x]]` AND the block nested-seq
4249        // `field:`\n`- - x` to the identical `Seq[Seq[String]]`. The old
4250        // `canonicalize_extra_value` collapsed every one-element `Seq[Seq[String]]`
4251        // to a string, destroying the array. The fix resolves the inline-link
4252        // case from the SOURCE text at parse time and leaves a genuine block
4253        // array verbatim.
4254        let yaml = "type: note\nsummary: nested\nmatrix:\n- - cell\n";
4255        let fm = Frontmatter::parse(yaml, Path::new("nested.md")).unwrap();
4256
4257        // The block source form stays a nested sequence, NOT a string — the
4258        // inline-link disambiguation only fires for source written `key: [[x]]`.
4259        let stored = fm.extra.get("matrix").expect("matrix preserved");
4260        assert!(
4261            matches!(stored, Value::Sequence(items)
4262                if items.len() == 1 && matches!(&items[0], Value::Sequence(_))),
4263            "genuine 2D array was retyped at parse time; got {stored:?}"
4264        );
4265
4266        let out = fm.to_yaml();
4267        // Emit must keep the array (a block nested sequence), never the bogus
4268        // scalar string `'[[cell]]'`.
4269        assert!(
4270            !out.contains("'[[cell]]'") && !out.contains("[[cell]]"),
4271            "genuine nested array retyped to a scalar wiki-link string; got:\n{out}"
4272        );
4273        assert!(
4274            out.contains("- - cell"),
4275            "nested array lost its 2D shape on emit; got:\n{out}"
4276        );
4277
4278        // Full round-trip: re-parsing the emitted YAML yields the identical value
4279        // — the file's bytes are preserved, which is what BUG 2 was about. (The
4280        // read-side `link_fields` still treats a one-element `Seq[Seq[String]]` as
4281        // the inline-link shape it is indistinguishable from on disk; that is the
4282        // same irreducible ambiguity and is out of scope here — the fix's job is
4283        // that `format` no longer silently RETYPES the array to a string.)
4284        let reparsed = Frontmatter::parse(&out, Path::new("nested.md")).unwrap();
4285        assert_eq!(
4286            reparsed.extra.get("matrix"),
4287            fm.extra.get("matrix"),
4288            "nested array did not round-trip through format"
4289        );
4290        // The stored value is still a sequence after round-trip (never a string).
4291        assert!(
4292            matches!(reparsed.extra.get("matrix"), Some(Value::Sequence(_))),
4293            "nested array became a non-sequence after round-trip"
4294        );
4295    }
4296
4297    #[test]
4298    fn inline_scalar_wiki_link_still_round_trips_after_nested_array_fix() {
4299        // The companion guarantee to the test above: the SPEC-canonical inline
4300        // scalar wiki-link `field: [[x]]` (SPEC.md:383) must still format to a
4301        // canonical inline `[[x]]` that round-trips and surfaces as one link —
4302        // the nested-array fix must not regress it.
4303        let yaml = "type: contact\ncompany: [[records/companies/northstar]]\n";
4304        let fm = Frontmatter::parse(yaml, Path::new("c.md")).unwrap();
4305        // Disambiguated at parse time to the canonical scalar string.
4306        assert_eq!(
4307            fm.extra.get("company").and_then(|v| v.as_str()),
4308            Some("[[records/companies/northstar]]")
4309        );
4310
4311        let out = fm.to_yaml();
4312        assert!(
4313            out.contains("[[records/companies/northstar]]") && !out.contains("- - "),
4314            "inline wiki-link not canonical after the nested-array fix; got:\n{out}"
4315        );
4316
4317        let reparsed = Frontmatter::parse(&out, Path::new("c.md")).unwrap();
4318        let fields = reparsed.link_fields();
4319        let links: Vec<(&str, &str)> = fields
4320            .iter()
4321            .map(|(k, l)| (k.as_str(), l.target.as_str()))
4322            .collect();
4323        assert_eq!(links, vec![("company", "records/companies/northstar")]);
4324        // Idempotent across repeated curator-loop writes.
4325        assert_eq!(
4326            reparsed.to_yaml(),
4327            out,
4328            "inline link is not a format fixed point"
4329        );
4330    }
4331
4332    // ── Regression: fence-line trailing whitespace is tolerated (#4) ───────────
4333
4334    #[test]
4335    fn regression_split_frontmatter_tolerates_trailing_whitespace_on_fences() {
4336        // A fence written `--- ` (trailing space — invisible in editors) is
4337        // indexed/validated clean by index.rs/validate.rs (both use `trim_end()`)
4338        // but, before the fix, hard-failed every read/edit surface routed through
4339        // `split_frontmatter`. All three must now agree.
4340        let text = "--- \ntype: note\nsummary: x\n---\t\nbody\n";
4341        let parsed = split_frontmatter(text, Path::new("f.md")).unwrap();
4342        assert_eq!(parsed.frontmatter_yaml, "type: note\nsummary: x\n");
4343        assert_eq!(parsed.body, "body\n");
4344
4345        // End to end through read_file's parse.
4346        let fm = Frontmatter::parse(&parsed.frontmatter_yaml, Path::new("f.md")).unwrap();
4347        assert_eq!(fm.type_.as_deref(), Some("note"));
4348    }
4349
4350    // ── Regression: CommonMark trailing-'#' heading rule (#6) ──────────────────
4351
4352    #[test]
4353    fn regression_heading_text_keeps_abutting_hash_drops_closing_sequence() {
4354        // `## C#` → `C#` (the `#` abuts content, not a closing sequence).
4355        assert_eq!(heading_text("## C#", 2), "C#");
4356        assert_eq!(heading_text("## F#", 2), "F#");
4357        assert_eq!(heading_text("## issue-123#", 2), "issue-123#");
4358        // A genuine ATX closing sequence (space before the `#` run) is dropped.
4359        assert_eq!(heading_text("## Title ##", 2), "Title");
4360        assert_eq!(heading_text("## Title #", 2), "Title");
4361        // All-hashes content collapses to empty.
4362        assert_eq!(heading_text("## ##", 2), "");
4363        // No trailing hashes — unchanged.
4364        assert_eq!(heading_text("## Plain", 2), "Plain");
4365    }
4366
4367    #[test]
4368    fn regression_extract_sections_keeps_csharp_heading_and_schema_type_binds() {
4369        // `dbmd sections` must report `C#`, not `C`.
4370        let secs = extract_sections("## C#\nbody\n");
4371        assert_eq!(secs.len(), 1);
4372        assert_eq!(secs[0].heading, "C#");
4373
4374        // And a `### c#` schema must register under `c#`, not `c`.
4375        let db = "---\ntype: db-md\n---\n\n## Schemas\n\n### c#\n- name (required)\n";
4376        let config = parse_db_md(db, Path::new("DB.md")).unwrap();
4377        assert!(
4378            config.schemas.contains_key("c#"),
4379            "schema bound to wrong key"
4380        );
4381        assert!(!config.schemas.contains_key("c"));
4382    }
4383
4384    // ── Regression: section line numbers offset by the frontmatter block (#7) ──
4385
4386    #[test]
4387    fn regression_extract_sections_in_file_reports_source_line_numbers() {
4388        // A heading on file line 6 (after a 4-line frontmatter block + 1 body
4389        // line) must be reported as L6, not the body-relative L2.
4390        let text = "---\ntype: note\nsummary: x\n---\nbody line\n## Heading\nmore\n";
4391        let secs = extract_sections_in_file(text);
4392        assert_eq!(secs.len(), 1);
4393        assert_eq!(secs[0].heading, "Heading");
4394        assert_eq!(secs[0].line, 6, "section line not offset by frontmatter");
4395
4396        // The body-relative helper is unchanged (validate relies on that frame).
4397        let body_secs = extract_sections("body line\n## Heading\nmore\n");
4398        assert_eq!(body_secs[0].line, 2);
4399
4400        // No frontmatter: whole text is body, no offset.
4401        let plain = extract_sections_in_file("## Top\nx\n## Next\n");
4402        assert_eq!(plain[0].line, 1);
4403        assert_eq!(plain[1].line, 3);
4404    }
4405
4406    // ── Regression: colon-form schema field bullet parses modifiers (#8) ───────
4407
4408    #[test]
4409    fn regression_colon_form_field_bullet_parses_modifiers() {
4410        // `- title: string, required` is the natural mis-spelling of
4411        // `- title (string, required)`; before the fix the whole text became the
4412        // field name and every modifier was silently lost.
4413        let f = parse_field_spec("- title: string, required");
4414        assert_eq!(f.name, "title");
4415        assert!(f.required, "required modifier lost on colon-form");
4416        assert_eq!(f.shape, Some(Shape::String));
4417
4418        // Through the schema-bullet classifier (the real path), it is a Field.
4419        match parse_schema_bullet("- title: string, required") {
4420            SchemaBullet::Field(f) => {
4421                assert_eq!(f.name, "title");
4422                assert!(f.required);
4423                assert_eq!(f.shape, Some(Shape::String));
4424            }
4425            other => panic!("expected Field, got {other:?}"),
4426        }
4427
4428        // A paren form whose modifiers contain a colon still parses by parens.
4429        let g = parse_field_spec("- status (enum: open, closed)");
4430        assert_eq!(g.name, "status");
4431        assert_eq!(
4432            g.enum_values,
4433            Some(vec!["open".to_string(), "closed".to_string()])
4434        );
4435    }
4436
4437    // ── Regression: comma inside a `default` value is preserved (#9) ───────────
4438
4439    #[test]
4440    fn regression_default_value_preserves_internal_commas() {
4441        let f = parse_field_spec("- title (default Director, Operations)");
4442        assert_eq!(
4443            f.default,
4444            Some(Value::String("Director, Operations".into())),
4445            "comma-bearing default truncated"
4446        );
4447
4448        let g = parse_field_spec("- region (default North America, EMEA fallback)");
4449        assert_eq!(
4450            g.default,
4451            Some(Value::String("North America, EMEA fallback".into()))
4452        );
4453
4454        // A single-token default still works (no regression).
4455        let h = parse_field_spec("- currency (default USD)");
4456        assert_eq!(h.default, Some(Value::String("USD".into())));
4457    }
4458
4459    // ── Regression: a `default` after `enum` is parsed, not swallowed (#10) ────
4460
4461    #[test]
4462    fn regression_default_after_enum_is_parsed_not_an_enum_member() {
4463        let f = parse_field_spec("- status (enum: open, closed, default open)");
4464        assert_eq!(
4465            f.enum_values,
4466            Some(vec!["open".to_string(), "closed".to_string()]),
4467            "`default open` leaked into the enum list"
4468        );
4469        assert_eq!(
4470            f.default,
4471            Some(Value::String("open".into())),
4472            "default after enum was dropped"
4473        );
4474
4475        // The bare `enum` keyword form, with a trailing default.
4476        let g = parse_field_spec("- status (enum, open, closed, default open)");
4477        assert_eq!(
4478            g.enum_values,
4479            Some(vec!["open".to_string(), "closed".to_string()])
4480        );
4481        assert_eq!(g.default, Some(Value::String("open".into())));
4482    }
4483
4484    // ── Regression: frozen-page policy does not fail open (#11) ────────────────
4485
4486    #[test]
4487    fn regression_frozen_match_handles_leading_slash() {
4488        let cfg = Config {
4489            frozen_pages: vec![PathBuf::from("/records/decisions/q1.md")],
4490            ..Config::default()
4491        };
4492        assert!(
4493            cfg.is_frozen(Path::new("records/decisions/q1.md")),
4494            "leading-slash entry failed open"
4495        );
4496        assert!(cfg.is_frozen(Path::new("records/decisions/q1")));
4497    }
4498
4499    #[test]
4500    fn regression_frozen_match_supports_globs() {
4501        let cfg = Config {
4502            frozen_pages: vec![PathBuf::from("records/decisions/*")],
4503            ..Config::default()
4504        };
4505        assert!(
4506            cfg.is_frozen(Path::new("records/decisions/q1.md")),
4507            "glob entry failed to protect a concrete file"
4508        );
4509        assert!(cfg.is_frozen(Path::new("records/decisions/q2.md")));
4510        // The glob does not cross a `/` segment.
4511        assert!(!cfg.is_frozen(Path::new("records/decisions/sub/q1.md")));
4512        // `**` crosses segments.
4513        let deep = Config {
4514            frozen_pages: vec![PathBuf::from("records/**")],
4515            ..Config::default()
4516        };
4517        assert!(deep.is_frozen(Path::new("records/decisions/sub/q1.md")));
4518        assert!(deep.is_frozen(Path::new("records/x.md")));
4519        assert!(!deep.is_frozen(Path::new("sources/x.md")));
4520        // A `*.md`-style intra-segment glob.
4521        let suffix = Config {
4522            frozen_pages: vec![PathBuf::from("records/decisions/q*")],
4523            ..Config::default()
4524        };
4525        assert!(suffix.is_frozen(Path::new("records/decisions/q1.md")));
4526        assert!(!suffix.is_frozen(Path::new("records/decisions/draft.md")));
4527    }
4528
4529    #[test]
4530    fn regression_frozen_glob_many_double_stars_does_not_backtrack_exponentially() {
4531        use std::time::Instant;
4532
4533        // A DB.md frozen-page bullet with many consecutive `**` segments and a
4534        // literal tail (`zzz`), matched against a deep target that ends in a
4535        // DIFFERENT segment (`file.md`), is the catastrophic-backtracking case:
4536        // the old two-way `glob_segments` recursion explored an exponential
4537        // number of (star, path) splits before concluding "no match" — ~119s for
4538        // 15 stars — hanging the store's entire write path (every write/rename/
4539        // fm-set funnels through `frozen_match`). The two-pointer matcher + `**`
4540        // collapse make this polynomial.
4541        let pat = format!("{}/zzz", vec!["**"; 30].join("/"));
4542        let target_path = format!("records/{}/file.md", vec!["a"; 40].join("/"));
4543        let cfg = Config {
4544            frozen_pages: vec![PathBuf::from(&pat)],
4545            ..Config::default()
4546        };
4547
4548        let start = Instant::now();
4549        let frozen = cfg.is_frozen(Path::new(&target_path));
4550        let elapsed = start.elapsed();
4551
4552        // The tail `zzz` never matches the target's `file.md`, so it is NOT frozen…
4553        assert!(
4554            !frozen,
4555            "non-matching deep target wrongly reported frozen (semantics changed)"
4556        );
4557        // …and the decision must be near-instant, not exponential. The pre-fix
4558        // code took tens of seconds here; a generous ceiling still fails loudly
4559        // if the blow-up ever returns.
4560        assert!(
4561            elapsed.as_secs() < 1,
4562            "frozen glob took {elapsed:?} — catastrophic backtracking is back"
4563        );
4564
4565        // Semantics preserved: the same many-`**` pattern with a tail that DOES
4566        // match still freezes the file (a real match still refuses the write).
4567        let pat_hit = format!("{}/file.md", vec!["**"; 30].join("/"));
4568        let cfg_hit = Config {
4569            frozen_pages: vec![PathBuf::from(&pat_hit)],
4570            ..Config::default()
4571        };
4572        assert!(
4573            cfg_hit.is_frozen(Path::new(&target_path)),
4574            "many-`**` pattern failed to freeze a genuinely-matching deep target"
4575        );
4576    }
4577
4578    #[test]
4579    fn frozen_glob_double_star_collapse_preserves_match_set() {
4580        // Collapsing consecutive `**` must not change which paths match: `**/**`
4581        // matches exactly what `**` does. Interleaved `**` and literals still
4582        // match across segments, and a non-matching literal tail still fails.
4583        let collapsed = Config {
4584            frozen_pages: vec![PathBuf::from("records/**/**/**/q1.md")],
4585            ..Config::default()
4586        };
4587        assert!(collapsed.is_frozen(Path::new("records/decisions/q1.md")));
4588        assert!(collapsed.is_frozen(Path::new("records/a/b/c/q1.md")));
4589        assert!(collapsed.is_frozen(Path::new("records/q1.md")));
4590        assert!(!collapsed.is_frozen(Path::new("records/a/b/c/q2.md")));
4591        assert!(!collapsed.is_frozen(Path::new("sources/a/q1.md")));
4592
4593        // `**` between two literals spans zero or more intermediate segments.
4594        let between = Config {
4595            frozen_pages: vec![PathBuf::from("records/**/draft.md")],
4596            ..Config::default()
4597        };
4598        assert!(between.is_frozen(Path::new("records/draft.md")));
4599        assert!(between.is_frozen(Path::new("records/a/b/draft.md")));
4600        assert!(!between.is_frozen(Path::new("records/a/b/final.md")));
4601    }
4602
4603    #[test]
4604    fn regression_frozen_entry_single_hyphen_comment_is_stripped() {
4605        // `records/decisions/q3.md - finalized` (single ASCII hyphen comment, no
4606        // backticks): the comment must be stripped so the entry is just the path.
4607        let path = extract_path_bullet("- records/decisions/q3.md - finalized");
4608        assert_eq!(path, "records/decisions/q3.md");
4609
4610        // End to end: such a bullet freezes the file.
4611        let cfg = Config {
4612            frozen_pages: vec![PathBuf::from(extract_path_bullet(
4613                "- records/decisions/q3.md - finalized",
4614            ))],
4615            ..Config::default()
4616        };
4617        assert!(
4618            cfg.is_frozen(Path::new("records/decisions/q3.md")),
4619            "single-hyphen-comment entry failed open"
4620        );
4621    }
4622}