1use std::collections::BTreeMap;
34use std::path::Path;
35
36use serde::Serialize;
37
38use crate::queen::{self, Entry};
39use crate::{notes, stats};
40
41pub const STAMP_W: f64 = 1.0;
43pub const MISSED_W: f64 = crate::memory::VETOED_W as f64;
45
46const YES: [&str; 11] = ["yes", "y", "ok", "okay", "fine", "sure", "go", "ahead", "proceed", "approved", "lgtm"];
48
49fn norm(text: &str) -> String {
50 text.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ")
51}
52
53pub fn stamp(e: &Entry, answer: &str) -> bool {
56 let a = norm(answer);
57 let plan = norm(e.kind.proceeds());
58 (!plan.is_empty() && a.starts_with(&plan)) || yes(answer)
59}
60
61pub fn yes(answer: &str) -> bool {
63 let a = norm(answer);
64 !a.is_empty() && a.split(' ').all(|w| YES.contains(&w))
65}
66
67pub fn answered(store: &Path, e: &Entry, answer: &str, author: &str, now: i64) -> Option<&'static str> {
70 if !e.kind.escalates() {
71 return None;
72 }
73 let kind = if stamp(e, answer) { stats::QUEEN_STAMP } else { stats::QUEEN_NO };
74 stats::count(store, kind, &e.session, |ev| {
75 ev.ms = now;
76 ev.engineer = author.into();
77 ev.repo = e.repo.clone();
78 ev.why = format!("{:?}", e.kind);
79 ev.text = format!("{} {}", e.id, stats::excerpt(answer, 120));
80 });
81 Some(kind)
82}
83
84pub fn escalated(store: &Path, session: &str) -> bool {
87 !session.is_empty() && queen::entries(store).iter().any(|e| e.session == session && e.kind.escalates())
88}
89
90pub fn merged(state: &Path, session: &str) -> bool {
93 !notes::landed_by(state, session).is_empty()
94}
95
96pub fn missed(store: &Path, session: &str, cause: &str, id: &str, repo: &str, now: i64) -> bool {
100 if session.is_empty() || escalated(store, session) {
101 return false;
102 }
103 if stats::events(store).iter().any(|e| e.kind == stats::QUEEN_MISSED && e.text.split(' ').next() == Some(id)) {
104 return false;
105 }
106 stats::count(store, stats::QUEEN_MISSED, session, |ev| {
107 ev.ms = now;
108 ev.repo = repo.into();
109 ev.why = cause.into();
110 ev.text = id.into();
111 });
112 true
113}
114
115#[derive(Debug, Clone, Default, PartialEq, Serialize)]
117pub struct Yield {
118 pub answered: u64,
120 pub no: u64,
121 pub stamps: u64,
122 pub missed: u64,
123 pub share: Option<f64>,
125 pub reward: f64,
127 pub alpha: f64,
128 pub beta: f64,
129}
130
131pub fn of(counts: &BTreeMap<String, u64>) -> Yield {
133 let n = |k: &str| counts.get(k).copied().unwrap_or(0);
134 let (no, stamps, missed) = (n(stats::QUEEN_NO), n(stats::QUEEN_STAMP), n(stats::QUEEN_MISSED));
135 let answered = no + stamps;
136 Yield {
137 answered,
138 no,
139 stamps,
140 missed,
141 share: (answered > 0).then(|| no as f64 / answered as f64),
142 reward: no as f64 - STAMP_W * stamps as f64 - MISSED_W * missed as f64,
143 alpha: STAMP_W,
144 beta: MISSED_W,
145 }
146}
147
148pub fn team(home: &Path) -> Yield {
150 let mut all = stats::Bucket::default();
151 for b in stats::current(home) {
152 all.add(&b);
153 }
154 of(&all.counts)
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 use crate::queen::Kind;
161
162 fn tmp(tag: &str) -> std::path::PathBuf {
163 let d = std::env::temp_dir().join(format!("borg-escalation-{tag}-{}", std::process::id()));
164 let _ = std::fs::remove_dir_all(&d);
165 std::fs::create_dir_all(&d).unwrap();
166 d
167 }
168
169 fn entry(id: &str, kind: Kind, session: &str) -> Entry {
170 let (a, b) = kind.options();
171 Entry {
172 id: id.into(),
173 decision_key: format!("k{id}"),
174 kind,
175 question: format!("q {id}"),
176 options: vec![a.into(), b.into()],
177 default: a.into(),
178 evidence: vec![],
179 session: session.into(),
180 cwd: String::new(),
181 repo: "app".into(),
182 engineer: "ann@x".into(),
183 ms: 1,
184 answer: None,
185 answered_by: None,
186 answered_ms: None,
187 disagreeing: vec![],
188 dismissed: None,
189 dismissed_ms: None,
190 payload: None,
191 }
192 }
193
194 #[test]
195 fn letting_the_plan_go_ahead_is_a_stamp_and_changing_course_is_a_no() {
196 let irreversible = entry("q1", Kind::Irreversible, "s");
197 assert!(stamp(&irreversible, "proceed as planned"));
198 assert!(stamp(&irreversible, "Yes, fine."));
199 assert!(stamp(&irreversible, "ok go ahead"));
200 assert!(!stamp(&irreversible, "make it reversible first (backup, soft delete, a revert path)"));
201 assert!(!stamp(&irreversible, "yes but keep a backup"), "a yes with a condition changes the course");
202 assert!(!stamp(&irreversible, "no"));
203 let push = entry("q2", Kind::ExternalMutation, "s");
205 assert!(stamp(&push, "run it as planned"));
206 assert!(!stamp(&push, &push.default), "holding it is the no");
207 }
208
209 #[test]
210 fn the_yield_folds_counts_with_the_design_weights() {
211 let counts: BTreeMap<String, u64> =
212 [(stats::QUEEN_NO, 3), (stats::QUEEN_STAMP, 1), (stats::QUEEN_MISSED, 1)].into_iter().map(|(k, v)| (k.to_string(), v)).collect();
213 let y = of(&counts);
214 assert_eq!((y.answered, y.no, y.stamps, y.missed), (4, 3, 1, 1));
215 assert_eq!(y.share, Some(0.75));
216 assert_eq!(y.reward, 3.0 - 1.0 - 3.0, "a missed escalation weighs a veto");
217 assert_eq!(of(&BTreeMap::new()), Yield { alpha: 1.0, beta: 3.0, ..Yield::default() }, "no answer, no share");
218 }
219
220 #[test]
221 fn only_the_queens_own_escalations_earn_and_each_answer_logs_once() {
222 let store = tmp("answered");
223 let mut e = entry("q1", Kind::PublicApi, "s1");
224 assert_eq!(answered(&store, &e, "keep the old contract working", "ann@x", 10), Some(stats::QUEEN_NO));
225 assert_eq!(answered(&store, &e, "proceed as planned", "ann@x", 11), Some(stats::QUEEN_STAMP));
226 for k in [Kind::Constraint, Kind::Reach, Kind::OpenDecision] {
227 e.kind = k;
228 assert_eq!(answered(&store, &e, "anything", "ann@x", 12), None, "{k:?} is a gate, not the queen's choice");
229 }
230 let y = team(&store);
231 assert_eq!((y.no, y.stamps), (1, 1));
232 let _ = std::fs::remove_dir_all(&store);
233 }
234
235 #[test]
236 fn a_no_without_an_escalation_is_missed_once_and_never_after_one() {
237 let store = tmp("missed");
238 assert!(missed(&store, "s1", "veto", "no-s1-5", "app", 5));
239 assert!(!missed(&store, "s1", "veto", "no-s1-5", "app", 6), "once per id");
240 assert!(!missed(&store, "", "regret", "r1", "app", 6), "an unknown session is nobody's miss");
241 let line = serde_json::to_string(&entry("q9", Kind::CrossRepo, "s2")).unwrap();
243 std::fs::create_dir_all(queen::dir(&store)).unwrap();
244 std::fs::write(queen::dir(&store).join("queue.jsonl"), format!("{line}\n")).unwrap();
245 assert!(escalated(&store, "s2"));
246 assert!(!missed(&store, "s2", "regret", "r2", "app", 7));
247 let line = serde_json::to_string(&entry("q10", Kind::Constraint, "s3")).unwrap();
249 std::fs::write(queen::dir(&store).join("queue.jsonl"), format!("{line}\n")).unwrap();
250 assert!(missed(&store, "s3", "regret", "r3", "app", 8));
251 let y = team(&store);
252 assert_eq!((y.missed, y.reward), (2, -6.0));
253 let _ = std::fs::remove_dir_all(&store);
254 }
255}