app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

affected.rs (23425B)


      1 //! Conservative diagnostics. Selection and input equality never certify execution.
      2 use crate::runtime_ownership::{Owner, OwnershipMap};
      3 use crate::{
      4     Command, Inventory, bounded_no_follow_bytes, git_command, load_ownership, run,
      5     validate_product_root,
      6 };
      7 use serde_json::{Value, json};
      8 use sha2::{Digest, Sha256};
      9 use std::collections::BTreeSet;
     10 use std::path::{Path, PathBuf};
     11 use std::process::Command as ProcessCommand;
     12 
     13 fn git(root: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
     14     let output = git_command(root)
     15         .args(args)
     16         .output()
     17         .map_err(|_| "Git unavailable".to_owned())?;
     18     if !output.status.success() {
     19         return Err(format!("Git operation failed: {}", args[0]));
     20     }
     21     Ok(output.stdout)
     22 }
     23 
     24 fn revision(root: &Path, name: &str) -> Result<String, String> {
     25     if name.is_empty() || name.len() > 1024 || name.chars().any(char::is_control) {
     26         return Err("invalid revision argument".to_owned());
     27     }
     28     let expression = format!("{name}^{{commit}}");
     29     let bytes = git(
     30         root,
     31         &["rev-parse", "--verify", "--end-of-options", &expression],
     32     )?;
     33     let value = std::str::from_utf8(&bytes)
     34         .map_err(|_| "invalid revision output")?
     35         .trim();
     36     if value.len() != 40 || !value.bytes().all(|b| b.is_ascii_hexdigit()) {
     37         return Err("unsupported Git object identity".to_owned());
     38     }
     39     Ok(value.to_owned())
     40 }
     41 
     42 pub fn discover_root(start: &Path) -> Result<PathBuf, String> {
     43     let mut root = start
     44         .canonicalize()
     45         .map_err(|_| "unable to resolve current directory")?;
     46     loop {
     47         if root
     48             .join("config/product/harvestcircle-v1.properties")
     49             .is_file()
     50         {
     51             return validate_product_root(&root);
     52         }
     53         if !root.pop() {
     54             return Err("no HarvestCircle product root above current directory".to_owned());
     55         }
     56     }
     57 }
     58 
     59 /// Parse Git's NUL-delimited name-status stream without shell/path quoting.
     60 fn changed_paths(bytes: &[u8]) -> Result<(BTreeSet<String>, bool), String> {
     61     if !bytes.is_empty() && bytes.last() != Some(&0) {
     62         return Err("unterminated Git name-status stream".to_owned());
     63     }
     64     let mut tokens = bytes.split(|b| *b == 0).collect::<Vec<_>>();
     65     if tokens.last() == Some(&&b""[..]) {
     66         tokens.pop();
     67     }
     68     let mut position = 0;
     69     let mut paths = BTreeSet::new();
     70     let mut ambiguous = false;
     71     while position < tokens.len() {
     72         let status = std::str::from_utf8(tokens[position]).map_err(|_| "invalid Git status")?;
     73         position += 1;
     74         let count = match status.as_bytes().first() {
     75             Some(b'R' | b'C')
     76                 if status[1..].bytes().all(|b| b.is_ascii_digit()) && status.len() > 1 =>
     77             {
     78                 ambiguous = true;
     79                 2
     80             }
     81             Some(b'D') if status == "D" => {
     82                 ambiguous = true;
     83                 1
     84             }
     85             Some(b'A' | b'M' | b'T') if status.len() == 1 => 1,
     86             _ => return Err("ambiguous Git status".to_owned()),
     87         };
     88         for _ in 0..count {
     89             let raw = tokens.get(position).ok_or("missing Git path")?;
     90             let path = std::str::from_utf8(raw).map_err(|_| "Git path is not UTF-8")?;
     91             // Reuse the ownership parser's literal path validation, including escapes.
     92             // The report caller classifies every admitted path before narrow selection.
     93             if path.is_empty() {
     94                 return Err("empty Git path".to_owned());
     95             }
     96             paths.insert(path.to_owned());
     97             position += 1;
     98         }
     99     }
    100     Ok((paths, ambiguous))
    101 }
    102 
    103 fn selection(root: &Path, map: &OwnershipMap, base: Option<&str>, head: &str) -> Value {
    104     let mut reasons = Vec::new();
    105     let mut paths = BTreeSet::new();
    106     let mut selected = BTreeSet::new();
    107     let mut merge_base = None;
    108     let mut resolved_head = None;
    109     let mut checked_out_head = None;
    110     let result = (|| -> Result<(), String> {
    111         let top = git(root, &["rev-parse", "--show-toplevel"])?;
    112         let top = std::str::from_utf8(&top)
    113             .map_err(|_| "Git root is not UTF-8")?
    114             .trim_end_matches('\n');
    115         if Path::new(top).canonicalize().ok().as_deref() != Some(root) {
    116             return Err(
    117                 "capsule has no independent Git history; enclosing history is not its base"
    118                     .to_owned(),
    119             );
    120         }
    121         let current = revision(root, "HEAD")?;
    122         checked_out_head = Some(current.clone());
    123         if git(root, &["rev-parse", "--is-shallow-repository"])? != b"false\n" {
    124             return Err("shallow history cannot prove complete selection".to_owned());
    125         }
    126         let requested = revision(root, head)?;
    127         resolved_head = Some(requested.clone());
    128         if current != requested {
    129             return Err("requested head differs from checked-out source".to_owned());
    130         }
    131         let base = revision(root, base.ok_or("base not supplied")?)?;
    132         let common = git(root, &["merge-base", &base, &requested])?;
    133         let common = std::str::from_utf8(&common)
    134             .map_err(|_| "invalid merge base")?
    135             .trim()
    136             .to_owned();
    137         if common.len() != 40 {
    138             return Err("missing unique merge base".to_owned());
    139         }
    140         merge_base = Some(common.clone());
    141         for pair in [vec![common.as_str(), requested.as_str()], vec!["HEAD"]] {
    142             let mut args = vec![
    143                 "diff",
    144                 "--name-status",
    145                 "-z",
    146                 "--find-renames",
    147                 "--no-ext-diff",
    148                 "--no-textconv",
    149             ];
    150             args.extend(pair);
    151             args.push("--");
    152             let (changed, ambiguous) = changed_paths(&git(root, &args)?)?;
    153             paths.extend(changed);
    154             if ambiguous {
    155                 reasons.push("rename, copy or deletion widens all runtimes".to_owned());
    156             }
    157         }
    158         let untracked = git(
    159             root,
    160             &[
    161                 "ls-files",
    162                 "--others",
    163                 "--exclude-standard",
    164                 "-z",
    165                 "--",
    166                 ".",
    167             ],
    168         )?;
    169         for raw in untracked.split(|b| *b == 0).filter(|p| !p.is_empty()) {
    170             paths.insert(
    171                 std::str::from_utf8(raw)
    172                     .map_err(|_| "untracked path is not UTF-8")?
    173                     .to_owned(),
    174             );
    175         }
    176         for path in &paths {
    177             let classification = map.classify(path)?;
    178             if let Some(reason) = classification.reason {
    179                 reasons.push(reason);
    180             }
    181             for owner in classification.owners {
    182                 if owner == Owner::Governance {
    183                     selected.extend([Owner::Native, Owner::Web, Owner::Interop]);
    184                 } else {
    185                     selected.insert(owner);
    186                 }
    187             }
    188         }
    189         Ok(())
    190     })();
    191     if let Err(reason) = result {
    192         reasons.push(reason);
    193     }
    194     if !reasons.is_empty() {
    195         selected.extend([Owner::Native, Owner::Web, Owner::Interop]);
    196     }
    197     json!({"merge_base": merge_base, "resolved_head": resolved_head, "checked_out_head": checked_out_head, "changed_paths": paths,
    198         "reasons": reasons, "native": selected.contains(&Owner::Native), "web": selected.contains(&Owner::Web),
    199         "interop": selected.contains(&Owner::Interop), "repository_check": "REQUIRED_FRESH", "execution": "NOT_EXECUTED"})
    200 }
    201 
    202 fn digest(bytes: &[u8]) -> String {
    203     format!("{:x}", Sha256::digest(bytes))
    204 }
    205 
    206 fn tool(root: &Path, program: &str, arguments: &[&str]) -> Option<String> {
    207     let output = ProcessCommand::new(program)
    208         .args(arguments)
    209         .current_dir(root)
    210         .env("COREPACK_ENABLE_NETWORK", "0")
    211         .env_remove("JAVA_TOOL_OPTIONS")
    212         .env_remove("JDK_JAVA_OPTIONS")
    213         .env_remove("_JAVA_OPTIONS")
    214         .env_remove("JAVA_OPTS")
    215         .env_remove("GRADLE_OPTS")
    216         .env_remove("NODE_OPTIONS")
    217         .output()
    218         .ok()?;
    219     if !output.status.success() || output.stdout.len() + output.stderr.len() > 65536 {
    220         return None;
    221     }
    222     let mut bytes = output.stdout;
    223     bytes.extend(output.stderr);
    224     let text = std::str::from_utf8(&bytes).ok()?.trim().to_owned();
    225     (!text.is_empty()).then_some(text)
    226 }
    227 
    228 fn cached_gradle(root: &Path) -> Option<String> {
    229     let properties = bounded_no_follow_bytes(
    230         root,
    231         Path::new("gradle/wrapper/gradle-wrapper.properties"),
    232         65536,
    233     )
    234     .ok()?;
    235     let properties = std::str::from_utf8(&properties).ok()?;
    236     let version = properties
    237         .lines()
    238         .find(|line| line.starts_with("distributionUrl="))?
    239         .rsplit_once("/gradle-")?
    240         .1
    241         .strip_suffix("-bin.zip")?;
    242     if version.is_empty() || !version.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
    243         return None;
    244     }
    245     let cache = std::env::var_os("GRADLE_USER_HOME")
    246         .map(PathBuf::from)
    247         .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".gradle")))?;
    248     let directory = cache
    249         .join("wrapper/dists")
    250         .join(format!("gradle-{version}-bin"));
    251     let mut candidates = std::fs::read_dir(directory)
    252         .ok()?
    253         .filter_map(Result::ok)
    254         .map(|entry| entry.path().join(format!("gradle-{version}/bin/gradle")))
    255         .filter(|path| path.is_file())
    256         .collect::<Vec<_>>();
    257     if candidates.len() != 1 {
    258         return None;
    259     }
    260     let executable = candidates.pop()?;
    261     tool(root, executable.to_str()?, &["--offline", "--version"])
    262 }
    263 
    264 const COMPILER_ENV: &[&str] = &[
    265     "CC", "CXX", "AR", "LD", "RANLIB", "CFLAGS", "CXXFLAGS", "CPPFLAGS", "LDFLAGS",
    266 ];
    267 
    268 fn relevant_native_environment(name: &str) -> bool {
    269     [
    270         "CARGO_BUILD_",
    271         "CARGO_TARGET_",
    272         "CARGO_PROFILE_",
    273         "ORG_GRADLE_PROJECT_",
    274     ]
    275     .iter()
    276     .any(|prefix| name.starts_with(prefix))
    277         || COMPILER_ENV.iter().any(|base| {
    278             name == *base
    279                 || name.starts_with(&format!("{base}_"))
    280                 || name == format!("HOST_{base}")
    281                 || name == format!("TARGET_{base}")
    282         })
    283 }
    284 
    285 fn environment_identity(
    286     fixed: &[&str],
    287     dynamic_native: bool,
    288 ) -> Result<serde_json::Map<String, Value>, String> {
    289     let mut names = fixed
    290         .iter()
    291         .map(|name| (*name).to_owned())
    292         .collect::<BTreeSet<_>>();
    293     if dynamic_native {
    294         for (name, _) in std::env::vars_os() {
    295             if let Some(name) = name.to_str() {
    296                 if relevant_native_environment(name) {
    297                     names.insert(name.to_owned());
    298                 }
    299             } else if name.as_encoded_bytes().starts_with(b"CARGO_BUILD_")
    300                 || name.as_encoded_bytes().starts_with(b"CARGO_TARGET_")
    301                 || name.as_encoded_bytes().starts_with(b"CARGO_PROFILE_")
    302                 || name.as_encoded_bytes().starts_with(b"ORG_GRADLE_PROJECT_")
    303                 || COMPILER_ENV.iter().any(|base| {
    304                     name.as_encoded_bytes()
    305                         .starts_with(format!("{base}_").as_bytes())
    306                 })
    307             {
    308                 return Err("non-UTF-8 build environment name".to_owned());
    309             }
    310         }
    311     }
    312     if names.len() > 128 {
    313         return Err("too many relevant build environment inputs".to_owned());
    314     }
    315     let mut result = serde_json::Map::new();
    316     let mut total = 0;
    317     for name in names {
    318         if name.len() > 256 || name.chars().any(char::is_control) {
    319             return Err("invalid build environment name".to_owned());
    320         }
    321         let value = std::env::var_os(&name)
    322             .map(|value| {
    323                 value
    324                     .into_string()
    325                     .map_err(|_| "non-UTF-8 build environment value")
    326             })
    327             .transpose()?;
    328         if let Some(value) = &value {
    329             total += value.len();
    330             if value.len() > 65536 || total > 256 * 1024 {
    331                 return Err("oversized build environment input set".to_owned());
    332             }
    333         }
    334         result.insert(
    335             name,
    336             value.map_or(Value::Null, |value| json!(digest(value.as_bytes()))),
    337         );
    338     }
    339     Ok(result)
    340 }
    341 
    342 fn external_configuration_present(root: &Path, native: bool) -> bool {
    343     if !native {
    344         return false;
    345     }
    346     // Inspect existence only, never read external configuration/credentials. Such
    347     // configuration needs its own authority; default source diagnostics cannot
    348     // certify its contents from a path selector or the reported compiler version.
    349     let cargo_home = std::env::var_os("CARGO_HOME")
    350         .map(PathBuf::from)
    351         .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")));
    352     let gradle_home = std::env::var_os("GRADLE_USER_HOME")
    353         .map(PathBuf::from)
    354         .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".gradle")));
    355     let mut candidates = Vec::new();
    356     if let Some(home) = cargo_home {
    357         candidates.extend([home.join("config"), home.join("config.toml")]);
    358     }
    359     if let Some(home) = gradle_home {
    360         candidates.extend([
    361             home.join("gradle.properties"),
    362             home.join("init.gradle"),
    363             home.join("init.gradle.kts"),
    364             home.join("init.d"),
    365         ]);
    366     }
    367     for parent in root.ancestors().skip(1) {
    368         candidates.extend([
    369             parent.join(".cargo/config"),
    370             parent.join(".cargo/config.toml"),
    371         ]);
    372     }
    373     candidates
    374         .iter()
    375         .any(|path| std::fs::symlink_metadata(path).is_ok())
    376 }
    377 
    378 fn fingerprint(
    379     root: &Path,
    380     map: &OwnershipMap,
    381     inventory: &Inventory,
    382     owner: Owner,
    383 ) -> Result<Value, String> {
    384     let mut files = Vec::new();
    385     for path in &inventory.paths {
    386         let metadata = std::fs::symlink_metadata(root.join(path))
    387             .map_err(|_| format!("missing input: {path}"))?;
    388         if metadata.is_dir() {
    389             continue;
    390         } // Archive inventories include ordinary directories.
    391         let owners = map.classify(path)?.owners;
    392         // Interop/governance are shared proof inputs, even for a runtime-only command.
    393         if !owners.contains(&owner)
    394             && !owners.contains(&Owner::Governance)
    395             && !owners.contains(&Owner::Interop)
    396         {
    397             continue;
    398         }
    399         let bytes = bounded_no_follow_bytes(root, Path::new(path), 32 * 1024 * 1024)?;
    400         #[cfg(unix)]
    401         let mode = {
    402             use std::os::unix::fs::PermissionsExt;
    403             metadata.permissions().mode() & 0o777
    404         };
    405         #[cfg(not(unix))]
    406         let mode = if metadata.permissions().readonly() {
    407             0o444
    408         } else {
    409             0o666
    410         };
    411         files.push(json!({"path":path,"mode":mode,"bytes":bytes.len(),"sha256":digest(&bytes)}));
    412     }
    413     let environment_names: &[&str] = if owner == Owner::Native {
    414         &[
    415             "HARVESTCIRCLE_BUILD_MODE",
    416             "HARVESTCIRCLE_NATIVE_FEATURES",
    417             "HARVESTCIRCLE_NATIVE_PROFILE",
    418             "SOURCE_DATE_EPOCH",
    419             "HARVESTCIRCLE_BUILD_RADROOTS_REVISION",
    420             "HARVESTCIRCLE_BUILD_RUST_TOOLCHAIN",
    421             "HARVESTCIRCLE_BUILD_JAVA_TOOLCHAIN",
    422             "HARVESTCIRCLE_BUILD_KOTLIN_TOOLCHAIN",
    423             "RUSTFLAGS",
    424             "CARGO_ENCODED_RUSTFLAGS",
    425             "CARGO_ENCODED_RUSTDOCFLAGS",
    426             "RUSTDOCFLAGS",
    427             "RUSTC",
    428             "RUSTDOC",
    429             "RUSTFMT",
    430             "RUSTC_WRAPPER",
    431             "RUSTC_WORKSPACE_WRAPPER",
    432             "CARGO_HOME",
    433             "GRADLE_USER_HOME",
    434             "PATH",
    435             "CARGO_INCREMENTAL",
    436             "CC",
    437             "CXX",
    438             "AR",
    439             "LD",
    440             "RANLIB",
    441             "CFLAGS",
    442             "CXXFLAGS",
    443             "CPPFLAGS",
    444             "LDFLAGS",
    445             "JAVA_TOOL_OPTIONS",
    446             "JDK_JAVA_OPTIONS",
    447             "_JAVA_OPTIONS",
    448             "JAVA_OPTS",
    449             "GRADLE_OPTS",
    450             "JAVA_HOME",
    451             "RUSTUP_TOOLCHAIN",
    452         ]
    453     } else {
    454         &[
    455             "HARVESTCIRCLE_BUILD_MODE",
    456             "NODE_OPTIONS",
    457             "NODE_ENV",
    458             "CI",
    459             "COREPACK_ENABLE_NETWORK",
    460             "PATH",
    461             "PNPM_HOME",
    462         ]
    463     };
    464     let environment = environment_identity(environment_names, owner == Owner::Native);
    465     let environment_finding = environment.as_ref().err().cloned();
    466     let environment = environment.unwrap_or_default();
    467     let custom = owner == Owner::Native
    468         && (external_configuration_present(root, true)
    469             || environment
    470                 .keys()
    471                 .any(|name| name.starts_with("ORG_GRADLE_PROJECT_"))
    472             || [
    473                 "RUSTC",
    474                 "RUSTDOC",
    475                 "RUSTFMT",
    476                 "RUSTC_WRAPPER",
    477                 "RUSTC_WORKSPACE_WRAPPER",
    478                 "CARGO_BUILD_RUSTC",
    479                 "CARGO_BUILD_RUSTDOC",
    480                 "CARGO_BUILD_RUSTC_WRAPPER",
    481                 "CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER",
    482             ]
    483             .iter()
    484             .any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty())));
    485     let mut tools = serde_json::Map::new();
    486     if owner == Owner::Native {
    487         // rustup run fails if the pinned toolchain is absent; it never installs it.
    488         tools.insert(
    489             "cargo".to_owned(),
    490             json!(tool(
    491                 root,
    492                 "rustup",
    493                 &["run", "1.99.0", "cargo", "--version"]
    494             )),
    495         );
    496         tools.insert(
    497             "rustc".to_owned(),
    498             json!(tool(root, "rustup", &["run", "1.99.0", "rustc", "-vV"])),
    499         );
    500         tools.insert("java".to_owned(), json!(tool(root, "java", &["-version"])));
    501         // Only invoke an already cached distribution, never a downloading wrapper.
    502         tools.insert("gradle".to_owned(), json!(cached_gradle(root)));
    503     } else {
    504         tools.insert("node".to_owned(), json!(tool(root, "node", &["--version"])));
    505         tools.insert(
    506             "pnpm".to_owned(),
    507             json!(tool(&root.join("web"), "corepack", &["pnpm", "--version"])),
    508         );
    509     }
    510     let tools_available = tools.values().all(|v| !v.is_null());
    511     let available = !custom && environment_finding.is_none() && tools_available;
    512     let input = json!({"schema":1,"files":files,"environment_sha256":environment,"tools":tools,
    513         "platform":{"os":std::env::consts::OS,"arch":std::env::consts::ARCH},
    514         "native_features_policy":"default unless explicitly supplied by HARVESTCIRCLE_NATIVE_FEATURES; no execution claim",
    515         "native_profile_policy":"debug unless explicitly supplied by HARVESTCIRCLE_NATIVE_PROFILE; no execution claim"});
    516     Ok(
    517         json!({"source_identity":digest(&serde_json::to_vec(&input["files"]).unwrap()),
    518         "input_identity":if available {Some(digest(&serde_json::to_vec(&input).unwrap()))} else {None},
    519         "availability":if environment_finding.is_some() {"INPUT_UNAVAILABLE"} else if !tools_available {"TOOL_UNAVAILABLE"} else if custom {"UNSUPPORTED_CUSTOM_COMMAND_INPUTS"} else {"DECLARED_INPUTS_AVAILABLE"}, "environment_finding":environment_finding, "custom_command_inputs":custom, "inputs":input,
    520         "scope":"repository default source-check commands; arbitrary feature/target/profile/config arguments, Make GRADLE overrides and injected init/project settings require separate evidence",
    521         "execution":"NOT_EXECUTED", "reuse":"NOT_ACCEPTED_BY_THIS_REPORT"}),
    522     )
    523 }
    524 
    525 pub fn report(start: &Path, base: Option<&str>, head: &str) -> Result<(String, bool), String> {
    526     let root = discover_root(start)?;
    527     let map = load_ownership(&root)?;
    528     // Always execute current global source policy; path selection never bypasses it.
    529     let safety = run(&root, Command::RepoAudit);
    530     let mut selected = selection(&root, &map, base, head);
    531     let source = selected["checked_out_head"].clone();
    532     let dirty = if source.is_null() {
    533         None
    534     } else {
    535         git(
    536             &root,
    537             &["status", "--porcelain=v1", "-z", "--untracked-files=all"],
    538         )
    539         .ok()
    540         .map(|bytes| !bytes.is_empty())
    541     };
    542     let mut provenance_environment = serde_json::Map::new();
    543     for name in [
    544         "HARVESTCIRCLE_BUILD_SOURCE_COMMIT",
    545         "HARVESTCIRCLE_BUILD_SOURCE_DIRTY",
    546     ] {
    547         let value = std::env::var_os(name)
    548             .map(|value| {
    549                 value
    550                     .into_string()
    551                     .map_err(|_| "non-UTF-8 source provenance input")
    552             })
    553             .transpose()?;
    554         if value.as_ref().is_some_and(|value| value.len() > 65536) {
    555             return Err("oversized source provenance input".to_owned());
    556         }
    557         provenance_environment.insert(
    558             name.to_owned(),
    559             value.map_or(Value::Null, |value| json!(digest(value.as_bytes()))),
    560         );
    561     }
    562     let unavailable = |reason: String| {
    563         json!({"availability":"INPUT_UNAVAILABLE","finding":reason,
    564         "input_identity":null,"execution":"NOT_EXECUTED","reuse":"NOT_ACCEPTED_BY_THIS_REPORT"})
    565     };
    566     let (native, web) = match Inventory::load(&root) {
    567         Ok(inventory) => (
    568             fingerprint(&root, &map, &inventory, Owner::Native).unwrap_or_else(&unavailable),
    569             fingerprint(&root, &map, &inventory, Owner::Web).unwrap_or_else(&unavailable),
    570         ),
    571         Err(reason) => (unavailable(reason.clone()), unavailable(reason)),
    572     };
    573     if native["input_identity"].is_null() || web["input_identity"].is_null() {
    574         for lane in ["native", "web", "interop"] {
    575             selected[lane] = json!(true);
    576         }
    577         selected["reasons"].as_array_mut().unwrap().push(json!(
    578             "complete runtime fingerprint unavailable; checks remain required"
    579         ));
    580     }
    581     let report = json!({"schema":"harvestcircle.affected.v1","selection":selected,
    582         "source_provenance":{"head":source,"dirty":dirty,"producer_environment_sha256":provenance_environment,"artifact_evidence":"NOT_PRODUCED"},
    583         "repository_safety":{"status":if safety.is_ok(){"PASS_FRESH"}else{"FAIL"},"findings":safety.err().unwrap_or_default()},
    584         "native":native,
    585         "web":web});
    586     let green = report["repository_safety"]["status"] == "PASS_FRESH";
    587     Ok((serde_json::to_string_pretty(&report).unwrap() + "\n", green))
    588 }
    589 
    590 #[cfg(test)]
    591 mod tests {
    592     use super::*;
    593     #[test]
    594     fn nul_status_preserves_both_literal_rename_paths() {
    595         let (paths, all) =
    596             changed_paths(b"R100\0web/old name.ts\0core/new name.rs\0M\0web/src/[id]/file.ts\0")
    597                 .unwrap();
    598         assert!(all);
    599         assert_eq!(paths.len(), 3);
    600         assert!(paths.contains("web/old name.ts"));
    601         assert!(paths.contains("core/new name.rs"));
    602     }
    603     #[test]
    604     fn deletion_and_malformed_streams_cannot_be_narrowed() {
    605         assert!(changed_paths(b"D\0web/gone.ts\0").unwrap().1);
    606         for bytes in [
    607             &b"M\0unterminated"[..],
    608             &b"R100\0one\0"[..],
    609             &b"U\0file\0"[..],
    610             &b"M\0\xff\0"[..],
    611         ] {
    612             assert!(changed_paths(bytes).is_err());
    613         }
    614         assert_eq!(changed_paths(b"").unwrap(), (BTreeSet::new(), false));
    615     }
    616 }