1use std::collections::BTreeMap;
9use std::io::Write as _;
10
11use chrono::{DateTime, Duration, DurationRound as _, Utc};
12
13use crate::core::agents::AgentEntry;
14use crate::core::agents::friction::{self, Event};
15
16use super::HiveStore;
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: &HiveStore, now: DateTime<Utc>) -> 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(DateTime::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 = crate::core::agents::AgentRegistry::load_or_create();
60 let agents = registry.list_all();
61 let vaults = VaultMap::load(dir);
62 let worker_of = |agent: &AgentEntry| {
63 let host = super::workers::attach::detect_host_app(
64 agent.transport.as_ref().map(|t| t.host.as_str()),
65 Some(agent.agent_type.as_str()),
66 std::iter::empty::<(&str, &str)>(),
67 None,
68 );
69 let role = agent
70 .role
71 .as_deref()
72 .unwrap_or(super::workers::GENERAL_ROLE);
73 super::workers::attach::attach(store, &instance.instance_id, &host, role)
74 .ok()
75 .map(|attached| attached.worker.worker_id)
76 };
77 let now_ms = u64::try_from(now.timestamp_millis()).unwrap_or(0);
78 let mut queued = 0;
79 let mut hour = first;
80 while hour < this_hour {
81 let end = hour + Duration::hours(1);
82 let events = friction::events(hour, end);
83 for finding in hour_findings(&events, agents, &vaults, &worker_of, hour, end) {
84 if let Err(error) = super::bus::relay_v2::queue_publish(store, finding.publish(now_ms))
85 {
86 store.record_error(&format!("collaboration finding: {error}"));
87 continue;
88 }
89 append_hour(dir, &finding);
90 queued += 1;
91 }
92 state.last_hour_ms = Some(hour.timestamp_millis());
93 hour = end;
94 }
95 if let Ok(bytes) = serde_json::to_vec(&state) {
96 let _ = super::state::write_private(dir, STATE_FILE, &bytes);
97 }
98 queued
99}
100
101fn append_hour(dir: &std::path::Path, finding: &HourFinding) {
102 let line = serde_json::json!({
103 "hour": finding.from_ms,
104 "worker_id": finding.worker_id,
105 "place": finding.to,
106 "counts": finding.counts,
107 });
108 let mut options = std::fs::OpenOptions::new();
109 options.create(true).append(true);
110 #[cfg(unix)]
111 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
112 if let Ok(mut file) = options.open(dir.join(HOURS_FILE)) {
113 let _ = writeln!(file, "{line}");
114 }
115}
116
117pub fn sample_merge_conflicts(store: &HiveStore, seen: &mut std::collections::BTreeSet<String>) {
122 let vaults = VaultMap::load(store.data_dir());
123 let registry = crate::core::agents::AgentRegistry::load_or_create();
124 let mut roots: BTreeMap<&str, &str> = BTreeMap::new();
125 for agent in registry.list_active(None) {
126 if vaults
127 .for_root(&agent.project_root)
128 .is_some_and(|record| !record.sealed)
129 {
130 roots
131 .entry(agent.project_root.as_str())
132 .or_insert(agent.agent_id.as_str());
133 }
134 }
135 seen.retain(|root| roots.contains_key(root.as_str()));
136 for (root, agent) in roots {
137 if has_unmerged_paths(root) {
138 if seen.insert(root.to_string()) {
139 friction::record_for(friction::MERGE_CONFLICT, Some(agent), Some(root));
140 }
141 } else {
142 seen.remove(root);
143 }
144 }
145}
146
147fn has_unmerged_paths(root: &str) -> bool {
149 std::process::Command::new("git")
150 .args(["-C", root, "ls-files", "-u", "-z"])
151 .stdin(std::process::Stdio::null())
152 .stderr(std::process::Stdio::null())
153 .output()
154 .is_ok_and(|out| out.status.success() && !out.stdout.is_empty())
155}
156
157pub const COUNT_KEYS: [&str; 8] = [
159 "claim_refused",
160 "claim_expired",
161 "registration_renewed",
162 "wait_timeout",
163 "merge_conflict",
164 "gate_reruns",
165 "agent_seconds",
166 "idle_seconds",
167];
168
169const FRICTION_KEYS: [&str; 6] = [
171 "claim_refused",
172 "claim_expired",
173 "registration_renewed",
174 "wait_timeout",
175 "merge_conflict",
176 "gate_reruns",
177];
178
179pub fn count_key(signal: &str) -> Option<&'static str> {
182 Some(match signal {
183 friction::CLAIM_REFUSED_PRESENCE
184 | friction::CLAIM_REFUSED_ROLE
185 | friction::CLAIM_REFUSED_PERMIT => "claim_refused",
186 friction::CLAIM_EXPIRED => "claim_expired",
187 friction::REGISTRATION_RENEWED => "registration_renewed",
188 friction::WAIT_TIMEOUT => "wait_timeout",
189 friction::MERGE_CONFLICT => "merge_conflict",
190 _ => return None,
191 })
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct HourFinding {
197 pub to: String,
199 pub worker_id: String,
202 pub from_ms: i64,
203 pub to_ms: i64,
204 pub counts: BTreeMap<&'static str, u32>,
206}
207
208impl HourFinding {
209 pub fn statement(&self) -> String {
212 let hhmm = |ms: i64| {
213 DateTime::from_timestamp_millis(ms)
214 .map_or_else(String::new, |t| t.format("%H:%M").to_string())
215 };
216 let signals: u32 = FRICTION_KEYS
217 .iter()
218 .filter_map(|key| self.counts.get(key))
219 .sum();
220 let seconds = self.counts.get("agent_seconds").copied().unwrap_or(0);
221 format!(
222 "Collaboration friction from {} to {}: {signals} signals in {:.1} agent-hours.",
223 hhmm(self.from_ms),
224 hhmm(self.to_ms),
225 f64::from(seconds) / 3600.0
226 )
227 }
228
229 pub fn publish(&self, now_ms: u64) -> Publish {
233 let get = |key: &str| self.counts.get(key).copied();
234 Publish {
235 schema: v2::BUS_SCHEMA.to_string(),
236 client_msg_id: v2::new_ulid(now_ms),
237 to: self.to.clone(),
238 kind: MessageType::Finding,
239 worker_id: self.worker_id.clone(),
240 thread_id: None,
241 reply_to: None,
242 refs: Vec::new(),
243 body: serde_json::json!({"statement": self.statement(), "evidence": "observed"}),
244 ck_wrapped: None,
245 epoch: None,
246 about: Some(About::Collaboration),
247 counts: Some(CollabCounts {
248 registration_renewed: get("registration_renewed"),
249 wait_timeout: get("wait_timeout"),
250 merge_conflict: get("merge_conflict"),
251 claim_refused: get("claim_refused"),
252 claim_expired: get("claim_expired"),
253 gate_reruns: get("gate_reruns"),
254 agent_seconds: get("agent_seconds"),
255 idle_seconds: get("idle_seconds"),
256 }),
257 window: Some(Window {
258 from_ms: u64::try_from(self.from_ms).unwrap_or(0),
259 to_ms: u64::try_from(self.to_ms).unwrap_or(0),
260 }),
261 }
262 }
263}
264
265pub(crate) fn hour_findings(
272 events: &[Event],
273 agents: &[AgentEntry],
274 vaults: &VaultMap,
275 worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
276 from: DateTime<Utc>,
277 to: DateTime<Utc>,
278) -> Vec<HourFinding> {
279 let place_of = |root: &str| {
280 vaults
281 .for_root(root)
282 .filter(|record| !record.sealed)
283 .map(super::bus::relay_v2::address_of)
284 };
285 let mut time: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
287 let mut counts: BTreeMap<String, BTreeMap<&'static str, u32>> = BTreeMap::new();
288 for agent in agents {
289 let (Some(place), Some(worker)) = (place_of(&agent.project_root), worker_of(agent)) else {
290 continue;
291 };
292 let start = agent.started_at.max(from);
293 let end = agent.last_active.min(to);
294 let seconds = (end - start).num_seconds().max(0);
295 *time.entry(place).or_default().entry(worker).or_default() += seconds;
296 }
297 for event in events {
298 let Some(key) = count_key(&event.signal) else {
299 continue;
300 };
301 let agent = event
302 .agent
303 .as_deref()
304 .and_then(|id| agents.iter().find(|a| a.agent_id == id));
305 let root = event
306 .root
307 .as_deref()
308 .or_else(|| agent.map(|a| a.project_root.as_str()));
309 let Some(place) = root.and_then(place_of) else {
310 continue;
311 };
312 if let Some(worker) = agent.and_then(worker_of) {
313 time.entry(place.clone())
314 .or_default()
315 .entry(worker)
316 .or_default();
317 }
318 let count = counts.entry(place).or_default().entry(key).or_default();
319 *count = count.saturating_add(1);
320 }
321 time.into_iter()
322 .filter_map(|(place, workers)| {
323 let worker_id = workers
324 .iter()
325 .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
326 .map(|(id, _)| id.clone())?;
327 let seconds: i64 = workers.values().sum();
328 let mut counts = counts.remove(&place).unwrap_or_default();
329 if seconds > 0 {
330 counts.insert("agent_seconds", u32::try_from(seconds).unwrap_or(u32::MAX));
331 }
332 (!counts.is_empty()).then(|| HourFinding {
333 to: place,
334 worker_id,
335 from_ms: from.timestamp_millis(),
336 to_ms: to.timestamp_millis(),
337 counts,
338 })
339 })
340 .collect()
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::core::agents::AgentStatus;
347 use crate::core::hive::vault::VaultRecord;
348
349 fn at(s: &str) -> DateTime<Utc> {
350 DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
351 }
352
353 fn agent(id: &str, root: &str, from: &str, to: &str) -> AgentEntry {
354 AgentEntry {
355 agent_id: id.into(),
356 agent_type: "claude".into(),
357 role: Some("engine".into()),
358 project_root: root.into(),
359 started_at: at(from),
360 last_active: at(to),
361 pid: 1,
362 process_identity: None,
363 durable_identity_id: None,
364 status: AgentStatus::Active,
365 status_message: None,
366 transport: None,
367 role_source: None,
368 parent: None,
369 }
370 }
371
372 fn event(signal: &str, agent: Option<&str>, root: Option<&str>) -> Event {
373 Event {
374 at: at("2026-10-24T08:30:00Z"),
375 signal: signal.into(),
376 agent: agent.map(Into::into),
377 root: root.map(Into::into),
378 }
379 }
380
381 fn vaults() -> VaultMap {
382 let mut map = VaultMap::default();
383 for (id, ns, name, sealed, root) in [
384 ("v1", "acme", "payments", false, "/w/pay"),
385 ("v2", "acme", "secret", true, "/w/secret"),
386 ] {
387 map.vaults.insert(
388 id.into(),
389 VaultRecord {
390 vault_id: id.into(),
391 ns: ns.into(),
392 name: name.into(),
393 sealed,
394 roots: vec![root.into()],
395 },
396 );
397 }
398 map
399 }
400
401 #[test]
404 fn local_signals_map_onto_the_contract_keys() {
405 for (signal, key) in [
406 (friction::CLAIM_REFUSED_PRESENCE, "claim_refused"),
407 (friction::CLAIM_REFUSED_ROLE, "claim_refused"),
408 (friction::CLAIM_REFUSED_PERMIT, "claim_refused"),
409 (friction::CLAIM_EXPIRED, "claim_expired"),
410 (friction::REGISTRATION_RENEWED, "registration_renewed"),
411 (friction::WAIT_TIMEOUT, "wait_timeout"),
412 (friction::MERGE_CONFLICT, "merge_conflict"),
413 ] {
414 assert_eq!(count_key(signal), Some(key), "{signal}");
415 assert!(COUNT_KEYS.contains(&key));
416 }
417 assert_eq!(count_key("something_else"), None);
418 }
419
420 #[test]
424 fn an_hour_sums_into_one_finding_per_vault() {
425 let agents = [
426 agent(
427 "mcp-a",
428 "/w/pay",
429 "2026-10-24T07:00:00Z",
430 "2026-10-24T08:30:00Z",
431 ),
432 agent(
433 "mcp-b",
434 "/w/pay",
435 "2026-10-24T08:30:00Z",
436 "2026-10-24T10:00:00Z",
437 ),
438 agent(
439 "mcp-c",
440 "/w/secret",
441 "2026-10-24T08:00:00Z",
442 "2026-10-24T09:00:00Z",
443 ),
444 ];
445 let worker_of = |a: &AgentEntry| Some(format!("wkr_{}", a.agent_id));
446 let events = [
447 event(friction::CLAIM_REFUSED_ROLE, Some("mcp-a"), None),
448 event(
449 friction::CLAIM_REFUSED_PRESENCE,
450 Some("mcp-b"),
451 Some("/w/pay"),
452 ),
453 event(friction::WAIT_TIMEOUT, None, Some("/w/pay")),
454 event(friction::CLAIM_EXPIRED, Some("mcp-c"), None),
455 event("unknown_signal", Some("mcp-a"), None),
456 ];
457 let findings = hour_findings(
458 &events,
459 &agents,
460 &vaults(),
461 &worker_of,
462 at("2026-10-24T08:00:00Z"),
463 at("2026-10-24T09:00:00Z"),
464 );
465 assert_eq!(
466 findings.len(),
467 1,
468 "the sealed vault gets none: {findings:?}"
469 );
470 let finding = &findings[0];
471 assert_eq!(finding.to, "#acme/payments");
472 assert_eq!(
473 finding.worker_id, "wkr_mcp-a",
474 "a tie of 30 min each goes to the smaller id"
475 );
476 assert_eq!(
477 (finding.from_ms, finding.to_ms),
478 (1_792_828_800_000, 1_792_832_400_000)
479 );
480 assert_eq!(
481 finding.counts,
482 BTreeMap::from([
483 ("agent_seconds", 3600),
484 ("claim_refused", 2),
485 ("wait_timeout", 1)
486 ])
487 );
488 assert_eq!(
489 finding.statement(),
490 "Collaboration friction from 08:00 to 09:00: 3 signals in 1.0 agent-hours."
491 );
492 assert!(finding.counts.keys().all(|key| COUNT_KEYS.contains(key)));
493 }
494
495 #[test]
499 fn the_publish_matches_the_contract_fixture() {
500 let path = format!(
501 "{}/crates/lean-ctx-protocol/tests/fixtures/hive-v2/bus/message.finding.collaboration.json",
502 env!("CARGO_MANIFEST_DIR")
503 );
504 let stored: serde_json::Value =
505 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
506 let counts: BTreeMap<&'static str, u32> = COUNT_KEYS
507 .iter()
508 .filter_map(|key| {
509 let n = stored["counts"][*key].as_u64()?;
510 Some((*key, u32::try_from(n).unwrap()))
511 })
512 .collect();
513 let finding = HourFinding {
514 to: stored["to"].as_str().unwrap().to_string(),
515 worker_id: stored["worker_id"].as_str().unwrap().to_string(),
516 from_ms: stored["window"]["from_ms"].as_i64().unwrap(),
517 to_ms: stored["window"]["to_ms"].as_i64().unwrap(),
518 counts,
519 };
520 let publish = finding.publish(1_792_803_600_000);
521 publish.validate().expect("a valid v2 publish");
522 let sent = serde_json::to_value(&publish).unwrap();
523 for member in [
524 "schema",
525 "type",
526 "about",
527 "counts",
528 "window",
529 "to",
530 "worker_id",
531 ] {
532 assert_eq!(sent[member], stored[member], "{member}");
533 }
534 assert!(sent.get("refs").is_none(), "no refs");
535 assert_eq!(sent["body"]["evidence"], "observed");
536 assert_eq!(
537 sent["body"]["statement"],
538 "Collaboration friction from 00:00 to 01:00: 8 signals in 1.5 agent-hours.",
539 "the window in UTC"
540 );
541 }
542
543 #[test]
546 fn closed_hours_are_queued_once_and_only_for_a_v2_hive() {
547 let _data = crate::core::data_dir::isolated_data_dir();
548 let dir = tempfile::tempdir().unwrap();
549 let store = HiveStore::at(dir.path().join("c"), dir.path().join("d"));
550 store
551 .write_config(
552 super::super::state::INSTANCE_FILE,
553 &super::super::state::InstanceRecord {
554 instance_id: "inst_a".into(),
555 org_id: "org_a".into(),
556 org_name: "Acme".into(),
557 label: "mac".into(),
558 url: "https://hive.example".into(),
559 org_salt_id: "salt".into(),
560 enrolled_at: "2026-10-24T00:00:00Z".into(),
561 web_url: None,
562 org_kind: None,
563 company_name: None,
564 },
565 )
566 .unwrap();
567 let project = tempfile::tempdir().unwrap();
568 let root = project.path().to_string_lossy().into_owned();
569 let mut map = VaultMap::default();
570 map.vaults.insert(
571 "v1".into(),
572 VaultRecord {
573 vault_id: "v1".into(),
574 ns: "acme".into(),
575 name: "payments".into(),
576 sealed: false,
577 roots: vec![root.clone()],
578 },
579 );
580 map.save(store.data_dir()).unwrap();
581 let mut registry = crate::core::agents::AgentRegistry::new();
582 let agent = registry
583 .register("claude", Some("engine"), &root, None)
584 .unwrap();
585 registry.save().unwrap();
586 friction::record_for(friction::WAIT_TIMEOUT, Some(&agent), Some(&root));
587 let next_hour = Utc::now() + Duration::hours(1);
588
589 super::super::bus::relay_v2::record_protocol(&store, false).unwrap();
590 assert_eq!(emit_due(&store, next_hour), 0, "a 1.x Hive gets none");
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 = crate::core::data_dir::isolated_data_dir();
608 let dir = tempfile::tempdir().unwrap();
609 let store = HiveStore::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 = crate::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 Utc::now() - Duration::hours(1),
651 Utc::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}