lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

hygiene.rs (93943B)


      1 use serde::Deserialize;
      2 use std::collections::HashSet;
      3 use std::fs;
      4 use std::io::Read;
      5 use std::path::{Path, PathBuf};
      6 use std::process::{Command, Stdio};
      7 
      8 const PROTOTYPE_CONTRACT_CONFIG_PATH: &str = "contracts/hygiene/prototype-contracts.v1.toml";
      9 const PROTOTYPE_CONTRACT_SCHEMA: &str = "radroots.prototype-contract-source-guard.v1";
     10 const PROTOTYPE_MAX_CONFIG_BYTES: u64 = 1024 * 1024;
     11 const PROTOTYPE_MAX_CONFIG_STRING_BYTES: usize = 1024;
     12 const PROTOTYPE_MAX_CONFIG_PATHS: usize = 256;
     13 const PROTOTYPE_MAX_CONFIG_EXTENSIONS: usize = 128;
     14 const PROTOTYPE_MAX_CONFIG_PATTERNS: usize = 1024;
     15 const PROTOTYPE_MAX_CONFIG_ALLOWLIST: usize = 4096;
     16 const PROTOTYPE_MAX_REASON_BYTES: usize = 512;
     17 const PROTOTYPE_MAX_CONFIGURED_SCAN_ENTRIES: usize = 100_000;
     18 const PROTOTYPE_MAX_CONFIGURED_INVENTORY_BYTES: usize = 64 * 1024 * 1024;
     19 const PROTOTYPE_MAX_CONFIGURED_FILE_BYTES: u64 = 64 * 1024 * 1024;
     20 const PROTOTYPE_MAX_CONFIGURED_MATCHES: usize = 100_000;
     21 const PROTOTYPE_MAX_CONFIGURED_REPORT_LINES: usize = 10_000;
     22 const PROTOTYPE_MAX_GIT_STDERR_BYTES: usize = 8 * 1024;
     23 
     24 #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
     25 #[serde(rename_all = "snake_case")]
     26 enum PrototypeGuardMode {
     27     ReportOnly,
     28     Strict,
     29 }
     30 
     31 impl PrototypeGuardMode {
     32     const fn as_str(self) -> &'static str {
     33         match self {
     34             Self::ReportOnly => "report_only",
     35             Self::Strict => "strict",
     36         }
     37     }
     38 }
     39 
     40 #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
     41 #[serde(rename_all = "snake_case")]
     42 enum PrototypeMatchKind {
     43     Substring,
     44     WordPrefix,
     45 }
     46 
     47 #[derive(Debug, Deserialize)]
     48 #[serde(deny_unknown_fields)]
     49 struct PrototypeGuardConfig {
     50     schema: String,
     51     mode: PrototypeGuardMode,
     52     scan: PrototypeScanConfig,
     53     limits: PrototypeGuardLimits,
     54     pattern: Vec<PrototypePattern>,
     55     #[serde(default)]
     56     allow: Vec<PrototypeAllow>,
     57 }
     58 
     59 #[derive(Debug, Deserialize)]
     60 #[serde(deny_unknown_fields)]
     61 struct PrototypeScanConfig {
     62     roots: Vec<String>,
     63     path_roots: Vec<String>,
     64     path_excludes: Vec<String>,
     65     extensions: Vec<String>,
     66     extensionless_names: Vec<String>,
     67 }
     68 
     69 #[derive(Debug, Deserialize)]
     70 #[serde(deny_unknown_fields)]
     71 struct PrototypeGuardLimits {
     72     max_scan_entries: usize,
     73     max_inventory_bytes: usize,
     74     max_file_bytes: u64,
     75     max_matches: usize,
     76     max_reported_findings: usize,
     77     max_reported_allowlisted: usize,
     78 }
     79 
     80 #[derive(Debug, Deserialize)]
     81 #[serde(deny_unknown_fields)]
     82 struct PrototypePattern {
     83     id: String,
     84     needle: String,
     85     match_kind: PrototypeMatchKind,
     86     description: String,
     87     #[serde(default)]
     88     match_path: bool,
     89     #[serde(default)]
     90     path_prefixes: Vec<String>,
     91 }
     92 
     93 #[derive(Debug, Deserialize)]
     94 #[serde(deny_unknown_fields)]
     95 struct PrototypeAllow {
     96     pattern_id: String,
     97     path: String,
     98     line_contains: String,
     99     reason: String,
    100 }
    101 
    102 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
    103 enum PrototypeFindingOrigin {
    104     Path,
    105     Content,
    106 }
    107 
    108 #[derive(Clone, Debug, Eq, PartialEq)]
    109 struct PrototypeFinding {
    110     pattern_id: String,
    111     path: String,
    112     origin: PrototypeFindingOrigin,
    113     line: Option<usize>,
    114     excerpt: String,
    115 }
    116 
    117 #[derive(Clone, Debug, Eq, PartialEq)]
    118 struct PrototypeAllowedMatch {
    119     finding: PrototypeFinding,
    120     reason: String,
    121 }
    122 
    123 #[derive(Debug, Default, Eq, PartialEq)]
    124 struct PrototypeGuardReport {
    125     findings: Vec<PrototypeFinding>,
    126     allowed: Vec<PrototypeAllowedMatch>,
    127 }
    128 
    129 const BINDING_DEPENDENCIES: &[&str] = &[
    130     "serde-wasm-bindgen",
    131     "ts-rs",
    132     "typeshare",
    133     "uniffi",
    134     "uniffi-build",
    135     "uniffi_build",
    136     "wasm-bindgen",
    137     "wasm-bindgen-futures",
    138     "wasm-bindgen-test",
    139 ];
    140 
    141 const RETIRED_PROTOCOL_EVENT_SURFACE_PATTERNS: &[&str] = &[
    142     "KIND_LISTING_DRAFT",
    143     "KIND_CLASSIFIED_LISTING_DRAFT",
    144     "KIND_OPERATIONAL_LISTING_DRAFT",
    145     "KIND_ORDER_REVISION",
    146     "KIND_TRADE_QUESTION",
    147     "KIND_TRADE_ANSWER",
    148     "KIND_TRADE_DISCOUNT_REQUEST",
    149     "KIND_TRADE_DISCOUNT_OFFER",
    150     "KIND_TRADE_DISCOUNT_ACCEPT",
    151     "KIND_TRADE_FULFILLMENT_UPDATE",
    152     "KIND_TRADE_RECEIPT",
    153     "KIND_TRADE_LISTING_VALIDATION_REQUEST",
    154     "KIND_TRADE_LISTING_VALIDATION_RESULT",
    155     "KIND_TRADE_TRANSITION_PROOF_REQUEST",
    156     "KIND_TRADE_TRANSITION_PROOF_RESULT",
    157     "RADROOTS_SP1_TRADE_KIND_LISTING_DRAFT",
    158     "RADROOTS_SP1_TRADE_KIND_CLASSIFIED_LISTING_DRAFT",
    159     "RADROOTS_SP1_TRADE_KIND_OPERATIONAL_LISTING_DRAFT",
    160     "RadrootsListingDraft",
    161     "RadrootsClassifiedListingDraft",
    162     "RadrootsOperationalListingDraft",
    163     "RadrootsCanonicalListingDraft",
    164     "RadrootsListingDraftError",
    165     "RadrootsClassifiedListingDraftError",
    166     "RadrootsOperationalListingDraftError",
    167     "OrderRevision",
    168     "RadrootsOrderRevisionId",
    169     "TradeValidationListingRequest",
    170     "TradeValidationListingResult",
    171     "ListingValidationRequest",
    172     "ListingValidationResult",
    173     "TransitionProof",
    174     "TradeQuestion",
    175     "TradeAnswer",
    176     "TradeFulfillmentUpdated",
    177     "TradeReceipt",
    178     "canonicalize_listing_draft",
    179     "listing_draft",
    180     "order_revision",
    181     "pending_revision_event_id",
    182     "trade_answer",
    183     "trade_discount_accept",
    184     "trade_discount_offer",
    185     "trade_discount_request",
    186     "trade_fulfillment_update",
    187     "trade_listing_validation_request",
    188     "trade_listing_validation_result",
    189     "trade_order_revision_decision",
    190     "trade_order_revision_proposal",
    191     "trade_question",
    192     "trade_receipt",
    193     "trade_transition_proof_request",
    194     "trade_transition_proof_result",
    195 ];
    196 
    197 const RETIRED_PROTOCOL_EVENT_SURFACE_ALLOWED_PATHS: &[&str] = &[
    198     "crates/event/src/dto.rs",
    199     "crates/protocol_contract_v1/src/lib.rs",
    200     "tools/xtask/src/hygiene.rs",
    201 ];
    202 
    203 const RETIRED_LISTING_ALIAS_IDENTIFIER_TOKENS: &[&str] = &[
    204     "KIND_LISTING",
    205     "LISTING_EVENT_KINDS",
    206     "is_listing_kind",
    207     "is_listing_event_kind",
    208     "RADROOTS_SP1_TRADE_KIND_LISTING",
    209     "ListingTagOptions",
    210     "ListingDecodeError",
    211     "ListingParseError",
    212     "ListingProjection",
    213     "ListingInventoryAccounting",
    214     "ListingAddress",
    215     "ListingSnapshot",
    216     "RADROOTS_LISTING_PRODUCT_TAG_KEYS",
    217     "RadrootsCanonicalListingEdit",
    218     "RadrootsPublicListingAddress",
    219     "RadrootsPublicListingAddressError",
    220     "RadrootsTradeListing",
    221     "RadrootsTradeListingSubtotal",
    222     "RadrootsTradeListingTotal",
    223     "RadrootsTradeValidationListingError",
    224     "farm_listings_list_set",
    225     "farm_listings_list_set_from_listings",
    226     "listing_from_event",
    227     "listing_from_event_parts",
    228     "listing_from_nostr_event",
    229     "parse_listing_address",
    230     "parse_listing_address_str",
    231     "parse_listing_event",
    232     "parse_public_listing_address",
    233     "search_listing_projection",
    234     "to_json_wire_parts_with_kind",
    235     "validate_listing_event",
    236     "listing_tags",
    237     "listing_tags_with_options",
    238     "listing_tags_full",
    239     "listing_build_tags",
    240     "decode_listing_from_event_parts",
    241     "listing_markdown_content",
    242     "build_listing_mutation_draft",
    243     "canonicalize_listing_edit",
    244     "reduce_listing_inventory_accounting",
    245 ];
    246 
    247 const RETIRED_LISTING_ALIAS_IDENTIFIER_PREFIXES: &[&str] = &["RadrootsListing"];
    248 const RETIRED_LISTING_CONTRACT_ID: &str = "radroots.listing.published.v1";
    249 
    250 pub fn run(args: &[String], root: &Path) -> Result<(), String> {
    251     match args.first().map(String::as_str) {
    252         Some("forbidden-identifiers") => validate_forbidden_identifiers(root),
    253         Some("prototype-contracts") => run_prototype_contract_guard(&args[1..], root),
    254         _ => Err("unknown hygiene subcommand".to_string()),
    255     }
    256 }
    257 
    258 fn run_prototype_contract_guard(args: &[String], root: &Path) -> Result<(), String> {
    259     let (config_path, mode_override) = parse_prototype_guard_args(args)?;
    260     let config = load_prototype_guard_config(root, &config_path)?;
    261     let mode = mode_override.unwrap_or(config.mode);
    262     let report = scan_prototype_contracts(root, &config)?;
    263     print_prototype_guard_report(mode, &report, &config.limits);
    264     if mode == PrototypeGuardMode::Strict && !report.findings.is_empty() {
    265         return Err(format!(
    266             "prototype contract source guard found {} non-allowlisted match(es)",
    267             report.findings.len()
    268         ));
    269     }
    270     Ok(())
    271 }
    272 
    273 fn parse_prototype_guard_args(
    274     args: &[String],
    275 ) -> Result<(PathBuf, Option<PrototypeGuardMode>), String> {
    276     let mut config_path = PathBuf::from(PROTOTYPE_CONTRACT_CONFIG_PATH);
    277     let mut mode = None;
    278     let mut index = 0;
    279     while index < args.len() {
    280         match args[index].as_str() {
    281             "--config" => {
    282                 let Some(value) = args.get(index + 1) else {
    283                     return Err("prototype-contracts --config requires a path".to_string());
    284                 };
    285                 validate_repo_relative_path(value, "prototype guard config path")?;
    286                 config_path = PathBuf::from(value);
    287                 index += 2;
    288             }
    289             "--strict" => {
    290                 set_prototype_mode(&mut mode, PrototypeGuardMode::Strict)?;
    291                 index += 1;
    292             }
    293             "--report-only" => {
    294                 set_prototype_mode(&mut mode, PrototypeGuardMode::ReportOnly)?;
    295                 index += 1;
    296             }
    297             value => return Err(format!("unknown prototype-contracts argument: {value}")),
    298         }
    299     }
    300     Ok((config_path, mode))
    301 }
    302 
    303 fn set_prototype_mode(
    304     current: &mut Option<PrototypeGuardMode>,
    305     requested: PrototypeGuardMode,
    306 ) -> Result<(), String> {
    307     if current.replace(requested).is_some() {
    308         return Err("prototype-contracts accepts only one mode override".to_string());
    309     }
    310     Ok(())
    311 }
    312 
    313 fn load_prototype_guard_config(
    314     root: &Path,
    315     relative_path: &Path,
    316 ) -> Result<PrototypeGuardConfig, String> {
    317     validate_repo_relative_path(
    318         &relative_path.to_string_lossy(),
    319         "prototype guard config path",
    320     )?;
    321     let path = root.join(relative_path);
    322     reject_symlinked_path_components(root, relative_path, "prototype guard config path")?;
    323     let metadata = fs::symlink_metadata(&path)
    324         .map_err(|error| format!("inspect prototype guard config {}: {error}", path.display()))?;
    325     if metadata.file_type().is_symlink() || !metadata.is_file() {
    326         return Err(format!(
    327             "prototype guard config must be a regular non-symlink file: {}",
    328             path.display()
    329         ));
    330     }
    331     let display = path.display().to_string();
    332     let source = read_bounded_prototype_input(&path, &display, PROTOTYPE_MAX_CONFIG_BYTES)?;
    333     let config: PrototypeGuardConfig = toml::from_str(&source)
    334         .map_err(|error| format!("parse prototype guard config {}: {error}", path.display()))?;
    335     validate_prototype_guard_config(&config)?;
    336     Ok(config)
    337 }
    338 
    339 fn validate_prototype_guard_config(config: &PrototypeGuardConfig) -> Result<(), String> {
    340     if config.schema != PROTOTYPE_CONTRACT_SCHEMA {
    341         return Err(format!(
    342             "prototype guard schema must be {PROTOTYPE_CONTRACT_SCHEMA}"
    343         ));
    344     }
    345     if config.scan.roots.is_empty() {
    346         return Err("prototype guard scan roots must not be empty".to_string());
    347     }
    348     if config.scan.path_roots.is_empty() {
    349         return Err("prototype guard path scan roots must not be empty".to_string());
    350     }
    351     if config.scan.extensions.is_empty() {
    352         return Err("prototype guard extensions must not be empty".to_string());
    353     }
    354     if config.limits.max_scan_entries == 0
    355         || config.limits.max_inventory_bytes == 0
    356         || config.limits.max_file_bytes == 0
    357         || config.limits.max_matches == 0
    358         || config.limits.max_reported_findings == 0
    359         || config.limits.max_reported_allowlisted == 0
    360         || config.limits.max_reported_findings > config.limits.max_matches
    361         || config.limits.max_reported_allowlisted > config.limits.max_matches
    362         || config.limits.max_scan_entries > PROTOTYPE_MAX_CONFIGURED_SCAN_ENTRIES
    363         || config.limits.max_inventory_bytes > PROTOTYPE_MAX_CONFIGURED_INVENTORY_BYTES
    364         || config.limits.max_file_bytes > PROTOTYPE_MAX_CONFIGURED_FILE_BYTES
    365         || config.limits.max_matches > PROTOTYPE_MAX_CONFIGURED_MATCHES
    366         || config.limits.max_reported_findings > PROTOTYPE_MAX_CONFIGURED_REPORT_LINES
    367         || config.limits.max_reported_allowlisted > PROTOTYPE_MAX_CONFIGURED_REPORT_LINES
    368     {
    369         return Err(
    370             "prototype guard limits must be positive, report limits must not exceed max_matches, and every value must remain within the compiled resource ceiling"
    371                 .to_string(),
    372         );
    373     }
    374     if config.pattern.is_empty() {
    375         return Err("prototype guard patterns must not be empty".to_string());
    376     }
    377     if config.scan.roots.len() > PROTOTYPE_MAX_CONFIG_PATHS
    378         || config.scan.path_roots.len() > PROTOTYPE_MAX_CONFIG_PATHS
    379         || config.scan.path_excludes.len() > PROTOTYPE_MAX_CONFIG_PATHS
    380         || config.scan.extensions.len() > PROTOTYPE_MAX_CONFIG_EXTENSIONS
    381         || config.scan.extensionless_names.len() > PROTOTYPE_MAX_CONFIG_EXTENSIONS
    382         || config.pattern.len() > PROTOTYPE_MAX_CONFIG_PATTERNS
    383         || config.allow.len() > PROTOTYPE_MAX_CONFIG_ALLOWLIST
    384     {
    385         return Err("prototype guard configuration collection exceeds compiled limit".to_string());
    386     }
    387 
    388     let mut roots = HashSet::new();
    389     for root in &config.scan.roots {
    390         validate_repo_relative_path(root, "prototype guard scan root")?;
    391         if !roots.insert(root.as_str()) {
    392             return Err(format!("duplicate prototype guard scan root: {root}"));
    393         }
    394     }
    395 
    396     let mut path_roots = HashSet::new();
    397     for root in &config.scan.path_roots {
    398         validate_repo_relative_or_root_path(root, "prototype guard path scan root")?;
    399         if !path_roots.insert(root.as_str()) {
    400             return Err(format!("duplicate prototype guard path scan root: {root}"));
    401         }
    402     }
    403 
    404     let mut path_excludes = HashSet::new();
    405     for excluded in &config.scan.path_excludes {
    406         validate_repo_relative_path(excluded, "prototype guard path exclusion")?;
    407         if !config
    408             .scan
    409             .path_roots
    410             .iter()
    411             .any(|root| root == "." || repository_path_is_within(excluded, root))
    412         {
    413             return Err(format!(
    414                 "prototype guard path exclusion is outside path scan roots: {excluded}"
    415             ));
    416         }
    417         if !path_excludes.insert(excluded.as_str()) {
    418             return Err(format!(
    419                 "duplicate prototype guard path exclusion: {excluded}"
    420             ));
    421         }
    422     }
    423 
    424     let mut extensions = HashSet::new();
    425     for extension in &config.scan.extensions {
    426         if extension.is_empty()
    427             || extension.len() > 32
    428             || extension.starts_with('.')
    429             || !extension
    430                 .chars()
    431                 .all(|character| character.is_ascii_alphanumeric())
    432         {
    433             return Err(format!(
    434                 "invalid prototype guard extension (omit the dot): {extension:?}"
    435             ));
    436         }
    437         if !extensions.insert(extension.as_str()) {
    438             return Err(format!("duplicate prototype guard extension: {extension}"));
    439         }
    440     }
    441 
    442     let mut extensionless_names = HashSet::new();
    443     for name in &config.scan.extensionless_names {
    444         if name.is_empty()
    445             || name.len() > 128
    446             || !name
    447                 .chars()
    448                 .all(|character| character.is_ascii_alphanumeric() || "._-".contains(character))
    449         {
    450             return Err(format!(
    451                 "invalid prototype guard extensionless file name: {name:?}"
    452             ));
    453         }
    454         if !extensionless_names.insert(name.as_str()) {
    455             return Err(format!(
    456                 "duplicate prototype guard extensionless file name: {name}"
    457             ));
    458         }
    459     }
    460 
    461     let mut pattern_ids = HashSet::new();
    462     for pattern in &config.pattern {
    463         if pattern.id.is_empty()
    464             || pattern.id.len() > 64
    465             || !pattern.id.chars().all(|character| {
    466                 character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
    467             })
    468         {
    469             return Err(format!(
    470                 "invalid prototype guard pattern id: {:?}",
    471                 pattern.id
    472             ));
    473         }
    474         if !pattern_ids.insert(pattern.id.as_str()) {
    475             return Err(format!(
    476                 "duplicate prototype guard pattern id: {}",
    477                 pattern.id
    478             ));
    479         }
    480         if pattern.needle.is_empty()
    481             || pattern.needle.len() > PROTOTYPE_MAX_CONFIG_STRING_BYTES
    482             || pattern.needle.chars().any(char::is_control)
    483         {
    484             return Err(format!(
    485                 "prototype guard pattern {} has an invalid needle",
    486                 pattern.id
    487             ));
    488         }
    489         if pattern.match_kind == PrototypeMatchKind::WordPrefix && !pattern.needle.is_ascii() {
    490             return Err(format!(
    491                 "prototype guard word-prefix pattern {} must use an ASCII needle",
    492                 pattern.id
    493             ));
    494         }
    495         if pattern.description.trim().is_empty()
    496             || pattern.description.len() > PROTOTYPE_MAX_CONFIG_STRING_BYTES
    497             || pattern.description.chars().any(char::is_control)
    498         {
    499             return Err(format!(
    500                 "prototype guard pattern {} requires a description",
    501                 pattern.id
    502             ));
    503         }
    504         let mut prefixes = HashSet::new();
    505         for prefix in &pattern.path_prefixes {
    506             validate_repo_relative_path(prefix, "prototype guard pattern path prefix")?;
    507             if !config
    508                 .scan
    509                 .roots
    510                 .iter()
    511                 .any(|root| repository_path_is_within(prefix, root))
    512             {
    513                 return Err(format!(
    514                     "prototype guard pattern {} path prefix is outside scan roots: {prefix}",
    515                     pattern.id
    516                 ));
    517             }
    518             if !prefixes.insert(prefix.as_str()) {
    519                 return Err(format!(
    520                     "duplicate path prefix for prototype guard pattern {}: {prefix}",
    521                     pattern.id
    522                 ));
    523             }
    524         }
    525     }
    526 
    527     let mut allow_keys = HashSet::new();
    528     for allowed in &config.allow {
    529         if !pattern_ids.contains(allowed.pattern_id.as_str()) {
    530             return Err(format!(
    531                 "prototype guard allowlist references unknown pattern: {:?}",
    532                 allowed.pattern_id
    533             ));
    534         }
    535         validate_repo_relative_path(&allowed.path, "prototype guard allowlist path")?;
    536         if !config
    537             .scan
    538             .roots
    539             .iter()
    540             .any(|root| repository_path_is_within(&allowed.path, root))
    541         {
    542             return Err(format!(
    543                 "prototype guard allowlist path is outside scan roots: {}",
    544                 allowed.path
    545             ));
    546         }
    547         let pattern = config
    548             .pattern
    549             .iter()
    550             .find(|pattern| pattern.id == allowed.pattern_id)
    551             .expect("validated pattern id must resolve");
    552         if !pattern.path_prefixes.is_empty()
    553             && !pattern
    554                 .path_prefixes
    555                 .iter()
    556                 .any(|prefix| repository_path_is_within(&allowed.path, prefix))
    557         {
    558             return Err(format!(
    559                 "prototype guard allowlist path {} is outside pattern {} path prefixes",
    560                 allowed.path, allowed.pattern_id
    561             ));
    562         }
    563         if allowed.line_contains.is_empty()
    564             || allowed.line_contains.len() > PROTOTYPE_MAX_CONFIG_STRING_BYTES
    565             || allowed.line_contains.chars().any(char::is_control)
    566         {
    567             return Err(format!(
    568                 "prototype guard allowlist for {} requires one line fragment",
    569                 allowed.pattern_id
    570             ));
    571         }
    572         if allowed.reason.trim().is_empty()
    573             || allowed.reason.len() > PROTOTYPE_MAX_REASON_BYTES
    574             || allowed.reason.chars().any(char::is_control)
    575         {
    576             return Err(format!(
    577                 "prototype guard allowlist for {} requires a reason",
    578                 allowed.pattern_id
    579             ));
    580         }
    581         let key = (
    582             allowed.pattern_id.as_str(),
    583             allowed.path.as_str(),
    584             allowed.line_contains.as_str(),
    585         );
    586         if !allow_keys.insert(key) {
    587             return Err(format!(
    588                 "duplicate prototype guard allowlist entry: {} {}",
    589                 allowed.pattern_id, allowed.path
    590             ));
    591         }
    592     }
    593     Ok(())
    594 }
    595 
    596 fn validate_repo_relative_path(value: &str, label: &str) -> Result<(), String> {
    597     let path = Path::new(value);
    598     if value.is_empty()
    599         || value.len() > PROTOTYPE_MAX_CONFIG_STRING_BYTES
    600         || value.chars().any(char::is_control)
    601         || value.contains('\\')
    602         || value.contains(':')
    603         || path.is_absolute()
    604         || path
    605             .components()
    606             .any(|component| !matches!(component, std::path::Component::Normal(_)))
    607     {
    608         return Err(format!(
    609             "{label} must be a normalized repository-relative path: {value:?}"
    610         ));
    611     }
    612     Ok(())
    613 }
    614 
    615 fn validate_repo_relative_or_root_path(value: &str, label: &str) -> Result<(), String> {
    616     if value == "." {
    617         return Ok(());
    618     }
    619     validate_repo_relative_path(value, label)
    620 }
    621 
    622 fn reject_symlinked_path_components(
    623     root: &Path,
    624     relative_path: &Path,
    625     label: &str,
    626 ) -> Result<(), String> {
    627     let mut candidate = root.to_path_buf();
    628     for component in relative_path.components() {
    629         let std::path::Component::Normal(component) = component else {
    630             return Err(format!(
    631                 "{label} must contain only normalized path components: {}",
    632                 relative_path.display()
    633             ));
    634         };
    635         candidate.push(component);
    636         let metadata = fs::symlink_metadata(&candidate).map_err(|error| {
    637             format!("inspect {label} component {}: {error}", candidate.display())
    638         })?;
    639         if metadata.file_type().is_symlink() {
    640             return Err(format!(
    641                 "{label} must not contain a symlinked component: {}",
    642                 candidate.display()
    643             ));
    644         }
    645     }
    646     Ok(())
    647 }
    648 
    649 fn repository_path_is_within(path: &str, prefix: &str) -> bool {
    650     path == prefix
    651         || path
    652             .strip_prefix(prefix)
    653             .is_some_and(|rest| rest.starts_with('/'))
    654 }
    655 
    656 fn scan_prototype_contracts(
    657     root: &Path,
    658     config: &PrototypeGuardConfig,
    659 ) -> Result<PrototypeGuardReport, String> {
    660     let extensions: HashSet<&str> = config.scan.extensions.iter().map(String::as_str).collect();
    661     let extensionless_names: HashSet<&str> = config
    662         .scan
    663         .extensionless_names
    664         .iter()
    665         .map(String::as_str)
    666         .collect();
    667     let mut inputs = PrototypeInputs::default();
    668     for relative_root in &config.scan.roots {
    669         reject_symlinked_path_components(
    670             root,
    671             Path::new(relative_root),
    672             "prototype guard scan root",
    673         )?;
    674     }
    675     for relative_root in &config.scan.path_roots {
    676         let relative_path = Path::new(relative_root);
    677         if relative_root != "." {
    678             reject_symlinked_path_components(
    679                 root,
    680                 relative_path,
    681                 "prototype guard path scan root",
    682             )?;
    683         }
    684     }
    685     if let Some(governed_paths) = git_governed_paths(
    686         root,
    687         config.limits.max_scan_entries,
    688         config.limits.max_inventory_bytes,
    689     )? {
    690         for candidate in governed_paths {
    691             let relative = prototype_display_path(root, &candidate)?;
    692             if path_is_excluded(&relative, &config.scan.path_excludes) {
    693                 continue;
    694             }
    695             if path_is_within_any_root(&relative, &config.scan.path_roots) {
    696                 inputs.paths.push(candidate.clone());
    697             }
    698             if path_is_within_any_root(&relative, &config.scan.roots)
    699                 && is_prototype_text_input(&candidate, &extensions, &extensionless_names)
    700             {
    701                 inputs.files.push(candidate);
    702             }
    703         }
    704     } else {
    705         for relative_root in &config.scan.roots {
    706             collect_prototype_inputs(
    707                 root,
    708                 &root.join(relative_root),
    709                 &extensions,
    710                 &extensionless_names,
    711                 &config.scan.path_excludes,
    712                 config.limits.max_scan_entries,
    713                 &mut inputs,
    714             )?;
    715         }
    716         for relative_root in &config.scan.path_roots {
    717             collect_prototype_paths(
    718                 root,
    719                 &root.join(relative_root),
    720                 &config.scan.path_excludes,
    721                 config.limits.max_scan_entries,
    722                 &mut inputs.paths,
    723             )?;
    724         }
    725     }
    726     inputs.files.sort();
    727     inputs.files.dedup();
    728     inputs.paths.sort();
    729     inputs.paths.dedup();
    730     if inputs.paths.len() > config.limits.max_scan_entries {
    731         return Err(format!(
    732             "prototype guard scan contains {} entries, limit is {}",
    733             inputs.paths.len(),
    734             config.limits.max_scan_entries
    735         ));
    736     }
    737 
    738     let mut report = PrototypeGuardReport::default();
    739     let mut allow_match_counts = vec![0_usize; config.allow.len()];
    740     for candidate in inputs.paths {
    741         let path = prototype_display_path(root, &candidate)?;
    742         for pattern in config.pattern.iter().filter(|pattern| pattern.match_path) {
    743             if !prototype_pattern_matches(&path, &path, pattern) {
    744                 continue;
    745             }
    746             record_prototype_match(
    747                 config,
    748                 &mut report,
    749                 &mut allow_match_counts,
    750                 PrototypeFinding {
    751                     pattern_id: pattern.id.clone(),
    752                     path: path.clone(),
    753                     origin: PrototypeFindingOrigin::Path,
    754                     line: None,
    755                     excerpt: bounded_excerpt(&path),
    756                 },
    757                 &path,
    758             )?;
    759         }
    760     }
    761     for file in inputs.files {
    762         let path = prototype_display_path(root, &file)?;
    763         let source = read_bounded_prototype_input(&file, &path, config.limits.max_file_bytes)?;
    764         for (line_index, line) in source.lines().enumerate() {
    765             for pattern in &config.pattern {
    766                 if !prototype_pattern_matches(&path, line, pattern) {
    767                     continue;
    768                 }
    769                 let finding = PrototypeFinding {
    770                     pattern_id: pattern.id.clone(),
    771                     path: path.clone(),
    772                     origin: PrototypeFindingOrigin::Content,
    773                     line: Some(line_index + 1),
    774                     excerpt: bounded_excerpt(line),
    775                 };
    776                 record_prototype_match(
    777                     config,
    778                     &mut report,
    779                     &mut allow_match_counts,
    780                     finding,
    781                     line,
    782                 )?;
    783             }
    784         }
    785     }
    786     for (allowed, match_count) in config.allow.iter().zip(allow_match_counts) {
    787         if match_count != 1 {
    788             return Err(format!(
    789                 "prototype guard allowlist entry must match exactly one line (matched {match_count}): {} {} contains {:?}",
    790                 allowed.pattern_id, allowed.path, allowed.line_contains
    791             ));
    792         }
    793     }
    794     report.findings.sort_by(|left, right| {
    795         (&left.path, left.origin, left.line, &left.pattern_id).cmp(&(
    796             &right.path,
    797             right.origin,
    798             right.line,
    799             &right.pattern_id,
    800         ))
    801     });
    802     report.allowed.sort_by(|left, right| {
    803         (
    804             &left.finding.path,
    805             left.finding.origin,
    806             left.finding.line,
    807             &left.finding.pattern_id,
    808         )
    809             .cmp(&(
    810                 &right.finding.path,
    811                 right.finding.origin,
    812                 right.finding.line,
    813                 &right.finding.pattern_id,
    814             ))
    815     });
    816     Ok(report)
    817 }
    818 
    819 fn git_governed_paths(
    820     root: &Path,
    821     max_scan_entries: usize,
    822     max_inventory_bytes: usize,
    823 ) -> Result<Option<Vec<PathBuf>>, String> {
    824     if !root.join(".git").exists() {
    825         return Ok(None);
    826     }
    827     let mut child = Command::new("git")
    828         .arg("-C")
    829         .arg(root)
    830         .args([
    831             "ls-files",
    832             "-z",
    833             "--cached",
    834             "--others",
    835             "--exclude-standard",
    836         ])
    837         .stdout(Stdio::piped())
    838         .stderr(Stdio::piped())
    839         .spawn()
    840         .map_err(|error| format!("run git source inventory for prototype guard: {error}"))?;
    841 
    842     let stdout = child
    843         .stdout
    844         .take()
    845         .ok_or_else(|| "Git source inventory stdout was not captured".to_string())?;
    846     let stderr = child
    847         .stderr
    848         .take()
    849         .ok_or_else(|| "Git source inventory stderr was not captured".to_string())?;
    850     let stderr_reader = std::thread::spawn(move || read_bounded_and_drain(stderr));
    851     let inventory = parse_git_inventory(root, stdout, max_scan_entries, max_inventory_bytes);
    852     if inventory.is_err() {
    853         let _ = child.kill();
    854     }
    855     let status = child
    856         .wait()
    857         .map_err(|error| format!("wait for Git source inventory: {error}"))?;
    858     let stderr = stderr_reader
    859         .join()
    860         .map_err(|_| "Git source inventory stderr reader panicked".to_string())?
    861         .map_err(|error| format!("read Git source inventory stderr: {error}"))?;
    862     let paths = inventory?;
    863     if !status.success() {
    864         return Err(format!(
    865             "Git source inventory for prototype guard failed: {}",
    866             escape_report_text(String::from_utf8_lossy(&stderr).trim())
    867         ));
    868     }
    869     Ok(Some(paths))
    870 }
    871 
    872 fn read_bounded_and_drain(mut reader: impl Read) -> std::io::Result<Vec<u8>> {
    873     let mut captured = Vec::new();
    874     let mut buffer = [0_u8; 4096];
    875     loop {
    876         let read = reader.read(&mut buffer)?;
    877         if read == 0 {
    878             return Ok(captured);
    879         }
    880         let remaining = PROTOTYPE_MAX_GIT_STDERR_BYTES.saturating_sub(captured.len());
    881         captured.extend_from_slice(&buffer[..read.min(remaining)]);
    882     }
    883 }
    884 
    885 fn parse_git_inventory(
    886     root: &Path,
    887     mut reader: impl Read,
    888     max_scan_entries: usize,
    889     max_inventory_bytes: usize,
    890 ) -> Result<Vec<PathBuf>, String> {
    891     let mut paths = Vec::new();
    892     let mut raw_path = Vec::new();
    893     let mut total_bytes = 0_usize;
    894     let mut buffer = [0_u8; 4096];
    895     loop {
    896         let read = reader
    897             .read(&mut buffer)
    898             .map_err(|error| format!("read Git source inventory: {error}"))?;
    899         if read == 0 {
    900             break;
    901         }
    902         total_bytes = total_bytes.checked_add(read).ok_or_else(|| {
    903             "prototype guard Git source inventory byte count overflowed".to_string()
    904         })?;
    905         if total_bytes > max_inventory_bytes {
    906             return Err(format!(
    907                 "prototype guard Git source inventory exceeds configured byte limit {max_inventory_bytes}"
    908             ));
    909         }
    910         for byte in &buffer[..read] {
    911             if *byte != 0 {
    912                 if raw_path.len() >= PROTOTYPE_MAX_CONFIG_STRING_BYTES {
    913                     return Err(format!(
    914                         "prototype guard Git source path exceeds compiled byte limit {PROTOTYPE_MAX_CONFIG_STRING_BYTES}"
    915                     ));
    916                 }
    917                 raw_path.push(*byte);
    918                 continue;
    919             }
    920             if raw_path.is_empty() {
    921                 continue;
    922             }
    923             if paths.len() >= max_scan_entries {
    924                 return Err(format!(
    925                     "prototype guard Git source inventory exceeds configured entry limit {max_scan_entries}"
    926                 ));
    927             }
    928             let relative = std::str::from_utf8(&raw_path)
    929                 .map_err(|error| format!("prototype guard Git path is not UTF-8: {error}"))?;
    930             validate_repo_relative_path(relative, "prototype guard Git source path")?;
    931             let candidate = root.join(relative);
    932             match fs::symlink_metadata(&candidate) {
    933                 Ok(_) => {
    934                     reject_symlinked_path_components(
    935                         root,
    936                         Path::new(relative),
    937                         "prototype guard Git source path",
    938                     )?;
    939                     paths.push(candidate);
    940                 }
    941                 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
    942                 Err(error) => {
    943                     return Err(format!(
    944                         "inspect prototype guard Git source {}: {error}",
    945                         candidate.display()
    946                     ));
    947                 }
    948             }
    949             raw_path.clear();
    950         }
    951     }
    952     if !raw_path.is_empty() {
    953         return Err(
    954             "prototype guard Git source inventory ended without a NUL delimiter".to_string(),
    955         );
    956     }
    957     paths.sort();
    958     paths.dedup();
    959     Ok(paths)
    960 }
    961 
    962 fn path_is_within_any_root(path: &str, roots: &[String]) -> bool {
    963     roots
    964         .iter()
    965         .any(|root| root == "." || repository_path_is_within(path, root))
    966 }
    967 
    968 fn path_is_excluded(path: &str, excluded_prefixes: &[String]) -> bool {
    969     excluded_prefixes
    970         .iter()
    971         .any(|prefix| repository_path_is_within(path, prefix))
    972 }
    973 
    974 fn prototype_display_path(root: &Path, path: &Path) -> Result<String, String> {
    975     let relative = path.strip_prefix(root).map_err(|_| {
    976         format!(
    977             "prototype guard path is outside repository root: {}",
    978             path.display()
    979         )
    980     })?;
    981     if relative.as_os_str().is_empty() {
    982         return Ok(".".to_string());
    983     }
    984     let mut components = Vec::new();
    985     for component in relative.components() {
    986         let std::path::Component::Normal(component) = component else {
    987             return Err("prototype guard path must contain only normal components".to_string());
    988         };
    989         components.push(
    990             component
    991                 .to_str()
    992                 .ok_or_else(|| "prototype guard path is not UTF-8".to_string())?,
    993         );
    994     }
    995     let relative = components.join("/");
    996     validate_repo_relative_path(&relative, "prototype guard source path")?;
    997     Ok(relative)
    998 }
    999 
   1000 fn is_prototype_text_input(
   1001     path: &Path,
   1002     extensions: &HashSet<&str>,
   1003     extensionless_names: &HashSet<&str>,
   1004 ) -> bool {
   1005     let extension_matches = path
   1006         .extension()
   1007         .and_then(|extension| extension.to_str())
   1008         .is_some_and(|extension| extensions.contains(extension));
   1009     let extensionless_matches = path.extension().is_none()
   1010         && path
   1011             .file_name()
   1012             .and_then(|name| name.to_str())
   1013             .is_some_and(|name| extensionless_names.contains(name));
   1014     extension_matches || extensionless_matches
   1015 }
   1016 
   1017 fn record_prototype_match(
   1018     config: &PrototypeGuardConfig,
   1019     report: &mut PrototypeGuardReport,
   1020     allow_match_counts: &mut [usize],
   1021     finding: PrototypeFinding,
   1022     matched_text: &str,
   1023 ) -> Result<(), String> {
   1024     let match_count = report.findings.len() + report.allowed.len();
   1025     if match_count >= config.limits.max_matches {
   1026         return Err(format!(
   1027             "prototype guard match count exceeds configured limit {}",
   1028             config.limits.max_matches
   1029         ));
   1030     }
   1031     if let Some((allow_index, allowed)) = config.allow.iter().enumerate().find(|(_, allowed)| {
   1032         allowed.pattern_id == finding.pattern_id
   1033             && allowed.path == finding.path
   1034             && matched_text.contains(&allowed.line_contains)
   1035     }) {
   1036         allow_match_counts[allow_index] += 1;
   1037         report.allowed.push(PrototypeAllowedMatch {
   1038             finding,
   1039             reason: allowed.reason.clone(),
   1040         });
   1041     } else {
   1042         report.findings.push(finding);
   1043     }
   1044     Ok(())
   1045 }
   1046 
   1047 fn read_bounded_prototype_input(
   1048     path: &Path,
   1049     display_path: &str,
   1050     max_file_bytes: u64,
   1051 ) -> Result<String, String> {
   1052     #[cfg(unix)]
   1053     let bytes = {
   1054         use crate::safe_artifact_io::{ArtifactIoFailureKind, LimitKind};
   1055 
   1056         crate::safe_artifact_io::read_regular_path(path, max_file_bytes).map_err(|error| {
   1057             match error.kind() {
   1058                 ArtifactIoFailureKind::LimitExceeded(LimitKind::FileBytes) => format!(
   1059                     "prototype guard input exceeds {max_file_bytes} bytes: {display_path}"
   1060                 ),
   1061                 ArtifactIoFailureKind::InvalidObject => format!(
   1062                     "prototype guard input must be a regular single-link file without linked path components: {display_path}"
   1063                 ),
   1064                 _ => format!("admit prototype guard input {display_path}: {error}"),
   1065             }
   1066         })?
   1067     };
   1068     #[cfg(not(unix))]
   1069     let bytes = {
   1070         let metadata = fs::symlink_metadata(path)
   1071             .map_err(|error| format!("inspect prototype guard input {display_path}: {error}"))?;
   1072         if metadata.file_type().is_symlink() || !metadata.is_file() {
   1073             return Err(format!(
   1074                 "prototype guard input must be a regular non-symlink file: {display_path}"
   1075             ));
   1076         }
   1077         let file = fs::File::open(path)
   1078             .map_err(|error| format!("open prototype guard input {display_path}: {error}"))?;
   1079         if !file
   1080             .metadata()
   1081             .map_err(|error| {
   1082                 format!("inspect opened prototype guard input {display_path}: {error}")
   1083             })?
   1084             .is_file()
   1085         {
   1086             return Err(format!(
   1087                 "prototype guard input must be a regular file: {display_path}"
   1088             ));
   1089         }
   1090         let mut bytes = Vec::new();
   1091         file.take(max_file_bytes + 1)
   1092             .read_to_end(&mut bytes)
   1093             .map_err(|error| format!("read prototype guard input {display_path}: {error}"))?;
   1094         if bytes.len() as u64 > max_file_bytes {
   1095             return Err(format!(
   1096                 "prototype guard input exceeds {max_file_bytes} bytes: {display_path}"
   1097             ));
   1098         }
   1099         bytes
   1100     };
   1101     String::from_utf8(bytes)
   1102         .map_err(|error| format!("prototype guard input is not UTF-8 {display_path}: {error}"))
   1103 }
   1104 
   1105 #[derive(Default)]
   1106 struct PrototypeInputs {
   1107     files: Vec<PathBuf>,
   1108     paths: Vec<PathBuf>,
   1109 }
   1110 
   1111 fn collect_prototype_inputs(
   1112     root: &Path,
   1113     path: &Path,
   1114     extensions: &HashSet<&str>,
   1115     extensionless_names: &HashSet<&str>,
   1116     excluded_prefixes: &[String],
   1117     max_scan_entries: usize,
   1118     inputs: &mut PrototypeInputs,
   1119 ) -> Result<(), String> {
   1120     let relative = prototype_display_path(root, path)?;
   1121     if path_is_excluded(&relative, excluded_prefixes) {
   1122         return Ok(());
   1123     }
   1124     let metadata = fs::symlink_metadata(path).map_err(|error| {
   1125         format!(
   1126             "inspect required prototype guard path {}: {error}",
   1127             path.display()
   1128         )
   1129     })?;
   1130     if metadata.file_type().is_symlink() {
   1131         return Err(format!(
   1132             "prototype guard refuses symlinked scan input: {}",
   1133             path.display()
   1134         ));
   1135     }
   1136     if inputs.paths.len() >= max_scan_entries {
   1137         return Err(format!(
   1138             "prototype guard scan exceeds configured entry limit {max_scan_entries}"
   1139         ));
   1140     }
   1141     inputs.paths.push(path.to_path_buf());
   1142     if metadata.is_file() {
   1143         if is_prototype_text_input(path, extensions, extensionless_names) {
   1144             inputs.files.push(path.to_path_buf());
   1145         }
   1146         return Ok(());
   1147     }
   1148     if !metadata.is_dir() {
   1149         if is_prototype_text_input(path, extensions, extensionless_names) {
   1150             return Err(format!(
   1151                 "prototype guard input must be a regular file: {relative}"
   1152             ));
   1153         }
   1154         return Ok(());
   1155     }
   1156     let entries = fs::read_dir(path)
   1157         .map_err(|error| format!("read prototype guard directory {}: {error}", path.display()))?;
   1158     for entry in entries {
   1159         let entry = entry.map_err(|error| {
   1160             format!(
   1161                 "read prototype guard entry under {}: {error}",
   1162                 path.display()
   1163             )
   1164         })?;
   1165         collect_prototype_inputs(
   1166             root,
   1167             &entry.path(),
   1168             extensions,
   1169             extensionless_names,
   1170             excluded_prefixes,
   1171             max_scan_entries,
   1172             inputs,
   1173         )?;
   1174     }
   1175     Ok(())
   1176 }
   1177 
   1178 fn collect_prototype_paths(
   1179     root: &Path,
   1180     path: &Path,
   1181     excluded_prefixes: &[String],
   1182     max_scan_entries: usize,
   1183     paths: &mut Vec<PathBuf>,
   1184 ) -> Result<(), String> {
   1185     let relative = prototype_display_path(root, path)?;
   1186     if excluded_prefixes
   1187         .iter()
   1188         .any(|prefix| repository_path_is_within(&relative, prefix))
   1189     {
   1190         return Ok(());
   1191     }
   1192     let metadata = fs::symlink_metadata(path).map_err(|error| {
   1193         format!(
   1194             "inspect required prototype guard path {}: {error}",
   1195             path.display()
   1196         )
   1197     })?;
   1198     if metadata.file_type().is_symlink() {
   1199         return Err(format!(
   1200             "prototype guard refuses symlinked scan input: {}",
   1201             path.display()
   1202         ));
   1203     }
   1204     if paths.len() >= max_scan_entries {
   1205         return Err(format!(
   1206             "prototype guard scan exceeds configured entry limit {max_scan_entries}"
   1207         ));
   1208     }
   1209     paths.push(path.to_path_buf());
   1210     if !metadata.is_dir() {
   1211         return Ok(());
   1212     }
   1213     let entries = fs::read_dir(path)
   1214         .map_err(|error| format!("read prototype guard directory {}: {error}", path.display()))?;
   1215     for entry in entries {
   1216         let entry = entry.map_err(|error| {
   1217             format!(
   1218                 "read prototype guard entry under {}: {error}",
   1219                 path.display()
   1220             )
   1221         })?;
   1222         collect_prototype_paths(
   1223             root,
   1224             &entry.path(),
   1225             excluded_prefixes,
   1226             max_scan_entries,
   1227             paths,
   1228         )?;
   1229     }
   1230     Ok(())
   1231 }
   1232 
   1233 fn prototype_pattern_matches(path: &str, line: &str, pattern: &PrototypePattern) -> bool {
   1234     let path_matches = pattern.path_prefixes.is_empty()
   1235         || pattern
   1236             .path_prefixes
   1237             .iter()
   1238             .any(|prefix| repository_path_is_within(path, prefix));
   1239     path_matches
   1240         && match pattern.match_kind {
   1241             PrototypeMatchKind::Substring => line.contains(&pattern.needle),
   1242             PrototypeMatchKind::WordPrefix => {
   1243                 let folded_line = line.to_ascii_lowercase();
   1244                 let folded_needle = pattern.needle.to_ascii_lowercase();
   1245                 folded_line.match_indices(&folded_needle).any(|(index, _)| {
   1246                     folded_line[..index]
   1247                         .chars()
   1248                         .next_back()
   1249                         .is_none_or(|character| !is_prototype_identifier_continue(character))
   1250                 })
   1251             }
   1252         }
   1253 }
   1254 
   1255 fn is_prototype_identifier_continue(character: char) -> bool {
   1256     character.is_alphanumeric() || character == '_'
   1257 }
   1258 
   1259 fn bounded_excerpt(line: &str) -> String {
   1260     const LIMIT: usize = 240;
   1261     let escaped = escape_report_text(line.trim());
   1262     if escaped.chars().count() <= LIMIT {
   1263         return escaped;
   1264     }
   1265     let mut excerpt: String = escaped.chars().take(LIMIT - 3).collect();
   1266     excerpt.push_str("...");
   1267     excerpt
   1268 }
   1269 
   1270 fn escape_report_text(value: &str) -> String {
   1271     let mut escaped = String::with_capacity(value.len());
   1272     for character in value.chars() {
   1273         if character.is_control() {
   1274             escaped.extend(character.escape_default());
   1275         } else {
   1276             escaped.push(character);
   1277         }
   1278     }
   1279     escaped
   1280 }
   1281 
   1282 fn print_prototype_guard_report(
   1283     mode: PrototypeGuardMode,
   1284     report: &PrototypeGuardReport,
   1285     limits: &PrototypeGuardLimits,
   1286 ) {
   1287     println!(
   1288         "prototype contract source guard: mode={} findings={} allowlisted={}",
   1289         mode.as_str(),
   1290         report.findings.len(),
   1291         report.allowed.len()
   1292     );
   1293     for finding in report.findings.iter().take(limits.max_reported_findings) {
   1294         print_prototype_finding("finding", finding, None);
   1295     }
   1296     if report.findings.len() > limits.max_reported_findings {
   1297         println!(
   1298             "... {} additional finding(s) omitted by report limit",
   1299             report.findings.len() - limits.max_reported_findings
   1300         );
   1301     }
   1302     for allowed in report.allowed.iter().take(limits.max_reported_allowlisted) {
   1303         print_prototype_finding("allowlisted", &allowed.finding, Some(&allowed.reason));
   1304     }
   1305     if report.allowed.len() > limits.max_reported_allowlisted {
   1306         println!(
   1307             "... {} additional allowlisted match(es) omitted by report limit",
   1308             report.allowed.len() - limits.max_reported_allowlisted
   1309         );
   1310     }
   1311 }
   1312 
   1313 fn print_prototype_finding(label: &str, finding: &PrototypeFinding, reason: Option<&str>) {
   1314     let path = escape_report_text(&finding.path);
   1315     let location = finding
   1316         .line
   1317         .map_or_else(|| format!("{path} [path]"), |line| format!("{path}:{line}"));
   1318     if let Some(reason) = reason {
   1319         let reason = escape_report_text(reason);
   1320         println!(
   1321             "{label} {} {location}: {} ({reason})",
   1322             finding.pattern_id,
   1323             escape_report_text(&finding.excerpt)
   1324         );
   1325     } else {
   1326         println!(
   1327             "{label} {} {location}: {}",
   1328             finding.pattern_id,
   1329             escape_report_text(&finding.excerpt)
   1330         );
   1331     }
   1332 }
   1333 
   1334 pub fn validate_forbidden_identifiers(root: &Path) -> Result<(), String> {
   1335     let mut failures = Vec::new();
   1336     let consolidation_active = consolidation_is_active(root);
   1337     reject_substrings(
   1338         root,
   1339         &[PathBuf::from("crates/transport_nostr/src")],
   1340         &["RadrootsEventIngest::verified"],
   1341         "relay fetch must not bypass event-store verification",
   1342         &[],
   1343         &mut failures,
   1344     );
   1345     reject_substrings(
   1346         root,
   1347         &[PathBuf::from("crates/event_store/src")],
   1348         &["last_created_at", "last_event_id"],
   1349         "event-store projection cursors must use last_event_seq",
   1350         &[],
   1351         &mut failures,
   1352     );
   1353     reject_raw_protocol_strings(root, &mut failures);
   1354     reject_substrings(
   1355         root,
   1356         &[
   1357             PathBuf::from("crates/event/src"),
   1358             PathBuf::from("crates/event_codec/src"),
   1359             PathBuf::from("crates/trade/src"),
   1360         ],
   1361         &[
   1362             "RadrootsTradeMessageType",
   1363             "RadrootsTradeEnvelope",
   1364             "RadrootsTradeMessagePayload",
   1365             "RadrootsTradeQuestion",
   1366             "RadrootsTradeAnswer",
   1367             "RadrootsTradeDiscount",
   1368             "RadrootsTradeOrder",
   1369             "RadrootsActiveOrder",
   1370             "RadrootsActiveTrade",
   1371             "RadrootsTradeListingParseError",
   1372             "RadrootsClassifiedListingTradeProjectionParseError",
   1373             "RadrootsOperationalListingTradeProjectionParseError",
   1374             "RadrootsTradeDomain",
   1375             "radroots_sdk::trade::",
   1376             "TradeListingParseError",
   1377             "TradeListingEnvelope",
   1378             "TradeListingMessage",
   1379             "KIND_TRADE_ORDER",
   1380             "TRADE_LISTING_KINDS",
   1381             "build_envelope_draft",
   1382             "parse_envelope",
   1383             "public_trade",
   1384             "events::trade::",
   1385             "event_codec::trade::",
   1386             "trade_order_economics_digest",
   1387             "trade_revision",
   1388             "trade_lifecycle",
   1389             "reduce_active_order",
   1390             "canonicalize_active_order",
   1391             "active_trade_",
   1392             "ActiveOrder",
   1393             "active_order",
   1394             "active order",
   1395             "active trade",
   1396             "RADROOTS_TRADE_LISTING_DOMAIN",
   1397             "RADROOTS_TRADE_ENVELOPE_VERSION",
   1398         ],
   1399         "removed trade identifiers must not reappear",
   1400         &[],
   1401         &mut failures,
   1402     );
   1403     reject_substrings(
   1404         root,
   1405         &[PathBuf::from("crates"), PathBuf::from("contracts")],
   1406         &[
   1407             "KIND_TRADE_LISTING_ORDER",
   1408             "KIND_TRADE_LISTING_QUESTION",
   1409             "KIND_TRADE_LISTING_ANSWER",
   1410             "KIND_TRADE_LISTING_DISCOUNT",
   1411             "KIND_TRADE_LISTING_CANCEL",
   1412             "KIND_TRADE_LISTING_FULFILLMENT",
   1413             "KIND_TRADE_LISTING_RECEIPT",
   1414             "KIND_TRADE_LISTING_VALIDATE_REQ",
   1415             "KIND_TRADE_LISTING_VALIDATE_RES",
   1416             "KIND_WORKER_TRADE_TRANSITION_PROOF_REQ",
   1417             "KIND_WORKER_TRADE_TRANSITION_PROOF_RES",
   1418         ],
   1419         "removed trade and DVM kind constants must not reappear",
   1420         &[],
   1421         &mut failures,
   1422     );
   1423     reject_substrings(
   1424         root,
   1425         &[
   1426             PathBuf::from("crates"),
   1427             PathBuf::from("contracts"),
   1428             PathBuf::from("tools"),
   1429         ],
   1430         RETIRED_PROTOCOL_EVENT_SURFACE_PATTERNS,
   1431         "retired V1 public event surfaces must not reappear outside negative contract guards",
   1432         RETIRED_PROTOCOL_EVENT_SURFACE_ALLOWED_PATHS,
   1433         &mut failures,
   1434     );
   1435     reject_substrings(
   1436         root,
   1437         &[
   1438             PathBuf::from("crates"),
   1439             PathBuf::from("contracts"),
   1440             PathBuf::from("tools"),
   1441             PathBuf::from("build"),
   1442         ],
   1443         &["tangle"],
   1444         "removed identifier 'tangle' must not reappear",
   1445         &[
   1446             "contracts/consolidation/baseline.v1.toml",
   1447             "contracts/consolidation/imports/studio_app.commit-map.v1.json",
   1448             "tools/xtask/src/sdk_generation/package_matrix.rs",
   1449             "tools/xtask/src/hygiene.rs",
   1450         ],
   1451         &mut failures,
   1452     );
   1453     reject_retired_listing_aliases(root, &mut failures);
   1454     if !consolidation_active {
   1455         reject_binding_dependencies(root, &mut failures);
   1456         reject_forbidden_crate_paths(root, &mut failures);
   1457     }
   1458     reject_existing_paths(
   1459         root,
   1460         &[
   1461             "spec",
   1462             "policy",
   1463             "nix",
   1464             "scripts",
   1465             "bindings",
   1466             "dist",
   1467             "ffi",
   1468             "generated",
   1469             "packages",
   1470             "pkg",
   1471             "contracts/exports",
   1472             "contracts/language-exports",
   1473             "contracts/language-exports.toml",
   1474             "contracts/language_exports",
   1475             "contracts/language_exports.toml",
   1476             "contracts/package-matrix",
   1477             "contracts/package-matrix.toml",
   1478             "contracts/package_matrix",
   1479             "contracts/package_matrix.toml",
   1480             "contracts/sdk-exports",
   1481             "contracts/sdk_exports",
   1482             "spec/exports",
   1483             "spec/sdk-exports",
   1484         ],
   1485         "SDK, binding, generated-package, and retired layout paths must stay outside rr-rs",
   1486         &mut failures,
   1487     );
   1488 
   1489     if failures.is_empty() {
   1490         println!("forbidden identifier hygiene passed");
   1491         Ok(())
   1492     } else {
   1493         Err(format!(
   1494             "forbidden identifier hygiene violations:\n{}",
   1495             failures.join("\n")
   1496         ))
   1497     }
   1498 }
   1499 
   1500 fn consolidation_is_active(root: &Path) -> bool {
   1501     let Ok(workspace) = fs::read_to_string(root.join("Cargo.toml")) else {
   1502         return false;
   1503     };
   1504     let Ok(workspace) = workspace.parse::<toml::Value>() else {
   1505         return false;
   1506     };
   1507     let Some(repository) = workspace
   1508         .get("workspace")
   1509         .and_then(|value| value.get("package"))
   1510         .and_then(|value| value.get("repository"))
   1511         .and_then(toml::Value::as_str)
   1512     else {
   1513         return false;
   1514     };
   1515     let Ok(consolidation) =
   1516         fs::read_to_string(root.join("contracts/consolidation/architecture.v1.toml"))
   1517     else {
   1518         return false;
   1519     };
   1520     let Ok(consolidation) = consolidation.parse::<toml::Value>() else {
   1521         return false;
   1522     };
   1523     consolidation
   1524         .get("canonical_rust_repository")
   1525         .and_then(toml::Value::as_str)
   1526         == Some(repository)
   1527 }
   1528 
   1529 fn reject_retired_listing_aliases(root: &Path, failures: &mut Vec<String>) {
   1530     let rel_roots = [
   1531         PathBuf::from("crates"),
   1532         PathBuf::from("contracts"),
   1533         PathBuf::from("tools"),
   1534         PathBuf::from("build"),
   1535         PathBuf::from("dto_bindgen.toml"),
   1536     ];
   1537 
   1538     for file in files_under(root, &rel_roots) {
   1539         let rel = display_path(root, &file);
   1540         if rel == "tools/xtask/src/hygiene.rs" {
   1541             continue;
   1542         }
   1543         if is_retired_listing_module_path(&rel) {
   1544             failures.push(format!(
   1545                 "retired listing public aliases must not reappear: {rel}: legacy listing module path"
   1546             ));
   1547         }
   1548 
   1549         let Ok(content) = fs::read_to_string(&file) else {
   1550             continue;
   1551         };
   1552         for (line_index, line) in content.lines().enumerate() {
   1553             if is_retired_listing_negative_guard(&rel, line) {
   1554                 continue;
   1555             }
   1556             let trimmed = line.trim_start();
   1557             if trimmed.starts_with("let ") || trimmed.starts_with("assert") {
   1558                 continue;
   1559             }
   1560 
   1561             for token in RETIRED_LISTING_ALIAS_IDENTIFIER_TOKENS {
   1562                 if contains_identifier_token(line, token) {
   1563                     failures.push(format!(
   1564                         "retired listing public aliases must not reappear: {}:{}: {}",
   1565                         rel,
   1566                         line_index + 1,
   1567                         line.trim()
   1568                     ));
   1569                 }
   1570             }
   1571             for prefix in RETIRED_LISTING_ALIAS_IDENTIFIER_PREFIXES {
   1572                 if contains_identifier_prefix(line, prefix) {
   1573                     failures.push(format!(
   1574                         "retired listing public aliases must not reappear: {}:{}: {}",
   1575                         rel,
   1576                         line_index + 1,
   1577                         line.trim()
   1578                     ));
   1579                 }
   1580             }
   1581             if line.contains(RETIRED_LISTING_CONTRACT_ID) {
   1582                 failures.push(format!(
   1583                     "retired listing public aliases must not reappear: {}:{}: {}",
   1584                     rel,
   1585                     line_index + 1,
   1586                     line.trim()
   1587                 ));
   1588             }
   1589             if is_listing_module_scope(&rel)
   1590                 && !is_canonical_event_listing_module_reference(&rel, line)
   1591                 && contains_retired_listing_module_reference(line)
   1592             {
   1593                 failures.push(format!(
   1594                     "retired listing public aliases must not reappear: {}:{}: {}",
   1595                     rel,
   1596                     line_index + 1,
   1597                     line.trim()
   1598                 ));
   1599             }
   1600         }
   1601     }
   1602 }
   1603 
   1604 fn contains_identifier_token(line: &str, token: &str) -> bool {
   1605     line.match_indices(token).any(|(index, _)| {
   1606         let before = line[..index].chars().next_back();
   1607         let after = line[index + token.len()..].chars().next();
   1608         before.is_none_or(|ch| !is_identifier_continue(ch))
   1609             && after.is_none_or(|ch| !is_identifier_continue(ch))
   1610     })
   1611 }
   1612 
   1613 fn contains_identifier_prefix(line: &str, prefix: &str) -> bool {
   1614     line.match_indices(prefix).any(|(index, _)| {
   1615         line[..index]
   1616             .chars()
   1617             .next_back()
   1618             .is_none_or(|ch| !is_identifier_continue(ch))
   1619     })
   1620 }
   1621 
   1622 fn is_identifier_continue(ch: char) -> bool {
   1623     ch.is_ascii_alphanumeric() || ch == '_'
   1624 }
   1625 
   1626 fn is_retired_listing_module_path(rel: &str) -> bool {
   1627     is_listing_module_scope(rel)
   1628         && !is_canonical_event_listing_module_path(rel)
   1629         && Path::new(rel).components().any(|component| {
   1630             component.as_os_str() == "listing"
   1631                 || Path::new(component.as_os_str())
   1632                     .file_stem()
   1633                     .is_some_and(|stem| stem == "listing")
   1634         })
   1635 }
   1636 
   1637 fn is_canonical_event_listing_module_path(rel: &str) -> bool {
   1638     rel == "crates/event/src/listing.rs" || rel.starts_with("crates/event/src/listing/")
   1639 }
   1640 
   1641 fn is_listing_module_scope(rel: &str) -> bool {
   1642     rel.starts_with("crates/event/src/")
   1643         || rel.starts_with("crates/event/tests/")
   1644         || rel.starts_with("crates/event_codec/src/")
   1645         || rel.starts_with("crates/event_codec/tests/")
   1646         || rel.starts_with("crates/trade/src/")
   1647         || rel.starts_with("crates/trade/tests/")
   1648         || rel.starts_with("contracts/conformance/vectors/")
   1649         || rel == "dto_bindgen.toml"
   1650 }
   1651 
   1652 fn contains_retired_listing_module_reference(line: &str) -> bool {
   1653     line.match_indices("listing").any(|(index, _)| {
   1654         let before = &line[..index];
   1655         let after = line[index + "listing".len()..].chars().next();
   1656         let starts_module_segment =
   1657             before.ends_with("::") || before.trim_end().ends_with("mod") || before.ends_with('/');
   1658         starts_module_segment && after.is_none_or(|ch| !is_identifier_continue(ch))
   1659     })
   1660 }
   1661 
   1662 fn is_canonical_event_listing_module_reference(rel: &str, line: &str) -> bool {
   1663     (rel == "crates/event/src/lib.rs" && line.trim() == "pub mod listing;")
   1664         || (rel.starts_with("crates/event/src/") && line.contains("crate::listing::"))
   1665         || line.contains("radroots_event::listing::")
   1666 }
   1667 
   1668 fn is_retired_listing_negative_guard(rel: &str, line: &str) -> bool {
   1669     (rel == "crates/event/src/dto.rs"
   1670         && (line.contains("\"ListingCancel\"") || line.contains("\"RadrootsListingCancel\"")))
   1671         || (rel == "crates/event/src/contract/registry_v7/tests.rs"
   1672             && line.contains("event_contract(\"radroots.listing.published.v1\").is_none()"))
   1673 }
   1674 
   1675 fn reject_binding_dependencies(root: &Path, failures: &mut Vec<String>) {
   1676     for file in manifest_files(root) {
   1677         let rel = display_path(root, &file);
   1678         let Ok(content) = fs::read_to_string(&file) else {
   1679             continue;
   1680         };
   1681         let Ok(manifest) = content.parse::<toml::Value>() else {
   1682             failures.push(format!("Cargo manifest must parse as TOML: {rel}"));
   1683             continue;
   1684         };
   1685         reject_binding_dependencies_in_value(&manifest, &mut Vec::new(), &rel, failures);
   1686     }
   1687 }
   1688 
   1689 fn reject_binding_dependencies_in_value(
   1690     value: &toml::Value,
   1691     path: &mut Vec<String>,
   1692     manifest_rel: &str,
   1693     failures: &mut Vec<String>,
   1694 ) {
   1695     let Some(table) = value.as_table() else {
   1696         return;
   1697     };
   1698     if path
   1699         .last()
   1700         .is_some_and(|segment| is_dependency_table_name(segment))
   1701     {
   1702         for dependency in BINDING_DEPENDENCIES {
   1703             if table.contains_key(*dependency) {
   1704                 failures.push(format!(
   1705                     "SDK, FFI, binding, and generated-package dependencies are forbidden in rr-rs: {manifest_rel}: {dependency} in [{}]",
   1706                     path.join(".")
   1707                 ));
   1708             }
   1709         }
   1710     }
   1711     for (key, child) in table {
   1712         path.push(key.clone());
   1713         reject_binding_dependencies_in_value(child, path, manifest_rel, failures);
   1714         path.pop();
   1715     }
   1716 }
   1717 
   1718 fn is_dependency_table_name(segment: &str) -> bool {
   1719     matches!(
   1720         segment,
   1721         "dependencies" | "dev-dependencies" | "build-dependencies"
   1722     )
   1723 }
   1724 
   1725 fn manifest_files(root: &Path) -> Vec<PathBuf> {
   1726     let mut files = vec![root.join("Cargo.toml")];
   1727     files.extend(files_under(
   1728         root,
   1729         &[PathBuf::from("crates"), PathBuf::from("tools")],
   1730     ));
   1731     files.retain(|path| path.file_name().and_then(|name| name.to_str()) == Some("Cargo.toml"));
   1732     files.sort();
   1733     files.dedup();
   1734     files
   1735 }
   1736 
   1737 fn reject_forbidden_crate_paths(root: &Path, failures: &mut Vec<String>) {
   1738     let Ok(entries) = fs::read_dir(root.join("crates")) else {
   1739         return;
   1740     };
   1741     for entry in entries.flatten() {
   1742         let path = entry.path();
   1743         if !path.is_dir() {
   1744             continue;
   1745         }
   1746         let name = entry.file_name().to_string_lossy().to_string();
   1747         if is_forbidden_crate_dir_name(&name) {
   1748             failures.push(format!(
   1749                 "SDK, FFI, binding, and generated-package crate paths are forbidden in rr-rs: crates/{name}"
   1750             ));
   1751         }
   1752     }
   1753 }
   1754 
   1755 fn is_forbidden_crate_dir_name(name: &str) -> bool {
   1756     let lowercase = name.to_ascii_lowercase();
   1757     lowercase.contains("ffi") || lowercase.contains("binding") || lowercase.contains("_wasm")
   1758 }
   1759 
   1760 fn reject_existing_paths(root: &Path, rel_paths: &[&str], label: &str, failures: &mut Vec<String>) {
   1761     for rel_path in rel_paths {
   1762         if root.join(rel_path).exists() {
   1763             failures.push(format!("{label}: {rel_path}"));
   1764         }
   1765     }
   1766 }
   1767 
   1768 fn reject_substrings(
   1769     root: &Path,
   1770     rel_roots: &[PathBuf],
   1771     patterns: &[&str],
   1772     label: &str,
   1773     ignored_rel_paths: &[&str],
   1774     failures: &mut Vec<String>,
   1775 ) {
   1776     for file in files_under(root, rel_roots) {
   1777         let rel = display_path(root, &file);
   1778         if ignored_rel_paths.contains(&rel.as_str()) {
   1779             continue;
   1780         }
   1781         let Ok(content) = fs::read_to_string(&file) else {
   1782             continue;
   1783         };
   1784         for (line_index, line) in content.lines().enumerate() {
   1785             for pattern in patterns {
   1786                 if line.contains(pattern) {
   1787                     failures.push(format!(
   1788                         "{label}: {}:{}: {}",
   1789                         rel,
   1790                         line_index + 1,
   1791                         line.trim()
   1792                     ));
   1793                 }
   1794             }
   1795         }
   1796     }
   1797 }
   1798 
   1799 fn reject_raw_protocol_strings(root: &Path, failures: &mut Vec<String>) {
   1800     let rel_roots = [
   1801         PathBuf::from("crates/event/src"),
   1802         PathBuf::from("crates/event_codec/src"),
   1803         PathBuf::from("crates/trade/src"),
   1804     ];
   1805     for file in files_under(root, &rel_roots) {
   1806         let Ok(content) = fs::read_to_string(&file) else {
   1807             continue;
   1808         };
   1809         let mut struct_name = String::new();
   1810         for (line_index, line) in content.lines().enumerate() {
   1811             let trimmed = line.trim();
   1812             if let Some(rest) = trimmed.strip_prefix("pub struct ") {
   1813                 struct_name = rest
   1814                     .split(['<', '{', ' ', '('])
   1815                     .next()
   1816                     .unwrap_or_default()
   1817                     .to_owned();
   1818             }
   1819             if trimmed == "}" {
   1820                 struct_name.clear();
   1821             }
   1822             if is_raw_protocol_field(trimmed) && !is_allowed_raw_boundary(&struct_name) {
   1823                 failures.push(format!(
   1824                     "raw commercial protocol identifier String fields are forbidden: {}:{}: {}",
   1825                     display_path(root, &file),
   1826                     line_index + 1,
   1827                     trimmed
   1828                 ));
   1829             }
   1830         }
   1831     }
   1832 }
   1833 
   1834 fn is_raw_protocol_field(line: &str) -> bool {
   1835     [
   1836         "pub order_id: String,",
   1837         "pub listing_addr: String,",
   1838         "pub revision_id: String,",
   1839         "pub quote_id: String,",
   1840         "pub primary_bin_id: String,",
   1841         "pub bin_id: String,",
   1842         "pub economics_digest: String,",
   1843     ]
   1844     .contains(&line)
   1845 }
   1846 
   1847 fn is_allowed_raw_boundary(struct_name: &str) -> bool {
   1848     struct_name == "OrderEnvelope"
   1849         || struct_name == "RadrootsValidationReceiptTags"
   1850         || struct_name == "RadrootsOperationalListingTradeProjection"
   1851         || struct_name.ends_with("Projection")
   1852         || struct_name.ends_with("Accounting")
   1853         || struct_name.ends_with("Availability")
   1854         || struct_name.ends_with("Reservation")
   1855         || struct_name.ends_with("Issue")
   1856         || struct_name.ends_with("NormalizedInventoryCount")
   1857 }
   1858 
   1859 fn files_under(root: &Path, rel_roots: &[PathBuf]) -> Vec<PathBuf> {
   1860     let mut files = Vec::new();
   1861     for rel_root in rel_roots {
   1862         collect_files(root.join(rel_root), &mut files);
   1863     }
   1864     files.sort();
   1865     files
   1866 }
   1867 
   1868 fn collect_files(path: PathBuf, files: &mut Vec<PathBuf>) {
   1869     let Ok(metadata) = fs::metadata(&path) else {
   1870         return;
   1871     };
   1872     if metadata.is_file() {
   1873         if matches!(
   1874             path.extension().and_then(|ext| ext.to_str()),
   1875             Some("json" | "md" | "nix" | "rs" | "sh" | "sql" | "toml")
   1876         ) {
   1877             files.push(path);
   1878         }
   1879         return;
   1880     }
   1881     let Ok(entries) = fs::read_dir(path) else {
   1882         return;
   1883     };
   1884     for entry in entries.flatten() {
   1885         collect_files(entry.path(), files);
   1886     }
   1887 }
   1888 
   1889 fn display_path(root: &Path, file: &Path) -> String {
   1890     file.strip_prefix(root)
   1891         .unwrap_or(file)
   1892         .to_string_lossy()
   1893         .to_string()
   1894 }
   1895 
   1896 #[cfg(test)]
   1897 mod tests {
   1898     use super::*;
   1899     use std::time::{SystemTime, UNIX_EPOCH};
   1900 
   1901     fn unique_temp_dir(prefix: &str) -> PathBuf {
   1902         let ns = SystemTime::now()
   1903             .duration_since(UNIX_EPOCH)
   1904             .expect("system time")
   1905             .as_nanos();
   1906         std::env::temp_dir().join(format!("radroots_xtask_hygiene_{prefix}_{ns}"))
   1907     }
   1908 
   1909     fn write_file(root: &Path, rel: &str, content: &str) {
   1910         let path = root.join(rel);
   1911         fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
   1912         fs::write(path, content).expect("write");
   1913     }
   1914 
   1915     #[test]
   1916     fn forbidden_identifiers_accept_clean_synthetic_tree() {
   1917         let root = unique_temp_dir("clean");
   1918         write_file(
   1919             &root,
   1920             "crates/transport_nostr/src/fetch.rs",
   1921             "fn fetch() { let _ = RadrootsEventIngest::new; }\n",
   1922         );
   1923         write_file(
   1924             &root,
   1925             "crates/event_store/src/store.rs",
   1926             "pub struct RadrootsProjectionCursor { pub last_event_seq: i64 }\n",
   1927         );
   1928         write_file(
   1929             &root,
   1930             "crates/trade/src/order.rs",
   1931             "pub struct RadrootsOrderProjection { pub order_id: OrderId, }\npub enum RadrootsTradeFulfillmentStateV1 { NotStarted }\n",
   1932         );
   1933         write_file(
   1934             &root,
   1935             "crates/protocol_contract_v1/src/lib.rs",
   1936             "const RETIRED: &str = \"listing_draft\";\n",
   1937         );
   1938         write_file(
   1939             &root,
   1940             "crates/event/src/dto.rs",
   1941             "const OBSOLETE: &str = \"OrderRevision\";\n",
   1942         );
   1943         write_file(
   1944             &root,
   1945             "tools/xtask/src/hygiene.rs",
   1946             "const GUARD: &str = \"trade_order_revision_proposal\";\n",
   1947         );
   1948         validate_forbidden_identifiers(&root).expect("clean tree");
   1949         let _ = fs::remove_dir_all(root);
   1950     }
   1951 
   1952     #[test]
   1953     fn consolidated_repository_accepts_governed_binding_surfaces() {
   1954         let root = unique_temp_dir("consolidated_bindings");
   1955         write_file(
   1956             &root,
   1957             "Cargo.toml",
   1958             "[workspace]\nmembers = []\n\n[workspace.package]\nrepository = \"https://github.com/radrootslabs/lib\"\n\n[workspace.dependencies]\nuniffi = \"0.29\"\nwasm-bindgen = \"0.2\"\n",
   1959         );
   1960         write_file(
   1961             &root,
   1962             "contracts/consolidation/architecture.v1.toml",
   1963             "canonical_rust_repository = \"https://github.com/radrootslabs/lib\"\n",
   1964         );
   1965         fs::create_dir_all(root.join("crates/sdk_ffi")).expect("create FFI crate dir");
   1966         fs::create_dir_all(root.join("crates/event_codec_wasm")).expect("create WASM crate dir");
   1967 
   1968         validate_forbidden_identifiers(&root).expect("consolidated binding surfaces are governed");
   1969         let _ = fs::remove_dir_all(root);
   1970     }
   1971 
   1972     #[test]
   1973     fn forbidden_identifiers_reject_regressions() {
   1974         let root = unique_temp_dir("dirty");
   1975         write_file(
   1976             &root,
   1977             "crates/transport_nostr/src/fetch.rs",
   1978             "fn fetch() { let _ = RadrootsEventIngest::verified; }\n",
   1979         );
   1980         write_file(
   1981             &root,
   1982             "crates/event_store/src/store.rs",
   1983             "pub struct Cursor { pub last_event_id: String }\n",
   1984         );
   1985         write_file(
   1986             &root,
   1987             "crates/trade/src/order.rs",
   1988             "pub struct BadOrder {\n    pub order_id: String,\n}\n",
   1989         );
   1990         write_file(&root, "contracts/events/social-events.md", "tangle\n");
   1991         write_file(
   1992             &root,
   1993             "crates/event/src/kinds.rs",
   1994             "pub const KIND_TRADE_LISTING_ORDER: u64 = 1;\npub const KIND_TRADE_LISTING_VALIDATE_REQ: u64 = 5321;\npub const KIND_LISTING_DRAFT: u32 = 30403;\npub const KIND_CLASSIFIED_LISTING_DRAFT: u32 = 30403;\npub const KIND_LISTING: u32 = 30402;\n",
   1995         );
   1996         write_file(
   1997             &root,
   1998             "contracts/conformance/retired.json",
   1999             "{\"name\":\"trade_order_revision_proposal\",\"type\":\"TradeFulfillmentUpdated\"}\n",
   2000         );
   2001         write_file(
   2002             &root,
   2003             "Cargo.toml",
   2004             "[workspace]\n[workspace.dependencies]\nwasm-bindgen = \"0.2\"\nuniffi = \"0.29\"\n",
   2005         );
   2006         fs::create_dir_all(root.join("crates/sql_wasm_bridge")).expect("create wasm crate dir");
   2007         fs::create_dir_all(root.join("scripts")).expect("create scripts dir");
   2008         fs::create_dir_all(root.join("contracts/sdk-exports")).expect("create sdk exports dir");
   2009         let err = validate_forbidden_identifiers(&root).expect_err("dirty tree");
   2010         assert!(err.contains("relay fetch must not bypass event-store verification"));
   2011         assert!(err.contains("event-store projection cursors must use last_event_seq"));
   2012         assert!(err.contains("raw commercial protocol identifier String fields are forbidden"));
   2013         assert!(err.contains("removed identifier 'tangle' must not reappear"));
   2014         assert!(err.contains("removed trade and DVM kind constants must not reappear"));
   2015         assert!(err.contains("retired V1 public event surfaces must not reappear"));
   2016         assert!(err.contains("retired listing public aliases must not reappear"));
   2017         assert!(err.contains("wasm-bindgen"));
   2018         assert!(err.contains("uniffi"));
   2019         assert!(err.contains("crates/sql_wasm_bridge"));
   2020         assert!(err.contains("scripts"));
   2021         assert!(err.contains("contracts/sdk-exports"));
   2022         let _ = fs::remove_dir_all(root);
   2023     }
   2024 
   2025     #[test]
   2026     fn listing_alias_guard_is_token_and_path_aware() {
   2027         let clean_root = unique_temp_dir("listing_alias_clean");
   2028         write_file(&clean_root, "crates/event/src/lib.rs", "pub mod listing;\n");
   2029         write_file(
   2030             &clean_root,
   2031             "crates/event/src/listing.rs",
   2032             "pub struct CanonicalListing;\n",
   2033         );
   2034         write_file(
   2035             &clean_root,
   2036             "crates/event/src/kinds.rs",
   2037             "pub const CLASSIFIED_LISTING_EVENT_KINDS: [u32; 1] = [KIND_CLASSIFIED_LISTING];\n",
   2038         );
   2039         write_file(
   2040             &clean_root,
   2041             "crates/event/src/operational_listing.rs",
   2042             "pub struct OperationalListing;\n",
   2043         );
   2044         write_file(
   2045             &clean_root,
   2046             "crates/event/src/contract/registry_v7/tests.rs",
   2047             "assert!(event_contract(\"radroots.listing.published.v1\").is_none());\n",
   2048         );
   2049         validate_forbidden_identifiers(&clean_root).expect("new listing taxonomy is accepted");
   2050         let _ = fs::remove_dir_all(clean_root);
   2051 
   2052         let dirty_root = unique_temp_dir("listing_alias_dirty");
   2053         write_file(
   2054             &dirty_root,
   2055             "crates/event/src/listing.rs",
   2056             "pub const LISTING_EVENT_KINDS: [u32; 1] = [KIND_LISTING];\n",
   2057         );
   2058         write_file(
   2059             &dirty_root,
   2060             "contracts/conformance/listing.json",
   2061             "{\"event_contract\":\"radroots.listing.published.v1\"}\n",
   2062         );
   2063         write_file(
   2064             &dirty_root,
   2065             "crates/event_codec/tests/listing.rs",
   2066             "#[test]\nfn legacy_module_path() {}\n",
   2067         );
   2068         write_file(
   2069             &dirty_root,
   2070             "contracts/conformance/vectors/listing/build_tags.v1.json",
   2071             "{}\n",
   2072         );
   2073         write_file(
   2074             &dirty_root,
   2075             "crates/event_codec/tests/retired_aliases.rs",
   2076             "use radroots_trade::{RadrootsPublicListingAddress, listing_from_event, listing_tags_with_options};\nconst _: &str = RADROOTS_LISTING_PRODUCT_TAG_KEYS;\n",
   2077         );
   2078         let err =
   2079             validate_forbidden_identifiers(&dirty_root).expect_err("old aliases are rejected");
   2080         assert!(err.contains("retired listing public aliases must not reappear"));
   2081         assert!(err.contains("legacy listing module path"));
   2082         assert!(err.contains(RETIRED_LISTING_CONTRACT_ID));
   2083         assert!(err.contains("crates/event_codec/tests/listing.rs"));
   2084         assert!(err.contains("RadrootsPublicListingAddress"));
   2085         assert!(err.contains("listing_from_event"));
   2086         assert!(err.contains("listing_tags_with_options"));
   2087         assert!(err.contains("contracts/conformance/vectors/listing/build_tags.v1.json"));
   2088         assert!(err.contains("RADROOTS_LISTING_PRODUCT_TAG_KEYS"));
   2089         let _ = fs::remove_dir_all(dirty_root);
   2090     }
   2091 
   2092     fn prototype_config(
   2093         mode: &str,
   2094         pattern_id: &str,
   2095         needle: &str,
   2096         match_kind: &str,
   2097         allow: Option<(&str, &str, &str)>,
   2098     ) -> String {
   2099         let allow = allow.map_or_else(String::new, |(path, line_contains, reason)| {
   2100             format!(
   2101                 r#"
   2102 [[allow]]
   2103 pattern_id = "{pattern_id}"
   2104 path = "{path}"
   2105 line_contains = "{line_contains}"
   2106 reason = "{reason}"
   2107 "#
   2108             )
   2109         });
   2110         format!(
   2111             r#"schema = "{PROTOTYPE_CONTRACT_SCHEMA}"
   2112 mode = "{mode}"
   2113 
   2114 [scan]
   2115 roots = ["src", "docs"]
   2116 path_roots = ["."]
   2117 path_excludes = [".git", "target"]
   2118 extensions = ["capnp", "md", "rs", "toml", "ts"]
   2119 extensionless_names = [".gitignore", "README"]
   2120 
   2121 [limits]
   2122 max_scan_entries = 100
   2123 max_inventory_bytes = 4096
   2124 max_file_bytes = 1024
   2125 max_matches = 16
   2126 max_reported_findings = 4
   2127 max_reported_allowlisted = 4
   2128 
   2129 [[pattern]]
   2130 id = "{pattern_id}"
   2131 needle = "{needle}"
   2132 match_kind = "{match_kind}"
   2133 description = "test prototype pattern"
   2134 {allow}"#
   2135         )
   2136     }
   2137 
   2138     #[test]
   2139     fn prototype_guard_reports_matches_and_narrow_allowlists() {
   2140         let root = unique_temp_dir("prototype_report");
   2141         let needle = ["config", ".env"].concat();
   2142         write_file(
   2143             &root,
   2144             "contracts/test-prototype-guard.toml",
   2145             &prototype_config(
   2146                 "report_only",
   2147                 "config-environment",
   2148                 &needle,
   2149                 "substring",
   2150                 Some((
   2151                     "docs/history.md",
   2152                     "historical fixture",
   2153                     "Historical fixture text is not an active configuration path.",
   2154                 )),
   2155             ),
   2156         );
   2157         write_file(
   2158             &root,
   2159             "src/config.rs",
   2160             &format!("const PROTOTYPE: &str = \"{needle}\";\n"),
   2161         );
   2162         write_file(
   2163             &root,
   2164             "docs/history.md",
   2165             &format!("historical fixture: {needle}\nactive example: {needle}\n"),
   2166         );
   2167 
   2168         let config =
   2169             load_prototype_guard_config(&root, Path::new("contracts/test-prototype-guard.toml"))
   2170                 .expect("load prototype guard config");
   2171         let report = scan_prototype_contracts(&root, &config).expect("scan prototype contracts");
   2172         assert_eq!(report.findings.len(), 2);
   2173         assert_eq!(report.allowed.len(), 1);
   2174         assert_eq!(report.findings[0].path, "docs/history.md");
   2175         assert_eq!(report.findings[0].origin, PrototypeFindingOrigin::Content);
   2176         assert_eq!(report.findings[1].path, "src/config.rs");
   2177         assert_eq!(report.allowed[0].finding.path, "docs/history.md");
   2178 
   2179         run_prototype_contract_guard(
   2180             &[
   2181                 "--config".to_string(),
   2182                 "contracts/test-prototype-guard.toml".to_string(),
   2183             ],
   2184             &root,
   2185         )
   2186         .expect("report-only prototype guard");
   2187         let strict_error = run_prototype_contract_guard(
   2188             &[
   2189                 "--config".to_string(),
   2190                 "contracts/test-prototype-guard.toml".to_string(),
   2191                 "--strict".to_string(),
   2192             ],
   2193             &root,
   2194         )
   2195         .expect_err("strict prototype guard rejects findings");
   2196         assert!(strict_error.contains("2 non-allowlisted match(es)"));
   2197         let _ = fs::remove_dir_all(root);
   2198     }
   2199 
   2200     #[test]
   2201     fn prototype_guard_word_prefix_avoids_embedded_false_positives() {
   2202         let root = unique_temp_dir("prototype_word_prefix");
   2203         let prefix = ["com", "pat"].concat();
   2204         write_file(
   2205             &root,
   2206             "contracts/test-prototype-guard.toml",
   2207             &prototype_config(
   2208                 "strict",
   2209                 "compatibility-concept",
   2210                 &prefix,
   2211                 "word_prefix",
   2212                 Some((
   2213                     "docs/interoperability.md",
   2214                     "compatible peer",
   2215                     "External interoperability is not a compatibility implementation path.",
   2216                 )),
   2217             ),
   2218         );
   2219         write_file(
   2220             &root,
   2221             "docs/interoperability.md",
   2222             "incompatible input\ncompatible peer\nCompatReader\nÉcompatReader\n",
   2223         );
   2224         write_file(&root, "src/clean.rs", "fn current_contract() {}\n");
   2225 
   2226         let config =
   2227             load_prototype_guard_config(&root, Path::new("contracts/test-prototype-guard.toml"))
   2228                 .expect("load prototype guard config");
   2229         let report = scan_prototype_contracts(&root, &config).expect("scan prototype contracts");
   2230         assert_eq!(report.findings.len(), 1);
   2231         assert_eq!(report.findings[0].line, Some(3));
   2232         assert_eq!(report.findings[0].excerpt, "CompatReader");
   2233         assert_eq!(report.allowed.len(), 1);
   2234         assert_eq!(report.allowed[0].finding.line, Some(2));
   2235 
   2236         let unsafe_path =
   2237             parse_prototype_guard_args(&["--config".to_string(), "../outside.toml".to_string()])
   2238                 .expect_err("parent traversal must fail");
   2239         assert!(unsafe_path.contains("normalized repository-relative path"));
   2240         let duplicate_mode =
   2241             parse_prototype_guard_args(&["--strict".to_string(), "--report-only".to_string()])
   2242                 .expect_err("duplicate mode must fail");
   2243         assert!(duplicate_mode.contains("only one mode override"));
   2244         let _ = fs::remove_dir_all(root);
   2245     }
   2246 
   2247     #[test]
   2248     fn prototype_guard_rejects_broad_or_stale_allowlists_and_symlinks() {
   2249         let root = unique_temp_dir("prototype_allowlist_integrity");
   2250         let needle = ["import", "_json"].concat();
   2251         write_file(
   2252             &root,
   2253             "contracts/test-prototype-guard.toml",
   2254             &prototype_config(
   2255                 "report_only",
   2256                 "state-import-identifier",
   2257                 &needle,
   2258                 "substring",
   2259                 Some((
   2260                     "src/import.rs",
   2261                     "import",
   2262                     "A test allowance that is intentionally too broad.",
   2263                 )),
   2264             ),
   2265         );
   2266         write_file(
   2267             &root,
   2268             "src/import.rs",
   2269             &format!("fn {needle}() {{}}\nfn second_{needle}() {{}}\n"),
   2270         );
   2271         write_file(&root, "docs/README", "Current contract.\n");
   2272         let config =
   2273             load_prototype_guard_config(&root, Path::new("contracts/test-prototype-guard.toml"))
   2274                 .expect("load prototype guard config");
   2275         let broad_error = scan_prototype_contracts(&root, &config)
   2276             .expect_err("one allowance must not authorize multiple matching lines");
   2277         assert!(broad_error.contains("must match exactly one line (matched 2)"));
   2278 
   2279         write_file(&root, "src/import.rs", "fn current_name() {}\n");
   2280         let stale_error =
   2281             scan_prototype_contracts(&root, &config).expect_err("stale allowance must fail closed");
   2282         assert!(stale_error.contains("must match exactly one line (matched 0)"));
   2283 
   2284         #[cfg(unix)]
   2285         {
   2286             use std::os::unix::fs::symlink;
   2287 
   2288             let outside = unique_temp_dir("prototype_symlink_target");
   2289             write_file(&outside, "forbidden.rs", &format!("fn {needle}() {{}}\n"));
   2290             symlink(outside.join("forbidden.rs"), root.join("src/linked.rs"))
   2291                 .expect("create scan symlink");
   2292             let symlink_error = scan_prototype_contracts(&root, &config)
   2293                 .expect_err("symlinked source must fail closed");
   2294             assert!(symlink_error.contains("refuses symlinked scan input"));
   2295             fs::remove_file(root.join("src/linked.rs")).expect("remove direct scan symlink");
   2296 
   2297             symlink(&outside, root.join("linked-root")).expect("create intermediate scan symlink");
   2298             let linked_root_source = prototype_config(
   2299                 "report_only",
   2300                 "state-import-identifier",
   2301                 &needle,
   2302                 "substring",
   2303                 None,
   2304             )
   2305             .replace("roots = [\"src\", \"docs\"]", "roots = [\"linked-root\"]")
   2306             .replace("path_roots = [\".\"]", "path_roots = [\"docs\"]")
   2307             .replace(
   2308                 "path_excludes = [\".git\", \"target\"]",
   2309                 "path_excludes = []",
   2310             );
   2311             write_file(
   2312                 &root,
   2313                 "contracts/linked-root-guard.toml",
   2314                 &linked_root_source,
   2315             );
   2316             let linked_root_config =
   2317                 load_prototype_guard_config(&root, Path::new("contracts/linked-root-guard.toml"))
   2318                     .expect("load intermediate symlink scan config");
   2319             let linked_root_error = scan_prototype_contracts(&root, &linked_root_config)
   2320                 .expect_err("intermediate scan-root symlink must fail closed");
   2321             assert!(linked_root_error.contains("must not contain a symlinked component"));
   2322 
   2323             fs::create_dir_all(root.join("configs")).expect("create config parent");
   2324             symlink(&outside, root.join("configs/linked"))
   2325                 .expect("create intermediate config symlink");
   2326             write_file(&outside, "guard.toml", &linked_root_source);
   2327             let linked_config_error =
   2328                 load_prototype_guard_config(&root, Path::new("configs/linked/guard.toml"))
   2329                     .expect_err("intermediate config symlink must fail closed");
   2330             assert!(linked_config_error.contains("must not contain a symlinked component"));
   2331             let _ = fs::remove_dir_all(outside);
   2332         }
   2333         let _ = fs::remove_dir_all(root);
   2334     }
   2335 
   2336     #[test]
   2337     fn prototype_guard_scans_paths_non_rust_inputs_and_required_roots() {
   2338         let root = unique_temp_dir("prototype_path_and_fixture_scan");
   2339         let path_needle = ["identity", ".example.json"].concat();
   2340         let content_needle = ["allow", "_generate_identity"].concat();
   2341         let env_path_needle = [".env", ".example"].concat();
   2342         let worker_path_needle = ["workers", "/rhi"].concat();
   2343         let config_source = prototype_config(
   2344             "report_only",
   2345             "identity-example-path",
   2346             &path_needle,
   2347             "substring",
   2348             None,
   2349         )
   2350         .replace(
   2351             "roots = [\"src\", \"docs\"]",
   2352             "roots = [\"src\", \"docs\", \".gitignore\"]",
   2353         )
   2354         .replace(
   2355             "description = \"test prototype pattern\"",
   2356             "description = \"test prototype pattern\"\nmatch_path = true",
   2357         ) + &format!(
   2358             r#"
   2359 [[pattern]]
   2360 id = "identity-generation-content"
   2361 needle = "{content_needle}"
   2362 match_kind = "substring"
   2363 description = "test non-Rust fixture pattern"
   2364 
   2365 [[pattern]]
   2366 id = "environment-example-path"
   2367 needle = "{env_path_needle}"
   2368 match_kind = "substring"
   2369 description = "test environment example path"
   2370 match_path = true
   2371 
   2372 [[pattern]]
   2373 id = "worker-directory-path"
   2374 needle = "{worker_path_needle}"
   2375 match_kind = "substring"
   2376 description = "test worker directory path"
   2377 match_path = true
   2378 "#,
   2379         );
   2380         write_file(&root, "contracts/test-prototype-guard.toml", &config_source);
   2381         let identity_path = format!("src/{path_needle}");
   2382         let env_path = env_path_needle.clone();
   2383         let worker_path = format!("src/{worker_path_needle}");
   2384         write_file(&root, &identity_path, "{}\n");
   2385         write_file(&root, &env_path, "CURRENT_SETTING=true\n");
   2386         write_file(&root, ".gitignore", &format!("# {content_needle}\n"));
   2387         fs::create_dir_all(root.join(&worker_path)).expect("create forbidden worker path");
   2388         write_file(
   2389             &root,
   2390             "src/generated.ts",
   2391             &format!("export const flag = \"{content_needle}\";\n"),
   2392         );
   2393         write_file(&root, "src/service.capnp", &format!("# {content_needle}\n"));
   2394         write_file(&root, "docs/README", &format!("{content_needle}\n"));
   2395 
   2396         let config =
   2397             load_prototype_guard_config(&root, Path::new("contracts/test-prototype-guard.toml"))
   2398                 .expect("load prototype guard config");
   2399         let report = scan_prototype_contracts(&root, &config).expect("scan active textual inputs");
   2400         assert_eq!(report.findings.len(), 7);
   2401         for path in [&env_path, &identity_path, &worker_path] {
   2402             assert!(report.findings.iter().any(|finding| {
   2403                 finding.path == *path
   2404                     && finding.origin == PrototypeFindingOrigin::Path
   2405                     && finding.line.is_none()
   2406             }));
   2407         }
   2408         for path in [
   2409             ".gitignore",
   2410             "docs/README",
   2411             "src/generated.ts",
   2412             "src/service.capnp",
   2413         ] {
   2414             assert!(report.findings.iter().any(|finding| {
   2415                 finding.path == path && finding.origin == PrototypeFindingOrigin::Content
   2416             }));
   2417         }
   2418 
   2419         fs::remove_dir_all(root.join("docs")).expect("remove required scan root");
   2420         let missing_error = scan_prototype_contracts(&root, &config)
   2421             .expect_err("a missing required scan root must fail closed");
   2422         assert!(missing_error.contains("prototype guard scan root component"));
   2423         let _ = fs::remove_dir_all(root);
   2424     }
   2425 
   2426     #[cfg(unix)]
   2427     #[test]
   2428     fn prototype_guard_git_inventory_ignores_workstation_symlinks() {
   2429         use std::os::unix::fs::symlink;
   2430 
   2431         let root = unique_temp_dir("prototype_git_inventory");
   2432         let needle = [".env", ".example"].concat();
   2433         let config_source = prototype_config(
   2434             "report_only",
   2435             "environment-example-path",
   2436             &needle,
   2437             "substring",
   2438             None,
   2439         )
   2440         .replace(
   2441             "description = \"test prototype pattern\"",
   2442             "description = \"test prototype pattern\"\nmatch_path = true",
   2443         );
   2444         write_file(&root, "contracts/test-prototype-guard.toml", &config_source);
   2445         write_file(&root, "src/current.rs", "fn current_contract() {}\n");
   2446         write_file(&root, "docs/README", "Current contract.\n");
   2447         let ignore = format!(".direnv/\nresult\n.env.*\n!{needle}\n");
   2448         write_file(&root, ".gitignore", &ignore);
   2449         write_file(&root, &needle, "CURRENT_SETTING=true\n");
   2450         let init = Command::new("git")
   2451             .args(["init", "-q"])
   2452             .current_dir(&root)
   2453             .status()
   2454             .expect("run git init");
   2455         assert!(init.success());
   2456 
   2457         let config =
   2458             load_prototype_guard_config(&root, Path::new("contracts/test-prototype-guard.toml"))
   2459                 .expect("load prototype guard config");
   2460         let before = scan_prototype_contracts(&root, &config).expect("scan governed Git source");
   2461         assert_eq!(before.findings.len(), 1);
   2462         assert_eq!(before.findings[0].path, needle);
   2463         assert_eq!(before.findings[0].origin, PrototypeFindingOrigin::Path);
   2464 
   2465         let control_path = "src/control\n\u{1b}.rs";
   2466         write_file(&root, control_path, "fn current_contract() {}\n");
   2467         let control_error = scan_prototype_contracts(&root, &config)
   2468             .expect_err("control characters in Git paths must fail closed");
   2469         assert_eq!(control_error.lines().count(), 1);
   2470         assert!(!control_error.contains('\u{1b}'));
   2471         assert!(control_error.contains("control\\n\\u{1b}.rs"));
   2472         fs::remove_file(root.join(control_path)).expect("remove control-character path");
   2473 
   2474         let outside = unique_temp_dir("prototype_ignored_symlink_target");
   2475         write_file(&outside, "ignored.rs", "Current ignored cache.\n");
   2476         fs::create_dir_all(root.join(".direnv")).expect("create ignored environment cache");
   2477         symlink(outside.join("ignored.rs"), root.join(".direnv/linked.rs"))
   2478             .expect("create ignored environment symlink");
   2479         symlink(&outside, root.join("result")).expect("create ignored Nix result symlink");
   2480 
   2481         let after = scan_prototype_contracts(&root, &config)
   2482             .expect("ignored workstation symlinks must not enter the source inventory");
   2483         assert_eq!(after, before);
   2484         let _ = fs::remove_dir_all(outside);
   2485         let _ = fs::remove_dir_all(root);
   2486     }
   2487 
   2488     #[test]
   2489     fn prototype_guard_git_inventory_parser_enforces_byte_and_entry_bounds() {
   2490         let root = unique_temp_dir("prototype_git_inventory_bounds");
   2491         write_file(&root, "src/one.rs", "fn one() {}\n");
   2492         write_file(&root, "src/two.rs", "fn two() {}\n");
   2493         let inventory = b"src/one.rs\0src/two.rs\0";
   2494 
   2495         let parsed = parse_git_inventory(&root, &inventory[..], 2, inventory.len())
   2496             .expect("bounded inventory must parse");
   2497         assert_eq!(parsed.len(), 2);
   2498 
   2499         let byte_error = parse_git_inventory(&root, &inventory[..], 2, inventory.len() - 1)
   2500             .expect_err("inventory bytes above the configured ceiling must fail");
   2501         assert!(byte_error.contains("configured byte limit"));
   2502 
   2503         let entry_error = parse_git_inventory(&root, &inventory[..], 1, inventory.len())
   2504             .expect_err("inventory entries above the configured ceiling must fail");
   2505         assert!(entry_error.contains("configured entry limit 1"));
   2506 
   2507         let delimiter_error =
   2508             parse_git_inventory(&root, &inventory[..inventory.len() - 1], 2, 4096)
   2509                 .expect_err("unterminated Git inventory must fail");
   2510         assert!(delimiter_error.contains("without a NUL delimiter"));
   2511 
   2512         let escaped = bounded_excerpt("safe\tvalue\u{1b}[31m");
   2513         assert_eq!(escaped, "safe\\tvalue\\u{1b}[31m");
   2514         assert!(!escaped.chars().any(char::is_control));
   2515         let _ = fs::remove_dir_all(root);
   2516     }
   2517 
   2518     #[test]
   2519     fn prototype_guard_bounds_configuration_bytes_counts_and_reasons() {
   2520         let root = unique_temp_dir("prototype_config_bounds");
   2521         let config_path = "contracts/test-prototype-guard.toml";
   2522         write_file(
   2523             &root,
   2524             config_path,
   2525             &"x".repeat(PROTOTYPE_MAX_CONFIG_BYTES as usize + 1),
   2526         );
   2527         let bytes_error = load_prototype_guard_config(&root, Path::new(config_path))
   2528             .expect_err("oversized configuration must fail before parsing");
   2529         assert!(bytes_error.contains("exceeds 1048576 bytes"));
   2530 
   2531         let needle = ["config", ".env"].concat();
   2532         let oversized_reason = "r".repeat(PROTOTYPE_MAX_REASON_BYTES + 1);
   2533         let reason_config = prototype_config(
   2534             "report_only",
   2535             "config-environment",
   2536             &needle,
   2537             "substring",
   2538             Some(("src/config.rs", "prototype", &oversized_reason)),
   2539         );
   2540         write_file(&root, config_path, &reason_config);
   2541         let reason_error = load_prototype_guard_config(&root, Path::new(config_path))
   2542             .expect_err("oversized printed reason must fail validation");
   2543         assert!(reason_error.contains("requires a reason"));
   2544 
   2545         let mut pattern_config =
   2546             prototype_config("report_only", "pattern-0", &needle, "substring", None);
   2547         for index in 1..=PROTOTYPE_MAX_CONFIG_PATTERNS {
   2548             pattern_config.push_str(&format!(
   2549                 r#"
   2550 [[pattern]]
   2551 id = "pattern-{index}"
   2552 needle = "current-{index}"
   2553 match_kind = "substring"
   2554 description = "bounded pattern"
   2555 "#,
   2556             ));
   2557         }
   2558         write_file(&root, config_path, &pattern_config);
   2559         let count_error = load_prototype_guard_config(&root, Path::new(config_path))
   2560             .expect_err("excessive pattern count must fail validation");
   2561         assert!(count_error.contains("configuration collection exceeds compiled limit"));
   2562         let _ = fs::remove_dir_all(root);
   2563     }
   2564 
   2565     #[test]
   2566     fn prototype_guard_enforces_file_and_match_resource_bounds() {
   2567         let root = unique_temp_dir("prototype_resource_bounds");
   2568         let needle = ["config", ".env"].concat();
   2569         write_file(
   2570             &root,
   2571             "contracts/test-prototype-guard.toml",
   2572             &prototype_config(
   2573                 "report_only",
   2574                 "config-environment",
   2575                 &needle,
   2576                 "substring",
   2577                 None,
   2578             ),
   2579         );
   2580         write_file(&root, "docs/README", "Current contract.\n");
   2581         write_file(&root, "src/large.rs", &"x".repeat(1025));
   2582         let config =
   2583             load_prototype_guard_config(&root, Path::new("contracts/test-prototype-guard.toml"))
   2584                 .expect("load prototype guard config");
   2585         let size_error = scan_prototype_contracts(&root, &config)
   2586             .expect_err("oversized source input must fail closed");
   2587         assert!(size_error.contains("exceeds 1024 bytes"));
   2588 
   2589         write_file(&root, "src/large.rs", &format!("{needle}\n").repeat(17));
   2590         let match_error = scan_prototype_contracts(&root, &config)
   2591             .expect_err("excessive matches must fail closed");
   2592         assert!(match_error.contains("match count exceeds configured limit 16"));
   2593         let _ = fs::remove_dir_all(root);
   2594     }
   2595 
   2596     #[test]
   2597     fn run_dispatches_forbidden_identifiers() {
   2598         let root = unique_temp_dir("run");
   2599         write_file(
   2600             &root,
   2601             "crates/transport_nostr/src/fetch.rs",
   2602             "fn fetch() { let _ = RadrootsEventIngest::new; }\n",
   2603         );
   2604         run(&["forbidden-identifiers".to_string()], &root).expect("hygiene run");
   2605         let unknown = run(&["unknown".to_string()], &root).expect_err("unknown hygiene command");
   2606         assert!(unknown.contains("unknown hygiene subcommand"));
   2607         let _ = fs::remove_dir_all(root);
   2608     }
   2609 }
   2610 
   2611 #[cfg(all(test, unix))]
   2612 #[path = "hygiene/prototype_input_tests.rs"]
   2613 mod prototype_input_tests;