Skip to main content

borg/
escalation.rs

1//! The queen's attention reward: did
2//! an escalation spend the engineer's minutes well?
3//!
4//! ```text
5//! R(queen) = no_after_escalation − α·rubber_stamp − β·missed_escalation
6//! ```
7//!
8//! Three stat lines (stats.rs), each logged once, where its event happens:
9//! - `queen_no` (+1): an escalation the engineer answered by changing course: holding the move,
10//!   making it reversible, keeping the old contract, leaving the other side to its owners, or own words
11//!   (queen.rs `answer`).
12//! - `queen_stamp` (−α): an escalation answered "yes, fine": the option that lets the plan go ahead
13//!   (`Kind::proceeds`), or a bare yes.
14//! - `queen_missed` (−β): a "no" that came after the work merged, from a session with no escalation:
15//!   a veto (veto.rs `record`, any of its three ways in) of a session whose work landed (a commit of its
16//!   own still on HEAD, notes.rs `landed_by`), or a strong regress link (notes/regress_learn.rs: a later
17//!   fix of a committed decision) of a deciding session.
18//!
19//! Escalations are the questions the queen chooses to raise: the four checkpoint kinds
20//! (`Kind::escalates`). The other queue kinds are proposals or gates an engineer must answer whatever
21//! the queen thinks (constraints, reach, open decisions), so they earn nothing.
22//! "No escalation" is judged against this node's queue: the queue is local, and so are the sessions it
23//! names.
24//!
25//! The lines roll up into `stats.jsonl` like every count and sync with it, so `of` folds the team's
26//! yield from the buckets; borg-web's queen view shows it. α = 1 (a wasted answer costs what a useful
27//! one earns) and β = memory.rs `VETOED_W` (a missed escalation weighs what the veto it missed weighs
28//! in a lesson's belief); both design-chosen, neither tuned. Nothing reads the reward but monitoring:
29//! the design keeps the queen's predictor a router, and optimising a proxy of the engineer is the
30//! Goodhart trap it warns about. Preparation: no value metric yet; it is what the value metric of a
31//! learned escalation policy will be read from.
32
33use std::collections::BTreeMap;
34use std::path::Path;
35
36use serde::Serialize;
37
38use crate::queen::{self, Entry};
39use crate::{notes, stats};
40
41/// α: what a rubber stamp costs.
42pub const STAMP_W: f64 = 1.0;
43/// β: what a missed escalation costs.
44pub const MISSED_W: f64 = crate::memory::VETOED_W as f64;
45
46/// Words an answer that only says "yes, fine" is made of.
47const 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
53/// Whether `answer` to escalation `e` is "yes, fine": it is (or starts with) the option that lets the
54/// plan go ahead, or every word of it is a plain yes.
55pub 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
61/// Whether `answer` says only yes: every word of it is a plain yes.
62pub fn yes(answer: &str) -> bool {
63    let a = norm(answer);
64    !a.is_empty() && a.split(' ').all(|w| YES.contains(&w))
65}
66
67/// Logs the reward of an answer to `e` (queen.rs `answer`, after it was recorded): `queen_no` or
68/// `queen_stamp` for an escalation, nothing for any other kind. Returns the kind logged.
69pub 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
84/// Whether the queen escalated anything from `session` (answered, open or dismissed alike: it was
85/// raised).
86pub 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
90/// Whether `session`'s work merged: it landed a commit of its own that is still on HEAD (notes.rs
91/// `landed_by`, from the hook's state in `state`).
92pub fn merged(state: &Path, session: &str) -> bool {
93    !notes::landed_by(state, session).is_empty()
94}
95
96/// Logs a missed escalation once per `id` (a veto episode, a regress link): `cause` `veto` or
97/// `regret`, of `session` in `repo`. Nothing when the queen escalated from that session, or for an
98/// unknown session. Returns whether it logged.
99pub 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/// The queen's attention reward over some counts (a bucket's, or the team's summed).
116#[derive(Debug, Clone, Default, PartialEq, Serialize)]
117pub struct Yield {
118    /// Escalations answered: `no` + `stamps`.
119    pub answered: u64,
120    pub no: u64,
121    pub stamps: u64,
122    pub missed: u64,
123    /// The share of answered escalations that ended in a "no"; None before any answer.
124    pub share: Option<f64>,
125    /// R(queen) = no − α·stamps − β·missed.
126    pub reward: f64,
127    pub alpha: f64,
128    pub beta: f64,
129}
130
131/// The yield of `counts` (stats.rs `Bucket::counts`).
132pub 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
148/// The team's yield: every bucket of the store (this node's events and the synced rollups), summed.
149pub 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        // An external mutation's default holds it: the engineer letting it run is the yes.
204        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        // The queen escalated from s2: a no there is the escalation working, not a miss.
242        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        // A gate question from s3 is no escalation.
248        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}