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 rels = walk_rels(store)?;
117
118 let mut files = Vec::with_capacity(rels.len());
119 let mut sources = 0usize;
120 let mut records = 0usize;
121 for rel in &rels {
122 let file = emit_file(store, rel)?;
123 match file.layer {
124 Some(Layer::Sources) => sources += 1,
125 Some(Layer::Records) => records += 1,
126 None => {}
127 }
128 files.push(file);
129 }
130 Ok(Emit {
131 files,
132 sources,
133 records,
134 })
135}
136
137/// The exact file set a dump covers, in the exact order it emits: every
138/// content file per [`Store::walk`] plus the root `DB.md`, path-sorted.
139/// One definition, shared by [`compute`] and streaming consumers (the
140/// `--ndjson` CLI mode projects these one at a time), so the two forms can
141/// never disagree on membership or order.
142pub fn walk_rels(store: &Store) -> crate::Result<Vec<PathBuf>> {
143 let mut rels: Vec<PathBuf> = store.walk()?;
144 rels.push(PathBuf::from("DB.md"));
145 rels.sort();
146 Ok(rels)
147}
148
149/// Project one store-relative file into its [`EmittedFile`]. Public for
150/// streaming consumers ([`walk_rels`] supplies the canonical file set);
151/// the lenient-degrade contract is the module's, identical under
152/// [`compute`] and per-file use.
153pub fn emit_file(store: &Store, rel: &Path) -> crate::Result<EmittedFile> {
154 let abs = store.abs_path(rel);
155 let bytes = std::fs::read(&abs)?;
156 let sha256 = sha256_hex(&bytes);
157
158 // Decode lossily: `sources/` is preserved verbatim per the SPEC and can
159 // carry non-UTF-8 imports; a stray byte substitutes U+FFFD rather than
160 // aborting the sweep (the same posture as the index projection and the
161 // store's link scan).
162 let text = String::from_utf8_lossy(&bytes);
163
164 // Split the frontmatter block with the canonical splitter (BOM + fence
165 // tolerance identical to every write surface). A file with no block — or
166 // an unterminated one — is still a complete dump member: empty
167 // frontmatter, the whole text as body.
168 let (yaml, body) = match split_frontmatter(&text, &abs) {
169 Ok(parsed) => (parsed.frontmatter_yaml, parsed.body),
170 Err(_) => (String::new(), text.clone().into_owned()),
171 };
172
173 // Parse the frontmatter YAML leniently: a malformed mapping yields an
174 // empty frontmatter (the body still carries the file), mirroring how a
175 // hand-written store degrades. Non-string keys are skipped, matching the
176 // index projection.
177 let map: serde_norway::Mapping = if yaml.trim().is_empty() {
178 serde_norway::Mapping::new()
179 } else {
180 serde_norway::from_str(&yaml).unwrap_or_default()
181 };
182
183 let mut frontmatter = serde_json::Map::new();
184 let mut type_ = None;
185 let mut summary = None;
186 let mut declared_meta_type = None;
187 let mut name_field = None;
188 let mut title_field = None;
189 let mut created = None;
190 let mut updated = None;
191 for (k, v) in &map {
192 let Some(key) = k.as_str() else { continue };
193 match key {
194 "type" => type_ = scalar_string(v),
195 "summary" => summary = scalar_string(v),
196 "meta-type" => declared_meta_type = scalar_string(v),
197 "name" => name_field = non_empty(scalar_string(v)),
198 "title" => title_field = non_empty(scalar_string(v)),
199 "created" => created = v.as_str().and_then(parse_ts),
200 "updated" => updated = v.as_str().and_then(parse_ts),
201 _ => {}
202 }
203 frontmatter.insert(key.to_string(), yaml_to_json_value(v));
204 }
205
206 let layer = rel
207 .components()
208 .next()
209 .and_then(|c| c.as_os_str().to_str())
210 .and_then(Layer::from_dir_name);
211
212 // Effective meta-type: records only; declared verbatim, absent ⇒ `fact`
213 // (`Frontmatter::effective_meta_type` / the index projection's default).
214 let meta_type = match layer {
215 Some(Layer::Records) => Some(declared_meta_type.unwrap_or_else(|| "fact".to_string())),
216 _ => None,
217 };
218
219 let title = name_field.or(title_field).or_else(|| first_h1(&body));
220
221 // Wiki-link targets over the WHOLE text (frontmatter values + body — the
222 // shared edge extractor handles the split and the fence state), `.md`
223 // appended to the canonical form, deduped in first-appearance order. The
224 // dedup key is the canonical spelling verbatim (byte-portable across
225 // hosts) — the local filesystem's case folding is a resolution concern,
226 // not a dump concern.
227 let mut links = Vec::new();
228 let mut seen = BTreeSet::new();
229 for target in store::extract_edge_targets(&text) {
230 let with_md = format!("{target}.md");
231 if seen.insert(with_md.clone()) {
232 links.push(with_md);
233 }
234 }
235
236 // Positional occurrences over the BODY only (see the field docs). The
237 // shared extractor guarantees these agree with `links` on every fence
238 // decision — one grammar, two views.
239 let link_spans = store::extract_edge_spans(&body);
240
241 Ok(EmittedFile {
242 path: rel.to_string_lossy().replace('\\', "/"),
243 layer,
244 frontmatter,
245 type_,
246 meta_type,
247 title,
248 summary,
249 body,
250 links,
251 link_spans,
252 created,
253 updated,
254 sha256,
255 })
256}
257
258/// A trimmed, non-empty scalar; `None` otherwise. The `name`/`title` fields
259/// only count as a display title when they carry visible text.
260fn non_empty(s: Option<String>) -> Option<String> {
261 s.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
262}
263
264/// The body's first ATX `#` (level-1) heading text, fence-aware: a `# ...`
265/// line inside a ``` / `~~~` fenced code block is code, not a title. Heading
266/// recognition and text extraction are the `render` module's CommonMark rules
267/// ([`heading_level`] / [`heading_text`]), so the dump's title agrees with
268/// `dbmd sections` / `dbmd outline` on what a heading is. An empty heading
269/// (`#` alone, `# ##`) yields no title and the scan continues.
270fn first_h1(body: &str) -> Option<String> {
271 let mut fence: Option<(u8, usize)> = None;
272 for line in body.lines() {
273 let content = line.trim_end_matches('\r');
274 if let Some(f) = fence {
275 if store::fence_closes(content, f) {
276 fence = None;
277 }
278 continue;
279 }
280 if let Some(opened) = store::fence_opens(content) {
281 fence = Some(opened);
282 continue;
283 }
284 if heading_level(content) == 1 {
285 let text = heading_text(content, 1);
286 if !text.is_empty() {
287 return Some(text);
288 }
289 }
290 }
291 None
292}
293
294/// Lowercase-hex SHA-256 of `bytes` — hashed over the same in-memory bytes
295/// the projection parsed, so the digest and the emitted content can never
296/// disagree about which file version was read.
297fn sha256_hex(bytes: &[u8]) -> String {
298 let digest = Sha256::digest(bytes);
299 let mut hex = String::with_capacity(64);
300 for b in digest.iter() {
301 let _ = write!(hex, "{b:02x}");
302 }
303 hex
304}
305
306// ─────────────────────────────────────────────────────────────────────────────
307// Tests
308// ─────────────────────────────────────────────────────────────────────────────
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313
314 /// A throwaway store rooted in a tempdir, with a `DB.md` marker.
315 fn store() -> (tempfile::TempDir, Store) {
316 let tmp = tempfile::TempDir::new().expect("tempdir");
317 std::fs::write(
318 tmp.path().join("DB.md"),
319 "---\ntype: db-md\nscope: test\n---\n\n# Test store\n",
320 )
321 .expect("DB.md");
322 let store = Store::open_strict(tmp.path()).expect("open store");
323 (tmp, store)
324 }
325
326 fn seed(root: &Path, rel: &str, contents: &str) {
327 let abs = root.join(rel);
328 std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
329 std::fs::write(abs, contents).unwrap();
330 }
331
332 fn by_path<'a>(emit: &'a Emit, path: &str) -> &'a EmittedFile {
333 emit.files
334 .iter()
335 .find(|f| f.path == path)
336 .unwrap_or_else(|| panic!("no emitted file {path}"))
337 }
338
339 #[test]
340 fn title_prefers_name_then_title_then_first_h1() {
341 let (tmp, store) = store();
342 seed(
343 tmp.path(),
344 "records/contacts/named.md",
345 "---\ntype: contact\nname: Sarah Chen\ntitle: Ignored\nsummary: s\n---\n\n# Also ignored\n",
346 );
347 seed(
348 tmp.path(),
349 "records/contacts/titled.md",
350 "---\ntype: contact\ntitle: The Title\nsummary: s\n---\nbody\n",
351 );
352 seed(
353 tmp.path(),
354 "records/decisions/h1.md",
355 "---\ntype: decision\nsummary: s\n---\n\n```\n# fenced, not a title\n```\n\n# Real Title ##\n",
356 );
357 let emit = compute(&store).expect("emit");
358 assert_eq!(
359 by_path(&emit, "records/contacts/named.md").title.as_deref(),
360 Some("Sarah Chen")
361 );
362 assert_eq!(
363 by_path(&emit, "records/contacts/titled.md")
364 .title
365 .as_deref(),
366 Some("The Title")
367 );
368 // Fence-aware: the fenced `#` line is code; the real H1's closing-hash
369 // run is stripped per the CommonMark ATX rule.
370 assert_eq!(
371 by_path(&emit, "records/decisions/h1.md").title.as_deref(),
372 Some("Real Title")
373 );
374 }
375
376 #[test]
377 fn no_frontmatter_degrades_to_empty_frontmatter_and_whole_body() {
378 let (tmp, store) = store();
379 let text = "Just a plain note, no frontmatter.\n";
380 seed(tmp.path(), "sources/notes/plain.md", text);
381 let emit = compute(&store).expect("emit");
382 let f = by_path(&emit, "sources/notes/plain.md");
383 assert!(f.frontmatter.is_empty());
384 assert_eq!(f.type_, None);
385 assert_eq!(f.body, text);
386 assert_eq!(f.layer, Some(Layer::Sources));
387 }
388
389 #[test]
390 fn meta_type_defaults_for_records_only() {
391 let (tmp, store) = store();
392 seed(
393 tmp.path(),
394 "records/contacts/fact.md",
395 "---\ntype: contact\nsummary: s\n---\nbody\n",
396 );
397 seed(
398 tmp.path(),
399 "records/decisions/conclusion.md",
400 "---\ntype: decision\nmeta-type: conclusion\nsummary: s\n---\nbody\n",
401 );
402 seed(
403 tmp.path(),
404 "sources/notes/n.md",
405 "---\ntype: note\nsummary: s\n---\nbody\n",
406 );
407 let emit = compute(&store).expect("emit");
408 assert_eq!(
409 by_path(&emit, "records/contacts/fact.md")
410 .meta_type
411 .as_deref(),
412 Some("fact")
413 );
414 assert_eq!(
415 by_path(&emit, "records/decisions/conclusion.md")
416 .meta_type
417 .as_deref(),
418 Some("conclusion")
419 );
420 assert_eq!(by_path(&emit, "sources/notes/n.md").meta_type, None);
421 assert_eq!(by_path(&emit, "DB.md").meta_type, None);
422 }
423
424 #[test]
425 fn links_are_normalized_deduped_and_fence_aware() {
426 let (tmp, store) = store();
427 seed(
428 tmp.path(),
429 "sources/notes/n.md",
430 "---\ntype: note\nsummary: s\ncompany: \"[[records/companies/acme]]\"\n---\n\
431 See [[records/contacts/sarah]] and [[records/contacts/sarah.md|Sarah]].\n\
432 Dangling: [[records/ghosts/nobody]].\n\
433 ```\n[[records/contacts/fenced]]\n```\n",
434 );
435 let emit = compute(&store).expect("emit");
436 let f = by_path(&emit, "sources/notes/n.md");
437 // Frontmatter link first (extraction order), then body links in
438 // first-appearance order; the `.md` and bare spellings collapse; the
439 // fenced pseudo-link is code, not an edge; the dangling target stays.
440 assert_eq!(
441 f.links,
442 vec![
443 "records/companies/acme.md".to_string(),
444 "records/contacts/sarah.md".to_string(),
445 "records/ghosts/nobody.md".to_string(),
446 ]
447 );
448 }
449
450 #[test]
451 fn db_md_is_emitted_with_no_layer_and_counts_ride_the_layers() {
452 let (tmp, store) = store();
453 seed(
454 tmp.path(),
455 "sources/notes/n.md",
456 "---\ntype: note\nsummary: s\n---\nbody\n",
457 );
458 seed(
459 tmp.path(),
460 "records/contacts/c.md",
461 "---\ntype: contact\nsummary: s\n---\nbody\n",
462 );
463 // A derived catalog must not be emitted.
464 seed(
465 tmp.path(),
466 "records/contacts/index.md",
467 "# Contacts index\n",
468 );
469 let emit = compute(&store).expect("emit");
470 let paths: Vec<&str> = emit.files.iter().map(|f| f.path.as_str()).collect();
471 assert_eq!(
472 paths,
473 vec!["DB.md", "records/contacts/c.md", "sources/notes/n.md"]
474 );
475 let db = by_path(&emit, "DB.md");
476 assert_eq!(db.layer, None);
477 assert_eq!(db.type_.as_deref(), Some("db-md"));
478 assert_eq!(db.title.as_deref(), Some("Test store"));
479 assert_eq!((emit.files.len(), emit.sources, emit.records), (3, 1, 1));
480 }
481}