Skip to main content

lean_ctx/core/agents/
friction.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Friction signals of agent coordination, counted locally for the retro
3//! loop: `<data>/agents/friction.jsonl`, one `{"at", "signal", "agent"?,
4//! "root"?}` line per event (fixed keys and ids, never message text),
5//! summed by `lean-ctx agent friction [--since <dur>]` and per hour, worker
6//! and vault by the Cloud connector's friction counter for the vault bus
7//! (V16.1).
8
9use std::collections::BTreeMap;
10use std::io::Write as _;
11use std::path::Path;
12
13use lean_ctx_time::{OffsetDateTime, UtcDateTime};
14
15/// A task claim Cloud refused because the agent was not on the bus.
16pub const CLAIM_REFUSED_PRESENCE: &str = "claim_refused_presence";
17/// A task claim Cloud refused because the agent was on the bus in another role.
18pub const CLAIM_REFUSED_ROLE: &str = "claim_refused_role";
19/// A task claim Cloud refused for a role or consent reason it did not name.
20pub const CLAIM_REFUSED_PERMIT: &str = "claim_refused_permit";
21/// A claim this machine held ended before its agent finished (stale or closed).
22pub const CLAIM_EXPIRED: &str = "claim_expired";
23/// An agent's registration had expired and a heartbeat renewed it.
24pub const REGISTRATION_RENEWED: &str = "registration_renewed";
25/// `ctx_agent wait` / `lean-ctx agent wait` ended without a message.
26pub const WAIT_TIMEOUT: &str = "wait_timeout";
27/// The bound checkout had unmerged paths while an agent worked in it.
28pub const MERGE_CONFLICT: &str = "merge_conflict";
29
30const FILE: &str = "friction.jsonl";
31/// Past this size the log keeps its newest half, so it stays small.
32const MAX_BYTES: u64 = 256 * 1024;
33
34#[derive(serde::Serialize, serde::Deserialize)]
35struct Line {
36    at: String,
37    signal: String,
38    /// The agent the signal belongs to, when the call site knows it.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    agent: Option<String>,
41    /// The checkout it happened in, when known (else the agent's).
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    root: Option<String>,
44}
45
46/// One recorded signal.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Event {
49    pub at: UtcDateTime,
50    pub signal: String,
51    pub agent: Option<String>,
52    pub root: Option<String>,
53}
54
55/// Count one `signal` now for `agent` in checkout `root` (either unknown).
56/// Best effort: a failure is logged, never raised.
57pub fn record_for(signal: &str, agent: Option<&str>, root: Option<&str>) {
58    let Ok(dir) = super::persistence::agents_dir() else {
59        return;
60    };
61    if let Err(error) = record_in(&dir, signal, agent, root, UtcDateTime::now()) {
62        tracing::debug!("lean-ctx: friction log: {error}");
63    }
64}
65
66fn record_in(
67    dir: &Path,
68    signal: &str,
69    agent: Option<&str>,
70    root: Option<&str>,
71    at: UtcDateTime,
72) -> std::io::Result<()> {
73    std::fs::create_dir_all(dir)?;
74    let path = dir.join(FILE);
75    if std::fs::metadata(&path).is_ok_and(|m| m.len() > MAX_BYTES) {
76        let text = std::fs::read_to_string(&path).unwrap_or_default();
77        let lines: Vec<&str> = text.lines().collect();
78        let kept = lines[lines.len() / 2..].join("\n");
79        crate::core::atomic_fs::try_atomic_write(&path, format!("{kept}\n").as_bytes(), None)
80            .map_err(std::io::Error::other)?;
81    }
82    let line = serde_json::to_string(&Line {
83        at: at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
84        signal: signal.to_string(),
85        agent: agent.map(str::to_string),
86        root: root.map(str::to_string),
87    })
88    .map_err(std::io::Error::other)?;
89    let mut options = std::fs::OpenOptions::new();
90    options.create(true).append(true);
91    #[cfg(unix)]
92    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
93    let mut file = options.open(&path)?;
94    writeln!(file, "{line}")
95}
96
97/// The signals recorded in `[from, to)`, oldest first.
98pub fn events(from: UtcDateTime, to: UtcDateTime) -> Vec<Event> {
99    super::persistence::agents_dir()
100        .map(|dir| events_in(&dir, from, to))
101        .unwrap_or_default()
102}
103
104pub(crate) fn events_in(dir: &Path, from: UtcDateTime, to: UtcDateTime) -> Vec<Event> {
105    let Ok(text) = std::fs::read_to_string(dir.join(FILE)) else {
106        return Vec::new();
107    };
108    text.lines()
109        .filter_map(|line| serde_json::from_str::<Line>(line).ok())
110        .filter_map(|line| {
111            let at = OffsetDateTime::parse_from_rfc3339(&line.at).ok()?.to_utc();
112            (from <= at && at < to).then_some(Event {
113                at,
114                signal: line.signal,
115                agent: line.agent,
116                root: line.root,
117            })
118        })
119        .collect()
120}
121
122/// Signal → count of the events at or after `since` (all when `None`).
123pub fn summary(since: Option<UtcDateTime>) -> BTreeMap<String, u64> {
124    super::persistence::agents_dir()
125        .map(|dir| summary_in(&dir, since))
126        .unwrap_or_default()
127}
128
129fn summary_in(dir: &Path, since: Option<UtcDateTime>) -> BTreeMap<String, u64> {
130    let mut counts = BTreeMap::new();
131    let Ok(text) = std::fs::read_to_string(dir.join(FILE)) else {
132        return counts;
133    };
134    for line in text.lines() {
135        let Ok(line) = serde_json::from_str::<Line>(line) else {
136            continue;
137        };
138        let Ok(at) = OffsetDateTime::parse_from_rfc3339(&line.at) else {
139            continue;
140        };
141        if since.is_none_or(|since| at >= since) {
142            *counts.entry(line.signal).or_insert(0) += 1;
143        }
144    }
145    counts
146}
147
148/// The summary as text: one `signal count` line each, sorted by signal.
149pub fn render(counts: &BTreeMap<String, u64>) -> String {
150    if counts.is_empty() {
151        return "No friction recorded.".to_string();
152    }
153    let width = counts.keys().map(String::len).max().unwrap_or(0);
154    counts
155        .iter()
156        .map(|(signal, n)| format!("{signal:<width$}  {n}"))
157        .collect::<Vec<_>>()
158        .join("\n")
159}
160
161/// `30m`, `12h`, `7d` or plain seconds.
162pub fn parse_duration(text: &str) -> Option<lean_ctx_time::Duration> {
163    let text = text.trim();
164    let (number, unit) = text
165        .find(|c: char| !c.is_ascii_digit())
166        .map_or((text, ""), |at| text.split_at(at));
167    let n: i64 = number.parse().ok()?;
168    match unit {
169        "" | "s" => Some(lean_ctx_time::Duration::seconds(n)),
170        "m" => Some(lean_ctx_time::Duration::minutes(n)),
171        "h" => Some(lean_ctx_time::Duration::hours(n)),
172        "d" => Some(lean_ctx_time::Duration::days(n)),
173        _ => None,
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn signals_are_counted_by_key_and_window() {
183        let dir = tempfile::tempdir().unwrap();
184        let at = |s: &str| OffsetDateTime::parse_from_rfc3339(s).unwrap().to_utc();
185        record_in(
186            dir.path(),
187            WAIT_TIMEOUT,
188            None,
189            None,
190            at("2026-10-24T08:00:00Z"),
191        )
192        .unwrap();
193        record_in(
194            dir.path(),
195            WAIT_TIMEOUT,
196            None,
197            None,
198            at("2026-10-24T10:00:00Z"),
199        )
200        .unwrap();
201        record_in(
202            dir.path(),
203            CLAIM_REFUSED_PRESENCE,
204            None,
205            None,
206            at("2026-10-24T10:30:00Z"),
207        )
208        .unwrap();
209        std::fs::OpenOptions::new()
210            .append(true)
211            .open(dir.path().join(FILE))
212            .unwrap()
213            .write_all(b"not json\n")
214            .unwrap();
215        let all = summary_in(dir.path(), None);
216        assert_eq!(all[WAIT_TIMEOUT], 2);
217        assert_eq!(all[CLAIM_REFUSED_PRESENCE], 1);
218        let recent = summary_in(dir.path(), Some(at("2026-10-24T09:00:00Z")));
219        assert_eq!(recent[WAIT_TIMEOUT], 1);
220        assert_eq!(
221            render(&recent),
222            "claim_refused_presence  1\nwait_timeout            1"
223        );
224        assert_eq!(render(&BTreeMap::new()), "No friction recorded.");
225        let text = std::fs::read_to_string(dir.path().join(FILE)).unwrap();
226        assert!(
227            text.lines()
228                .next()
229                .unwrap()
230                .contains(r#""signal":"wait_timeout""#)
231        );
232        #[cfg(unix)]
233        {
234            use std::os::unix::fs::PermissionsExt as _;
235            let mode = std::fs::metadata(dir.path().join(FILE))
236                .unwrap()
237                .permissions()
238                .mode();
239            assert_eq!(mode & 0o777, 0o600);
240        }
241    }
242
243    #[test]
244    fn the_log_stays_bounded() {
245        let dir = tempfile::tempdir().unwrap();
246        let now = UtcDateTime::now();
247        for _ in 0..6000 {
248            record_in(dir.path(), CLAIM_EXPIRED, None, None, now).unwrap();
249        }
250        assert!(std::fs::metadata(dir.path().join(FILE)).unwrap().len() <= MAX_BYTES + 128);
251        assert!(summary_in(dir.path(), None)[CLAIM_EXPIRED] > 1000);
252    }
253
254    /// V16.1: a signal carries its agent and checkout when the call site
255    /// knows them; a window query returns `[from, to)` only.
256    #[test]
257    fn events_carry_agent_and_checkout_and_respect_the_window() {
258        let dir = tempfile::tempdir().unwrap();
259        let at = |s: &str| OffsetDateTime::parse_from_rfc3339(s).unwrap().to_utc();
260        record_in(
261            dir.path(),
262            WAIT_TIMEOUT,
263            Some("mcp-1"),
264            Some("/w/a"),
265            at("2026-10-24T08:10:00Z"),
266        )
267        .unwrap();
268        record_in(
269            dir.path(),
270            CLAIM_EXPIRED,
271            None,
272            None,
273            at("2026-10-24T09:00:00Z"),
274        )
275        .unwrap();
276        let hour = events_in(
277            dir.path(),
278            at("2026-10-24T08:00:00Z"),
279            at("2026-10-24T09:00:00Z"),
280        );
281        assert_eq!(
282            hour,
283            [Event {
284                at: at("2026-10-24T08:10:00Z"),
285                signal: WAIT_TIMEOUT.into(),
286                agent: Some("mcp-1".into()),
287                root: Some("/w/a".into()),
288            }]
289        );
290        let text = std::fs::read_to_string(dir.path().join(FILE)).unwrap();
291        assert!(
292            text.lines()
293                .nth(1)
294                .unwrap()
295                .ends_with(r#""signal":"claim_expired"}"#),
296            "unknown agent and checkout are left out: {text}"
297        );
298    }
299
300    #[test]
301    fn durations_parse() {
302        assert_eq!(
303            parse_duration("90"),
304            Some(lean_ctx_time::Duration::seconds(90))
305        );
306        assert_eq!(
307            parse_duration("30m"),
308            Some(lean_ctx_time::Duration::minutes(30))
309        );
310        assert_eq!(
311            parse_duration("12h"),
312            Some(lean_ctx_time::Duration::hours(12))
313        );
314        assert_eq!(parse_duration("7d"), Some(lean_ctx_time::Duration::days(7)));
315        assert_eq!(parse_duration("7w"), None);
316        assert_eq!(parse_duration("h"), None);
317    }
318}