Skip to main content

lean_ctx/core/
compact_directive.rs

1//! Store for the agent-driven conversation-compaction directive (#1570 P1).
2//!
3//! The MCP server cannot rewrite the client's conversation — only the proxy
4//! sees the messages. `ctx_session(action="compact")` therefore records a
5//! *directive*; the proxy applies it to every subsequent request (cache-safe,
6//! live-suffix only). Restore is lossless by construction: the client resends
7//! the full original history each turn, so clearing the directive is enough.
8
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use serde::{Deserialize, Serialize};
12
13/// A directive older than this is ignored and cleaned up.
14const TTL_SECS: u64 = 1800;
15
16/// Anti-obsession guard (#1570 P6): a fresh compact may only be created this
17/// long after the previous one.
18const MIN_INTERVAL_SECS: u64 = 300;
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct CompactDirective {
22    pub created_unix: u64,
23    /// How many trailing plain-user turns stay verbatim.
24    pub keep_recent_turns: usize,
25    /// The agent-authored summary that replaces the compacted span.
26    pub summary: String,
27    /// Fingerprint of the first message AFTER the cut, pinned on first apply
28    /// so the replaced prefix stays byte-identical while the conversation
29    /// grows (provider prompt caches keep hitting).
30    pub boundary_fingerprint: Option<String>,
31    /// CCR handle of the verbatim replaced span (defense in depth — restore
32    /// itself only needs the directive cleared).
33    pub original_handle: Option<String>,
34}
35
36fn now_unix() -> u64 {
37    SystemTime::now()
38        .duration_since(UNIX_EPOCH)
39        .map(|d| d.as_secs())
40        .unwrap_or(0)
41}
42
43fn store_path() -> Option<std::path::PathBuf> {
44    crate::core::data_dir::lean_ctx_data_dir()
45        .ok()
46        .map(|d| d.join("compact_directive.json"))
47}
48
49/// Create a new directive. Fails when one was created less than
50/// `MIN_INTERVAL_SECS` ago (rate limit — nothing is ever blocked, the agent
51/// simply keeps its current, already-compacted context).
52pub fn create(keep_recent_turns: usize, summary: String) -> Result<(), String> {
53    if let Some(existing) = load_active()
54        && now_unix().saturating_sub(existing.created_unix) < MIN_INTERVAL_SECS
55    {
56        return Err(format!(
57            "a compaction from {}s ago is still active — one compact per {}s \
58             (anti-obsession guard); use ctx_session action=\"restore\" first if needed",
59            now_unix().saturating_sub(existing.created_unix),
60            MIN_INTERVAL_SECS
61        ));
62    }
63    let directive = CompactDirective {
64        created_unix: now_unix(),
65        keep_recent_turns,
66        summary,
67        boundary_fingerprint: None,
68        original_handle: None,
69    };
70    save(&directive)
71}
72
73pub fn save(directive: &CompactDirective) -> Result<(), String> {
74    let path = store_path().ok_or_else(|| "no data dir".to_string())?;
75    let json = serde_json::to_string(directive).map_err(|e| e.to_string())?;
76    std::fs::write(path, json).map_err(|e| e.to_string())
77}
78
79/// Load the directive when it exists and is younger than `TTL_SECS`.
80pub fn load_active() -> Option<CompactDirective> {
81    let path = store_path()?;
82    let raw = std::fs::read_to_string(&path).ok()?;
83    let directive: CompactDirective = serde_json::from_str(&raw).ok()?;
84    if now_unix().saturating_sub(directive.created_unix) > TTL_SECS {
85        let _ = std::fs::remove_file(&path);
86        return None;
87    }
88    Some(directive)
89}
90
91/// Drop the directive — the client's next request carries the full original
92/// history again, so this alone is a complete, lossless restore.
93pub fn clear() -> bool {
94    store_path().is_some_and(|path| std::fs::remove_file(path).is_ok())
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn directive_roundtrip_rate_limit_and_clear() {
103        let _lock = crate::core::data_dir::test_env_lock();
104        let _dir = crate::core::data_dir::isolated_data_dir();
105        assert!(load_active().is_none());
106
107        create(6, "summary one".into()).expect("first create succeeds");
108        let d = load_active().expect("directive active");
109        assert_eq!(d.keep_recent_turns, 6);
110        assert!(d.boundary_fingerprint.is_none());
111
112        // Rate limit: a second compact right away is refused with guidance.
113        let err = create(4, "summary two".into()).expect_err("rate-limited");
114        assert!(err.contains("anti-obsession"), "{err}");
115
116        assert!(clear());
117        assert!(load_active().is_none());
118        // After clear, creating again is allowed immediately.
119        create(4, "summary three".into()).expect("create after clear");
120        clear();
121    }
122
123    #[test]
124    fn expired_directive_is_ignored_and_removed() {
125        let _lock = crate::core::data_dir::test_env_lock();
126        let _dir = crate::core::data_dir::isolated_data_dir();
127        let stale = CompactDirective {
128            created_unix: now_unix() - TTL_SECS - 10,
129            keep_recent_turns: 6,
130            summary: "old".into(),
131            boundary_fingerprint: None,
132            original_handle: None,
133        };
134        save(&stale).unwrap();
135        assert!(load_active().is_none(), "expired directive must not apply");
136        assert!(load_active().is_none());
137    }
138}