Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/crates/site-builder/src/collector.rs # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / crates / site-builder / src / collector.rs` 1757 lines ยท 78147 bytes Raw Blame History 1 //! Project progress for /progress/. `progress` reads every public project repository from the 2 //! local Radicle storage and writes `public/data/project-progress.json` (schemaVersion 2), the 3 //! file `public/js/project-progress.js` draws. 4 //! 5 //! The repositories are the public repository table (`data/public-repos.md`, the forge table). 6 //! Every figure comes from a public record: Git objects at each repository's canonical default 7 //! branch in the Radicle storage, its Radicle patches (read with `rad cob`), and the GitHub-era 8 //! pull request and Actions record up to 2026-10-01 (`scripts/progress/github-era.json`), which 9 //! Radicle does not carry and which is kept exactly as it was collected. Nothing here estimates 10 //! or fills in a number, and nothing here uses the network. A snapshot that does not reconcile 11 //! is refused before it is written, so a failed refresh leaves the last good file in place. 12 13 use serde::{Deserialize, Serialize}; 14 use serde_json::Value; 15 use std::collections::{BTreeMap, HashMap, HashSet}; 16 use std::io::{BufRead, BufReader, Write}; 17 use std::path::{Path, PathBuf}; 18 use std::process::{Command, Stdio}; 19 use std::rc::Rc; 20 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; 21 use std::sync::Mutex; 22 23 /// Every named project repository on the public Radicle table: the project name the page shows 24 /// (and the Core and Sites groups match on), then its name in that table and on the forge. Some 25 /// still carry the `-mv` suffix of the GitHub retired-name block; when a name changes, that is a 26 /// one-line edit here. Other repositories in the table that match the name rule are read as 27 /// well, under their Radicle name. 28 pub const REPOS: &[(&str, &str)] = &[ 29 ("aien-sovereign-core", "aien-sovereign-core-mv"), 30 ("aienux", "aienux"), 31 ("omega", "omega-mv"), 32 ("physics", "physics-mv"), 33 ("aien-protocols", "aien-protocols-mv"), 34 ("aien-architecture", "aien-architecture-mv"), 35 ("benchmarks", "benchmarks-mv"), 36 ("aegis-runtime", "aegis-runtime-mv"), 37 ("spark-rsi", "spark-rsi-mv"), 38 ("aienos.com", "aienos.com"), 39 (".github", ".github"), 40 ("interplane", "interplane-mv"), 41 ("synapse", "synapse"), 42 ("interplane.io", "interplane.io"), 43 ]; 44 /// The public Radicle table: `| repo | rad:RID | default branch |`. 45 const TABLE: &str = include_str!("../../../data/public-repos.md"); 46 /// Local-only repositories: never read, whatever a table says. 47 const NEVER_READ: &[&str] = &["omega-pearl", "aien-crypto"]; 48 const NEVER_READ_RID_PREFIX: &str = "z2ft64"; 49 /// The GitHub-era pull request and Actions record (see the module notes). 50 const GITHUB_ERA: &str = include_str!("../../../scripts/progress/github-era.json"); 51 const PATCH_TYPE: &str = "xyz.radicle.patch"; 52 pub const TIMEZONE: &str = "America/Chicago"; 53 54 const EXTENSIONS: &[(&str, &str)] = &[ 55 (".rs", "Rust"), (".c", "C"), (".h", "C"), (".inc", "C"), (".mojo", "Mojo"), (".py", "Python"), 56 (".sh", "Shell"), (".bash", "Shell"), (".js", "Web"), (".mjs", "Web"), (".cjs", "Web"), (".jsx", "Web"), 57 (".ts", "Web"), (".tsx", "Web"), (".html", "Web"), (".css", "Web"), (".S", "Assembly"), (".s", "Assembly"), 58 (".asm", "Assembly"), (".cu", "CUDA"), (".cuh", "CUDA"), (".cc", "C++"), (".cpp", "C++"), (".hpp", "C++"), 59 (".zig", "Zig"), 60 ]; 61 /// A path with any of these directory names (any case) is not measured. 62 const EXCLUDED_DIRS: &[&str] = &[ 63 "vendor", "vendored", "third_party", "third-party", "node_modules", "target", "dist", "build", "generated", 64 "evidence", "receipts", "artifacts", "data", "results", "fixtures", 65 ]; 66 /// `aienux` is the kernel. A repository named `aienos` is still read as its own 67 /// Core project. ADR 0045 retired aien-dev/aienix: it is not the core tree. 68 /// Sovereign Intelligence (aien-dev/sovereign-intelligence) is the whole system, 69 /// and AienOS is only the operating-system layer. 70 const CORE_NAMES: &[&str] = &["aien-sovereign-core", "aienux", "aienos", "omega", "physics", "forge", "atlas", "aien-protocols", "aien-architecture", "benchmarks"]; 71 const SITE_NAMES: &[&str] = &["aienos.com", "drakestapleton.com", "interplane.io", ".github", "aien-dev"]; 72 73 /// A repository the collector reads. 74 #[derive(Debug)] 75 struct Target { 76 /// The project name the page shows. 77 name: String, 78 /// Its name in the public Radicle table and on the forge. 79 repo: String, 80 /// Its Radicle ID, without `rad:`. 81 rid: &'static str, 82 /// The default branch the table records. 83 branch: String, 84 } 85 86 fn valid_branch(b: &str) -> bool { 87 !b.is_empty() && !b.contains("..") && b.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-' | b'/')) 88 } 89 90 /// The readable rows of a public table, `(repo, rid, default branch)`: every three-cell 91 /// `| repo | rad:RID | branch |` row whose RID is the one the forge table holds for that repo. 92 /// A row marked PRIVATE or WITHDRAWN and the local-only repositories are dropped. 93 fn table_rows(table: &str) -> Vec<(String, &'static str, String)> { 94 table 95 .lines() 96 .filter_map(|l| { 97 let cells: Vec<&str> = l.trim().strip_prefix('|')?.strip_suffix('|')?.split('|').map(str::trim).collect(); 98 let [repo, rid, branch] = cells[..] else { return None }; 99 if cells.iter().any(|c| c.contains("PRIVATE") || c.contains("WITHDRAWN")) || NEVER_READ.contains(&repo) { 100 return None; 101 } 102 let known = crate::forge::rid(repo)?; 103 let ok = rid.strip_prefix("rad:") == Some(known) 104 && !known.starts_with(NEVER_READ_RID_PREFIX) 105 && valid_repo_name(repo) 106 && valid_branch(branch); 107 ok.then(|| (repo.to_string(), known, branch.to_string())) 108 }) 109 .collect() 110 } 111 112 /// Pick the repositories to read from the public table rows. A repository in REPOS is read 113 /// under its project name. Any other repository that matches the name rule is read under its 114 /// Radicle name, unless a REPOS entry was found under that project name. Returns the targets 115 /// in table order and the REPOS entries the table does not hold. 116 fn select_targets(rows: &[(String, &'static str, String)]) -> (Vec, Vec) { 117 let mapped = |repo: &str| REPOS.iter().find(|(_, r)| *r == repo).map(|(p, _)| *p); 118 let found: HashSet<&str> = rows.iter().filter_map(|(repo, _, _)| mapped(repo)).collect(); 119 let mut targets = Vec::new(); 120 for (repo, rid, branch) in rows { 121 let name = match mapped(repo) { 122 Some(project) => project.to_string(), 123 None if project_named(repo) && !found.contains(repo.as_str()) => repo.clone(), 124 None => continue, 125 }; 126 targets.push(Target { name, repo: repo.clone(), rid: *rid, branch: branch.clone() }); 127 } 128 let missing = REPOS.iter().filter(|(p, _)| !found.contains(p)).map(|(p, r)| format!("{r} ({p})")).collect(); 129 (targets, missing) 130 } 131 132 /// The group the page files a repository under, by project name. 133 fn group_of(name: &str, archived: bool) -> &'static str { 134 if archived { 135 "Archived" 136 } else if CORE_NAMES.contains(&name) { 137 "Core" 138 } else if SITE_NAMES.contains(&name) { 139 "Sites" 140 } else { 141 "Experimental" 142 } 143 } 144 145 /// The name rule for automatically discovered project repositories. 146 fn project_named(name: &str) -> bool { 147 let word = |w: &str| name == w || name.starts_with(&format!("{w}-")); 148 name.starts_with("aien-") 149 || name.starts_with("aienos") 150 || ["aegis-", "spark-", "cortex-", "crumb-"].iter().any(|p| name.starts_with(p)) 151 || ["omega", "forge", "physics", "atlas"].iter().any(|w| word(w)) 152 } 153 154 // --------------------------------------------------------------------------------------------- 155 // Time. No time crate: civil dates from day numbers, and the US daylight saving rules for 156 // America/Chicago written out (UTC-6 standard, UTC-5 daylight). 157 // --------------------------------------------------------------------------------------------- 158 159 /// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's algorithm). 160 fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { 161 let y = if m <= 2 { y - 1 } else { y }; 162 let era = y.div_euclid(400); 163 let yoe = y - era * 400; 164 let mp = (m + 9) % 12; 165 let doy = (153 * mp + 2) / 5 + d - 1; 166 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; 167 era * 146_097 + doe - 719_468 168 } 169 170 fn civil_from_days(days: i64) -> (i64, i64, i64) { 171 let z = days + 719_468; 172 let era = z.div_euclid(146_097); 173 let doe = z.rem_euclid(146_097); 174 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; 175 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); 176 let mp = (5 * doy + 2) / 153; 177 let d = doy - (153 * mp + 2) / 5 + 1; 178 let m = if mp < 10 { mp + 3 } else { mp - 9 }; 179 (if m <= 2 { yoe + era * 400 + 1 } else { yoe + era * 400 }, m, d) 180 } 181 182 fn days_in_month(y: i64, m: i64) -> i64 { 183 days_from_civil(if m == 12 { y + 1 } else { y }, if m == 12 { 1 } else { m + 1 }, 1) - days_from_civil(y, m, 1) 184 } 185 186 /// 0 = Sunday. 1970-01-01 was a Thursday. 187 fn weekday(days: i64) -> i64 { 188 (days + 4).rem_euclid(7) 189 } 190 191 fn nth_sunday(y: i64, m: i64, n: i64) -> i64 { 192 let first = days_from_civil(y, m, 1); 193 first + (7 - weekday(first)) % 7 + 7 * (n - 1) 194 } 195 196 fn last_sunday(y: i64, m: i64) -> i64 { 197 let last = days_from_civil(y, m, 1) + days_in_month(y, m) - 1; 198 last - weekday(last) 199 } 200 201 /// UTC offset of America/Chicago, in seconds, at a UTC instant. Daylight time starts at 202 /// 02:00 standard (08:00 UTC) and ends at 02:00 daylight (07:00 UTC). 203 /// 2007 onward: second Sunday of March to first Sunday of November (Energy Policy Act 2005). 204 /// 1987 to 2006: first Sunday of April to last Sunday of October. 205 /// 1967 to 1986: last Sunday of April to last Sunday of October (the 1974 and 1975 emergency 206 /// dates are not modelled). Before 1967: standard time only. Measured history starts in 2026. 207 pub fn chicago_offset(unix_secs: i64) -> i64 { 208 let (y, _, _) = civil_from_days(unix_secs.div_euclid(86_400)); 209 let (start, end) = if y >= 2007 { 210 (nth_sunday(y, 3, 2), nth_sunday(y, 11, 1)) 211 } else if y >= 1987 { 212 (nth_sunday(y, 4, 1), last_sunday(y, 10)) 213 } else if y >= 1967 { 214 (last_sunday(y, 4), last_sunday(y, 10)) 215 } else { 216 return -6 * 3600; 217 }; 218 let (start, end) = (start * 86_400 + 8 * 3600, end * 86_400 + 7 * 3600); 219 if unix_secs >= start && unix_secs < end { -5 * 3600 } else { -6 * 3600 } 220 } 221 222 fn ymd(days: i64) -> String { 223 let (y, m, d) = civil_from_days(days); 224 format!("{y:04}-{m:02}-{d:02}") 225 } 226 227 /// The America/Chicago calendar day of a UTC instant given in milliseconds. 228 pub fn day_ms(ms: i64) -> String { 229 let secs = ms.div_euclid(1000); 230 ymd((secs + chicago_offset(secs)).div_euclid(86_400)) 231 } 232 233 /// Milliseconds since the epoch for `YYYY-MM-DD` (midnight UTC) or 234 /// `YYYY-MM-DDTHH:MM:SS[.fraction](Z|+HH:MM|-HH:MM)`. A time without a zone is refused. 235 pub fn parse_time_ms(s: &str) -> Option { 236 let b = s.as_bytes(); 237 let num = |from: usize, to: usize| -> Option { 238 let part = b.get(from..to)?; 239 if part.iter().all(u8::is_ascii_digit) { std::str::from_utf8(part).ok()?.parse().ok() } else { None } 240 }; 241 let (y, m, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); 242 if b.get(4) != Some(&b'-') || b.get(7) != Some(&b'-') || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) { 243 return None; 244 } 245 let date_ms = days_from_civil(y, m, d) * 86_400_000; 246 if b.len() == 10 { 247 return Some(date_ms); 248 } 249 if b.get(10) != Some(&b'T') || b.get(13) != Some(&b':') || b.get(16) != Some(&b':') { 250 return None; 251 } 252 let (hh, mm, ss) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); 253 if hh > 23 || mm > 59 || ss > 59 { 254 return None; 255 } 256 let mut rest = &s[19..]; 257 let mut millis = 0; 258 if let Some(frac) = rest.strip_prefix('.') { 259 let digits = frac.bytes().take_while(u8::is_ascii_digit).count(); 260 if digits == 0 { 261 return None; 262 } 263 let first3: String = frac[..digits].chars().chain("00".chars()).take(3).collect(); 264 millis = first3.parse::().ok()?; 265 rest = &frac[digits..]; 266 } 267 let offset_secs = match rest { 268 "Z" | "z" => 0, 269 _ => { 270 let rb = rest.as_bytes(); 271 if rb.len() != 6 || rb[3] != b':' || !(rb[0] == b'+' || rb[0] == b'-') { 272 return None; 273 } 274 let oh: i64 = rest[1..3].parse().ok()?; 275 let om: i64 = rest[4..6].parse().ok()?; 276 if !rest[1..3].bytes().chain(rest[4..6].bytes()).all(|c| c.is_ascii_digit()) || oh > 23 || om > 59 { 277 return None; 278 } 279 (oh * 3600 + om * 60) * if rb[0] == b'-' { -1 } else { 1 } 280 } 281 }; 282 Some(date_ms + ((hh * 3600 + mm * 60 + ss) - offset_secs) * 1000 + millis) 283 } 284 285 /// `2026-10-16T17:04:05.123Z`, the shape JavaScript's `toISOString` writes. 286 pub fn iso_ms(ms: i64) -> String { 287 let secs = ms.div_euclid(1000); 288 let rem = secs.rem_euclid(86_400); 289 format!( 290 "{}T{:02}:{:02}:{:02}.{:03}Z", 291 ymd(secs.div_euclid(86_400)), 292 rem / 3600, 293 (rem % 3600) / 60, 294 rem % 60, 295 ms.rem_euclid(1000) 296 ) 297 } 298 299 fn now_ms() -> i64 { 300 std::time::SystemTime::now() 301 .duration_since(std::time::UNIX_EPOCH) 302 .map(|d| d.as_millis() as i64) 303 .unwrap_or(0) 304 } 305 306 // --------------------------------------------------------------------------------------------- 307 // Measurement boundaries. 308 // --------------------------------------------------------------------------------------------- 309 310 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 311 pub enum Kind { 312 Source, 313 Test, 314 Docs, 315 } 316 317 #[derive(Debug, Clone, PartialEq, Eq)] 318 pub struct Spec { 319 pub kind: Kind, 320 pub lang: &'static str, 321 } 322 323 /// Node's `path.posix.extname`: from the last dot of the last component, unless that dot opens 324 /// the name (`.bashrc`) or the name is `..`. 325 fn extname(file: &str) -> &str { 326 let base = file.rsplit('/').next().unwrap_or(file); 327 match base.rfind('.') { 328 Some(0) | None => "", 329 Some(_) if base == ".." => "", 330 Some(i) => &base[i..], 331 } 332 } 333 334 fn excluded(file: &str) -> bool { 335 file.split('/').any(|part| EXCLUDED_DIRS.iter().any(|d| part.eq_ignore_ascii_case(d))) 336 } 337 338 /// Test footprint by file-path naming: a `test`/`tests` directory or name, `test_*`, `*_test(s)`, 339 /// or `*.test.*` / `*.spec.*` (any case). 340 fn test_path(file: &str) -> bool { 341 let lower = file.to_ascii_lowercase(); 342 if lower.contains(".test.") || lower.contains(".spec.") { 343 return true; 344 } 345 lower.split('/').any(|part| { 346 part.char_indices() 347 .filter(|(_, c)| *c == '.') 348 .map(|(i, _)| i) 349 .chain(std::iter::once(part.len())) 350 .any(|cut| { 351 let p = &part[..cut]; 352 p == "test" || p == "tests" || p.starts_with("test_") || p.ends_with("_test") || p.ends_with("_tests") 353 }) 354 }) 355 } 356 357 pub fn classify(file: &str, mode: &str) -> Option { 358 if mode == "120000" || excluded(file) { 359 return None; 360 } 361 let ext = extname(file); 362 if let Some((_, lang)) = EXTENSIONS.iter().find(|(e, _)| *e == ext) { 363 return Some(Spec { kind: if test_path(file) { Kind::Test } else { Kind::Source }, lang }); 364 } 365 let lower = ext.to_ascii_lowercase(); 366 if [".md", ".rst", ".txt"].contains(&lower.as_str()) && !["LICENSE", "NOTICE", "COPYING"].iter().any(|w| file.contains(w)) { 367 return Some(Spec { kind: Kind::Docs, lang: "Docs" }); 368 } 369 None 370 } 371 372 /// Physical lines: newline count, plus one for an unterminated last line. A blob with a NUL 373 /// byte is binary and counts zero. 374 pub fn physical_lines(bytes: &[u8]) -> u64 { 375 if bytes.contains(&0) { 376 return 0; 377 } 378 let lines = bytes.iter().filter(|b| **b == b'\n').count() as u64; 379 lines + u64::from(bytes.last().is_some_and(|b| *b != b'\n')) 380 } 381 382 #[derive(Debug, Clone)] 383 pub struct Entry { 384 pub oid: String, 385 pub kind: Kind, 386 pub lang: &'static str, 387 } 388 389 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] 390 pub struct Size { 391 pub source: u64, 392 pub test: u64, 393 pub docs: u64, 394 pub files: u64, 395 pub testfiles: u64, 396 pub docfiles: u64, 397 } 398 399 #[derive(Debug, Clone, Default, PartialEq, Eq)] 400 pub struct Counts { 401 pub size: Size, 402 pub langs: BTreeMap, 403 } 404 405 impl Counts { 406 fn add(&mut self, other: &Counts) { 407 let (a, b) = (&mut self.size, &other.size); 408 a.source += b.source; 409 a.test += b.test; 410 a.docs += b.docs; 411 a.files += b.files; 412 a.testfiles += b.testfiles; 413 a.docfiles += b.docfiles; 414 for (lang, n) in &other.langs { 415 *self.langs.entry(lang.clone()).or_insert(0) += n; 416 } 417 } 418 } 419 420 /// Sum a tree's measured blobs. `seen` is shared across every repository of one snapshot, so 421 /// a blob with identical content in two repositories (or twice in one) is counted once. 422 pub fn count_entries(entries: &[Entry], blob_lines: &HashMap, seen: &mut HashSet) -> Result { 423 let mut c = Counts::default(); 424 for e in entries { 425 if !seen.insert(e.oid.clone()) { 426 continue; 427 } 428 let lines = *blob_lines.get(&e.oid).ok_or("Invalid blob line count")?; 429 match e.kind { 430 Kind::Source => c.size.source += lines, 431 Kind::Test => c.size.test += lines, 432 Kind::Docs => c.size.docs += lines, 433 } 434 if e.kind == Kind::Docs { 435 c.size.docfiles += 1; 436 } else { 437 c.size.files += 1; 438 if e.kind == Kind::Test { 439 c.size.testfiles += 1; 440 } 441 *c.langs.entry(e.lang.to_string()).or_insert(0) += lines; 442 } 443 } 444 Ok(c) 445 } 446 447 // --------------------------------------------------------------------------------------------- 448 // Snapshot validation: refuse before writing. 449 // --------------------------------------------------------------------------------------------- 450 451 const REQUIRED: &[&str] = &["source", "test", "docs", "loc", "files", "testfiles", "docfiles", "repos", "commits", "prs", "merged", "ci"]; 452 453 /// JavaScript's `Number.isSafeInteger(x) && x >= 0`. 454 fn safe_count(v: Option<&Value>) -> Option { 455 let v = v?; 456 if let Some(n) = v.as_u64() { 457 return (n < (1u64 << 53)).then_some(n); 458 } 459 let f = v.as_f64()?; 460 (f >= 0.0 && f.fract() == 0.0 && f <= ((1u64 << 53) - 1) as f64).then_some(f as u64) 461 } 462 463 fn is_day(s: &str) -> bool { 464 let b = s.as_bytes(); 465 b.len() == 10 466 && b.iter().enumerate().all(|(i, c)| if i == 4 || i == 7 { *c == b'-' } else { c.is_ascii_digit() }) 467 } 468 469 /// `rad:` and a base58 Radicle ID, as the page's RID pattern. 470 fn valid_rid(rid: &str) -> bool { 471 rid.strip_prefix("rad:z") 472 .is_some_and(|id| !id.is_empty() && id.bytes().all(|c| c.is_ascii_alphanumeric() && !matches!(c, b'0' | b'O' | b'I' | b'l'))) 473 } 474 475 /// An event or activity link: plain text (""), or a page on the forge, as the page's SOURCE_URL. 476 fn valid_source_link(url: &str) -> bool { 477 url.is_empty() 478 || url.strip_prefix(crate::forge::FORGE).and_then(|r| r.strip_prefix('/')).is_some_and(|path| { 479 path.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-' | b'/')) 480 && path.split('/').all(|seg| !seg.is_empty() && !seg.chars().all(|c| c == '.')) 481 }) 482 } 483 484 pub fn validate_snapshot(data: &Value) -> Result<(), String> { 485 let series = data.get("series").and_then(Value::as_array).filter(|a| !a.is_empty()); 486 let repos = data.get("repos").and_then(Value::as_array).filter(|a| !a.is_empty()); 487 let asof_ok = data.get("asof").and_then(Value::as_str).and_then(parse_time_ms).is_some(); 488 let (Some(series), Some(repos), true) = (series, repos, asof_ok) else { 489 return Err("Empty or invalid snapshot".into()); 490 }; 491 let mut prev = String::new(); 492 for row in series { 493 let date = row.get("date").and_then(Value::as_str).unwrap_or(""); 494 if !is_day(date) || date <= prev.as_str() { 495 return Err("Unordered snapshot dates".into()); 496 } 497 prev = date.to_string(); 498 let mut m = HashMap::new(); 499 for key in REQUIRED { 500 let n = safe_count(row.get(*key)).ok_or_else(|| format!("Missing or invalid metric: {key}"))?; 501 m.insert(*key, n); 502 } 503 if m["loc"] != m["source"] + m["test"] || m["merged"] > m["prs"] || m["testfiles"] > m["files"] { 504 return Err("Snapshot totals do not reconcile".into()); 505 } 506 let langs = row.get("langs").and_then(Value::as_object).ok_or("Language total mismatch")?; 507 let total: f64 = langs.values().map(|v| v.as_f64().unwrap_or(f64::NAN)).sum(); 508 if total != m["loc"] as f64 { 509 return Err("Language total mismatch".into()); 510 } 511 } 512 let latest = series.last().expect("non-empty"); 513 let summary = data.get("summary").ok_or("Summary differs from the latest snapshot: source")?; 514 for key in REQUIRED { 515 if summary.get(*key) != latest.get(*key) { 516 return Err(format!("Summary differs from the latest snapshot: {key}")); 517 } 518 } 519 let names: HashSet<&str> = repos.iter().filter_map(|r| r.get("name").and_then(Value::as_str)).collect(); 520 if names.len() != repos.len() { 521 return Err("Duplicate repositories".into()); 522 } 523 let sum = |key: &str| -> f64 { repos.iter().map(|r| r.get(key).and_then(Value::as_f64).unwrap_or(f64::NAN)).sum() }; 524 let summary_n = |key: &str| summary.get(key).and_then(Value::as_f64).unwrap_or(f64::NAN); 525 if summary_n("prs") != sum("prCount") { 526 return Err("PR totals do not reconcile".into()); 527 } 528 if summary_n("ci") != sum("ciCount") { 529 return Err("CI totals do not reconcile".into()); 530 } 531 let conclusions: f64 = data 532 .get("ciConclusions") 533 .and_then(Value::as_object) 534 .map(|o| o.values().map(|v| v.as_f64().unwrap_or(f64::NAN)).sum()) 535 .unwrap_or(f64::NAN); 536 if summary_n("ci") != conclusions { 537 return Err("CI conclusions do not reconcile".into()); 538 } 539 for repo in repos { 540 let head = repo.get("head").and_then(Value::as_str).unwrap_or(""); 541 if head.len() != 40 || !head.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) { 542 return Err("Missing pinned head".into()); 543 } 544 // Snapshots written before 2026-10-17 carry no link, and a repository with no Radicle 545 // copy carries none; a link that is present must be a forge or Radicle repository page. 546 if let Some(url) = repo.get("url") { 547 if !url.as_str().is_some_and(crate::forge::valid_repo_link) { 548 return Err("Invalid repository link".into()); 549 } 550 } 551 if let Some(rid) = repo.get("rid") { 552 if !rid.as_str().is_some_and(valid_rid) { 553 return Err("Invalid Radicle ID".into()); 554 } 555 } 556 // A recorded-only row has no Radicle copy, so it carries no link and no Radicle ID. 557 if let Some(day) = repo.get("recorded") { 558 if !day.as_str().is_some_and(is_day) || repo.get("url").is_some() || repo.get("rid").is_some() { 559 return Err("Invalid recorded repository".into()); 560 } 561 } 562 } 563 // The page refuses a dataset with any other link; refuse it here first. 564 for list in ["events", "activity"] { 565 for item in data.get(list).and_then(Value::as_array).into_iter().flatten() { 566 if !item.get("url").and_then(Value::as_str).is_some_and(valid_source_link) { 567 return Err(format!("Invalid {list} link")); 568 } 569 if let Some(rid) = item.get("rid") { 570 if !rid.as_str().is_some_and(valid_rid) { 571 return Err(format!("Invalid {list} Radicle ID")); 572 } 573 } 574 } 575 } 576 Ok(()) 577 } 578 579 // --------------------------------------------------------------------------------------------- 580 // Git: the Radicle storage and the objects inside it. 581 // --------------------------------------------------------------------------------------------- 582 583 fn git(dir: &Path, args: &[&str]) -> Result, String> { 584 let out = Command::new("git") 585 .arg(format!("--git-dir={}", dir.display())) 586 .args(args) 587 .output() 588 .map_err(|e| format!("cannot run git: {e}"))?; 589 if !out.status.success() { 590 return Err(format!("git {} failed in {}: {}", args.join(" "), dir.display(), String::from_utf8_lossy(&out.stderr).trim())); 591 } 592 Ok(out.stdout) 593 } 594 595 #[derive(Debug, Clone)] 596 struct Commit { 597 sha: String, 598 ts: i64, 599 date: String, 600 } 601 602 fn commits_at(dir: &Path, head: &str, first_parent: bool) -> Result, String> { 603 let mut args = vec!["log"]; 604 if first_parent { 605 args.push("--first-parent"); 606 } 607 args.extend(["--format=%H%x09%ct", head]); 608 let text = String::from_utf8(git(dir, &args)?).map_err(|_| "git log is not UTF-8")?; 609 text.lines() 610 .filter(|l| !l.is_empty()) 611 .map(|line| { 612 let (sha, ts) = line.split_once('\t').ok_or("Malformed git log line")?; 613 let ts: i64 = ts.parse().map_err(|_| "Malformed git log time")?; 614 Ok(Commit { sha: sha.to_string(), ts, date: day_ms(ts * 1000) }) 615 }) 616 .collect() 617 } 618 619 /// Parse `git cat-file --batch` output for `oids`, in order, storing each blob's line count. 620 pub fn read_blob_batch(mut out: R, oids: &[String], cache: &mut HashMap) -> Result<(), String> { 621 let mut header = Vec::new(); 622 let mut body = Vec::new(); 623 for oid in oids { 624 header.clear(); 625 out.read_until(b'\n', &mut header).map_err(|e| e.to_string())?; 626 if header.last() != Some(&b'\n') { 627 return Err("Truncated Git blob batch".into()); 628 } 629 let text = String::from_utf8_lossy(&header[..header.len() - 1]).to_string(); 630 let parts: Vec<&str> = text.split(' ').collect(); 631 let size = parts.get(2).and_then(|s| s.parse::().ok()); 632 let (Some(size), true) = (size, parts.len() == 3 && parts[0] == oid && parts[1] == "blob") else { 633 return Err("Malformed Git blob batch".into()); 634 }; 635 body.resize(size + 1, 0); 636 out.read_exact(&mut body).map_err(|_| "Malformed Git blob batch")?; 637 cache.insert(oid.clone(), physical_lines(&body[..size])); 638 } 639 Ok(()) 640 } 641 642 fn cat_blobs(dir: &Path, oids: &[String], cache: &mut HashMap) -> Result<(), String> { 643 let mut child = Command::new("git") 644 .arg(format!("--git-dir={}", dir.display())) 645 .args(["cat-file", "--batch"]) 646 .stdin(Stdio::piped()) 647 .stdout(Stdio::piped()) 648 .stderr(Stdio::piped()) 649 .spawn() 650 .map_err(|e| format!("cannot run git: {e}"))?; 651 let mut stdin = child.stdin.take().expect("piped"); 652 let input: String = oids.iter().map(|o| format!("{o}\n")).collect(); 653 let writer = std::thread::spawn(move || stdin.write_all(input.as_bytes())); 654 let parsed = read_blob_batch(BufReader::with_capacity(1 << 20, child.stdout.take().expect("piped")), oids, cache); 655 let wrote = writer.join().map_err(|_| "git cat-file writer panicked")?; 656 let status = child.wait().map_err(|e| e.to_string())?; 657 parsed?; 658 wrote.map_err(|e| format!("git cat-file input: {e}"))?; 659 if !status.success() { 660 return Err(format!("git cat-file failed in {}", dir.display())); 661 } 662 Ok(()) 663 } 664 665 /// Measured blobs of one tree. Trees are cached per repository and commit, blob line counts 666 /// per object id (identical content has an identical id in every repository). 667 fn read_entries( 668 repo: &Repo, 669 head: &str, 670 blobs: &mut HashMap, 671 trees: &mut HashMap>>, 672 ) -> Result>, String> { 673 let key = format!("{}:{}", repo.name, head); 674 if let Some(t) = trees.get(&key) { 675 return Ok(t.clone()); 676 } 677 let listing = git(&repo.dir, &["ls-tree", "-r", "-z", head])?; 678 let mut entries = Vec::new(); 679 for row in listing.split(|b| *b == 0) { 680 if row.is_empty() { 681 continue; 682 } 683 let row = String::from_utf8_lossy(row); 684 let (meta, file) = row.split_once('\t').ok_or("Malformed git ls-tree row")?; 685 let mut it = meta.split(' '); 686 let (mode, kind, oid) = (it.next().unwrap_or(""), it.next().unwrap_or(""), it.next().unwrap_or("")); 687 if kind == "blob" { 688 if let Some(spec) = classify(file, mode) { 689 entries.push(Entry { oid: oid.to_string(), kind: spec.kind, lang: spec.lang }); 690 } 691 } 692 } 693 let mut missing: Vec = Vec::new(); 694 let mut queued = HashSet::new(); 695 for e in &entries { 696 if !blobs.contains_key(&e.oid) && queued.insert(e.oid.clone()) { 697 missing.push(e.oid.clone()); 698 } 699 } 700 if !missing.is_empty() { 701 cat_blobs(&repo.dir, &missing, blobs)?; 702 } 703 let entries = Rc::new(entries); 704 trees.insert(key, entries.clone()); 705 Ok(entries) 706 } 707 708 // --------------------------------------------------------------------------------------------- 709 // Radicle: the storage, identities and patches, read locally through `rad`. 710 // --------------------------------------------------------------------------------------------- 711 712 /// The Radicle storage, where `rad` finds it: `$RAD_HOME/storage`, else `~/.radicle/storage`. 713 fn storage_dir() -> Result { 714 if let Some(home) = std::env::var_os("RAD_HOME") { 715 return Ok(PathBuf::from(home).join("storage")); 716 } 717 let home = std::env::var_os("HOME").ok_or("Neither RAD_HOME nor HOME is set")?; 718 Ok(PathBuf::from(home).join(".radicle/storage")) 719 } 720 721 fn rad(args: &[&str]) -> Result, String> { 722 let out = Command::new("rad") 723 .args(args) 724 .stdin(Stdio::null()) 725 .output() 726 .map_err(|e| format!("cannot run rad: {e}"))?; 727 if !out.status.success() { 728 return Err(format!("rad {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); 729 } 730 Ok(out.stdout) 731 } 732 733 fn is_oid(s: &str) -> bool { 734 s.len() == 40 && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) 735 } 736 737 /// The merge of a merged patch. 738 #[derive(Debug, Clone, PartialEq)] 739 struct Merge { 740 ms: i64, 741 day: String, 742 commit: String, 743 } 744 745 /// A Radicle patch, as `rad cob show --format json` prints it. 746 #[derive(Debug, Clone, PartialEq)] 747 struct Patch { 748 id: String, 749 title: Value, 750 /// draft, open, archived or merged. 751 status: String, 752 created_ms: i64, 753 created_day: String, 754 merge: Option, 755 } 756 757 /// Parse one patch. A patch's ID is the ID of its root revision, and it was opened at that 758 /// revision's time. A merged patch was merged when the commit its state names was merged (the 759 /// earliest such merge when several delegates merged it). 760 fn parse_patch(id: &str, v: &Value) -> Result { 761 let bad = |what: &str| format!("Patch {id}: {what}"); 762 if !is_oid(id) { 763 return Err(bad("invalid ID")); 764 } 765 let created_ms = v 766 .get("revisions") 767 .and_then(|r| r.get(id)) 768 .and_then(|r| r.get("timestamp")) 769 .and_then(Value::as_i64) 770 .filter(|t| *t > 0) 771 .ok_or_else(|| bad("no root revision"))?; 772 let status = v.pointer("/state/status").and_then(Value::as_str).ok_or_else(|| bad("no state"))?.to_string(); 773 if !matches!(status.as_str(), "draft" | "open" | "archived" | "merged") { 774 return Err(bad("unknown state")); 775 } 776 let merge = if status == "merged" { 777 let commit = v.pointer("/state/commit").and_then(Value::as_str).filter(|c| is_oid(c)).ok_or_else(|| bad("merged without a commit"))?; 778 let ms = v 779 .get("merges") 780 .and_then(Value::as_object) 781 .into_iter() 782 .flatten() 783 .filter(|(_, m)| m.get("commit").and_then(Value::as_str) == Some(commit)) 784 .filter_map(|(_, m)| m.get("timestamp").and_then(Value::as_i64)) 785 .filter(|t| *t > 0) 786 .min() 787 .ok_or_else(|| bad("merged without a merge record"))?; 788 Some(Merge { ms, day: day_ms(ms), commit: commit.to_string() }) 789 } else { 790 None 791 }; 792 Ok(Patch { id: id.to_string(), title: v.get("title").cloned().unwrap_or(Value::Null), status, created_ms, created_day: day_ms(created_ms), merge }) 793 } 794 795 /// Every patch of a repository, read from the local storage. 796 fn read_patches(rid: &str) -> Result, String> { 797 let repo = format!("rad:{rid}"); 798 let list = String::from_utf8(rad(&["cob", "list", "--repo", &repo, "--type", PATCH_TYPE])?).map_err(|_| "rad cob list is not UTF-8")?; 799 let ids: Vec<&str> = list.split_whitespace().collect(); 800 let mut patches = Vec::with_capacity(ids.len()); 801 for chunk in ids.chunks(64) { 802 let mut args = vec!["cob", "show", "--repo", repo.as_str(), "--type", PATCH_TYPE, "--format", "json"]; 803 for id in chunk { 804 args.extend(["--object", id]); 805 } 806 let text = String::from_utf8(rad(&args)?).map_err(|_| "rad cob show is not UTF-8")?; 807 let rows: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect(); 808 if rows.len() != chunk.len() { 809 return Err(format!("rad cob show printed {} of {} patches of {repo}", rows.len(), chunk.len())); 810 } 811 // One JSON object per line, in the order asked; parse_patch checks each against its ID. 812 for (id, row) in chunk.iter().zip(rows) { 813 let v: Value = serde_json::from_str(row).map_err(|e| format!("rad cob show sent bad JSON for {id}: {e}"))?; 814 patches.push(parse_patch(id, &v)?); 815 } 816 } 817 Ok(patches) 818 } 819 820 // --------------------------------------------------------------------------------------------- 821 // The GitHub-era record. 822 // --------------------------------------------------------------------------------------------- 823 824 /// The pull request and Actions figures GitHub held up to the move, as collected then. 825 struct GithubEra { 826 /// Its last day; Radicle patches count only after it. 827 last: String, 828 /// Per day: prs, merged, ci, ciDaily. 829 days: BTreeMap, 830 ci_conclusions: BTreeMap, 831 /// Repository rows as collected then. 832 repos: Vec, 833 activity: Vec, 834 } 835 836 impl GithubEra { 837 fn day(&self, date: &str) -> Result<[u64; 4], String> { 838 match self.days.get(date) { 839 Some(d) => Ok(*d), 840 None if self.days.keys().next().is_some_and(|first| date < first.as_str()) => Ok([0; 4]), 841 None => Err(format!("The GitHub-era record has no day {date}")), 842 } 843 } 844 845 fn row(&self, name: &str) -> Option<&Value> { 846 self.repos.iter().find(|r| r.get("name").and_then(Value::as_str) == Some(name)) 847 } 848 } 849 850 /// Read the record and check that it reconciles with itself. 851 fn github_era(text: &str) -> Result { 852 let v: Value = serde_json::from_str(text).map_err(|e| format!("The GitHub-era record is not JSON: {e}"))?; 853 let last = s(&v, "last").filter(|d| is_day(d)).ok_or("The GitHub-era record has no last day")?; 854 let mut days = BTreeMap::new(); 855 for row in v.get("series").and_then(Value::as_array).ok_or("The GitHub-era record has no series")? { 856 let date = s(row, "date").filter(|d| is_day(d) && *d <= last).ok_or("Invalid GitHub-era day")?; 857 let n = |k: &str| safe_count(row.get(k)).ok_or_else(|| format!("Invalid GitHub-era {k} on {date}")); 858 let day = [n("prs")?, n("merged")?, n("ci")?, n("ciDaily")?]; 859 if day[1] > day[0] || days.insert(date.clone(), day).is_some() { 860 return Err(format!("Invalid GitHub-era day {date}")); 861 } 862 } 863 let end = *days.get(&last).ok_or("The GitHub-era record lacks its last day")?; 864 let ci_conclusions: BTreeMap = 865 serde_json::from_value(v.get("ciConclusions").cloned().unwrap_or(Value::Null)).map_err(|_| "Invalid GitHub-era CI conclusions")?; 866 let repos = v.get("repos").and_then(Value::as_array).cloned().ok_or("The GitHub-era record has no repositories")?; 867 let sum = |k: &str| repos.iter().map(|r| safe_count(r.get(k))).sum::>(); 868 if sum("prCount") != Some(end[0]) || sum("mergedCount") != Some(end[1]) || sum("ciCount") != Some(end[2]) || ci_conclusions.values().sum::() != end[2] { 869 return Err("The GitHub-era record does not reconcile".into()); 870 } 871 let activity = serde_json::from_value(v.get("activity").cloned().unwrap_or_else(|| Value::Array(vec![]))) 872 .map_err(|e| format!("Invalid GitHub-era activity: {e}"))?; 873 Ok(GithubEra { last, days, ci_conclusions, repos, activity }) 874 } 875 876 // --------------------------------------------------------------------------------------------- 877 // Collection. 878 // --------------------------------------------------------------------------------------------- 879 880 #[derive(Debug, Clone)] 881 struct Repo { 882 name: String, 883 repo: String, 884 rid: &'static str, 885 dir: PathBuf, 886 head: String, 887 branch: String, 888 commits: Vec, 889 fp: Vec, 890 patches: Vec, 891 group: &'static str, 892 first: String, 893 last: String, 894 } 895 896 #[derive(Serialize)] 897 struct Row { 898 date: String, 899 #[serde(flatten)] 900 size: Size, 901 langs: BTreeMap, 902 loc: u64, 903 repos: u64, 904 commits: u64, 905 daily: u64, 906 prs: u64, 907 merged: u64, 908 ci: u64, 909 #[serde(rename = "ciDaily")] 910 ci_daily: u64, 911 } 912 913 #[derive(Serialize)] 914 struct Summary { 915 #[serde(flatten)] 916 size: Size, 917 loc: u64, 918 repos: u64, 919 commits: u64, 920 daily: u64, 921 prs: u64, 922 merged: u64, 923 ci: u64, 924 #[serde(rename = "ciDaily")] 925 ci_daily: u64, 926 active: u64, 927 archived: u64, 928 } 929 930 #[derive(Serialize, Deserialize)] 931 #[serde(rename_all = "camelCase")] 932 struct PublicRepo { 933 name: String, 934 #[serde(default, skip_serializing_if = "Option::is_none")] 935 url: Option, 936 #[serde(default, skip_serializing_if = "Option::is_none")] 937 rid: Option, 938 /// For a GitHub-era repository that is not on the public Radicle table: the last day of the 939 /// GitHub record its figures come from. Such a row is carried as recorded and not measured. 940 #[serde(default, skip_serializing_if = "Option::is_none")] 941 recorded: Option, 942 head: String, 943 branch: String, 944 first: String, 945 last: String, 946 archived: bool, 947 group: String, 948 size: Size, 949 langs: BTreeMap, 950 revisions: u64, 951 pr_count: u64, 952 merged_count: u64, 953 ci_count: u64, 954 } 955 956 #[derive(Serialize, Deserialize)] 957 struct Activity { 958 repo: String, 959 title: Value, 960 number: Value, 961 url: String, 962 #[serde(default, skip_serializing_if = "Option::is_none")] 963 rid: Option, 964 state: String, 965 date: String, 966 timestamp: String, 967 } 968 969 #[derive(Serialize)] 970 #[serde(rename_all = "camelCase")] 971 struct Snapshot { 972 schema_version: u32, 973 asof: String, 974 timezone: &'static str, 975 first: String, 976 last: String, 977 series: Vec, 978 summary: Summary, 979 ci_conclusions: BTreeMap, 980 repos: Vec, 981 events: Value, 982 activity: Vec, 983 source_policy: String, 984 commit_policy: String, 985 } 986 987 pub struct Options { 988 /// The dataset to replace; its curated events are kept. 989 pub output: PathBuf, 990 /// Measurement cutoff (RFC 3339). Default: the moment the history has been read. 991 pub asof: Option, 992 } 993 994 pub struct Report { 995 pub repos: usize, 996 pub loc: u64, 997 pub commits: u64, 998 pub prs: u64, 999 pub patches: u64, 1000 pub ci: u64, 1001 pub asof: String, 1002 } 1003 1004 fn s(v: &Value, key: &str) -> Option { 1005 v.get(key).and_then(Value::as_str).map(str::to_string) 1006 } 1007 1008 /// Run `f` over `items` with at most `limit` at a time, keeping order. Stops taking new items 1009 /// after the first failure and returns that failure. 1010 fn limited(items: &[T], limit: usize, f: impl Fn(&T) -> Result + Sync) -> Result, String> { 1011 let next = AtomicUsize::new(0); 1012 let failed = AtomicBool::new(false); 1013 let results: Vec>>> = items.iter().map(|_| Mutex::new(None)).collect(); 1014 std::thread::scope(|scope| { 1015 for _ in 0..limit.min(items.len()) { 1016 scope.spawn(|| loop { 1017 if failed.load(Ordering::Relaxed) { 1018 break; 1019 } 1020 let i = next.fetch_add(1, Ordering::Relaxed); 1021 if i >= items.len() { 1022 break; 1023 } 1024 let r = f(&items[i]); 1025 if r.is_err() { 1026 failed.store(true, Ordering::Relaxed); 1027 } 1028 *results[i].lock().expect("unpoisoned") = Some(r); 1029 }); 1030 } 1031 }); 1032 let mut out = Vec::with_capacity(items.len()); 1033 for r in results { 1034 match r.into_inner().expect("unpoisoned") { 1035 Some(Ok(v)) => out.push(v), 1036 Some(Err(e)) => return Err(e), 1037 None => {} 1038 } 1039 } 1040 if out.len() != items.len() { 1041 return Err("Repository collection stopped early".into()); 1042 } 1043 Ok(out) 1044 } 1045 1046 fn valid_repo_name(name: &str) -> bool { 1047 !name.is_empty() && name.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-')) 1048 } 1049 1050 /// Normal Git history cannot place a commit after the moment it was measured. 1051 fn refuse_future(name: &str, commits: &[Commit], cutoff: i64) -> Result<(), String> { 1052 if commits.iter().any(|c| c.ts.saturating_mul(1000) > cutoff) { 1053 return Err(format!("Pinned repository contains a future-dated commit: {name}")); 1054 } 1055 Ok(()) 1056 } 1057 1058 /// Read one repository from the storage: the canonical default branch (Radicle keeps it at the 1059 /// delegates' branch), its history, and its patches. 1060 fn collect_repo(target: &Target, storage: &Path, cutoff: i64) -> Result { 1061 let Target { name, repo, rid, branch } = target; 1062 if !valid_repo_name(name) || !valid_repo_name(repo) || !valid_branch(branch) { 1063 return Err("Invalid repository identity".into()); 1064 } 1065 let payload: Value = serde_json::from_slice(&rad(&["inspect", &format!("rad:{rid}"), "--payload"])?) 1066 .map_err(|e| format!("rad inspect sent bad JSON for {repo}: {e}"))?; 1067 let declared = payload.pointer("/xyz.radicle.project/defaultBranch").and_then(Value::as_str); 1068 if declared != Some(branch.as_str()) { 1069 return Err(format!("{repo}: the identity names default branch {declared:?}, the public table {branch}")); 1070 } 1071 let dir = storage.join(rid); 1072 let head = String::from_utf8_lossy(&git(&dir, &["rev-parse", "--verify", &format!("refs/heads/{branch}^{{commit}}")])?).trim().to_string(); 1073 if !is_oid(&head) { 1074 return Err(format!("{repo}: no canonical {branch} in {}", dir.display())); 1075 } 1076 let commits = commits_at(&dir, &head, false)?; 1077 let fp = commits_at(&dir, &head, true)?; 1078 refuse_future(name, &commits, cutoff)?; 1079 let patches = read_patches(rid)?; 1080 let first = commits.iter().map(|c| c.date.as_str()).fold("9999-12-31", |a, b| if b < a { b } else { a }).to_string(); 1081 let last = commits.iter().map(|c| c.date.as_str()).fold("0000-01-01", |a, b| if b > a { b } else { a }).to_string(); 1082 Ok(Repo { 1083 name: name.clone(), 1084 repo: repo.clone(), 1085 rid: *rid, 1086 dir, 1087 head, 1088 branch: branch.clone(), 1089 commits, 1090 fp, 1091 patches, 1092 group: group_of(name, false), 1093 first, 1094 last, 1095 }) 1096 } 1097 1098 /// The row of a GitHub-era repository that is not on the public Radicle table: its recorded 1099 /// figures, archived flag and group exactly as collected, marked with the record's last day. 1100 /// It has no forge link or Radicle ID, since it has no Radicle copy. 1101 fn carried_row(row: &Value, last: &str) -> Result { 1102 let mut carried: PublicRepo = 1103 serde_json::from_value(row.clone()).map_err(|e| format!("Invalid GitHub-era repository {:?}: {e}", row.get("name")))?; 1104 carried.url = None; 1105 carried.rid = None; 1106 carried.recorded = Some(last.to_string()); 1107 Ok(carried) 1108 } 1109 1110 /// Where the rules of this file are stated for readers of the dataset. 1111 fn policies(era: &GithubEra) -> (String, String) { 1112 let last = &era.last; 1113 let source = format!( 1114 "Physical lines including blanks/comments in listed source extensions at each repository's pinned canonical default branch in the Radicle storage. \ 1115 The repositories are the public repository table (data/public-repos.md) under their project names; private, withdrawn and local-only repositories are never read. \ 1116 Excludes evidence, receipts, data, results, fixture directories, generated/build/vendor trees and symlinks. \ 1117 Exact matching blobs deduplicated across repositories at each snapshot; similar migrated copies may remain. \ 1118 Test footprint uses file-path naming, not executed test count. \ 1119 Rows with a recorded day are GitHub-era repositories that are not on the public Radicle table: their figures, archived flag and group are the last GitHub collection ({last}), carried unchanged; they are not measured now and not part of the daily series." 1120 ); 1121 let commit = format!( 1122 "Unique commit SHAs reachable from each pinned default branch, including merge commits. \ 1123 Daily timestamps use committer date, America/Chicago. Snapshots use first-parent state at each day end. \ 1124 Pre-import/unrecorded work cannot be reconstructed. \ 1125 Pull requests: up to {last}, the GitHub pull request record exactly as collected then (it includes repositories no longer read); \ 1126 after {last}, the Radicle patches of the repositories read, in every state, a merged patch counted on its merge day and linked to its merge commit on the forge. \ 1127 CI: the GitHub Actions record up to {last}, exactly as collected then. Radicle keeps no CI record, so no runs are counted after {last}." 1128 ); 1129 (source, commit) 1130 } 1131 1132 pub fn collect(opts: &Options) -> Result { 1133 let mut cutoff = match &opts.asof { 1134 Some(a) => parse_time_ms(a).ok_or("Invalid measurement cutoff")?, 1135 None => i64::MAX, 1136 }; 1137 let existing: Value = serde_json::from_str( 1138 &std::fs::read_to_string(&opts.output).map_err(|e| format!("cannot read the existing {}: {e}", opts.output.display()))?, 1139 ) 1140 .map_err(|e| format!("{} is not JSON: {e}", opts.output.display()))?; 1141 let mut era = github_era(GITHUB_ERA)?; 1142 let era_activity = std::mem::take(&mut era.activity); 1143 let (source_policy, commit_policy) = policies(&era); 1144 let storage = storage_dir()?; 1145 1146 let (targets, missing) = select_targets(&table_rows(TABLE)); 1147 for m in &missing { 1148 eprintln!("Warning: a named project repository is not on the public Radicle table, skipping: {m}"); 1149 } 1150 let started = std::time::Instant::now(); 1151 let repos = limited(&targets, 4, |target| collect_repo(target, &storage, cutoff))?; 1152 println!(" [PROGRESS] read {} repositories (git history, patches) from {} in {:.2?}", repos.len(), storage.display(), started.elapsed()); 1153 1154 let asof = match &opts.asof { 1155 Some(a) => a.clone(), 1156 None => { 1157 let a = iso_ms(now_ms()); 1158 cutoff = parse_time_ms(&a).ok_or("Invalid measurement cutoff")?; 1159 a 1160 } 1161 }; 1162 for r in &repos { 1163 refuse_future(&r.name, &r.commits, cutoff)?; 1164 } 1165 let first = repos.iter().map(|r| r.first.as_str()).fold("9999-12-31", |a, b| if b < a { b } else { a }).to_string(); 1166 let last = day_ms(cutoff); 1167 let first_days = parse_time_ms(&first).ok_or("Invalid first day")?.div_euclid(86_400_000); 1168 let last_days = parse_time_ms(&last).ok_or("Invalid last day")?.div_euclid(86_400_000); 1169 if last_days - first_days + 1 > 10_000 { 1170 return Err("Unexpected historical range".into()); 1171 } 1172 let dates: Vec = (first_days..=last_days).map(ymd).collect(); 1173 1174 let mut blobs: HashMap = HashMap::new(); 1175 let mut trees: HashMap>> = HashMap::new(); 1176 // Distinct commit SHAs across every repository, by Chicago day. 1177 let mut commit_days: HashMap<&str, &str> = HashMap::new(); 1178 for r in &repos { 1179 for c in &r.commits { 1180 commit_days.insert(&c.sha, &c.date); 1181 } 1182 } 1183 let mut commit_dates: Vec<&str> = commit_days.into_values().collect(); 1184 commit_dates.sort_unstable(); 1185 // Patches count after the GitHub-era record ends, merges up to the cutoff. 1186 let counted = |p: &Patch| p.created_day > era.last && p.created_ms <= cutoff; 1187 let merge_of = |p: &Patch| p.merge.as_ref().filter(|m| m.ms <= cutoff).map(|m| m.day.clone()); 1188 let all_patches: Vec<&Patch> = repos.iter().flat_map(|r| r.patches.iter()).filter(|p| counted(p)).collect(); 1189 let end = era.day(&era.last)?; 1190 1191 let mut series = Vec::with_capacity(dates.len()); 1192 for date in &dates { 1193 let mut seen = HashSet::new(); 1194 let mut total = Counts::default(); 1195 let mut number = 0; 1196 for r in &repos { 1197 let Some(candidate) = r.fp.iter().find(|c| c.date.as_str() <= date.as_str()) else { continue }; 1198 number += 1; 1199 let entries = read_entries(r, &candidate.sha, &mut blobs, &mut trees)?; 1200 total.add(&count_entries(&entries, &blobs, &mut seen)?); 1201 } 1202 let upto = commit_dates.partition_point(|d| *d <= date.as_str()); 1203 let before = commit_dates.partition_point(|d| *d < date.as_str()); 1204 let [prs, merged, ci, ci_daily] = if *date <= era.last { 1205 era.day(date)? 1206 } else { 1207 let opened = all_patches.iter().filter(|p| p.created_day <= *date).count() as u64; 1208 let landed = all_patches.iter().filter(|p| merge_of(p).is_some_and(|d| d <= *date)).count() as u64; 1209 [end[0] + opened, end[1] + landed, end[2], 0] 1210 }; 1211 series.push(Row { 1212 date: date.clone(), 1213 loc: total.size.source + total.size.test, 1214 size: total.size, 1215 langs: total.langs, 1216 repos: number, 1217 commits: upto as u64, 1218 daily: (upto - before) as u64, 1219 prs, 1220 merged, 1221 ci, 1222 ci_daily, 1223 }); 1224 } 1225 println!(" [PROGRESS] measured {} daily snapshots in {:.2?}", series.len(), started.elapsed()); 1226 1227 let mut public_repos = Vec::with_capacity(repos.len() + era.repos.len()); 1228 for r in &repos { 1229 let entries = read_entries(r, &r.head, &mut blobs, &mut trees)?; 1230 let counts = count_entries(&entries, &blobs, &mut HashSet::new())?; 1231 let before = |k: &str| era.row(&r.name).and_then(|row| safe_count(row.get(k))).unwrap_or(0); 1232 let mine: Vec<&Patch> = r.patches.iter().filter(|p| counted(p)).collect(); 1233 public_repos.push(PublicRepo { 1234 name: r.name.clone(), 1235 url: crate::forge::repo_url(&r.repo), 1236 rid: Some(format!("rad:{}", r.rid)), 1237 recorded: None, 1238 head: r.head.clone(), 1239 branch: r.branch.clone(), 1240 first: r.first.clone(), 1241 last: r.last.clone(), 1242 archived: false, 1243 group: r.group.to_string(), 1244 size: counts.size, 1245 langs: counts.langs, 1246 revisions: r.commits.len() as u64, 1247 pr_count: before("prCount") + mine.len() as u64, 1248 merged_count: before("mergedCount") + mine.iter().filter(|p| merge_of(p).is_some()).count() as u64, 1249 ci_count: before("ciCount"), 1250 }); 1251 } 1252 // A GitHub-era repository that is not read any more keeps its recorded row. 1253 for row in &era.repos { 1254 let name = s(row, "name").ok_or("A GitHub-era repository has no name")?; 1255 if !repos.iter().any(|r| r.name == name) { 1256 public_repos.push(carried_row(row, &era.last)?); 1257 } 1258 } 1259 public_repos.sort_by_key(|r| std::cmp::Reverse(r.size.source + r.size.test)); 1260 1261 let latest = series.last().ok_or("Empty or invalid snapshot")?; 1262 let active = public_repos.iter().filter(|r| !r.archived).count() as u64; 1263 let summary = Summary { 1264 size: latest.size.clone(), 1265 loc: latest.loc, 1266 repos: latest.repos, 1267 commits: latest.commits, 1268 daily: latest.daily, 1269 prs: latest.prs, 1270 merged: latest.merged, 1271 ci: latest.ci, 1272 ci_daily: latest.ci_daily, 1273 active, 1274 archived: public_repos.len() as u64 - active, 1275 }; 1276 1277 let mut activity: Vec<(i64, Activity)> = Vec::new(); 1278 for a in era_activity { 1279 let ms = parse_time_ms(&a.timestamp).ok_or_else(|| format!("Invalid timestamp: {}", a.timestamp))?; 1280 activity.push((ms, a)); 1281 } 1282 for r in &repos { 1283 for p in r.patches.iter().filter(|p| counted(p)) { 1284 let (state, ms, url, rid) = match (&p.merge, p.status.as_str()) { 1285 (Some(m), _) if m.ms <= cutoff => { 1286 let repo_url = crate::forge::repo_url(&r.repo).ok_or("A read repository is not on the forge")?; 1287 ("Merged", m.ms, format!("{repo_url}/commit/{}", m.commit), Some(format!("rad:{}", r.rid))) 1288 } 1289 (_, "open") => ("Open", p.created_ms, String::new(), None), 1290 (_, "draft") => ("Draft", p.created_ms, String::new(), None), 1291 _ => continue, 1292 }; 1293 let activity_row = Activity { 1294 repo: r.name.clone(), 1295 title: p.title.clone(), 1296 number: Value::from(&p.id[..7]), 1297 url, 1298 rid, 1299 state: state.to_string(), 1300 date: day_ms(ms), 1301 timestamp: iso_ms(ms), 1302 }; 1303 activity.push((ms, activity_row)); 1304 } 1305 } 1306 activity.sort_by_key(|a| std::cmp::Reverse(a.0)); 1307 let activity: Vec = activity.into_iter().take(12).map(|(_, a)| a).collect(); 1308 1309 let events = existing.get("events").filter(|e| truthy(e)).cloned().unwrap_or_else(|| Value::Array(vec![])); 1310 let snapshot = Snapshot { 1311 schema_version: 2, 1312 asof: asof.clone(), 1313 timezone: TIMEZONE, 1314 first, 1315 last, 1316 series, 1317 summary, 1318 ci_conclusions: era.ci_conclusions.clone(), 1319 repos: public_repos, 1320 events, 1321 activity, 1322 source_policy, 1323 commit_policy, 1324 }; 1325 let value = serde_json::to_value(&snapshot).map_err(|e| e.to_string())?; 1326 validate_snapshot(&value)?; 1327 1328 if let Some(parent) = opts.output.parent().filter(|p| !p.as_os_str().is_empty()) { 1329 std::fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?; 1330 } 1331 let tmp = PathBuf::from(format!("{}.tmp", opts.output.display())); 1332 let text = serde_json::to_string(&snapshot).map_err(|e| e.to_string())?; 1333 std::fs::write(&tmp, text).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; 1334 std::fs::rename(&tmp, &opts.output).map_err(|e| format!("cannot replace {}: {e}", opts.output.display()))?; 1335 Ok(Report { 1336 repos: repos.len(), 1337 loc: snapshot.summary.loc, 1338 commits: snapshot.summary.commits, 1339 prs: snapshot.summary.prs, 1340 patches: all_patches.len() as u64, 1341 ci: snapshot.summary.ci, 1342 asof, 1343 }) 1344 } 1345 1346 /// JavaScript truthiness for a JSON value (`existing.events || []`). 1347 fn truthy(v: &Value) -> bool { 1348 match v { 1349 Value::Null => false, 1350 Value::Bool(b) => *b, 1351 Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()), 1352 Value::String(s) => !s.is_empty(), 1353 _ => true, 1354 } 1355 } 1356 1357 #[cfg(test)] 1358 mod tests { 1359 use super::*; 1360 1361 fn kind(file: &str) -> Option { 1362 classify(file, "100644").map(|s| s.kind) 1363 } 1364 1365 #[test] 1366 fn measurement_boundaries_keep_named_tests_and_exclude_evidence_third_party_and_symlinks() { 1367 assert_eq!(kind("src/runtime/main.c"), Some(Kind::Source)); 1368 assert_eq!(kind("tests/compiler/check.inc"), Some(Kind::Test)); 1369 assert_eq!(kind("src/lib.rs"), Some(Kind::Source)); 1370 for p in ["vendor/d3.js", "public/vendor/d3.js", "evidence/old.c", "tests/fixtures/sample.rs", "data/generated.c"] { 1371 assert_eq!(classify(p, "100644"), None, "{p}"); 1372 } 1373 assert_eq!(classify("alias.c", "120000"), None); 1374 assert_eq!(classify("scripts/collect-progress.mjs", "100644").map(|s| s.lang), Some("Web")); 1375 } 1376 1377 #[test] 1378 fn test_path_and_extension_rules_match_the_former_regular_expressions() { 1379 for p in ["src/foo_test.rs", "src/test_foo.py", "Tests/x.c", "a/test.c", "a/tests.rs", "web/app.spec.ts", "web/App.TEST.js", "x/unit_tests/y.rs", "x/my_tests.c"] { 1380 assert_eq!(kind(p), Some(Kind::Test), "{p}"); 1381 } 1382 for p in ["src/testing.rs", "src/contest.rs", "src/latest/x.rs", "src/attest_x.c"] { 1383 assert_eq!(kind(p), Some(Kind::Source), "{p}"); 1384 } 1385 assert_eq!(classify("Build/x.c", "100644"), None); 1386 assert_eq!(classify("README.md", "100644").map(|s| s.lang), Some("Docs")); 1387 assert_eq!(classify("docs/Notes.TXT", "100644").map(|s| s.kind), Some(Kind::Docs)); 1388 assert_eq!(classify("LICENSE.md", "100644"), None); 1389 assert_eq!(classify("third-party/NOTICE.txt", "100644"), None); 1390 assert_eq!(classify(".bashrc", "100644"), None); 1391 assert_eq!(classify("boot/start.S", "100644").map(|s| s.lang), Some("Assembly")); 1392 assert_eq!(classify("photo.PNG", "100644"), None); 1393 assert_eq!(extname("a/..x"), ".x"); 1394 assert_eq!(extname(".."), ""); 1395 assert_eq!(extname("a/b.tar.gz"), ".gz"); 1396 } 1397 1398 #[test] 1399 fn physical_lines_handle_empty_unterminated_and_binary_blobs() { 1400 assert_eq!(physical_lines(b""), 0); 1401 assert_eq!(physical_lines(b"x"), 1); 1402 assert_eq!(physical_lines(b"x\n"), 1); 1403 assert_eq!(physical_lines(b"x\n\n"), 2); 1404 assert_eq!(physical_lines(&[65, 0, 10]), 0); 1405 } 1406 1407 #[test] 1408 fn the_shared_blob_set_prevents_double_counting_migrated_files_across_repositories() { 1409 let lines: HashMap = [("shared".to_string(), 10), ("test".to_string(), 5)].into_iter().collect(); 1410 let entry = |oid: &str, kind, lang| Entry { oid: oid.into(), kind, lang }; 1411 let mut seen = HashSet::new(); 1412 let a = count_entries(&[entry("shared", Kind::Source, "C")], &lines, &mut seen).unwrap(); 1413 let b = count_entries(&[entry("shared", Kind::Source, "C"), entry("test", Kind::Test, "Rust")], &lines, &mut seen).unwrap(); 1414 assert_eq!(a.size.source + b.size.source, 10); 1415 assert_eq!(b.size.test, 5); 1416 assert_eq!(b.size.files, 1); 1417 assert!(count_entries(&[entry("missing", Kind::Test, "C")], &lines, &mut HashSet::new()).is_err()); 1418 } 1419 1420 /// The America/Chicago calendar day of an RFC 3339 timestamp. 1421 fn day(timestamp: &str) -> Result { 1422 parse_time_ms(timestamp).map(day_ms).ok_or_else(|| format!("Invalid timestamp: {timestamp}")) 1423 } 1424 1425 #[test] 1426 fn daily_boundaries_use_chicago_rather_than_utc_including_daylight_saving_time() { 1427 assert_eq!(day("2026-10-01T03:00:00Z").unwrap(), "2026-09-30"); 1428 assert_eq!(day("2026-12-01T05:30:00Z").unwrap(), "2026-11-30"); 1429 // The switches themselves: 2026-03-08 08:00 UTC and 2026-11-01 07:00 UTC. 1430 let at = |t: &str| chicago_offset(parse_time_ms(t).unwrap() / 1000) / 3600; 1431 assert_eq!(at("2026-03-08T07:59:59Z"), -6); 1432 assert_eq!(at("2026-03-08T08:00:00Z"), -5); 1433 assert_eq!(at("2026-11-01T06:59:59Z"), -5); 1434 assert_eq!(at("2026-11-01T07:00:00Z"), -6); 1435 assert_eq!(at("2027-03-14T08:00:00Z"), -5); 1436 assert_eq!(at("2006-04-02T08:00:00Z"), -5); 1437 assert_eq!(at("2006-10-29T07:00:00Z"), -6); 1438 assert_eq!(day("2026-10-01T05:00:00Z").unwrap(), "2026-10-01"); 1439 assert_eq!(day("2026-12-01T06:00:00Z").unwrap(), "2026-12-01"); 1440 } 1441 1442 #[test] 1443 fn timestamps_parse_and_print_like_javascript() { 1444 assert_eq!(parse_time_ms("1970-01-01T00:00:00Z"), Some(0)); 1445 assert_eq!(parse_time_ms("2026-10-01T19:37:24.600923+00:00"), parse_time_ms("2026-10-01T19:37:24.600Z")); 1446 assert_eq!(parse_time_ms("2026-10-01T14:37:24-05:00"), parse_time_ms("2026-10-01T19:37:24Z")); 1447 assert_eq!(parse_time_ms("2026-10-16"), parse_time_ms("2026-10-16T00:00:00Z")); 1448 for bad in ["", "main", "2026-02-30T00:00:00Z", "2026-10-01T19:37:24", "2026-10-01T25:00:00Z"] { 1449 assert_eq!(parse_time_ms(bad), None, "{bad}"); 1450 } 1451 let t = parse_time_ms("2026-10-16T17:04:05.123Z").unwrap(); 1452 assert_eq!(iso_ms(t), "2026-10-16T17:04:05.123Z"); 1453 assert_eq!(ymd(days_from_civil(2024, 2, 29)), "2024-02-29"); 1454 } 1455 1456 #[test] 1457 fn blob_batches_are_read_in_order_and_malformed_batches_refused() { 1458 let oids = vec!["a".to_string(), "b".to_string()]; 1459 let mut cache = HashMap::new(); 1460 read_blob_batch(&b"a blob 4\nx\ny\n\nb blob 0\n\n"[..], &oids, &mut cache).unwrap(); 1461 assert_eq!(cache["a"], 2); 1462 assert_eq!(cache["b"], 0); 1463 assert!(read_blob_batch(&b"a missing\n"[..], &oids, &mut HashMap::new()).is_err()); 1464 assert!(read_blob_batch(&b"a blob 9\nshort"[..], &oids, &mut HashMap::new()).is_err()); 1465 assert!(read_blob_batch(&b"b blob 0\n\n"[..], &oids, &mut HashMap::new()).is_err()); 1466 } 1467 1468 #[test] 1469 fn repository_names_follow_the_project_rule() { 1470 for n in ["aien-edge", "aienos", "aienos.com", "omega", "omega-mv", "spark-hive", "crumb-spec", "atlas"] { 1471 assert!(project_named(n), "{n}"); 1472 } 1473 for n in ["omegaman", "aien", "forgery", "physicsx", "cortex", "sparky"] { 1474 assert!(!project_named(n), "{n}"); 1475 } 1476 } 1477 1478 fn find<'a>(targets: &'a [Target], name: &str) -> &'a Target { 1479 targets.iter().find(|t| t.name == name).unwrap_or_else(|| panic!("{name} not selected")) 1480 } 1481 1482 fn row(repo: &str, rid: &'static str) -> (String, &'static str, String) { 1483 (repo.to_string(), rid, "main".to_string()) 1484 } 1485 1486 #[test] 1487 fn the_public_radicle_table_maps_to_project_names() { 1488 let rows = table_rows(TABLE); 1489 let (targets, missing) = select_targets(&rows); 1490 assert!(missing.is_empty(), "missing: {missing:?}"); 1491 // Every named repository is read from its Radicle copy under its project name. 1492 for (project, repo) in REPOS { 1493 let t = find(&targets, project); 1494 assert_eq!(t.repo, *repo); 1495 assert_eq!(Some(t.rid), crate::forge::rid(repo), "{project}"); 1496 assert_eq!(t.branch, "main"); 1497 } 1498 assert_eq!(find(&targets, "omega").rid, "z6do9WDBhuSnvopDkgFdFr1yWA62"); 1499 for core in ["aien-sovereign-core", "aienux", "omega", "physics", "aien-protocols", "aien-architecture", "benchmarks"] { 1500 assert_eq!(group_of(core, false), "Core", "{core}"); 1501 } 1502 assert_eq!(group_of("aienos.com", false), "Sites"); 1503 // The name rule finds the other project repositories of the table and nothing else. 1504 let mut names: Vec<&str> = targets.iter().map(|t| t.name.as_str()).collect(); 1505 names.sort_unstable(); 1506 let mut expected: Vec<&str> = REPOS.iter().map(|(p, _)| *p).collect(); 1507 expected.extend(["aien-receipts", "aien-rig", "aien-train", "omega-blas", "omega-bridge", "omega-gpu-driver", "omega-harness", "omega-mcp", "omega-mission"]); 1508 expected.sort_unstable(); 1509 assert_eq!(names, expected); 1510 for skipped in ["aien", "aienix", "CUDApp", "cuda-crack", "gpu-head-to-head", "interplane-forge", "sovereign-intelligence"] { 1511 assert!(rows.iter().any(|(r, _, _)| r == skipped), "{skipped} is in the table"); 1512 assert!(targets.iter().all(|t| t.repo != skipped), "{skipped} is read"); 1513 } 1514 } 1515 1516 #[test] 1517 fn private_withdrawn_unknown_and_local_only_rows_are_never_read() { 1518 let table = "\ 1519 | repo | RID | default branch | 1520 |---|---|---| 1521 | aienux | rad:`z2Q6ob2gL6Qo5oUMpyehukayVF7mN` | main | 1522 | omega-mv | rad:z6do9WDBhuSnvopDkgFdFr1yWA62 | main | PRIVATE | 1523 | physics-mv | rad:`z49She8eifZpLd2aiSvk2pph3DMUo` | WITHDRAWN | 1524 | aien-protocols-mv PRIVATE | rad:zzxgxYRc5tw6VwYXkQNLC2hqKkfb | main | 1525 | benchmarks-mv | rad:z6do9WDBhuSnvopDkgFdFr1yWA62 | main | 1526 | omega-pearl | rad:z2ft64aaaaaaaaaaaaaaaaaaaaaa | main | 1527 | aien-crypto | rad:z2ft64bbbbbbbbbbbbbbbbbbbbbb | main | 1528 | aien-unknown | rad:`z3iwnx2pktbGhnfBpJSsaFcTmKgHU` | main | 1529 | aienos.com | rad:`z3iwnx2pktbGhnfBpJSsaFcTmKgHU` | ../x | 1530 "; 1531 let rows = table_rows(table); 1532 assert_eq!(rows, vec![row("aienux", "`z2Q6ob2gL6Qo5oUMpyehukayVF7mN`")]); 1533 let (targets, _) = select_targets(&rows); 1534 assert_eq!(targets.len(), 1); 1535 // The compiled table holds no row that is not public. 1536 assert!(table_rows(TABLE).iter().all(|(r, rid, _)| !NEVER_READ.contains(&r.as_str()) && !rid.starts_with(NEVER_READ_RID_PREFIX))); 1537 } 1538 1539 #[test] 1540 fn a_mapped_name_is_read_once_and_aienos_is_its_own_project() { 1541 // A repository literally named omega next to omega-mv: the map wins, omega is read once. 1542 let rows = [row("omega", "zOmega"), row("omega-mv", "z6do9WDBhuSnvopDkgFdFr1yWA62")]; 1543 let (targets, _) = select_targets(&rows); 1544 assert_eq!(targets.iter().filter(|t| t.name == "omega").count(), 1); 1545 assert_eq!(find(&targets, "omega").repo, "omega-mv"); 1546 // A repository named aienos is its own Core project beside the kernel; ADR 0045 retired 1547 // aienix, and no snapshot treats either as the whole system. 1548 let rows = [row("aienux", "`z2Q6ob2gL6Qo5oUMpyehukayVF7mN`"), row("aienos", "zAienos")]; 1549 let (targets, _) = select_targets(&rows); 1550 assert_eq!((find(&targets, "aienux").repo.as_str(), find(&targets, "aienos").repo.as_str()), ("aienux", "aienos")); 1551 assert_eq!((group_of("aienux", false), group_of("aienos", false)), ("Core", "Core")); 1552 // A snapshot carrying both projects passes; the same rows under one name are refused. 1553 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../public/data/project-progress.json"); 1554 let mut data: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); 1555 let repos = data["repos"].as_array_mut().unwrap(); 1556 let mut entry = repos.iter().find(|r| r["name"] == "aienux").expect("committed data names the kernel aienux").clone(); 1557 entry["name"] = Value::from("aienos"); 1558 entry.as_object_mut().unwrap().remove("url"); 1559 entry["prCount"] = Value::from(0); 1560 entry["ciCount"] = Value::from(0); 1561 repos.push(entry); 1562 validate_snapshot(&data).unwrap(); 1563 for r in data["repos"].as_array_mut().unwrap().iter_mut().filter(|r| r["name"] == "aienux") { 1564 r["name"] = Value::from("aienos"); 1565 } 1566 assert_eq!(validate_snapshot(&data), Err("Duplicate repositories".into())); 1567 } 1568 1569 /// A merged patch as `rad cob show --format json` printed it (omega-mv, 2026-11-10). 1570 const MERGED: &str = r#"{"title":"omc-train-4: training chain on main `2239dccd`","author":{"id":"did:key:`z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK`"},"state":{"status":"merged","revision":"`f5c457f479e0835f4224a2868644b5a11bba124e`","commit":"`12bdb787b5d4507f3d219d7a958fc05e2f620e20`"},"target":"delegates","labels":[],"merges":{"`z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK`":{"revision":"`f5c457f479e0835f4224a2868644b5a11bba124e`","commit":"`12bdb787b5d4507f3d219d7a958fc05e2f620e20`","timestamp":`1794306153000`}},"revisions":{"`f5c457f479e0835f4224a2868644b5a11bba124e`":{"id":"`f5c457f479e0835f4224a2868644b5a11bba124e`","author":{"id":"did:key:`z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK`"},"description":[],"base":"`2239dccd89631aa9e0d79cb5d60d15ead6d16820`","oid":"`12bdb787b5d4507f3d219d7a958fc05e2f620e20`","discussion":{"comments":{},"timeline":[]},"reviews":{},"timestamp":`1794306148000`,"resolves":[],"reactions":[]}},"assignees":[],"timeline":["`f5c457f479e0835f4224a2868644b5a11bba124e`"],"reviews":{}}"#; 1571 const MERGED_ID: &str = "`f5c457f479e0835f4224a2868644b5a11bba124e`"; 1572 1573 #[test] 1574 fn patches_parse_from_rad_cob_show() { 1575 let v: Value = serde_json::from_str(MERGED).unwrap(); 1576 let p = parse_patch(MERGED_ID, &v).unwrap(); 1577 assert_eq!((p.status.as_str(), p.created_ms, p.created_day.as_str()), ("merged", `1794306148000`, "2026-11-10")); 1578 assert_eq!(p.title, Value::from("omc-train-4: training chain on main `2239dccd`")); 1579 assert_eq!( 1580 p.merge, 1581 Some(Merge { ms: `1794306153000`, day: "2026-11-10".into(), commit: "`12bdb787b5d4507f3d219d7a958fc05e2f620e20`".into() }) 1582 ); 1583 // An open patch has no merge; the state decides, not leftover merge records. 1584 let mut open = v.clone(); 1585 open["state"] = serde_json::json!({ "status": "open" }); 1586 assert_eq!(parse_patch(MERGED_ID, &open).unwrap().merge, None); 1587 // Malformed records are refused rather than counted. 1588 let refused: Vec = vec![ 1589 |v| v["state"]["status"] = Value::from("closed"), 1590 |v| v["merges"] = serde_json::json!({}), 1591 |v| v["state"]["commit"] = Value::from("main"), 1592 |v| v["merges"]["`z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK`"]["commit"] = Value::from("`0000000000000000000000000000000000000000`"), 1593 |v| v["revisions"] = serde_json::json!({}), 1594 |v| { 1595 v.as_object_mut().unwrap().remove("state"); 1596 }, 1597 ]; 1598 for corrupt in refused { 1599 let mut copy = v.clone(); 1600 corrupt(&mut copy); 1601 assert!(parse_patch(MERGED_ID, ©).is_err(), "{copy}"); 1602 } 1603 // Another patch's record under this ID is refused: the root revision must be its own. 1604 assert!(parse_patch("`05f5a8bcbcd69f69c703bbf6e3edc620ae20cd7b`", &v).is_err()); 1605 assert!(parse_patch("F5C457F479E0835F4224A2868644B5A11BBA124E", &v).is_err()); 1606 } 1607 1608 #[test] 1609 fn the_github_era_record_is_kept_exactly_and_reconciles() { 1610 let era = github_era(GITHUB_ERA).unwrap(); 1611 assert_eq!(era.last, "2026-10-01"); 1612 // The figures of public/data/project-progress.json at `ec4df656` (collected 2026-10-01). 1613 assert_eq!(era.day("2026-10-01").unwrap(), [901, 852, 2328, 1080]); 1614 assert_eq!(era.day("2026-09-18").unwrap()[0], 130); 1615 assert_eq!(era.day("2026-01-01").unwrap(), [0; 4]); 1616 assert_eq!(era.ci_conclusions.values().sum::(), 2328); 1617 assert_eq!((era.repos.len(), era.activity.len()), (29, 12)); 1618 assert!(era.day("2026-10-02").is_err()); 1619 // An edited record no longer reconciles and is refused. 1620 let mut edited: Value = serde_json::from_str(GITHUB_ERA).unwrap(); 1621 edited["repos"][0]["prCount"] = Value::from(edited["repos"][0]["prCount"].as_u64().unwrap() + 1); 1622 assert!(github_era(&edited.to_string()).is_err()); 1623 let mut edited: Value = serde_json::from_str(GITHUB_ERA).unwrap(); 1624 edited["ciConclusions"]["success"] = Value::from(0); 1625 assert!(github_era(&edited.to_string()).is_err()); 1626 } 1627 1628 #[test] 1629 fn github_era_rows_are_carried_as_recorded() { 1630 let era = github_era(GITHUB_ERA).unwrap(); 1631 let carried = |name: &str| carried_row(era.row(name).unwrap(), &era.last).unwrap(); 1632 // Not archived on GitHub, so not published as archived. 1633 let site = carried("drakestapleton.com"); 1634 assert_eq!((site.archived, site.group.as_str(), site.recorded.as_deref()), (false, "Sites", Some("2026-10-01"))); 1635 assert_eq!((site.url.as_deref(), site.rid.as_deref(), site.pr_count, site.ci_count), (None, None, 44, 133)); 1636 assert_eq!((carried("atlas").archived, carried("atlas").group.as_str()), (false, "Core")); 1637 assert_eq!((carried("spark-hive").archived, carried("spark-hive").group.as_str()), (true, "Archived")); 1638 // Every recorded row keeps the recorded flag and group. 1639 for row in &era.repos { 1640 let c = carried_row(row, &era.last).unwrap(); 1641 assert_eq!(Some(c.archived), row["archived"].as_bool()); 1642 assert_eq!(Some(c.group.as_str()), row["group"].as_str()); 1643 } 1644 // A recorded-only row with a link, a Radicle ID or a bad day is refused. 1645 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../public/data/project-progress.json"); 1646 let data: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); 1647 let i = data["repos"].as_array().unwrap().iter().position(|r| r.get("recorded").is_some()).expect("committed data carries recorded rows"); 1648 let with = |key: &str, v: Value| { 1649 let mut d = data.clone(); 1650 d["repos"][i][key] = v; 1651 validate_snapshot(&d) 1652 }; 1653 assert!(with("recorded", Value::from("2026-10-01")).is_ok()); 1654 assert!(with("recorded", Value::from("Oct 1")).is_err()); 1655 assert!(with("url", Value::from("https://interplane.io/drakestapleton/atlas")).is_err()); 1656 assert!(with("rid", Value::from("rad:z6do9WDBhuSnvopDkgFdFr1yWA62")).is_err()); 1657 } 1658 1659 #[test] 1660 fn future_dated_commits_are_refused() { 1661 let cutoff = parse_time_ms("2026-11-10T12:00:00Z").unwrap(); 1662 let at = |ts: i64| Commit { sha: "a".repeat(40), ts, date: day_ms(ts * 1000) }; 1663 assert!(refuse_future("omega", &[at(cutoff / 1000 - 60), at(cutoff / 1000)], cutoff).is_ok()); 1664 assert_eq!( 1665 refuse_future("omega", &[at(cutoff / 1000 - 60), at(cutoff / 1000 + 1)], cutoff), 1666 Err("Pinned repository contains a future-dated commit: omega".into()) 1667 ); 1668 } 1669 1670 #[test] 1671 fn activity_and_event_links_must_be_forge_links_or_plain_text() { 1672 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../public/data/project-progress.json"); 1673 let data: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); 1674 validate_snapshot(&data).unwrap(); 1675 let with = |list: &str, url: Value, rid: Option<&str>| { 1676 let mut d = data.clone(); 1677 d[list][0]["url"] = url; 1678 match rid { 1679 Some(r) => d[list][0]["rid"] = Value::from(r), 1680 None => { 1681 d[list][0].as_object_mut().unwrap().remove("rid"); 1682 } 1683 } 1684 validate_snapshot(&d) 1685 }; 1686 for list in ["activity", "events"] { 1687 assert!(with(list, Value::from(""), None).is_ok()); 1688 assert!(with(list, Value::from("https://interplane.io/drakestapleton/omega-mv/commit/`12bdb787b5d4`"), Some("rad:z6do9WDBhuSnvopDkgFdFr1yWA62")).is_ok()); 1689 for bad in [ 1690 "https://github.com/aien-dev/omega/pull/1", 1691 "https://interplane.io/drakestapleton/", 1692 "https://interplane.io/drakestapleton/../x", 1693 "https://interplane.io/drakestapleton/omega-mv/commit/1?x=", 1694 "javascript:alert(1)", 1695 ] { 1696 assert!(with(list, Value::from(bad), None).is_err(), "{list} {bad}"); 1697 } 1698 assert!(with(list, Value::from(3), None).is_err()); 1699 assert!(with(list, Value::from(""), Some("rad:0OIl")).is_err()); 1700 } 1701 let mut d = data.clone(); 1702 d["repos"][0]["rid"] = Value::from("z6do9WDBhuSnvopDkgFdFr1yWA62"); 1703 assert_eq!(validate_snapshot(&d), Err("Invalid Radicle ID".into())); 1704 } 1705 1706 #[test] 1707 fn repository_links_must_be_forge_or_radicle_addresses() { 1708 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../public/data/project-progress.json"); 1709 let data: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); 1710 let with = |url: Value| { 1711 let mut d = data.clone(); 1712 d["repos"][0]["url"] = url; 1713 validate_snapshot(&d) 1714 }; 1715 assert!(with(Value::from("https://interplane.io/drakestapleton/omega-mv")).is_ok()); 1716 assert!(with(Value::from("https://interplane.io/drakestapleton/.github")).is_ok()); 1717 assert!(with(Value::from("https://radicle.network/nodes/rosa.radicle.network/rad:`z3iwnx2pktbGhnfBpJSsaFcTmKgHU`")).is_ok()); 1718 for bad in [ 1719 "https://example.com/aien-dev/omega", 1720 "https://interplane.io/drakestapleton", 1721 "https://interplane.io/drakestapleton/..", 1722 "https://interplane.io/drakestapleton/omega-mv/tree/x", 1723 "https://github.com/aien-dev/omega", 1724 "https://github.com/aien-dev/omega/tree/x", 1725 "https://github.com/../..", 1726 "https://radicle.network/nodes/rosa.radicle.network/rad:", 1727 "javascript:alert(1)", 1728 ] { 1729 assert!(with(Value::from(bad)).is_err(), "{bad}"); 1730 } 1731 assert!(with(Value::from(3)).is_err()); 1732 } 1733 1734 #[test] 1735 fn incomplete_and_inconsistent_observations_are_refused_before_publication() { 1736 let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../public/data/project-progress.json"); 1737 let data: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); 1738 validate_snapshot(&data).unwrap(); 1739 let corruptions: Vec = vec![ 1740 |d| { 1741 let row = d["series"].as_array_mut().unwrap().last_mut().unwrap(); 1742 row["loc"] = Value::from(row["loc"].as_u64().unwrap() + 1); 1743 }, 1744 |d| d["summary"]["ci"] = Value::from(d["summary"]["ci"].as_u64().unwrap() + 1), 1745 |d| d["repos"][0]["head"] = Value::from("main"), 1746 |d| d["series"] = Value::Array(vec![]), 1747 |d| { 1748 d["series"][0].as_object_mut().unwrap().remove("testfiles"); 1749 }, 1750 ]; 1751 for corrupt in corruptions { 1752 let mut copy = data.clone(); 1753 corrupt(&mut copy); 1754 assert!(validate_snapshot(©).is_err()); 1755 } 1756 } 1757 }