use std::fmt;
use std::str::FromStr;
use thiserror::Error;
pub const PROVENANCE_KEY: &str = "provenance";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Provenance {
FrameworkOwned,
TmAgentManagerBuilt,
UserAuthored,
}
impl Provenance {
pub const ALL: [Provenance; 3] = [
Provenance::FrameworkOwned,
Provenance::TmAgentManagerBuilt,
Provenance::UserAuthored,
];
pub fn as_str(self) -> &'static str {
match self {
Provenance::FrameworkOwned => "framework-owned",
Provenance::TmAgentManagerBuilt => "tm-agent-manager-built",
Provenance::UserAuthored => "user-authored",
}
}
pub fn is_framework_owned(self) -> bool {
matches!(self, Provenance::FrameworkOwned)
}
}
impl fmt::Display for Provenance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error(
"unknown `provenance:` value `{value}` — expected one of \
framework-owned, tm-agent-manager-built, user-authored"
)]
pub struct UnknownProvenance {
pub value: String,
}
impl FromStr for Provenance {
type Err = UnknownProvenance;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let trimmed = s.trim();
Provenance::ALL
.into_iter()
.find(|p| p.as_str() == trimmed)
.ok_or_else(|| UnknownProvenance {
value: trimmed.to_string(),
})
}
}
pub fn declared_or_default(declared: Option<Provenance>) -> Provenance {
declared.unwrap_or(Provenance::UserAuthored)
}
pub fn without_provenance_line(doc: &str) -> String {
let mut out = String::with_capacity(doc.len());
let mut in_frontmatter = false;
let mut dropped = false;
for (idx, line) in doc.split_inclusive('\n').enumerate() {
let trimmed = line.trim_end_matches(['\n', '\r']);
if idx == 0 && trimmed == "---" {
in_frontmatter = true;
out.push_str(line);
continue;
}
if in_frontmatter && trimmed == "---" {
in_frontmatter = false;
out.push_str(line);
continue;
}
let is_provenance = in_frontmatter
&& !dropped
&& trimmed
.split_once(':')
.is_some_and(|(key, _)| key.trim() == PROVENANCE_KEY);
if is_provenance {
dropped = true;
continue;
}
out.push_str(line);
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reconciled {
pub framework_owned: bool,
pub disagreement: Option<String>,
}
pub fn reconcile_with_ledger(
file_name: &str,
ledger_framework_owned: bool,
declared: Option<Provenance>,
) -> Reconciled {
let Some(declared) = declared else {
return Reconciled {
framework_owned: ledger_framework_owned,
disagreement: None,
};
};
if declared.is_framework_owned() == ledger_framework_owned {
return Reconciled {
framework_owned: ledger_framework_owned,
disagreement: None,
};
}
let ledger_spelling = if ledger_framework_owned {
Provenance::FrameworkOwned.as_str()
} else {
"not framework-owned"
};
let message = format!(
"'{file_name}' declares `provenance: {}` but the deployed-agent manifest records it as \
{ledger_spelling}; the manifest wins (#4698)",
declared.as_str()
);
tracing::warn!(
file = %file_name,
declared = %declared.as_str(),
ledger_framework_owned,
"agent `provenance:` disagrees with the deployed-agent manifest — the manifest wins"
);
Reconciled {
framework_owned: ledger_framework_owned,
disagreement: Some(message),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provenance_round_trips_every_value() {
for p in Provenance::ALL {
assert_eq!(p.as_str().parse::<Provenance>(), Ok(p), "{p} round-trips");
}
assert_eq!(Provenance::FrameworkOwned.as_str(), "framework-owned");
assert_eq!(
Provenance::TmAgentManagerBuilt.as_str(),
"tm-agent-manager-built"
);
assert_eq!(Provenance::UserAuthored.as_str(), "user-authored");
}
#[test]
fn provenance_parse_trims_surrounding_whitespace() {
assert_eq!(
" framework-owned ".parse::<Provenance>(),
Ok(Provenance::FrameworkOwned)
);
}
#[test]
fn provenance_rejects_an_unknown_value() {
let err = "framework_owned".parse::<Provenance>().unwrap_err();
assert_eq!(err.value, "framework_owned");
assert!(
err.to_string().contains("framework-owned"),
"the error lists the accepted spellings: {err}"
);
assert!("".parse::<Provenance>().is_err(), "empty is not a value");
assert!(
"Framework-Owned".parse::<Provenance>().is_err(),
"the spelling is case-sensitive"
);
}
#[test]
fn absent_provenance_is_user_authored() {
assert_eq!(declared_or_default(None), Provenance::UserAuthored);
assert!(!declared_or_default(None).is_framework_owned());
assert_eq!(
declared_or_default(Some(Provenance::FrameworkOwned)),
Provenance::FrameworkOwned
);
}
#[test]
fn only_framework_owned_is_framework_owned() {
assert!(Provenance::FrameworkOwned.is_framework_owned());
assert!(!Provenance::TmAgentManagerBuilt.is_framework_owned());
assert!(!Provenance::UserAuthored.is_framework_owned());
}
#[test]
fn without_provenance_line_drops_only_that_line() {
let doc = "---\nname: qa\nprovenance: framework-owned\nrole: qa\n---\n\nBody.\n";
assert_eq!(
without_provenance_line(doc),
"---\nname: qa\nrole: qa\n---\n\nBody.\n"
);
}
#[test]
fn without_provenance_line_is_a_no_op_when_absent() {
let doc = "---\nname: qa\nrole: qa\n---\n\nBody.\n";
assert_eq!(without_provenance_line(doc), doc);
assert_eq!(without_provenance_line("just prose\n"), "just prose\n");
}
#[test]
fn without_provenance_line_ignores_a_body_line() {
let doc = "---\nname: qa\n---\n\nSet provenance: framework-owned in frontmatter.\n";
assert_eq!(without_provenance_line(doc), doc);
}
#[test]
fn reconcile_agreeing_declaration_is_silent() {
let r = reconcile_with_ledger("qa.md", true, Some(Provenance::FrameworkOwned));
assert!(r.framework_owned);
assert_eq!(r.disagreement, None);
let r = reconcile_with_ledger("mine.md", false, Some(Provenance::UserAuthored));
assert!(!r.framework_owned);
assert_eq!(r.disagreement, None);
let r = reconcile_with_ledger("built.md", false, Some(Provenance::TmAgentManagerBuilt));
assert_eq!(r.disagreement, None);
}
#[test]
fn reconcile_disagreement_lets_the_ledger_win_and_names_the_file() {
let r = reconcile_with_ledger("rust-engineer.md", true, Some(Provenance::UserAuthored));
assert!(r.framework_owned, "the manifest wins");
let msg = r.disagreement.expect("a disagreement is reported");
assert!(msg.contains("rust-engineer.md"), "names the file: {msg}");
assert!(
msg.contains("user-authored"),
"names the declaration: {msg}"
);
let r = reconcile_with_ledger("mine.md", false, Some(Provenance::FrameworkOwned));
assert!(!r.framework_owned, "the manifest wins in both directions");
assert!(r.disagreement.is_some_and(|m| m.contains("mine.md")));
}
#[test]
fn reconcile_without_a_declaration_is_silent() {
for owned in [true, false] {
let r = reconcile_with_ledger("legacy.md", owned, None);
assert_eq!(r.framework_owned, owned);
assert_eq!(r.disagreement, None);
}
}
}