1use std::collections::BTreeMap;
21
22use serde::Serialize;
23use sha2::{Digest, Sha256};
24
25use crate::anchor::{Anchor, JoinPolicy};
26use crate::evidence_diff::derive_status_provenance;
27use crate::project::Project;
28use crate::status_provenance::BelnapStatus;
29
30pub const ATLAS_SCHEMA: &str = "vela.atlas.v0.1";
31pub const ATLAS_PROJECTION_VERSION: &str = "atlas-proj-v0.1";
34
35#[derive(Debug, Clone, Serialize)]
38pub struct AtlasCell {
39 pub class_id: String,
41 pub stable_handle: Option<String>,
44 pub projection_hash: String,
47 pub members: Vec<String>,
49 pub anchors: Vec<Anchor>,
51 pub belnap: &'static str,
54 pub support_kappa: String,
56 pub refutation_kappa: String,
58 pub label: String,
60 #[serde(skip_serializing_if = "Option::is_none")]
67 pub status: Option<String>,
68}
69
70#[derive(Debug, Clone, Serialize)]
75pub struct AtlasEdge {
76 pub source: String,
77 pub target: String,
78 pub kind: String,
79}
80
81#[derive(Debug, Clone, Serialize)]
82pub struct Atlas {
83 pub schema: String,
84 pub projection_version: String,
85 pub frontiers: Vec<String>,
87 pub cells: Vec<AtlasCell>,
88 pub edges: Vec<AtlasEdge>,
89}
90
91struct Member {
92 global_id: String,
93 label: String,
94 context_key: String,
95 hard_anchors: Vec<Anchor>,
96 support_x: bool,
98 refute_y: bool,
100 belnap: BelnapStatus,
101 status: Option<&'static str>,
102 links: Vec<(String, String)>,
104}
105
106fn anchor_join_key(a: &Anchor) -> String {
108 format!(
109 "{}|{}|{}|{}|{}",
110 a.namespace,
111 a.id,
112 a.role,
113 a.namespace_version.as_deref().unwrap_or(""),
114 a.statement_fingerprint.as_deref().unwrap_or(""),
115 )
116}
117
118fn context_key_of(conditions: &crate::bundle::Conditions) -> String {
122 match crate::canonical::to_canonical_bytes(conditions) {
123 Ok(bytes) => hex::encode(Sha256::digest(bytes))[..16].to_string(),
124 Err(_) => "ctx_unkeyable".to_string(),
125 }
126}
127
128fn coord_str(present: bool) -> String {
132 if present {
133 "1/1".to_string()
134 } else {
135 "0/1".to_string()
136 }
137}
138
139fn belnap_str(b: BelnapStatus) -> &'static str {
140 match b {
141 BelnapStatus::True => "T",
142 BelnapStatus::False => "F",
143 BelnapStatus::Both => "B",
144 BelnapStatus::None => "N",
145 }
146}
147
148fn declared_status(text: &str) -> Option<&'static str> {
152 let t = text.to_ascii_lowercase();
153 if t.contains("disproved") || t.contains("disproven") {
154 Some("disproved")
155 } else if t.contains("solved") {
156 Some("solved")
157 } else if t.contains("proved") || t.contains("proven") {
158 Some("proved")
159 } else if t.contains("open") {
160 Some("open")
161 } else {
162 None
163 }
164}
165
166#[must_use]
168pub fn project(projects: &[&Project]) -> Atlas {
169 let mut members: Vec<Member> = Vec::new();
170 let mut frontiers: Vec<String> = Vec::new();
171
172 for proj in projects {
173 let vfr = proj
174 .frontier_id
175 .clone()
176 .unwrap_or_else(|| proj.project.name.clone());
177 frontiers.push(vfr.clone());
178 for f in &proj.findings {
179 let sp = derive_status_provenance(&proj.events, &f.id);
180 let belnap = sp.derive_status();
181 let support_x = !sp.support.is_empty();
184 let refute_y = !sp.refute.is_empty();
185 let hard_anchors: Vec<Anchor> = proj
186 .anchor_links
187 .iter()
188 .filter(|l| l.target == f.id && l.anchor.join_policy == JoinPolicy::HardIdentity)
189 .map(|l| l.anchor.clone())
190 .collect();
191 members.push(Member {
192 global_id: format!("{}@{}", f.id, vfr),
193 label: f.assertion.text.chars().take(120).collect(),
194 context_key: context_key_of(&f.conditions),
195 hard_anchors,
196 support_x,
197 refute_y,
198 belnap,
199 status: declared_status(&f.assertion.text),
200 links: f
201 .links
202 .iter()
203 .map(|l| {
204 let tgt = if l.target.contains('@') {
207 l.target.clone()
208 } else {
209 format!("{}@{}", l.target, vfr)
210 };
211 (tgt, l.link_type.clone())
212 })
213 .collect(),
214 });
215 }
216 }
217 frontiers.sort();
218 frontiers.dedup();
219
220 let mut parent: Vec<usize> = (0..members.len()).collect();
222 fn find(parent: &mut [usize], mut i: usize) -> usize {
223 while parent[i] != i {
224 parent[i] = parent[parent[i]];
225 i = parent[i];
226 }
227 i
228 }
229 let mut seen: BTreeMap<(String, String), usize> = BTreeMap::new();
230 for (i, m) in members.iter().enumerate() {
231 for a in &m.hard_anchors {
232 let ctx = if a.kind == crate::anchor::AnchorKind::ProblemEntry {
239 String::new()
240 } else {
241 m.context_key.clone()
242 };
243 let key = (anchor_join_key(a), ctx);
244 if let Some(&j) = seen.get(&key) {
245 let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
246 if ri != rj {
247 parent[ri] = rj;
248 }
249 } else {
250 seen.insert(key, i);
251 }
252 }
253 }
254
255 let mut groups: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
257 for i in 0..members.len() {
258 let r = find(&mut parent, i);
259 groups.entry(r).or_default().push(i);
260 }
261
262 let mut cells: Vec<AtlasCell> = groups
263 .values()
264 .map(|idxs| {
265 let mut member_ids: Vec<String> =
266 idxs.iter().map(|&i| members[i].global_id.clone()).collect();
267 member_ids.sort();
268
269 let mut anchors: Vec<Anchor> = Vec::new();
271 let mut anchor_keys: std::collections::BTreeSet<String> =
272 std::collections::BTreeSet::new();
273 for &i in idxs {
274 for a in &members[i].hard_anchors {
275 if anchor_keys.insert(anchor_join_key(a)) {
276 anchors.push(a.clone());
277 }
278 }
279 }
280 anchors.sort_by_key(anchor_join_key);
281
282 let support = idxs
285 .iter()
286 .any(|&i| matches!(members[i].belnap, BelnapStatus::True | BelnapStatus::Both));
287 let refute = idxs
288 .iter()
289 .any(|&i| matches!(members[i].belnap, BelnapStatus::False | BelnapStatus::Both));
290 let belnap = match (support, refute) {
291 (true, true) => BelnapStatus::Both,
292 (true, false) => BelnapStatus::True,
293 (false, true) => BelnapStatus::False,
294 (false, false) => BelnapStatus::None,
295 };
296
297 let support_kappa = idxs.iter().any(|&i| members[i].support_x);
300 let refutation_kappa = idxs.iter().any(|&i| members[i].refute_y);
301
302 let stable_handle = anchors
303 .first()
304 .map(|a| format!("{}:{}#{}", a.namespace, a.id, a.role));
305 let label = idxs
306 .iter()
307 .map(|&i| members[i].label.clone())
308 .min()
309 .unwrap_or_default();
310
311 let statuses: std::collections::BTreeSet<&str> =
315 idxs.iter().filter_map(|&i| members[i].status).collect();
316 let status = match statuses.len() {
317 0 => None,
318 1 => statuses.iter().next().map(|s| s.to_string()),
319 _ => Some("contested".to_string()),
320 };
321
322 let class_id = format!(
323 "vac_{}",
324 &hex::encode(Sha256::digest(member_ids.join(",").as_bytes()))[..16]
325 );
326 let projection_hash = hex::encode(Sha256::digest(
327 format!("{}|{}", member_ids.join(","), ATLAS_PROJECTION_VERSION).as_bytes(),
328 ));
329
330 AtlasCell {
331 class_id,
332 stable_handle,
333 projection_hash,
334 members: member_ids,
335 anchors,
336 belnap: belnap_str(belnap),
337 support_kappa: coord_str(support_kappa),
338 refutation_kappa: coord_str(refutation_kappa),
339 label,
340 status,
341 }
342 })
343 .collect();
344 cells.sort_by(|a, b| a.class_id.cmp(&b.class_id));
345
346 let mut global_to_class: BTreeMap<&str, &str> = BTreeMap::new();
350 for c in &cells {
351 for m in &c.members {
352 global_to_class.insert(m.as_str(), c.class_id.as_str());
353 }
354 }
355 let mut edge_set: std::collections::BTreeSet<(String, String, String)> =
356 std::collections::BTreeSet::new();
357 for m in &members {
358 let Some(&src) = global_to_class.get(m.global_id.as_str()) else {
359 continue;
360 };
361 for (tgt_global, kind) in &m.links {
362 if let Some(&tgt) = global_to_class.get(tgt_global.as_str())
363 && src != tgt
364 {
365 edge_set.insert((src.to_string(), tgt.to_string(), kind.clone()));
366 }
367 }
368 }
369 let edges: Vec<AtlasEdge> = edge_set
370 .into_iter()
371 .map(|(source, target, kind)| AtlasEdge {
372 source,
373 target,
374 kind,
375 })
376 .collect();
377
378 Atlas {
379 schema: ATLAS_SCHEMA.to_string(),
380 projection_version: ATLAS_PROJECTION_VERSION.to_string(),
381 frontiers,
382 cells,
383 edges,
384 }
385}
386
387#[derive(Debug, Clone, Serialize)]
394pub struct DomainState {
395 pub name: String,
396 pub claim_count: usize,
398 pub belnap: &'static str,
400 pub support_kappa: String,
402 pub refutation_kappa: String,
403 pub belnap_counts: BTreeMap<String, usize>,
405 pub status_counts: BTreeMap<String, usize>,
407 pub contested: usize,
409}
410
411#[derive(Debug, Clone, Serialize)]
412pub struct DomainAtlas {
413 pub schema: String,
414 pub projection_version: String,
415 pub domains: Vec<DomainState>,
417}
418
419fn coord_present(s: &str) -> bool {
423 s != "0/1"
424}
425
426fn corner(support: bool, refute: bool) -> BelnapStatus {
428 match (support, refute) {
429 (true, true) => BelnapStatus::Both,
430 (true, false) => BelnapStatus::True,
431 (false, true) => BelnapStatus::False,
432 (false, false) => BelnapStatus::None,
433 }
434}
435
436pub fn project_domains(
445 atlas: &Atlas,
446 problem_domains: &BTreeMap<String, Vec<String>>,
447) -> DomainAtlas {
448 struct Acc {
449 support: bool,
450 refute: bool,
451 belnap: BTreeMap<String, usize>,
452 status: BTreeMap<String, usize>,
453 contested: usize,
454 count: usize,
455 }
456 let mut acc: BTreeMap<String, Acc> = BTreeMap::new();
457 for cell in &atlas.cells {
458 let Some(pid) = cell
459 .anchors
460 .iter()
461 .find(|a| a.namespace == "erdos")
462 .map(|a| a.id.clone())
463 else {
464 continue;
465 };
466 let Some(domains) = problem_domains.get(&pid) else {
467 continue;
468 };
469 let support = coord_present(&cell.support_kappa);
470 let refute = coord_present(&cell.refutation_kappa);
471 for dom in domains {
472 let e = acc.entry(dom.clone()).or_insert_with(|| Acc {
473 support: false,
474 refute: false,
475 belnap: BTreeMap::new(),
476 status: BTreeMap::new(),
477 contested: 0,
478 count: 0,
479 });
480 e.support |= support;
481 e.refute |= refute;
482 *e.belnap.entry(cell.belnap.to_string()).or_insert(0) += 1;
483 if cell.belnap == "B" {
484 e.contested += 1;
485 }
486 if let Some(s) = &cell.status {
487 *e.status.entry(s.clone()).or_insert(0) += 1;
488 }
489 e.count += 1;
490 }
491 }
492 let mut domains: Vec<DomainState> = acc
493 .into_iter()
494 .map(|(name, a)| DomainState {
495 name,
496 claim_count: a.count,
497 belnap: belnap_str(corner(a.support, a.refute)),
498 support_kappa: coord_str(a.support),
499 refutation_kappa: coord_str(a.refute),
500 belnap_counts: a.belnap,
501 status_counts: a.status,
502 contested: a.contested,
503 })
504 .collect();
505 domains.sort_by(|a, b| b.claim_count.cmp(&a.claim_count).then(a.name.cmp(&b.name)));
506 DomainAtlas {
507 schema: "vela.atlas.domains.v0.1".to_string(),
508 projection_version: ATLAS_PROJECTION_VERSION.to_string(),
509 domains,
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use crate::anchor::AnchorKind;
517
518 fn anchor(ns: &str, id: &str, role: &str, policy: JoinPolicy) -> Anchor {
519 Anchor {
520 namespace: ns.to_string(),
521 id: id.to_string(),
522 role: role.to_string(),
523 kind: AnchorKind::Sequence,
524 join_policy: policy,
525 namespace_version: None,
526 source_revision: None,
527 statement_fingerprint: None,
528 }
529 }
530
531 fn proj_with(vfr: &str, vf: &str, text: &str, a: Anchor) -> Project {
534 let mut f = crate::test_support::make_finding(vf, 0.9, "math");
535 f.assertion.text = text.to_string();
536 let mut p = crate::test_support::make_project(vfr, vec![f]);
537 p.frontier_id = Some(vfr.to_string());
538 let ev = crate::events::new_finding_event(crate::events::FindingEventInput {
540 kind: "finding.asserted",
541 finding_id: vf,
542 actor_id: "reviewer:t",
543 actor_type: "human",
544 reason: "seed",
545 before_hash: "sha256:null",
546 after_hash: "sha256:null",
547 payload: serde_json::json!({}),
548 caveats: Vec::new(),
549 timestamp: None,
550 });
551 let key = ed25519_dalek::SigningKey::from_bytes(&[3u8; 32]);
552 let link = crate::anchor::AnchorLink::build(
553 crate::anchor::AnchorLinkDraft {
554 target: vf.to_string(),
555 anchor: a,
556 attached_by: "reviewer:t".to_string(),
557 attached_at: "2026-06-15T00:00:00Z".to_string(),
558 },
559 &key,
560 )
561 .unwrap();
562 p.events.push(ev);
563 p.anchor_links.push(link);
564 p
565 }
566
567 #[test]
568 fn same_hard_anchor_across_frontiers_joins() {
569 let a = anchor(
570 "oeis",
571 "A309370",
572 "lower-bound a(10)",
573 JoinPolicy::HardIdentity,
574 );
575 let p1 = proj_with("vfr_one", "vf_aaaa", "claim one", a.clone());
576 let p2 = proj_with("vfr_two", "vf_bbbb", "claim two", a);
577 let atlas = project(&[&p1, &p2]);
578 assert_eq!(
580 atlas.cells.len(),
581 1,
582 "shared anchor must collapse to one cell"
583 );
584 assert_eq!(atlas.cells[0].members.len(), 2);
585 assert_eq!(
586 atlas.cells[0].stable_handle.as_deref(),
587 Some("oeis:A309370#lower-bound a(10)")
588 );
589 }
590
591 #[test]
592 fn different_role_does_not_join() {
593 let p1 = proj_with(
594 "vfr_one",
595 "vf_aaaa",
596 "lower",
597 anchor(
598 "oeis",
599 "A309370",
600 "lower-bound a(10)",
601 JoinPolicy::HardIdentity,
602 ),
603 );
604 let p2 = proj_with(
605 "vfr_two",
606 "vf_bbbb",
607 "upper",
608 anchor(
609 "oeis",
610 "A309370",
611 "upper-bound a(10)",
612 JoinPolicy::HardIdentity,
613 ),
614 );
615 let atlas = project(&[&p1, &p2]);
616 assert_eq!(
617 atlas.cells.len(),
618 2,
619 "different role = different sub-claim = two cells"
620 );
621 }
622
623 #[test]
624 fn search_only_never_joins() {
625 let p1 = proj_with(
626 "vfr_one",
627 "vf_aaaa",
628 "one",
629 anchor("arxiv", "2401.1", "cite", JoinPolicy::SearchOnly),
630 );
631 let p2 = proj_with(
632 "vfr_two",
633 "vf_bbbb",
634 "two",
635 anchor("arxiv", "2401.1", "cite", JoinPolicy::SearchOnly),
636 );
637 let atlas = project(&[&p1, &p2]);
638 assert_eq!(
639 atlas.cells.len(),
640 2,
641 "SearchOnly anchors never induce identity"
642 );
643 }
644
645 #[test]
646 fn project_domains_lifts_state_to_a_field() {
647 let p1 = proj_with(
649 "vfr_a",
650 "vf_1",
651 "Erdős #1",
652 anchor("erdos", "1", "problem", JoinPolicy::HardIdentity),
653 );
654 let p2 = proj_with(
655 "vfr_b",
656 "vf_2",
657 "Erdős #2",
658 anchor("erdos", "2", "problem", JoinPolicy::HardIdentity),
659 );
660 let atlas = project(&[&p1, &p2]);
661 let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
662 map.insert("1".into(), vec!["number theory".into()]);
663 map.insert(
664 "2".into(),
665 vec!["number theory".into(), "additive combinatorics".into()],
666 );
667 let da = project_domains(&atlas, &map);
668 assert_eq!(da.domains[0].name, "number theory");
670 let nt = da
671 .domains
672 .iter()
673 .find(|d| d.name == "number theory")
674 .unwrap();
675 assert_eq!(nt.claim_count, 2);
676 assert_eq!(nt.belnap, "T");
678 assert_eq!(nt.contested, 0);
679 let ac = da
680 .domains
681 .iter()
682 .find(|d| d.name == "additive combinatorics")
683 .unwrap();
684 assert_eq!(ac.claim_count, 1); }
686}