dbmd-cli 0.4.6

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
//! Integration tests for `dbmd assets` (scan / verify / status / paths) and the
//! asset-manifest validation codes.
//!
//! These drive the real `dbmd` binary against synthetic temp stores (the asset
//! commands write `assets.jsonl`, so the committed corpora are never touched).
//! Intent-derived: they assert the properties that MUST hold — the manifest is a
//! pure projection of declarations, `verify` is the byte-completeness gate,
//! `validate` checks integrity without reading bytes (so a fresh clone passes),
//! and a hostile asset path can never escape the store.

mod common;

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

const WRAPPER: &str = "\
---
type: pdf-source
created: 2026-06-17T09:00:00-05:00
updated: 2026-06-17T09:00:00-05:00
summary: \"Contract PDF wrapper\"
asset: sources/docs/2026/06/contract.pdf
---

# Contract
";

/// A store with one wrapper declaring one present binary asset.
fn setup(dir: &std::path::Path) {
    write_db_md(dir);
    write_file(dir, "sources/docs/2026/06/contract.pdf.md", WRAPPER);
    write_file(
        dir,
        "sources/docs/2026/06/contract.pdf",
        "FAKE PDF BYTES 0123456789 abcdefghij",
    );
}

fn json_stdout(out: &std::process::Output) -> Value {
    serde_json::from_slice(&out.stdout).expect("stdout is valid JSON")
}

#[test]
fn scan_catalogs_then_verify_passes() {
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());

    let assert = dbmd()
        .args(["--json", "assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(v["cataloged"], 1);
    assert_eq!(v["hashed"], 1);
    assert_eq!(v["preserved"], 0);
    assert_eq!(v["wrote"], true);

    // The manifest is a real, parseable JSONL record with a 64-hex digest.
    let manifest = std::fs::read_to_string(tmp.path().join("assets.jsonl")).unwrap();
    let rec: Value = serde_json::from_str(manifest.lines().next().unwrap()).unwrap();
    assert_eq!(rec["path"], "sources/docs/2026/06/contract.pdf");
    assert_eq!(rec["sha256"].as_str().unwrap().len(), 64);
    assert_eq!(rec["media_type"], "application/pdf");
    assert_eq!(rec["required"], true);
    assert_eq!(rec["wrappers"][0], "sources/docs/2026/06/contract.pdf.md");

    // Verify is the gate: present + hash-correct ⇒ complete, exit 0.
    let assert = dbmd()
        .args(["--json", "assets", "verify", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(v["complete"], true);
    assert_eq!(v["checked"], 1);
}

#[test]
fn scan_is_idempotent_no_change_on_second_run() {
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let assert = dbmd()
        .args(["--json", "assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(
        v["wrote"], false,
        "a no-op rescan must not rewrite the manifest"
    );
}

#[test]
fn scan_recompacts_duplicate_line_manifest() {
    // The documented git `merge=union` recovery (SPEC § Assets): a manifest with
    // duplicate identical lines must be recompacted to the single canonical line
    // by `assets scan`, and reported as updated — not silently left as-is. The
    // bug was a no-change gate comparing parsed (deduped-by-path) records instead
    // of the on-disk bytes, so a duplicate-line manifest parsed back equal and
    // was never repaired.
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();

    let manifest = tmp.path().join("assets.jsonl");
    let canonical = std::fs::read_to_string(&manifest).unwrap();
    assert_eq!(canonical.lines().count(), 1);

    // Simulate `merge=union`: the same canonical content, twice.
    std::fs::write(&manifest, format!("{canonical}{canonical}")).unwrap();
    assert_eq!(
        std::fs::read_to_string(&manifest).unwrap().lines().count(),
        2
    );

    let assert = dbmd()
        .args(["--json", "assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(
        v["wrote"], true,
        "a non-canonical (duplicate-line) manifest must be recompacted and reported as updated"
    );

    let after = std::fs::read_to_string(&manifest).unwrap();
    assert_eq!(
        after.lines().count(),
        1,
        "duplicate lines must collapse to the single canonical line"
    );
    assert_eq!(
        after, canonical,
        "scan must restore the exact canonical bytes"
    );

    // And re-running over the now-canonical manifest is a true no-op again.
    let assert = dbmd()
        .args(["--json", "assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(
        v["wrote"], false,
        "a recompacted, canonical manifest must rescan as no-change"
    );
    assert_eq!(
        std::fs::read_to_string(&manifest).unwrap(),
        canonical,
        "the no-op rescan must leave the manifest byte-identical"
    );
}

#[test]
fn verify_fails_and_status_reports_missing_required() {
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    std::fs::remove_file(tmp.path().join("sources/docs/2026/06/contract.pdf")).unwrap();

    // The gate fails (non-zero) when a required asset is absent.
    dbmd()
        .args(["assets", "verify", "--dir"])
        .arg(tmp.path())
        .assert()
        .failure();

    // status never fails; it reports the gap.
    let assert = dbmd()
        .args(["--json", "assets", "status", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(v["missing"], 1);
    assert_eq!(v["required_missing"], 1);
}

#[test]
fn rescan_preserves_evicted_asset() {
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    // Evict the bytes (disk-relief): the record must survive, hash preserved.
    std::fs::remove_file(tmp.path().join("sources/docs/2026/06/contract.pdf")).unwrap();

    let assert = dbmd()
        .args(["--json", "assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(v["cataloged"], 1);
    assert_eq!(v["preserved"], 1);
    assert_eq!(v["hashed"], 0);
    assert!(std::fs::read_to_string(tmp.path().join("assets.jsonl"))
        .unwrap()
        .contains("contract.pdf"));
}

#[test]
fn traversal_asset_path_is_rejected_and_not_cataloged() {
    let tmp = tempfile::TempDir::new().unwrap();
    write_db_md(tmp.path());
    write_file(
        tmp.path(),
        "sources/docs/2026/06/evil.md",
        "---\ntype: pdf-source\ncreated: 2026-06-17T09:00:00-05:00\nupdated: \
         2026-06-17T09:00:00-05:00\nsummary: \"evil\"\nasset: \
         ../../../../../../etc/passwd\n---\n\n# Evil\n",
    );
    let assert = dbmd()
        .args(["--json", "assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    assert_eq!(v["cataloged"], 0, "a `..` path must never be cataloged");
    assert!(
        v["warnings"]
            .as_array()
            .unwrap()
            .iter()
            .any(|w| w.as_str().unwrap().contains("..")),
        "the rejection is reported as a warning: {v}"
    );
    // No manifest written when nothing valid was cataloged.
    assert!(!tmp.path().join("assets.jsonl").exists());
}

#[test]
fn paths_omits_store_escaping_records() {
    // SPEC § Assets > Path safety: `dbmd` enforces store-relative containment
    // "wherever it reads the manifest". A poisoned / hand-edited `assets.jsonl`
    // (the `merge=union`-corruption state the SPEC anticipates) with an absolute
    // and a `..`-traversal recorded path must NOT leak those verbatim out of
    // `assets paths` — a harness pipes that list straight into a `.gitignore`
    // managed block or sync-exclude. The escaping entries are omitted (the list
    // analog of how `verify` counts them corrupt and `status` counts them
    // missing); the legitimate in-store path is emitted unchanged.
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();

    // Append two store-escaping records to the scanned manifest.
    let manifest = tmp.path().join("assets.jsonl");
    let mut text = std::fs::read_to_string(&manifest).unwrap();
    text.push_str(
        "{\"path\":\"../../../../../../etc/passwd\",\"sha256\":\"deadbeef\",\"bytes\":4096,\
\"media_type\":\"text/plain\",\"wrappers\":[\"sources/docs/2026/06/contract.pdf.md\"],\
\"required\":false}\n",
    );
    text.push_str(
        "{\"path\":\"/etc/hosts\",\"sha256\":\"deadbeef\",\"bytes\":4096,\
\"media_type\":\"text/plain\",\"wrappers\":[\"sources/docs/2026/06/contract.pdf.md\"],\
\"required\":false}\n",
    );
    std::fs::write(&manifest, text).unwrap();

    // Text form: only the safe in-store path, never the escaping ones.
    let assert = dbmd()
        .args(["assets", "paths", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.contains("sources/docs/2026/06/contract.pdf"),
        "the legitimate in-store path is still emitted: {stdout:?}"
    );
    assert!(
        !stdout.contains("etc/passwd") && !stdout.contains("etc/hosts"),
        "no store-escaping path may leak from `assets paths`: {stdout:?}"
    );

    // JSON form: same containment — only the safe path in the array.
    let assert = dbmd()
        .args(["--json", "assets", "paths", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    let v = json_stdout(assert.get_output());
    let list = v.as_array().expect("paths --json is an array");
    assert_eq!(
        list,
        &vec![Value::from("sources/docs/2026/06/contract.pdf")],
        "JSON `paths` emits only the safe in-store path"
    );
}

#[test]
fn validate_all_passes_on_a_byteless_fresh_clone() {
    // The load-bearing property: `validate` checks manifest integrity (text
    // only), never byte presence, so a clone whose assets have not been restored
    // still validates.
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    dbmd()
        .args(["index", "rebuild", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    // Simulate a fresh clone: text + manifest present, bytes gone.
    std::fs::remove_file(tmp.path().join("sources/docs/2026/06/contract.pdf")).unwrap();

    dbmd()
        .arg("validate")
        .arg(tmp.path())
        .arg("--all")
        .assert()
        .success();
}

#[test]
fn undeclared_asset_is_flagged_by_validate_until_scanned() {
    let tmp = tempfile::TempDir::new().unwrap();
    setup(tmp.path());
    dbmd()
        .args(["index", "rebuild", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();

    // Wrapper declares contract.pdf but it was never scanned into the manifest.
    let assert = dbmd()
        .args(["--json", "validate"])
        .arg(tmp.path())
        .arg("--all")
        .assert()
        .failure();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.contains("ASSET_UNDECLARED"),
        "validate --all flags the uncataloged declaration: {stdout}"
    );

    // After a scan it reconciles and validate is clean.
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    dbmd()
        .arg("validate")
        .arg(tmp.path())
        .arg("--all")
        .assert()
        .success();
}

#[test]
fn optional_asset_excluded_from_default_verify() {
    let tmp = tempfile::TempDir::new().unwrap();
    write_db_md(tmp.path());
    write_file(
        tmp.path(),
        "records/expenses/e1.md",
        "---\ntype: expense\ncreated: 2026-06-17T09:00:00-05:00\nupdated: \
         2026-06-17T09:00:00-05:00\nsummary: \"expense + optional receipt\"\nassets:\n  - \
         { path: records/expenses/r1.png, required: false }\n---\n\n# Expense\n",
    );
    write_file(tmp.path(), "records/expenses/r1.png", "PNG BYTES");
    dbmd()
        .args(["assets", "scan", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    // Delete the optional asset.
    std::fs::remove_file(tmp.path().join("records/expenses/r1.png")).unwrap();

    // Default verify ignores optional assets ⇒ still complete.
    dbmd()
        .args(["assets", "verify", "--dir"])
        .arg(tmp.path())
        .assert()
        .success();
    // With --include-optional the missing optional asset fails the gate.
    dbmd()
        .args(["assets", "verify", "--include-optional", "--dir"])
        .arg(tmp.path())
        .assert()
        .failure();
}