agent-first-data 0.39.1

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use crate::output::{OutputFormat, OutputTo};
use crate::protocol::{
    BuildError, Event, LogLevel, ProtocolViolation, json_error, json_log, json_progress,
    json_result, validate_protocol_event,
};
use crate::redaction::OutputOptions;
use serde_json::Value;

// ═══════════════════════════════════════════
// Public API: CLI Helpers
// ═══════════════════════════════════════════

/// Parsed and normalized log filters (trimmed, lowercased, deduplicated).
///
/// Semantics (a stable contract):
/// - An **empty** set emits no logs (filtering is opt-in, not opt-out).
/// - The single wildcard word `"all"` emits every log. (`"*"` is not special —
///   there is one wildcard spelling, not two.)
/// - Otherwise a log is emitted iff its lowercased event name **starts with**
///   any filter string (prefix match).
///
/// Consequence to know: a mistyped filter simply matches nothing, so it
/// silently emits no output — that is the documented behavior, not a bug.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LogFilters(Vec<String>);

impl LogFilters {
    /// Create a new LogFilters from filter strings. Entries are trimmed,
    /// lowercased, and de-duplicated; empty entries are dropped.
    pub fn new<I, S>(filters: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut out: Vec<String> = Vec::new();
        for entry in filters {
            let s = entry.as_ref().trim().to_ascii_lowercase();
            if !s.is_empty() && !out.contains(&s) {
                out.push(s);
            }
        }
        Self(out)
    }

    /// Check if an event should be logged based on these filters.
    ///
    /// Returns `false` if empty (no logs). Returns `true` if the set contains
    /// the wildcard word `"all"`. Otherwise returns `true` iff the lowercased
    /// event name starts with any filter (prefix match).
    pub fn enabled(&self, event: &str) -> bool {
        if self.0.is_empty() {
            return false;
        }
        let event_lower = event.to_ascii_lowercase();
        if self.0.contains(&"all".to_string()) {
            return true;
        }
        self.0.iter().any(|filter| event_lower.starts_with(filter))
    }

    /// Check if this filter set is empty (no filters configured).
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Access the underlying filter strings as a slice.
    pub fn as_slice(&self) -> &[String] {
        &self.0
    }
}

/// Parse `--output` flag value into [`OutputFormat`].
///
/// Returns `Err` with a value-safe message suitable for passing to
/// [`crate::build_cli_error`] on unknown values.
///
/// ```
/// use agent_first_data::{cli_parse_output, OutputFormat};
/// assert!(matches!(cli_parse_output("json"), Ok(OutputFormat::Json)));
/// assert!(cli_parse_output("xml").is_err());
/// ```
pub fn cli_parse_output(s: &str) -> Result<OutputFormat, String> {
    s.parse()
        .map_err(|_| "invalid --output format: expected json, yaml, or plain".to_string())
}

/// Normalize `--log` flag entries: trim, lowercase, deduplicate, remove empty.
///
/// Accepts pre-split entries produced by a caller's comma-list parser.
///
/// ```
/// use agent_first_data::{cli_parse_log_filters, LogFilters};
/// let f = cli_parse_log_filters(&["Query", " error ", "query"]);
/// assert_eq!(f, LogFilters::new(["query", "error"]));
/// ```
pub fn cli_parse_log_filters<S: AsRef<str>>(entries: &[S]) -> LogFilters {
    LogFilters::new(entries.iter().map(AsRef::as_ref))
}

/// Error returned by [`CliEmitter`].
#[derive(Debug)]
pub enum CliEmitterError {
    /// A protocol-validation failure.
    Validation(ProtocolViolation),
    /// An event builder rejected its inputs (empty code/message, reserved field).
    Build(BuildError),
    /// An emitter lifecycle rule was violated (terminal ordering).
    Lifecycle(String),
    /// Writing the event to the underlying writer failed.
    Write(std::io::Error),
}

impl std::fmt::Display for CliEmitterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Validation(v) => write!(f, "{v}"),
            Self::Build(e) => write!(f, "{e}"),
            Self::Lifecycle(err) => f.write_str(err),
            Self::Write(err) => write!(f, "failed to write CLI event: {err}"),
        }
    }
}

impl CliEmitterError {
    /// Return the underlying writer error, when event emission failed during I/O.
    pub const fn io_error(&self) -> Option<&std::io::Error> {
        match self {
            Self::Write(err) => Some(err),
            Self::Validation(_) | Self::Build(_) | Self::Lifecycle(_) => None,
        }
    }

    /// Return the underlying writer error kind, when available.
    pub fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
        self.io_error().map(std::io::Error::kind)
    }
}

impl std::error::Error for CliEmitterError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.io_error()
            .map(|err| err as &(dyn std::error::Error + 'static))
    }
}

impl From<std::io::Error> for CliEmitterError {
    fn from(err: std::io::Error) -> Self {
        Self::Write(err)
    }
}

impl From<BuildError> for CliEmitterError {
    fn from(err: BuildError) -> Self {
        Self::Build(err)
    }
}

/// Stateful emitter for structured CLI executions.
///
/// An emitter is one of two consumption modes ([`OutputTo`] selects between
/// them, see the spec's CLI Event Framing):
///
/// - [`CliEmitter::finite`] — finite one-shot: `result` (and raw bytes) go to
///   the result writer, `error`/`progress`/`log` to the diagnostic writer. The
///   result stream then carries only successful payloads, so a shell capture
///   or pipe never mistakes a failure for data.
/// - [`CliEmitter::stream`] — event stream: every event, including `error`,
///   goes to the one writer, preserving interleaved ordering for a consumer
///   that reads in order and branches on `kind`.
///
/// A command is an event stream when it produces more than one caller-needed
/// output over time — a chunked payload, or an address the caller must act on
/// before the command can report its outcome. Such a command defaults to
/// [`OutputTo::Stdout`] and rejects an explicit `split`, because splitting it
/// would strand the caller's data on the diagnostic stream.
///
/// [`CliEmitter::from_output_to`] and [`CliEmitter::from_plan`] build either
/// mode wired to the process streams. Options are chained:
/// [`with_options`](Self::with_options),
/// [`with_strict_protocol`](Self::with_strict_protocol).
///
/// Emitting after a terminal event or emitting a second terminal event is an
/// error. A failed write is returned *and* remembered, so whoever owns the
/// process exit can settle it once with [`exit_code`](Self::exit_code): a
/// closed reader is success, any other failure is exit 4 with
/// `output_write_failed` on the diagnostic stream.
pub struct CliEmitter<W: std::io::Write> {
    writer: W,
    diagnostic: Option<Box<dyn std::io::Write>>,
    write_failure_diagnostic: Option<Box<dyn std::io::Write>>,
    diagnostic_failed: bool,
    format: OutputFormat,
    output_options: OutputOptions,
    strict_protocol: bool,
    terminal_emitted: bool,
    write_failure: Option<std::io::ErrorKind>,
    failure_reported: bool,
}

impl<W: std::io::Write> CliEmitter<W> {
    /// Event-stream mode: every event, including `error`, goes to `writer`.
    pub fn stream(writer: W, format: OutputFormat) -> Self {
        Self {
            writer,
            diagnostic: None,
            write_failure_diagnostic: None,
            diagnostic_failed: false,
            format,
            output_options: OutputOptions::default(),
            strict_protocol: false,
            terminal_emitted: false,
            write_failure: None,
            failure_reported: false,
        }
    }

    /// Finite one-shot mode: `result` and raw bytes go to `result_writer`,
    /// `error`/`progress`/`log` go to `diagnostic`.
    pub fn finite(
        result_writer: W,
        diagnostic: impl std::io::Write + 'static,
        format: OutputFormat,
    ) -> Self {
        let mut emitter = Self::stream(result_writer, format);
        emitter.diagnostic = Some(Box::new(diagnostic));
        emitter
    }

    /// Render with these redaction and formatting options.
    #[must_use]
    pub fn with_options(mut self, output_options: OutputOptions) -> Self {
        self.output_options = output_options;
        self
    }

    /// Change the options of an emitter someone else built — the one a CLI
    /// entry hands to its handler, for a command that decides its redaction
    /// policy from its own arguments.
    pub fn set_options(&mut self, output_options: OutputOptions) {
        self.output_options = output_options;
    }

    /// Require the AFDATA recommended strict profile for every emitted event.
    #[must_use]
    pub fn with_strict_protocol(mut self) -> Self {
        self.strict_protocol = true;
        self
    }

    /// The format events are rendered in.
    pub const fn format(&self) -> OutputFormat {
        self.format
    }

    /// Emit a typed Event (unified entry for all event kinds).
    ///
    /// Accepts only SDK-constructed Event; for dynamic JSON, use emit_validated_value.
    pub fn emit(&mut self, event: Event) -> Result<(), CliEmitterError> {
        let value = event.into_value();
        self.write_event(value)
    }

    /// Emit and validate dynamic JSON, then apply redaction/formatting/write.
    ///
    /// Runs strict validation first, ensuring the dynamic JSON is safe.
    pub fn emit_validated_value(&mut self, value: Value) -> Result<(), CliEmitterError> {
        validate_protocol_event(&value, true).map_err(CliEmitterError::Validation)?;
        self.write_event(value)
    }

    /// Convenience: build and emit a result event.
    pub fn emit_result(&mut self, payload: Value) -> Result<(), CliEmitterError> {
        self.emit(json_result(payload).build())
    }

    /// Convenience: build and emit an error event.
    pub fn emit_error(&mut self, code: &str, message: &str) -> Result<(), CliEmitterError> {
        self.emit(json_error(code, message).build()?)
    }

    /// Convenience: build and emit a progress event.
    pub fn emit_progress(&mut self, message: &str) -> Result<(), CliEmitterError> {
        self.emit(json_progress(serde_json::json!({ "message": message })).build())
    }

    /// Convenience: build and emit a log event.
    pub fn emit_log(&mut self, level: LogLevel, message: &str) -> Result<(), CliEmitterError> {
        self.emit(
            json_log(serde_json::json!({
            "level": level.as_str(),
            "message": message,
            }))
            .build(),
        )
    }

    /// Write bytes that are not an event to the result writer, unchanged.
    ///
    /// Not everything a CLI emits is an event. `--docs` renders a Markdown
    /// reference, `--output plain` help a human catalog, `shell bash` a
    /// sourceable script, and a raw-output command its own bytes: their
    /// consumer is `>` or `source`, so a protocol envelope would be wrong. They
    /// still go through the emitter, so the routing and the exit policy for a
    /// failed write are the same ones every event gets.
    pub fn write_raw(&mut self, bytes: &[u8]) -> Result<(), CliEmitterError> {
        if self.terminal_emitted {
            return Err(CliEmitterError::Lifecycle(
                "cannot write raw output after terminal output".to_string(),
            ));
        }
        self.ensure_writable()?;
        let written = self
            .writer
            .write_all(bytes)
            .and_then(|()| self.writer.flush());
        self.record(written).map_err(CliEmitterError::Write)
    }

    /// Write the invocation's final raw bytes and settle its exit code.
    pub fn finish_raw(&mut self, bytes: &[u8]) -> u8 {
        let result = self.write_raw(bytes);
        self.terminal_emitted = true;
        let intended = u8::from(matches!(result, Err(CliEmitterError::Lifecycle(_))));
        self.exit_code(intended)
    }

    /// Emit `event` as the terminal event and resolve the process exit code.
    ///
    /// A refused event — a protocol violation or a second terminal event — is
    /// the command's own failure and returns `1`. Otherwise this is
    /// [`exit_code`](Self::exit_code) with `success_code`.
    pub fn finish(&mut self, event: Event, success_code: u8) -> u8 {
        match self.emit(event) {
            Ok(()) | Err(CliEmitterError::Write(_)) => self.exit_code(success_code),
            Err(
                CliEmitterError::Validation(_)
                | CliEmitterError::Build(_)
                | CliEmitterError::Lifecycle(_),
            ) => self.exit_code(1),
        }
    }

    /// Convenience over [`CliEmitter::finish`]: emit a `result` payload and
    /// return `0` on success.
    ///
    /// For an error, build it with [`json_error`] (`.hint(…)`, `.retryable(…)`,
    /// `.field(…)` as needed) and pass the event to [`CliEmitter::finish`] with
    /// the desired exit code.
    pub fn finish_result(&mut self, payload: Value) -> u8 {
        self.finish(json_result(payload).build(), 0)
    }

    /// The exit code a command that meant to exit `intended` must use, given
    /// everything this emitter has written.
    ///
    /// No failed write: `intended`. A closed reader (`tool | head`): `0`,
    /// silently — reading part of the output is not a failure. Any other failed
    /// write: `4`, after reporting `output_write_failed` once as an `error`
    /// event — on the diagnostic sink in finite mode, on the process's stderr
    /// in event-stream mode, whose only writer may be the one that failed. That
    /// report is best effort; a stderr that cannot be written leaves only the
    /// code. A library never calls `process::exit` itself — return this from
    /// `main` (`std::process::ExitCode::from(code)`).
    pub fn exit_code(&mut self, intended: u8) -> u8 {
        match self.write_failure {
            None => intended,
            Some(std::io::ErrorKind::BrokenPipe) => 0,
            Some(_) => {
                if !self.failure_reported {
                    self.failure_reported = true;
                    self.report_output_write_failed();
                }
                4
            }
        }
    }

    /// The kind of the first failed write, if any.
    pub const fn write_failure(&self) -> Option<std::io::ErrorKind> {
        self.write_failure
    }

    fn report_output_write_failed(&mut self) {
        if self.diagnostic_failed {
            return;
        }
        if let Some(diagnostic) = self
            .diagnostic
            .as_mut()
            .or(self.write_failure_diagnostic.as_mut())
        {
            let event = crate::cli_afdata::cli_output_write_failed_event();
            let rendered =
                crate::formatting::render(event.as_value(), self.format, &OutputOptions::default());
            let _unwritable = write_event_line(diagnostic.as_mut(), &rendered);
        }
    }

    fn ensure_writable(&self) -> Result<(), CliEmitterError> {
        match self.write_failure {
            Some(kind) => Err(CliEmitterError::Write(kind.into())),
            None => Ok(()),
        }
    }

    /// Access the underlying writer.
    pub fn into_inner(self) -> W {
        self.writer
    }

    /// Remember the first failed write, and hand the result back.
    fn record(&mut self, result: std::io::Result<()>) -> std::io::Result<()> {
        if let Err(error) = &result
            && self.write_failure.is_none()
        {
            self.write_failure = Some(error.kind());
        }
        result
    }

    fn write_event(&mut self, event: Value) -> Result<(), CliEmitterError> {
        validate_protocol_event(&event, self.strict_protocol)
            .map_err(CliEmitterError::Validation)?;
        let kind = event.get("kind").and_then(Value::as_str).ok_or_else(|| {
            CliEmitterError::Validation(ProtocolViolation {
                rule: "kind_invalid",
                pointer: "/kind".to_string(),
                message: "event.kind is required".to_string(),
            })
        })?;
        match kind {
            "log" | "progress" => {
                if self.terminal_emitted {
                    return Err(CliEmitterError::Lifecycle(
                        "cannot emit non-terminal event after terminal event".to_string(),
                    ));
                }
            }
            "result" | "error" => {
                if self.terminal_emitted {
                    return Err(CliEmitterError::Lifecycle(
                        "cannot emit duplicate terminal event".to_string(),
                    ));
                }
            }
            _ => {
                return Err(CliEmitterError::Validation(ProtocolViolation {
                    rule: "kind_unsupported",
                    pointer: "/kind".to_string(),
                    message: format!("unsupported event kind {kind:?}"),
                }));
            }
        }
        self.ensure_writable()?;
        let terminal = matches!(kind, "result" | "error");
        let rendered = crate::formatting::render(&event, self.format, &self.output_options);
        // Finite mode (a diagnostic sink is present) splits by kind: `result`
        // stays on the primary writer (stdout), while `error`/`progress`/`log`
        // are diagnostics routed to the diagnostic writer (stderr). Event-stream
        // mode (no diagnostic sink) keeps every event on the single writer.
        let written = match &mut self.diagnostic {
            Some(diagnostic) if kind != "result" => {
                let written = write_event_line(diagnostic.as_mut(), &rendered);
                self.diagnostic_failed = written.is_err();
                written
            }
            _ => write_event_line(&mut self.writer, &rendered),
        };
        // A terminal event that failed to write still ends the command: the
        // caller's outcome is now an output failure, not a second attempt.
        if terminal {
            self.terminal_emitted = true;
        }
        self.record(written)?;
        Ok(())
    }
}

/// Write one rendered event line (payload plus trailing newline) and flush.
fn write_event_line(writer: &mut dyn std::io::Write, rendered: &str) -> std::io::Result<()> {
    writer.write_all(rendered.as_bytes())?;
    writer.write_all(b"\n")?;
    writer.flush()
}

// The emitter's own sinks are the spec's sanctioned exception to the "no
// ad-hoc stderr" rule (Channel policy): these wired constructors name the
// process streams directly, and `clippy.toml`'s `disallowed-methods` keeps
// stray writes elsewhere from bypassing this routing.
#[allow(clippy::disallowed_methods)]
impl CliEmitter<Box<dyn std::io::Write>> {
    /// The emitter a resolved plan asks for, strict, wired to the process
    /// streams. A raw-output plan gets finite mode with JSON diagnostics: its
    /// bytes go to stdout through [`write_raw`](Self::write_raw), its failures
    /// to stderr.
    pub fn from_plan(plan: &crate::cli_spec::OutputPlan) -> Self {
        Self::from_output_to(
            plan.output_to().unwrap_or(OutputTo::Split),
            plan.output_format().unwrap_or(OutputFormat::Json),
        )
        .with_strict_protocol()
    }

    /// Build either mode from a parsed [`OutputTo`] selector, wired to the
    /// process streams: `Split` is finite mode (`result` → stdout, everything
    /// else → stderr); `Stdout`/`Stderr` are event-stream mode onto that stream.
    pub fn from_output_to(selector: OutputTo, format: OutputFormat) -> Self {
        match selector {
            OutputTo::Split => Self::finite(Box::new(std::io::stdout()), std::io::stderr(), format),
            OutputTo::Stdout => {
                let mut emitter = Self::stream(Box::new(std::io::stdout()), format);
                emitter.write_failure_diagnostic = Some(Box::new(std::io::stderr()));
                emitter
            }
            OutputTo::Stderr => Self::stream(Box::new(std::io::stderr()), format),
        }
    }
}

/// Build a standard CLI version event: a `kind:"result"` event whose payload is
/// `{ "code": "version", "name": <name>, "version": <version> }`, plus
/// `"display_name"`/`"build"` when given. `name` is the short/bin identity
/// (e.g. `"afdata"`); `display_name` is an optional human-facing product name
/// (e.g. `"Agent-First Data"`); `build` is an opaque caller-supplied identifier (a git
/// commit SHA, for example) — its meaning is entirely up to the caller. Both
/// are `None` when unavailable, and simply absent from the payload.
pub fn build_cli_version(
    name: &str,
    display_name: Option<&str>,
    version: &str,
    build: Option<&str>,
) -> Event {
    let mut payload = serde_json::json!({
        "code": "version",
        "name": name,
        "version": version,
    });
    if let Some(display_name) = display_name {
        payload["display_name"] = Value::String(display_name.to_string());
    }
    if let Some(build) = build {
        payload["build"] = Value::String(build.to_string());
    }
    json_result(payload).build()
}

/// Render a CLI version response as a protocol-v1 event in `format`.
pub fn cli_render_version(
    name: &str,
    display_name: Option<&str>,
    version: &str,
    build: Option<&str>,
    format: OutputFormat,
) -> String {
    let mut rendered = crate::formatting::render(
        build_cli_version(name, display_name, version, build).as_value(),
        format,
        &OutputOptions::default(),
    );
    while rendered.ends_with('\n') {
        rendered.pop();
    }
    rendered.push('\n');
    rendered
}