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
// === crates/m1nd-mcp/src/session.rs ===
use crate::brand;
use m1nd_core::counterfactual::CounterfactualEngine;
use m1nd_core::domain::DomainConfig;
use m1nd_core::error::M1ndResult;
use m1nd_core::graph::{Graph, SharedGraph};
use m1nd_core::plasticity::PlasticityEngine;
use m1nd_core::query::QueryOrchestrator;
use m1nd_core::resonance::ResonanceEngine;
use m1nd_core::temporal::TemporalEngine;
use m1nd_core::topology::TopologyAnalyzer;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use crate::perspective::state::{
LockState, PeekSecurityConfig, PerspectiveLimits, PerspectiveState, WatchTrigger, WatcherEvent,
};
// ---------------------------------------------------------------------------
// AgentSession — per-agent session tracking
// ---------------------------------------------------------------------------
/// Lightweight session record for a connected agent.
pub struct AgentSession {
pub agent_id: String,
pub first_seen: Instant,
pub last_seen: Instant,
pub query_count: u64,
}
// ---------------------------------------------------------------------------
// SessionState — all server state in one place
// Replaces: 03-MCP Section 1.1 server internal state
// ---------------------------------------------------------------------------
/// Server session state. Owns the graph and all engine instances.
/// Single instance shared across all agent connections.
pub struct SessionState {
/// Shared graph with RwLock for concurrent read access.
pub graph: SharedGraph,
/// Domain configuration (code, music, generic, etc.)
pub domain: DomainConfig,
/// Query orchestrator (owns HybridEngine, XLR, Semantic, etc.)
pub orchestrator: QueryOrchestrator,
/// Temporal engine (co-change, causal chains, decay, velocity, impact).
pub temporal: TemporalEngine,
/// Counterfactual engine.
pub counterfactual: CounterfactualEngine,
/// Topology analyzer.
pub topology: TopologyAnalyzer,
/// Resonance engine.
pub resonance: ResonanceEngine,
/// Plasticity engine.
pub plasticity: PlasticityEngine,
/// Query counter for auto-persist.
pub queries_processed: u64,
/// Auto-persist interval (persist every N queries).
pub auto_persist_interval: u32,
/// Server start time.
pub start_time: Instant,
/// Last persistence timestamp.
pub last_persist_time: Option<Instant>,
/// Path to graph snapshot file.
pub graph_path: PathBuf,
/// Path to plasticity state file.
pub plasticity_path: PathBuf,
/// Per-agent session tracking.
pub sessions: HashMap<String, AgentSession>,
// --- Perspective MCP state (12-PERSPECTIVE-SYNTHESIS) ---
/// Generation counter: bumped on ingest, rebuild_engines (Theme 1).
pub graph_generation: u64,
/// Generation counter: bumped on learn (Theme 1).
pub plasticity_generation: u64,
/// Unified cache generation: max(graph_gen, plasticity_gen). Bumped on ALL mutations (Theme 1).
pub cache_generation: u64,
/// Perspective state per (agent_id, perspective_id) (Theme 2).
pub perspectives: HashMap<(String, String), PerspectiveState>,
/// Lock state per lock_id (Theme 2).
pub locks: HashMap<String, LockState>,
/// Per-agent monotonic counter for perspective IDs (Theme 2).
pub perspective_counter: HashMap<String, u64>,
/// Per-agent monotonic counter for lock IDs (Theme 2).
pub lock_counter: HashMap<String, u64>,
/// Pending watcher events queue (Theme 10).
pub pending_watcher_events: Vec<WatcherEvent>,
/// Hard caps for perspective/lock resources (Theme 5).
pub perspective_limits: PerspectiveLimits,
/// Peek security configuration (Theme 6).
pub peek_security: PeekSecurityConfig,
/// Ingest root paths for peek allow-list (Theme 6).
pub ingest_roots: Vec<String>,
}
impl SessionState {
/// Initialize from a loaded graph. Builds all engines.
/// Replaces: 03-MCP Section 1.2 startup sequence steps 3-6.
pub fn initialize(
graph: Graph,
config: &crate::server::McpConfig,
domain: DomainConfig,
) -> M1ndResult<Self> {
// Build all engines from graph
let orchestrator = QueryOrchestrator::build(&graph)?;
let temporal = TemporalEngine::build(&graph)?;
let counterfactual = CounterfactualEngine::with_defaults();
let topology = TopologyAnalyzer::with_defaults();
let resonance = ResonanceEngine::with_defaults();
let plasticity =
PlasticityEngine::new(&graph, m1nd_core::plasticity::PlasticityConfig::default());
let shared = Arc::new(parking_lot::RwLock::new(graph));
Ok(Self {
graph: shared,
domain,
orchestrator,
temporal,
counterfactual,
topology,
resonance,
plasticity,
queries_processed: 0,
auto_persist_interval: config.auto_persist_interval,
start_time: Instant::now(),
last_persist_time: None,
graph_path: config.graph_source.clone(),
plasticity_path: config.plasticity_state.clone(),
sessions: HashMap::new(),
// Perspective MCP state
graph_generation: 0,
plasticity_generation: 0,
cache_generation: 0,
perspectives: HashMap::new(),
locks: HashMap::new(),
perspective_counter: HashMap::new(),
lock_counter: HashMap::new(),
pending_watcher_events: Vec::new(),
perspective_limits: PerspectiveLimits::default(),
peek_security: PeekSecurityConfig::default(),
ingest_roots: Vec::new(),
})
}
/// Check if auto-persist should trigger. Returns true every N queries.
pub fn should_persist(&self) -> bool {
self.queries_processed > 0
&& self.queries_processed % self.auto_persist_interval as u64 == 0
}
/// Persist all state to disk.
///
/// Ordering: graph first (source of truth), then plasticity.
/// If graph save fails, skip plasticity to avoid inconsistent state.
/// If plasticity save fails after graph succeeds, log warning but don't crash.
pub fn persist(&mut self) -> M1ndResult<()> {
let graph = self.graph.read();
// Graph is the source of truth — save it first.
m1nd_core::snapshot::save_graph(&graph, &self.graph_path)?;
// Graph succeeded. Now try plasticity — failure here is non-fatal.
match self.plasticity.export_state(&graph) {
Ok(states) => {
if let Err(e) =
m1nd_core::snapshot::save_plasticity_state(&states, &self.plasticity_path)
{
eprintln!(
"{}",
brand::log_colored(&format!(
"WARNING: graph saved but plasticity persist failed: {}",
e
))
);
}
}
Err(e) => {
eprintln!(
"{}",
brand::log_colored(&format!(
"WARNING: graph saved but plasticity export failed: {}",
e
))
);
}
}
self.last_persist_time = Some(Instant::now());
Ok(())
}
/// Rebuild all engines after graph replacement (e.g. after ingest).
/// Critical: SemanticEngine indexes, TemporalEngine, PlasticityEngine
/// are all built from graph state and become stale on graph swap.
///
/// Also invalidates all perspective and lock state (Theme 16).
pub fn rebuild_engines(&mut self) -> M1ndResult<()> {
// Scope the read lock so it's dropped before &mut self methods
{
let graph = self.graph.read();
self.orchestrator = QueryOrchestrator::build(&graph)?;
self.temporal = TemporalEngine::build(&graph)?;
self.plasticity =
PlasticityEngine::new(&graph, m1nd_core::plasticity::PlasticityConfig::default());
}
// Theme 16: invalidate all perspective and lock state after rebuild
self.invalidate_all_perspectives();
self.mark_all_lock_baselines_stale();
self.graph_generation += 1;
self.cache_generation = self.cache_generation.max(self.graph_generation);
Ok(())
}
// --- Perspective MCP methods (12-PERSPECTIVE-SYNTHESIS) ---
/// Bump graph generation (Theme 1). Called after ingest and rebuild_engines.
pub fn bump_graph_generation(&mut self) {
self.graph_generation += 1;
self.cache_generation = self.cache_generation.max(self.graph_generation);
}
/// Bump plasticity generation (Theme 1). Called after learn.
pub fn bump_plasticity_generation(&mut self) {
self.plasticity_generation += 1;
self.cache_generation = self.cache_generation.max(self.plasticity_generation);
}
/// Invalidate all perspectives (Theme 16).
/// Sets stale=true, clears route caches, bumps route_set_version.
/// Does NOT close perspectives — agents may still want them.
pub fn invalidate_all_perspectives(&mut self) {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
for state in self.perspectives.values_mut() {
state.stale = true;
state.route_cache = None;
state.route_set_version = now_ms;
}
}
/// Mark all lock baselines as stale (Theme 16).
/// Does NOT release locks. lock.diff reports staleness and suggests lock.rebase.
pub fn mark_all_lock_baselines_stale(&mut self) {
for lock in self.locks.values_mut() {
lock.baseline_stale = true;
}
}
/// Get a perspective for an agent (Theme 2).
pub fn get_perspective(
&self,
agent_id: &str,
perspective_id: &str,
) -> Option<&PerspectiveState> {
self.perspectives
.get(&(agent_id.to_string(), perspective_id.to_string()))
}
/// Get a mutable perspective for an agent (Theme 2).
pub fn get_perspective_mut(
&mut self,
agent_id: &str,
perspective_id: &str,
) -> Option<&mut PerspectiveState> {
self.perspectives
.get_mut(&(agent_id.to_string(), perspective_id.to_string()))
}
/// Generate a new perspective ID for an agent (Theme 2).
pub fn next_perspective_id(&mut self, agent_id: &str) -> String {
let counter = self
.perspective_counter
.entry(agent_id.to_string())
.or_insert(0);
*counter += 1;
let short_id = &agent_id[..agent_id.len().min(8)];
format!("persp_{}_{:03}", short_id, counter)
}
/// Generate a new lock ID for an agent (Theme 2).
pub fn next_lock_id(&mut self, agent_id: &str) -> String {
let counter = self.lock_counter.entry(agent_id.to_string()).or_insert(0);
*counter += 1;
let short_id = &agent_id[..agent_id.len().min(8)];
format!("lock_{}_{:03}", short_id, counter)
}
/// Count perspectives for an agent (for limit enforcement, Theme 5).
pub fn agent_perspective_count(&self, agent_id: &str) -> usize {
self.perspectives
.keys()
.filter(|(a, _)| a == agent_id)
.count()
}
/// Count locks for an agent (for limit enforcement, Theme 5).
pub fn agent_lock_count(&self, agent_id: &str) -> usize {
self.locks
.values()
.filter(|l| l.agent_id == agent_id)
.count()
}
/// Notify watchers after ingest/learn (Theme 10).
/// Records (lock_id, trigger, timestamp) in pending_watcher_events.
/// Diff computed lazily on next lock.diff call.
pub fn notify_watchers(&mut self, trigger: WatchTrigger) {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let matching_locks: Vec<String> = self
.locks
.values()
.filter(|l| {
l.watcher
.as_ref()
.map_or(false, |w| match (&trigger, &w.strategy) {
(
WatchTrigger::Ingest,
crate::perspective::state::WatchStrategy::OnIngest,
) => true,
(
WatchTrigger::Learn,
crate::perspective::state::WatchStrategy::OnLearn,
) => true,
_ => false,
})
})
.map(|l| l.lock_id.clone())
.collect();
for lock_id in matching_locks {
self.pending_watcher_events.push(WatcherEvent {
lock_id,
trigger: trigger.clone(),
timestamp_ms: now_ms,
});
}
}
/// Cleanup all state for an agent (called on session timeout, Theme 2).
pub fn cleanup_agent_state(&mut self, agent_id: &str) {
// Remove perspectives
self.perspectives.retain(|(a, _), _| a != agent_id);
// Remove locks owned by this agent
let agent_locks: Vec<String> = self
.locks
.values()
.filter(|l| l.agent_id == agent_id)
.map(|l| l.lock_id.clone())
.collect();
for lock_id in &agent_locks {
self.locks.remove(lock_id);
}
// Clean pending watcher events for removed locks
self.pending_watcher_events
.retain(|e| !agent_locks.contains(&e.lock_id));
// Clean counters
self.perspective_counter.remove(agent_id);
self.lock_counter.remove(agent_id);
}
/// Estimate memory usage of perspective + lock state (Theme 5).
/// Used for 50MB budget enforcement.
pub fn perspective_and_lock_memory_bytes(&self) -> usize {
// Rough estimate: serialize to JSON and measure
let persp_size: usize = self
.perspectives
.values()
.map(|p| {
std::mem::size_of_val(p)
+ p.navigation_history.len() * 100
+ p.visited_nodes.len() * 40
})
.sum();
let lock_size: usize = self
.locks
.values()
.map(|l| {
std::mem::size_of_val(l)
+ l.baseline.nodes.len() * 40
+ l.baseline.edges.len() * 120
})
.sum();
persp_size + lock_size
}
/// Uptime in seconds.
pub fn uptime_seconds(&self) -> f64 {
self.start_time.elapsed().as_secs_f64()
}
/// Track an agent session. Creates a new session if first contact,
/// otherwise updates last_seen and increments query_count.
pub fn track_agent(&mut self, agent_id: &str) {
let now = Instant::now();
let session = self
.sessions
.entry(agent_id.to_string())
.or_insert_with(|| AgentSession {
agent_id: agent_id.to_string(),
first_seen: now,
last_seen: now,
query_count: 0,
});
session.last_seen = now;
session.query_count += 1;
}
/// Generate a summary of active agent sessions for health output.
pub fn session_summary(&self) -> Vec<serde_json::Value> {
self.sessions
.values()
.map(|s| {
serde_json::json!({
"agent_id": s.agent_id,
"first_seen_secs_ago": s.first_seen.elapsed().as_secs_f64(),
"last_seen_secs_ago": s.last_seen.elapsed().as_secs_f64(),
"query_count": s.query_count,
})
})
.collect()
}
}