lean-ctx 3.9.18

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Stigmergic scent field for zero-token multi-agent coordination (#540, EFF-3).
//!
//! Agents coordinate indirectly through a shared, time-decaying field of
//! "scent" deposits instead of reading each other's scratchpad messages
//! (Many Tems: 3.4x fewer coordination tokens; Pressure Fields 2601.08129:
//! temporal decay prevents premature convergence). Deposits happen as side
//! effects of normal work — reads, bounces, claims, handoffs — and the `sync`
//! view is pure arithmetic over the field: no LLM calls, no message reads.
//!
//! Storage: one JSON file under `data_dir/agents/scent_field.json`, guarded by
//! the same create-new file lock the agent registry uses. Decayed entries are
//! garbage-collected lazily on every locked operation — no daemon, no timer.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Scents below this effective intensity are dead and get collected.
const GC_THRESHOLD: f64 = 0.05;
/// Superposed intensity per (agent, kind, target) is capped here.
const INTENSITY_CAP: f64 = 3.0;
/// A foreign claim is considered active at or above this effective intensity.
pub(crate) const CLAIM_ACTIVE_THRESHOLD: f64 = 0.3;
/// Max rendered lines in the sync view.
const SYNC_TOP_K: usize = 15;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ScentKind {
    /// Agent is actively working on this target (file, task, deploy unit).
    Claimed,
    /// Agent finished something related to the target.
    Done,
    /// Agent hit a wall here (edit failures, bounces).
    Stuck,
    /// Target is being read/touched a lot right now.
    Hot,
    /// Target should not be touched (e.g. broken generated file).
    Avoid,
}

impl ScentKind {
    /// Exponential-decay half-life per kind, in seconds.
    fn half_life_secs(self) -> f64 {
        match self {
            ScentKind::Claimed | ScentKind::Hot => 600.0,
            ScentKind::Stuck => 1800.0,
            ScentKind::Done | ScentKind::Avoid => 3600.0,
        }
    }

    pub(crate) fn as_str(self) -> &'static str {
        match self {
            ScentKind::Claimed => "CLAIMED",
            ScentKind::Done => "DONE",
            ScentKind::Stuck => "STUCK",
            ScentKind::Hot => "HOT",
            ScentKind::Avoid => "AVOID",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Scent {
    pub agent_id: String,
    pub kind: ScentKind,
    /// Normalized target: relative file path, task label, or deploy unit.
    pub target: String,
    /// Deposited (pre-decay) intensity.
    pub intensity: f64,
    /// Unix seconds at deposit time.
    pub deposited_at: u64,
}

impl Scent {
    pub(crate) fn effective_intensity(&self, now: u64) -> f64 {
        let dt = now.saturating_sub(self.deposited_at) as f64;
        self.intensity * (-(std::f64::consts::LN_2) * dt / self.kind.half_life_secs()).exp()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub(crate) struct ScentField {
    pub scents: Vec<Scent>,
    pub schema_version: u32,
    /// Lifetime count of rejected claims (#549): every rejection is a piece
    /// of duplicate work the field prevented — the efficacy currency of #540.
    #[serde(default)]
    pub claims_rejected: u64,
}

fn field_path() -> Result<PathBuf, String> {
    let dir = crate::core::data_dir::lean_ctx_data_dir()?.join("agents");
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    Ok(dir.join("scent_field.json"))
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// Scent-field identity (#547). `agent_identity::current_agent_id` falls back
/// to a shared `"local"` for every unconfigured process, which would make
/// claims between two parallel MCP servers on the same machine invisible to
/// each other (`foreign_claim` filters on `agent_id != self`). For scents we
/// disambiguate with the PID; ledger/heatmap attribution keeps using the
/// stable shared identity and is intentionally NOT changed.
#[must_use]
pub(crate) fn scent_agent_id() -> &'static str {
    static CACHE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    CACHE.get_or_init(|| {
        let base = crate::core::agent_identity::current_agent_id();
        if base == "local" {
            format!("local-{}", std::process::id())
        } else {
            base.to_string()
        }
    })
}

impl ScentField {
    fn load_unlocked(path: &PathBuf) -> Self {
        if let Ok(content) = std::fs::read_to_string(path)
            && let Ok(f) = serde_json::from_str::<ScentField>(&content)
        {
            return f;
        }
        ScentField {
            schema_version: 1,
            ..Default::default()
        }
    }

    fn save_unlocked(&self, path: &PathBuf) -> Result<(), String> {
        let json = serde_json::to_string(self).map_err(|e| e.to_string())?;
        std::fs::write(path, json).map_err(|e| e.to_string())
    }

    /// Drop scents whose effective intensity fell below the GC threshold.
    pub(crate) fn gc(&mut self, now: u64) {
        self.scents
            .retain(|s| s.effective_intensity(now) >= GC_THRESHOLD);
    }

    /// Superpose a deposit: same (agent, kind, target) folds into one scent
    /// with summed effective intensity (capped), fresh timestamp.
    pub(crate) fn deposit(
        &mut self,
        agent_id: &str,
        kind: ScentKind,
        target: &str,
        intensity: f64,
        now: u64,
    ) {
        self.gc(now);
        let target = target.trim();
        if target.is_empty() || agent_id.is_empty() {
            return;
        }
        if let Some(existing) = self
            .scents
            .iter_mut()
            .find(|s| s.agent_id == agent_id && s.kind == kind && s.target == target)
        {
            let carried = existing.effective_intensity(now);
            existing.intensity = (carried + intensity).min(INTENSITY_CAP);
            existing.deposited_at = now;
        } else {
            self.scents.push(Scent {
                agent_id: agent_id.to_string(),
                kind,
                target: target.to_string(),
                intensity: intensity.min(INTENSITY_CAP),
                deposited_at: now,
            });
        }
    }

    /// Active foreign claim on `target`, if any: returns (agent_id, age_secs).
    pub(crate) fn foreign_claim(
        &self,
        target: &str,
        self_agent: &str,
        now: u64,
    ) -> Option<(String, u64)> {
        self.scents
            .iter()
            .filter(|s| {
                s.kind == ScentKind::Claimed
                    && s.target == target
                    && s.agent_id != self_agent
                    && s.effective_intensity(now) >= CLAIM_ACTIVE_THRESHOLD
            })
            .max_by(|a, b| {
                a.effective_intensity(now)
                    .partial_cmp(&b.effective_intensity(now))
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|s| (s.agent_id.clone(), now.saturating_sub(s.deposited_at)))
    }

    /// Arithmetic sync view: targets grouped, intensities superposed across
    /// agents, sorted by total intensity, capped at SYNC_TOP_K lines.
    pub(crate) fn render_sync(&self, now: u64) -> String {
        use std::collections::HashMap;
        // (kind, target) -> (total intensity, agents)
        type SyncKey<'a> = (ScentKind, &'a str);
        type SyncAgg<'a> = (f64, Vec<&'a str>);
        let mut groups: HashMap<SyncKey<'_>, SyncAgg<'_>> = HashMap::new();
        for s in &self.scents {
            let eff = s.effective_intensity(now);
            if eff < GC_THRESHOLD {
                continue;
            }
            let entry = groups.entry((s.kind, s.target.as_str())).or_default();
            entry.0 += eff;
            if !entry.1.contains(&s.agent_id.as_str()) {
                entry.1.push(s.agent_id.as_str());
            }
        }
        if groups.is_empty() {
            return String::new();
        }
        let mut rows: Vec<(SyncKey<'_>, SyncAgg<'_>)> = groups.into_iter().collect();
        rows.sort_by(|a, b| {
            b.1.0
                .partial_cmp(&a.1.0)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.0.1.cmp(b.0.1))
        });

        let mut out = String::from("Scent field (decaying, zero-token coordination):\n");
        for ((kind, target), (total, agents)) in rows.iter().take(SYNC_TOP_K) {
            let who = if agents.len() == 1 {
                agents[0].to_string()
            } else {
                format!("{} agents", agents.len())
            };
            out.push_str(&format!(
                "  {} {} ({:.1}) by {}\n",
                kind.as_str(),
                target,
                total,
                who
            ));
        }
        let extra = rows.len().saturating_sub(SYNC_TOP_K);
        if extra > 0 {
            out.push_str(&format!("  … {extra} weaker scent(s) below cutoff\n"));
        }
        out
    }
}

/// Locked load-modify-save against the shared field file.
fn with_field<R>(f: impl FnOnce(&mut ScentField, u64) -> R) -> Result<R, String> {
    let path = field_path()?;
    let lock_path = path.with_extension("json.lock");
    let _lock = crate::core::agents::FileLock::acquire(&lock_path)?;
    let mut field = ScentField::load_unlocked(&path);
    let now = now_secs();
    let result = f(&mut field, now);
    field.gc(now);
    field.save_unlocked(&path)?;
    Ok(result)
}

/// Deposit a scent as a side effect of normal work. Errors are swallowed —
/// coordination hints must never break the primary operation.
pub(crate) fn deposit(agent_id: &str, kind: ScentKind, target: &str, intensity: f64) {
    let _ = with_field(|field, now| field.deposit(agent_id, kind, target, intensity, now));
}

/// Atomic claim: fails with the holder's id if another agent's claim is still
/// active, otherwise deposits a strong Claimed scent for `agent_id`.
pub(crate) fn claim(agent_id: &str, target: &str) -> Result<(), String> {
    with_field(|field, now| {
        if let Some((holder, age)) = field.foreign_claim(target, agent_id, now) {
            field.claims_rejected += 1;
            return Err(format!(
                "already claimed by {holder} ({}m ago, still active)",
                age / 60
            ));
        }
        field.deposit(agent_id, ScentKind::Claimed, target, 2.0, now);
        Ok(())
    })?
}

/// Lifetime rejected-claim counter (#549): duplicate work prevented.
pub(crate) fn claims_rejected_total() -> u64 {
    field_path().map_or(0, |p| ScentField::load_unlocked(&p).claims_rejected)
}

/// Read-only view of currently effective scents for the dashboard (#548):
/// `(scent, effective_intensity_now)`, strongest first. Lock-free read —
/// a slightly stale view is fine for display.
pub(crate) fn active_scents() -> Vec<(Scent, f64)> {
    let Ok(path) = field_path() else {
        return Vec::new();
    };
    let field = ScentField::load_unlocked(&path);
    let now = now_secs();
    let mut v: Vec<(Scent, f64)> = field
        .scents
        .into_iter()
        .filter_map(|s| {
            let eff = s.effective_intensity(now);
            (eff >= GC_THRESHOLD).then_some((s, eff))
        })
        .collect();
    v.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
    v
}

/// Release a claim (and any Hot scent) on `target` held by `agent_id`.
pub(crate) fn release(agent_id: &str, target: &str) {
    let _ = with_field(|field, now| {
        field.scents.retain(|s| {
            !(s.agent_id == agent_id && s.target == target && s.kind == ScentKind::Claimed)
        });
        field.gc(now);
    });
}

/// One-line hint for ctx_read when someone else actively claimed this path.
/// Costs ~10 tokens and prevents duplicate work.
pub(crate) fn read_hint(path: &str, self_agent: &str) -> Option<String> {
    let field_file = field_path().ok()?;
    // Read-only fast path: no lock needed for a hint; stale reads are fine.
    let field = ScentField::load_unlocked(&field_file);
    let now = now_secs();
    let rel = crate::core::pathutil::normalize_tool_path(path);
    let (holder, age) = field.foreign_claim(&rel, self_agent, now)?;
    Some(format!("[scent: claimed by {holder} {}m ago]", age / 60))
}

/// Arithmetic sync block for ctx_agent sync.
pub(crate) fn sync_block() -> String {
    let Ok(path) = field_path() else {
        return String::new();
    };
    let field = ScentField::load_unlocked(&path);
    field.render_sync(now_secs())
}

#[cfg(test)]
mod tests {
    use super::*;

    const NOW: u64 = 1_780_000_000;

    #[test]
    fn decay_halves_at_half_life() {
        let s = Scent {
            agent_id: "a1".into(),
            kind: ScentKind::Hot,
            target: "src/x.rs".into(),
            intensity: 1.0,
            deposited_at: NOW,
        };
        let eff = s.effective_intensity(NOW + 600);
        assert!((eff - 0.5).abs() < 0.01, "half-life decay, got {eff}");
        // After two half-lives < 0.3 (ticket acceptance).
        assert!(s.effective_intensity(NOW + 1200) < 0.3);
    }

    #[test]
    fn superposition_caps_intensity() {
        let mut f = ScentField::default();
        for _ in 0..20 {
            f.deposit("a1", ScentKind::Hot, "src/x.rs", 0.3, NOW);
        }
        assert_eq!(f.scents.len(), 1);
        assert!(f.scents[0].intensity <= INTENSITY_CAP + f64::EPSILON);
    }

    #[test]
    fn gc_drops_dead_scents() {
        let mut f = ScentField::default();
        f.deposit("a1", ScentKind::Hot, "src/x.rs", 0.3, NOW);
        f.gc(NOW + 6 * 600); // six half-lives: 0.3 -> ~0.0047
        assert!(f.scents.is_empty());
    }

    #[test]
    fn foreign_claim_detected_and_own_ignored() {
        let mut f = ScentField::default();
        f.deposit("a1", ScentKind::Claimed, "src/x.rs", 2.0, NOW);
        assert!(f.foreign_claim("src/x.rs", "a2", NOW + 60).is_some());
        assert!(f.foreign_claim("src/x.rs", "a1", NOW + 60).is_none());
        // Expired claim no longer blocks.
        assert!(f.foreign_claim("src/x.rs", "a2", NOW + 3 * 600).is_none());
    }

    #[test]
    fn sync_view_caps_lines_and_superposes() {
        let mut f = ScentField::default();
        for i in 0..50 {
            f.deposit("a1", ScentKind::Hot, &format!("src/f{i}.rs"), 0.5, NOW);
        }
        f.deposit("a2", ScentKind::Hot, "src/f0.rs", 0.5, NOW);
        let view = f.render_sync(NOW);
        let lines: Vec<&str> = view.lines().collect();
        assert!(
            lines.len() <= SYNC_TOP_K + 2,
            "header + topk + overflow, got {}",
            lines.len()
        );
        assert!(view.contains("2 agents"), "superposed line: {view}");
        assert!(view.contains("weaker scent"));
    }

    #[test]
    fn empty_field_renders_empty() {
        let f = ScentField::default();
        assert!(f.render_sync(NOW).is_empty());
    }

    #[test]
    fn scent_identity_disambiguates_unconfigured_processes() {
        let id = scent_agent_id();
        let base = crate::core::agent_identity::current_agent_id();
        if base == "local" {
            // #547: two parallel unconfigured processes must not collide.
            assert_eq!(id, format!("local-{}", std::process::id()));
        } else {
            // Explicitly configured identity is kept verbatim.
            assert_eq!(id, base);
        }
        // Claims between distinct PIDs are mutually foreign.
        let mut f = ScentField::default();
        f.deposit("local-1111", ScentKind::Claimed, "src/x.rs", 2.0, NOW);
        assert!(
            f.foreign_claim("src/x.rs", "local-2222", NOW + 30)
                .is_some()
        );
    }
}