Skip to main content

fulcrum/
finding.rs

1//! finding.rs — the FULCRUM FINDING STORE: the single citable surface for
2//! every conclusion the campaign reaches. It supersedes banked-conclusion
3//! prose (the `~/.claude/.../memory/*.md` sentences). Prose becomes connective
4//! tissue *between* machine verdicts; the verdicts themselves live here, each
5//! one a [`Finding`] = CELL with a full machine-checkable fingerprint.
6//!
7//! ## The two errors this store is built to make impossible
8//!
9//! 1. **The stale-disproof citation (#17 "247ms tax dominates").** A sentence
10//!    was banked with no machine-checkable scope, then cited as eternal fact
11//!    long after the source it measured had changed — real-then, gone-at-HEAD.
12//!    Cure: every CELL carries the `commit_sha` it was measured at, and
13//!    [`Store::cite`] *refuses* to quote a CELL as current once
14//!    `git diff <commit_sha>..HEAD -- src/` is non-empty ([`SrcChange::Stale`]).
15//!    A stale CELL must be re-run to refresh; it cannot speak for HEAD.
16//!
17//! 2. **Not consulting the measured ledger before interpreting.** The ledger
18//!    had ALREADY located the causes by removal-oracle, but a whole session
19//!    re-derived (and re-mislabeled) them in prose. Cure: [`Store::consult`]
20//!    is the FIRST thing any new hypothesis work queries — "what do we already
21//!    know (with tiers + scope) about region X?" — so re-derivation in prose is
22//!    unnecessary and visibly redundant.
23//!
24//! ## The non-negotiable predicates (all pure, all unit-tested)
25//!
26//! * **Citability** ([`Finding::is_citable`]): a finding with no well-formed
27//!   `cell_id` is NON-CITABLE by construction. The `cell_id` is a deterministic
28//!   content hash of the fingerprint, so it cannot be hand-waved into existence.
29//! * **Tier honesty** ([`Store::cite`] + [`EvidenceTier::can_be_cited_as`]):
30//!   the store refuses to let a HYPOTHESIS/WEAK cell be cited as a STRONG
31//!   finding. Tiers: perturbation/oracle/frozen-matrix = STRONG;
32//!   self-validated-tool/source-read = HYPOTHESIS; whole-program-attribution =
33//!   WEAK.
34//! * **Auto-decay** ([`SrcChange`]): a cell whose `commit_sha`'s `src/` changed
35//!   is auto-stamped STALE and cannot be quoted as current.
36//! * **Scope-boundedness** ([`Scope::supports`]): a cell measured at
37//!   (corpus=silesia, arch=AMD, T=4) refuses to be cited as a claim about any
38//!   other (corpus, arch, T). No silent generalization.
39
40use crate::compare::{hex32, sha256};
41use serde::{Deserialize, Serialize};
42use std::path::{Path, PathBuf};
43use std::process::Command;
44
45// ─── Evidence tiers ───────────────────────────────────────────────────────────
46
47/// The provenance class of a finding — how the value was obtained. This pins
48/// the *strength* of any citation: the verdict tools (perturbation, oracle,
49/// frozen matrix) earn STRONG; a self-validated tool reading or a source read
50/// is only a HYPOTHESIS; raw whole-program attribution is WEAK (the CPU-sum lie
51/// FULCRUM exists to defeat).
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53pub enum EvidenceTier {
54    /// Causal slow/-speed-injection perturbation with a frequency-neutral
55    /// control (the gold standard of this campaign).
56    Perturbation,
57    /// Region-removal / window-seed oracle: the lever's ceiling, measured by
58    /// removing it, not extrapolating a slope.
59    Oracle,
60    /// Frozen-host interleaved best-of-N matrix run (`fulcrum score` / `compare`).
61    FrozenMatrix,
62    /// A self-validated tool reading (passed its positive/negative controls)
63    /// but NOT yet causally confirmed — a hypothesis generator.
64    SelfValidatedTool,
65    /// A reading of source code (vendor or ours). A hypothesis, never a verdict.
66    SourceRead,
67    /// Whole-program attribution (busy-time / latency-share / critical-path
68    /// "blame"). Analyst-biasable; the weakest tier.
69    WholeProgramAttribution,
70}
71
72/// The three citation strengths a tier maps onto.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
74pub enum Strength {
75    /// Whole-program attribution only.
76    Weak = 0,
77    /// Self-validated tool reading or source read — a hypothesis.
78    Hypothesis = 1,
79    /// Perturbation, oracle, or frozen matrix — a verdict.
80    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    /// Parse a requested strength for `cite --as-tier`.
92    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    /// The citation strength this tier earns.
115    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    /// Tier-honesty predicate: may a finding of this tier be cited *as* a claim
126    /// of the requested strength? You can always cite DOWN (a STRONG finding
127    /// cited as a hypothesis), never UP (a HYPOTHESIS cited as STRONG).
128    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// ─── Verdict ──────────────────────────────────────────────────────────────────
150
151/// The conclusion a finding records. Kept deliberately small and typed so a
152/// verdict is never free-text prose. `Located`/`Refuted` are the campaign's
153/// causal-attribution verdicts; `Win`/`Tie`/`Loss` are the matrix verdicts.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155pub enum Verdict {
156    /// A removal-oracle / perturbation LOCATED a cause here.
157    Located,
158    /// A direction was causally REFUTED (with a mechanism, per the rules).
159    Refuted,
160    /// Subject beat the field in this cell (correct bytes).
161    Win,
162    /// Within measurement spread — parity, not a win.
163    Tie,
164    /// Subject lost this cell.
165    Loss,
166    /// A claim SURVIVED an audit as stated.
167    Survives,
168    /// A claim NARROWED to a smaller true scope.
169    NarrowsToScope,
170    /// A claim was FALSE even narrowed.
171    False,
172    /// Anything else, named explicitly (still not free prose — a short tag).
173    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// ─── Scope ──────────────────────────────────────────────────────────────────
206
207/// The thread-count a cell was measured at, or that a citation asks about.
208/// `Any` is the wildcard used ONLY by a citation that does not constrain T; a
209/// FINDING is never stored as `Any` (a measurement always ran at a concrete T,
210/// or an explicit sweep that you would store as one finding per T).
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub enum Threads {
213    Fixed(usize),
214    /// `-P0` / all-cores auto.
215    Auto,
216    /// Citation-side wildcard: "I don't constrain T".
217    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    /// Does this MEASURED thread-cell answer a citation asking about `claim`?
243    /// A concrete measurement answers only its own T (or a wildcard claim).
244    fn answers(&self, claim: &Threads) -> bool {
245        match claim {
246            Threads::Any => true,
247            _ => self == claim,
248        }
249    }
250}
251
252/// The (corpus, arch, threads) coordinate. A FINDING stores the coordinate it
253/// was MEASURED at; a CITATION supplies the coordinate it wants to CLAIM about.
254/// A finding `supports` a claim only when each axis of the claim is either the
255/// finding's own value or an explicit wildcard.
256#[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    /// The label used both for display and as a fingerprint ingredient.
273    pub fn label(&self) -> String {
274        format!("{}/{}/{}", self.arch, self.corpus, self.threads.label())
275    }
276
277    /// Scope-bounded citation predicate. `self` is the FINDING's measured scope;
278    /// `claim` is what the citation asserts. Returns `Ok(())` only when the
279    /// finding's measurement actually covers the claim. The wildcard `*` (and
280    /// `Threads::Any`) on the CLAIM side means "unconstrained on this axis" and
281    /// always matches; a wildcard on the FINDING side is not allowed (a
282    /// measurement is concrete) and is treated literally.
283    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/// Why a scope-bounded citation was refused.
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct ScopeMismatch {
309    pub axis: String,
310    pub measured: String,
311    pub claimed: String,
312}
313
314// ─── The Finding (a persisted CELL) ───────────────────────────────────────────
315
316/// One persisted CELL. The `cell_id` is derived (a content hash of the
317/// fingerprint) and re-derivable; it is NOT user-set, so a "finding" typed into
318/// prose with no measurement can never mint a `cell_id` and is non-citable by
319/// construction.
320#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
321pub struct Finding {
322    /// Deterministic content hash of the fingerprint (see [`Finding::derive_id`]).
323    /// Stored so the JSONL is self-describing; re-derived and checked on load.
324    pub cell_id: String,
325    /// The subsystem/region this finding is ABOUT (the consult key), e.g.
326    /// `"ParallelSM/per-chunk-serialization"`.
327    pub region: String,
328    /// The conclusion in one short human line. Connective tissue ONLY — never
329    /// the verdict (that is `verdict`) and never a substitute for the cell_id.
330    pub claim: String,
331    /// The project-repo commit the binaries/source were measured at. The decay
332    /// anchor.
333    pub commit_sha: String,
334    /// Measured coordinate.
335    pub scope: Scope,
336    /// Output sink (`/dev/null`, `regular-file`, `stdout`) — the SINK LAW axis.
337    pub sink: String,
338    /// Sample count (best-of-N).
339    pub n: usize,
340    /// Inter-run spread (max/min − 1).
341    pub inter_run_spread: f64,
342    /// Provenance class.
343    pub evidence_tier: EvidenceTier,
344    /// The conclusion.
345    pub verdict: Verdict,
346    /// The measured quantity and its unit.
347    pub value: f64,
348    pub dimension: String,
349    /// Peak resident-set size of the SUBJECT arm, in MiB, when the runner
350    /// captured it (`/usr/bin/time -v` "Maximum resident set size"). `None` ⇒
351    /// memory was not measured for this cell. When `Some`, it is folded into the
352    /// fingerprint (the rss_mb dimension) so a cell that gates MEMORY is a
353    /// distinct CELL from a wall-only one (the ship goal is memory AND
354    /// performance).
355    #[serde(default)]
356    pub rss_mb: Option<f64>,
357    /// How it was measured (perturbation script / oracle name / `fulcrum score`).
358    pub method: String,
359    /// ISO date the measurement was taken.
360    pub created_utc: String,
361}
362
363impl Finding {
364    /// Build a finding and stamp its derived `cell_id`. This is the ONLY mint —
365    /// there is no constructor that takes a caller-supplied id.
366    #[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    /// Attach a captured peak RSS (MiB) to this finding and RE-DERIVE its id (the
404    /// rss_mb dimension is part of the cell identity). A memory-gated cell is a
405    /// distinct CELL from a wall-only one. Chainable after [`Finding::new`].
406    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    /// The fingerprint: the canonical, order-stable string the `cell_id` hashes.
413    /// Two findings with the same fingerprint are the same CELL. `value` is
414    /// rounded to 6 sig-figs of its own magnitude so float formatting jitter
415    /// cannot fork the id. `claim` is deliberately EXCLUDED — re-wording the
416    /// prose must NOT mint a new cell (the prose is connective tissue).
417    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        // The rss_mb dimension is appended ONLY when measured, so a wall-only
434        // cell keeps its historical id while a memory-gated cell forks to a
435        // distinct CELL (memory AND performance).
436        match self.rss_mb {
437            Some(r) => format!("{base}|rss_mb={}", canon_value(r)),
438            None => base,
439        }
440    }
441
442    /// Derive the `cell_id` from the fingerprint. `F-` prefix + 12 hex chars of
443    /// sha256 — short enough to cite, wide enough not to collide in a campaign.
444    pub fn derive_id(&self) -> String {
445        let digest = sha256(self.fingerprint().as_bytes());
446        format!("F-{}", &hex32(&digest)[..12])
447    }
448
449    /// Citability: a finding is citable only if its stored `cell_id` is
450    /// well-formed AND matches the re-derived id of its own fingerprint. A
451    /// hand-edited JSONL row whose id was tampered with (or a prose "finding"
452    /// with a made-up id) fails here.
453    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    /// A one-line greppable summary (the consult-table row).
477    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
496/// Round a value to a stable canonical string so float-format jitter cannot
497/// fork a `cell_id`. 6 significant figures relative to magnitude.
498fn 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    // strip trailing zeros / dot so 1.50 and 1.5 hash identically
509    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// ─── Staleness (auto-decay) ───────────────────────────────────────────────────
527
528/// The freshness of a finding relative to HEAD of the project repo.
529#[derive(Debug, Clone, PartialEq, Eq)]
530pub enum SrcChange {
531    /// `git diff <sha>..HEAD -- src/` is empty — the measured source is current.
532    Fresh,
533    /// `src/` changed since the finding's commit — the finding is STALE and
534    /// cannot be quoted as current. (Kills the #17 stale-247ms citation.)
535    Stale,
536    /// The freshness could not be determined (sha unknown to the repo, repo not
537    /// a git tree, git unavailable). Treated conservatively as un-citable-as-
538    /// current — like a provenance UNKNOWN, you may not interpret it.
539    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
552/// An oracle that answers "did `src/` change since this commit?". The real
553/// implementation shells out to git; tests inject a deterministic map so the
554/// decay predicate is unit-testable without a fixture repo.
555pub trait SrcChangeOracle {
556    fn src_changed_since(&self, commit_sha: &str) -> SrcChange;
557}
558
559/// The production oracle: `git -C <repo> diff --quiet <sha>..HEAD -- src/`.
560/// Exit 0 ⇒ no change ⇒ FRESH; exit 1 ⇒ changed ⇒ STALE; anything else ⇒
561/// UNKNOWN (bad sha, not a repo, git missing).
562pub struct GitSrcOracle {
563    pub repo: PathBuf,
564    /// Path(s) under the repo whose change invalidates a finding. Default `src`.
565    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        // Verify the sha exists in the repo first, so an unknown sha is UNKNOWN
583        // (conservative) rather than silently FRESH.
584        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
615/// A deterministic oracle that answers a FIXED [`SrcChange`] regardless of the
616/// queried commit. It exists so the CLI `run --dry-run --gate --fixture-oracle`
617/// path can certify a SYNTHETIC/fixture commit (which by construction is not in any
618/// git repo, so the live [`GitSrcOracle`] would answer `UNKNOWN("commit … not in
619/// repo")` and refuse at the freshness gate). NEVER select this on a LIVE run — the
620/// caller must keep real measurements on [`GitSrcOracle`] so a real finding's
621/// freshness is checked against actual `src/` changes. The choice MUST be explicit
622/// and logged.
623pub struct FixedOracle {
624    pub answer: SrcChange,
625}
626
627impl FixedOracle {
628    /// A fixture oracle that always answers FRESH (the dry-run certification case).
629    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// ─── Citation (the refusal-bearing read path) ─────────────────────────────────
643
644/// What a citation ASSERTS: the strength it wants to claim and the scope it
645/// wants to claim about. The store grants the citation only if the finding
646/// clears all four gates (citable, fresh, tier, scope).
647#[derive(Debug, Clone)]
648pub struct CitationRequest {
649    /// The strength the citer wants to claim (e.g. `Strong`). A
650    /// whole-program-attribution cell cited `as Strong` is refused.
651    pub as_strength: Strength,
652    /// The coordinate the citer wants to claim about. Wildcards (`*` / `Any`)
653    /// allowed only here, on the CLAIM side.
654    pub claim_scope: Scope,
655}
656
657/// The outcome of a citation attempt — granted (the finding may be quoted) or
658/// refused (with the machine reason that names the failed gate).
659#[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/// The specific gate a citation failed. Each variant is a machine-checkable
679/// fact, not prose.
680#[derive(Debug, Clone, PartialEq, Eq)]
681pub enum CiteRefusal {
682    /// No such cell_id in the store.
683    NotFound,
684    /// The finding's own citability check failed (malformed/tampered id).
685    NonCitable(String),
686    /// The finding is STALE (or freshness UNKNOWN) — cannot be quoted as
687    /// current. Carries the freshness label.
688    Stale(String),
689    /// The finding's tier is too weak for the requested strength.
690    TierTooWeak { has: String, requested: String },
691    /// The citation's scope is outside the finding's measured scope.
692    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// ─── The Store ────────────────────────────────────────────────────────────────
720
721/// The persistent finding store. An append-only JSONL ledger: one [`Finding`]
722/// per line. Append-only because a measurement is a historical fact — you
723/// SUPERSEDE a stale finding by adding a fresh one at a newer commit, you do
724/// not delete the old (its staleness is computed, not asserted).
725#[derive(Debug, Clone, Default)]
726pub struct Store {
727    pub findings: Vec<Finding>,
728}
729
730impl Store {
731    /// The default store path: `$FULCRUM_FINDING_STORE`, else
732    /// `<repo>/.fulcrum/findings.jsonl`.
733    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    /// Load a store from a JSONL file. A missing file is an empty store (the
741    /// consult-first surface must work before the first finding is added).
742    /// Malformed lines are an error (a corrupt ledger must not silently shrink).
743    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    /// Append a finding to the on-disk ledger and the in-memory store. Refuses
767    /// to write a non-citable finding (so the ledger can never hold a row that
768    /// is unquotable by construction). Idempotent on `cell_id`: re-adding the
769    /// same CELL is a no-op (the fingerprint already determined identity).
770    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); // already present
776        }
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    /// The CITE API. Walks all four gates in order and returns the first
797    /// failure, or grants the citation. `oracle` supplies the freshness verdict
798    /// (real = git; tests = injected).
799    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        // Gate 1: citability.
812        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        // Gate 2: tier honesty.
819        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        // Gate 3: scope.
829        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        // Gate 4: freshness (auto-decay). Run last so the cheaper pure gates
836        // short-circuit before shelling out to git.
837        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    /// The CONSULT-FIRST API — the FIRST thing queried before any new
852    /// hypothesis work. "What do we already know (with tiers + scope) about
853    /// region/cell X?" Returns every finding whose region matches the query
854    /// (case-insensitive substring) and that falls inside the optional scope
855    /// filter, each annotated with its current freshness so a reader sees at a
856    /// glance what is STRONG-and-FRESH vs what needs a re-run.
857    ///
858    /// This is the cure for the root bias: the ledger already located the
859    /// causes; consult surfaces them so no one re-derives them in prose.
860    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        // Strongest + freshest first so the actionable verdicts lead.
881        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/// One row of a consult result: the finding plus its computed freshness.
902#[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    /// A deterministic oracle for tests: maps commit_sha → SrcChange.
919    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        // The rss_mb dimension is part of the cell identity: a memory-gated cell
976        // is a DISTINCT, still-citable CELL from its wall-only twin.
977        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        // and the fork is deterministic.
983        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        // claim is excluded from the fingerprint; the id is unchanged.
992        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    // ── CI self-test: a HYPOTHESIS cell cannot be cited as STRONG ──────────────
1010    #[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        // ...but it CAN be cited as a hypothesis (cite down is allowed).
1030        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    // ── CI self-test: a WEAK cell cannot be cited as STRONG ───────────────────
1038    #[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    // ── CI self-test: an AMD cell cannot be cited as an Intel law ─────────────
1049    #[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        // A claim that does NOT constrain arch (wildcard) is fine.
1068        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    // ── CI self-test: a T4 cell cannot be cited as a T8 claim ─────────────────
1076    #[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    // ── CI self-test: THE #17 GUARD — a STALE cell cannot be cited as current ──
1097    #[test]
1098    fn stale_cell_refused_as_current() {
1099        // The finding was measured at commit `old1234`. src/ has since changed.
1100        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    // ── CI self-test: UNKNOWN freshness is also refused as current ────────────
1119    #[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    // ── CI self-test: a FRESH, STRONG, in-scope cell IS granted ───────────────
1135    #[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    // ── CONSULT-FIRST surface returns known findings with tiers + freshness ────
1150    #[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        // Strongest first: the Perturbation (STRONG) leads the WholeProgram (WEAK).
1165        assert_eq!(hits[0].finding.evidence_tier, EvidenceTier::Perturbation);
1166        assert_eq!(hits[0].freshness, SrcChange::Fresh);
1167        // The stale weak one is present but flagged STALE.
1168        assert_eq!(hits[1].freshness, SrcChange::Stale);
1169    }
1170
1171    // ── append/load round-trip preserves every cell exactly ───────────────────
1172    #[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        // re-adding the same cell is a no-op (idempotent on fingerprint).
1182        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(); // tamper
1200        assert!(store.append(&path, f).is_err());
1201        let _ = std::fs::remove_dir_all(&dir);
1202    }
1203}