1use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16
17pub const AGENT_LEASE_SCHEMA_VERSION: u16 = 1;
18const DEFAULT_MAX_LEASES: usize = 1_024;
19const MAX_LEASE_DURATION_MS: u64 = 60 * 60 * 1_000;
20
21#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum AgentLeaseResourceKindV1 {
24 Path,
25 Symbol,
26 WorkGraphNode,
28}
29
30#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct AgentLeaseRequestV1 {
33 pub schema_version: u16,
34 pub lease_request_ref: String,
35 pub resource_kind: AgentLeaseResourceKindV1,
36 pub resource_ref: String,
37 pub owner_agent_id: String,
38 pub duration_ms: u64,
39}
40
41impl AgentLeaseRequestV1 {
42 pub fn validate(&self) -> Result<(), AgentLeaseError> {
43 if self.schema_version != AGENT_LEASE_SCHEMA_VERSION {
44 return Err(AgentLeaseError::UnsupportedVersion(self.schema_version));
45 }
46 opaque_ref("lease_request_ref", &self.lease_request_ref)?;
47 opaque_ref("resource_ref", &self.resource_ref)?;
48 agent_id(&self.owner_agent_id)?;
49 if self.duration_ms == 0 || self.duration_ms > MAX_LEASE_DURATION_MS {
50 return Err(AgentLeaseError::Invalid(format!(
51 "duration_ms must be between 1 and {MAX_LEASE_DURATION_MS}"
52 )));
53 }
54 Ok(())
55 }
56}
57
58#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct AgentLeaseV1 {
61 pub schema_version: u16,
62 pub lease_ref: String,
63 pub request: AgentLeaseRequestV1,
64 pub expires_at_epoch_ms: u64,
65}
66
67impl AgentLeaseV1 {
68 pub fn is_active_at(&self, now_epoch_ms: u64) -> bool {
69 now_epoch_ms < self.expires_at_epoch_ms
70 }
71}
72
73#[derive(Clone, Debug, Eq, PartialEq)]
74pub enum AgentLeaseAcquireV1 {
75 Granted(AgentLeaseV1),
76 HeldBy {
77 owner_agent_id: String,
78 lease_ref: String,
79 expires_at_epoch_ms: u64,
80 },
81}
82
83pub struct AgentLeaseRegistryV1 {
85 leases: BTreeMap<(AgentLeaseResourceKindV1, String), AgentLeaseV1>,
86 max_leases: usize,
87}
88
89impl Default for AgentLeaseRegistryV1 {
90 fn default() -> Self {
91 Self::new(DEFAULT_MAX_LEASES)
92 }
93}
94
95impl AgentLeaseRegistryV1 {
96 #[must_use]
97 pub fn new(max_leases: usize) -> Self {
98 Self {
99 leases: BTreeMap::new(),
100 max_leases: max_leases.max(1),
101 }
102 }
103
104 pub fn acquire(
105 &mut self,
106 request: AgentLeaseRequestV1,
107 now_epoch_ms: u64,
108 ) -> Result<AgentLeaseAcquireV1, AgentLeaseError> {
109 request.validate()?;
110 self.remove_expired(now_epoch_ms);
111 let key = (request.resource_kind, request.resource_ref.clone());
112 if let Some(existing) = self.leases.get(&key) {
113 if existing.request.owner_agent_id == request.owner_agent_id
114 && existing.request.lease_request_ref == request.lease_request_ref
115 {
116 return Ok(AgentLeaseAcquireV1::Granted(existing.clone()));
117 }
118 return Ok(AgentLeaseAcquireV1::HeldBy {
119 owner_agent_id: existing.request.owner_agent_id.clone(),
120 lease_ref: existing.lease_ref.clone(),
121 expires_at_epoch_ms: existing.expires_at_epoch_ms,
122 });
123 }
124 if request.resource_kind == AgentLeaseResourceKindV1::Path
127 && request.resource_ref.starts_with("path:")
128 && let Some(existing) = self.leases.values().find(|lease| {
129 lease.request.resource_kind == AgentLeaseResourceKindV1::Path
130 && crate::core::work_graph::path_claims_overlap(
131 &lease.request.resource_ref,
132 &request.resource_ref,
133 )
134 })
135 {
136 return Ok(AgentLeaseAcquireV1::HeldBy {
137 owner_agent_id: existing.request.owner_agent_id.clone(),
138 lease_ref: existing.lease_ref.clone(),
139 expires_at_epoch_ms: existing.expires_at_epoch_ms,
140 });
141 }
142 if self.leases.len() >= self.max_leases {
143 return Err(AgentLeaseError::CapacityExceeded(self.max_leases));
144 }
145 let expires_at_epoch_ms = now_epoch_ms.saturating_add(request.duration_ms);
146 let lease_ref = compute_lease_ref(&request, expires_at_epoch_ms)?;
147 let lease = AgentLeaseV1 {
148 schema_version: AGENT_LEASE_SCHEMA_VERSION,
149 lease_ref,
150 request,
151 expires_at_epoch_ms,
152 };
153 self.leases.insert(key, lease.clone());
154 Ok(AgentLeaseAcquireV1::Granted(lease))
155 }
156
157 pub fn release(
158 &mut self,
159 resource_kind: AgentLeaseResourceKindV1,
160 resource_ref: &str,
161 owner_agent_id: &str,
162 lease_ref: &str,
163 now_epoch_ms: u64,
164 ) -> Result<bool, AgentLeaseError> {
165 opaque_ref("resource_ref", resource_ref)?;
166 agent_id(owner_agent_id)?;
167 self.remove_expired(now_epoch_ms);
168 let key = (resource_kind, resource_ref.to_string());
169 let Some(existing) = self.leases.get(&key) else {
170 return Ok(false);
171 };
172 if existing.request.owner_agent_id != owner_agent_id || existing.lease_ref != lease_ref {
173 return Err(AgentLeaseError::NotOwner);
174 }
175 self.leases.remove(&key);
176 Ok(true)
177 }
178
179 pub fn renew(
186 &mut self,
187 resource_kind: AgentLeaseResourceKindV1,
188 resource_ref: &str,
189 owner_agent_id: &str,
190 lease_ref: &str,
191 duration_ms: u64,
192 now_epoch_ms: u64,
193 ) -> Result<AgentLeaseV1, AgentLeaseError> {
194 opaque_ref("resource_ref", resource_ref)?;
195 agent_id(owner_agent_id)?;
196 if duration_ms == 0 || duration_ms > MAX_LEASE_DURATION_MS {
197 return Err(AgentLeaseError::Invalid(format!(
198 "duration_ms must be between 1 and {MAX_LEASE_DURATION_MS}"
199 )));
200 }
201 let key = (resource_kind, resource_ref.to_string());
202 let Some(existing) = self.leases.get(&key) else {
203 return Err(AgentLeaseError::NotFound);
204 };
205 if !existing.is_active_at(now_epoch_ms) {
206 self.leases.remove(&key);
207 return Err(AgentLeaseError::Expired);
208 }
209 if existing.request.owner_agent_id != owner_agent_id || existing.lease_ref != lease_ref {
210 return Err(AgentLeaseError::NotOwner);
211 }
212 let existing = self.leases.get_mut(&key).expect("lease checked above");
213 existing.request.duration_ms = duration_ms;
214 existing.expires_at_epoch_ms = now_epoch_ms.saturating_add(duration_ms);
215 Ok(existing.clone())
216 }
217
218 #[must_use]
219 pub fn active_count(&self, now_epoch_ms: u64) -> usize {
220 self.leases
221 .values()
222 .filter(|l| l.is_active_at(now_epoch_ms))
223 .count()
224 }
225
226 fn remove_expired(&mut self, now_epoch_ms: u64) {
227 self.leases.retain(|_, l| l.is_active_at(now_epoch_ms));
228 }
229}
230
231#[derive(Serialize, Deserialize)]
236#[serde(deny_unknown_fields)]
237struct AgentLeaseFileV1 {
238 schema_version: u16,
239 leases: Vec<AgentLeaseV1>,
240}
241
242fn now_epoch_ms() -> u64 {
243 std::time::SystemTime::now()
244 .duration_since(std::time::UNIX_EPOCH)
245 .unwrap_or_default()
246 .as_millis() as u64
247}
248
249fn shared_dir() -> Result<PathBuf, AgentLeaseError> {
250 crate::core::data_dir::lean_ctx_data_dir()
251 .map(|dir| dir.join("agents"))
252 .map_err(AgentLeaseError::Store)
253}
254
255fn load_registry(path: &Path) -> Result<AgentLeaseRegistryV1, AgentLeaseError> {
256 let mut registry = AgentLeaseRegistryV1::default();
257 let content = match std::fs::read_to_string(path) {
258 Ok(content) => content,
259 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(registry),
260 Err(error) => {
261 return Err(AgentLeaseError::Store(format!(
262 "read {}: {error}",
263 path.display()
264 )));
265 }
266 };
267 let file: AgentLeaseFileV1 = serde_json::from_str(&content).map_err(|error| {
270 AgentLeaseError::Store(format!(
271 "lease store is corrupt at {}: {error}",
272 path.display()
273 ))
274 })?;
275 if file.schema_version != AGENT_LEASE_SCHEMA_VERSION {
276 return Err(AgentLeaseError::UnsupportedVersion(file.schema_version));
277 }
278 for lease in file.leases {
279 let key = (
280 lease.request.resource_kind,
281 lease.request.resource_ref.clone(),
282 );
283 registry.leases.insert(key, lease);
284 }
285 Ok(registry)
286}
287
288fn save_registry(path: &Path, registry: &AgentLeaseRegistryV1) -> Result<(), AgentLeaseError> {
289 let file = AgentLeaseFileV1 {
290 schema_version: AGENT_LEASE_SCHEMA_VERSION,
291 leases: registry.leases.values().cloned().collect(),
292 };
293 let json = serde_json::to_string_pretty(&file)
294 .map_err(|error| AgentLeaseError::Serialize(error.to_string()))?;
295 crate::config_io::write_atomic(path, &json)
296 .map_err(|error| AgentLeaseError::Store(format!("persist {}: {error}", path.display())))
297}
298
299fn with_shared_registry<T>(
302 mutate: impl FnOnce(&mut AgentLeaseRegistryV1, u64) -> Result<T, AgentLeaseError>,
303) -> Result<T, AgentLeaseError> {
304 let dir = shared_dir()?;
305 std::fs::create_dir_all(&dir).map_err(|error| {
306 AgentLeaseError::Store(format!("create lease directory {}: {error}", dir.display()))
307 })?;
308 let _lock = crate::core::agents::FileLock::acquire(&dir.join("leases.lock"))
309 .map_err(AgentLeaseError::Store)?;
310 let path = dir.join("leases.json");
311 let mut registry = load_registry(&path)?;
312 let result = mutate(&mut registry, now_epoch_ms())?;
313 save_registry(&path, ®istry)?;
314 Ok(result)
315}
316
317pub fn acquire_shared(
319 request: AgentLeaseRequestV1,
320) -> Result<AgentLeaseAcquireV1, AgentLeaseError> {
321 with_shared_registry(|registry, now| registry.acquire(request, now))
322}
323
324pub fn release_shared(
326 resource_kind: AgentLeaseResourceKindV1,
327 resource_ref: &str,
328 owner_agent_id: &str,
329 lease_ref: &str,
330) -> Result<bool, AgentLeaseError> {
331 with_shared_registry(|registry, now| {
332 registry.release(resource_kind, resource_ref, owner_agent_id, lease_ref, now)
333 })
334}
335
336pub fn renew_shared(
340 resource_kind: AgentLeaseResourceKindV1,
341 resource_ref: &str,
342 owner_agent_id: &str,
343 lease_ref: &str,
344 duration_ms: u64,
345) -> Result<AgentLeaseV1, AgentLeaseError> {
346 with_shared_registry(|registry, now| {
347 registry.renew(
348 resource_kind,
349 resource_ref,
350 owner_agent_id,
351 lease_ref,
352 duration_ms,
353 now,
354 )
355 })
356}
357
358fn compute_lease_ref(
361 request: &AgentLeaseRequestV1,
362 expires_at_epoch_ms: u64,
363) -> Result<String, AgentLeaseError> {
364 let bytes = serde_json::to_vec(&(request, expires_at_epoch_ms))
365 .map_err(|e| AgentLeaseError::Serialize(e.to_string()))?;
366 Ok(format!("lease:{}", blake3::hash(&bytes).to_hex()))
367}
368
369fn opaque_ref(label: &str, value: &str) -> Result<(), AgentLeaseError> {
370 let (scheme, identifier) = value.split_once(':').ok_or_else(|| {
371 AgentLeaseError::Invalid(format!("{label} must use scheme:identifier form"))
372 })?;
373 let scheme_valid = !scheme.is_empty()
374 && scheme
375 .bytes()
376 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
377 let identifier_valid = !identifier.is_empty()
378 && value.len() <= 256
379 && identifier.bytes().all(|b| b.is_ascii_graphic());
380 (scheme_valid && identifier_valid)
381 .then_some(())
382 .ok_or_else(|| AgentLeaseError::Invalid(format!("invalid {label}")))
383}
384
385fn agent_id(value: &str) -> Result<(), AgentLeaseError> {
386 (!value.is_empty() && value.len() <= 256 && value.bytes().all(|b| b.is_ascii_graphic()))
387 .then_some(())
388 .ok_or_else(|| AgentLeaseError::Invalid("invalid owner_agent_id".into()))
389}
390
391#[derive(Debug, thiserror::Error)]
394pub enum AgentLeaseError {
395 #[error("unsupported schema version {0}")]
396 UnsupportedVersion(u16),
397 #[error("invalid lease: {0}")]
398 Invalid(String),
399 #[error("registry at capacity {0}")]
400 CapacityExceeded(usize),
401 #[error("not owner or mismatched lease_ref")]
402 NotOwner,
403 #[error("lease not found")]
404 NotFound,
405 #[error("lease expired")]
406 Expired,
407 #[error("serialization failed: {0}")]
408 Serialize(String),
409 #[error("lease store: {0}")]
410 Store(String),
411}
412
413#[cfg(test)]
416pub mod tests {
417 use super::*;
418
419 fn request(owner: &str, ref_id: &str) -> AgentLeaseRequestV1 {
420 AgentLeaseRequestV1 {
421 schema_version: AGENT_LEASE_SCHEMA_VERSION,
422 lease_request_ref: ref_id.to_string(),
423 resource_kind: AgentLeaseResourceKindV1::Path,
424 resource_ref: "pathref:src-core-main".to_string(),
425 owner_agent_id: owner.to_string(),
426 duration_ms: 100,
427 }
428 }
429
430 #[test]
431 fn idempotent_grant_blocks_foreign_owner() {
432 let mut reg = AgentLeaseRegistryV1::default();
433 let AgentLeaseAcquireV1::Granted(granted) =
434 reg.acquire(request("agent-a", "request:a"), 10).unwrap()
435 else {
436 panic!("expected grant")
437 };
438 assert_eq!(
439 reg.acquire(request("agent-a", "request:a"), 20).unwrap(),
440 AgentLeaseAcquireV1::Granted(granted)
441 );
442 assert!(matches!(
443 reg.acquire(request("agent-b", "request:b"), 20),
444 Ok(AgentLeaseAcquireV1::HeldBy { owner_agent_id, .. }) if owner_agent_id == "agent-a"
445 ));
446 }
447
448 #[test]
449 fn hierarchical_paths_block_both_orders_without_prefix_false_positives() {
450 for (held, incoming) in [
451 ("path:project/src", "path:project/src/main.rs"),
452 ("path:project/src/main.rs", "path:project/src"),
453 ] {
454 let mut reg = AgentLeaseRegistryV1::default();
455 let mut first = request("agent-a", "request:a");
456 first.resource_ref = held.into();
457 let granted = reg.acquire(first.clone(), 1).unwrap();
458 assert_eq!(reg.acquire(first, 2).unwrap(), granted);
459 for owner in ["agent-a", "agent-b"] {
460 let mut competing = request(owner, "request:b");
461 competing.resource_ref = incoming.into();
462 assert!(matches!(
463 reg.acquire(competing, 2).unwrap(),
464 AgentLeaseAcquireV1::HeldBy { .. }
465 ));
466 }
467 for independent in ["path:project/src-other", "path:other-project/src"] {
468 let mut next = request("agent-b", "request:c");
469 next.resource_ref = independent.into();
470 assert!(matches!(
471 reg.acquire(next, 2).unwrap(),
472 AgentLeaseAcquireV1::Granted(_)
473 ));
474 }
475 }
476 }
477
478 #[test]
479 fn expiry_frees_resource() {
480 let mut reg = AgentLeaseRegistryV1::default();
481 let _ = reg.acquire(request("agent-a", "request:a"), 10).unwrap();
482 assert!(matches!(
483 reg.acquire(request("agent-b", "request:b"), 111),
484 Ok(AgentLeaseAcquireV1::Granted(_))
485 ));
486 }
487
488 #[test]
489 fn release_requires_owner() {
490 let mut reg = AgentLeaseRegistryV1::default();
491 let AgentLeaseAcquireV1::Granted(granted) =
492 reg.acquire(request("agent-a", "request:a"), 10).unwrap()
493 else {
494 panic!("expected grant")
495 };
496 assert!(
497 reg.release(
498 AgentLeaseResourceKindV1::Path,
499 "pathref:src-core-main",
500 "agent-b",
501 &granted.lease_ref,
502 20
503 )
504 .is_err()
505 );
506 assert!(
507 reg.release(
508 AgentLeaseResourceKindV1::Path,
509 "pathref:src-core-main",
510 "agent-a",
511 &granted.lease_ref,
512 20
513 )
514 .unwrap()
515 );
516 }
517
518 #[test]
519 fn renew_extends_owned_lease_without_rotating_fence() {
520 let mut reg = AgentLeaseRegistryV1::default();
521 let AgentLeaseAcquireV1::Granted(granted) =
522 reg.acquire(request("agent-a", "request:a"), 10).unwrap()
523 else {
524 panic!("expected grant")
525 };
526 let renewed = reg
527 .renew(
528 AgentLeaseResourceKindV1::Path,
529 "pathref:src-core-main",
530 "agent-a",
531 &granted.lease_ref,
532 500,
533 50,
534 )
535 .unwrap();
536 assert_eq!(renewed.lease_ref, granted.lease_ref);
537 assert_eq!(renewed.expires_at_epoch_ms, 550);
538 assert!(renewed.is_active_at(549));
539 }
540
541 #[test]
542 fn renew_rejects_expired_token_and_allows_reclaim() {
543 let mut reg = AgentLeaseRegistryV1::default();
544 let AgentLeaseAcquireV1::Granted(granted) =
545 reg.acquire(request("agent-a", "request:a"), 10).unwrap()
546 else {
547 panic!("expected grant")
548 };
549 assert!(matches!(
550 reg.renew(
551 AgentLeaseResourceKindV1::Path,
552 "pathref:src-core-main",
553 "agent-a",
554 &granted.lease_ref,
555 500,
556 110,
557 ),
558 Err(AgentLeaseError::Expired)
559 ));
560 assert!(matches!(
561 reg.acquire(request("agent-b", "request:b"), 111),
562 Ok(AgentLeaseAcquireV1::Granted(_))
563 ));
564 }
565
566 #[test]
567 fn capacity_enforced() {
568 let mut reg = AgentLeaseRegistryV1::new(1);
569 let _ = reg.acquire(request("agent-a", "request:a"), 1).unwrap();
570 let second = AgentLeaseRequestV1 {
571 resource_ref: "symbolref:main".to_string(),
572 resource_kind: AgentLeaseResourceKindV1::Symbol,
573 ..request("agent-b", "request:b")
574 };
575 assert!(matches!(
576 reg.acquire(second, 1),
577 Err(AgentLeaseError::CapacityExceeded(1))
578 ));
579 }
580
581 fn long_request(owner: &str, ref_id: &str) -> AgentLeaseRequestV1 {
582 AgentLeaseRequestV1 {
583 duration_ms: 60_000,
584 ..request(owner, ref_id)
585 }
586 }
587
588 #[test]
591 fn shared_registry_is_visible_across_calls_and_persisted() {
592 let iso = crate::core::data_dir::isolated_data_dir();
593 let AgentLeaseAcquireV1::Granted(granted) =
594 acquire_shared(long_request("agent-a", "request:a")).unwrap()
595 else {
596 panic!("expected grant")
597 };
598 let store = iso.path().join("agents").join("leases.json");
599 assert!(store.exists(), "lease store is written to the data dir");
600 assert!(matches!(
601 acquire_shared(long_request("agent-b", "request:b")),
602 Ok(AgentLeaseAcquireV1::HeldBy { owner_agent_id, .. }) if owner_agent_id == "agent-a"
603 ));
604 assert!(
605 release_shared(
606 AgentLeaseResourceKindV1::Path,
607 "pathref:src-core-main",
608 "agent-a",
609 &granted.lease_ref,
610 )
611 .unwrap()
612 );
613 assert!(matches!(
614 acquire_shared(long_request("agent-b", "request:b")),
615 Ok(AgentLeaseAcquireV1::Granted(_))
616 ));
617 }
618
619 #[test]
620 fn corrupt_shared_store_fails_closed() {
621 let iso = crate::core::data_dir::isolated_data_dir();
622 let dir = iso.path().join("agents");
623 std::fs::create_dir_all(&dir).unwrap();
624 std::fs::write(dir.join("leases.json"), "{not json").unwrap();
625 assert!(matches!(
626 acquire_shared(long_request("agent-a", "request:a")),
627 Err(AgentLeaseError::Store(message)) if message.contains("corrupt")
628 ));
629 assert_eq!(
630 std::fs::read_to_string(dir.join("leases.json")).unwrap(),
631 "{not json",
632 "a corrupt store is never overwritten"
633 );
634 }
635}
636