File size: 8,071 Bytes
1d29e75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPF Smart Gateway - Session State
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// In-memory session state. Persisted to LMDB on checkpoints.
// NOTE: files_read/files_written REMOVED from this struct in v3.0.1.
// Now persisted in AgentStateDb (LMDB5) to prevent heap fragmentation crashes.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;

/// Active session state — lives in RAM, flushed to LMDB periodically.
/// file tracking is now handled by AgentStateDb to prevent unbounded Vec<String> growth.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub action_count: u64,
    pub last_tool: Option<String>,
    pub last_result: Option<String>,
    pub last_file: Option<String>,
    pub started: DateTime<Utc>,
    pub last_action: Option<DateTime<Utc>>,
    pub complexity_history: Vec<ComplexityEntry>,
    pub manifest: Vec<ManifestEntry>,
    pub failures: Vec<FailureEntry>,
    /// Per-minute action timestamps for rate limiting (circular buffer)
    #[serde(default)]
    pub rate_window: Vec<DateTime<Utc>>,
    /// Recent file reads cache for Build Anchor Protocol (bounded, max 20).
    /// Full history is persisted in AgentStateDb (LMDB5).
    #[serde(default)]
    pub recent_reads: Vec<String>,
    /// Session file tracking (bounded, max 50).
    /// Persisted for LLM-visible session context. Small enough to avoid heap crash.
    #[serde(default)]
    pub files_read: VecDeque<String>,
    /// Session file tracking (bounded, max 50).
    /// Persisted for LLM-visible session context. Small enough to avoid heap crash.
    #[serde(default)]
    pub files_written: VecDeque<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityEntry {
    pub timestamp: DateTime<Utc>,
    pub tool: String,
    pub c: u64,
    pub tier: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestEntry {
    pub timestamp: DateTime<Utc>,
    pub tool: String,
    pub c: u64,
    pub action: String, // "ALLOWED" or "BLOCKED"
    pub reason: Option<String>,
    /// The actual command or file path that was executed (WH-5 audit trail)
    #[serde(default)]
    pub command: Option<String>,
    /// Extracted target paths from the command (WH-5 audit trail)
    #[serde(default)]
    pub targets: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureEntry {
    pub timestamp: DateTime<Utc>,
    pub tool: String,
    pub error: String,
}

impl Session {
    pub fn new() -> Self {
        Self {
            action_count: 0,
            last_tool: None,
            last_result: None,
            last_file: None,
            started: Utc::now(),
            last_action: None,
            complexity_history: Vec::new(),
            manifest: Vec::new(),
            failures: Vec::new(),
            rate_window: Vec::new(),
            recent_reads: Vec::new(),
            files_read: VecDeque::new(),
            files_written: VecDeque::new(),
        }
    }

    /// Track a file read for Build Anchor Protocol and session history.
    /// NOTE: bounded to prevent heap fragmentation. Full history in AgentStateDb.
    pub fn track_read(&mut self, path: &str) {
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => path.to_string(),
        };
        // Build anchor cache (max 20)
        if !self.recent_reads.contains(&canonical) {
            self.recent_reads.push(canonical.clone());
            if self.recent_reads.len() > 20 {
                self.recent_reads.remove(0);
            }
        }
        // Session history (max 50)
        if !self.files_read.contains(&canonical) {
            self.files_read.push_back(canonical);
            if self.files_read.len() > 50 {
                self.files_read.pop_front();
            }
        }
    }

    /// Track a file write
    /// NOTE: this is bounded to prevent heap fragmentation.
    /// Full history is persisted in AgentStateDb (LMDB5).
    pub fn track_write(&mut self, path: &str) {
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => path.to_string(),
        };
        if !self.files_written.contains(&canonical) {
            self.files_written.push_back(canonical);
            if self.files_written.len() > 50 {
                self.files_written.pop_front();
            }
        }
    }

    /// Record an action (called after every tool use)
    pub fn record_action(&mut self, tool: &str, result: &str, file_path: Option<&str>) {
        self.action_count += 1;
        self.last_tool = Some(tool.to_string());
        self.last_result = Some(result.to_string());
        self.last_file = file_path.map(|s| s.to_string());
        let now = Utc::now();
        self.last_action = Some(now);

        // Record timestamp for rate limiting and prune expired entries
        self.rate_window.push(now);
        let one_minute_ago = now - chrono::Duration::seconds(60);
        self.rate_window.retain(|ts| *ts > one_minute_ago);
    }

    /// Record complexity calculation
    pub fn record_complexity(&mut self, tool: &str, c: u64, tier: &str) {
        self.complexity_history.push(ComplexityEntry {
            timestamp: Utc::now(),
            tool: tool.to_string(),
            c,
            tier: tier.to_string(),
        });
        // Keep last 100 entries
        if self.complexity_history.len() > 100 {
            self.complexity_history.remove(0);
        }
    }

    /// Record manifest entry (allowed/blocked) — basic version
    /// Delegates to record_manifest_detailed with empty command/targets.
    pub fn record_manifest(&mut self, tool: &str, c: u64, action: &str, reason: Option<&str>) {
        self.record_manifest_detailed(tool, c, action, reason, None, &[]);
    }

    /// Record manifest entry with command and target audit trail (WH-5)
    /// Captures the actual command string and extracted target paths
    /// for security forensics and audit logging.
    pub fn record_manifest_detailed(
        &mut self,
        tool: &str,
        c: u64,
        action: &str,
        reason: Option<&str>,
        command: Option<&str>,
        targets: &[String],
    ) {
        self.manifest.push(ManifestEntry {
            timestamp: Utc::now(),
            tool: tool.to_string(),
            c,
            action: action.to_string(),
            reason: reason.map(|s| s.to_string()),
            command: command.map(|s| s.to_string()),
            targets: targets.to_vec(),
        });
        if self.manifest.len() > 200 {
            self.manifest.remove(0);
        }
    }

    /// Record failure
    pub fn record_failure(&mut self, tool: &str, error: &str) {
        self.failures.push(FailureEntry {
            timestamp: Utc::now(),
            tool: tool.to_string(),
            error: error.to_string(),
        });
        if self.failures.len() > 50 {
            self.failures.remove(0);
        }
    }

    /// Build Anchor ratio: reads / writes
    /// NOTE: counts now come from AgentStateDb, not in-memory Vecs.
    pub fn anchor_ratio(&self, file_read_count: usize, file_write_count: usize) -> String {
        if file_write_count == 0 {
            "N/A (no writes)".to_string()
        } else {
            format!("{}/{}", file_read_count, file_write_count)
        }
    }

    /// Status summary string
    /// NOTE: counts now come from AgentStateDb, not in-memory Vecs.
    pub fn status_summary(&self, file_read_count: usize, file_write_count: usize) -> String {
        format!(
            "Actions: {} | Reads: {} | Writes: {} | Last: {} | Anchor: {}",
            self.action_count,
            file_read_count,
            file_write_count,
            self.last_tool.as_deref().unwrap_or("none"),
            self.anchor_ratio(file_read_count, file_write_count),
        )
    }

}

impl Default for Session {
    fn default() -> Self {
        Self::new()
    }
}