1use crate::compare::{hex32, sha256};
41use serde::{Deserialize, Serialize};
42use std::path::{Path, PathBuf};
43use std::process::Command;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53pub enum EvidenceTier {
54 Perturbation,
57 Oracle,
60 FrozenMatrix,
62 SelfValidatedTool,
65 SourceRead,
67 WholeProgramAttribution,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
74pub enum Strength {
75 Weak = 0,
77 Hypothesis = 1,
79 Strong = 2,
81}
82
83impl Strength {
84 pub fn label(self) -> &'static str {
85 match self {
86 Strength::Weak => "WEAK",
87 Strength::Hypothesis => "HYPOTHESIS",
88 Strength::Strong => "STRONG",
89 }
90 }
91 pub fn parse(s: &str) -> Option<Strength> {
93 match s.trim().to_ascii_lowercase().as_str() {
94 "strong" => Some(Strength::Strong),
95 "hypothesis" | "hyp" => Some(Strength::Hypothesis),
96 "weak" => Some(Strength::Weak),
97 _ => None,
98 }
99 }
100}
101
102impl EvidenceTier {
103 pub fn label(self) -> &'static str {
104 match self {
105 EvidenceTier::Perturbation => "perturbation",
106 EvidenceTier::Oracle => "oracle",
107 EvidenceTier::FrozenMatrix => "frozen-matrix",
108 EvidenceTier::SelfValidatedTool => "self-validated-tool",
109 EvidenceTier::SourceRead => "source-read",
110 EvidenceTier::WholeProgramAttribution => "whole-program-attribution",
111 }
112 }
113
114 pub fn strength(self) -> Strength {
116 match self {
117 EvidenceTier::Perturbation | EvidenceTier::Oracle | EvidenceTier::FrozenMatrix => {
118 Strength::Strong
119 }
120 EvidenceTier::SelfValidatedTool | EvidenceTier::SourceRead => Strength::Hypothesis,
121 EvidenceTier::WholeProgramAttribution => Strength::Weak,
122 }
123 }
124
125 pub fn can_be_cited_as(self, requested: Strength) -> bool {
129 self.strength() >= requested
130 }
131
132 pub fn parse(s: &str) -> Option<EvidenceTier> {
133 match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
134 "perturbation" | "perturb" => Some(EvidenceTier::Perturbation),
135 "oracle" => Some(EvidenceTier::Oracle),
136 "frozen-matrix" | "frozen" | "matrix" => Some(EvidenceTier::FrozenMatrix),
137 "self-validated-tool" | "self-validated" | "tool" => {
138 Some(EvidenceTier::SelfValidatedTool)
139 }
140 "source-read" | "source" | "src-read" => Some(EvidenceTier::SourceRead),
141 "whole-program-attribution" | "attribution" | "whole-program" => {
142 Some(EvidenceTier::WholeProgramAttribution)
143 }
144 _ => None,
145 }
146 }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155pub enum Verdict {
156 Located,
158 Refuted,
160 Win,
162 Tie,
164 Loss,
166 Survives,
168 NarrowsToScope,
170 False,
172 Other(String),
174}
175
176impl Verdict {
177 pub fn label(&self) -> String {
178 match self {
179 Verdict::Located => "LOCATED".into(),
180 Verdict::Refuted => "REFUTED".into(),
181 Verdict::Win => "WIN".into(),
182 Verdict::Tie => "TIE".into(),
183 Verdict::Loss => "LOSS".into(),
184 Verdict::Survives => "SURVIVES".into(),
185 Verdict::NarrowsToScope => "NARROWS-TO-SCOPE".into(),
186 Verdict::False => "FALSE".into(),
187 Verdict::Other(s) => s.to_ascii_uppercase(),
188 }
189 }
190 pub fn parse(s: &str) -> Verdict {
191 match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
192 "located" => Verdict::Located,
193 "refuted" => Verdict::Refuted,
194 "win" => Verdict::Win,
195 "tie" => Verdict::Tie,
196 "loss" => Verdict::Loss,
197 "survives" => Verdict::Survives,
198 "narrows-to-scope" | "narrows" => Verdict::NarrowsToScope,
199 "false" => Verdict::False,
200 other => Verdict::Other(other.to_string()),
201 }
202 }
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub enum Threads {
213 Fixed(usize),
214 Auto,
216 Any,
218}
219
220impl Threads {
221 pub fn label(&self) -> String {
222 match self {
223 Threads::Fixed(n) => format!("t{n}"),
224 Threads::Auto => "auto".into(),
225 Threads::Any => "t*".into(),
226 }
227 }
228 pub fn parse(s: &str) -> Threads {
229 let s = s.trim().to_ascii_lowercase();
230 if s == "*" || s == "any" || s.is_empty() {
231 return Threads::Any;
232 }
233 if s == "auto" || s == "-p0" || s == "p0" {
234 return Threads::Auto;
235 }
236 let digits = s.trim_start_matches('t');
237 digits
238 .parse::<usize>()
239 .map(Threads::Fixed)
240 .unwrap_or(Threads::Any)
241 }
242 fn answers(&self, claim: &Threads) -> bool {
245 match claim {
246 Threads::Any => true,
247 _ => self == claim,
248 }
249 }
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257pub struct Scope {
258 pub corpus: String,
259 pub arch: String,
260 pub threads: Threads,
261}
262
263impl Scope {
264 pub fn new(corpus: &str, arch: &str, threads: Threads) -> Scope {
265 Scope {
266 corpus: corpus.to_string(),
267 arch: arch.to_string(),
268 threads,
269 }
270 }
271
272 pub fn label(&self) -> String {
274 format!("{}/{}/{}", self.arch, self.corpus, self.threads.label())
275 }
276
277 pub fn supports(&self, claim: &Scope) -> Result<(), ScopeMismatch> {
284 let corpus_ok = claim.corpus == "*" || claim.corpus == self.corpus;
285 let arch_ok = claim.arch == "*" || claim.arch == self.arch;
286 let threads_ok = self.threads.answers(&claim.threads);
287 if corpus_ok && arch_ok && threads_ok {
288 Ok(())
289 } else {
290 Err(ScopeMismatch {
291 axis: if !arch_ok {
292 "arch"
293 } else if !corpus_ok {
294 "corpus"
295 } else {
296 "threads"
297 }
298 .to_string(),
299 measured: self.label(),
300 claimed: claim.label(),
301 })
302 }
303 }
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct ScopeMismatch {
309 pub axis: String,
310 pub measured: String,
311 pub claimed: String,
312}
313
314#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
321pub struct Finding {
322 pub cell_id: String,
325 pub region: String,
328 pub claim: String,
331 pub commit_sha: String,
334 pub scope: Scope,
336 pub sink: String,
338 pub n: usize,
340 pub inter_run_spread: f64,
342 pub evidence_tier: EvidenceTier,
344 pub verdict: Verdict,
346 pub value: f64,
348 pub dimension: String,
349 #[serde(default)]
356 pub rss_mb: Option<f64>,
357 pub method: String,
359 pub created_utc: String,
361}
362
363impl Finding {
364 #[allow(clippy::too_many_arguments)]
367 pub fn new(
368 region: &str,
369 claim: &str,
370 commit_sha: &str,
371 scope: Scope,
372 sink: &str,
373 n: usize,
374 inter_run_spread: f64,
375 evidence_tier: EvidenceTier,
376 verdict: Verdict,
377 value: f64,
378 dimension: &str,
379 method: &str,
380 created_utc: &str,
381 ) -> Finding {
382 let mut f = Finding {
383 cell_id: String::new(),
384 region: region.to_string(),
385 claim: claim.to_string(),
386 commit_sha: commit_sha.to_string(),
387 scope,
388 sink: sink.to_string(),
389 n,
390 inter_run_spread,
391 evidence_tier,
392 verdict,
393 value,
394 dimension: dimension.to_string(),
395 rss_mb: None,
396 method: method.to_string(),
397 created_utc: created_utc.to_string(),
398 };
399 f.cell_id = f.derive_id();
400 f
401 }
402
403 pub fn with_rss(mut self, rss_mb: f64) -> Finding {
407 self.rss_mb = Some(rss_mb);
408 self.cell_id = self.derive_id();
409 self
410 }
411
412 pub fn fingerprint(&self) -> String {
418 let base = format!(
419 "v1|region={}|commit={}|arch={}|corpus={}|threads={}|sink={}|n={}|tier={}|verdict={}|value={}|dim={}|method={}",
420 self.region,
421 self.commit_sha,
422 self.scope.arch,
423 self.scope.corpus,
424 self.scope.threads.label(),
425 self.sink,
426 self.n,
427 self.evidence_tier.label(),
428 self.verdict.label(),
429 canon_value(self.value),
430 self.dimension,
431 self.method,
432 );
433 match self.rss_mb {
437 Some(r) => format!("{base}|rss_mb={}", canon_value(r)),
438 None => base,
439 }
440 }
441
442 pub fn derive_id(&self) -> String {
445 let digest = sha256(self.fingerprint().as_bytes());
446 format!("F-{}", &hex32(&digest)[..12])
447 }
448
449 pub fn is_citable(&self) -> Result<(), String> {
454 if self.cell_id.is_empty() {
455 return Err(
456 "NON-CITABLE: empty cell_id (a claim with no cell_id is not a finding)".into(),
457 );
458 }
459 if !self.cell_id.starts_with("F-") || self.cell_id.len() != 14 {
460 return Err(format!(
461 "NON-CITABLE: malformed cell_id {:?} (expected F-<12 hex>)",
462 self.cell_id
463 ));
464 }
465 let derived = self.derive_id();
466 if derived != self.cell_id {
467 return Err(format!(
468 "NON-CITABLE: cell_id {:?} does not match its fingerprint (derives {:?}) \
469 — the row was edited by hand, not measured",
470 self.cell_id, derived
471 ));
472 }
473 Ok(())
474 }
475
476 pub fn summary(&self) -> String {
478 format!(
479 "{id} [{tier}/{strength}] {region} {verdict} {value}{dim} @ {scope} sink={sink} N={n} spread={spread:.1}% commit={commit}",
480 id = self.cell_id,
481 tier = self.evidence_tier.label(),
482 strength = self.evidence_tier.strength().label(),
483 region = self.region,
484 verdict = self.verdict.label(),
485 value = trim_float(self.value),
486 dim = self.dimension,
487 scope = self.scope.label(),
488 sink = self.sink,
489 n = self.n,
490 spread = self.inter_run_spread * 100.0,
491 commit = short_sha(&self.commit_sha),
492 )
493 }
494}
495
496fn canon_value(v: f64) -> String {
499 if !v.is_finite() {
500 return format!("{v}");
501 }
502 if v == 0.0 {
503 return "0".into();
504 }
505 let mag = v.abs().log10().floor() as i32;
506 let decimals = (5 - mag).clamp(0, 12) as usize;
507 let s = format!("{v:.decimals$}");
508 let s = s.trim_end_matches('0').trim_end_matches('.');
510 if s.is_empty() || s == "-" {
511 "0".into()
512 } else {
513 s.to_string()
514 }
515}
516
517fn trim_float(v: f64) -> String {
518 let s = format!("{v:.3}");
519 s.trim_end_matches('0').trim_end_matches('.').to_string()
520}
521
522fn short_sha(s: &str) -> String {
523 s.chars().take(7).collect()
524}
525
526#[derive(Debug, Clone, PartialEq, Eq)]
530pub enum SrcChange {
531 Fresh,
533 Stale,
536 Unknown(String),
540}
541
542impl SrcChange {
543 pub fn label(&self) -> String {
544 match self {
545 SrcChange::Fresh => "FRESH".into(),
546 SrcChange::Stale => "STALE".into(),
547 SrcChange::Unknown(why) => format!("UNKNOWN({why})"),
548 }
549 }
550}
551
552pub trait SrcChangeOracle {
556 fn src_changed_since(&self, commit_sha: &str) -> SrcChange;
557}
558
559pub struct GitSrcOracle {
563 pub repo: PathBuf,
564 pub watch: Vec<String>,
566}
567
568impl GitSrcOracle {
569 pub fn new(repo: impl Into<PathBuf>) -> GitSrcOracle {
570 GitSrcOracle {
571 repo: repo.into(),
572 watch: vec!["src".to_string()],
573 }
574 }
575}
576
577impl SrcChangeOracle for GitSrcOracle {
578 fn src_changed_since(&self, commit_sha: &str) -> SrcChange {
579 if commit_sha.trim().is_empty() {
580 return SrcChange::Unknown("empty commit_sha".into());
581 }
582 let cat = Command::new("git")
585 .arg("-C")
586 .arg(&self.repo)
587 .args(["cat-file", "-e", &format!("{commit_sha}^{{commit}}")])
588 .output();
589 match cat {
590 Ok(o) if o.status.success() => {}
591 Ok(_) => {
592 return SrcChange::Unknown(format!("commit {} not in repo", short_sha(commit_sha)))
593 }
594 Err(e) => return SrcChange::Unknown(format!("git unavailable: {e}")),
595 }
596 let mut cmd = Command::new("git");
597 cmd.arg("-C").arg(&self.repo).args([
598 "diff",
599 "--quiet",
600 &format!("{commit_sha}..HEAD"),
601 "--",
602 ]);
603 for w in &self.watch {
604 cmd.arg(w);
605 }
606 match cmd.status() {
607 Ok(s) if s.success() => SrcChange::Fresh,
608 Ok(s) if s.code() == Some(1) => SrcChange::Stale,
609 Ok(s) => SrcChange::Unknown(format!("git diff exit {:?}", s.code())),
610 Err(e) => SrcChange::Unknown(format!("git unavailable: {e}")),
611 }
612 }
613}
614
615pub struct FixedOracle {
624 pub answer: SrcChange,
625}
626
627impl FixedOracle {
628 pub fn fresh() -> FixedOracle {
630 FixedOracle {
631 answer: SrcChange::Fresh,
632 }
633 }
634}
635
636impl SrcChangeOracle for FixedOracle {
637 fn src_changed_since(&self, _commit_sha: &str) -> SrcChange {
638 self.answer.clone()
639 }
640}
641
642#[derive(Debug, Clone)]
648pub struct CitationRequest {
649 pub as_strength: Strength,
652 pub claim_scope: Scope,
655}
656
657#[derive(Debug, Clone)]
660pub enum CiteOutcome {
661 Granted {
662 finding: Box<Finding>,
663 freshness: SrcChange,
664 granted_as: Strength,
665 },
666 Refused {
667 cell_id: String,
668 reason: CiteRefusal,
669 },
670}
671
672impl CiteOutcome {
673 pub fn is_granted(&self) -> bool {
674 matches!(self, CiteOutcome::Granted { .. })
675 }
676}
677
678#[derive(Debug, Clone, PartialEq, Eq)]
681pub enum CiteRefusal {
682 NotFound,
684 NonCitable(String),
686 Stale(String),
689 TierTooWeak { has: String, requested: String },
691 OutOfScope(ScopeMismatch),
693}
694
695impl CiteRefusal {
696 pub fn explain(&self) -> String {
697 match self {
698 CiteRefusal::NotFound => "REFUSED: no such cell_id in the store".into(),
699 CiteRefusal::NonCitable(why) => format!("REFUSED: {why}"),
700 CiteRefusal::Stale(fresh) => format!(
701 "REFUSED: cell is {fresh} — src/ changed since the measured commit; \
702 re-run to refresh before quoting as current (this is the #17 stale-citation guard)"
703 ),
704 CiteRefusal::TierTooWeak { has, requested } => format!(
705 "REFUSED: cell is tier {has} (cannot be cited as a {requested} finding); \
706 a hypothesis/weak cell may only be cited DOWN, never up"
707 ),
708 CiteRefusal::OutOfScope(m) => format!(
709 "REFUSED: scope mismatch on {axis} — cell was measured at {measured}, \
710 the citation claims {claimed}; no silent generalization",
711 axis = m.axis,
712 measured = m.measured,
713 claimed = m.claimed
714 ),
715 }
716 }
717}
718
719#[derive(Debug, Clone, Default)]
726pub struct Store {
727 pub findings: Vec<Finding>,
728}
729
730impl Store {
731 pub fn default_path(repo: &Path) -> PathBuf {
734 if let Ok(p) = std::env::var("FULCRUM_FINDING_STORE") {
735 return PathBuf::from(p);
736 }
737 repo.join(".fulcrum").join("findings.jsonl")
738 }
739
740 pub fn load(path: &Path) -> std::io::Result<Store> {
744 let text = match std::fs::read_to_string(path) {
745 Ok(t) => t,
746 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Store::default()),
747 Err(e) => return Err(e),
748 };
749 let mut findings = Vec::new();
750 for (i, line) in text.lines().enumerate() {
751 let line = line.trim();
752 if line.is_empty() {
753 continue;
754 }
755 let f: Finding = serde_json::from_str(line).map_err(|e| {
756 std::io::Error::new(
757 std::io::ErrorKind::InvalidData,
758 format!("findings.jsonl line {}: {e}", i + 1),
759 )
760 })?;
761 findings.push(f);
762 }
763 Ok(Store { findings })
764 }
765
766 pub fn append(&mut self, path: &Path, finding: Finding) -> std::io::Result<bool> {
771 finding
772 .is_citable()
773 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
774 if self.findings.iter().any(|f| f.cell_id == finding.cell_id) {
775 return Ok(false); }
777 if let Some(parent) = path.parent() {
778 std::fs::create_dir_all(parent)?;
779 }
780 let line = serde_json::to_string(&finding)
781 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
782 use std::io::Write;
783 let mut f = std::fs::OpenOptions::new()
784 .create(true)
785 .append(true)
786 .open(path)?;
787 writeln!(f, "{line}")?;
788 self.findings.push(finding);
789 Ok(true)
790 }
791
792 pub fn get(&self, cell_id: &str) -> Option<&Finding> {
793 self.findings.iter().find(|f| f.cell_id == cell_id)
794 }
795
796 pub fn cite(
800 &self,
801 cell_id: &str,
802 req: &CitationRequest,
803 oracle: &dyn SrcChangeOracle,
804 ) -> CiteOutcome {
805 let Some(f) = self.get(cell_id) else {
806 return CiteOutcome::Refused {
807 cell_id: cell_id.to_string(),
808 reason: CiteRefusal::NotFound,
809 };
810 };
811 if let Err(why) = f.is_citable() {
813 return CiteOutcome::Refused {
814 cell_id: cell_id.to_string(),
815 reason: CiteRefusal::NonCitable(why),
816 };
817 }
818 if !f.evidence_tier.can_be_cited_as(req.as_strength) {
820 return CiteOutcome::Refused {
821 cell_id: cell_id.to_string(),
822 reason: CiteRefusal::TierTooWeak {
823 has: f.evidence_tier.strength().label().to_string(),
824 requested: req.as_strength.label().to_string(),
825 },
826 };
827 }
828 if let Err(m) = f.scope.supports(&req.claim_scope) {
830 return CiteOutcome::Refused {
831 cell_id: cell_id.to_string(),
832 reason: CiteRefusal::OutOfScope(m),
833 };
834 }
835 let freshness = oracle.src_changed_since(&f.commit_sha);
838 if freshness != SrcChange::Fresh {
839 return CiteOutcome::Refused {
840 cell_id: cell_id.to_string(),
841 reason: CiteRefusal::Stale(freshness.label()),
842 };
843 }
844 CiteOutcome::Granted {
845 finding: Box::new(f.clone()),
846 freshness,
847 granted_as: req.as_strength,
848 }
849 }
850
851 pub fn consult(
861 &self,
862 region_query: &str,
863 scope_filter: Option<&Scope>,
864 oracle: &dyn SrcChangeOracle,
865 ) -> Vec<ConsultHit> {
866 let q = region_query.to_ascii_lowercase();
867 let mut hits: Vec<ConsultHit> = self
868 .findings
869 .iter()
870 .filter(|f| q.is_empty() || f.region.to_ascii_lowercase().contains(&q))
871 .filter(|f| match scope_filter {
872 None => true,
873 Some(s) => f.scope.supports(s).is_ok(),
874 })
875 .map(|f| ConsultHit {
876 finding: f.clone(),
877 freshness: oracle.src_changed_since(&f.commit_sha),
878 })
879 .collect();
880 hits.sort_by(|a, b| {
882 b.finding
883 .evidence_tier
884 .strength()
885 .cmp(&a.finding.evidence_tier.strength())
886 .then_with(|| fresh_rank(&a.freshness).cmp(&fresh_rank(&b.freshness)))
887 .then_with(|| b.finding.created_utc.cmp(&a.finding.created_utc))
888 });
889 hits
890 }
891}
892
893fn fresh_rank(s: &SrcChange) -> u8 {
894 match s {
895 SrcChange::Fresh => 0,
896 SrcChange::Unknown(_) => 1,
897 SrcChange::Stale => 2,
898 }
899}
900
901#[derive(Debug, Clone)]
903pub struct ConsultHit {
904 pub finding: Finding,
905 pub freshness: SrcChange,
906}
907
908impl ConsultHit {
909 pub fn render(&self) -> String {
910 format!("[{}] {}", self.freshness.label(), self.finding.summary())
911 }
912}
913
914#[cfg(test)]
915mod tests {
916 use super::*;
917
918 struct FakeOracle {
920 map: std::collections::HashMap<String, SrcChange>,
921 default: SrcChange,
922 }
923 impl FakeOracle {
924 fn new(default: SrcChange) -> Self {
925 FakeOracle {
926 map: Default::default(),
927 default,
928 }
929 }
930 fn with(mut self, sha: &str, c: SrcChange) -> Self {
931 self.map.insert(sha.to_string(), c);
932 self
933 }
934 }
935 impl SrcChangeOracle for FakeOracle {
936 fn src_changed_since(&self, sha: &str) -> SrcChange {
937 self.map.get(sha).cloned().unwrap_or(self.default.clone())
938 }
939 }
940
941 fn sample(tier: EvidenceTier, sha: &str, scope: Scope) -> Finding {
942 Finding::new(
943 "ParallelSM/per-chunk-serialization",
944 "247ms per-chunk serialization tax dominates T1",
945 sha,
946 scope,
947 "regular-file",
948 9,
949 0.012,
950 tier,
951 Verdict::Located,
952 247.0,
953 "ms",
954 "removal-oracle DIS-15",
955 "2026-06-13",
956 )
957 }
958
959 fn amd_t4() -> Scope {
960 Scope::new("silesia", "amd", Threads::Fixed(4))
961 }
962
963 #[test]
964 fn cell_id_is_deterministic_and_derived() {
965 let a = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
966 let b = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
967 assert_eq!(a.cell_id, b.cell_id);
968 assert!(a.cell_id.starts_with("F-"));
969 assert_eq!(a.cell_id.len(), 14);
970 a.is_citable().unwrap();
971 }
972
973 #[test]
974 fn rss_dimension_forks_the_cell_and_is_citable() {
975 let wall = sample(EvidenceTier::FrozenMatrix, "abc1234", amd_t4());
978 let mem = wall.clone().with_rss(412.5);
979 assert_ne!(wall.cell_id, mem.cell_id, "rss must fork the id");
980 assert_eq!(mem.rss_mb, Some(412.5));
981 mem.is_citable().unwrap();
982 assert_eq!(mem.derive_id(), wall.clone().with_rss(412.5).cell_id);
984 }
985
986 #[test]
987 fn rewording_claim_does_not_fork_the_cell() {
988 let mut a = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
989 let id0 = a.cell_id.clone();
990 a.claim = "totally different prose wording".into();
991 assert_eq!(a.derive_id(), id0);
993 }
994
995 #[test]
996 fn tampered_id_is_non_citable() {
997 let mut a = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
998 a.cell_id = "F-000000000000".into();
999 assert!(a.is_citable().is_err());
1000 }
1001
1002 #[test]
1003 fn empty_id_is_non_citable() {
1004 let mut a = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
1005 a.cell_id = String::new();
1006 assert!(a.is_citable().is_err());
1007 }
1008
1009 #[test]
1011 fn hypothesis_cannot_be_cited_as_strong() {
1012 let oracle = FakeOracle::new(SrcChange::Fresh);
1013 let mut store = Store::default();
1014 let f = sample(EvidenceTier::SourceRead, "abc1234", amd_t4());
1015 let id = f.cell_id.clone();
1016 store.findings.push(f);
1017 let req = CitationRequest {
1018 as_strength: Strength::Strong,
1019 claim_scope: amd_t4(),
1020 };
1021 let out = store.cite(&id, &req, &oracle);
1022 match out {
1023 CiteOutcome::Refused {
1024 reason: CiteRefusal::TierTooWeak { .. },
1025 ..
1026 } => {}
1027 other => panic!("expected TierTooWeak refusal, got {other:?}"),
1028 }
1029 let req_down = CitationRequest {
1031 as_strength: Strength::Hypothesis,
1032 claim_scope: amd_t4(),
1033 };
1034 assert!(store.cite(&id, &req_down, &oracle).is_granted());
1035 }
1036
1037 #[test]
1039 fn whole_program_attribution_is_weak() {
1040 assert_eq!(
1041 EvidenceTier::WholeProgramAttribution.strength(),
1042 Strength::Weak
1043 );
1044 assert!(!EvidenceTier::WholeProgramAttribution.can_be_cited_as(Strength::Hypothesis));
1045 assert!(EvidenceTier::Perturbation.can_be_cited_as(Strength::Strong));
1046 }
1047
1048 #[test]
1050 fn amd_cell_refused_as_intel_law() {
1051 let oracle = FakeOracle::new(SrcChange::Fresh);
1052 let mut store = Store::default();
1053 let f = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
1054 let id = f.cell_id.clone();
1055 store.findings.push(f);
1056 let req = CitationRequest {
1057 as_strength: Strength::Strong,
1058 claim_scope: Scope::new("silesia", "intel", Threads::Fixed(4)),
1059 };
1060 match store.cite(&id, &req, &oracle) {
1061 CiteOutcome::Refused {
1062 reason: CiteRefusal::OutOfScope(m),
1063 ..
1064 } => assert_eq!(m.axis, "arch"),
1065 other => panic!("expected arch OutOfScope refusal, got {other:?}"),
1066 }
1067 let req_wild = CitationRequest {
1069 as_strength: Strength::Strong,
1070 claim_scope: Scope::new("silesia", "*", Threads::Fixed(4)),
1071 };
1072 assert!(store.cite(&id, &req_wild, &oracle).is_granted());
1073 }
1074
1075 #[test]
1077 fn t4_cell_refused_as_t8_claim() {
1078 let oracle = FakeOracle::new(SrcChange::Fresh);
1079 let mut store = Store::default();
1080 let f = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
1081 let id = f.cell_id.clone();
1082 store.findings.push(f);
1083 let req = CitationRequest {
1084 as_strength: Strength::Strong,
1085 claim_scope: Scope::new("silesia", "amd", Threads::Fixed(8)),
1086 };
1087 match store.cite(&id, &req, &oracle) {
1088 CiteOutcome::Refused {
1089 reason: CiteRefusal::OutOfScope(m),
1090 ..
1091 } => assert_eq!(m.axis, "threads"),
1092 other => panic!("expected threads OutOfScope refusal, got {other:?}"),
1093 }
1094 }
1095
1096 #[test]
1098 fn stale_cell_refused_as_current() {
1099 let oracle = FakeOracle::new(SrcChange::Fresh).with("old1234", SrcChange::Stale);
1101 let mut store = Store::default();
1102 let f = sample(EvidenceTier::Perturbation, "old1234", amd_t4());
1103 let id = f.cell_id.clone();
1104 store.findings.push(f);
1105 let req = CitationRequest {
1106 as_strength: Strength::Strong,
1107 claim_scope: amd_t4(),
1108 };
1109 match store.cite(&id, &req, &oracle) {
1110 CiteOutcome::Refused {
1111 reason: CiteRefusal::Stale(_),
1112 ..
1113 } => {}
1114 other => panic!("expected Stale refusal (the #17 guard), got {other:?}"),
1115 }
1116 }
1117
1118 #[test]
1120 fn unknown_freshness_refused_as_current() {
1121 let oracle =
1122 FakeOracle::new(SrcChange::Fresh).with("ghost99", SrcChange::Unknown("no sha".into()));
1123 let mut store = Store::default();
1124 let f = sample(EvidenceTier::Oracle, "ghost99", amd_t4());
1125 let id = f.cell_id.clone();
1126 store.findings.push(f);
1127 let req = CitationRequest {
1128 as_strength: Strength::Strong,
1129 claim_scope: amd_t4(),
1130 };
1131 assert!(!store.cite(&id, &req, &oracle).is_granted());
1132 }
1133
1134 #[test]
1136 fn fresh_strong_in_scope_is_granted() {
1137 let oracle = FakeOracle::new(SrcChange::Fresh);
1138 let mut store = Store::default();
1139 let f = sample(EvidenceTier::Perturbation, "head1234", amd_t4());
1140 let id = f.cell_id.clone();
1141 store.findings.push(f);
1142 let req = CitationRequest {
1143 as_strength: Strength::Strong,
1144 claim_scope: amd_t4(),
1145 };
1146 assert!(store.cite(&id, &req, &oracle).is_granted());
1147 }
1148
1149 #[test]
1151 fn consult_surfaces_the_ledger() {
1152 let oracle = FakeOracle::new(SrcChange::Fresh).with("old1234", SrcChange::Stale);
1153 let mut store = Store::default();
1154 store.findings.push(sample(
1155 EvidenceTier::WholeProgramAttribution,
1156 "old1234",
1157 amd_t4(),
1158 ));
1159 store
1160 .findings
1161 .push(sample(EvidenceTier::Perturbation, "head1234", amd_t4()));
1162 let hits = store.consult("parallelsm", None, &oracle);
1163 assert_eq!(hits.len(), 2);
1164 assert_eq!(hits[0].finding.evidence_tier, EvidenceTier::Perturbation);
1166 assert_eq!(hits[0].freshness, SrcChange::Fresh);
1167 assert_eq!(hits[1].freshness, SrcChange::Stale);
1169 }
1170
1171 #[test]
1173 fn jsonl_round_trip() {
1174 let dir = std::env::temp_dir().join(format!("fulcrum-finding-{}", std::process::id()));
1175 let path = dir.join("findings.jsonl");
1176 let _ = std::fs::remove_file(&path);
1177 let mut store = Store::default();
1178 let f = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
1179 let id = f.cell_id.clone();
1180 assert!(store.append(&path, f).unwrap());
1181 assert!(!store
1183 .append(&path, sample(EvidenceTier::Oracle, "abc1234", amd_t4()))
1184 .unwrap());
1185 let reloaded = Store::load(&path).unwrap();
1186 assert_eq!(reloaded.findings.len(), 1);
1187 assert_eq!(reloaded.get(&id).unwrap().value, 247.0);
1188 reloaded.get(&id).unwrap().is_citable().unwrap();
1189 let _ = std::fs::remove_dir_all(&dir);
1190 }
1191
1192 #[test]
1193 fn append_refuses_non_citable() {
1194 let dir = std::env::temp_dir().join(format!("fulcrum-finding-nc-{}", std::process::id()));
1195 let path = dir.join("findings.jsonl");
1196 let _ = std::fs::remove_file(&path);
1197 let mut store = Store::default();
1198 let mut f = sample(EvidenceTier::Oracle, "abc1234", amd_t4());
1199 f.cell_id = "F-deadbeefdead".into(); assert!(store.append(&path, f).is_err());
1201 let _ = std::fs::remove_dir_all(&dir);
1202 }
1203}