use std::collections::BTreeMap;
use std::io::Write as _;
use lean_ctx_time::{Duration, UtcDateTime};
use lean_ctx::core::agents::AgentEntry;
use lean_ctx::core::agents::friction::{self, Event};
use super::CloudStore;
use super::bus::v2::{self, About, CollabCounts, MessageType, Publish, Window};
use super::vault::VaultMap;
const HOURS_FILE: &str = "friction.jsonl";
const STATE_FILE: &str = "friction-state.json";
const CATCH_UP_HOURS: i64 = 24;
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct EmitState {
last_hour_ms: Option<i64>,
}
pub fn emit_due(store: &CloudStore, now: UtcDateTime) -> usize {
if !super::bus::relay_v2::speaks_v2(store) {
return 0;
}
let Ok(Some(instance)) = store.instance() else {
return 0;
};
let Ok(this_hour) = now.duration_trunc(Duration::hours(1)) else {
return 0;
};
let dir = store.data_dir();
let state_path = dir.join(STATE_FILE);
let mut state: EmitState = std::fs::read(&state_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let first = state
.last_hour_ms
.and_then(UtcDateTime::from_timestamp_millis)
.map_or(this_hour - Duration::hours(1), |last| {
(last + Duration::hours(1)).max(this_hour - Duration::hours(CATCH_UP_HOURS))
});
let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
let agents = registry.list_all();
let vaults = VaultMap::load(dir);
let active: std::collections::BTreeSet<&str> = registry
.list_active(None)
.into_iter()
.map(|a| a.agent_id.as_str())
.collect();
let worker_of = |agent: &AgentEntry| {
if agent.is_engine_placeholder() {
return None;
}
let (host, role) = super::workers::attach::agent_worker_key(agent);
if active.contains(agent.agent_id.as_str()) {
super::workers::attach::attach(store, &instance.instance_id, &host, &role)
.ok()
.map(|attached| attached.worker.worker_id)
} else {
super::workers::attach::known(store, &instance.instance_id, &host, &role)
.map(|worker| worker.worker_id)
}
};
let now_ms = u64::try_from(now.timestamp_millis()).unwrap_or(0);
let mut queued = 0;
let mut hour = first;
while hour < this_hour {
let end = hour + Duration::hours(1);
let events = friction::events(hour, end);
for finding in hour_findings(dir, &events, agents, &vaults, &worker_of, hour, end) {
if let Err(error) = super::bus::relay_v2::queue_publish(store, finding.publish(now_ms))
{
store.record_error(&format!("collaboration finding: {error}"));
continue;
}
append_hour(dir, &finding);
queued += 1;
}
state.last_hour_ms = Some(hour.timestamp_millis());
hour = end;
}
if let Ok(bytes) = serde_json::to_vec(&state) {
let _ = super::state::write_private(dir, STATE_FILE, &bytes);
}
queued
}
fn append_hour(dir: &std::path::Path, finding: &HourFinding) {
let line = serde_json::json!({
"hour": finding.from_ms,
"worker_id": finding.worker_id,
"place": finding.to,
"counts": finding.counts,
});
let mut options = std::fs::OpenOptions::new();
options.create(true).append(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
if let Ok(mut file) = options.open(dir.join(HOURS_FILE)) {
let _ = writeln!(file, "{line}");
}
}
pub fn sample_merge_conflicts(store: &CloudStore, seen: &mut std::collections::BTreeSet<String>) {
let vaults = crate::vault::connected_map(store);
let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
let mut roots: BTreeMap<&str, &str> = BTreeMap::new();
for agent in registry.list_active(None) {
if crate::unlinked::shared_record(store.data_dir(), &vaults, &agent.project_root).is_some()
{
roots
.entry(agent.project_root.as_str())
.or_insert(agent.agent_id.as_str());
}
}
seen.retain(|root| roots.contains_key(root.as_str()));
for (root, agent) in roots {
if has_unmerged_paths(root) {
if seen.insert(root.to_string()) {
friction::record_for(friction::MERGE_CONFLICT, Some(agent), Some(root));
}
} else {
seen.remove(root);
}
}
}
fn has_unmerged_paths(root: &str) -> bool {
std::process::Command::new("git")
.args(["-C", root, "ls-files", "-u", "-z"])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.is_ok_and(|out| out.status.success() && !out.stdout.is_empty())
}
pub const COUNT_KEYS: [&str; 8] = [
"claim_refused",
"claim_expired",
"registration_renewed",
"wait_timeout",
"merge_conflict",
"gate_reruns",
"agent_seconds",
"idle_seconds",
];
const FRICTION_KEYS: [&str; 6] = [
"claim_refused",
"claim_expired",
"registration_renewed",
"wait_timeout",
"merge_conflict",
"gate_reruns",
];
pub fn count_key(signal: &str) -> Option<&'static str> {
Some(match signal {
friction::CLAIM_REFUSED_PRESENCE
| friction::CLAIM_REFUSED_ROLE
| friction::CLAIM_REFUSED_PERMIT => "claim_refused",
friction::CLAIM_EXPIRED => "claim_expired",
friction::REGISTRATION_RENEWED => "registration_renewed",
friction::WAIT_TIMEOUT => "wait_timeout",
friction::MERGE_CONFLICT => "merge_conflict",
_ => return None,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HourFinding {
pub to: String,
pub worker_id: String,
pub from_ms: i64,
pub to_ms: i64,
pub counts: BTreeMap<&'static str, u32>,
}
impl HourFinding {
pub fn statement(&self) -> String {
let hhmm = |ms: i64| {
UtcDateTime::from_timestamp_millis(ms)
.map_or_else(String::new, |t| t.format("%H:%M").to_string())
};
let signals: u32 = FRICTION_KEYS
.iter()
.filter_map(|key| self.counts.get(key))
.sum();
let seconds = self.counts.get("agent_seconds").copied().unwrap_or(0);
format!(
"Collaboration friction from {} to {}: {signals} signals in {:.1} agent-hours.",
hhmm(self.from_ms),
hhmm(self.to_ms),
f64::from(seconds) / 3600.0
)
}
pub fn publish(&self, now_ms: u64) -> Publish {
let get = |key: &str| self.counts.get(key).copied();
Publish {
schema: v2::BUS_SCHEMA.to_string(),
client_msg_id: v2::new_ulid(now_ms),
to: self.to.clone(),
kind: MessageType::Finding,
worker_id: self.worker_id.clone(),
thread_id: None,
reply_to: None,
refs: Vec::new(),
body: serde_json::json!({"statement": self.statement(), "evidence": "observed"}),
ck_wrapped: None,
epoch: None,
about: Some(About::Collaboration),
counts: Some(CollabCounts {
registration_renewed: get("registration_renewed"),
wait_timeout: get("wait_timeout"),
merge_conflict: get("merge_conflict"),
claim_refused: get("claim_refused"),
claim_expired: get("claim_expired"),
gate_reruns: get("gate_reruns"),
agent_seconds: get("agent_seconds"),
idle_seconds: get("idle_seconds"),
}),
window: Some(Window {
from_ms: u64::try_from(self.from_ms).unwrap_or(0),
to_ms: u64::try_from(self.to_ms).unwrap_or(0),
}),
}
}
}
pub(crate) fn hour_findings(
data_dir: &std::path::Path,
events: &[Event],
agents: &[AgentEntry],
vaults: &VaultMap,
worker_of: &dyn Fn(&AgentEntry) -> Option<String>,
from: UtcDateTime,
to: UtcDateTime,
) -> Vec<HourFinding> {
let place_of = |root: &str| {
crate::unlinked::shared_record(data_dir, vaults, root).map(super::bus::relay_v2::address_of)
};
let mut time: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
let mut counts: BTreeMap<String, BTreeMap<&'static str, u32>> = BTreeMap::new();
for agent in agents {
let Some(place) = place_of(&agent.project_root) else {
continue;
};
let Some(worker) = worker_of(agent) else {
continue;
};
let start = agent.started_at.max(from);
let end = agent.last_active.min(to);
let seconds = (end - start).num_seconds().max(0);
*time.entry(place).or_default().entry(worker).or_default() += seconds;
}
for event in events {
let Some(key) = count_key(&event.signal) else {
continue;
};
let agent = event
.agent
.as_deref()
.and_then(|id| agents.iter().find(|a| a.agent_id == id));
let root = event
.root
.as_deref()
.or_else(|| agent.map(|a| a.project_root.as_str()));
let Some(place) = root.and_then(place_of) else {
continue;
};
if let Some(worker) = agent.and_then(worker_of) {
time.entry(place.clone())
.or_default()
.entry(worker)
.or_default();
}
let count = counts.entry(place).or_default().entry(key).or_default();
*count = count.saturating_add(1);
}
time.into_iter()
.filter_map(|(place, workers)| {
let worker_id = workers
.iter()
.max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
.map(|(id, _)| id.clone())?;
let seconds: i64 = workers.values().sum();
let mut counts = counts.remove(&place).unwrap_or_default();
if seconds > 0 {
counts.insert("agent_seconds", u32::try_from(seconds).unwrap_or(u32::MAX));
}
(!counts.is_empty()).then(|| HourFinding {
to: place,
worker_id,
from_ms: from.timestamp_millis(),
to_ms: to.timestamp_millis(),
counts,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vault::VaultRecord;
use lean_ctx::core::agents::AgentStatus;
fn at(s: &str) -> UtcDateTime {
lean_ctx_time::OffsetDateTime::parse_from_rfc3339(s)
.unwrap()
.to_utc()
}
fn agent(id: &str, root: &str, from: &str, to: &str) -> AgentEntry {
AgentEntry {
agent_id: id.into(),
agent_type: "claude".into(),
role: Some("engine".into()),
project_root: root.into(),
started_at: at(from),
last_active: at(to),
pid: 1,
process_identity: None,
durable_identity_id: None,
status: AgentStatus::Active,
status_message: None,
agent_status_message: None,
transport: None,
role_source: None,
parent: None,
parent_client: None,
app_session_id: None,
display_name: None,
}
}
fn event(signal: &str, agent: Option<&str>, root: Option<&str>) -> Event {
Event {
at: at("2026-10-24T08:30:00Z"),
signal: signal.into(),
agent: agent.map(Into::into),
root: root.map(Into::into),
}
}
fn vaults() -> VaultMap {
let mut map = VaultMap::default();
map.vaults.insert(
"v1".into(),
VaultRecord {
vault_id: "v1".into(),
ns: "acme".into(),
name: "payments".into(),
sealed: false,
roots: vec!["/w/pay".into()],
},
);
map
}
#[test]
fn unlink_of_a_worktree_sends_no_friction_findings() {
let base = tempfile::tempdir().unwrap();
let base = base.path().canonicalize().unwrap();
let (main, wt) = crate::unlinked::fake_worktree(&base);
let data = base.join("data");
let mut map = VaultMap::default();
map.vaults.insert(
"v1".into(),
VaultRecord {
vault_id: "v1".into(),
ns: "acme".into(),
name: "payments".into(),
sealed: false,
roots: vec![main.to_string_lossy().into_owned()],
},
);
let wt_text = wt.to_string_lossy().into_owned();
let agents = [agent(
"mcp-a",
&wt_text,
"2026-10-24T07:00:00Z",
"2026-10-24T10:00:00Z",
)];
let events = [event(friction::WAIT_TIMEOUT, None, Some(&wt_text))];
let worker_of = |a: &AgentEntry| Some(format!("wkr_{}", a.agent_id));
let run = || {
hour_findings(
&data,
&events,
&agents,
&map,
&worker_of,
at("2026-10-24T08:00:00Z"),
at("2026-10-24T09:00:00Z"),
)
};
assert!(!run().is_empty(), "shared through the main checkout");
crate::unlinked::add(&data, &wt).unwrap();
assert!(run().is_empty(), "{:?}", run());
}
#[test]
fn local_signals_map_onto_the_contract_keys() {
for (signal, key) in [
(friction::CLAIM_REFUSED_PRESENCE, "claim_refused"),
(friction::CLAIM_REFUSED_ROLE, "claim_refused"),
(friction::CLAIM_REFUSED_PERMIT, "claim_refused"),
(friction::CLAIM_EXPIRED, "claim_expired"),
(friction::REGISTRATION_RENEWED, "registration_renewed"),
(friction::WAIT_TIMEOUT, "wait_timeout"),
(friction::MERGE_CONFLICT, "merge_conflict"),
] {
assert_eq!(count_key(signal), Some(key), "{signal}");
assert!(COUNT_KEYS.contains(&key));
}
assert_eq!(count_key("something_else"), None);
}
#[test]
fn an_hour_sums_into_one_finding_per_vault() {
let agents = [
agent(
"mcp-a",
"/w/pay",
"2026-10-24T07:00:00Z",
"2026-10-24T08:30:00Z",
),
agent(
"mcp-b",
"/w/pay",
"2026-10-24T08:30:00Z",
"2026-10-24T10:00:00Z",
),
agent(
"mcp-c",
"/w/scratch",
"2026-10-24T08:00:00Z",
"2026-10-24T09:00:00Z",
),
];
let worker_of = |a: &AgentEntry| Some(format!("wkr_{}", a.agent_id));
let events = [
event(friction::CLAIM_REFUSED_ROLE, Some("mcp-a"), None),
event(
friction::CLAIM_REFUSED_PRESENCE,
Some("mcp-b"),
Some("/w/pay"),
),
event(friction::WAIT_TIMEOUT, None, Some("/w/pay")),
event(friction::CLAIM_EXPIRED, Some("mcp-c"), None),
event("unknown_signal", Some("mcp-a"), None),
];
let findings = hour_findings(
std::path::Path::new("/nonexistent/cloud-data"),
&events,
&agents,
&vaults(),
&worker_of,
at("2026-10-24T08:00:00Z"),
at("2026-10-24T09:00:00Z"),
);
assert_eq!(
findings.len(),
1,
"a checkout outside every vault gets none: {findings:?}"
);
let finding = &findings[0];
assert_eq!(finding.to, "#acme/payments");
assert_eq!(
finding.worker_id, "wkr_mcp-a",
"a tie of 30 min each goes to the smaller id"
);
assert_eq!(
(finding.from_ms, finding.to_ms),
(1_792_828_800_000, 1_792_832_400_000)
);
assert_eq!(
finding.counts,
BTreeMap::from([
("agent_seconds", 3600),
("claim_refused", 2),
("wait_timeout", 1)
])
);
assert_eq!(
finding.statement(),
"Collaboration friction from 08:00 to 09:00: 3 signals in 1.0 agent-hours."
);
assert!(finding.counts.keys().all(|key| COUNT_KEYS.contains(key)));
}
#[test]
fn the_publish_matches_the_contract_fixture() {
let path = format!(
"{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/bus/message.finding.collaboration.json",
concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
);
let stored: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let counts: BTreeMap<&'static str, u32> = COUNT_KEYS
.iter()
.filter_map(|key| {
let n = stored["counts"][*key].as_u64()?;
Some((*key, u32::try_from(n).unwrap()))
})
.collect();
let finding = HourFinding {
to: stored["to"].as_str().unwrap().to_string(),
worker_id: stored["worker_id"].as_str().unwrap().to_string(),
from_ms: stored["window"]["from_ms"].as_i64().unwrap(),
to_ms: stored["window"]["to_ms"].as_i64().unwrap(),
counts,
};
let publish = finding.publish(1_792_803_600_000);
publish.validate().expect("a valid v2 publish");
let sent = serde_json::to_value(&publish).unwrap();
for member in [
"schema",
"type",
"about",
"counts",
"window",
"to",
"worker_id",
] {
assert_eq!(sent[member], stored[member], "{member}");
}
assert!(sent.get("refs").is_none(), "no refs");
assert_eq!(sent["body"]["evidence"], "observed");
assert_eq!(
sent["body"]["statement"],
"Collaboration friction from 00:00 to 01:00: 8 signals in 1.5 agent-hours.",
"the window in UTC"
);
}
#[test]
fn closed_hours_are_queued_once_and_only_for_a_v2_cloud() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
store
.write_config(
super::super::state::INSTANCE_FILE,
&super::super::state::InstanceRecord {
instance_id: "inst_a".into(),
org_id: "org_a".into(),
org_name: "Acme".into(),
label: "mac".into(),
url: "https://cloud.example".into(),
org_salt_id: "salt".into(),
enrolled_at: "2026-10-24T00:00:00Z".into(),
web_url: None,
org_kind: None,
company_name: None,
},
)
.unwrap();
let project = tempfile::tempdir().unwrap();
let root = project.path().to_string_lossy().into_owned();
let mut map = VaultMap::default();
map.vaults.insert(
"v1".into(),
VaultRecord {
vault_id: "v1".into(),
ns: "acme".into(),
name: "payments".into(),
sealed: false,
roots: vec![root.clone()],
},
);
map.save(store.data_dir()).unwrap();
let mut registry = lean_ctx::core::agents::AgentRegistry::new();
let agent = registry
.register("claude", Some("engine"), &root, None)
.unwrap();
registry.save().unwrap();
friction::record_for(friction::WAIT_TIMEOUT, Some(&agent), Some(&root));
let next_hour = UtcDateTime::now() + Duration::hours(1);
super::super::bus::relay_v2::record_protocol(&store, false).unwrap();
assert_eq!(
emit_due(&store, next_hour),
0,
"a 1.x Cloud server gets none"
);
super::super::bus::relay_v2::record_protocol(&store, true).unwrap();
assert_eq!(emit_due(&store, next_hour), 1);
assert_eq!(emit_due(&store, next_hour), 0, "an hour is queued once");
let lines = std::fs::read_to_string(store.data_dir().join(HOURS_FILE)).unwrap();
let line: serde_json::Value = serde_json::from_str(lines.trim()).unwrap();
assert_eq!(line["place"], "#acme/payments");
assert_eq!(line["counts"]["wait_timeout"], 1);
assert!(line["worker_id"].as_str().unwrap().starts_with("wkr_"));
}
#[test]
fn a_merge_conflict_counts_once_per_conflict() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
let repo = tempfile::tempdir().unwrap();
let root = repo.path().to_string_lossy().into_owned();
let git = |args: &[&str]| {
let out = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-C", &root])
.args(args)
.output()
.unwrap();
out.status.success()
};
assert!(git(&["init", "-q", "-b", "main"]));
std::fs::write(repo.path().join("f"), "base\n").unwrap();
assert!(git(&["add", "f"]) && git(&["commit", "-qm", "base"]));
assert!(git(&["checkout", "-qb", "other"]));
std::fs::write(repo.path().join("f"), "other\n").unwrap();
assert!(git(&["commit", "-qam", "other"]) && git(&["checkout", "-q", "main"]));
std::fs::write(repo.path().join("f"), "main\n").unwrap();
assert!(git(&["commit", "-qam", "main"]));
assert!(!git(&["merge", "-q", "other"]), "the merge conflicts");
let mut map = VaultMap::default();
map.vaults.insert(
"v1".into(),
VaultRecord {
vault_id: "v1".into(),
ns: "acme".into(),
name: "payments".into(),
sealed: false,
roots: vec![root.clone()],
},
);
map.save(store.data_dir()).unwrap();
let mut registry = lean_ctx::core::agents::AgentRegistry::new();
let agent = registry
.register("claude", Some("engine"), &root, None)
.unwrap();
registry.save().unwrap();
let conflicts = || {
friction::events(
UtcDateTime::now() - Duration::hours(1),
UtcDateTime::now() + Duration::hours(1),
)
.into_iter()
.filter(|e| e.signal == friction::MERGE_CONFLICT)
.collect::<Vec<_>>()
};
let mut seen = std::collections::BTreeSet::new();
sample_merge_conflicts(&store, &mut seen);
sample_merge_conflicts(&store, &mut seen);
let counted = conflicts();
assert_eq!(counted.len(), 1, "one conflict, two samples");
assert_eq!(counted[0].agent.as_deref(), Some(agent.as_str()));
assert_eq!(counted[0].root.as_deref(), Some(root.as_str()));
assert!(git(&["merge", "--abort"]));
sample_merge_conflicts(&store, &mut seen);
assert!(seen.is_empty(), "resolved");
assert!(!git(&["merge", "-q", "other"]));
sample_merge_conflicts(&store, &mut seen);
assert_eq!(conflicts().len(), 2, "a new conflict counts again");
}
#[test]
fn a_quiet_hour_has_no_finding() {
let agents = [agent(
"mcp-a",
"/w/pay",
"2026-10-24T05:00:00Z",
"2026-10-24T06:00:00Z",
)];
let findings = hour_findings(
std::path::Path::new("/nonexistent/cloud-data"),
&[],
&agents,
&vaults(),
&|a: &AgentEntry| Some(a.agent_id.clone()),
at("2026-10-24T08:00:00Z"),
at("2026-10-24T09:00:00Z"),
);
assert!(findings.is_empty(), "{findings:?}");
}
}