dbmd-cli 0.4.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
//! Regression tests for the write-path launch-blocking bugs (findings #17,
//! #18, #25). Each test reconstructs the finding's exact trigger and asserts the
//! corrected behavior through the real `dbmd` binary, so the bug can never
//! silently return.
//!
//!   - #17 — `dbmd write --summary` / `dbmd fm init --summary` must NOT silently
//!     hard-truncate an explicit >200-char agent summary (parity with
//!     `dbmd fm set`, which preserves it verbatim).
//!   - #18 — `dbmd write`'s collision guard must be atomic, not TOCTOU: two
//!     concurrent writers to the same resolved path can never both succeed and
//!     silently clobber one another's primary content.
//!   - #25 — `dbmd fm init` on a file that opens a `---` frontmatter fence but
//!     never closes it must refuse with `FM_MALFORMED`, not demote the intended
//!     keys into the body and inject a dangling `---`.

mod common;

use std::process::Command as StdCommand;
use std::sync::{Arc, Barrier};

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

// ─────────────────────────────────────────────────────────────────────────────
// #17 — explicit `--summary` is collapsed but never truncated.
// ─────────────────────────────────────────────────────────────────────────────

/// A >200-char single-line summary whose meaningful qualifier sits in the tail —
/// the exact shape the pre-fix 200-char truncation silently dropped.
fn long_summary() -> String {
    format!(
        "Director of Operations at Northstar; renewal champion who drove the 175-seat expansion and {}END_QUALIFIER",
        "x".repeat(150)
    )
}

#[test]
fn regression_write_preserves_long_explicit_summary() {
    let tmp = tempfile::TempDir::new().unwrap();
    let store = tmp.path();
    write_db_md(store);

    let summary = long_summary();
    assert!(summary.chars().count() > 200, "fixture must exceed the cap");

    dbmd()
        .current_dir(store)
        .args([
            "write",
            "records/contacts/sarah.md",
            "--type",
            "contact",
            "--summary",
            &summary,
        ])
        .assert()
        .success();

    let written = std::fs::read_to_string(store.join("records/contacts/sarah.md")).unwrap();
    // The full agent summary survives — the trailing qualifier (the part a
    // 200-char cut would discard) is on disk.
    assert!(
        written.contains("END_QUALIFIER"),
        "explicit --summary must not be truncated; the tail is missing:\n{written}"
    );
    assert!(
        written.contains(&summary),
        "the full explicit summary must round-trip verbatim:\n{written}"
    );
}

#[test]
fn regression_fm_init_preserves_long_explicit_summary() {
    let (_tmp, store) = copy_store_to_temp(&corpus_a());
    write_file(
        &store,
        "records/contacts/nina-ray.md",
        "---\nname: Nina Ray\nrole: Analyst\n---\n\n# Nina Ray\n",
    );

    let summary = long_summary();
    dbmd()
        .current_dir(&store)
        .args([
            "fm",
            "init",
            "records/contacts/nina-ray.md",
            "--summary",
            &summary,
        ])
        .assert()
        .success();

    let written = std::fs::read_to_string(store.join("records/contacts/nina-ray.md")).unwrap();
    assert!(
        written.contains("END_QUALIFIER") && written.contains(&summary),
        "fm init --summary must not truncate the agent's value:\n{written}"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// #18 — the collision guard is atomic, not TOCTOU.
// ─────────────────────────────────────────────────────────────────────────────

/// Two concurrent `dbmd write`s targeting the SAME resolved path can never both
/// succeed with different content — that is the silent-clobber the pre-fix
/// `exists()`-then-`rename` window allowed. Exactly one wins (exit 0); the other
/// is refused with `PATH_COLLISION` (exit 5); and the surviving file holds the
/// winner's content, not a torn or overwritten mix. Run many rounds so the
/// race window is actually exercised — the invariant is one-sided (it can fail
/// pre-fix, never post-fix).
#[test]
fn regression_concurrent_write_never_silently_clobbers() {
    let bin = env!("CARGO_BIN_EXE_dbmd");

    for round in 0..40 {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = tmp.path().to_path_buf();
        write_db_md(&store);

        let rel = "records/contacts/sarah.md";
        let barrier = Arc::new(Barrier::new(2));
        let summaries = ["SUMMARY_A", "SUMMARY_B"];

        let handles: Vec<_> = summaries
            .iter()
            .map(|s| {
                let bin = bin.to_string();
                let store = store.clone();
                let barrier = Arc::clone(&barrier);
                let summary = s.to_string();
                std::thread::spawn(move || {
                    // Synchronize the two spawns so they hit the resolve→claim
                    // window as close together as possible.
                    barrier.wait();
                    let out = StdCommand::new(&bin)
                        .current_dir(&store)
                        .args([
                            "write",
                            "records/contacts/sarah.md",
                            "--type",
                            "contact",
                            "--summary",
                            &summary,
                        ])
                        .output()
                        .expect("spawn dbmd");
                    (summary, out.status.code())
                })
            })
            .collect();

        let results: Vec<(String, Option<i32>)> =
            handles.into_iter().map(|h| h.join().unwrap()).collect();

        let successes: Vec<&String> = results
            .iter()
            .filter(|(_, code)| *code == Some(0))
            .map(|(s, _)| s)
            .collect();
        let collisions = results.iter().filter(|(_, code)| *code == Some(5)).count();

        // Exactly one writer may win; the other MUST be told PATH_COLLISION
        // (exit 5) rather than silently succeeding and clobbering.
        assert_eq!(
            successes.len(),
            1,
            "round {round}: exactly one concurrent write may succeed, got {results:?}",
        );
        assert_eq!(
            collisions, 1,
            "round {round}: the losing write must report PATH_COLLISION (exit 5), got {results:?}",
        );

        // The surviving file holds the winner's content (no torn write, no
        // silent overwrite of the winner by the loser).
        let written = std::fs::read_to_string(store.join(rel)).unwrap();
        let winner = successes[0];
        assert!(
            written.contains(&format!("summary: {winner}")),
            "round {round}: surviving file must hold the winner's summary `{winner}`:\n{written}",
        );
    }
}

/// A plain pre-existing file is still refused with the structured
/// `PATH_COLLISION` and left byte-for-byte untouched — the core create-new
/// writer must not regress the ordinary collision contract.
#[test]
fn regression_write_atomic_new_still_refuses_existing_file_without_overwrite() {
    let (_tmp, store) = copy_store_to_temp(&corpus_a());
    let original =
        "---\ntype: contact\nsummary: ORIGINAL\nname: Sarah\n---\n\n# Sarah\n\nOriginal body.\n";
    write_file(&store, "records/contacts/collide.md", original);

    dbmd()
        .current_dir(&store)
        .args([
            "write",
            "records/contacts/collide.md",
            "--type",
            "contact",
            "--summary",
            "A DIFFERENT SUMMARY",
        ])
        .assert()
        .code(5);

    let after = std::fs::read_to_string(store.join("records/contacts/collide.md")).unwrap();
    assert_eq!(
        after, original,
        "a refused write must not modify the existing file",
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// #25 — `fm init` refuses an unterminated frontmatter fence.
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn regression_fm_init_refuses_unterminated_frontmatter_fence() {
    let (_tmp, store) = copy_store_to_temp(&corpus_a());
    // Opens a `---` fence but never closes it: the operator INTENDED `name`
    // and `role` as frontmatter. Pre-fix, `fm init` demoted these into the body
    // and injected a stray `---`; now it must refuse.
    let malformed = "---\nname: Tom\nrole: VP\n# Tom\nbody\n";
    let path = write_file(&store, "records/contacts/tom.md", malformed);

    dbmd()
        .current_dir(&store)
        .args(["fm", "init", "records/contacts/tom.md"])
        .assert()
        .failure()
        .code(1);

    // The file is left byte-for-byte untouched — no demotion, no injected fence.
    let after = std::fs::read_to_string(&path).unwrap();
    assert_eq!(
        after, malformed,
        "a refused fm init must not rewrite the malformed file",
    );
}

#[test]
fn regression_fm_init_refuses_unterminated_fence_with_structured_code() {
    let (_tmp, store) = copy_store_to_temp(&corpus_a());
    write_file(
        &store,
        "records/contacts/tom-json.md",
        "---\nname: Tom\nrole: VP\nbody\n",
    );

    let out = StdCommand::new(env!("CARGO_BIN_EXE_dbmd"))
        .current_dir(&store)
        .args(["--json", "fm", "init", "records/contacts/tom-json.md"])
        .output()
        .expect("spawn dbmd");
    assert_eq!(out.status.code(), Some(1));
    let err: serde_json::Value =
        serde_json::from_str(String::from_utf8_lossy(&out.stderr).trim()).expect("json error");
    assert_eq!(
        err["error"]["code"], "FM_MALFORMED",
        "unterminated fence must surface the FM_MALFORMED code, got {err}",
    );
}

/// A genuinely headerless import (no opening fence) must STILL be canonicalized —
/// the #25 fix must not regress the raw-markdown import path into a false
/// refusal.
#[test]
fn regression_fm_init_still_imports_headerless_file() {
    let (_tmp, store) = copy_store_to_temp(&corpus_a());
    let raw = "# Tom Vega\n\nNew finance contact.\n";
    write_file(&store, "records/contacts/tom-raw.md", raw);

    dbmd()
        .current_dir(&store)
        .args(["fm", "init", "records/contacts/tom-raw.md"])
        .assert()
        .success();

    let written = std::fs::read_to_string(store.join("records/contacts/tom-raw.md")).unwrap();
    assert!(
        written.starts_with("---\n"),
        "frontmatter added:\n{written}"
    );
    assert!(
        written.contains("type: contact"),
        "type inferred:\n{written}"
    );
    assert!(
        written.ends_with(raw),
        "the raw headerless body must be preserved verbatim:\n{written}"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Adversarial review — a dot-prefixed INTERMEDIATE directory must be refused on
// every write surface. `ensure_safe_store_relative` dot-checked only the LEAF,
// so `records/.hidden/c.md --type contact` was honored as the type-folder. All
// store walkers run `.hidden(true)`, so the record + its write-through sidecars
// were invisible: `validate --all` reported 0 issues, `query` returned nothing,
// and `index rebuild` neither catalogued the record nor deleted the orphan
// sidecars — silent primary-data loss no sweep could heal.
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn regression_write_refuses_dot_prefixed_intermediate_directory() {
    let tmp = tempfile::TempDir::new().unwrap();
    let store = tmp.path();
    write_db_md(store);

    // The bug's exact trigger: a dot-prefixed intermediate directory.
    let out = dbmd()
        .current_dir(store)
        .args([
            "write",
            "records/.hidden/c.md",
            "--type",
            "contact",
            "--fm",
            "name=Carol",
            "--summary",
            "Carol",
        ])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "a dot-prefixed intermediate dir must be refused"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("DOTFILE_NOT_ALLOWED") || stderr.to_lowercase().contains("hidden"),
        "the refusal must name the dotfile rule; stderr: {stderr}"
    );
    // Nothing landed on disk — not under the dot-dir, and it did NOT silently
    // collapse to the canonical type-folder either.
    assert!(
        !store.join("records/.hidden/c.md").exists(),
        "no record may land under the dot-dir"
    );
    assert!(
        !store.join("records/contacts/c.md").exists(),
        "the refused write must not collapse to the canonical folder"
    );

    // Control: a dot-prefixed LEAF remains refused (pre-existing behavior).
    dbmd()
        .current_dir(store)
        .args([
            "write",
            "records/notes/.draft.md",
            "--type",
            "note",
            "--summary",
            "Draft",
        ])
        .assert()
        .failure();

    // Control: an ordinary path under an ordinary folder still succeeds and is
    // visible to a query (proving the guard rejects only dot-components).
    dbmd()
        .current_dir(store)
        .args([
            "write",
            "records/contacts/carol.md",
            "--type",
            "contact",
            "--fm",
            "name=Carol",
            "--summary",
            "Carol",
        ])
        .assert()
        .success();
    assert!(
        store.join("records/contacts/carol.md").exists(),
        "a normal write must still work"
    );
}

#[test]
fn regression_rename_refuses_dot_prefixed_destination_directory() {
    let tmp = tempfile::TempDir::new().unwrap();
    let store = tmp.path();
    write_db_md(store);

    // A real, queryable record.
    dbmd()
        .current_dir(store)
        .args([
            "write",
            "records/contacts/dana.md",
            "--type",
            "contact",
            "--fm",
            "name=Dana",
            "--summary",
            "Dana",
        ])
        .assert()
        .success();

    // Renaming it INTO a dot-prefixed directory must be refused — the same hole
    // the write surface had, reached through `require_store_relative`.
    let out = dbmd()
        .current_dir(store)
        .args([
            "rename",
            "records/contacts/dana.md",
            "records/.stash/dana.md",
        ])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "rename into a dot-prefixed dir must be refused"
    );
    // The record stays queryable at its original visible path.
    assert!(
        store.join("records/contacts/dana.md").exists(),
        "the record must not be hidden by a refused rename"
    );
    assert!(
        !store.join("records/.stash/dana.md").exists(),
        "nothing may land under the dot-dir"
    );
}