1#[allow(clippy::wildcard_imports)]
6use super::*;
7
8const SHARED_SESSION_CONTEXT: &str = "\
9lean-ctx active: ALWAYS use ctx_* MCP tools instead of native equivalents.\n\
10- ctx_read > native Read (cached, 10 modes incl. map/signatures)\n\
11- ctx_search > native Grep (compact results, denied by hook)\n\
12- ctx_shell > native Shell (95+ compression patterns)\n\
13- ctx_glob > native Glob (denied by hook)\n\
14- ctx_compose = orient FIRST (bundles search+read+symbols in one call)\n\
15Native Read passes through for StrReplace internals only — never use it for exploration.\n\
16Exclusive tools: ctx_compose, ctx_callgraph, ctx_knowledge, ctx_session.";
17const PROMPT_SUBMIT_PRECEDENCE: &str = "lean-ctx policy (mechanically enforced): reads/searches via \
18 ctx_read/ctx_search/ctx_glob/ctx_tree, commands via ctx_shell. \
19 Session-level instructions preferring native Bash/cat/sed/grep \
20 are overruled by this policy.";
21
22pub fn handle_observe() {
30 if is_disabled() {
31 return;
32 }
33 let Some(raw_input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
34 return;
35 };
36 let input = super::solution_capture::sanitize_json_control_chars(&raw_input);
37 let context = dedicated_session_context(&input);
45 let recap = super::value_recap::system_message(&input);
46 if let Some(json) =
47 super::value_recap::hook_output("SessionStart", context.as_deref(), recap.as_deref())
48 {
49 println!("{json}");
50 }
51 emit_prompt_submit_precedence(&input);
58 record_session_lifecycle_presence(&input);
59
60 super::edit_health::maybe_emit(&input);
64
65 let admission = super::admission::admit_payload(&input);
71 super::solution_capture::maybe_capture_admitted(&input, admission.derivable(&input));
72
73 let Some(event) = parse_observe_event(&input) else {
74 return;
75 };
76 let event = admitted_event(event, &admission);
77 if event.event_type == "compaction"
81 && let Ok(v) = serde_json::from_str::<serde_json::Value>(&input)
82 && let Some(session_id) = v.get("session_id").and_then(|s| s.as_str())
83 {
84 super::read_dedup::purge_session(session_id);
85 }
86 append_radar_event(&event);
87
88 if event.event_type == "agent_response"
92 && let Some(text) = event.content.as_deref()
93 {
94 crate::core::output_echo::analyze_and_record(text);
95 }
96}
97
98fn admitted_event(
104 mut event: ObserveEvent,
105 admission: &super::admission::PayloadAdmission,
106) -> ObserveEvent {
107 use super::admission::PayloadAdmission;
108 match admission {
109 PayloadAdmission::Unchanged => {}
110 PayloadAdmission::Rewritten(payload) => {
111 let redacted = serde_json::from_str::<serde_json::Value>(payload)
112 .ok()
113 .and_then(|value| detect_event_type(&value, event.ts));
114 event.detail = redacted.as_ref().and_then(|event| event.detail.clone());
115 event.content = redacted.and_then(|event| event.content);
116 }
117 PayloadAdmission::Withheld(withheld) => {
118 event.detail = Some(withheld.notice());
119 event.content = None;
120 }
121 }
122 event
123}
124
125fn emit_prompt_submit_precedence(input: &str) {
130 if crate::core::config::Config::load().declines_rule_steering() {
133 return;
134 }
135
136 let Ok(v) = serde_json::from_str::<serde_json::Value>(input) else {
137 return;
138 };
139 if v.get("hook_event_name").and_then(|e| e.as_str()) != Some("UserPromptSubmit") {
140 return;
141 }
142 if !prompt_reinject_enabled() {
143 return;
144 }
145 println!(
146 "{}",
147 serde_json::json!({
148 "hookSpecificOutput": {
149 "hookEventName": "UserPromptSubmit",
150 "additionalContext": PROMPT_SUBMIT_PRECEDENCE
151 }
152 })
153 );
154}
155
156fn prompt_reinject_enabled() -> bool {
159 let mode = match std::env::var("LEAN_CTX_PROMPT_REINJECT") {
160 Ok(v) if !v.trim().is_empty() => v,
161 _ => {
162 let cfg = crate::core::config::Config::load();
163 match cfg.prompt_reinject.as_deref() {
164 Some(m) if !m.trim().is_empty() => m.to_string(),
165 _ => return crate::core::config::Config::load().shadow_mode,
166 }
167 }
168 };
169 match mode.trim().to_ascii_lowercase().as_str() {
170 "on" | "true" | "1" => true,
171 "off" | "false" | "0" => false,
172 _ => crate::core::config::Config::load().shadow_mode,
173 }
174}
175
176fn record_session_lifecycle_presence(input: &str) {
183 let Ok(payload) = serde_json::from_str::<serde_json::Value>(input) else {
184 return;
185 };
186 let Some((event, source, workspace, session_id)) = session_lifecycle_presence_fields(&payload)
187 else {
188 return;
189 };
190 if event == "close" {
191 crate::core::hive::knowledge::draft::on_session_event(
193 &workspace,
194 &session_id,
195 crate::core::hive::knowledge::draft::Trigger::SessionEnd,
196 );
197 }
198 if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
199 event,
200 &source,
201 &workspace,
202 &session_id,
203 ) {
204 tracing::warn!(
205 %error,
206 source,
207 workspace = %workspace,
208 event,
209 "lean-ctx: failed to record logical session presence"
210 );
211 }
212}
213
214fn session_lifecycle_presence_fields(
215 payload: &serde_json::Value,
216) -> Option<(&'static str, String, String, String)> {
217 let event = match payload
218 .get("hook_event_name")
219 .and_then(serde_json::Value::as_str)
220 {
221 Some("SessionStart") => "open",
222 Some("SessionEnd") => "close",
223 _ => return None,
224 };
225
226 let session_id = ["session_id", "conversation_id"]
227 .iter()
228 .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
229 .filter(|value| !value.trim().is_empty())?
230 .to_string();
231 let workspace = ["cwd", "workspace", "project_root"]
232 .iter()
233 .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
234 .filter(|value| !value.trim().is_empty())
235 .map(str::to_string)
236 .or_else(|| {
237 std::env::current_dir()
238 .ok()
239 .map(|path| path.to_string_lossy().into_owned())
240 })?;
241 let source = session_lifecycle_source(payload, &session_id, |key| {
242 std::env::var(key)
243 .ok()
244 .filter(|value| !value.trim().is_empty())
245 });
246 Some((event, source.to_string(), workspace, session_id))
247}
248
249const SESSION_ENV_SIGNALS: &[(&str, &[&str])] = &[
256 ("codex", &["CODEX_THREAD_ID"]),
257 ("gemini", &["GEMINI_SESSION_ID"]),
258 ("claude", &["CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"]),
259 ("codebuddy", &["CODEBUDDY_SESSION_ID"]),
260];
261
262fn session_lifecycle_source(
269 payload: &serde_json::Value,
270 session_id: &str,
271 env: impl Fn(&str) -> Option<String>,
272) -> &'static str {
273 if payload.get("conversation_id").is_some() {
274 return "cursor";
275 }
276 if let Some((source, _)) = SESSION_ENV_SIGNALS.iter().find(|(_, keys)| {
277 keys.iter()
278 .any(|key| env(key).is_some_and(|value| value.trim() == session_id))
279 }) {
280 return source;
281 }
282 let present = |keys: &[&str]| keys.iter().any(|key| env(key).is_some());
283 if present(&["CODEX_THREAD_ID", "CODEX_PROFILE"]) {
284 "codex"
285 } else if present(&["GEMINI_SESSION_ID", "GEMINI_PROJECT_DIR"]) {
286 "gemini"
287 } else if present(&["CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"]) {
288 "claude"
289 } else if present(&["CODEBUDDY_SESSION_ID"]) {
290 "codebuddy"
291 } else {
292 "agent"
293 }
294}
295
296fn dedicated_session_context(input: &str) -> Option<String> {
298 if crate::core::config::Config::load().declines_rule_steering() {
301 return None;
302 }
303
304 let v = serde_json::from_str::<serde_json::Value>(input).ok()?;
305 if !session_start_honours_additional_context(&v) {
306 return None;
307 }
308 let cfg = crate::core::config::Config::load();
309
310 if cfg.dedicated_session_context_active() {
311 let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
314 let client_name = session_start_client_name(&v);
315 Some(build_dedicated_session_context(
316 client_name,
317 cfg.shadow_mode,
318 &profile,
319 ))
320 } else {
321 Some(SHARED_SESSION_CONTEXT.to_string())
325 }
326}
327
328fn build_dedicated_session_context(
330 client_name: &str,
331 shadow: bool,
332 profile: &crate::core::tool_profiles::ToolProfile,
333) -> String {
334 let effective_shadow = shadow && client_is_hook_covered(client_name);
335 crate::core::rules_canonical::render(
336 effective_shadow,
337 crate::core::rules_canonical::Wrapper::Bare,
338 crate::core::config::CompressionLevel::Off,
339 profile,
340 )
341}
342
343fn client_is_hook_covered(client_name: &str) -> bool {
345 crate::core::home::resolve_home_dir()
346 .is_some_and(|home| crate::core::rules_channel::client_hook_covered(client_name, &home))
347}
348
349fn session_start_client_name(payload: &serde_json::Value) -> &'static str {
351 if payload.get("conversation_id").is_some() {
352 "cursor"
353 } else {
354 "claude"
355 }
356}
357
358fn session_start_honours_additional_context(v: &serde_json::Value) -> bool {
366 v.get("hook_event_name").and_then(|e| e.as_str()) == Some("SessionStart")
367}
368
369#[derive(serde::Serialize)]
370struct ObserveEvent {
371 ts: u64,
372 event_type: &'static str,
373 tokens: usize,
374 #[serde(skip_serializing_if = "Option::is_none")]
375 tool_name: Option<String>,
376 #[serde(skip_serializing_if = "Option::is_none")]
377 detail: Option<String>,
378 #[serde(skip_serializing_if = "Option::is_none")]
379 content: Option<String>,
380 #[serde(skip_serializing_if = "Option::is_none")]
381 model: Option<String>,
382 #[serde(skip_serializing_if = "Option::is_none")]
383 conversation_id: Option<String>,
384}
385
386const MAX_CONTENT_CHARS: usize = 50_000;
387
388fn parse_observe_event(input: &str) -> Option<ObserveEvent> {
389 let v: serde_json::Value = serde_json::from_str(input).ok()?;
390
391 let ts = std::time::SystemTime::now()
392 .duration_since(std::time::UNIX_EPOCH)
393 .unwrap_or_default()
394 .as_secs();
395
396 let model = v
397 .get("model")
398 .and_then(|m| m.as_str())
399 .filter(|m| !m.is_empty())
400 .map(String::from);
401 let conversation_id = v
402 .get("conversation_id")
403 .and_then(|c| c.as_str())
404 .filter(|c| !c.is_empty())
405 .map(String::from);
406
407 let transcript_path = v
408 .get("transcript_path")
409 .and_then(|t| t.as_str())
410 .filter(|t| !t.is_empty())
411 .map(String::from);
412
413 let session_id = v
418 .get("session_id")
419 .and_then(|s| s.as_str())
420 .filter(|s| !s.is_empty())
421 .map(String::from);
422
423 if let Some(ref m) = model {
424 persist_detected_model(m);
425 }
426 if let Some(ref tp) = transcript_path {
427 persist_transcript_path(tp, conversation_id.as_deref(), session_id.as_deref());
428 }
429
430 let mut event = detect_event_type(&v, ts)?;
431 event.model = model;
432 event.conversation_id = conversation_id;
433 Some(event)
434}
435
436fn detect_event_type(v: &serde_json::Value, ts: u64) -> Option<ObserveEvent> {
437 if let Some(result) = v.get("toolResult") {
442 let tool = super::payload::resolve_tool_name(v).unwrap_or_else(|| "unknown".to_string());
443 let args = super::payload::resolve_tool_args(v);
444 let command = args
445 .as_ref()
446 .and_then(|a| a.get("command"))
447 .and_then(|c| c.as_str());
448 let result_text = result
449 .get("textResultForLlm")
450 .and_then(|t| t.as_str())
451 .map_or_else(|| result.to_string(), String::from);
452 let tokens = result_text.len() / 4;
453 let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
454 let event_type = if is_lctx {
455 "mcp_call"
456 } else if command.is_some() {
457 "shell"
458 } else {
459 "native_tool"
460 };
461 let content = match command {
462 Some(cmd) => format!("$ {cmd}\n{result_text}"),
463 None => result_text,
464 };
465 return Some(ObserveEvent {
466 ts,
467 event_type,
468 tokens,
469 tool_name: Some(tool),
470 detail: command.map(|c| truncate_str(c, 80)),
471 content: Some(cap_content(&content)),
472 model: None,
473 conversation_id: None,
474 });
475 }
476
477 if let Some(result) = v
478 .get("result_json")
479 .or_else(|| v.get("result"))
480 .or_else(|| v.get("tool_response"))
481 .or_else(|| v.get("tool_output"))
482 {
483 let tool = v
484 .get("tool_name")
485 .and_then(|t| t.as_str())
486 .unwrap_or("unknown");
487 let tokens = estimate_tokens_json(result);
488 let content_str = match result {
489 serde_json::Value::String(s) => s.clone(),
490 other => other.to_string(),
491 };
492 return Some(ObserveEvent {
493 ts,
494 event_type: "mcp_call",
495 tokens,
496 tool_name: Some(tool.to_string()),
497 detail: v
498 .get("server_name")
499 .and_then(|s| s.as_str())
500 .map(String::from),
501 content: Some(cap_content(&content_str)),
502 model: None,
503 conversation_id: None,
504 });
505 }
506
507 if let Some(output) = v.get("output") {
508 let cmd = v
509 .get("command")
510 .and_then(|c| c.as_str())
511 .unwrap_or("")
512 .to_string();
513 let tokens = estimate_tokens_value(output);
514 let out_str = match output {
515 serde_json::Value::String(s) => s.clone(),
516 other => other.to_string(),
517 };
518 return Some(ObserveEvent {
519 ts,
520 event_type: "shell",
521 tokens,
522 tool_name: None,
523 detail: Some(truncate_str(&cmd, 80)),
524 content: Some(cap_content(&format!("$ {cmd}\n{out_str}"))),
525 model: None,
526 conversation_id: None,
527 });
528 }
529
530 if v.get("content").is_some() && v.get("file_path").is_some() {
531 let path = v
532 .get("file_path")
533 .and_then(|p| p.as_str())
534 .unwrap_or("")
535 .to_string();
536 let file_content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
537 let tokens = file_content.len() / 4;
538 return Some(ObserveEvent {
539 ts,
540 event_type: "file_read",
541 tokens,
542 tool_name: None,
543 detail: Some(truncate_str(&path, 120)),
544 content: Some(cap_content(file_content)),
545 model: None,
546 conversation_id: None,
547 });
548 }
549
550 if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
551 let has_duration = v.get("duration_ms").is_some();
552 let event_type = if has_duration {
553 "thinking"
554 } else {
555 "agent_response"
556 };
557 let tokens = text.len() / 4;
558 return Some(ObserveEvent {
559 ts,
560 event_type,
561 tokens,
562 tool_name: None,
563 detail: None,
564 content: Some(cap_content(text)),
565 model: None,
566 conversation_id: None,
567 });
568 }
569
570 if let Some(prompt) = v.get("prompt").and_then(|p| p.as_str()) {
571 let tokens = prompt.len() / 4;
572 let mut full = prompt.to_string();
573 if let Some(attachments) = v.get("attachments").and_then(|a| a.as_array())
574 && !attachments.is_empty()
575 {
576 full.push_str(&format!("\n\n[{} attachments]", attachments.len()));
577 for att in attachments {
578 if let Some(name) = att.get("name").and_then(|n| n.as_str()) {
579 full.push_str(&format!("\n - {name}"));
580 }
581 }
582 }
583 return Some(ObserveEvent {
584 ts,
585 event_type: "user_message",
586 tokens,
587 tool_name: None,
588 detail: v
589 .get("attachments")
590 .and_then(|a| a.as_array())
591 .map(|a| format!("{} attachments", a.len())),
592 content: Some(cap_content(&full)),
593 model: None,
594 conversation_id: None,
595 });
596 }
597
598 if v.get("tool_name").is_some() || v.get("tool_input").is_some() {
599 let tool = v
600 .get("tool_name")
601 .and_then(|t| t.as_str())
602 .unwrap_or("unknown")
603 .to_string();
604 let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
605 let tokens = v.get("tool_input").map_or(0, estimate_tokens_json);
606 let input_str = v
607 .get("tool_input")
608 .map(std::string::ToString::to_string)
609 .unwrap_or_default();
610 return Some(ObserveEvent {
611 ts,
612 event_type: if is_lctx { "mcp_call" } else { "native_tool" },
613 tokens,
614 tool_name: Some(tool),
615 detail: None,
616 content: if input_str.is_empty() {
617 None
618 } else {
619 Some(cap_content(&input_str))
620 },
621 model: None,
622 conversation_id: None,
623 });
624 }
625
626 let is_compaction = v.get("compaction").is_some()
636 || v.get("messages_count").is_some()
637 || v.get("hook_event_name")
638 .and_then(|e| e.as_str())
639 .is_some_and(|e| e == "PreCompact")
640 || v.get("event")
641 .and_then(|e| e.as_str())
642 .is_some_and(|e| e == "compaction" || e == "compact");
643 if !is_compaction && v.get("session_id").is_some() {
644 return Some(ObserveEvent {
645 ts,
646 event_type: "session",
647 tokens: 0,
648 tool_name: None,
649 detail: v
650 .get("session_id")
651 .and_then(|s| s.as_str())
652 .map(String::from),
653 content: None,
654 model: None,
655 conversation_id: None,
656 });
657 }
658
659 if is_compaction {
660 return Some(ObserveEvent {
661 ts,
662 event_type: "compaction",
663 tokens: 0,
664 tool_name: None,
665 detail: None,
666 content: None,
667 model: None,
668 conversation_id: None,
669 });
670 }
671
672 None
673}
674
675fn estimate_tokens_json(v: &serde_json::Value) -> usize {
676 match v {
677 serde_json::Value::String(s) => s.len() / 4,
678 _ => v.to_string().len() / 4,
679 }
680}
681
682fn estimate_tokens_value(v: &serde_json::Value) -> usize {
683 match v {
684 serde_json::Value::String(s) => s.len() / 4,
685 _ => v.to_string().len() / 4,
686 }
687}
688
689fn persist_detected_model(model: &str) {
690 if crate::core::model_registry::is_background_model(model) {
691 return;
692 }
693
694 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
695 return;
696 };
697 let path = data_dir.join("detected_model.json");
698 let ts = std::time::SystemTime::now()
699 .duration_since(std::time::UNIX_EPOCH)
700 .unwrap_or_default()
701 .as_secs();
702 let window = model_context_window(model);
703 let payload = serde_json::json!({
704 "model": model,
705 "window_size": window,
706 "detected_at": ts,
707 });
708 if let Ok(json) = serde_json::to_string_pretty(&payload) {
709 let tmp = path.with_extension("tmp");
710 if std::fs::write(&tmp, &json).is_ok() {
711 let _ = std::fs::rename(&tmp, &path);
712 }
713 }
714}
715
716pub fn model_context_window(model: &str) -> usize {
717 crate::core::model_registry::context_window_for_model(model)
718}
719
720pub fn load_detected_model() -> Option<(String, usize)> {
721 let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
722 let path = data_dir.join("detected_model.json");
723 let content = std::fs::read_to_string(&path).ok()?;
724 let v: serde_json::Value = serde_json::from_str(&content).ok()?;
725 let model = v.get("model")?.as_str()?.to_string();
726 let window = v.get("window_size")?.as_u64()? as usize;
727 let detected_at = v.get("detected_at")?.as_u64()?;
728 let now = std::time::SystemTime::now()
729 .duration_since(std::time::UNIX_EPOCH)
730 .unwrap_or_default()
731 .as_secs();
732 if now.saturating_sub(detected_at) > 7200 {
733 return None;
734 }
735 Some((model, window))
736}
737
738fn persist_transcript_path(path: &str, conversation_id: Option<&str>, session_id: Option<&str>) {
739 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
740 return;
741 };
742 let meta_path = data_dir.join("active_transcript.json");
743 let ts = std::time::SystemTime::now()
744 .duration_since(std::time::UNIX_EPOCH)
745 .unwrap_or_default()
746 .as_secs();
747 let payload = serde_json::json!({
748 "transcript_path": path,
749 "conversation_id": conversation_id,
750 "session_id": session_id,
751 "updated_at": ts,
752 });
753 if let Ok(json) = serde_json::to_string_pretty(&payload) {
754 let tmp = meta_path.with_extension("tmp");
755 if std::fs::write(&tmp, &json).is_ok() {
756 let _ = std::fs::rename(&tmp, &meta_path);
757 }
758 }
759}
760
761pub fn load_active_transcript() -> Option<(String, Option<String>)> {
762 let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
763 let path = data_dir.join("active_transcript.json");
764 let content = std::fs::read_to_string(&path).ok()?;
765 let v: serde_json::Value = serde_json::from_str(&content).ok()?;
766 let tp = v.get("transcript_path")?.as_str()?.to_string();
767 let conv = v
771 .get("conversation_id")
772 .and_then(|c| c.as_str())
773 .or_else(|| v.get("session_id").and_then(|s| s.as_str()))
774 .map(String::from);
775 let updated = v.get("updated_at")?.as_u64()?;
776 let now = std::time::SystemTime::now()
777 .duration_since(std::time::UNIX_EPOCH)
778 .unwrap_or_default()
779 .as_secs();
780 if now.saturating_sub(updated) > 7200 {
781 return None;
782 }
783 Some((tp, conv))
784}
785
786fn cap_content(s: &str) -> String {
787 if s.len() <= MAX_CONTENT_CHARS {
788 s.to_string()
789 } else {
790 let truncated = safe_truncate(s, MAX_CONTENT_CHARS);
791 format!("{}…\n\n[truncated: {} total chars]", truncated, s.len())
792 }
793}
794
795fn truncate_str(s: &str, max: usize) -> String {
796 if s.len() <= max {
797 s.to_string()
798 } else {
799 format!("{}...", safe_truncate(s, max))
800 }
801}
802
803fn safe_truncate(s: &str, max: usize) -> &str {
805 if max >= s.len() {
806 return s;
807 }
808 let mut end = max;
809 while end > 0 && !s.is_char_boundary(end) {
810 end -= 1;
811 }
812 &s[..end]
813}
814
815fn append_radar_event(event: &ObserveEvent) {
816 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
817 return;
818 };
819 let radar_path = data_dir.join("context_radar.jsonl");
820
821 if event.event_type == "session"
822 && let Ok(meta) = std::fs::metadata(&radar_path)
823 {
824 const MAX_RADAR_SIZE: u64 = 10 * 1024 * 1024; if meta.len() > MAX_RADAR_SIZE {
826 let prev = data_dir.join("context_radar.prev.jsonl");
827 let _ = std::fs::rename(&radar_path, &prev);
828 }
829 }
830
831 let Ok(line) = serde_json::to_string(event) else {
832 return;
833 };
834
835 use std::fs::OpenOptions;
836 use std::io::Write;
837 if let Ok(mut f) = OpenOptions::new()
838 .create(true)
839 .append(true)
840 .open(&radar_path)
841 {
842 let _ = writeln!(f, "{line}");
843 }
844
845 if event.event_type == "compaction" {
848 write_compaction_marker(&data_dir, event.ts);
849 }
850}
851
852fn write_compaction_marker(data_dir: &std::path::Path, ts: u64) {
855 use std::io::Write;
856 let marker_path = data_dir.join("last_compaction.json");
857 let tmp_path = data_dir.join("last_compaction.json.tmp");
858 let payload = format!(r#"{{"ts":{ts}}}"#);
859 let Ok(mut f) = std::fs::File::create(&tmp_path) else {
860 return;
861 };
862 if f.write_all(payload.as_bytes()).is_err() || f.sync_all().is_err() {
863 let _ = std::fs::remove_file(&tmp_path);
864 return;
865 }
866 drop(f);
867 let _ = std::fs::rename(&tmp_path, &marker_path);
868}
869
870#[must_use]
878pub fn radar_event_count() -> usize {
879 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
880 return 0;
881 };
882 let Ok(file) = std::fs::File::open(data_dir.join("context_radar.jsonl")) else {
883 return 0;
884 };
885 use std::io::{BufRead, BufReader};
886 BufReader::new(file)
887 .lines()
888 .map_while(Result::ok)
889 .filter(|l| !l.trim().is_empty())
890 .count()
891}
892
893#[cfg(test)]
894#[path = "observe_tests.rs"]
895mod tests;