1use std::collections::BTreeSet;
31use std::fmt::Write as _;
32use std::path::Path;
33
34use serde::{Deserialize, Serialize};
35
36use crate::core::agent_lease::{
37 AGENT_LEASE_SCHEMA_VERSION, AgentLeaseAcquireV1, AgentLeaseRequestV1, AgentLeaseResourceKindV1,
38 AgentLeaseV1,
39};
40
41pub const UNIT_SCHEME: &str = "project-unit:";
43pub const WHOLE_FILE: &str = "*";
45pub const CLAIM_TTL_MS: u64 = 10 * 60 * 1_000;
47pub const CLAIMS_SCHEMA: &str = "leanctx.claims.v1";
49const MAX_REF_BYTES: usize = 256;
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum ClaimMode {
54 Off,
55 Warn,
56 Strict,
57}
58
59#[must_use]
61pub fn mode() -> ClaimMode {
62 match std::env::var("LEAN_CTX_CLAIM_MODE")
63 .unwrap_or_default()
64 .trim()
65 .to_ascii_lowercase()
66 .as_str()
67 {
68 "off" | "0" | "false" => ClaimMode::Off,
69 "strict" | "enforce" | "refuse" => ClaimMode::Strict,
70 _ => ClaimMode::Warn,
71 }
72}
73
74#[must_use]
79pub fn repo_scope(project_root: &str) -> String {
80 let identity = crate::core::project_hash::project_identity(project_root)
81 .unwrap_or_else(|| crate::core::project_hash::hash_project_root(project_root));
82 blake3::hash(identity.as_bytes()).to_hex()[..16].to_string()
83}
84
85fn encode(out: &mut String, text: &str) {
86 for byte in text.bytes() {
87 if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_' | b':') {
88 out.push(byte as char);
89 } else {
90 let _ = write!(out, "%{byte:02X}");
91 }
92 }
93}
94
95fn decode(text: &str) -> Option<String> {
96 let bytes = text.as_bytes();
97 let mut out = Vec::with_capacity(bytes.len());
98 let mut i = 0;
99 while i < bytes.len() {
100 if bytes[i] == b'%' {
101 let hex = text.get(i + 1..i + 3)?;
102 out.push(u8::from_str_radix(hex, 16).ok()?);
103 i += 3;
104 } else {
105 out.push(bytes[i]);
106 i += 1;
107 }
108 }
109 String::from_utf8(out).ok()
110}
111
112#[must_use]
115pub fn unit_resource(scope: &str, rel: &str, unit: &str) -> Option<String> {
116 let mut out = format!("{UNIT_SCHEME}{scope}/");
117 encode(&mut out, rel);
118 out.push('#');
119 encode(&mut out, unit);
120 (out.len() <= MAX_REF_BYTES).then_some(out)
121}
122
123#[must_use]
125pub fn parse_unit_resource(resource: &str) -> Option<(String, String, String)> {
126 let rest = resource.strip_prefix(UNIT_SCHEME)?;
127 let (scope, rest) = rest.split_once('/')?;
128 let (rel, unit) = rest.rsplit_once('#')?;
129 Some((scope.to_string(), decode(rel)?, decode(unit)?))
130}
131
132#[must_use]
134pub fn relative_path(project_root: &str, path: &Path) -> Option<String> {
135 let root = Path::new(project_root);
136 let rel = path
137 .strip_prefix(root)
138 .ok()
139 .map(Path::to_path_buf)
140 .or_else(|| {
141 let root = crate::core::pathutil::safe_canonicalize_or_self(root);
142 let path = path
143 .parent()
144 .map(crate::core::pathutil::safe_canonicalize_or_self)
145 .map(|p| p.join(path.file_name().unwrap_or_default()))?;
146 path.strip_prefix(root).ok().map(Path::to_path_buf)
147 })?;
148 let rel = rel.to_string_lossy().replace('\\', "/");
149 (!rel.is_empty() && !rel.split('/').any(|p| p == "..")).then_some(rel)
150}
151
152#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct UnitSpan {
157 pub name: String,
158 pub start: usize,
159 pub end: usize,
160}
161
162fn markdown_sections(content: &str) -> Vec<UnitSpan> {
163 let lines: Vec<&str> = content.lines().collect();
164 let mut heads: Vec<(usize, usize, String)> = Vec::new();
165 let mut fence = false;
166 for (i, line) in lines.iter().enumerate() {
167 let trimmed = line.trim_start();
168 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
169 fence = !fence;
170 continue;
171 }
172 if fence {
173 continue;
174 }
175 let level = line.bytes().take_while(|b| *b == b'#').count();
176 if (1..=6).contains(&level) && line[level..].starts_with(' ') {
177 heads.push((i + 1, level, line[level..].trim().to_string()));
178 }
179 }
180 heads
181 .iter()
182 .enumerate()
183 .map(|(k, (start, level, name))| {
184 let end = heads[k + 1..]
185 .iter()
186 .find(|(_, l, _)| l <= level)
187 .map_or(lines.len(), |(s, _, _)| s - 1);
188 UnitSpan {
189 name: name.clone(),
190 start: *start,
191 end: end.max(*start),
192 }
193 })
194 .collect()
195}
196
197#[must_use]
200pub fn units_of(path: &str, content: &str) -> Vec<UnitSpan> {
201 let ext = Path::new(path)
202 .extension()
203 .and_then(|e| e.to_str())
204 .unwrap_or("")
205 .to_ascii_lowercase();
206 if matches!(ext.as_str(), "md" | "markdown" | "mdx") {
207 return markdown_sections(content);
208 }
209 crate::core::signatures::extract_signatures_counted(content, &ext)
211 .0
212 .into_iter()
213 .filter_map(|sig| {
214 let start = sig.start_line?;
215 let end = sig.end_line.unwrap_or(start).max(start);
216 (!sig.name.is_empty()).then_some(UnitSpan {
217 name: sig.name,
218 start,
219 end,
220 })
221 })
222 .collect()
223}
224
225#[must_use]
228pub fn changed_spans(before: &str, after: &str) -> (Vec<(usize, usize)>, Vec<(usize, usize)>) {
229 let diff = similar::TextDiff::from_lines(before, after);
230 let mut old = Vec::new();
231 let mut new = Vec::new();
232 for op in diff.ops() {
233 let (tag, o, n) = op.as_tag_tuple();
234 if tag == similar::DiffTag::Equal {
235 continue;
236 }
237 old.push((o.start + 1, o.end));
238 new.push((n.start + 1, n.end));
239 }
240 (old, new)
241}
242
243fn touches(unit: &UnitSpan, (start, end): (usize, usize)) -> bool {
244 if end < start {
245 unit.start < start && start <= unit.end
248 } else {
249 unit.start <= end && start <= unit.end
250 }
251}
252
253#[must_use]
255pub fn touched_units(units: &[UnitSpan], spans: &[(usize, usize)]) -> BTreeSet<String> {
256 let mut out = BTreeSet::new();
257 for &span in spans {
258 let hit: Vec<&UnitSpan> = units.iter().filter(|u| touches(u, span)).collect();
259 for u in &hit {
260 let inner = hit.iter().any(|v| {
261 v != u
262 && v.start >= u.start
263 && v.end <= u.end
264 && (v.end - v.start) < (u.end - u.start)
265 });
266 if !inner {
267 out.insert(u.name.clone());
268 }
269 }
270 }
271 out
272}
273
274#[must_use]
277pub fn edit_footprint(
278 path: &str,
279 before: &str,
280 after: &str,
281) -> (BTreeSet<String>, Vec<(usize, usize)>) {
282 let (old, new) = changed_spans(before, after);
283 let mut names = touched_units(&units_of(path, before), &old);
284 names.extend(touched_units(&units_of(path, after), &new));
285 (names, old)
286}
287
288#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct Conflict {
293 pub holder: String,
294 pub path: String,
295 pub unit: String,
296 pub expires_at_epoch_ms: u64,
297}
298
299fn other_live(leases: Vec<AgentLeaseV1>, agent_id: &str) -> impl Iterator<Item = AgentLeaseV1> {
300 let agent_id = agent_id.to_string();
301 leases
302 .into_iter()
303 .filter(move |lease| lease.request.owner_agent_id != agent_id)
304}
305
306#[must_use]
311#[allow(clippy::too_many_arguments)]
312pub fn conflicts_in(
313 leases: Vec<AgentLeaseV1>,
314 project_root: &str,
315 scope: &str,
316 agent_id: &str,
317 rel: &str,
318 before: &str,
319 names: &BTreeSet<String>,
320 spans: &[(usize, usize)],
321) -> Vec<Conflict> {
322 let rel_folded = rel.to_lowercase();
323 let mut before_units: Option<Vec<UnitSpan>> = None;
324 let mut out = Vec::new();
325 for lease in other_live(leases, agent_id) {
326 let held = &lease.request.resource_ref;
327 let unit = match lease.request.resource_kind {
328 AgentLeaseResourceKindV1::Symbol => {
329 let Some((s, path, unit)) = parse_unit_resource(held) else {
330 continue;
331 };
332 if s != scope || path != rel {
333 continue;
334 }
335 let name = unit_symbol_name(&unit);
337 let hit = unit == WHOLE_FILE
338 || names.contains(&unit)
339 || names.contains(name)
340 || before_units
341 .get_or_insert_with(|| units_of(rel, before))
342 .iter()
343 .any(|u| {
344 (u.name == unit || u.name == name)
345 && spans.iter().any(|s| touches(u, *s))
346 });
347 if !hit {
348 continue;
349 }
350 unit
351 }
352 AgentLeaseResourceKindV1::Path => {
353 let Some(path) = crate::core::agent_lease::project_path_of(project_root, held)
354 else {
355 continue;
356 };
357 let path = decode(&path).unwrap_or(path).to_lowercase();
358 if rel_folded != path && !rel_folded.starts_with(&format!("{path}/")) {
359 continue;
360 }
361 WHOLE_FILE.to_string()
362 }
363 AgentLeaseResourceKindV1::WorkGraphNode => continue,
364 };
365 out.push(Conflict {
366 holder: lease.request.owner_agent_id.clone(),
367 path: rel.to_string(),
368 unit,
369 expires_at_epoch_ms: lease.expires_at_epoch_ms,
370 });
371 }
372 out.sort_by(|a, b| (&a.holder, &a.unit).cmp(&(&b.holder, &b.unit)));
373 out.dedup();
374 out
375}
376
377fn now_ms() -> u64 {
378 std::time::SystemTime::now()
379 .duration_since(std::time::UNIX_EPOCH)
380 .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
381}
382
383#[must_use]
385pub fn render_conflicts(conflicts: &[Conflict], refused: bool) -> String {
386 let now = now_ms();
387 let mut out = if refused {
388 "ERROR: claim conflict (LEAN_CTX_CLAIM_MODE=strict), nothing was written:\n".to_string()
389 } else {
390 "WARNING: claim conflict, another agent is editing what this edit touched:\n".to_string()
391 };
392 for c in conflicts {
393 let unit = if c.unit == WHOLE_FILE {
394 "the whole file".to_string()
395 } else {
396 format!("unit `{}`", c.unit)
397 };
398 let _ = writeln!(
399 out,
400 " {}: {unit} is claimed by {} for {}s more",
401 c.path,
402 c.holder,
403 c.expires_at_epoch_ms.saturating_sub(now) / 1_000
404 );
405 }
406 out.push_str(
407 " Alternative: edit a different unit, wait until the holder finishes \
408 (ctx_agent action=claims shows holders), or message the holder; \
409 ctx_agent action=plan_claims plans a task around held units.",
410 );
411 out
412}
413
414fn request(agent_id: &str, resource_ref: String, duration_ms: u64) -> AgentLeaseRequestV1 {
417 AgentLeaseRequestV1 {
418 schema_version: AGENT_LEASE_SCHEMA_VERSION,
419 lease_request_ref: format!(
420 "lease-request:{}",
421 blake3::hash(format!("{agent_id}:{resource_ref}").as_bytes()).to_hex()
422 ),
423 resource_kind: AgentLeaseResourceKindV1::Symbol,
424 resource_ref,
425 owner_agent_id: agent_id.to_string(),
426 duration_ms,
427 }
428}
429
430pub const MAX_EXPLICIT_TTL_MS: u64 = 60 * 60 * 1_000;
432
433#[must_use]
438pub fn unit_symbol_name(unit: &str) -> &str {
439 fn kinded(segment: &str) -> Option<&str> {
440 let (kind, name) = segment.split_once(':')?;
441 let kind_ok = !kind.is_empty()
442 && kind
443 .bytes()
444 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
445 let name_ok = name
446 .chars()
447 .next()
448 .is_some_and(|c| c != ':' && !c.is_whitespace());
449 (kind_ok && name_ok).then_some(name)
450 }
451 if unit.split('/').all(|segment| kinded(segment).is_some()) {
452 unit.rsplit('/').next().and_then(kinded).unwrap_or(unit)
453 } else {
454 unit
455 }
456}
457
458#[derive(Clone, Debug, PartialEq, Eq)]
460pub enum ExplicitClaim {
461 Held { expires_ms: u64 },
463 HeldBy { holder: String, expires_ms: u64 },
466 Failed(String),
468}
469
470pub fn claim_explicit(
476 scope: &str,
477 agent_id: &str,
478 rel: &str,
479 unit: &str,
480 ttl_ms: u64,
481) -> ExplicitClaim {
482 let ttl_ms = ttl_ms.clamp(1, MAX_EXPLICIT_TTL_MS);
483 let Some(resource) = unit_resource(scope, rel, unit) else {
484 return ExplicitClaim::Failed(format!(
485 "{rel}#{unit}: unit reference exceeds {MAX_REF_BYTES} bytes"
486 ));
487 };
488 if let Some((holder, expires_ms)) = same_symbol_holder(scope, agent_id, rel, unit) {
491 return ExplicitClaim::HeldBy { holder, expires_ms };
492 }
493 match crate::core::agent_lease::acquire_shared(request(agent_id, resource.clone(), ttl_ms)) {
494 Ok(AgentLeaseAcquireV1::Granted(lease)) => {
495 if lease.expires_at_epoch_ms.saturating_add(1_000) < now_ms().saturating_add(ttl_ms) {
497 if let Ok(renewed) = crate::core::agent_lease::renew_shared(
498 AgentLeaseResourceKindV1::Symbol,
499 &resource,
500 agent_id,
501 &lease.lease_ref,
502 ttl_ms,
503 ) {
504 return ExplicitClaim::Held {
505 expires_ms: renewed.expires_at_epoch_ms,
506 };
507 }
508 }
509 ExplicitClaim::Held {
510 expires_ms: lease.expires_at_epoch_ms,
511 }
512 }
513 Ok(AgentLeaseAcquireV1::HeldBy {
514 owner_agent_id,
515 expires_at_epoch_ms,
516 ..
517 }) => ExplicitClaim::HeldBy {
518 holder: owner_agent_id,
519 expires_ms: expires_at_epoch_ms,
520 },
521 Err(error) => ExplicitClaim::Failed(format!("{rel}#{unit}: {error}")),
522 }
523}
524
525fn same_symbol_holder(scope: &str, agent_id: &str, rel: &str, unit: &str) -> Option<(String, u64)> {
530 if unit == WHOLE_FILE {
531 return None;
532 }
533 let name = unit_symbol_name(unit);
534 let bare = name == unit;
535 let leases = crate::core::agent_lease::active_shared().ok()?;
536 other_live(leases, agent_id).find_map(|lease| {
537 if lease.request.resource_kind != AgentLeaseResourceKindV1::Symbol {
538 return None;
539 }
540 let (s, path, held) = parse_unit_resource(&lease.request.resource_ref)?;
541 let held_name = unit_symbol_name(&held);
542 let meets = s == scope
543 && path == rel
544 && held != unit
545 && held != WHOLE_FILE
546 && held_name == name
547 && (bare || held_name == held);
548 meets.then(|| {
549 (
550 lease.request.owner_agent_id.clone(),
551 lease.expires_at_epoch_ms,
552 )
553 })
554 })
555}
556
557pub fn release_units(scope: &str, agent_id: &str, units: &[(String, String)]) -> usize {
561 let Ok(leases) = crate::core::agent_lease::active_shared() else {
562 return 0;
563 };
564 leases
565 .into_iter()
566 .filter(|l| {
567 l.request.owner_agent_id == agent_id
568 && l.request.resource_kind == AgentLeaseResourceKindV1::Symbol
569 && parse_unit_resource(&l.request.resource_ref).is_some_and(|(s, rel, unit)| {
570 s == scope
571 && (units.is_empty() || units.iter().any(|(r, u)| *r == rel && *u == unit))
572 })
573 })
574 .filter(|l| {
575 crate::core::agent_lease::release_shared(
576 AgentLeaseResourceKindV1::Symbol,
577 &l.request.resource_ref,
578 agent_id,
579 &l.lease_ref,
580 )
581 .unwrap_or(false)
582 })
583 .count()
584}
585
586pub fn claim(scope: &str, agent_id: &str, rel: &str, units: &BTreeSet<String>) -> Vec<String> {
590 let mut held = Vec::new();
591 for unit in units {
592 let Some(resource) = unit_resource(scope, rel, unit) else {
593 continue;
594 };
595 match crate::core::agent_lease::acquire_shared(request(
596 agent_id,
597 resource.clone(),
598 CLAIM_TTL_MS,
599 )) {
600 Ok(AgentLeaseAcquireV1::Granted(lease)) => {
601 if lease.expires_at_epoch_ms.saturating_sub(now_ms()) < CLAIM_TTL_MS / 2 {
602 let _ = crate::core::agent_lease::renew_shared(
603 AgentLeaseResourceKindV1::Symbol,
604 &resource,
605 agent_id,
606 &lease.lease_ref,
607 CLAIM_TTL_MS,
608 );
609 }
610 held.push(unit.clone());
611 }
612 Ok(AgentLeaseAcquireV1::HeldBy { .. }) | Err(_) => {}
613 }
614 }
615 held
616}
617
618pub fn release_agent(agent_id: &str) -> usize {
620 let Ok(leases) = crate::core::agent_lease::active_shared() else {
621 return 0;
622 };
623 leases
624 .into_iter()
625 .filter(|l| {
626 l.request.owner_agent_id == agent_id
627 && l.request.resource_kind == AgentLeaseResourceKindV1::Symbol
628 && l.request.resource_ref.starts_with(UNIT_SCHEME)
629 })
630 .filter(|l| {
631 crate::core::agent_lease::release_shared(
632 AgentLeaseResourceKindV1::Symbol,
633 &l.request.resource_ref,
634 agent_id,
635 &l.lease_ref,
636 )
637 .unwrap_or(false)
638 })
639 .count()
640}
641
642#[derive(Clone, Debug, PartialEq, Eq)]
646pub enum Gate {
647 Clear,
649 Warn(String),
651 Refuse(String),
653}
654
655#[must_use]
658pub fn gate(project_root: &str, agent_id: &str, path: &Path, before: &str, after: &str) -> Gate {
659 gate_with(mode(), project_root, agent_id, path, before, after)
660}
661
662#[must_use]
664pub fn gate_with(
665 mode: ClaimMode,
666 project_root: &str,
667 agent_id: &str,
668 path: &Path,
669 before: &str,
670 after: &str,
671) -> Gate {
672 if mode == ClaimMode::Off || project_root.is_empty() || agent_id.is_empty() {
673 return Gate::Clear;
674 }
675 let Some(rel) = relative_path(project_root, path) else {
676 return Gate::Clear;
677 };
678 let scope = repo_scope(project_root);
679 let (names, spans) = edit_footprint(&rel, before, after);
680 let leases = crate::core::agent_lease::active_shared().unwrap_or_default();
681 let found = conflicts_in(
682 leases,
683 project_root,
684 &scope,
685 agent_id,
686 &rel,
687 before,
688 &names,
689 &spans,
690 );
691 if !found.is_empty() && mode == ClaimMode::Strict {
692 return Gate::Refuse(render_conflicts(&found, true));
693 }
694 let _ = claim(&scope, agent_id, &rel, &names);
695 if found.is_empty() {
696 Gate::Clear
697 } else {
698 Gate::Warn(render_conflicts(&found, false))
699 }
700}
701
702#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
706pub struct ClaimEntry {
707 pub holder: String,
708 pub path: String,
709 pub unit: String,
710 pub expires_ms: Option<u64>,
711}
712
713#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
715pub struct ClaimsSnapshot {
716 pub schema: String,
717 pub claims: Vec<ClaimEntry>,
718}
719
720#[must_use]
722pub fn snapshot(project_root: &str) -> ClaimsSnapshot {
723 let scope = repo_scope(project_root);
724 let leases = crate::core::agent_lease::active_shared().unwrap_or_default();
725 let mut claims: Vec<ClaimEntry> = leases
726 .into_iter()
727 .filter_map(|lease| {
728 let (path, unit) = match lease.request.resource_kind {
729 AgentLeaseResourceKindV1::Symbol => {
730 let (s, path, unit) = parse_unit_resource(&lease.request.resource_ref)?;
731 (s == scope).then_some((path, unit))?
732 }
733 AgentLeaseResourceKindV1::Path => {
734 let path = crate::core::agent_lease::project_path_of(
735 project_root,
736 &lease.request.resource_ref,
737 )?;
738 (decode(&path).unwrap_or(path), WHOLE_FILE.to_string())
739 }
740 AgentLeaseResourceKindV1::WorkGraphNode => return None,
741 };
742 Some(ClaimEntry {
743 holder: lease.request.owner_agent_id,
744 path,
745 unit,
746 expires_ms: Some(lease.expires_at_epoch_ms),
747 })
748 })
749 .collect();
750 claims.sort_by(|a, b| (&a.path, &a.unit, &a.holder).cmp(&(&b.path, &b.unit, &b.holder)));
751 ClaimsSnapshot {
752 schema: CLAIMS_SCHEMA.to_string(),
753 claims,
754 }
755}
756
757#[cfg(test)]
758mod tests {
759 use super::*;
760
761 fn lease(owner: &str, kind: AgentLeaseResourceKindV1, resource: &str) -> AgentLeaseV1 {
762 AgentLeaseV1 {
763 schema_version: AGENT_LEASE_SCHEMA_VERSION,
764 lease_ref: format!("lease:{owner}"),
765 request: AgentLeaseRequestV1 {
766 schema_version: AGENT_LEASE_SCHEMA_VERSION,
767 lease_request_ref: "lease-request:x".into(),
768 resource_kind: kind,
769 resource_ref: resource.into(),
770 owner_agent_id: owner.into(),
771 duration_ms: CLAIM_TTL_MS,
772 },
773 expires_at_epoch_ms: u64::MAX,
774 }
775 }
776
777 const RUST: &str =
778 "fn alpha() {\n let a = 1;\n a\n}\n\nfn beta() {\n let b = 2;\n b\n}\n";
779
780 fn unit(scope: &str, rel: &str, name: &str) -> String {
781 unit_resource(scope, rel, name).expect("bounded")
782 }
783
784 #[test]
785 fn second_agent_on_the_same_unit_is_warned_refused_then_clear() {
786 let dir = tempfile::tempdir().expect("tempdir");
787 let root = dir.path().to_string_lossy().into_owned();
788 let file = dir.path().join("x.rs");
789 let a = format!("agent-a-{}", std::process::id());
790 let b = format!("agent-b-{}", std::process::id());
791 let beta = RUST.replace("let b = 2;", "let b = 3;");
792 let alpha = RUST.replace("let a = 1;", "let a = 5;");
793
794 assert_eq!(
795 gate_with(ClaimMode::Warn, &root, &a, &file, RUST, &beta),
796 Gate::Clear
797 );
798 assert_eq!(
800 gate_with(ClaimMode::Warn, &root, &b, &file, RUST, &alpha),
801 Gate::Clear
802 );
803 match gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta) {
804 Gate::Refuse(text) => assert!(text.contains(&a) && text.contains("`beta`"), "{text}"),
805 other => panic!("expected a refusal, got {other:?}"),
806 }
807 match gate_with(ClaimMode::Warn, &root, &b, &file, RUST, &beta) {
808 Gate::Warn(text) => assert!(text.contains(&a), "{text}"),
809 other => panic!("expected a warning, got {other:?}"),
810 }
811 let held: Vec<(String, String)> = snapshot(&root)
812 .claims
813 .into_iter()
814 .map(|c| (c.holder, c.unit))
815 .collect();
816 assert!(held.contains(&(a.clone(), "beta".to_string())), "{held:?}");
817 assert!(held.contains(&(b.clone(), "alpha".to_string())), "{held:?}");
818
819 assert_eq!(release_agent(&a), 1);
820 assert_eq!(
821 gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta),
822 Gate::Clear
823 );
824 assert_eq!(release_agent(&b), 2);
825 assert!(snapshot(&root).claims.is_empty());
826 }
827
828 #[test]
829 fn unit_resource_round_trips_and_is_bounded() {
830 let r = unit("0123456789abcdef", "src/a b.rs", "Foo::bar");
831 assert_eq!(r, "project-unit:0123456789abcdef/src/a%20b.rs#Foo::bar");
832 assert_eq!(
833 parse_unit_resource(&r),
834 Some((
835 "0123456789abcdef".into(),
836 "src/a b.rs".into(),
837 "Foo::bar".into()
838 ))
839 );
840 assert!(unit_resource("s", &"x".repeat(300), "f").is_none());
841 assert_eq!(
842 parse_unit_resource(&unit("s", "a.rs", "a#b")).unwrap().2,
843 "a#b"
844 );
845 }
846
847 #[test]
848 fn edit_touches_only_the_innermost_changed_unit() {
849 let after = RUST.replace("let b = 2;", "let b = 3;");
850 let (names, spans) = edit_footprint("x.rs", RUST, &after);
851 assert_eq!(
852 names.into_iter().collect::<Vec<_>>(),
853 vec!["beta".to_string()]
854 );
855 assert_eq!(spans, vec![(7, 7)]);
856 }
857
858 #[test]
859 fn insertion_between_units_touches_only_the_new_unit() {
860 let after = RUST.replace("}\n\nfn beta", "}\n\nfn gamma() {}\n\nfn beta");
861 let (names, _) = edit_footprint("x.rs", RUST, &after);
862 assert_eq!(
863 names.into_iter().collect::<Vec<_>>(),
864 vec!["gamma".to_string()]
865 );
866 }
867
868 #[test]
869 fn markdown_sections_nest_and_skip_fences() {
870 let md = "# A\nx\n## B\n```\n# not\n```\ny\n# C\nz\n";
871 let spans: Vec<(String, usize, usize)> = markdown_sections(md)
872 .into_iter()
873 .map(|u| (u.name, u.start, u.end))
874 .collect();
875 assert_eq!(
876 spans,
877 vec![
878 ("A".to_string(), 1, 7),
879 ("B".to_string(), 3, 7),
880 ("C".to_string(), 8, 9)
881 ]
882 );
883 let after = md.replace("y\n", "y2\n");
884 let (names, _) = edit_footprint("doc.md", md, &after);
885 assert_eq!(names.into_iter().collect::<Vec<_>>(), vec!["B".to_string()]);
886 }
887
888 #[test]
889 fn conflicts_name_other_holders_only() {
890 let scope = "0123456789abcdef";
891 let after = RUST.replace("let b = 2;", "let b = 3;");
892 let (names, spans) = edit_footprint("x.rs", RUST, &after);
893 let symbol = AgentLeaseResourceKindV1::Symbol;
894 let leases = vec![
895 lease("me", symbol, &unit(scope, "x.rs", "beta")),
896 lease("other", symbol, &unit(scope, "x.rs", "beta")),
897 lease("third", symbol, &unit(scope, "x.rs", "alpha")),
898 lease("fourth", symbol, &unit("ffffffffffffffff", "x.rs", "beta")),
899 lease("whole", symbol, &unit(scope, "x.rs", WHOLE_FILE)),
900 ];
901 let found = conflicts_in(
902 leases,
903 "/nonexistent",
904 scope,
905 "me",
906 "x.rs",
907 RUST,
908 &names,
909 &spans,
910 );
911 let holders: Vec<(&str, &str)> = found
912 .iter()
913 .map(|c| (c.holder.as_str(), c.unit.as_str()))
914 .collect();
915 assert_eq!(holders, vec![("other", "beta"), ("whole", "*")]);
916 let text = render_conflicts(&found, true);
917 assert!(text.contains("claimed by other"), "{text}");
918 assert!(text.starts_with("ERROR"), "{text}");
919 }
920
921 #[test]
922 fn path_lease_above_the_file_conflicts() {
923 let root = "/nonexistent/claims-root";
924 let dir = crate::core::agent_lease::project_path_resource(root, "src").unwrap();
925 let leases = vec![lease("other", AgentLeaseResourceKindV1::Path, &dir)];
926 let names = BTreeSet::new();
927 let found = conflicts_in(leases.clone(), root, "s", "me", "src/x.rs", "", &names, &[]);
928 assert_eq!(found.len(), 1);
929 assert_eq!(found[0].unit, WHOLE_FILE);
930 let none = conflicts_in(leases, root, "s", "me", "srcx/x.rs", "", &names, &[]);
931 assert!(none.is_empty());
932 }
933
934 #[test]
935 fn explicit_kind_name_claim_is_seen_by_the_edit_gate() {
936 let dir = tempfile::tempdir().expect("tempdir");
937 let root = dir.path().to_string_lossy().into_owned();
938 let file = dir.path().join("x.rs");
939 let a = format!("explicit-a-{}", std::process::id());
940 let b = format!("explicit-b-{}", std::process::id());
941 let scope = repo_scope(&root);
942 let beta = RUST.replace("let b = 2;", "let b = 3;");
943 let alpha = RUST.replace("let a = 1;", "let a = 5;");
944
945 assert!(matches!(
946 claim_explicit(&scope, &a, "x.rs", "fn:beta", 5 * 60 * 1_000),
947 ExplicitClaim::Held { .. }
948 ));
949 match claim_explicit(&scope, &b, "x.rs", "fn:beta", 60_000) {
951 ExplicitClaim::HeldBy { holder, .. } => assert_eq!(holder, a),
952 other => panic!("expected HeldBy, got {other:?}"),
953 }
954 match gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta) {
955 Gate::Refuse(text) => {
956 assert!(text.contains(&a) && text.contains("fn:beta"), "{text}");
957 }
958 other => panic!("expected a refusal, got {other:?}"),
959 }
960 assert_eq!(
961 gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &alpha),
962 Gate::Clear
963 );
964 assert_eq!(release_units(&scope, &a, &[]), 1);
965 assert_eq!(
966 gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta),
967 Gate::Clear
968 );
969 assert_eq!(release_agent(&b), 2);
970 }
971
972 #[test]
976 fn explicit_claim_at_max_ttl_is_renewed_by_a_reclaim() {
977 let dir = tempfile::tempdir().expect("tempdir");
978 let root = dir.path().to_string_lossy().into_owned();
979 let scope = repo_scope(&root);
980 let a = format!("renew-a-{}", std::process::id());
981 let first = match claim_explicit(&scope, &a, "x.rs", "fn:alpha", MAX_EXPLICIT_TTL_MS) {
982 ExplicitClaim::Held { expires_ms } => expires_ms,
983 other => panic!("expected Held, got {other:?}"),
984 };
985 assert!(first <= now_ms() + MAX_EXPLICIT_TTL_MS);
986 std::thread::sleep(std::time::Duration::from_millis(1_200));
988 let renewed = match claim_explicit(&scope, &a, "x.rs", "fn:alpha", MAX_EXPLICIT_TTL_MS) {
989 ExplicitClaim::Held { expires_ms } => expires_ms,
990 other => panic!("expected the renewal to hold, got {other:?}"),
991 };
992 assert!(
993 renewed > first,
994 "re-claim at the maximum TTL renews: {renewed} <= {first}"
995 );
996 assert!(renewed + 5_000 >= now_ms() + MAX_EXPLICIT_TTL_MS);
997 let held = snapshot(&root).claims;
998 assert_eq!(held.len(), 1, "a renewal never adds a second claim");
999 assert_eq!(held[0].expires_ms, Some(renewed));
1000 assert_eq!(release_units(&scope, &a, &[]), 1);
1001 }
1002
1003 #[test]
1004 fn unit_symbol_name_strips_kinds_only_from_kind_name_units() {
1005 assert_eq!(unit_symbol_name("fn:parse"), "parse");
1006 assert_eq!(unit_symbol_name("impl:A/fn:b"), "b");
1007 assert_eq!(unit_symbol_name("impl:A"), "A");
1008 assert_eq!(unit_symbol_name("parse"), "parse");
1009 assert_eq!(unit_symbol_name("Foo::bar"), "Foo::bar");
1010 assert_eq!(unit_symbol_name("Note: x"), "Note: x");
1011 assert_eq!(unit_symbol_name(WHOLE_FILE), WHOLE_FILE);
1012 }
1013
1014 #[test]
1015 fn off_mode_and_outside_paths_are_clear() {
1016 assert_eq!(
1017 gate_with(ClaimMode::Off, "/r", "a", Path::new("/r/x.rs"), "", "x"),
1018 Gate::Clear
1019 );
1020 assert_eq!(relative_path("/r", Path::new("/elsewhere/x.rs")), None);
1021 assert_eq!(
1022 relative_path("/r", Path::new("/r/src/x.rs")).as_deref(),
1023 Some("src/x.rs")
1024 );
1025 }
1026}