Skip to main content

jev_repl/
mock.rs

1//! Offline answers, so the shapes can be learned without an API key.
2//!
3//! Deterministic: the same state and question always produce the same numbers. Plausible, not
4//! predictive — nothing here reasons about anything.
5
6use serde_json::{Value, json};
7use typesafe::{Answer, ModelMetadata};
8
9/// Simulate an answer to one question. `None` for question shapes the simulator cannot fake.
10pub fn answer(state: &Value, name: &str, question: &Value) -> Option<Answer> {
11    let state = state.to_string();
12    let kind = question.get("type")?.as_str()?;
13    let instructions = question
14        .get("instructions")
15        .map(ToString::to_string)
16        .unwrap_or_default();
17    let seed = format!("{state}\u{1}{name}\u{1}{instructions}");
18    match kind {
19        "noul" => {
20            let p = round(0.04 + 0.92 * unit(&[&seed, "noul"]));
21            from_value(json!({ "noul": p }))
22        }
23        "choice" => {
24            let labels: Vec<String> = question
25                .get("criteria")?
26                .as_object()?
27                .keys()
28                .cloned()
29                .collect();
30            let probs = distribution(&seed, &state, &labels);
31            let (choice, _) = probs
32                .iter()
33                .cloned()
34                .max_by(|a, b| a.1.total_cmp(&b.1))
35                .unwrap_or_default();
36            let map: serde_json::Map<String, Value> =
37                probs.iter().map(|(l, p)| (l.clone(), json!(p))).collect();
38            let conf = confidence(probs.iter().map(|(_, p)| *p));
39            from_value(json!({"choice": choice, "probabilities": map, "confidence": conf}))
40        }
41        "score" => {
42            let levels = question.get("criteria")?.as_array()?;
43            let keys: Vec<String> = (0..levels.len()).map(|i| i.to_string()).collect();
44            let probs = distribution(&seed, &state, &keys);
45            let score = round(
46                probs
47                    .iter()
48                    .enumerate()
49                    .map(|(i, (_, p))| i as f64 * p)
50                    .sum(),
51            );
52            let legend: serde_json::Map<String, Value> = levels
53                .iter()
54                .enumerate()
55                .map(|(i, v)| (i.to_string(), v.clone()))
56                .collect();
57            let map: serde_json::Map<String, Value> =
58                probs.iter().map(|(k, p)| (k.clone(), json!(p))).collect();
59            let conf = confidence(probs.iter().map(|(_, p)| *p));
60            from_value(
61                json!({"score": score, "confidence": conf, "legend": legend, "probabilities": map}),
62            )
63        }
64        _ => None,
65    }
66}
67
68/// One answer as it arrives on the wire — what `:last` shows offline, and what the cost estimate
69/// measures to say what an answer of this shape costs.
70pub fn answer_json(answer: &Answer) -> Value {
71    match answer {
72        Answer::Noul(a) => json!({"type": "noul", "noul": a.noul}),
73        Answer::Choice(a) => json!({
74            "type": "choice", "choice": a.choice,
75            "probabilities": a.probabilities.iter()
76                .map(|(k, v)| (k.clone(), json!(v)))
77                .collect::<serde_json::Map<String, Value>>(),
78            "confidence": a.confidence,
79        }),
80        Answer::Score(a) => json!({
81            "type": "score", "score": a.score, "confidence": a.confidence,
82            "legend": a.legend.iter()
83                .map(|(k, v)| (k.to_string(), v.clone()))
84                .collect::<serde_json::Map<String, Value>>(),
85            "probabilities": a.probabilities.iter()
86                .map(|(k, v)| (k.to_string(), json!(v)))
87                .collect::<serde_json::Map<String, Value>>(),
88        }),
89        // An answer variant a later SDK adds: this one has no shape to measure or print.
90        _ => Value::Null,
91    }
92}
93
94/// What `:models` shows offline.
95pub fn models() -> Vec<ModelMetadata> {
96    [
97        (
98            "jev-latest",
99            "Alias for the newest jev release",
100            "2026-05-01",
101        ),
102        ("jev-2", "Previous generation", "2025-11-12"),
103    ]
104    .into_iter()
105    .filter_map(|(name, description, release_date)| {
106        serde_json::from_value(json!({
107            "name": name, "description": description, "release_date": release_date
108        }))
109        .ok()
110    })
111    .collect()
112}
113
114fn from_value(v: Value) -> Option<Answer> {
115    // The answer structs are `#[non_exhaustive]`, so they are built through their `Deserialize`
116    // impls — which also keeps this honest about the wire shape.
117    if v.get("noul").is_some() {
118        return serde_json::from_value(v).ok().map(Answer::Noul);
119    }
120    if v.get("choice").is_some() {
121        return serde_json::from_value(v).ok().map(Answer::Choice);
122    }
123    serde_json::from_value(v).ok().map(Answer::Score)
124}
125
126/// Weights per label, nudged up when the label's word shows up in the state, then normalized.
127fn distribution(seed: &str, state: &str, labels: &[String]) -> Vec<(String, f64)> {
128    let lower = state.to_lowercase();
129    let mut raw: Vec<(String, f64)> = labels
130        .iter()
131        .map(|label| {
132            let u = unit(&[seed, label]);
133            let mut w = 0.02 + u * u * u;
134            if label.len() > 3 && lower.contains(&label.to_lowercase()) {
135                w *= 4.0;
136            }
137            (label.clone(), w)
138        })
139        .collect();
140    let total: f64 = raw.iter().map(|(_, w)| w).sum();
141    if total <= 0.0 {
142        let even = round(1.0 / raw.len().max(1) as f64);
143        return raw.into_iter().map(|(l, _)| (l, even)).collect();
144    }
145    for (_, w) in &mut raw {
146        *w = round(*w / total);
147    }
148    // Rounding leaves a few thousandths on the table; give them to the leader.
149    let drift = 1.0 - raw.iter().map(|(_, w)| w).sum::<f64>();
150    if let Some(top) = raw
151        .iter_mut()
152        .max_by(|a, b| a.1.total_cmp(&b.1))
153        .filter(|_| drift.abs() > f64::EPSILON)
154    {
155        top.1 = round(top.1 + drift);
156    }
157    raw
158}
159
160/// 0 when the distribution is flat, 1 when it is certain — the same direction the API reports.
161fn confidence(probs: impl Iterator<Item = f64>) -> f64 {
162    let probs: Vec<f64> = probs.collect();
163    let n = probs.len();
164    if n < 2 {
165        return 1.0;
166    }
167    let max = probs.iter().copied().fold(0.0, f64::max);
168    let floor = 1.0 / n as f64;
169    round(((max - floor) / (1.0 - floor)).clamp(0.0, 1.0))
170}
171
172fn unit(parts: &[&str]) -> f64 {
173    (fnv(parts) % 100_000) as f64 / 100_000.0
174}
175
176fn fnv(parts: &[&str]) -> u64 {
177    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
178    for part in parts {
179        for b in part.as_bytes() {
180            h ^= *b as u64;
181            h = h.wrapping_mul(0x0000_0100_0000_01b3);
182        }
183        h ^= 0xff;
184        h = h.wrapping_mul(0x0000_0100_0000_01b3);
185    }
186    h
187}
188
189fn round(x: f64) -> f64 {
190    (x * 1000.0).round() / 1000.0
191}
192
193/// The body the mock answers would have arrived in — so `:last` teaches the same shape offline.
194pub fn body(answers: &[(String, Option<Answer>)], model: &str) -> String {
195    let mut map = serde_json::Map::new();
196    for (name, answer) in answers {
197        let value = match answer {
198            Some(answer) => answer_json(answer),
199            None => Value::Null,
200        };
201        map.insert(name.clone(), value);
202    }
203    serde_json::to_string_pretty(&serde_json::json!({
204        "model": model,
205        "answers": map,
206        "usage": {"input_tokens": null, "output_tokens": null},
207    }))
208    .unwrap_or_default()
209}