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 origin: crate::core::knowledge::FactOrigin::Unverified,
125 category: category.to_owned(),
126 key,
127 value,
128 source_session: session.id.clone(),
129 confidence,
130 created_at: timestamp,
131 last_confirmed: timestamp,
132 retrieval_count: 0,
133 last_retrieved: None,
134 valid_from: None,
135 valid_until: None,
136 supersedes: None,
137 confirmation_count: 1,
138 feedback_up: 0,
139 feedback_down: 0,
140 last_feedback: None,
141 privacy: Default::default(),
142 sensitivity: Default::default(),
143 imported_from: None,
144 archetype: Default::default(),
145 fidelity: None,
146 revision_count: 0,
147 }
148}
149
150impl Default for SessionState {
151 fn default() -> Self {
152 Self::new()
153 }
154}
155
156impl SessionState {
157 pub fn new() -> Self {
159 let now = Utc::now();
160 Self {
161 canonical_checkpoint: None,
162 save_gate: Default::default(),
163 last_save_failed: false,
164 id: generate_session_id(),
165 version: 0,
166 started_at: now,
167 updated_at: now,
168 project_root: None,
169 shell_cwd: None,
170 task: None,
171 findings: Vec::new(),
172 decisions: Vec::new(),
173 handoff_context: Vec::new(),
174 files_touched: Vec::new(),
175 test_results: None,
176 progress: Vec::new(),
177 next_steps: Vec::new(),
178 evidence: Vec::new(),
179 intents: Vec::new(),
180 active_structured_intent: None,
181 stats: SessionStats::default(),
182 terse_mode: false,
183 compression_level: String::new(),
184 last_consolidate_ts: None,
185 last_aaak_hash: None,
186 extra_roots: Vec::new(),
187 live_zone: super::types::LiveZoneSessionState::default(),
188 wakeup_manifest: Vec::new(),
189 playbook: super::playbook::Playbook::default(),
190 last_semantic_query: None,
191 last_flush: None,
192 }
193 .with_compression_from_config()
194 }
195
196 pub fn refresh_handoff_context(&mut self) {
197 let Some(project_root) = self.project_root.clone() else {
198 self.handoff_context.clear();
199 return;
200 };
201
202 let session_id = self.id.clone();
203 self.handoff_context = crate::core::knowledge::ProjectKnowledge::load(&project_root)
204 .map(|knowledge| {
205 knowledge
206 .recent_decisions(10)
207 .into_iter()
208 .filter(|fact| fact.source_session != session_id)
209 .collect()
210 })
211 .unwrap_or_default();
212 }
213
214 fn with_compression_from_config(mut self) -> Self {
215 let cfg = crate::core::config::Config::load();
216 let level = crate::core::config::CompressionLevel::effective(&cfg);
217 self.compression_level = level.label().to_string();
218 self.terse_mode = level.is_active();
219 self
220 }
221
222 pub fn increment(&mut self) {
224 self.version += 1;
225 self.updated_at = Utc::now();
226 self.stats.unsaved_changes += 1;
227 }
228
229 pub fn should_save(&self) -> bool {
236 if self.stats.unsaved_changes == 0 {
237 return false;
238 }
239 if self.stats.unsaved_changes >= BATCH_SAVE_INTERVAL {
240 return true;
241 }
242 match self.last_flush {
243 Some(t) => t.elapsed() >= SESSION_FLUSH_INTERVAL,
244 None => true,
245 }
246 }
247
248 pub fn set_task(&mut self, description: &str, intent: Option<&str>) {
250 let (description_clean, _) =
251 crate::core::secret_detection::scan_and_redact_from_config(description);
252 let progress_pct = if self.canonical_checkpoint.is_some() {
254 self.task.as_ref().and_then(|task| task.progress_pct)
255 } else {
256 None
257 };
258 self.task = Some(TaskInfo {
259 description: description_clean.clone(),
260 intent: intent.map(std::string::ToString::to_string),
261 progress_pct,
262 });
263
264 let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
265 let si = if touched.is_empty() {
266 crate::core::intent_engine::StructuredIntent::from_query(&description_clean)
267 } else {
268 crate::core::intent_engine::StructuredIntent::from_query_with_session(
269 &description_clean,
270 &touched,
271 )
272 };
273 if si.confidence >= 0.7 {
274 self.active_structured_intent = Some(si);
275 }
276
277 self.increment();
278 }
279
280 pub fn auto_infer_task(&mut self) {
283 if self.task.is_some() {
285 return;
286 }
287
288 if let Some(task_from_plan) = Self::infer_task_from_plans() {
290 self.set_task(&task_from_plan, Some("plan"));
291 return;
292 }
293
294 if let Some(ref root) = self.project_root
296 && let Some(task_from_git) = Self::infer_task_from_git(root)
297 {
298 self.set_task(&task_from_git, Some("git"));
299 return;
300 }
301
302 if self.files_touched.len() >= 3 {
304 let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
305 let intent = crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
306 if intent.confidence >= 0.5 {
307 let dirs: std::collections::HashSet<&str> = touched
308 .iter()
309 .filter_map(|f| std::path::Path::new(f).parent()?.to_str())
310 .collect();
311 let primary_dir = dirs.iter().next().unwrap_or(&".");
312 let desc = format!("Working on {} ({})", primary_dir, intent.task_type.as_str());
313 self.set_task(&desc, Some("inferred"));
314 }
315 }
316 }
317
318 fn infer_task_from_plans() -> Option<String> {
319 let plans_dir = std::path::Path::new(".cursor/plans");
320 if !plans_dir.exists() {
321 return None;
322 }
323
324 let mut newest: Option<(std::time::SystemTime, String)> = None;
325 if let Ok(entries) = std::fs::read_dir(plans_dir) {
326 for entry in entries.flatten() {
327 let path = entry.path();
328 if !path.to_string_lossy().ends_with(".plan.md") {
329 continue;
330 }
331 let mtime = entry.metadata().ok()?.modified().ok()?;
332 let content = std::fs::read_to_string(&path).ok()?;
333
334 let has_active =
336 content.contains("status: pending") || content.contains("status: in_progress");
337 if !has_active {
338 continue;
339 }
340
341 let name = content
343 .lines()
344 .find(|l| l.starts_with("name:"))
345 .map_or("Unknown Plan", |l| {
346 l.trim_start_matches("name:").trim().trim_matches('"')
347 });
348
349 let better = newest.as_ref().is_none_or(|(t, _)| mtime > *t);
350 if better {
351 newest = Some((mtime, name.to_string()));
352 }
353 }
354 }
355
356 newest.map(|(_, name)| name)
357 }
358
359 fn infer_task_from_git(project_root: &str) -> Option<String> {
360 let output = std::process::Command::new("git")
361 .args(["diff", "--stat", "--no-color"])
362 .current_dir(project_root)
363 .output()
364 .ok()?;
365
366 if !output.status.success() {
367 return None;
368 }
369
370 let stat = String::from_utf8_lossy(&output.stdout);
371 let lines: Vec<&str> = stat.lines().collect();
372 if lines.is_empty() {
373 return None;
374 }
375
376 let summary_line = lines.last()?;
378 if !summary_line.contains("changed") {
379 return None;
380 }
381
382 let file_lines: Vec<&str> = lines[..lines.len() - 1].to_vec();
384 let dirs: std::collections::HashSet<&str> = file_lines
385 .iter()
386 .filter_map(|l| {
387 let path = l.split('|').next()?.trim();
388 std::path::Path::new(path).parent()?.to_str()
389 })
390 .collect();
391
392 let primary = if dirs.len() == 1 {
393 dirs.into_iter().next().unwrap_or(".")
394 } else {
395 "multiple dirs"
396 };
397
398 Some(format!("Modified: {} in {}", summary_line.trim(), primary))
399 }
400
401 pub fn add_finding(&mut self, file: Option<&str>, line: Option<u32>, summary: &str) {
403 let (summary_clean, _) =
404 crate::core::secret_detection::scan_and_redact_from_config(summary);
405 self.findings.push(Finding {
406 file: file.map(std::string::ToString::to_string),
407 line,
408 summary: summary_clean,
409 timestamp: Utc::now(),
410 });
411 while self.findings.len() > MAX_FINDINGS {
412 self.findings.remove(0);
413 }
414 self.increment();
415 }
416
417 pub fn add_decision(&mut self, summary: &str, rationale: Option<&str>) {
419 let (summary_clean, _) =
420 crate::core::secret_detection::scan_and_redact_from_config(summary);
421 let rationale_clean =
422 rationale.map(|r| crate::core::secret_detection::scan_and_redact_from_config(r).0);
423 self.decisions.push(Decision {
424 summary: summary_clean,
425 rationale: rationale_clean,
426 timestamp: Utc::now(),
427 });
428 while self.decisions.len() > MAX_DECISIONS {
429 self.decisions.remove(0);
430 }
431 self.increment();
432 }
433
434 pub fn touch_file(&mut self, path: &str, file_ref: Option<&str>, mode: &str, tokens: usize) {
436 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
437 existing.read_count += 1;
438 existing.last_mode = mode.to_string();
439 existing.tokens = tokens;
440 if let Some(r) = file_ref {
441 existing.file_ref = Some(r.to_string());
442 }
443 } else {
444 let item_id = crate::core::context_field::ContextItemId::from_file(path);
445 self.files_touched.push(FileTouched {
446 path: path.to_string(),
447 file_ref: file_ref.map(std::string::ToString::to_string),
448 read_count: 1,
449 modified: false,
450 last_mode: mode.to_string(),
451 tokens,
452 stale: false,
453 context_item_id: Some(item_id.to_string()),
454 summary: None,
455 });
456 while self.files_touched.len() > MAX_FILES {
457 self.files_touched.remove(0);
458 }
459 }
460 self.stats.files_read += 1;
461 self.increment();
462
463 if full_science_enabled()
464 && let Ok(mut trajectory) = FILE_TRAJECTORY.lock()
465 {
466 trajectory.record(path);
467 }
468 }
469
470 #[allow(dead_code)] pub(crate) fn prefetch_predictions(&self, top_k: usize) -> Vec<String> {
473 if !full_science_enabled() || top_k == 0 {
474 return Vec::new();
475 }
476 FILE_TRAJECTORY
477 .lock()
478 .map(|trajectory| {
479 trajectory
480 .predict(top_k)
481 .into_iter()
482 .map(|(path, _)| path)
483 .collect()
484 })
485 .unwrap_or_default()
486 }
487
488 pub fn mark_modified(&mut self, path: &str) {
490 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
491 existing.modified = true;
492 }
493 self.increment();
494 }
495
496 pub fn set_file_summary(&mut self, path: &str, summary: &str) {
498 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
499 let truncated = if summary.len() > 80 {
500 format!("{}…", &summary[..79])
501 } else {
502 summary.to_string()
503 };
504 existing.summary = Some(truncated);
505 }
506 }
507
508 pub fn record_tool_call(&mut self, tokens_saved: u64, tokens_input: u64) {
510 self.stats.total_tool_calls += 1;
511 self.stats.total_tokens_saved += tokens_saved;
512 self.stats.total_tokens_input += tokens_input;
513 }
514
515 pub fn record_intent(&mut self, mut intent: IntentRecord) {
517 if intent.occurrences == 0 {
518 intent.occurrences = 1;
519 }
520
521 if let Some(last) = self.intents.last_mut()
522 && last.fingerprint() == intent.fingerprint()
523 {
524 last.occurrences = last.occurrences.saturating_add(intent.occurrences);
525 last.timestamp = intent.timestamp;
526 match intent.source {
527 IntentSource::Inferred => self.stats.intents_inferred += 1,
528 IntentSource::Explicit => self.stats.intents_explicit += 1,
529 }
530 self.increment();
531 return;
532 }
533
534 match intent.source {
535 IntentSource::Inferred => self.stats.intents_inferred += 1,
536 IntentSource::Explicit => self.stats.intents_explicit += 1,
537 }
538
539 self.intents.push(intent);
540 while self.intents.len() > crate::core::budgets::INTENTS_PER_SESSION_LIMIT {
541 self.intents.remove(0);
542 }
543 self.increment();
544 }
545
546 pub fn record_tool_receipt(
548 &mut self,
549 tool: &str,
550 action: Option<&str>,
551 input_md5: &str,
552 output_md5: &str,
553 agent_id: Option<&str>,
554 client_name: Option<&str>,
555 ) {
556 self.record_tool_receipt_with_task(
557 tool,
558 action,
559 input_md5,
560 output_md5,
561 agent_id,
562 client_name,
563 None,
564 );
565 }
566
567 pub fn record_tool_receipt_with_task(
569 &mut self,
570 tool: &str,
571 action: Option<&str>,
572 input_md5: &str,
573 output_md5: &str,
574 agent_id: Option<&str>,
575 client_name: Option<&str>,
576 task_id: Option<&str>,
577 ) {
578 let now = Utc::now();
579 let mut push = |key: String| {
580 self.evidence.push(EvidenceRecord {
581 kind: EvidenceKind::ToolCall,
582 key,
583 value: None,
584 tool: Some(tool.to_string()),
585 input_md5: Some(input_md5.to_string()),
586 output_md5: Some(output_md5.to_string()),
587 agent_id: agent_id.map(std::string::ToString::to_string),
588 client_name: client_name.map(std::string::ToString::to_string),
589 task_id: task_id.map(std::string::ToString::to_string),
590 timestamp: now,
591 });
592 };
593
594 push(format!("tool:{tool}"));
595 if let Some(a) = action {
596 push(format!("tool:{tool}:{a}"));
597 }
598 while self.evidence.len() > MAX_EVIDENCE {
599 self.evidence.remove(0);
600 }
601 self.increment();
602 }
603
604 pub fn record_manual_evidence(&mut self, key: &str, value: Option<&str>) {
606 self.evidence.push(EvidenceRecord {
607 kind: EvidenceKind::Manual,
608 key: key.to_string(),
609 value: value.map(std::string::ToString::to_string),
610 tool: None,
611 input_md5: None,
612 output_md5: None,
613 agent_id: None,
614 client_name: None,
615 task_id: None,
616 timestamp: Utc::now(),
617 });
618 while self.evidence.len() > MAX_EVIDENCE {
619 self.evidence.remove(0);
620 }
621 self.increment();
622 }
623
624 pub fn has_evidence_key(&self, key: &str) -> bool {
626 self.evidence.iter().any(|e| e.key == key)
627 }
628
629 pub fn record_cache_hit(&mut self) {
631 self.stats.cache_hits += 1;
632 }
633
634 pub fn record_command(&mut self) {
636 self.stats.commands_run += 1;
637 }
638
639 pub fn effective_cwd(&self, explicit_cwd: Option<&str>) -> String {
644 self.effective_cwd_checked(explicit_cwd).0
645 }
646
647 pub fn effective_cwd_checked(&self, explicit_cwd: Option<&str>) -> (String, Option<String>) {
659 let root = self.project_root.as_deref().unwrap_or(".");
660 if let Some(cwd) = explicit_cwd
661 && !cwd.is_empty()
662 && cwd != "."
663 {
664 return Self::jail_cwd(cwd, root);
665 }
666 if let Some(ref cwd) = self.shell_cwd {
667 return (cwd.clone(), None);
668 }
669 if let Some(ref r) = self.project_root {
670 return (r.clone(), None);
671 }
672 (
673 std::env::current_dir()
674 .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string()),
675 None,
676 )
677 }
678
679 fn jail_cwd(candidate: &str, fallback_root: &str) -> (String, Option<String>) {
686 let p = std::path::Path::new(candidate);
687 match crate::core::pathjail::jail_path(p, std::path::Path::new(fallback_root)) {
688 Ok(jailed) => (jailed.to_string_lossy().to_string(), None),
689 Err(reason) => (fallback_root.to_string(), Some(reason.to_string())),
690 }
691 }
692
693 pub fn note_explicit_cwd(&mut self, cwd: &str) {
701 let path = std::path::Path::new(cwd);
702 if path.is_absolute() && path.is_dir() {
703 self.shell_cwd = Some(
704 crate::core::pathutil::safe_canonicalize_or_self(path)
705 .to_string_lossy()
706 .to_string(),
707 );
708 }
709 }
710
711 pub fn update_shell_cwd(&mut self, command: &str) {
716 let base = self.effective_cwd(None);
717 if let Some(new_cwd) = extract_cd_target(command, &base) {
718 let path = std::path::Path::new(&new_cwd);
719 if path.exists() && path.is_dir() {
720 let canonical = crate::core::pathutil::safe_canonicalize_or_self(path)
721 .to_string_lossy()
722 .to_string();
723 let root = self.project_root.as_deref().unwrap_or(".");
724 if crate::core::pathjail::jail_path(
725 std::path::Path::new(&canonical),
726 std::path::Path::new(root),
727 )
728 .is_ok()
729 {
730 self.shell_cwd = Some(canonical);
731 }
732 }
733 }
734 }
735}