Skip to main content

lean_ctx_ext/core/
unit_claims.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Unit claims: which agent is editing which function or section of a file.
3//!
4//! The edit tools take a short claim on the innermost units (function,
5//! method, type, markdown section) an edit touches, and check the claims of
6//! other agents before they write. Another agent's claim on a touched unit
7//! is a conflict: by default the edit goes ahead with a warning naming the
8//! holder (`warn`); `LEAN_CTX_CLAIM_MODE=strict` refuses it; `off` disables
9//! both the check and the claims.
10//!
11//! Claims are ordinary machine-wide leases ([`crate::core::agent_lease`]) of
12//! kind `Symbol` with a readable reference
13//! `project-unit:<repo>/<path>#<unit>`, so stores and processes that predate
14//! unit claims read them unchanged. `<repo>` names the repository, not the
15//! checkout: linked worktrees of one repository share it, so two agents in
16//! two worktrees meet on the same unit. A claim lives ten minutes from the
17//! last edit that touched the unit and is released when its agent finishes.
18//!
19//! Agents can also claim units before they edit (`ctx_agent action=claim
20//! units=[path|path#kind:name]`, [`claim_explicit`]): the same leases, with
21//! the unit spelled `kind:name` (`fn:parse`, `impl:A/fn:b`) or `*` for the
22//! whole file, and a caller-chosen TTL. The gate matches such a unit by its
23//! innermost symbol name ([`unit_symbol_name`]), so an explicit claim on
24//! `fn:parse` warns (or refuses) another agent's edit of `parse`.
25//!
26//! This module detects, reports and hints only. Planning a task against the
27//! claims is an optional external planner's job (`weave plan-claims`), fed
28//! the [`snapshot`] in the `leanctx.claims.v1` contract.
29
30use 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
41/// Lease reference scheme of a unit claim.
42pub const UNIT_SCHEME: &str = "project-unit:";
43/// Unit name of a whole-file claim.
44pub const WHOLE_FILE: &str = "*";
45/// How long a claim lives after the last edit that touched its unit.
46pub const CLAIM_TTL_MS: u64 = 10 * 60 * 1_000;
47/// Schema of the snapshot handed to an external planner.
48pub const CLAIMS_SCHEMA: &str = "leanctx.claims.v1";
49const MAX_REF_BYTES: usize = 256;
50
51/// What the edit tools do with another agent's claim on a touched unit.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum ClaimMode {
54    Off,
55    Warn,
56    Strict,
57}
58
59/// `LEAN_CTX_CLAIM_MODE` (`off`, `warn`, `strict`); `warn` when unset or unknown.
60#[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// ─── Resources ───────────────────────────────────────────────────────────────
75
76/// Repository scope of `project_root`: its project identity (a linked
77/// worktree follows its main checkout's origin), else the checkout itself.
78#[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/// Lease reference of unit `unit` of the repository-relative file `rel`;
113/// `None` when it would exceed the lease reference bound.
114#[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/// `(scope, rel, unit)` of a unit claim reference.
124#[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/// Repository-relative spelling of `path` under `project_root` (`/` separated).
133#[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// ─── Units of a file ─────────────────────────────────────────────────────────
153
154/// One named unit of a file: 1-based inclusive line span.
155#[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/// Named units of `content` (the file `path`): markdown sections, else the
198/// spans of the signatures tree-sitter (or the regex fallback) finds.
199#[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    // Uncounted: a claim check must not write grammar telemetry per edit.
210    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/// Line spans an edit touches, on each side: `(old, new)`, 1-based inclusive.
226/// A pure insertion before line `L` is the empty span `(L, L - 1)`.
227#[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        // Insertion between lines `start - 1` and `start`: inside only when
246        // both neighbours are.
247        unit.start < start && start <= unit.end
248    } else {
249        unit.start <= end && start <= unit.end
250    }
251}
252
253/// Innermost units each span touches (a span that touches none adds nothing).
254#[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/// What an edit of `path` from `before` to `after` touches: the innermost
275/// unit names on either side, and the old-side spans.
276#[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// ─── Conflicts ───────────────────────────────────────────────────────────────
289
290/// Another agent's claim on something an edit touches.
291#[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/// Claims of other agents that an edit of `rel` touching `names` (and the
307/// old-side `spans` of `before`) collides with: unit claims on the same
308/// unit, on a unit containing a touched line, or on the whole file, and
309/// path leases on the file or a directory above it.
310#[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                // An explicit `kind:name` claim meets the edit by its symbol name.
336                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/// One line per conflict for the agent, naming holder, unit and what to do.
384#[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
414// ─── Claiming and releasing ──────────────────────────────────────────────────
415
416fn 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
430/// Longest explicit claim: the lease store's maximum lease duration.
431pub const MAX_EXPLICIT_TTL_MS: u64 = 60 * 60 * 1_000;
432
433/// Symbol name an edit reports for a claimed unit. Explicit claims
434/// (`ctx_agent action=claim units=[path#kind:name]`) store `kind:name`, nested
435/// with `/` (`fn:parse`, `impl:A/fn:b`); they name their innermost symbol
436/// (`parse`, `b`). Every other unit (the names edits claim, `*`) is its own name.
437#[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/// Result of an explicit claim of one unit.
459#[derive(Clone, Debug, PartialEq, Eq)]
460pub enum ExplicitClaim {
461    /// Held by the caller until this epoch ms.
462    Held { expires_ms: u64 },
463    /// Another agent holds the unit (or it is reserved for an agent waiting
464    /// on it); nothing was recorded for the caller.
465    HeldBy { holder: String, expires_ms: u64 },
466    /// Not claimable (reference too long, store unavailable).
467    Failed(String),
468}
469
470/// Claims unit `unit` (`*`, or the `kind:name` spelling of an explicit claim)
471/// of `rel` for `agent_id` for `ttl_ms` (at most [`MAX_EXPLICIT_TTL_MS`]),
472/// in the same lease store the edit tools claim in, so the edit gate of every
473/// other agent sees it. Claiming a unit the caller already holds renews it
474/// to `ttl_ms` from now.
475pub 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    // The same symbol under its other spelling (`fn:parse` against the
489    // edit-made `parse`) is the same unit: one holder per unit.
490    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            // A fresh grant already runs `ttl_ms`; an existing one is renewed.
496            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
525/// Another agent's live claim on `unit` of `rel` under a different spelling
526/// of the same symbol: a kinded unit (`fn:parse`) against a bare edit-made
527/// name (`parse`) or the reverse. Two kinded units (`fn:parse`,
528/// `struct:parse`) stay distinct; the exact spelling is the lease store's.
529fn 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
557/// Releases `agent_id`'s unit claims in repository `scope` (explicit and
558/// edit-made alike): those on the `(rel, unit)` pairs named, or all of them
559/// when `units` is empty. Returns how many.
560pub 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
586/// Claims `units` of `rel` for `agent_id` (or extends its own claims to a
587/// full TTL). Units another agent holds are skipped. Returns the units now
588/// held.
589pub 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
618/// Releases every unit claim `agent_id` holds. Returns how many.
619pub 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// ─── The edit gate ───────────────────────────────────────────────────────────
643
644/// Outcome of [`gate`].
645#[derive(Clone, Debug, PartialEq, Eq)]
646pub enum Gate {
647    /// Nothing held by another agent (or claims are off).
648    Clear,
649    /// Write, then show this warning.
650    Warn(String),
651    /// Do not write; this is the error.
652    Refuse(String),
653}
654
655/// Checks an edit of `path` by `agent_id` against other agents' claims and,
656/// unless refused, claims the units it touches.
657#[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/// [`gate`] with an explicit mode.
663#[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// ─── Snapshot for planners ───────────────────────────────────────────────────
703
704/// One claim of the `leanctx.claims.v1` snapshot.
705#[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/// The `leanctx.claims.v1` snapshot.
714#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
715pub struct ClaimsSnapshot {
716    pub schema: String,
717    pub claims: Vec<ClaimEntry>,
718}
719
720/// Active unit claims and path leases of the repository at `project_root`.
721#[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        // The lease store lives in the data dir: hold an isolated one, which
787        // also takes the test env lock, so no other test swaps it mid-test.
788        let _data = crate::core::data_dir::isolated_data_dir();
789        let dir = tempfile::tempdir().expect("tempdir");
790        let root = dir.path().to_string_lossy().into_owned();
791        let file = dir.path().join("x.rs");
792        let a = format!("agent-a-{}", std::process::id());
793        let b = format!("agent-b-{}", std::process::id());
794        let beta = RUST.replace("let b = 2;", "let b = 3;");
795        let alpha = RUST.replace("let a = 1;", "let a = 5;");
796
797        assert_eq!(
798            gate_with(ClaimMode::Warn, &root, &a, &file, RUST, &beta),
799            Gate::Clear
800        );
801        // Another unit of the same file: no conflict.
802        assert_eq!(
803            gate_with(ClaimMode::Warn, &root, &b, &file, RUST, &alpha),
804            Gate::Clear
805        );
806        match gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta) {
807            Gate::Refuse(text) => assert!(text.contains(&a) && text.contains("`beta`"), "{text}"),
808            other => panic!("expected a refusal, got {other:?}"),
809        }
810        match gate_with(ClaimMode::Warn, &root, &b, &file, RUST, &beta) {
811            Gate::Warn(text) => assert!(text.contains(&a), "{text}"),
812            other => panic!("expected a warning, got {other:?}"),
813        }
814        let held: Vec<(String, String)> = snapshot(&root)
815            .claims
816            .into_iter()
817            .map(|c| (c.holder, c.unit))
818            .collect();
819        assert!(held.contains(&(a.clone(), "beta".to_string())), "{held:?}");
820        assert!(held.contains(&(b.clone(), "alpha".to_string())), "{held:?}");
821
822        assert_eq!(release_agent(&a), 1);
823        assert_eq!(
824            gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta),
825            Gate::Clear
826        );
827        assert_eq!(release_agent(&b), 2);
828        assert!(snapshot(&root).claims.is_empty());
829    }
830
831    #[test]
832    fn unit_resource_round_trips_and_is_bounded() {
833        let r = unit("0123456789abcdef", "src/a b.rs", "Foo::bar");
834        assert_eq!(r, "project-unit:0123456789abcdef/src/a%20b.rs#Foo::bar");
835        assert_eq!(
836            parse_unit_resource(&r),
837            Some((
838                "0123456789abcdef".into(),
839                "src/a b.rs".into(),
840                "Foo::bar".into()
841            ))
842        );
843        assert!(unit_resource("s", &"x".repeat(300), "f").is_none());
844        assert_eq!(
845            parse_unit_resource(&unit("s", "a.rs", "a#b")).unwrap().2,
846            "a#b"
847        );
848    }
849
850    #[test]
851    fn edit_touches_only_the_innermost_changed_unit() {
852        let after = RUST.replace("let b = 2;", "let b = 3;");
853        let (names, spans) = edit_footprint("x.rs", RUST, &after);
854        assert_eq!(
855            names.into_iter().collect::<Vec<_>>(),
856            vec!["beta".to_string()]
857        );
858        assert_eq!(spans, vec![(7, 7)]);
859    }
860
861    #[test]
862    fn insertion_between_units_touches_only_the_new_unit() {
863        let after = RUST.replace("}\n\nfn beta", "}\n\nfn gamma() {}\n\nfn beta");
864        let (names, _) = edit_footprint("x.rs", RUST, &after);
865        assert_eq!(
866            names.into_iter().collect::<Vec<_>>(),
867            vec!["gamma".to_string()]
868        );
869    }
870
871    #[test]
872    fn markdown_sections_nest_and_skip_fences() {
873        let md = "# A\nx\n## B\n```\n# not\n```\ny\n# C\nz\n";
874        let spans: Vec<(String, usize, usize)> = markdown_sections(md)
875            .into_iter()
876            .map(|u| (u.name, u.start, u.end))
877            .collect();
878        assert_eq!(
879            spans,
880            vec![
881                ("A".to_string(), 1, 7),
882                ("B".to_string(), 3, 7),
883                ("C".to_string(), 8, 9)
884            ]
885        );
886        let after = md.replace("y\n", "y2\n");
887        let (names, _) = edit_footprint("doc.md", md, &after);
888        assert_eq!(names.into_iter().collect::<Vec<_>>(), vec!["B".to_string()]);
889    }
890
891    #[test]
892    fn conflicts_name_other_holders_only() {
893        let scope = "0123456789abcdef";
894        let after = RUST.replace("let b = 2;", "let b = 3;");
895        let (names, spans) = edit_footprint("x.rs", RUST, &after);
896        let symbol = AgentLeaseResourceKindV1::Symbol;
897        let leases = vec![
898            lease("me", symbol, &unit(scope, "x.rs", "beta")),
899            lease("other", symbol, &unit(scope, "x.rs", "beta")),
900            lease("third", symbol, &unit(scope, "x.rs", "alpha")),
901            lease("fourth", symbol, &unit("ffffffffffffffff", "x.rs", "beta")),
902            lease("whole", symbol, &unit(scope, "x.rs", WHOLE_FILE)),
903        ];
904        let found = conflicts_in(
905            leases,
906            "/nonexistent",
907            scope,
908            "me",
909            "x.rs",
910            RUST,
911            &names,
912            &spans,
913        );
914        let holders: Vec<(&str, &str)> = found
915            .iter()
916            .map(|c| (c.holder.as_str(), c.unit.as_str()))
917            .collect();
918        assert_eq!(holders, vec![("other", "beta"), ("whole", "*")]);
919        let text = render_conflicts(&found, true);
920        assert!(text.contains("claimed by other"), "{text}");
921        assert!(text.starts_with("ERROR"), "{text}");
922    }
923
924    #[test]
925    fn path_lease_above_the_file_conflicts() {
926        let root = "/nonexistent/claims-root";
927        let dir = crate::core::agent_lease::project_path_resource(root, "src").unwrap();
928        let leases = vec![lease("other", AgentLeaseResourceKindV1::Path, &dir)];
929        let names = BTreeSet::new();
930        let found = conflicts_in(leases.clone(), root, "s", "me", "src/x.rs", "", &names, &[]);
931        assert_eq!(found.len(), 1);
932        assert_eq!(found[0].unit, WHOLE_FILE);
933        let none = conflicts_in(leases, root, "s", "me", "srcx/x.rs", "", &names, &[]);
934        assert!(none.is_empty());
935    }
936
937    #[test]
938    fn explicit_kind_name_claim_is_seen_by_the_edit_gate() {
939        // The lease store lives in the data dir: hold an isolated one, which
940        // also takes the test env lock, so no other test swaps it mid-test.
941        let _data = crate::core::data_dir::isolated_data_dir();
942        let dir = tempfile::tempdir().expect("tempdir");
943        let root = dir.path().to_string_lossy().into_owned();
944        let file = dir.path().join("x.rs");
945        let a = format!("explicit-a-{}", std::process::id());
946        let b = format!("explicit-b-{}", std::process::id());
947        let scope = repo_scope(&root);
948        let beta = RUST.replace("let b = 2;", "let b = 3;");
949        let alpha = RUST.replace("let a = 1;", "let a = 5;");
950
951        assert!(matches!(
952            claim_explicit(&scope, &a, "x.rs", "fn:beta", 5 * 60 * 1_000),
953            ExplicitClaim::Held { .. }
954        ));
955        // The second agent cannot take the same unit; it is told who holds it.
956        match claim_explicit(&scope, &b, "x.rs", "fn:beta", 60_000) {
957            ExplicitClaim::HeldBy { holder, .. } => assert_eq!(holder, a),
958            other => panic!("expected HeldBy, got {other:?}"),
959        }
960        match gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta) {
961            Gate::Refuse(text) => {
962                assert!(text.contains(&a) && text.contains("fn:beta"), "{text}");
963            }
964            other => panic!("expected a refusal, got {other:?}"),
965        }
966        assert_eq!(
967            gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &alpha),
968            Gate::Clear
969        );
970        assert_eq!(release_units(&scope, &a, &[]), 1);
971        assert_eq!(
972            gate_with(ClaimMode::Strict, &root, &b, &file, RUST, &beta),
973            Gate::Clear
974        );
975        assert_eq!(release_agent(&b), 2);
976    }
977
978    /// A long session keeps its claim: re-claiming at the maximum TTL renews
979    /// the claim the agent already holds to the full TTL from now, without a
980    /// second lease and without handing the unit to anyone else.
981    #[test]
982    fn explicit_claim_at_max_ttl_is_renewed_by_a_reclaim() {
983        // The lease store lives in the data dir: hold an isolated one, which
984        // also takes the test env lock, so no other test swaps it mid-test.
985        let _data = crate::core::data_dir::isolated_data_dir();
986        let dir = tempfile::tempdir().expect("tempdir");
987        let root = dir.path().to_string_lossy().into_owned();
988        let scope = repo_scope(&root);
989        let a = format!("renew-a-{}", std::process::id());
990        let first = match claim_explicit(&scope, &a, "x.rs", "fn:alpha", MAX_EXPLICIT_TTL_MS) {
991            ExplicitClaim::Held { expires_ms } => expires_ms,
992            other => panic!("expected Held, got {other:?}"),
993        };
994        assert!(first <= now_ms() + MAX_EXPLICIT_TTL_MS);
995        // Past the renewal slack of one second.
996        std::thread::sleep(std::time::Duration::from_millis(1_200));
997        let renewed = match claim_explicit(&scope, &a, "x.rs", "fn:alpha", MAX_EXPLICIT_TTL_MS) {
998            ExplicitClaim::Held { expires_ms } => expires_ms,
999            other => panic!("expected the renewal to hold, got {other:?}"),
1000        };
1001        assert!(
1002            renewed > first,
1003            "re-claim at the maximum TTL renews: {renewed} <= {first}"
1004        );
1005        assert!(renewed + 5_000 >= now_ms() + MAX_EXPLICIT_TTL_MS);
1006        let held = snapshot(&root).claims;
1007        assert_eq!(held.len(), 1, "a renewal never adds a second claim");
1008        assert_eq!(held[0].expires_ms, Some(renewed));
1009        assert_eq!(release_units(&scope, &a, &[]), 1);
1010    }
1011
1012    #[test]
1013    fn unit_symbol_name_strips_kinds_only_from_kind_name_units() {
1014        assert_eq!(unit_symbol_name("fn:parse"), "parse");
1015        assert_eq!(unit_symbol_name("impl:A/fn:b"), "b");
1016        assert_eq!(unit_symbol_name("impl:A"), "A");
1017        assert_eq!(unit_symbol_name("parse"), "parse");
1018        assert_eq!(unit_symbol_name("Foo::bar"), "Foo::bar");
1019        assert_eq!(unit_symbol_name("Note: x"), "Note: x");
1020        assert_eq!(unit_symbol_name(WHOLE_FILE), WHOLE_FILE);
1021    }
1022
1023    #[test]
1024    fn off_mode_and_outside_paths_are_clear() {
1025        assert_eq!(
1026            gate_with(ClaimMode::Off, "/r", "a", Path::new("/r/x.rs"), "", "x"),
1027            Gate::Clear
1028        );
1029        assert_eq!(relative_path("/r", Path::new("/elsewhere/x.rs")), None);
1030        assert_eq!(
1031            relative_path("/r", Path::new("/r/src/x.rs")).as_deref(),
1032            Some("src/x.rs")
1033        );
1034    }
1035}