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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! CLI error type + the documented **exit-code convention**.
//!
//! `dbmd` is an agent-primary tool: every failure is machine-parseable. A
//! command returns a [`CliError`]; [`crate::main`] maps it to a stable exit
//! code (see [`ExitCode`]) and, under `--json`, prints a structured
//! `{"error": {...}}` object to stderr so the calling agent can branch on
//! `code` without scraping prose.
//!
//! # Exit codes (stable contract)
//!
//! | Code | Meaning                       | Example                                   |
//! |------|-------------------------------|-------------------------------------------|
//! | `0`  | success                       | command ran, no problems                  |
//! | `1`  | runtime error                 | I/O failure, parse failure, file missing  |
//! | `2`  | usage error                   | bad flags / args (emitted by `clap`)      |
//! | `3`  | not a db.md store             | no `DB.md` at the resolved root           |
//! | `4`  | policy refusal                | write blocked by a `DB.md ## Policies` rule |
//! | `5`  | collision / conflict          | `dbmd write` onto an existing path        |
//! | `6`  | validation found issues       | `dbmd validate` reported errors           |
//! | `64` | not yet implemented           | reserved; no current body returns it      |
//!
//! These codes are part of the tool's interface; do not renumber them. New
//! failure classes get a new code, never a reuse. `clap` owns exit code `2`
//! for argument-parsing failures — handlers here never return it.

use std::fmt;

/// Stable process exit codes. The numeric values are a public contract; see
/// the module docs. `clap` emits `2` for arg-parse errors on its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum ExitCode {
    /// Everything succeeded.
    Success = 0,
    /// A runtime error: I/O, parse, missing file, or any uncategorized failure.
    Runtime = 1,
    /// Bad invocation (flags / args). Reserved for `clap`; handlers don't use it.
    Usage = 2,
    /// The resolved path is not a db.md store (no `DB.md` at the root).
    NotAStore = 3,
    /// A write was refused by a `DB.md ## Policies` rule (e.g. a frozen page).
    Policy = 4,
    /// A path / entity collision (e.g. `dbmd write` onto an existing file).
    Collision = 5,
    /// `dbmd validate` completed but reported one or more errors.
    ValidationFailed = 6,
    /// A subcommand body not yet implemented. Reserved: every current body is
    /// implemented, so nothing returns this today, but the code stays allocated
    /// so a future not-yet-built subcommand has a stable, unambiguous exit code.
    NotImplemented = 64,
}

impl ExitCode {
    /// The raw integer this code maps to for `std::process::exit`.
    pub fn code(self) -> i32 {
        self as i32
    }
}

/// A short, stable machine code string used in `--json` error output and in
/// human messages. Kept distinct from [`ExitCode`] so several string codes can
/// share one exit code (e.g. several policy codes all exit `4`).
///
/// `dbmd-core` already defines the canonical write-path codes (`NOT_A_STORE`,
/// `POLICY_FROZEN_PAGE`, …); this mirrors them at the CLI boundary.
#[derive(Debug, Clone)]
pub struct CliError {
    /// The exit code this error maps to.
    pub exit: ExitCode,
    /// A stable machine-parseable code string, e.g. `"NOT_A_STORE"`,
    /// `"NOT_IMPLEMENTED"`, `"IO_ERROR"`. Surfaced verbatim in `--json`.
    pub code: &'static str,
    /// Human-readable, single-line explanation.
    pub message: String,
    /// Optional remediation hint (a command to run, a path to fix).
    pub hint: Option<String>,
    /// Permission-filtered structured diagnostics supplied by the hub.
    pub details: Option<serde_json::Value>,
}

impl CliError {
    /// Construct an error with an explicit exit code + machine code.
    pub fn new(exit: ExitCode, code: &'static str, message: impl Into<String>) -> Self {
        Self {
            exit,
            code,
            message: message.into(),
            hint: None,
            details: None,
        }
    }

    /// Attach a remediation hint (chainable).
    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// Attach structured diagnostics (chainable).
    pub fn with_details(mut self, details: serde_json::Value) -> Self {
        self.details = Some(details);
        self
    }

    /// The canonical "this subcommand is not built yet" error. No current body
    /// returns it — every subcommand is implemented — but it is kept as the
    /// reserved constructor for the `64` contract code so a future not-yet-built
    /// subcommand (and tests) can signal an unimplemented path unambiguously.
    pub fn not_implemented(subcommand: &str) -> Self {
        Self::new(
            ExitCode::NotImplemented,
            "NOT_IMPLEMENTED",
            format!("`dbmd {subcommand}` is not implemented yet"),
        )
        .with_hint("this subcommand is recognized but its body is not implemented in this build")
    }

    /// A generic runtime error (exit `1`, code `RUNTIME_ERROR`).
    pub fn runtime(message: impl Into<String>) -> Self {
        Self::new(ExitCode::Runtime, "RUNTIME_ERROR", message)
    }

    /// Render this error as a structured JSON object for `--json` mode. Shape:
    /// `{"error": {"code": "...", "message": "...", "hint": "..."}}`.
    pub fn to_json(&self) -> serde_json::Value {
        let mut obj = serde_json::Map::new();
        obj.insert(
            "code".to_string(),
            serde_json::Value::String(self.code.to_string()),
        );
        obj.insert(
            "message".to_string(),
            serde_json::Value::String(self.message.clone()),
        );
        if let Some(hint) = &self.hint {
            obj.insert("hint".to_string(), serde_json::Value::String(hint.clone()));
        }
        if let Some(details) = &self.details {
            obj.insert("details".to_string(), details.clone());
        }
        serde_json::json!({ "error": serde_json::Value::Object(obj) })
    }
}

impl fmt::Display for CliError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)?;
        if let Some(hint) = &self.hint {
            write!(f, "\n  hint: {hint}")?;
        }
        Ok(())
    }
}

impl std::error::Error for CliError {}

/// Map a `dbmd_core::Error` onto a [`CliError`] with the right exit code +
/// machine code. This is the single conversion point so every subcommand that
/// bubbles a core error gets consistent exit semantics.
impl From<dbmd_core::Error> for CliError {
    fn from(err: dbmd_core::Error) -> Self {
        match err {
            dbmd_core::Error::NotAStore(_) => {
                CliError::new(ExitCode::NotAStore, "NOT_A_STORE", err.to_string())
                    .with_hint("run `dbmd` from inside a db.md store, or pass the store path")
            }
            dbmd_core::Error::Policy { code, message } => {
                CliError::new(ExitCode::Policy, code, message)
            }
            dbmd_core::Error::Store(_) => {
                CliError::new(ExitCode::Runtime, "STORE_ERROR", err.to_string())
            }
            dbmd_core::Error::Parse(_) => {
                CliError::new(ExitCode::Runtime, "PARSE_ERROR", err.to_string())
            }
            dbmd_core::Error::Io(_) => {
                CliError::new(ExitCode::Runtime, "IO_ERROR", err.to_string())
            }
        }
    }
}

impl From<std::io::Error> for CliError {
    fn from(err: std::io::Error) -> Self {
        CliError::new(ExitCode::Runtime, "IO_ERROR", err.to_string())
    }
}

/// Map a link.md client error onto a [`CliError`]: every wire-or-config
/// failure is a `Runtime` (exit `1`) with a stable machine code — an agent
/// branches on the string code, not new exit numbers (the numeric table is a
/// locked contract and the link verbs add no new class to it).
impl From<dbmd_core::linkmd::LinkError> for CliError {
    fn from(err: dbmd_core::linkmd::LinkError) -> Self {
        use dbmd_core::linkmd::LinkError as L;
        let message = err.to_string();
        match err {
            L::NoHub => CliError::new(ExitCode::Runtime, "NO_HUB", message),
            L::NoCredential => CliError::new(ExitCode::Runtime, "NO_CREDENTIAL", message),
            L::BadKey => CliError::new(ExitCode::Runtime, "BAD_CREDENTIAL", message),
            L::UnboundCredential => CliError::new(ExitCode::Runtime, "UNBOUND_CREDENTIAL", message),
            L::UnsafeHub { .. } => CliError::new(ExitCode::Runtime, "HUB_NOT_HTTPS", message),
            L::Transport { .. } => CliError::new(ExitCode::Runtime, "HUB_UNREACHABLE", message),
            L::Http { code, details, .. } => {
                let mut e = match code.as_deref() {
                    Some("NOT_FOUND") => {
                        CliError::new(ExitCode::Runtime, "NOT_FOUND", message)
                    }
                    Some("validation_refused") => {
                        CliError::new(ExitCode::ValidationFailed, "VALIDATION_REFUSED", message)
                    }
                    Some("authorization_refused") => {
                        CliError::new(ExitCode::Policy, "AUTHORIZATION_REFUSED", message)
                    }
                    Some("source_coordinate_used") => CliError::new(
                        ExitCode::Policy,
                        "SOURCE_COORDINATE_USED",
                        message,
                    )
                    .with_hint(
                        "restore the exact historical source coordinate; do not re-append it as new evidence",
                    ),
                    Some("v1_migration_required") => {
                        CliError::new(ExitCode::Policy, "V1_MIGRATION_REQUIRED", message)
                            .with_hint("an owner or brain administrator must complete the explicit v2 migration")
                    }
                    Some("v2_sync_required") => {
                        CliError::new(ExitCode::Policy, "V2_SYNC_REQUIRED", message)
                            .with_hint("retry through dbmd sync, which negotiates link.md v2")
                    }
                    _ => CliError::new(ExitCode::Runtime, "HUB_ERROR", message),
                };
                if let Some(details) = details {
                    e = e.with_details(details);
                }
                match code.as_deref() {
                    Some(c) if e.code == "HUB_ERROR" => e.with_hint(format!("hub error code: {c}")),
                    Some("validation_refused") if e.details.is_some() => {
                        e.with_hint("fix the permission-filtered issues in error.details and retry")
                    }
                    _ => e,
                }
            }
            L::NotJson { .. } => CliError::new(ExitCode::Runtime, "HUB_NOT_JSON", message),
            L::ResponseTooLarge { .. } => {
                CliError::new(ExitCode::Runtime, "RESPONSE_TOO_LARGE", message)
            }
            L::BadAddress { .. } => CliError::new(ExitCode::Runtime, "BAD_ADDRESS", message)
                .with_hint(
                    "addresses are `@brain`, `@brain/<record-id>`, or `@brain/<store-path>.md`",
                ),
            L::BadGrantId { .. } => CliError::new(ExitCode::Runtime, "BAD_GRANT_ID", message)
                .with_hint("copy the id from `dbmd grant list <brain>`"),
            L::UnsafePath { .. } => CliError::new(ExitCode::Runtime, "UNSAFE_PATH", message),
            L::PushTooLarge { .. } => CliError::new(ExitCode::Runtime, "PUSH_TOO_LARGE", message),
            L::ProposeTooLarge { .. } => {
                CliError::new(ExitCode::Runtime, "PROPOSE_TOO_LARGE", message)
            }
            L::NotUtf8 { .. } => CliError::new(ExitCode::Runtime, "NOT_UTF8", message),
            L::InvalidPack { .. } => CliError::new(ExitCode::Runtime, "INVALID_PACK", message),
            L::InvalidFeed { .. } => CliError::new(ExitCode::Runtime, "INVALID_FEED", message),
            L::AliasRebindRequired { alias, from, to } => CliError::new(
                ExitCode::Policy,
                "ALIAS_REBIND_REQUIRED",
                message,
            )
            .with_hint(format!(
                "after verifying both canonical ids, run `dbmd sync {alias} rebind --from {from} --to {to}`"
            ))
            .with_details(serde_json::json!({
                "alias": alias,
                "from": from,
                "to": to,
            })),
            L::Conflict { .. } => CliError::new(ExitCode::Runtime, "SYNC_CONFLICT", message),
            L::ConflictBundle { bundle, paths } => CliError::new(
                ExitCode::Runtime,
                "SYNC_CONFLICT",
                message,
            )
            .with_hint(
                "inspect .dbmd/conflicts/<bundle>/plan.json, then run `dbmd sync resolve <bundle> --keep-local`, `--take-remote`, or `--from <safe-file>`",
            )
            .with_details(serde_json::json!({
                "class": "content_resolution_required",
                "bundle": bundle,
                "paths": paths,
            })),
            L::LocalPolicyTransition { .. } => {
                CliError::new(ExitCode::Policy, "LOCAL_POLICY_RELAXED", message)
            }
            L::AssetWithdrawalRequired { paths } => CliError::new(
                ExitCode::Policy,
                "ASSET_WITHDRAWAL_REQUIRED",
                message,
            )
            .with_hint(
                "review custody for every listed path, then retry with --withdraw-from-hosting <path> and --withdraw-reason <company audit reason>",
            )
            .with_details(serde_json::json!({ "paths": paths })),
            L::BulkPreviewRequired { preview } => CliError::new(
                ExitCode::Policy,
                "BULK_PREVIEW_REQUIRED",
                message,
            )
            .with_hint(
                "review error.details, then retry the same sync with --confirm-bulk <bulk_preview_id>:<bulk_preview_digest>",
            )
            .with_details(preview),
            L::ScopedProjectionModified => {
                CliError::new(ExitCode::Policy, "SCOPED_PROJECTION_MODIFIED", message)
            }
            L::ScopedViewChanged => CliError::new(ExitCode::Policy, "SCOPED_VIEW_CHANGED", message),
            L::BrainUnavailable => CliError::new(ExitCode::Policy, "BRAIN_UNAVAILABLE", message),
            L::RemoteAdvancedDuringSync => {
                CliError::new(ExitCode::Runtime, "REMOTE_ADVANCED_DURING_SYNC", message)
            }
            L::UnsupportedPlatform { .. } => {
                CliError::new(ExitCode::Runtime, "UNSUPPORTED_PLATFORM", message)
            }
            L::BadAgentKey { .. } => CliError::new(ExitCode::Runtime, "BAD_AGENT_KEY", message)
                .with_hint("mint a key with `dbmd key generate --out <file>`"),
            L::Io(_) => CliError::new(ExitCode::Runtime, "IO_ERROR", message),
            L::Store(_) => CliError::new(ExitCode::Runtime, "STORE_ERROR", message),
        }
    }
}

/// Convenience result alias for subcommand bodies.
pub type CliResult = std::result::Result<(), CliError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn permission_filtered_hub_validation_details_keep_a_stable_contract() {
        let details = serde_json::json!({
            "issues": [{
                "code": "SCHEMA_MISSING_REQUIRED",
                "file": "records/contacts/new.md",
                "key": "email"
            }]
        });
        let error = CliError::from(dbmd_core::linkmd::LinkError::Http {
            what: "v2 sync push",
            status: 422,
            message: "mutation introduces db.md validation errors".to_string(),
            code: Some("validation_refused".to_string()),
            details: Some(details.clone()),
        });
        assert_eq!(error.exit, ExitCode::ValidationFailed);
        assert_eq!(error.code, "VALIDATION_REFUSED");
        assert_eq!(error.to_json()["error"]["details"], details);
        assert!(error.hint.as_deref().unwrap().contains("error.details"));
    }

    #[test]
    fn withdrawn_source_reuse_is_a_typed_policy_refusal() {
        let error = CliError::from(dbmd_core::linkmd::LinkError::Http {
            what: "v2 sync",
            status: 409,
            message: "a withdrawn source coordinate may only be restored from exact history".into(),
            code: Some("source_coordinate_used".into()),
            details: None,
        });
        assert_eq!(error.exit, ExitCode::Policy);
        assert_eq!(error.code, "SOURCE_COORDINATE_USED");
        assert!(error.hint.as_deref().unwrap().contains("exact historical"));
    }

    #[test]
    fn hosted_asset_withdrawal_requires_explicit_audited_intent() {
        let paths = vec!["sources/private/customer-export.csv".to_string()];
        let error = CliError::from(dbmd_core::linkmd::LinkError::AssetWithdrawalRequired {
            paths: paths.clone(),
        });
        assert_eq!(error.exit, ExitCode::Policy);
        assert_eq!(error.code, "ASSET_WITHDRAWAL_REQUIRED");
        assert_eq!(
            error.to_json()["error"]["details"]["paths"],
            serde_json::json!(paths)
        );
        assert!(error.hint.as_deref().unwrap().contains("--withdraw-reason"));
    }

    #[test]
    fn hub_authorization_refusal_is_a_policy_exit() {
        let error = CliError::from(dbmd_core::linkmd::LinkError::Http {
            what: "v2 sync push",
            status: 403,
            message: "mutation authority refused".to_string(),
            code: Some("authorization_refused".to_string()),
            details: None,
        });
        assert_eq!(error.exit, ExitCode::Policy);
        assert_eq!(error.code, "AUTHORIZATION_REFUSED");
    }

    #[test]
    fn profile_cutover_refusals_have_stable_agent_codes() {
        for (hub_code, cli_code) in [
            ("v1_migration_required", "V1_MIGRATION_REQUIRED"),
            ("v2_sync_required", "V2_SYNC_REQUIRED"),
        ] {
            let error = CliError::from(dbmd_core::linkmd::LinkError::Http {
                what: "sync push",
                status: 426,
                message: "profile upgrade required".to_string(),
                code: Some(hub_code.to_string()),
                details: None,
            });
            assert_eq!(error.exit, ExitCode::Policy);
            assert_eq!(error.code, cli_code);
            assert!(error.hint.is_some());
        }
    }

    #[test]
    fn link_not_found_has_a_stable_machine_code_without_scraping_prose() {
        let error = CliError::from(dbmd_core::linkmd::LinkError::Http {
            what: "resolve",
            status: 404,
            message: "record not found".to_string(),
            code: Some("NOT_FOUND".to_string()),
            details: None,
        });
        assert_eq!(error.exit, ExitCode::Runtime);
        assert_eq!(error.code, "NOT_FOUND");
        assert!(error.hint.is_none());
    }

    #[test]
    fn bulk_preview_refusal_preserves_the_exact_structured_receipt() {
        let preview = serde_json::json!({
            "v": 2,
            "code": "bulk_preview_created",
            "bulk_preview_id": "01arz3ndektsv4rrffq69g5fav",
            "bulk_preview_digest": "a".repeat(64),
            "impact": { "deletes": 26 }
        });
        let error = CliError::from(dbmd_core::linkmd::LinkError::BulkPreviewRequired {
            preview: preview.clone(),
        });
        assert_eq!(error.exit, ExitCode::Policy);
        assert_eq!(error.code, "BULK_PREVIEW_REQUIRED");
        assert_eq!(error.to_json()["error"]["details"], preview);
        assert!(error.hint.as_deref().unwrap().contains("--confirm-bulk"));
    }
}