dbmd-cli 0.13.2

The `dbmd` command-line tool for db.md, the open standard for databases in plain files. A thin wrapper over dbmd-core: validate, search, query, graph, write, index, and log over a db.md store. Zero AI dependencies.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// SPDX-License-Identifier: Apache-2.0

//! End-to-end tests for `dbmd emit` — the whole-store structured dump —
//! driven through the real `dbmd` binary against a synthetic temp store.
//!
//! Intent-derived: each test pins a property the dump contract requires
//! (the JSON envelope shape, layer classification, link normalization,
//! meta-type defaulting, body extraction, the file-bytes SHA-256) the way a
//! hosting hub or indexer would consume it — parse stdout, address fields
//! structurally, never string-compare the whole document.

mod common;

use std::path::{Path, PathBuf};

use common::{dbmd, write_db_md, write_file};

// ─────────────────────────────────────────────────────────────────────────────
// The fixture store
// ─────────────────────────────────────────────────────────────────────────────

/// A testimonial source with links: a dup pair (`.md` + alias spellings of the
/// same target), a dangling target, and a frontmatter passthrough field.
const NOTE_BODY: &str = "\nCarlos confirmed with [[records/contacts/sarah-chen]] and\n[[records/contacts/sarah-chen.md|Sarah]]; see [[records/decisions/ghost-call]].\n";
const NOTE_FM: &str = "type: note\ncreated: 2026-05-27T08:00:00Z\nupdated: 2026-06-01T09:30:00Z\nsummary: Carlos said the pivot is on\ntold_by: Carlos\n";

/// An entity record: no `meta-type` (⇒ effective `fact`), `name` as the title
/// source, a type-specific field for the verbatim-frontmatter assertion.
const CONTACT: &str = "---\ntype: contact\nname: Sarah Chen\ncreated: 2026-05-01T12:00:00Z\nupdated: 2026-06-02T10:00:00Z\nsummary: Design lead at Acme\ncompany: Acme\n---\n\nMet at the pivot call.\n";

/// A conclusion record with NO summary, an H1 title, and a fenced code block
/// whose `[[...]]` must not count as a link.
const DECISION: &str = "---\ntype: decision\nmeta-type: conclusion\ncreated: 2026-06-03T08:00:00Z\nupdated: 2026-06-03T08:00:00Z\n---\n\n# Ship the pivot\n\nDecided with [[records/contacts/sarah-chen]].\n\n```\n[[records/contacts/fenced-not-a-link]]\n```\n";

/// A hand-written file with no frontmatter block at all.
const PLAIN: &str = "Just a plain note that predates the store discipline.\n";

/// Seed the fixture store into `root` (which already carries `DB.md`).
fn seed_store(root: &Path) {
    let note = format!("---\n{NOTE_FM}---\n{NOTE_BODY}");
    write_file(root, "sources/notes/pivot-call.md", &note);
    write_file(root, "sources/notes/plain.md", PLAIN);
    write_file(root, "records/contacts/sarah-chen.md", CONTACT);
    write_file(root, "records/decisions/pivot.md", DECISION);
    // Derived catalogs must be skipped, per the store's discovery rules.
    write_file(root, "records/contacts/index.md", "# Contacts\n");
    write_file(root, "records/contacts/index.jsonl", "");
}

/// A fresh fixture store in a tempdir: `(guard, root)`.
fn fixture() -> (tempfile::TempDir, PathBuf) {
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let root = tmp.path().to_path_buf();
    write_db_md(&root);
    seed_store(&root);
    (tmp, root)
}

/// Run `dbmd --json emit <root>` and parse stdout as the dump document.
fn emit_json(root: &Path) -> serde_json::Value {
    let out = dbmd().args(["--json", "emit"]).arg(root).assert().success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).expect("utf8 stdout");
    serde_json::from_str(stdout.trim()).expect("stdout is one JSON document")
}

/// The emitted file object for `path`, or panic.
fn file<'a>(dump: &'a serde_json::Value, path: &str) -> &'a serde_json::Value {
    dump["files"]
        .as_array()
        .expect("files is an array")
        .iter()
        .find(|f| f["path"] == path)
        .unwrap_or_else(|| panic!("no emitted file {path} in {dump}"))
}

/// Lowercase-hex SHA-256 — the independent recomputation the dump's `sha256`
/// is checked against.
fn sha256_hex(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    use std::fmt::Write as _;
    let digest = Sha256::digest(bytes);
    let mut hex = String::with_capacity(64);
    for b in digest.iter() {
        let _ = write!(hex, "{b:02x}");
    }
    hex
}

// ─────────────────────────────────────────────────────────────────────────────
// The envelope: shape, membership, order, summary counts
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn dump_envelope_has_store_files_and_summary_counts() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    // Top-level shape.
    assert_eq!(dump["store"], root.to_string_lossy().as_ref());
    assert!(dump["files"].is_array());

    // Membership + order: content files plus DB.md, sorted by path; the
    // derived index.md catalog (and the non-markdown sidecar) never appear.
    let paths: Vec<&str> = dump["files"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| f["path"].as_str().expect("path is a string"))
        .collect();
    assert_eq!(
        paths,
        vec![
            "DB.md",
            "records/contacts/sarah-chen.md",
            "records/decisions/pivot.md",
            "sources/notes/pivot-call.md",
            "sources/notes/plain.md",
        ]
    );

    // Summary counts: DB.md is a file but belongs to neither layer.
    assert_eq!(dump["summary"]["files"], 5);
    assert_eq!(dump["summary"]["sources"], 2);
    assert_eq!(dump["summary"]["records"], 2);
}

#[test]
fn layers_classify_source_record_and_null_for_db_md() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    assert_eq!(
        file(&dump, "sources/notes/pivot-call.md")["layer"],
        "source"
    );
    assert_eq!(
        file(&dump, "records/contacts/sarah-chen.md")["layer"],
        "record"
    );
    let db = file(&dump, "DB.md");
    assert!(db["layer"].is_null(), "DB.md carries no layer: {db}");
    // DB.md is still a full member: its config frontmatter and H1 title ride
    // along so a host needs no separate DB.md parse.
    assert_eq!(db["type"], "db-md");
    assert_eq!(db["frontmatter"]["scope"], "company");
    assert_eq!(db["title"], "Test store");
    assert!(db["meta_type"].is_null());
}

// ─────────────────────────────────────────────────────────────────────────────
// Per-file projection: frontmatter, meta-type, title, summary, body, times
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn frontmatter_is_verbatim_and_derived_fields_are_typed() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    let note = file(&dump, "sources/notes/pivot-call.md");
    // Full frontmatter, values verbatim — including the custom passthrough
    // field and the raw timestamp spellings.
    assert_eq!(note["frontmatter"]["type"], "note");
    assert_eq!(note["frontmatter"]["told_by"], "Carlos");
    assert_eq!(note["frontmatter"]["created"], "2026-05-27T08:00:00Z");
    // Derived typed fields: canonical RFC3339 timestamps, coerced scalars.
    assert_eq!(note["type"], "note");
    assert_eq!(note["summary"], "Carlos said the pivot is on");
    assert_eq!(note["created"], "2026-05-27T08:00:00+00:00");
    assert_eq!(note["updated"], "2026-06-01T09:30:00+00:00");
    // A source carries no meta-type.
    assert!(note["meta_type"].is_null());

    let contact = file(&dump, "records/contacts/sarah-chen.md");
    assert_eq!(contact["frontmatter"]["company"], "Acme");
    assert_eq!(
        contact["title"], "Sarah Chen",
        "title from the `name` field"
    );
}

#[test]
fn meta_type_defaults_to_fact_for_records_and_keeps_declared_values() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    // No declared meta-type on a record ⇒ the SPEC default.
    assert_eq!(
        file(&dump, "records/contacts/sarah-chen.md")["meta_type"],
        "fact"
    );
    // A declared value passes through verbatim.
    assert_eq!(
        file(&dump, "records/decisions/pivot.md")["meta_type"],
        "conclusion"
    );
}

#[test]
fn missing_summary_is_null_and_title_falls_back_to_first_h1() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    let decision = file(&dump, "records/decisions/pivot.md");
    assert!(
        decision["summary"].is_null(),
        "no summary field ⇒ null, never an invented one: {decision}"
    );
    assert_eq!(decision["title"], "Ship the pivot");
}

#[test]
fn body_is_the_verbatim_text_after_the_frontmatter_block() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    // With a frontmatter block: everything after the closing fence, verbatim.
    assert_eq!(
        file(&dump, "sources/notes/pivot-call.md")["body"],
        NOTE_BODY
    );

    // Without one: the whole text is the body and the frontmatter is empty.
    let plain = file(&dump, "sources/notes/plain.md");
    assert_eq!(plain["body"], PLAIN);
    assert_eq!(
        plain["frontmatter"],
        serde_json::json!({}),
        "no frontmatter block ⇒ empty object"
    );
    assert!(plain["type"].is_null());
    assert_eq!(plain["layer"], "source");
}

// ─────────────────────────────────────────────────────────────────────────────
// Links: normalization, dedup, fence-awareness, dangling targets
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn links_are_normalized_md_paths_deduped_with_dangling_kept() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    // Alias stripped (text before `|`), `.md` appended, the bare and `.md`
    // spellings of one target collapsed, first-appearance order; the dangling
    // target is still emitted (existence is validate's concern, not the dump's).
    assert_eq!(
        file(&dump, "sources/notes/pivot-call.md")["links"],
        serde_json::json!([
            "records/contacts/sarah-chen.md",
            "records/decisions/ghost-call.md",
        ])
    );

    // A `[[...]]` inside a fenced code block is code, not an edge.
    assert_eq!(
        file(&dump, "records/decisions/pivot.md")["links"],
        serde_json::json!(["records/contacts/sarah-chen.md"])
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// sha256: the digest of the exact file bytes
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn sha256_is_the_hex_digest_of_the_raw_file_bytes() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    // Recompute independently from the fixture constants (the bytes on disk).
    assert_eq!(
        file(&dump, "records/contacts/sarah-chen.md")["sha256"],
        sha256_hex(CONTACT.as_bytes())
    );
    assert_eq!(
        file(&dump, "sources/notes/plain.md")["sha256"],
        sha256_hex(PLAIN.as_bytes())
    );

    // And against the actual on-disk bytes for a composed file, so the
    // assertion cannot drift from what was written.
    let note_bytes = std::fs::read(root.join("sources/notes/pivot-call.md")).unwrap();
    assert_eq!(
        file(&dump, "sources/notes/pivot-call.md")["sha256"],
        sha256_hex(&note_bytes)
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Text mode + the not-a-store failure
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn text_mode_prints_the_emitted_paths_one_per_line() {
    let (_tmp, root) = fixture();
    let out = dbmd().arg("emit").arg(&root).assert().success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert_eq!(
        stdout,
        "DB.md\nrecords/contacts/sarah-chen.md\nrecords/decisions/pivot.md\nsources/notes/pivot-call.md\nsources/notes/plain.md\n"
    );
}

#[test]
fn a_non_store_dir_fails_with_not_a_store_exit_3() {
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let out = dbmd()
        .args(["--json", "emit"])
        .arg(tmp.path())
        .assert()
        .failure()
        .code(3);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    let err: serde_json::Value = serde_json::from_str(stderr.trim()).expect("structured error");
    assert_eq!(err["error"]["code"], "NOT_A_STORE");
}

// ─────────────────────────────────────────────────────────────────────────────
// link_spans — the positional view a renderer splices on
// ─────────────────────────────────────────────────────────────────────────────

/// A host that renders wiki-links needs to know WHERE the tokens are, not just
/// which targets exist. Without that it must re-find them itself, which means
/// re-implementing bracket scanning and — the part that rots — fence tracking.
/// These pin the contract that makes the re-implementation unnecessary.
#[test]
fn link_spans_are_body_occurrences_a_consumer_can_splice_on() {
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let root = tmp.path().to_path_buf();
    write_db_md(&root);
    std::fs::create_dir_all(root.join("records/notes")).unwrap();
    std::fs::write(
        root.join("records/notes/doc.md"),
        "---\ntype: note\nsummary: Spans fixture.\nrelated: \"[[records/notes/in-fm]]\"\n---\n\n\
         How you write a link:\n\n\
         ```markdown\n[[records/notes/fenced-example]]\n```\n\n\
         A real one: [[records/notes/target|The Target]] here.\n",
    )
    .unwrap();

    let dump = emit_json(&root);
    let doc = file(&dump, "records/notes/doc.md");
    let spans = doc["link_spans"]
        .as_array()
        .expect("link_spans is an array");
    let body = doc["body"].as_str().expect("body is a string");

    // The edge SET carries the frontmatter link (it is a real edge) and the
    // body link; the fenced example is an edge to neither view.
    let links: Vec<&str> = doc["links"]
        .as_array()
        .unwrap()
        .iter()
        .map(|l| l.as_str().unwrap())
        .collect();
    assert_eq!(links, ["records/notes/in-fm.md", "records/notes/target.md"]);

    // The positional view is BODY-only, so exactly one occurrence: the
    // frontmatter link has no span, and the fenced example is not a link.
    assert_eq!(
        spans.len(),
        1,
        "expected one body occurrence, got {spans:?}"
    );
    let s = &spans[0];
    assert_eq!(s["target"], "records/notes/target");
    assert_eq!(s["alias"], "The Target");
    assert_eq!(s["raw"], "records/notes/target|The Target");

    // The span indexes `body` exactly — the splice a renderer performs.
    let (start, end) = (
        s["start"].as_u64().unwrap() as usize,
        s["end"].as_u64().unwrap() as usize,
    );
    assert_eq!(&body[start..end], "[[records/notes/target|The Target]]");
    let spliced = format!("{}<LINK>{}", &body[..start], &body[end..]);
    assert!(spliced.contains("A real one: <LINK> here."));
    // And the fenced example survived the splice untouched — the whole point.
    assert!(spliced.contains("[[records/notes/fenced-example]]"));
}

// ─────────────────────────────────────────────────────────────────────────────
// NDJSON: the streaming form of the same contract
// ─────────────────────────────────────────────────────────────────────────────

/// `emit --ndjson` is `--json`'s `files[]` verbatim, one compact object per
/// line, same membership and order, no envelope — the property a streaming
/// consumer (a hosting hub) relies on: concatenating the lines reconstructs
/// the array exactly, so the two forms can never drift.
#[test]
fn ndjson_lines_equal_json_files_array_in_order() {
    let (_tmp, root) = fixture();
    let dump = emit_json(&root);

    let out = dbmd()
        .args(["emit", "--ndjson"])
        .arg(&root)
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).expect("utf8 stdout");
    let lines: Vec<serde_json::Value> = stdout
        .lines()
        .map(|l| serde_json::from_str(l).expect("each line is one JSON object"))
        .collect();

    assert_eq!(
        serde_json::Value::Array(lines),
        dump["files"],
        "ndjson lines must equal the --json files[] array, in order"
    );
}

/// The global `--json` flag composes with (and is redundant with) `--ndjson`:
/// the streaming form already IS machine output, so both spellings produce
/// identical NDJSON — never the enveloped document.
#[test]
fn ndjson_wins_when_global_json_is_also_set() {
    let (_tmp, root) = fixture();
    let plain = dbmd()
        .args(["emit", "--ndjson"])
        .arg(&root)
        .assert()
        .success();
    let both = dbmd()
        .args(["--json", "emit", "--ndjson"])
        .arg(&root)
        .assert()
        .success();
    assert_eq!(
        String::from_utf8(plain.get_output().stdout.clone()).unwrap(),
        String::from_utf8(both.get_output().stdout.clone()).unwrap(),
    );
}