1use chrono::Utc;
2use std::sync::{LazyLock, Mutex};
3
4use crate::core::cognitive_gate::full_science_enabled;
5use crate::core::context_prefetch::FileTrajectory;
6use crate::core::intent_protocol::{IntentRecord, IntentSource};
7
8use super::paths::{extract_cd_target, generate_session_id};
9#[allow(clippy::wildcard_imports)]
10use super::types::*;
11
12const MAX_FINDINGS: usize = 20;
13const MAX_DECISIONS: usize = 10;
14const MAX_FILES: usize = 50;
15const MAX_EVIDENCE: usize = 500;
16pub(crate) const BATCH_SAVE_INTERVAL: u32 = 5;
17pub(crate) const SESSION_FLUSH_INTERVAL: std::time::Duration = std::time::Duration::from_mins(1);
21
22static FILE_TRAJECTORY: LazyLock<Mutex<FileTrajectory>> =
23 LazyLock::new(|| Mutex::new(FileTrajectory::new(100)));
24
25pub(crate) fn extract_session_facts(
27 session: &SessionState,
28) -> Vec<crate::core::knowledge::KnowledgeFact> {
29 let mut facts = Vec::new();
30
31 facts.extend(session.decisions.iter().filter_map(|decision| {
32 let summary = decision.summary.trim();
33 if summary.is_empty() {
34 return None;
35 }
36 let value = decision
37 .rationale
38 .as_deref()
39 .filter(|rationale| !rationale.trim().is_empty())
40 .map_or_else(
41 || summary.to_owned(),
42 |rationale| format!("{summary} — {rationale}"),
43 );
44 Some(auto_session_fact(
45 "auto:decision",
46 value,
47 session,
48 decision.timestamp,
49 0.9,
50 ))
51 }));
52
53 facts.extend(
54 session
55 .files_touched
56 .iter()
57 .filter(|file| file.modified)
58 .map(|file| {
59 let summary = file
60 .summary
61 .as_deref()
62 .filter(|summary| !summary.trim().is_empty())
63 .map_or_else(String::new, |summary| format!("; {summary}"));
64 auto_session_fact(
65 "auto:pattern",
66 format!(
67 "Modified {} (mode: {}, reads: {}){summary}",
68 file.path, file.last_mode, file.read_count
69 ),
70 session,
71 session.updated_at,
72 0.8,
73 )
74 }),
75 );
76
77 facts.extend(session.findings.iter().filter_map(|finding| {
78 let summary = finding.summary.trim();
79 if summary.is_empty() {
80 return None;
81 }
82 let normalized = summary.to_ascii_lowercase();
83 let label = if ["resolved", "fixed", "solved", "unblocked", "passed"]
84 .iter()
85 .any(|keyword| normalized.contains(keyword))
86 {
87 "Resolution"
88 } else if [
89 "block", "fail", "error", "unable", "cannot", "missing", "timeout", "denied",
90 ]
91 .iter()
92 .any(|keyword| normalized.contains(keyword))
93 {
94 "Blocker"
95 } else {
96 "Finding"
97 };
98 let location = finding.file.as_deref().map_or_else(String::new, |file| {
99 finding
100 .line
101 .map_or_else(|| format!("{file}: "), |line| format!("{file}:{line}: "))
102 });
103 Some(auto_session_fact(
104 "auto:blocker",
105 format!("{label}: {location}{summary}"),
106 session,
107 finding.timestamp,
108 0.75,
109 ))
110 }));
111
112 facts
113}
114
115fn auto_session_fact(
116 category: &str,
117 value: String,
118 session: &SessionState,
119 timestamp: chrono::DateTime<Utc>,
120 confidence: f32,
121) -> crate::core::knowledge::KnowledgeFact {
122 let key = value.clone();
123 crate::core::knowledge::KnowledgeFact {
124 category: category.to_owned(),
125 key,
126 value,
127 source_session: session.id.clone(),
128 confidence,
129 created_at: timestamp,
130 last_confirmed: timestamp,
131 retrieval_count: 0,
132 last_retrieved: None,
133 valid_from: None,
134 valid_until: None,
135 supersedes: None,
136 confirmation_count: 1,
137 feedback_up: 0,
138 feedback_down: 0,
139 last_feedback: None,
140 privacy: Default::default(),
141 sensitivity: Default::default(),
142 imported_from: None,
143 archetype: Default::default(),
144 fidelity: None,
145 revision_count: 0,
146 }
147}
148
149impl Default for SessionState {
150 fn default() -> Self {
151 Self::new()
152 }
153}
154
155impl SessionState {
156 pub fn new() -> Self {
158 let now = Utc::now();
159 Self {
160 id: generate_session_id(),
161 version: 0,
162 started_at: now,
163 updated_at: now,
164 project_root: None,
165 shell_cwd: None,
166 task: None,
167 findings: Vec::new(),
168 decisions: Vec::new(),
169 handoff_context: Vec::new(),
170 files_touched: Vec::new(),
171 test_results: None,
172 progress: Vec::new(),
173 next_steps: Vec::new(),
174 evidence: Vec::new(),
175 intents: Vec::new(),
176 active_structured_intent: None,
177 stats: SessionStats::default(),
178 terse_mode: false,
179 compression_level: String::new(),
180 last_consolidate_ts: None,
181 last_aaak_hash: None,
182 extra_roots: Vec::new(),
183 live_zone: super::types::LiveZoneSessionState::default(),
184 wakeup_manifest: Vec::new(),
185 playbook: super::playbook::Playbook::default(),
186 last_semantic_query: None,
187 last_flush: None,
188 }
189 .with_compression_from_config()
190 }
191
192 pub fn refresh_handoff_context(&mut self) {
193 let Some(project_root) = self.project_root.clone() else {
194 self.handoff_context.clear();
195 return;
196 };
197
198 let session_id = self.id.clone();
199 self.handoff_context = crate::core::knowledge::ProjectKnowledge::load(&project_root)
200 .map(|knowledge| {
201 knowledge
202 .recent_decisions(10)
203 .into_iter()
204 .filter(|fact| fact.source_session != session_id)
205 .collect()
206 })
207 .unwrap_or_default();
208 }
209
210 fn with_compression_from_config(mut self) -> Self {
211 let cfg = crate::core::config::Config::load();
212 let level = crate::core::config::CompressionLevel::effective(&cfg);
213 self.compression_level = level.label().to_string();
214 self.terse_mode = level.is_active();
215 self
216 }
217
218 pub fn increment(&mut self) {
220 self.version += 1;
221 self.updated_at = Utc::now();
222 self.stats.unsaved_changes += 1;
223 }
224
225 pub fn should_save(&self) -> bool {
232 if self.stats.unsaved_changes == 0 {
233 return false;
234 }
235 if self.stats.unsaved_changes >= BATCH_SAVE_INTERVAL {
236 return true;
237 }
238 match self.last_flush {
239 Some(t) => t.elapsed() >= SESSION_FLUSH_INTERVAL,
240 None => true,
241 }
242 }
243
244 pub fn set_task(&mut self, description: &str, intent: Option<&str>) {
246 let (description_clean, _) =
247 crate::core::secret_detection::scan_and_redact_from_config(description);
248 self.task = Some(TaskInfo {
249 description: description_clean.clone(),
250 intent: intent.map(std::string::ToString::to_string),
251 progress_pct: None,
252 });
253
254 let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
255 let si = if touched.is_empty() {
256 crate::core::intent_engine::StructuredIntent::from_query(&description_clean)
257 } else {
258 crate::core::intent_engine::StructuredIntent::from_query_with_session(
259 &description_clean,
260 &touched,
261 )
262 };
263 if si.confidence >= 0.7 {
264 self.active_structured_intent = Some(si);
265 }
266
267 self.increment();
268 }
269
270 pub fn auto_infer_task(&mut self) {
273 if self.task.is_some() {
275 return;
276 }
277
278 if let Some(task_from_plan) = Self::infer_task_from_plans() {
280 self.set_task(&task_from_plan, Some("plan"));
281 return;
282 }
283
284 if let Some(ref root) = self.project_root
286 && let Some(task_from_git) = Self::infer_task_from_git(root)
287 {
288 self.set_task(&task_from_git, Some("git"));
289 return;
290 }
291
292 if self.files_touched.len() >= 3 {
294 let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
295 let intent = crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
296 if intent.confidence >= 0.5 {
297 let dirs: std::collections::HashSet<&str> = touched
298 .iter()
299 .filter_map(|f| std::path::Path::new(f).parent()?.to_str())
300 .collect();
301 let primary_dir = dirs.iter().next().unwrap_or(&".");
302 let desc = format!("Working on {} ({})", primary_dir, intent.task_type.as_str());
303 self.set_task(&desc, Some("inferred"));
304 }
305 }
306 }
307
308 fn infer_task_from_plans() -> Option<String> {
309 let plans_dir = std::path::Path::new(".cursor/plans");
310 if !plans_dir.exists() {
311 return None;
312 }
313
314 let mut newest: Option<(std::time::SystemTime, String)> = None;
315 if let Ok(entries) = std::fs::read_dir(plans_dir) {
316 for entry in entries.flatten() {
317 let path = entry.path();
318 if !path.to_string_lossy().ends_with(".plan.md") {
319 continue;
320 }
321 let mtime = entry.metadata().ok()?.modified().ok()?;
322 let content = std::fs::read_to_string(&path).ok()?;
323
324 let has_active =
326 content.contains("status: pending") || content.contains("status: in_progress");
327 if !has_active {
328 continue;
329 }
330
331 let name = content
333 .lines()
334 .find(|l| l.starts_with("name:"))
335 .map_or("Unknown Plan", |l| {
336 l.trim_start_matches("name:").trim().trim_matches('"')
337 });
338
339 let better = newest.as_ref().is_none_or(|(t, _)| mtime > *t);
340 if better {
341 newest = Some((mtime, name.to_string()));
342 }
343 }
344 }
345
346 newest.map(|(_, name)| name)
347 }
348
349 fn infer_task_from_git(project_root: &str) -> Option<String> {
350 let output = std::process::Command::new("git")
351 .args(["diff", "--stat", "--no-color"])
352 .current_dir(project_root)
353 .output()
354 .ok()?;
355
356 if !output.status.success() {
357 return None;
358 }
359
360 let stat = String::from_utf8_lossy(&output.stdout);
361 let lines: Vec<&str> = stat.lines().collect();
362 if lines.is_empty() {
363 return None;
364 }
365
366 let summary_line = lines.last()?;
368 if !summary_line.contains("changed") {
369 return None;
370 }
371
372 let file_lines: Vec<&str> = lines[..lines.len() - 1].to_vec();
374 let dirs: std::collections::HashSet<&str> = file_lines
375 .iter()
376 .filter_map(|l| {
377 let path = l.split('|').next()?.trim();
378 std::path::Path::new(path).parent()?.to_str()
379 })
380 .collect();
381
382 let primary = if dirs.len() == 1 {
383 dirs.into_iter().next().unwrap_or(".")
384 } else {
385 "multiple dirs"
386 };
387
388 Some(format!("Modified: {} in {}", summary_line.trim(), primary))
389 }
390
391 pub fn add_finding(&mut self, file: Option<&str>, line: Option<u32>, summary: &str) {
393 let (summary_clean, _) =
394 crate::core::secret_detection::scan_and_redact_from_config(summary);
395 self.findings.push(Finding {
396 file: file.map(std::string::ToString::to_string),
397 line,
398 summary: summary_clean,
399 timestamp: Utc::now(),
400 });
401 while self.findings.len() > MAX_FINDINGS {
402 self.findings.remove(0);
403 }
404 self.increment();
405 }
406
407 pub fn add_decision(&mut self, summary: &str, rationale: Option<&str>) {
409 let (summary_clean, _) =
410 crate::core::secret_detection::scan_and_redact_from_config(summary);
411 let rationale_clean =
412 rationale.map(|r| crate::core::secret_detection::scan_and_redact_from_config(r).0);
413 self.decisions.push(Decision {
414 summary: summary_clean,
415 rationale: rationale_clean,
416 timestamp: Utc::now(),
417 });
418 while self.decisions.len() > MAX_DECISIONS {
419 self.decisions.remove(0);
420 }
421 self.increment();
422 }
423
424 pub fn touch_file(&mut self, path: &str, file_ref: Option<&str>, mode: &str, tokens: usize) {
426 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
427 existing.read_count += 1;
428 existing.last_mode = mode.to_string();
429 existing.tokens = tokens;
430 if let Some(r) = file_ref {
431 existing.file_ref = Some(r.to_string());
432 }
433 } else {
434 let item_id = crate::core::context_field::ContextItemId::from_file(path);
435 self.files_touched.push(FileTouched {
436 path: path.to_string(),
437 file_ref: file_ref.map(std::string::ToString::to_string),
438 read_count: 1,
439 modified: false,
440 last_mode: mode.to_string(),
441 tokens,
442 stale: false,
443 context_item_id: Some(item_id.to_string()),
444 summary: None,
445 });
446 while self.files_touched.len() > MAX_FILES {
447 self.files_touched.remove(0);
448 }
449 }
450 self.stats.files_read += 1;
451 self.increment();
452
453 if full_science_enabled()
454 && let Ok(mut trajectory) = FILE_TRAJECTORY.lock()
455 {
456 trajectory.record(path);
457 }
458 }
459
460 #[allow(dead_code)] pub(crate) fn prefetch_predictions(&self, top_k: usize) -> Vec<String> {
463 if !full_science_enabled() || top_k == 0 {
464 return Vec::new();
465 }
466 FILE_TRAJECTORY
467 .lock()
468 .map(|trajectory| {
469 trajectory
470 .predict(top_k)
471 .into_iter()
472 .map(|(path, _)| path)
473 .collect()
474 })
475 .unwrap_or_default()
476 }
477
478 pub fn mark_modified(&mut self, path: &str) {
480 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
481 existing.modified = true;
482 }
483 self.increment();
484 }
485
486 pub fn set_file_summary(&mut self, path: &str, summary: &str) {
488 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
489 let truncated = if summary.len() > 80 {
490 format!("{}…", &summary[..79])
491 } else {
492 summary.to_string()
493 };
494 existing.summary = Some(truncated);
495 }
496 }
497
498 pub fn record_tool_call(&mut self, tokens_saved: u64, tokens_input: u64) {
500 self.stats.total_tool_calls += 1;
501 self.stats.total_tokens_saved += tokens_saved;
502 self.stats.total_tokens_input += tokens_input;
503 }
504
505 pub fn record_intent(&mut self, mut intent: IntentRecord) {
507 if intent.occurrences == 0 {
508 intent.occurrences = 1;
509 }
510
511 if let Some(last) = self.intents.last_mut()
512 && last.fingerprint() == intent.fingerprint()
513 {
514 last.occurrences = last.occurrences.saturating_add(intent.occurrences);
515 last.timestamp = intent.timestamp;
516 match intent.source {
517 IntentSource::Inferred => self.stats.intents_inferred += 1,
518 IntentSource::Explicit => self.stats.intents_explicit += 1,
519 }
520 self.increment();
521 return;
522 }
523
524 match intent.source {
525 IntentSource::Inferred => self.stats.intents_inferred += 1,
526 IntentSource::Explicit => self.stats.intents_explicit += 1,
527 }
528
529 self.intents.push(intent);
530 while self.intents.len() > crate::core::budgets::INTENTS_PER_SESSION_LIMIT {
531 self.intents.remove(0);
532 }
533 self.increment();
534 }
535
536 pub fn record_tool_receipt(
538 &mut self,
539 tool: &str,
540 action: Option<&str>,
541 input_md5: &str,
542 output_md5: &str,
543 agent_id: Option<&str>,
544 client_name: Option<&str>,
545 ) {
546 self.record_tool_receipt_with_task(
547 tool,
548 action,
549 input_md5,
550 output_md5,
551 agent_id,
552 client_name,
553 None,
554 );
555 }
556
557 pub fn record_tool_receipt_with_task(
559 &mut self,
560 tool: &str,
561 action: Option<&str>,
562 input_md5: &str,
563 output_md5: &str,
564 agent_id: Option<&str>,
565 client_name: Option<&str>,
566 task_id: Option<&str>,
567 ) {
568 let now = Utc::now();
569 let mut push = |key: String| {
570 self.evidence.push(EvidenceRecord {
571 kind: EvidenceKind::ToolCall,
572 key,
573 value: None,
574 tool: Some(tool.to_string()),
575 input_md5: Some(input_md5.to_string()),
576 output_md5: Some(output_md5.to_string()),
577 agent_id: agent_id.map(std::string::ToString::to_string),
578 client_name: client_name.map(std::string::ToString::to_string),
579 task_id: task_id.map(std::string::ToString::to_string),
580 timestamp: now,
581 });
582 };
583
584 push(format!("tool:{tool}"));
585 if let Some(a) = action {
586 push(format!("tool:{tool}:{a}"));
587 }
588 while self.evidence.len() > MAX_EVIDENCE {
589 self.evidence.remove(0);
590 }
591 self.increment();
592 }
593
594 pub fn record_manual_evidence(&mut self, key: &str, value: Option<&str>) {
596 self.evidence.push(EvidenceRecord {
597 kind: EvidenceKind::Manual,
598 key: key.to_string(),
599 value: value.map(std::string::ToString::to_string),
600 tool: None,
601 input_md5: None,
602 output_md5: None,
603 agent_id: None,
604 client_name: None,
605 task_id: None,
606 timestamp: Utc::now(),
607 });
608 while self.evidence.len() > MAX_EVIDENCE {
609 self.evidence.remove(0);
610 }
611 self.increment();
612 }
613
614 pub fn has_evidence_key(&self, key: &str) -> bool {
616 self.evidence.iter().any(|e| e.key == key)
617 }
618
619 pub fn record_cache_hit(&mut self) {
621 self.stats.cache_hits += 1;
622 }
623
624 pub fn record_command(&mut self) {
626 self.stats.commands_run += 1;
627 }
628
629 pub fn effective_cwd(&self, explicit_cwd: Option<&str>) -> String {
634 self.effective_cwd_checked(explicit_cwd).0
635 }
636
637 pub fn effective_cwd_checked(&self, explicit_cwd: Option<&str>) -> (String, Option<String>) {
649 let root = self.project_root.as_deref().unwrap_or(".");
650 if let Some(cwd) = explicit_cwd
651 && !cwd.is_empty()
652 && cwd != "."
653 {
654 return Self::jail_cwd(cwd, root);
655 }
656 if let Some(ref cwd) = self.shell_cwd {
657 return (cwd.clone(), None);
658 }
659 if let Some(ref r) = self.project_root {
660 return (r.clone(), None);
661 }
662 (
663 std::env::current_dir()
664 .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string()),
665 None,
666 )
667 }
668
669 fn jail_cwd(candidate: &str, fallback_root: &str) -> (String, Option<String>) {
676 let p = std::path::Path::new(candidate);
677 match crate::core::pathjail::jail_path(p, std::path::Path::new(fallback_root)) {
678 Ok(jailed) => (jailed.to_string_lossy().to_string(), None),
679 Err(reason) => (fallback_root.to_string(), Some(reason.to_string())),
680 }
681 }
682
683 pub fn note_explicit_cwd(&mut self, cwd: &str) {
691 let path = std::path::Path::new(cwd);
692 if path.is_absolute() && path.is_dir() {
693 self.shell_cwd = Some(
694 crate::core::pathutil::safe_canonicalize_or_self(path)
695 .to_string_lossy()
696 .to_string(),
697 );
698 }
699 }
700
701 pub fn update_shell_cwd(&mut self, command: &str) {
706 let base = self.effective_cwd(None);
707 if let Some(new_cwd) = extract_cd_target(command, &base) {
708 let path = std::path::Path::new(&new_cwd);
709 if path.exists() && path.is_dir() {
710 let canonical = crate::core::pathutil::safe_canonicalize_or_self(path)
711 .to_string_lossy()
712 .to_string();
713 let root = self.project_root.as_deref().unwrap_or(".");
714 if crate::core::pathjail::jail_path(
715 std::path::Path::new(&canonical),
716 std::path::Path::new(root),
717 )
718 .is_ok()
719 {
720 self.shell_cwd = Some(canonical);
721 }
722 }
723 }
724 }
725}