Skip to main content

lean_ctx_cloud/
friction.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Collaboration friction per hour (V16.1, RESOLUTIONS R128): the local
3//! friction log (`core::agents::friction`) summed for one closed hour per
4//! vault into the C0 2.0 counts of a collaboration `finding`
5//! (`about: collaboration`, `counts`, `window`; CONTRACT §3.19.2). Counts
6//! and ids only, never text.
7
8use std::collections::BTreeMap;
9use std::io::Write as _;
10
11use lean_ctx_time::{Duration, UtcDateTime};
12
13use lean_ctx::core::agents::AgentEntry;
14use lean_ctx::core::agents::friction::{self, Event};
15
16use super::CloudStore;
17use super::bus::v2::{self, About, CollabCounts, MessageType, Publish, Window};
18use super::vault::VaultMap;
19
20/// `<data>/cloud/friction.jsonl`: one `{hour, worker_id, place, counts}`
21/// line per finding sent (R128; counts and ids only).
22const HOURS_FILE: &str = "friction.jsonl";
23/// The last hour (`from_ms`) whose findings were queued.
24const STATE_FILE: &str = "friction-state.json";
25/// Closed hours caught up at most after a pause (the relay was off).
26const CATCH_UP_HOURS: i64 = 24;
27
28#[derive(Default, serde::Serialize, serde::Deserialize)]
29struct EmitState {
30    last_hour_ms: Option<i64>,
31}
32
33/// Queue the collaboration findings of every hour closed since the last
34/// run (at most `CATCH_UP_HOURS`) for the v2 vault bus; returns how many
35/// were queued. Nothing on a 1.x Cloud. The first run starts with the hour
36/// that just closed. Called by the bus relay about once a minute.
37pub fn emit_due(store: &CloudStore, now: UtcDateTime) -> usize {
38    if !super::bus::relay_v2::speaks_v2(store) {
39        return 0;
40    }
41    let Ok(Some(instance)) = store.instance() else {
42        return 0;
43    };
44    let Ok(this_hour) = now.duration_trunc(Duration::hours(1)) else {
45        return 0;
46    };
47    let dir = store.data_dir();
48    let state_path = dir.join(STATE_FILE);
49    let mut state: EmitState = std::fs::read(&state_path)
50        .ok()
51        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
52        .unwrap_or_default();
53    let first = state
54        .last_hour_ms
55        .and_then(UtcDateTime::from_timestamp_millis)
56        .map_or(this_hour - Duration::hours(1), |last| {
57            (last + Duration::hours(1)).max(this_hour - Duration::hours(CATCH_UP_HOURS))
58        });
59    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
60    let agents = registry.list_all();
61    let vaults = VaultMap::load(dir);
62    let active: std::collections::BTreeSet<&str> = registry
63        .list_active(None)
64        .into_iter()
65        .map(|a| a.agent_id.as_str())
66        .collect();
67    // A session still running attaches as usual; one that has finished
68    // only names the worker it had, so an hour's findings never bring a
69    // gone role back into a full book (and push out an idle one).
70    let worker_of = |agent: &AgentEntry| {
71        // rc4-86: an MCP server's own presence is no worker.
72        if agent.is_engine_placeholder() {
73            return None;
74        }
75        let (host, role) = super::workers::attach::agent_worker_key(agent);
76        if active.contains(agent.agent_id.as_str()) {
77            super::workers::attach::attach(store, &instance.instance_id, &host, &role)
78                .ok()
79                .map(|attached| attached.worker.worker_id)
80        } else {
81            super::workers::attach::known(store, &instance.instance_id, &host, &role)
82                .map(|worker| worker.worker_id)
83        }
84    };
85    let now_ms = u64::try_from(now.timestamp_millis()).unwrap_or(0);
86    let mut queued = 0;
87    let mut hour = first;
88    while hour < this_hour {
89        let end = hour + Duration::hours(1);
90        let events = friction::events(hour, end);
91        for finding in hour_findings(dir, &events, agents, &vaults, &worker_of, hour, end) {
92            if let Err(error) = super::bus::relay_v2::queue_publish(store, finding.publish(now_ms))
93            {
94                store.record_error(&format!("collaboration finding: {error}"));
95                continue;
96            }
97            append_hour(dir, &finding);
98            queued += 1;
99        }
100        state.last_hour_ms = Some(hour.timestamp_millis());
101        hour = end;
102    }
103    if let Ok(bytes) = serde_json::to_vec(&state) {
104        let _ = super::state::write_private(dir, STATE_FILE, &bytes);
105    }
106    queued
107}
108
109fn append_hour(dir: &std::path::Path, finding: &HourFinding) {
110    let line = serde_json::json!({
111        "hour": finding.from_ms,
112        "worker_id": finding.worker_id,
113        "place": finding.to,
114        "counts": finding.counts,
115    });
116    let mut options = std::fs::OpenOptions::new();
117    options.create(true).append(true);
118    #[cfg(unix)]
119    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
120    if let Ok(mut file) = options.open(dir.join(HOURS_FILE)) {
121        let _ = writeln!(file, "{line}");
122    }
123}
124
125/// Count a merge conflict when a bound checkout an active agent
126/// works in has unmerged paths that the last sample did not see; `seen`
127/// carries the conflicted checkouts from one sample to the next, so one
128/// conflict counts once however long it lasts.
129pub fn sample_merge_conflicts(store: &CloudStore, seen: &mut std::collections::BTreeSet<String>) {
130    let vaults = crate::vault::connected_map(store);
131    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
132    let mut roots: BTreeMap<&str, &str> = BTreeMap::new();
133    for agent in registry.list_active(None) {
134        // An unlinked checkout sends nothing, also not through its main
135        // checkout's record (bd 40060).
136        if crate::unlinked::shared_record(store.data_dir(), &vaults, &agent.project_root).is_some()
137        {
138            roots
139                .entry(agent.project_root.as_str())
140                .or_insert(agent.agent_id.as_str());
141        }
142    }
143    seen.retain(|root| roots.contains_key(root.as_str()));
144    for (root, agent) in roots {
145        if has_unmerged_paths(root) {
146            if seen.insert(root.to_string()) {
147                friction::record_for(friction::MERGE_CONFLICT, Some(agent), Some(root));
148            }
149        } else {
150            seen.remove(root);
151        }
152    }
153}
154
155/// Whether `git ls-files -u` lists any path in `root` (an error is "no").
156fn has_unmerged_paths(root: &str) -> bool {
157    std::process::Command::new("git")
158        .args(["-C", root, "ls-files", "-u", "-z"])
159        .stdin(std::process::Stdio::null())
160        .stderr(std::process::Stdio::null())
161        .output()
162        .is_ok_and(|out| out.status.success() && !out.stdout.is_empty())
163}
164
165/// The C0 `counts` keys (enums/friction-signals.json), in that order.
166pub const COUNT_KEYS: [&str; 8] = [
167    "claim_refused",
168    "claim_expired",
169    "registration_renewed",
170    "wait_timeout",
171    "merge_conflict",
172    "gate_reruns",
173    "agent_seconds",
174    "idle_seconds",
175];
176
177/// The keys that are friction (all but the two time measures).
178const FRICTION_KEYS: [&str; 6] = [
179    "claim_refused",
180    "claim_expired",
181    "registration_renewed",
182    "wait_timeout",
183    "merge_conflict",
184    "gate_reruns",
185];
186
187/// The C0 key a local signal counts under; `None` for signals that are
188/// not part of the contract.
189pub fn count_key(signal: &str) -> Option<&'static str> {
190    Some(match signal {
191        friction::CLAIM_REFUSED_PRESENCE
192        | friction::CLAIM_REFUSED_ROLE
193        | friction::CLAIM_REFUSED_PERMIT => "claim_refused",
194        friction::CLAIM_EXPIRED => "claim_expired",
195        friction::REGISTRATION_RENEWED => "registration_renewed",
196        friction::WAIT_TIMEOUT => "wait_timeout",
197        friction::MERGE_CONFLICT => "merge_conflict",
198        _ => return None,
199    })
200}
201
202/// One vault's collaboration finding for one closed hour.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct HourFinding {
205    /// `#<ws>/<vault>`.
206    pub to: String,
207    /// The worker that sends it: the one with the most agent time in the
208    /// vault that hour (ties: the smaller id).
209    pub worker_id: String,
210    pub from_ms: i64,
211    pub to_ms: i64,
212    /// C0 keys with a non-zero value only.
213    pub counts: BTreeMap<&'static str, u32>,
214}
215
216impl HourFinding {
217    /// The C0 statement template: "Collaboration friction from {from} to
218    /// {to}: {n} signals in {h} agent-hours." (times in UTC, `HH:MM`).
219    pub fn statement(&self) -> String {
220        let hhmm = |ms: i64| {
221            UtcDateTime::from_timestamp_millis(ms)
222                .map_or_else(String::new, |t| t.format("%H:%M").to_string())
223        };
224        let signals: u32 = FRICTION_KEYS
225            .iter()
226            .filter_map(|key| self.counts.get(key))
227            .sum();
228        let seconds = self.counts.get("agent_seconds").copied().unwrap_or(0);
229        format!(
230            "Collaboration friction from {} to {}: {signals} signals in {:.1} agent-hours.",
231            hhmm(self.from_ms),
232            hhmm(self.to_ms),
233            f64::from(seconds) / 3600.0
234        )
235    }
236
237    /// The finding as a v2 vault-bus publish (CONTRACT §3.19.2): type
238    /// `finding`, `about: collaboration`, no refs, the counts and window in
239    /// plaintext, the statement as an observed finding.
240    pub fn publish(&self, now_ms: u64) -> Publish {
241        let get = |key: &str| self.counts.get(key).copied();
242        Publish {
243            schema: v2::BUS_SCHEMA.to_string(),
244            client_msg_id: v2::new_ulid(now_ms),
245            to: self.to.clone(),
246            kind: MessageType::Finding,
247            worker_id: self.worker_id.clone(),
248            thread_id: None,
249            reply_to: None,
250            refs: Vec::new(),
251            body: serde_json::json!({"statement": self.statement(), "evidence": "observed"}),
252            ck_wrapped: None,
253            epoch: None,
254            about: Some(About::Collaboration),
255            counts: Some(CollabCounts {
256                registration_renewed: get("registration_renewed"),
257                wait_timeout: get("wait_timeout"),
258                merge_conflict: get("merge_conflict"),
259                claim_refused: get("claim_refused"),
260                claim_expired: get("claim_expired"),
261                gate_reruns: get("gate_reruns"),
262                agent_seconds: get("agent_seconds"),
263                idle_seconds: get("idle_seconds"),
264            }),
265            window: Some(Window {
266                from_ms: u64::try_from(self.from_ms).unwrap_or(0),
267                to_ms: u64::try_from(self.to_ms).unwrap_or(0),
268            }),
269        }
270    }
271}
272
273/// The findings of the hour `[from, to)`: the signals of `events` and the
274/// agent time of `agents`, attributed to the vault of their checkout
275/// (`vaults`) and to the worker `worker_of` names for
276/// their agent. A signal without a known agent counts for the vault of its
277/// checkout under the vault's sending worker. Vaults without friction and
278/// without agent time get no finding.
279pub(crate) fn hour_findings(
280    data_dir: &std::path::Path,
281    events: &[Event],
282    agents: &[AgentEntry],
283    vaults: &VaultMap,
284    worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
285    from: UtcDateTime,
286    to: UtcDateTime,
287) -> Vec<HourFinding> {
288    // A checkout the person unlinked has no place, also not through its
289    // main checkout's record (bd 40060).
290    let place_of = |root: &str| {
291        crate::unlinked::shared_record(data_dir, vaults, root).map(super::bus::relay_v2::address_of)
292    };
293    // vault → worker → agent seconds, and vault → C0 key → count.
294    let mut time: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
295    let mut counts: BTreeMap<String, BTreeMap<&'static str, u32>> = BTreeMap::new();
296    for agent in agents {
297        // The place first: an agent in a project no vault links gets no
298        // worker attached just to be skipped.
299        let Some(place) = place_of(&agent.project_root) else {
300            continue;
301        };
302        let Some(worker) = worker_of(agent) else {
303            continue;
304        };
305        let start = agent.started_at.max(from);
306        let end = agent.last_active.min(to);
307        let seconds = (end - start).num_seconds().max(0);
308        *time.entry(place).or_default().entry(worker).or_default() += seconds;
309    }
310    for event in events {
311        let Some(key) = count_key(&event.signal) else {
312            continue;
313        };
314        let agent = event
315            .agent
316            .as_deref()
317            .and_then(|id| agents.iter().find(|a| a.agent_id == id));
318        let root = event
319            .root
320            .as_deref()
321            .or_else(|| agent.map(|a| a.project_root.as_str()));
322        let Some(place) = root.and_then(place_of) else {
323            continue;
324        };
325        if let Some(worker) = agent.and_then(worker_of) {
326            time.entry(place.clone())
327                .or_default()
328                .entry(worker)
329                .or_default();
330        }
331        let count = counts.entry(place).or_default().entry(key).or_default();
332        *count = count.saturating_add(1);
333    }
334    time.into_iter()
335        .filter_map(|(place, workers)| {
336            let worker_id = workers
337                .iter()
338                .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
339                .map(|(id, _)| id.clone())?;
340            let seconds: i64 = workers.values().sum();
341            let mut counts = counts.remove(&place).unwrap_or_default();
342            if seconds > 0 {
343                counts.insert("agent_seconds", u32::try_from(seconds).unwrap_or(u32::MAX));
344            }
345            (!counts.is_empty()).then(|| HourFinding {
346                to: place,
347                worker_id,
348                from_ms: from.timestamp_millis(),
349                to_ms: to.timestamp_millis(),
350                counts,
351            })
352        })
353        .collect()
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use crate::vault::VaultRecord;
360    use lean_ctx::core::agents::AgentStatus;
361
362    fn at(s: &str) -> UtcDateTime {
363        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(s)
364            .unwrap()
365            .to_utc()
366    }
367
368    fn agent(id: &str, root: &str, from: &str, to: &str) -> AgentEntry {
369        AgentEntry {
370            agent_id: id.into(),
371            agent_type: "claude".into(),
372            role: Some("engine".into()),
373            project_root: root.into(),
374            started_at: at(from),
375            last_active: at(to),
376            pid: 1,
377            process_identity: None,
378            durable_identity_id: None,
379            status: AgentStatus::Active,
380            status_message: None,
381            agent_status_message: None,
382            transport: None,
383            role_source: None,
384            parent: None,
385            parent_client: None,
386            app_session_id: None,
387            display_name: None,
388        }
389    }
390
391    fn event(signal: &str, agent: Option<&str>, root: Option<&str>) -> Event {
392        Event {
393            at: at("2026-10-24T08:30:00Z"),
394            signal: signal.into(),
395            agent: agent.map(Into::into),
396            root: root.map(Into::into),
397        }
398    }
399
400    fn vaults() -> VaultMap {
401        let mut map = VaultMap::default();
402        map.vaults.insert(
403            "v1".into(),
404            VaultRecord {
405                vault_id: "v1".into(),
406                ns: "acme".into(),
407                name: "payments".into(),
408                sealed: false,
409                roots: vec!["/w/pay".into()],
410            },
411        );
412        map
413    }
414
415    /// bd 40060 MUST: a worktree the person unlinked sends no findings,
416    /// also not through its main checkout's record.
417    #[test]
418    fn unlink_of_a_worktree_sends_no_friction_findings() {
419        let base = tempfile::tempdir().unwrap();
420        let base = base.path().canonicalize().unwrap();
421        let (main, wt) = crate::unlinked::fake_worktree(&base);
422        let data = base.join("data");
423        let mut map = VaultMap::default();
424        map.vaults.insert(
425            "v1".into(),
426            VaultRecord {
427                vault_id: "v1".into(),
428                ns: "acme".into(),
429                name: "payments".into(),
430                sealed: false,
431                roots: vec![main.to_string_lossy().into_owned()],
432            },
433        );
434        let wt_text = wt.to_string_lossy().into_owned();
435        let agents = [agent(
436            "mcp-a",
437            &wt_text,
438            "2026-10-24T07:00:00Z",
439            "2026-10-24T10:00:00Z",
440        )];
441        let events = [event(friction::WAIT_TIMEOUT, None, Some(&wt_text))];
442        let worker_of = |a: &AgentEntry| Some(format!("wkr_{}", a.agent_id));
443        let run = || {
444            hour_findings(
445                &data,
446                &events,
447                &agents,
448                &map,
449                &worker_of,
450                at("2026-10-24T08:00:00Z"),
451                at("2026-10-24T09:00:00Z"),
452            )
453        };
454        assert!(!run().is_empty(), "shared through the main checkout");
455        crate::unlinked::add(&data, &wt).unwrap();
456        assert!(run().is_empty(), "{:?}", run());
457    }
458
459    /// Every local signal counts under exactly one C0 key, and only the
460    /// eight C0 keys exist.
461    #[test]
462    fn local_signals_map_onto_the_contract_keys() {
463        for (signal, key) in [
464            (friction::CLAIM_REFUSED_PRESENCE, "claim_refused"),
465            (friction::CLAIM_REFUSED_ROLE, "claim_refused"),
466            (friction::CLAIM_REFUSED_PERMIT, "claim_refused"),
467            (friction::CLAIM_EXPIRED, "claim_expired"),
468            (friction::REGISTRATION_RENEWED, "registration_renewed"),
469            (friction::WAIT_TIMEOUT, "wait_timeout"),
470            (friction::MERGE_CONFLICT, "merge_conflict"),
471        ] {
472            assert_eq!(count_key(signal), Some(key), "{signal}");
473            assert!(COUNT_KEYS.contains(&key));
474        }
475        assert_eq!(count_key("something_else"), None);
476    }
477
478    /// One finding per vault and hour: signals and agent time of the
479    /// vault's checkouts, sent by the worker with the most agent time; a
480    /// checkout outside every vault and other hours get nothing.
481    #[test]
482    fn an_hour_sums_into_one_finding_per_vault() {
483        let agents = [
484            agent(
485                "mcp-a",
486                "/w/pay",
487                "2026-10-24T07:00:00Z",
488                "2026-10-24T08:30:00Z",
489            ),
490            agent(
491                "mcp-b",
492                "/w/pay",
493                "2026-10-24T08:30:00Z",
494                "2026-10-24T10:00:00Z",
495            ),
496            agent(
497                "mcp-c",
498                "/w/scratch",
499                "2026-10-24T08:00:00Z",
500                "2026-10-24T09:00:00Z",
501            ),
502        ];
503        let worker_of = |a: &AgentEntry| Some(format!("wkr_{}", a.agent_id));
504        let events = [
505            event(friction::CLAIM_REFUSED_ROLE, Some("mcp-a"), None),
506            event(
507                friction::CLAIM_REFUSED_PRESENCE,
508                Some("mcp-b"),
509                Some("/w/pay"),
510            ),
511            event(friction::WAIT_TIMEOUT, None, Some("/w/pay")),
512            event(friction::CLAIM_EXPIRED, Some("mcp-c"), None),
513            event("unknown_signal", Some("mcp-a"), None),
514        ];
515        let findings = hour_findings(
516            std::path::Path::new("/nonexistent/cloud-data"),
517            &events,
518            &agents,
519            &vaults(),
520            &worker_of,
521            at("2026-10-24T08:00:00Z"),
522            at("2026-10-24T09:00:00Z"),
523        );
524        assert_eq!(
525            findings.len(),
526            1,
527            "a checkout outside every vault gets none: {findings:?}"
528        );
529        let finding = &findings[0];
530        assert_eq!(finding.to, "#acme/payments");
531        assert_eq!(
532            finding.worker_id, "wkr_mcp-a",
533            "a tie of 30 min each goes to the smaller id"
534        );
535        assert_eq!(
536            (finding.from_ms, finding.to_ms),
537            (1_792_828_800_000, 1_792_832_400_000)
538        );
539        assert_eq!(
540            finding.counts,
541            BTreeMap::from([
542                ("agent_seconds", 3600),
543                ("claim_refused", 2),
544                ("wait_timeout", 1)
545            ])
546        );
547        assert_eq!(
548            finding.statement(),
549            "Collaboration friction from 08:00 to 09:00: 3 signals in 1.0 agent-hours."
550        );
551        assert!(finding.counts.keys().all(|key| COUNT_KEYS.contains(key)));
552    }
553
554    /// The publish carries exactly what the C0 2.0 collaboration finding
555    /// fixture stores (`about`, `counts`, `window`, `to`, `worker_id`,
556    /// type, no refs) and passes the engine's own v2 publish rules.
557    #[test]
558    fn the_publish_matches_the_contract_fixture() {
559        let path = format!(
560            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/bus/message.finding.collaboration.json",
561            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
562        );
563        let stored: serde_json::Value =
564            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
565        let counts: BTreeMap<&'static str, u32> = COUNT_KEYS
566            .iter()
567            .filter_map(|key| {
568                let n = stored["counts"][*key].as_u64()?;
569                Some((*key, u32::try_from(n).unwrap()))
570            })
571            .collect();
572        let finding = HourFinding {
573            to: stored["to"].as_str().unwrap().to_string(),
574            worker_id: stored["worker_id"].as_str().unwrap().to_string(),
575            from_ms: stored["window"]["from_ms"].as_i64().unwrap(),
576            to_ms: stored["window"]["to_ms"].as_i64().unwrap(),
577            counts,
578        };
579        let publish = finding.publish(1_792_803_600_000);
580        publish.validate().expect("a valid v2 publish");
581        let sent = serde_json::to_value(&publish).unwrap();
582        for member in [
583            "schema",
584            "type",
585            "about",
586            "counts",
587            "window",
588            "to",
589            "worker_id",
590        ] {
591            assert_eq!(sent[member], stored[member], "{member}");
592        }
593        assert!(sent.get("refs").is_none(), "no refs");
594        assert_eq!(sent["body"]["evidence"], "observed");
595        assert_eq!(
596            sent["body"]["statement"],
597            "Collaboration friction from 00:00 to 01:00: 8 signals in 1.5 agent-hours.",
598            "the window in UTC"
599        );
600    }
601
602    /// The relay queues each closed hour's findings once, keeps a line per
603    /// finding in `friction.jsonl`, and queues nothing for a 1.x Cloud.
604    #[test]
605    fn closed_hours_are_queued_once_and_only_for_a_v2_cloud() {
606        let _data = lean_ctx::core::data_dir::isolated_data_dir();
607        let dir = tempfile::tempdir().unwrap();
608        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
609        store
610            .write_config(
611                super::super::state::INSTANCE_FILE,
612                &super::super::state::InstanceRecord {
613                    instance_id: "inst_a".into(),
614                    org_id: "org_a".into(),
615                    org_name: "Acme".into(),
616                    label: "mac".into(),
617                    url: "https://cloud.example".into(),
618                    org_salt_id: "salt".into(),
619                    enrolled_at: "2026-10-24T00:00:00Z".into(),
620                    web_url: None,
621                    org_kind: None,
622                    company_name: None,
623                },
624            )
625            .unwrap();
626        let project = tempfile::tempdir().unwrap();
627        let root = project.path().to_string_lossy().into_owned();
628        let mut map = VaultMap::default();
629        map.vaults.insert(
630            "v1".into(),
631            VaultRecord {
632                vault_id: "v1".into(),
633                ns: "acme".into(),
634                name: "payments".into(),
635                sealed: false,
636                roots: vec![root.clone()],
637            },
638        );
639        map.save(store.data_dir()).unwrap();
640        let mut registry = lean_ctx::core::agents::AgentRegistry::new();
641        let agent = registry
642            .register("claude", Some("engine"), &root, None)
643            .unwrap();
644        registry.save().unwrap();
645        friction::record_for(friction::WAIT_TIMEOUT, Some(&agent), Some(&root));
646        let next_hour = UtcDateTime::now() + Duration::hours(1);
647
648        super::super::bus::relay_v2::record_protocol(&store, false).unwrap();
649        assert_eq!(
650            emit_due(&store, next_hour),
651            0,
652            "a 1.x Cloud server gets none"
653        );
654
655        super::super::bus::relay_v2::record_protocol(&store, true).unwrap();
656        assert_eq!(emit_due(&store, next_hour), 1);
657        assert_eq!(emit_due(&store, next_hour), 0, "an hour is queued once");
658        let lines = std::fs::read_to_string(store.data_dir().join(HOURS_FILE)).unwrap();
659        let line: serde_json::Value = serde_json::from_str(lines.trim()).unwrap();
660        assert_eq!(line["place"], "#acme/payments");
661        assert_eq!(line["counts"]["wait_timeout"], 1);
662        assert!(line["worker_id"].as_str().unwrap().starts_with("wkr_"));
663    }
664
665    /// R128 `merge_conflict`: unmerged paths in a bound checkout count once
666    /// per conflict, however many samples see it; a resolved checkout
667    /// counts again on its next conflict.
668    #[test]
669    fn a_merge_conflict_counts_once_per_conflict() {
670        let _data = lean_ctx::core::data_dir::isolated_data_dir();
671        let dir = tempfile::tempdir().unwrap();
672        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
673        let repo = tempfile::tempdir().unwrap();
674        let root = repo.path().to_string_lossy().into_owned();
675        let git = |args: &[&str]| {
676            let out = std::process::Command::new("git")
677                .args(["-c", "user.name=t", "-c", "user.email=t@t", "-C", &root])
678                .args(args)
679                .output()
680                .unwrap();
681            out.status.success()
682        };
683        assert!(git(&["init", "-q", "-b", "main"]));
684        std::fs::write(repo.path().join("f"), "base\n").unwrap();
685        assert!(git(&["add", "f"]) && git(&["commit", "-qm", "base"]));
686        assert!(git(&["checkout", "-qb", "other"]));
687        std::fs::write(repo.path().join("f"), "other\n").unwrap();
688        assert!(git(&["commit", "-qam", "other"]) && git(&["checkout", "-q", "main"]));
689        std::fs::write(repo.path().join("f"), "main\n").unwrap();
690        assert!(git(&["commit", "-qam", "main"]));
691        assert!(!git(&["merge", "-q", "other"]), "the merge conflicts");
692
693        let mut map = VaultMap::default();
694        map.vaults.insert(
695            "v1".into(),
696            VaultRecord {
697                vault_id: "v1".into(),
698                ns: "acme".into(),
699                name: "payments".into(),
700                sealed: false,
701                roots: vec![root.clone()],
702            },
703        );
704        map.save(store.data_dir()).unwrap();
705        let mut registry = lean_ctx::core::agents::AgentRegistry::new();
706        let agent = registry
707            .register("claude", Some("engine"), &root, None)
708            .unwrap();
709        registry.save().unwrap();
710
711        let conflicts = || {
712            friction::events(
713                UtcDateTime::now() - Duration::hours(1),
714                UtcDateTime::now() + Duration::hours(1),
715            )
716            .into_iter()
717            .filter(|e| e.signal == friction::MERGE_CONFLICT)
718            .collect::<Vec<_>>()
719        };
720        let mut seen = std::collections::BTreeSet::new();
721        sample_merge_conflicts(&store, &mut seen);
722        sample_merge_conflicts(&store, &mut seen);
723        let counted = conflicts();
724        assert_eq!(counted.len(), 1, "one conflict, two samples");
725        assert_eq!(counted[0].agent.as_deref(), Some(agent.as_str()));
726        assert_eq!(counted[0].root.as_deref(), Some(root.as_str()));
727
728        assert!(git(&["merge", "--abort"]));
729        sample_merge_conflicts(&store, &mut seen);
730        assert!(seen.is_empty(), "resolved");
731        assert!(!git(&["merge", "-q", "other"]));
732        sample_merge_conflicts(&store, &mut seen);
733        assert_eq!(conflicts().len(), 2, "a new conflict counts again");
734    }
735
736    #[test]
737    fn a_quiet_hour_has_no_finding() {
738        let agents = [agent(
739            "mcp-a",
740            "/w/pay",
741            "2026-10-24T05:00:00Z",
742            "2026-10-24T06:00:00Z",
743        )];
744        let findings = hour_findings(
745            std::path::Path::new("/nonexistent/cloud-data"),
746            &[],
747            &agents,
748            &vaults(),
749            &|a: &AgentEntry| Some(a.agent_id.clone()),
750            at("2026-10-24T08:00:00Z"),
751            at("2026-10-24T09:00:00Z"),
752        );
753        assert!(findings.is_empty(), "{findings:?}");
754    }
755}