agent-first-data 0.40.0

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
//! Optional naming and representation suggestions for CLI authors.

use crate::lint_input::{Visitor, parse_json_number_text, walk};
use crate::suffix::{REGISTERED_SUFFIXES, has_registered_suffix, has_suffix_ci};
use serde::Serialize;
use serde_json::Value;

#[derive(Debug, Serialize)]
pub(super) struct Advisory {
    rule_id: &'static str,
    pointer: String,
    message: String,
}

pub(super) fn advisories(
    value: &Value,
    pointer: &str,
    schema: bool,
    untyped: bool,
) -> Vec<Advisory> {
    let mut visitor = Suggestions {
        untyped,
        findings: Vec::new(),
    };
    walk(&mut visitor, value, None, pointer, schema);
    visitor.findings
}

struct Suggestions {
    untyped: bool,
    findings: Vec<Advisory>,
}

impl Visitor for Suggestions {
    fn field(&mut self, key: &str, value: &Value, pointer: &str) {
        lint_missing_suffix(key, value, pointer, self.untyped, &mut self.findings);
    }

    fn property(&mut self, key: &str, schema: &Value, pointer: &str) {
        if has_registered_suffix(key) {
            return;
        }
        let (Some(category), Some(types)) = (suffix_category(key), schema.get("type")) else {
            return;
        };
        let compatible = |kind: &str| match category {
            "duration" | "currency" | "size" | "percentage" => matches!(kind, "integer" | "number"),
            "timestamp" => matches!(kind, "integer" | "number" | "string"),
            _ => kind == "string",
        };
        if types.as_str().is_some_and(compatible)
            || types
                .as_array()
                .is_some_and(|items| items.iter().filter_map(Value::as_str).any(compatible))
        {
            push_missing_suffix(key, category, pointer, &mut self.findings);
        }
    }

    fn string(&mut self, key: Option<&str>, text: &str, pointer: &str) {
        if !self.untyped {
            lint_formatted_quantity(key, text, pointer, &mut self.findings);
        }
    }
}

fn lint_formatted_quantity(
    key: Option<&str>,
    text: &str,
    pointer: &str,
    findings: &mut Vec<Advisory>,
) {
    if let Some(key) = key {
        let last_word = key.rsplit(['_', '-']).next().unwrap_or(key);
        const TEXT_FIELDS: &[&str] = &[
            "Version", "Build", "Id", "Code", "Zip", "Postcode", "Phone", "Sku", "Label", "Name",
            "Title", "Sqlstate",
        ];
        let is_text = TEXT_FIELDS
            .iter()
            .any(|word| last_word.eq_ignore_ascii_case(word) || last_word.ends_with(word))
            || last_word.ends_with("ID")
            || last_word.ends_with("SKU");
        let has_text_suffix = [
            "_epoch_ns",
            "_sats",
            "_msats",
            "_rfc3339",
            "_rfc3339_date",
            "_rfc3339_time",
            "_bcp47",
            "_utc_offset",
            "_url",
            "_secret",
        ]
        .iter()
        .any(|suffix| has_suffix_ci(key, suffix));
        if is_text || has_text_suffix {
            return;
        }
    }
    let message = if matches!(text, "—" | "-")
        || text.eq_ignore_ascii_case("n/a")
        || text.eq_ignore_ascii_case("none")
    {
        "If this represents an absent value, send null.".to_owned()
    } else if let Some(advice) = formatted_quantity_advice(text, key) {
        format!("If this is a quantity, {advice}.")
    } else {
        return;
    };
    findings.push(Advisory {
        rule_id: "formatted_quantity_string",
        pointer: pointer.to_owned(),
        message,
    });
}

fn ascii_digits(text: &str) -> bool {
    !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
}

const GROUP_SEPARATORS: [char; 5] = [',', '.', ' ', '\u{a0}', '\u{202f}'];

fn grouped_digits(text: &str) -> bool {
    GROUP_SEPARATORS.into_iter().any(|separator| {
        let Some((first, rest)) = text.split_once(separator) else {
            return false;
        };
        first.len() <= 3
            && ascii_digits(first)
            && rest
                .split(separator)
                .all(|group| group.len() == 3 && ascii_digits(group))
    })
}

fn decimal_quantity(text: &str) -> bool {
    ascii_digits(text)
        || grouped_digits(text)
        || text
            .rsplit_once(['.', ','])
            .is_some_and(|(whole, fractional)| {
                (ascii_digits(whole) || grouped_digits(whole)) && ascii_digits(fractional)
            })
}

fn formatted_quantity_advice(text: &str, key: Option<&str>) -> Option<String> {
    let recommend = |action: &str, suffix: &str| {
        Some(if key.is_some_and(|key| has_suffix_ci(key, suffix)) {
            action.to_owned()
        } else {
            format!("{action} with the {suffix} suffix")
        })
    };
    let text = text.strip_prefix(['-', '+', '−']).unwrap_or(text);
    if ascii_digits(text) || grouped_digits(text) {
        return Some("send a JSON number".to_owned());
    }
    if let Some((hours, rest)) = text.split_once(':')
        && let Some((minutes, seconds)) = rest.split_once(':')
        && hours.len() >= 2
        && ascii_digits(hours)
        && [minutes, seconds]
            .iter()
            .all(|part| part.len() == 2 && ascii_digits(part) && *part < "60")
    {
        return recommend("send a numeric duration", "_s");
    }
    let duration_units = ['d', 'h', 'm', 's'];
    let mut units = duration_units.iter();
    if text.contains(' ')
        && text.split(' ').all(|part| {
            let number = part.trim_end_matches(duration_units);
            ascii_digits(number) && units.any(|unit| part.strip_suffix(*unit) == Some(number))
        })
    {
        return recommend("send a numeric duration", "_s");
    }
    if let Some((symbol, number)) = text.split_at_checked(text.chars().next()?.len_utf8())
        && decimal_quantity(number.trim_start_matches([' ', '\u{a0}', '\u{202f}']))
    {
        match symbol {
            "$" => {
                return Some(
                    "send integer minor units with the currency-specific suffix".to_owned(),
                );
            }
            "€" => return recommend("send integer cents", "_eur_cents"),
            "Â¥" => return Some("send integer yen with the _jpy suffix for JPY".to_owned()),
            "£" => return recommend("send integer pence", "_gbp_cents"),
            _ => {}
        }
    }
    let split = text.find(|c: char| !c.is_ascii_digit() && !GROUP_SEPARATORS.contains(&c))?;
    // The unit follows the number; grouping whitespace can also precede it.
    let (number, unit) = text.split_at(split);
    if !decimal_quantity(number.trim_end_matches([' ', '\u{a0}', '\u{202f}'])) {
        return None;
    }
    match unit {
        "B" | "byte" | "bytes" | "kB" | "KB" | "MB" | "GB" | "TB" | "PB" | "EB" | "KiB" | "MiB"
        | "GiB" | "TiB" | "PiB" | "EiB" => recommend("send integer bytes", "_bytes"),
        "ns" | "nanosecond" | "nanoseconds" => recommend("send a number", "_ns"),
        "us" | "µs" | "μs" | "microsecond" | "microseconds" => recommend("send a number", "_us"),
        "ms" | "millisecond" | "milliseconds" => recommend("send a number", "_ms"),
        "s" | "sec" | "second" | "seconds" => recommend("send a number", "_s"),
        "m" | "min" | "minute" | "minutes" => recommend("send a number", "_minutes"),
        "h" | "hr" | "hour" | "hours" => recommend("send a number", "_hours"),
        "d" | "day" | "days" => recommend("send a number", "_days"),
        "%" | "percent" => recommend("send a number", "_percent"),
        "°C" | "°F" | "K" => {
            Some("send a number and identify the temperature scale in the field name".to_owned())
        }
        "sat" | "sats" => recommend("send an integer", "_sats"),
        "msat" | "msats" => recommend("send an integer", "_msats"),
        "JPY" => recommend("send integer yen", "_jpy"),
        "USD" => recommend("send integer cents", "_usd_cents"),
        "EUR" => recommend("send integer cents", "_eur_cents"),
        _ => None,
    }
}

const UNSUFFIXED_STEMS: &[(&str, &str)] = &[
    ("timeout", "duration"),
    ("elapsed", "duration"),
    ("duration", "duration"),
    ("ttl", "duration"),
    ("interval", "duration"),
    ("latency", "duration"),
    ("delay", "duration"),
    ("uptime", "duration"),
    ("price", "currency"),
    ("amount", "currency"),
    ("cost", "currency"),
    ("fee", "currency"),
    ("balance", "currency"),
    ("subtotal", "currency"),
    ("revenue", "currency"),
    ("created", "timestamp"),
    ("updated", "timestamp"),
    ("modified", "timestamp"),
    ("expires", "timestamp"),
    ("issued", "timestamp"),
    ("timestamp", "timestamp"),
    ("apikey", "sensitive"),
    ("api_key", "sensitive"),
    ("token", "sensitive"),
    ("password", "sensitive"),
    ("passwd", "sensitive"),
    ("secret", "sensitive"),
    ("credential", "sensitive"),
];

fn lint_missing_suffix(
    key: &str,
    value: &Value,
    pointer: &str,
    untyped_text_scalars: bool,
    findings: &mut Vec<Advisory>,
) {
    if value.is_null() || has_registered_suffix(key) {
        return;
    }
    let Some(category) = suffix_category(key) else {
        return;
    };
    let is_plausible_scalar = |val: &Value| {
        let is_numeric = val.is_number()
            || (untyped_text_scalars && val.as_str().and_then(parse_json_number_text).is_some());
        match category {
            "duration" | "currency" | "size" | "percentage" => is_numeric,
            "timestamp" => is_numeric || val.is_string(),
            _ => val.is_string(),
        }
    };
    let plausible = if let Some(items) = value.as_array() {
        let mut has_non_null = false;
        let mut all_valid = true;
        for item in items {
            if item.is_null() {
                continue;
            }
            has_non_null = true;
            if !is_plausible_scalar(item) {
                all_valid = false;
                break;
            }
        }
        has_non_null && all_valid
    } else {
        is_plausible_scalar(value)
    };
    if !plausible {
        return;
    }
    push_missing_suffix(key, category, pointer, findings);
}

fn suffix_category(key: &str) -> Option<&'static str> {
    let lower = key.to_ascii_lowercase();
    if lower.ends_with("_at") {
        Some("timestamp")
    } else {
        UNSUFFIXED_STEMS
            .iter()
            .find(|(stem, _)| {
                lower == *stem
                    || lower.ends_with(&format!("_{stem}"))
                    || lower == format!("{stem}s")
                    || lower.ends_with(&format!("_{stem}s"))
            })
            .map(|(_, category)| *category)
    }
}

fn push_missing_suffix(key: &str, category: &str, pointer: &str, findings: &mut Vec<Advisory>) {
    let suffixes = REGISTERED_SUFFIXES
        .iter()
        .find(|(name, _)| *name == category)
        .map(|(_, suffixes)| suffixes.join(", "))
        .unwrap_or_default();
    let message = if category == "sensitive" {
        format!("If `{key}` holds a credential, mark it with _secret for redaction.")
    } else {
        format!(
            "If `{key}` represents a {category}, specify its unit or format with one of {suffixes}."
        )
    };
    findings.push(Advisory {
        rule_id: "missing_suffix",
        pointer: pointer.to_owned(),
        message,
    });
}

#[cfg(test)]
mod tests {
    use super::advisories;
    use serde_json::json;

    #[test]
    fn missing_suffix_reads_intent_from_the_name() {
        for (label, value) in [
            ("bare dimension name", json!({"timeout": 5000})),
            ("suffixed dimension name", json!({"request_timeout": 1})),
            ("_at timestamp", json!({"expires_at": 1})),
        ] {
            let findings = advisories(&value, "", false, false);
            assert!(
                findings.iter().any(|f| f.rule_id == "missing_suffix"),
                "{label}: expected a missing_suffix advisory, got {findings:?}"
            );
        }

        for (label, value) in [
            ("already labelled duration", json!({"timeout_ms": 5000})),
            ("already labelled currency", json!({"price_gbp_cents": 1})),
            ("already labelled secret", json!({"api_key_secret": "sk"})),
            // A dimension name over a container is a config block, not a bare
            // number. This is the guard that has no other test.
            (
                "dimension name over a container",
                json!({"timeout": {"connect": 1}}),
            ),
            ("credentials block", json!({"credentials": {"user": "x"}})),
            ("unrelated name", json!({"name": "demo"})),
        ] {
            let findings = advisories(&value, "", false, false);
            assert!(
                findings.is_empty(),
                "{label}: expected no findings, got {findings:?}"
            );
        }
    }
}