Skip to main content

dbmd_core/
emit.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! `emit` — the whole-store structured dump (a SWEEP, off the loop).
4//!
5//! [`compute`] walks every content file (`sources/` + `records/`, per the
6//! same [`Store::walk`] discovery every SWEEP uses — derived `index.md`
7//! catalogs are skipped) plus the root `DB.md`, and projects each into an
8//! [`EmittedFile`]: the parsed frontmatter with values verbatim, the derived
9//! fields (layer, `type`, effective `meta-type`, title, `summary`,
10//! timestamps), the verbatim body, the normalized wiki-link targets, and the
11//! SHA-256 of the raw file bytes. The host-integration surface: a hub, an
12//! indexer, or a migration ingests a store as a pure consumer of `dbmd`
13//! output instead of reimplementing the parse.
14//!
15//! **Lenient by design.** A dump must describe the store as it is, so a
16//! malformed file degrades instead of aborting the sweep: a file with no
17//! frontmatter block emits an empty `frontmatter` with the whole text as
18//! `body`; unparseable frontmatter YAML emits an empty `frontmatter` with the
19//! after-fence remainder as `body`; a bad `created`/`updated` scalar leaves
20//! the typed timestamp unset while the raw value still rides in
21//! `frontmatter`. (Reporting those defects is `validate`'s job, not the
22//! dump's.) Only real failures — an unreadable file, a broken walk — error.
23//!
24//! **One notion, shared with the rest of the toolkit.** Link extraction is
25//! [`store::extract_edge_targets`] (fence-aware, alias-stripped,
26//! whitespace-trimmed) with the `.md` extension appended — the same
27//! resolution `graph` applies, in the on-disk spelling a consumer can match
28//! against `path` directly. Scalar coercion and the YAML→JSON value
29//! projection are the `index` module's ([`crate::index`]), so `emit` and
30//! `query --json` present identical value shapes. The effective `meta-type`
31//! mirrors [`Frontmatter::effective_meta_type`]: records only, absent ⇒
32//! `fact`, declared values verbatim. Title derivation reuses the `render`
33//! module's CommonMark ATX heading rules.
34//!
35//! [`Frontmatter::effective_meta_type`]: crate::parser::Frontmatter::effective_meta_type
36
37use std::collections::BTreeSet;
38use std::fmt::Write as _;
39use std::path::{Path, PathBuf};
40
41use chrono::{DateTime, FixedOffset};
42use sha2::{Digest, Sha256};
43
44use crate::index::{parse_ts, scalar_string, yaml_to_json_value};
45use crate::parser::split_frontmatter;
46use crate::render::{heading_level, heading_text};
47use crate::store::{self, EdgeSpan, Layer, Store};
48
49/// One file of the dump: the store-relative identity, the parsed frontmatter
50/// (values verbatim), the derived fields, the verbatim body, the normalized
51/// link targets, and the content hash.
52#[derive(Debug, Clone, PartialEq)]
53pub struct EmittedFile {
54    /// Store-relative path, POSIX separators (`records/contacts/sarah.md`).
55    pub path: String,
56    /// The layer the file lives in; `None` for the root `DB.md`.
57    pub layer: Option<Layer>,
58    /// The full parsed frontmatter mapping, values verbatim (the `index`
59    /// projection: strings/numbers/bools/lists as written; an inline
60    /// `[[...]]`-valued field as its wiki-link literal). Empty when the file
61    /// has no frontmatter block or its YAML does not parse.
62    pub frontmatter: serde_json::Map<String, serde_json::Value>,
63    /// The frontmatter `type`, scalar-coerced like `index`/`validate` coerce it.
64    pub type_: Option<String>,
65    /// The effective `meta-type` — records only: the declared value verbatim,
66    /// or `fact` when absent (SPEC default). `None` for sources and `DB.md`.
67    pub meta_type: Option<String>,
68    /// Display title: the `name` field, else the `title` field, else the
69    /// body's first ATX `#` heading (fence-aware, CommonMark rules).
70    pub title: Option<String>,
71    /// The frontmatter `summary`, scalar-coerced; `None` when absent.
72    pub summary: Option<String>,
73    /// The verbatim markdown body after the frontmatter block (the whole text
74    /// when the file has no frontmatter block).
75    pub body: String,
76    /// Normalized wiki-link targets in first-appearance order, deduped:
77    /// alias stripped (text before `|`), whitespace trimmed, `.md` appended —
78    /// the on-disk spelling, so a target matches a document `path` directly.
79    /// Dangling targets are included (existence is `validate`'s concern).
80    pub links: Vec<String>,
81    /// Every wiki-link OCCURRENCE in the body, in document order, with the byte
82    /// span it covers in `body` — the positional view `links` cannot give
83    /// (`links` is a deduped set; a renderer needs to splice at offsets).
84    ///
85    /// Body-only, deliberately: a `[[…]]` in a frontmatter VALUE is a real edge
86    /// (and appears in `links`) but is field data, never markdown rendered in
87    /// place, so it has no span. Empty for `DB.md` and for bodies with no
88    /// links.
89    pub link_spans: Vec<EdgeSpan>,
90    /// Frontmatter `created`, when present and RFC3339-parseable.
91    pub created: Option<DateTime<FixedOffset>>,
92    /// Frontmatter `updated`, when present and RFC3339-parseable.
93    pub updated: Option<DateTime<FixedOffset>>,
94    /// Lowercase-hex SHA-256 of the raw file bytes — the exact bytes this
95    /// projection was parsed from, so a consumer can detect drift.
96    pub sha256: String,
97}
98
99/// A computed whole-store dump: every emitted file plus the per-layer tally.
100#[derive(Debug, Clone, PartialEq)]
101pub struct Emit {
102    /// Every emitted file (content files + `DB.md`), sorted by path.
103    pub files: Vec<EmittedFile>,
104    /// How many emitted files live in `sources/`.
105    pub sources: usize,
106    /// How many emitted files live in `records/`.
107    pub records: usize,
108}
109
110/// **SWEEP.** Project the whole store into an [`Emit`]: every content file
111/// via [`Store::walk`] (both layers, derived catalogs skipped) plus the root
112/// `DB.md`, sorted by path. Read-only; errors only on real failures (an
113/// unreadable file, a broken walk) — malformed content degrades per the
114/// module contract, it never aborts the dump.
115pub fn compute(store: &Store) -> crate::Result<Emit> {
116    let mut rels: Vec<PathBuf> = store.walk()?;
117    rels.push(PathBuf::from("DB.md"));
118    rels.sort();
119
120    let mut files = Vec::with_capacity(rels.len());
121    let mut sources = 0usize;
122    let mut records = 0usize;
123    for rel in &rels {
124        let file = emit_file(store, rel)?;
125        match file.layer {
126            Some(Layer::Sources) => sources += 1,
127            Some(Layer::Records) => records += 1,
128            None => {}
129        }
130        files.push(file);
131    }
132    Ok(Emit {
133        files,
134        sources,
135        records,
136    })
137}
138
139/// Project one store-relative file into its [`EmittedFile`].
140fn emit_file(store: &Store, rel: &Path) -> crate::Result<EmittedFile> {
141    let abs = store.abs_path(rel);
142    let bytes = std::fs::read(&abs)?;
143    let sha256 = sha256_hex(&bytes);
144
145    // Decode lossily: `sources/` is preserved verbatim per the SPEC and can
146    // carry non-UTF-8 imports; a stray byte substitutes U+FFFD rather than
147    // aborting the sweep (the same posture as the index projection and the
148    // store's link scan).
149    let text = String::from_utf8_lossy(&bytes);
150
151    // Split the frontmatter block with the canonical splitter (BOM + fence
152    // tolerance identical to every write surface). A file with no block — or
153    // an unterminated one — is still a complete dump member: empty
154    // frontmatter, the whole text as body.
155    let (yaml, body) = match split_frontmatter(&text, &abs) {
156        Ok(parsed) => (parsed.frontmatter_yaml, parsed.body),
157        Err(_) => (String::new(), text.clone().into_owned()),
158    };
159
160    // Parse the frontmatter YAML leniently: a malformed mapping yields an
161    // empty frontmatter (the body still carries the file), mirroring how a
162    // hand-written store degrades. Non-string keys are skipped, matching the
163    // index projection.
164    let map: serde_norway::Mapping = if yaml.trim().is_empty() {
165        serde_norway::Mapping::new()
166    } else {
167        serde_norway::from_str(&yaml).unwrap_or_default()
168    };
169
170    let mut frontmatter = serde_json::Map::new();
171    let mut type_ = None;
172    let mut summary = None;
173    let mut declared_meta_type = None;
174    let mut name_field = None;
175    let mut title_field = None;
176    let mut created = None;
177    let mut updated = None;
178    for (k, v) in &map {
179        let Some(key) = k.as_str() else { continue };
180        match key {
181            "type" => type_ = scalar_string(v),
182            "summary" => summary = scalar_string(v),
183            "meta-type" => declared_meta_type = scalar_string(v),
184            "name" => name_field = non_empty(scalar_string(v)),
185            "title" => title_field = non_empty(scalar_string(v)),
186            "created" => created = v.as_str().and_then(parse_ts),
187            "updated" => updated = v.as_str().and_then(parse_ts),
188            _ => {}
189        }
190        frontmatter.insert(key.to_string(), yaml_to_json_value(v));
191    }
192
193    let layer = rel
194        .components()
195        .next()
196        .and_then(|c| c.as_os_str().to_str())
197        .and_then(Layer::from_dir_name);
198
199    // Effective meta-type: records only; declared verbatim, absent ⇒ `fact`
200    // (`Frontmatter::effective_meta_type` / the index projection's default).
201    let meta_type = match layer {
202        Some(Layer::Records) => Some(declared_meta_type.unwrap_or_else(|| "fact".to_string())),
203        _ => None,
204    };
205
206    let title = name_field.or(title_field).or_else(|| first_h1(&body));
207
208    // Wiki-link targets over the WHOLE text (frontmatter values + body — the
209    // shared edge extractor handles the split and the fence state), `.md`
210    // appended to the canonical form, deduped in first-appearance order. The
211    // dedup key is the canonical spelling verbatim (byte-portable across
212    // hosts) — the local filesystem's case folding is a resolution concern,
213    // not a dump concern.
214    let mut links = Vec::new();
215    let mut seen = BTreeSet::new();
216    for target in store::extract_edge_targets(&text) {
217        let with_md = format!("{target}.md");
218        if seen.insert(with_md.clone()) {
219            links.push(with_md);
220        }
221    }
222
223    // Positional occurrences over the BODY only (see the field docs). The
224    // shared extractor guarantees these agree with `links` on every fence
225    // decision — one grammar, two views.
226    let link_spans = store::extract_edge_spans(&body);
227
228    Ok(EmittedFile {
229        path: rel.to_string_lossy().replace('\\', "/"),
230        layer,
231        frontmatter,
232        type_,
233        meta_type,
234        title,
235        summary,
236        body,
237        links,
238        link_spans,
239        created,
240        updated,
241        sha256,
242    })
243}
244
245/// A trimmed, non-empty scalar; `None` otherwise. The `name`/`title` fields
246/// only count as a display title when they carry visible text.
247fn non_empty(s: Option<String>) -> Option<String> {
248    s.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
249}
250
251/// The body's first ATX `#` (level-1) heading text, fence-aware: a `# ...`
252/// line inside a ``` / `~~~` fenced code block is code, not a title. Heading
253/// recognition and text extraction are the `render` module's CommonMark rules
254/// ([`heading_level`] / [`heading_text`]), so the dump's title agrees with
255/// `dbmd sections` / `dbmd outline` on what a heading is. An empty heading
256/// (`#` alone, `# ##`) yields no title and the scan continues.
257fn first_h1(body: &str) -> Option<String> {
258    let mut fence: Option<(u8, usize)> = None;
259    for line in body.lines() {
260        let content = line.trim_end_matches('\r');
261        if let Some(f) = fence {
262            if store::fence_closes(content, f) {
263                fence = None;
264            }
265            continue;
266        }
267        if let Some(opened) = store::fence_opens(content) {
268            fence = Some(opened);
269            continue;
270        }
271        if heading_level(content) == 1 {
272            let text = heading_text(content, 1);
273            if !text.is_empty() {
274                return Some(text);
275            }
276        }
277    }
278    None
279}
280
281/// Lowercase-hex SHA-256 of `bytes` — hashed over the same in-memory bytes
282/// the projection parsed, so the digest and the emitted content can never
283/// disagree about which file version was read.
284fn sha256_hex(bytes: &[u8]) -> String {
285    let digest = Sha256::digest(bytes);
286    let mut hex = String::with_capacity(64);
287    for b in digest.iter() {
288        let _ = write!(hex, "{b:02x}");
289    }
290    hex
291}
292
293// ─────────────────────────────────────────────────────────────────────────────
294// Tests
295// ─────────────────────────────────────────────────────────────────────────────
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    /// A throwaway store rooted in a tempdir, with a `DB.md` marker.
302    fn store() -> (tempfile::TempDir, Store) {
303        let tmp = tempfile::TempDir::new().expect("tempdir");
304        std::fs::write(
305            tmp.path().join("DB.md"),
306            "---\ntype: db-md\nscope: test\n---\n\n# Test store\n",
307        )
308        .expect("DB.md");
309        let store = Store::open_strict(tmp.path()).expect("open store");
310        (tmp, store)
311    }
312
313    fn seed(root: &Path, rel: &str, contents: &str) {
314        let abs = root.join(rel);
315        std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
316        std::fs::write(abs, contents).unwrap();
317    }
318
319    fn by_path<'a>(emit: &'a Emit, path: &str) -> &'a EmittedFile {
320        emit.files
321            .iter()
322            .find(|f| f.path == path)
323            .unwrap_or_else(|| panic!("no emitted file {path}"))
324    }
325
326    #[test]
327    fn title_prefers_name_then_title_then_first_h1() {
328        let (tmp, store) = store();
329        seed(
330            tmp.path(),
331            "records/contacts/named.md",
332            "---\ntype: contact\nname: Sarah Chen\ntitle: Ignored\nsummary: s\n---\n\n# Also ignored\n",
333        );
334        seed(
335            tmp.path(),
336            "records/contacts/titled.md",
337            "---\ntype: contact\ntitle: The Title\nsummary: s\n---\nbody\n",
338        );
339        seed(
340            tmp.path(),
341            "records/decisions/h1.md",
342            "---\ntype: decision\nsummary: s\n---\n\n```\n# fenced, not a title\n```\n\n# Real Title ##\n",
343        );
344        let emit = compute(&store).expect("emit");
345        assert_eq!(
346            by_path(&emit, "records/contacts/named.md").title.as_deref(),
347            Some("Sarah Chen")
348        );
349        assert_eq!(
350            by_path(&emit, "records/contacts/titled.md")
351                .title
352                .as_deref(),
353            Some("The Title")
354        );
355        // Fence-aware: the fenced `#` line is code; the real H1's closing-hash
356        // run is stripped per the CommonMark ATX rule.
357        assert_eq!(
358            by_path(&emit, "records/decisions/h1.md").title.as_deref(),
359            Some("Real Title")
360        );
361    }
362
363    #[test]
364    fn no_frontmatter_degrades_to_empty_frontmatter_and_whole_body() {
365        let (tmp, store) = store();
366        let text = "Just a plain note, no frontmatter.\n";
367        seed(tmp.path(), "sources/notes/plain.md", text);
368        let emit = compute(&store).expect("emit");
369        let f = by_path(&emit, "sources/notes/plain.md");
370        assert!(f.frontmatter.is_empty());
371        assert_eq!(f.type_, None);
372        assert_eq!(f.body, text);
373        assert_eq!(f.layer, Some(Layer::Sources));
374    }
375
376    #[test]
377    fn meta_type_defaults_for_records_only() {
378        let (tmp, store) = store();
379        seed(
380            tmp.path(),
381            "records/contacts/fact.md",
382            "---\ntype: contact\nsummary: s\n---\nbody\n",
383        );
384        seed(
385            tmp.path(),
386            "records/decisions/conclusion.md",
387            "---\ntype: decision\nmeta-type: conclusion\nsummary: s\n---\nbody\n",
388        );
389        seed(
390            tmp.path(),
391            "sources/notes/n.md",
392            "---\ntype: note\nsummary: s\n---\nbody\n",
393        );
394        let emit = compute(&store).expect("emit");
395        assert_eq!(
396            by_path(&emit, "records/contacts/fact.md")
397                .meta_type
398                .as_deref(),
399            Some("fact")
400        );
401        assert_eq!(
402            by_path(&emit, "records/decisions/conclusion.md")
403                .meta_type
404                .as_deref(),
405            Some("conclusion")
406        );
407        assert_eq!(by_path(&emit, "sources/notes/n.md").meta_type, None);
408        assert_eq!(by_path(&emit, "DB.md").meta_type, None);
409    }
410
411    #[test]
412    fn links_are_normalized_deduped_and_fence_aware() {
413        let (tmp, store) = store();
414        seed(
415            tmp.path(),
416            "sources/notes/n.md",
417            "---\ntype: note\nsummary: s\ncompany: \"[[records/companies/acme]]\"\n---\n\
418             See [[records/contacts/sarah]] and [[records/contacts/sarah.md|Sarah]].\n\
419             Dangling: [[records/ghosts/nobody]].\n\
420             ```\n[[records/contacts/fenced]]\n```\n",
421        );
422        let emit = compute(&store).expect("emit");
423        let f = by_path(&emit, "sources/notes/n.md");
424        // Frontmatter link first (extraction order), then body links in
425        // first-appearance order; the `.md` and bare spellings collapse; the
426        // fenced pseudo-link is code, not an edge; the dangling target stays.
427        assert_eq!(
428            f.links,
429            vec![
430                "records/companies/acme.md".to_string(),
431                "records/contacts/sarah.md".to_string(),
432                "records/ghosts/nobody.md".to_string(),
433            ]
434        );
435    }
436
437    #[test]
438    fn db_md_is_emitted_with_no_layer_and_counts_ride_the_layers() {
439        let (tmp, store) = store();
440        seed(
441            tmp.path(),
442            "sources/notes/n.md",
443            "---\ntype: note\nsummary: s\n---\nbody\n",
444        );
445        seed(
446            tmp.path(),
447            "records/contacts/c.md",
448            "---\ntype: contact\nsummary: s\n---\nbody\n",
449        );
450        // A derived catalog must not be emitted.
451        seed(
452            tmp.path(),
453            "records/contacts/index.md",
454            "# Contacts index\n",
455        );
456        let emit = compute(&store).expect("emit");
457        let paths: Vec<&str> = emit.files.iter().map(|f| f.path.as_str()).collect();
458        assert_eq!(
459            paths,
460            vec!["DB.md", "records/contacts/c.md", "sources/notes/n.md"]
461        );
462        let db = by_path(&emit, "DB.md");
463        assert_eq!(db.layer, None);
464        assert_eq!(db.type_.as_deref(), Some("db-md"));
465        assert_eq!(db.title.as_deref(), Some("Test store"));
466        assert_eq!((emit.files.len(), emit.sources, emit.records), (3, 1, 1));
467    }
468}