1use 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
20const HOURS_FILE: &str = "friction.jsonl";
23const STATE_FILE: &str = "friction-state.json";
25const CATCH_UP_HOURS: i64 = 24;
27
28#[derive(Default, serde::Serialize, serde::Deserialize)]
29struct EmitState {
30 last_hour_ms: Option<i64>,
31}
32
33pub 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 let worker_of = |agent: &AgentEntry| {
71 let (host, role) = super::workers::attach::agent_worker_key(agent);
72 if active.contains(agent.agent_id.as_str()) {
73 super::workers::attach::attach(store, &instance.instance_id, &host, &role)
74 .ok()
75 .map(|attached| attached.worker.worker_id)
76 } else {
77 super::workers::attach::known(store, &instance.instance_id, &host, &role)
78 .map(|worker| worker.worker_id)
79 }
80 };
81 let now_ms = u64::try_from(now.timestamp_millis()).unwrap_or(0);
82 let mut queued = 0;
83 let mut hour = first;
84 while hour < this_hour {
85 let end = hour + Duration::hours(1);
86 let events = friction::events(hour, end);
87 for finding in hour_findings(&events, agents, &vaults, &worker_of, hour, end) {
88 if let Err(error) = super::bus::relay_v2::queue_publish(store, finding.publish(now_ms))
89 {
90 store.record_error(&format!("collaboration finding: {error}"));
91 continue;
92 }
93 append_hour(dir, &finding);
94 queued += 1;
95 }
96 state.last_hour_ms = Some(hour.timestamp_millis());
97 hour = end;
98 }
99 if let Ok(bytes) = serde_json::to_vec(&state) {
100 let _ = super::state::write_private(dir, STATE_FILE, &bytes);
101 }
102 queued
103}
104
105fn append_hour(dir: &std::path::Path, finding: &HourFinding) {
106 let line = serde_json::json!({
107 "hour": finding.from_ms,
108 "worker_id": finding.worker_id,
109 "place": finding.to,
110 "counts": finding.counts,
111 });
112 let mut options = std::fs::OpenOptions::new();
113 options.create(true).append(true);
114 #[cfg(unix)]
115 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
116 if let Ok(mut file) = options.open(dir.join(HOURS_FILE)) {
117 let _ = writeln!(file, "{line}");
118 }
119}
120
121pub fn sample_merge_conflicts(store: &CloudStore, seen: &mut std::collections::BTreeSet<String>) {
126 let vaults = VaultMap::load(store.data_dir());
127 let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
128 let mut roots: BTreeMap<&str, &str> = BTreeMap::new();
129 for agent in registry.list_active(None) {
130 if vaults.for_root(&agent.project_root).is_some() {
131 roots
132 .entry(agent.project_root.as_str())
133 .or_insert(agent.agent_id.as_str());
134 }
135 }
136 seen.retain(|root| roots.contains_key(root.as_str()));
137 for (root, agent) in roots {
138 if has_unmerged_paths(root) {
139 if seen.insert(root.to_string()) {
140 friction::record_for(friction::MERGE_CONFLICT, Some(agent), Some(root));
141 }
142 } else {
143 seen.remove(root);
144 }
145 }
146}
147
148fn has_unmerged_paths(root: &str) -> bool {
150 std::process::Command::new("git")
151 .args(["-C", root, "ls-files", "-u", "-z"])
152 .stdin(std::process::Stdio::null())
153 .stderr(std::process::Stdio::null())
154 .output()
155 .is_ok_and(|out| out.status.success() && !out.stdout.is_empty())
156}
157
158pub const COUNT_KEYS: [&str; 8] = [
160 "claim_refused",
161 "claim_expired",
162 "registration_renewed",
163 "wait_timeout",
164 "merge_conflict",
165 "gate_reruns",
166 "agent_seconds",
167 "idle_seconds",
168];
169
170const FRICTION_KEYS: [&str; 6] = [
172 "claim_refused",
173 "claim_expired",
174 "registration_renewed",
175 "wait_timeout",
176 "merge_conflict",
177 "gate_reruns",
178];
179
180pub fn count_key(signal: &str) -> Option<&'static str> {
183 Some(match signal {
184 friction::CLAIM_REFUSED_PRESENCE
185 | friction::CLAIM_REFUSED_ROLE
186 | friction::CLAIM_REFUSED_PERMIT => "claim_refused",
187 friction::CLAIM_EXPIRED => "claim_expired",
188 friction::REGISTRATION_RENEWED => "registration_renewed",
189 friction::WAIT_TIMEOUT => "wait_timeout",
190 friction::MERGE_CONFLICT => "merge_conflict",
191 _ => return None,
192 })
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct HourFinding {
198 pub to: String,
200 pub worker_id: String,
203 pub from_ms: i64,
204 pub to_ms: i64,
205 pub counts: BTreeMap<&'static str, u32>,
207}
208
209impl HourFinding {
210 pub fn statement(&self) -> String {
213 let hhmm = |ms: i64| {
214 UtcDateTime::from_timestamp_millis(ms)
215 .map_or_else(String::new, |t| t.format("%H:%M").to_string())
216 };
217 let signals: u32 = FRICTION_KEYS
218 .iter()
219 .filter_map(|key| self.counts.get(key))
220 .sum();
221 let seconds = self.counts.get("agent_seconds").copied().unwrap_or(0);
222 format!(
223 "Collaboration friction from {} to {}: {signals} signals in {:.1} agent-hours.",
224 hhmm(self.from_ms),
225 hhmm(self.to_ms),
226 f64::from(seconds) / 3600.0
227 )
228 }
229
230 pub fn publish(&self, now_ms: u64) -> Publish {
234 let get = |key: &str| self.counts.get(key).copied();
235 Publish {
236 schema: v2::BUS_SCHEMA.to_string(),
237 client_msg_id: v2::new_ulid(now_ms),
238 to: self.to.clone(),
239 kind: MessageType::Finding,
240 worker_id: self.worker_id.clone(),
241 thread_id: None,
242 reply_to: None,
243 refs: Vec::new(),
244 body: serde_json::json!({"statement": self.statement(), "evidence": "observed"}),
245 ck_wrapped: None,
246 epoch: None,
247 about: Some(About::Collaboration),
248 counts: Some(CollabCounts {
249 registration_renewed: get("registration_renewed"),
250 wait_timeout: get("wait_timeout"),
251 merge_conflict: get("merge_conflict"),
252 claim_refused: get("claim_refused"),
253 claim_expired: get("claim_expired"),
254 gate_reruns: get("gate_reruns"),
255 agent_seconds: get("agent_seconds"),
256 idle_seconds: get("idle_seconds"),
257 }),
258 window: Some(Window {
259 from_ms: u64::try_from(self.from_ms).unwrap_or(0),
260 to_ms: u64::try_from(self.to_ms).unwrap_or(0),
261 }),
262 }
263 }
264}
265
266pub(crate) fn hour_findings(
273 events: &[Event],
274 agents: &[AgentEntry],
275 vaults: &VaultMap,
276 worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
277 from: UtcDateTime,
278 to: UtcDateTime,
279) -> Vec<HourFinding> {
280 let place_of = |root: &str| vaults.for_root(root).map(super::bus::relay_v2::address_of);
281 let mut time: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
283 let mut counts: BTreeMap<String, BTreeMap<&'static str, u32>> = BTreeMap::new();
284 for agent in agents {
285 let (Some(place), Some(worker)) = (place_of(&agent.project_root), worker_of(agent)) else {
286 continue;
287 };
288 let start = agent.started_at.max(from);
289 let end = agent.last_active.min(to);
290 let seconds = (end - start).num_seconds().max(0);
291 *time.entry(place).or_default().entry(worker).or_default() += seconds;
292 }
293 for event in events {
294 let Some(key) = count_key(&event.signal) else {
295 continue;
296 };
297 let agent = event
298 .agent
299 .as_deref()
300 .and_then(|id| agents.iter().find(|a| a.agent_id == id));
301 let root = event
302 .root
303 .as_deref()
304 .or_else(|| agent.map(|a| a.project_root.as_str()));
305 let Some(place) = root.and_then(place_of) else {
306 continue;
307 };
308 if let Some(worker) = agent.and_then(worker_of) {
309 time.entry(place.clone())
310 .or_default()
311 .entry(worker)
312 .or_default();
313 }
314 let count = counts.entry(place).or_default().entry(key).or_default();
315 *count = count.saturating_add(1);
316 }
317 time.into_iter()
318 .filter_map(|(place, workers)| {
319 let worker_id = workers
320 .iter()
321 .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
322 .map(|(id, _)| id.clone())?;
323 let seconds: i64 = workers.values().sum();
324 let mut counts = counts.remove(&place).unwrap_or_default();
325 if seconds > 0 {
326 counts.insert("agent_seconds", u32::try_from(seconds).unwrap_or(u32::MAX));
327 }
328 (!counts.is_empty()).then(|| HourFinding {
329 to: place,
330 worker_id,
331 from_ms: from.timestamp_millis(),
332 to_ms: to.timestamp_millis(),
333 counts,
334 })
335 })
336 .collect()
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use crate::vault::VaultRecord;
343 use lean_ctx::core::agents::AgentStatus;
344
345 fn at(s: &str) -> UtcDateTime {
346 lean_ctx_time::OffsetDateTime::parse_from_rfc3339(s)
347 .unwrap()
348 .to_utc()
349 }
350
351 fn agent(id: &str, root: &str, from: &str, to: &str) -> AgentEntry {
352 AgentEntry {
353 agent_id: id.into(),
354 agent_type: "claude".into(),
355 role: Some("engine".into()),
356 project_root: root.into(),
357 started_at: at(from),
358 last_active: at(to),
359 pid: 1,
360 process_identity: None,
361 durable_identity_id: None,
362 status: AgentStatus::Active,
363 status_message: None,
364 agent_status_message: None,
365 transport: None,
366 role_source: None,
367 parent: None,
368 app_session_id: None,
369 display_name: None,
370 }
371 }
372
373 fn event(signal: &str, agent: Option<&str>, root: Option<&str>) -> Event {
374 Event {
375 at: at("2026-10-24T08:30:00Z"),
376 signal: signal.into(),
377 agent: agent.map(Into::into),
378 root: root.map(Into::into),
379 }
380 }
381
382 fn vaults() -> VaultMap {
383 let mut map = VaultMap::default();
384 map.vaults.insert(
385 "v1".into(),
386 VaultRecord {
387 vault_id: "v1".into(),
388 ns: "acme".into(),
389 name: "payments".into(),
390 sealed: false,
391 roots: vec!["/w/pay".into()],
392 },
393 );
394 map
395 }
396
397 #[test]
400 fn local_signals_map_onto_the_contract_keys() {
401 for (signal, key) in [
402 (friction::CLAIM_REFUSED_PRESENCE, "claim_refused"),
403 (friction::CLAIM_REFUSED_ROLE, "claim_refused"),
404 (friction::CLAIM_REFUSED_PERMIT, "claim_refused"),
405 (friction::CLAIM_EXPIRED, "claim_expired"),
406 (friction::REGISTRATION_RENEWED, "registration_renewed"),
407 (friction::WAIT_TIMEOUT, "wait_timeout"),
408 (friction::MERGE_CONFLICT, "merge_conflict"),
409 ] {
410 assert_eq!(count_key(signal), Some(key), "{signal}");
411 assert!(COUNT_KEYS.contains(&key));
412 }
413 assert_eq!(count_key("something_else"), None);
414 }
415
416 #[test]
420 fn an_hour_sums_into_one_finding_per_vault() {
421 let agents = [
422 agent(
423 "mcp-a",
424 "/w/pay",
425 "2026-10-24T07:00:00Z",
426 "2026-10-24T08:30:00Z",
427 ),
428 agent(
429 "mcp-b",
430 "/w/pay",
431 "2026-10-24T08:30:00Z",
432 "2026-10-24T10:00:00Z",
433 ),
434 agent(
435 "mcp-c",
436 "/w/scratch",
437 "2026-10-24T08:00:00Z",
438 "2026-10-24T09:00:00Z",
439 ),
440 ];
441 let worker_of = |a: &AgentEntry| Some(format!("wkr_{}", a.agent_id));
442 let events = [
443 event(friction::CLAIM_REFUSED_ROLE, Some("mcp-a"), None),
444 event(
445 friction::CLAIM_REFUSED_PRESENCE,
446 Some("mcp-b"),
447 Some("/w/pay"),
448 ),
449 event(friction::WAIT_TIMEOUT, None, Some("/w/pay")),
450 event(friction::CLAIM_EXPIRED, Some("mcp-c"), None),
451 event("unknown_signal", Some("mcp-a"), None),
452 ];
453 let findings = hour_findings(
454 &events,
455 &agents,
456 &vaults(),
457 &worker_of,
458 at("2026-10-24T08:00:00Z"),
459 at("2026-10-24T09:00:00Z"),
460 );
461 assert_eq!(
462 findings.len(),
463 1,
464 "a checkout outside every vault gets none: {findings:?}"
465 );
466 let finding = &findings[0];
467 assert_eq!(finding.to, "#acme/payments");
468 assert_eq!(
469 finding.worker_id, "wkr_mcp-a",
470 "a tie of 30 min each goes to the smaller id"
471 );
472 assert_eq!(
473 (finding.from_ms, finding.to_ms),
474 (1_792_828_800_000, 1_792_832_400_000)
475 );
476 assert_eq!(
477 finding.counts,
478 BTreeMap::from([
479 ("agent_seconds", 3600),
480 ("claim_refused", 2),
481 ("wait_timeout", 1)
482 ])
483 );
484 assert_eq!(
485 finding.statement(),
486 "Collaboration friction from 08:00 to 09:00: 3 signals in 1.0 agent-hours."
487 );
488 assert!(finding.counts.keys().all(|key| COUNT_KEYS.contains(key)));
489 }
490
491 #[test]
495 fn the_publish_matches_the_contract_fixture() {
496 let path = format!(
497 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/bus/message.finding.collaboration.json",
498 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
499 );
500 let stored: serde_json::Value =
501 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
502 let counts: BTreeMap<&'static str, u32> = COUNT_KEYS
503 .iter()
504 .filter_map(|key| {
505 let n = stored["counts"][*key].as_u64()?;
506 Some((*key, u32::try_from(n).unwrap()))
507 })
508 .collect();
509 let finding = HourFinding {
510 to: stored["to"].as_str().unwrap().to_string(),
511 worker_id: stored["worker_id"].as_str().unwrap().to_string(),
512 from_ms: stored["window"]["from_ms"].as_i64().unwrap(),
513 to_ms: stored["window"]["to_ms"].as_i64().unwrap(),
514 counts,
515 };
516 let publish = finding.publish(1_792_803_600_000);
517 publish.validate().expect("a valid v2 publish");
518 let sent = serde_json::to_value(&publish).unwrap();
519 for member in [
520 "schema",
521 "type",
522 "about",
523 "counts",
524 "window",
525 "to",
526 "worker_id",
527 ] {
528 assert_eq!(sent[member], stored[member], "{member}");
529 }
530 assert!(sent.get("refs").is_none(), "no refs");
531 assert_eq!(sent["body"]["evidence"], "observed");
532 assert_eq!(
533 sent["body"]["statement"],
534 "Collaboration friction from 00:00 to 01:00: 8 signals in 1.5 agent-hours.",
535 "the window in UTC"
536 );
537 }
538
539 #[test]
542 fn closed_hours_are_queued_once_and_only_for_a_v2_cloud() {
543 let _data = lean_ctx::core::data_dir::isolated_data_dir();
544 let dir = tempfile::tempdir().unwrap();
545 let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
546 store
547 .write_config(
548 super::super::state::INSTANCE_FILE,
549 &super::super::state::InstanceRecord {
550 instance_id: "inst_a".into(),
551 org_id: "org_a".into(),
552 org_name: "Acme".into(),
553 label: "mac".into(),
554 url: "https://cloud.example".into(),
555 org_salt_id: "salt".into(),
556 enrolled_at: "2026-10-24T00:00:00Z".into(),
557 web_url: None,
558 org_kind: None,
559 company_name: None,
560 },
561 )
562 .unwrap();
563 let project = tempfile::tempdir().unwrap();
564 let root = project.path().to_string_lossy().into_owned();
565 let mut map = VaultMap::default();
566 map.vaults.insert(
567 "v1".into(),
568 VaultRecord {
569 vault_id: "v1".into(),
570 ns: "acme".into(),
571 name: "payments".into(),
572 sealed: false,
573 roots: vec![root.clone()],
574 },
575 );
576 map.save(store.data_dir()).unwrap();
577 let mut registry = lean_ctx::core::agents::AgentRegistry::new();
578 let agent = registry
579 .register("claude", Some("engine"), &root, None)
580 .unwrap();
581 registry.save().unwrap();
582 friction::record_for(friction::WAIT_TIMEOUT, Some(&agent), Some(&root));
583 let next_hour = UtcDateTime::now() + Duration::hours(1);
584
585 super::super::bus::relay_v2::record_protocol(&store, false).unwrap();
586 assert_eq!(
587 emit_due(&store, next_hour),
588 0,
589 "a 1.x LeanCTX Cloud server gets none"
590 );
591
592 super::super::bus::relay_v2::record_protocol(&store, true).unwrap();
593 assert_eq!(emit_due(&store, next_hour), 1);
594 assert_eq!(emit_due(&store, next_hour), 0, "an hour is queued once");
595 let lines = std::fs::read_to_string(store.data_dir().join(HOURS_FILE)).unwrap();
596 let line: serde_json::Value = serde_json::from_str(lines.trim()).unwrap();
597 assert_eq!(line["place"], "#acme/payments");
598 assert_eq!(line["counts"]["wait_timeout"], 1);
599 assert!(line["worker_id"].as_str().unwrap().starts_with("wkr_"));
600 }
601
602 #[test]
606 fn a_merge_conflict_counts_once_per_conflict() {
607 let _data = lean_ctx::core::data_dir::isolated_data_dir();
608 let dir = tempfile::tempdir().unwrap();
609 let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
610 let repo = tempfile::tempdir().unwrap();
611 let root = repo.path().to_string_lossy().into_owned();
612 let git = |args: &[&str]| {
613 let out = std::process::Command::new("git")
614 .args(["-c", "user.name=t", "-c", "user.email=t@t", "-C", &root])
615 .args(args)
616 .output()
617 .unwrap();
618 out.status.success()
619 };
620 assert!(git(&["init", "-q", "-b", "main"]));
621 std::fs::write(repo.path().join("f"), "base\n").unwrap();
622 assert!(git(&["add", "f"]) && git(&["commit", "-qm", "base"]));
623 assert!(git(&["checkout", "-qb", "other"]));
624 std::fs::write(repo.path().join("f"), "other\n").unwrap();
625 assert!(git(&["commit", "-qam", "other"]) && git(&["checkout", "-q", "main"]));
626 std::fs::write(repo.path().join("f"), "main\n").unwrap();
627 assert!(git(&["commit", "-qam", "main"]));
628 assert!(!git(&["merge", "-q", "other"]), "the merge conflicts");
629
630 let mut map = VaultMap::default();
631 map.vaults.insert(
632 "v1".into(),
633 VaultRecord {
634 vault_id: "v1".into(),
635 ns: "acme".into(),
636 name: "payments".into(),
637 sealed: false,
638 roots: vec![root.clone()],
639 },
640 );
641 map.save(store.data_dir()).unwrap();
642 let mut registry = lean_ctx::core::agents::AgentRegistry::new();
643 let agent = registry
644 .register("claude", Some("engine"), &root, None)
645 .unwrap();
646 registry.save().unwrap();
647
648 let conflicts = || {
649 friction::events(
650 UtcDateTime::now() - Duration::hours(1),
651 UtcDateTime::now() + Duration::hours(1),
652 )
653 .into_iter()
654 .filter(|e| e.signal == friction::MERGE_CONFLICT)
655 .collect::<Vec<_>>()
656 };
657 let mut seen = std::collections::BTreeSet::new();
658 sample_merge_conflicts(&store, &mut seen);
659 sample_merge_conflicts(&store, &mut seen);
660 let counted = conflicts();
661 assert_eq!(counted.len(), 1, "one conflict, two samples");
662 assert_eq!(counted[0].agent.as_deref(), Some(agent.as_str()));
663 assert_eq!(counted[0].root.as_deref(), Some(root.as_str()));
664
665 assert!(git(&["merge", "--abort"]));
666 sample_merge_conflicts(&store, &mut seen);
667 assert!(seen.is_empty(), "resolved");
668 assert!(!git(&["merge", "-q", "other"]));
669 sample_merge_conflicts(&store, &mut seen);
670 assert_eq!(conflicts().len(), 2, "a new conflict counts again");
671 }
672
673 #[test]
674 fn a_quiet_hour_has_no_finding() {
675 let agents = [agent(
676 "mcp-a",
677 "/w/pay",
678 "2026-10-24T05:00:00Z",
679 "2026-10-24T06:00:00Z",
680 )];
681 let findings = hour_findings(
682 &[],
683 &agents,
684 &vaults(),
685 &|a: &AgentEntry| Some(a.agent_id.clone()),
686 at("2026-10-24T08:00:00Z"),
687 at("2026-10-24T09:00:00Z"),
688 );
689 assert!(findings.is_empty(), "{findings:?}");
690 }
691}