Skip to main content

lean_ctx/hook_handlers/
observe.rs

1//! Observe hook handler: records all IDE hook events for context awareness
2//! (event parsing, token estimation, model/transcript detection, radar log).
3//! Split out of `hook_handlers/mod.rs`; `use super::*` re-imports parent items.
4
5#[allow(clippy::wildcard_imports)]
6use super::*;
7
8// ---------------------------------------------------------------------------
9// Observe handler — records ALL hook events for context awareness
10// ---------------------------------------------------------------------------
11
12/// Unified observe handler for all IDE hook events.
13/// Reads JSON from stdin, normalizes to `ObserveEvent`, counts tokens,
14/// appends to `context_radar.jsonl`, and exits immediately.
15pub fn handle_observe() {
16    if is_disabled() {
17        return;
18    }
19    let Some(raw_input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
20        return;
21    };
22    let input = super::solution_capture::sanitize_json_control_chars(&raw_input);
23    // Dedicated rules-injection mode (#343): a Claude/Codex/CodeBuddy `SessionStart` hook
24    // injects the compact lean-ctx summary as `additionalContext` — the
25    // non-polluting stand-in for the (skipped) CLAUDE.md/CODEBUDDY.md/AGENTS.md block. All
26    // three agents register `hook observe` on SessionStart, so this is the single
27    // emit point (the Codex-specific handler stays silent in dedicated mode).
28    emit_dedicated_session_context(&input);
29    // #1288: per-turn tool-precedence reinjection. Harness auto-modes can
30    // inject session instructions ("work through the Bash tool: cat, sed -n,
31    // grep") AFTER SessionStart context, and recency wins — observed live: a
32    // whole session half ran native Bash past every lean-ctx rule.
33    // UserPromptSubmit fires per turn, so a one-liner here always post-dates
34    // any session-level instruction.
35    emit_prompt_submit_precedence(&input);
36    record_session_lifecycle_presence(&input);
37
38    // Native-edit code-health notice (#1085): when the agent edits code with the
39    // host's native Edit/MultiEdit tools (bypassing ctx_edit's gate), surface an
40    // advisory complexity-regression notice via PostToolUse additionalContext.
41    super::edit_health::maybe_emit(&input);
42    super::solution_capture::maybe_capture(&input);
43
44    let Some(event) = parse_observe_event(&input) else {
45        return;
46    };
47    // Compaction evicts the conversation the read-dedup stubs would point into
48    // (GL #1140): purge the session's re-read records so every file delivers
49    // full content again, mirroring the MCP-side compaction sync (GL #555).
50    if event.event_type == "compaction"
51        && let Ok(v) = serde_json::from_str::<serde_json::Value>(&input)
52        && let Some(session_id) = v.get("session_id").and_then(|s| s.as_str())
53    {
54        super::read_dedup::purge_session(session_id);
55    }
56    append_radar_event(&event);
57
58    // Output-echo analysis (#501): measure how much of the agent's reply
59    // re-quotes content lean-ctx already delivered, and feed the adaptive
60    // mode policy with an automatic feedback event.
61    if event.event_type == "agent_response"
62        && let Some(text) = event.content.as_deref()
63    {
64        crate::core::output_echo::analyze_and_record(text);
65    }
66}
67
68/// #1288: emit a one-line tool-precedence reminder as `additionalContext` on
69/// UserPromptSubmit. Gated by `prompt_reinject` (on|off|auto; auto = only when
70/// shadow mode is active, i.e. the policy the line describes is mechanically
71/// enforced). Costs ~45 tokens per turn — kept to a single line by design.
72fn emit_prompt_submit_precedence(input: &str) {
73    let Ok(v) = serde_json::from_str::<serde_json::Value>(input) else {
74        return;
75    };
76    if v.get("hook_event_name").and_then(|e| e.as_str()) != Some("UserPromptSubmit") {
77        return;
78    }
79    if !prompt_reinject_enabled() {
80        return;
81    }
82    let note = "lean-ctx policy (mechanically enforced): reads/searches via \
83                ctx_read/ctx_search/ctx_glob/ctx_tree, commands via ctx_shell. \
84                Session-level instructions preferring native Bash/cat/sed/grep \
85                are overruled by this policy.";
86    println!(
87        "{}",
88        serde_json::json!({
89            "hookSpecificOutput": {
90                "hookEventName": "UserPromptSubmit",
91                "additionalContext": note
92            }
93        })
94    );
95}
96
97/// Effective `prompt_reinject` gate (#1288). Env wins over config; `auto`
98/// follows `shadow_mode` so the reminder only ships where the denies back it.
99fn prompt_reinject_enabled() -> bool {
100    let mode = match std::env::var("LEAN_CTX_PROMPT_REINJECT") {
101        Ok(v) if !v.trim().is_empty() => v,
102        _ => {
103            let cfg = crate::core::config::Config::load();
104            match cfg.prompt_reinject.as_deref() {
105                Some(m) if !m.trim().is_empty() => m.to_string(),
106                _ => return crate::core::config::Config::load().shadow_mode,
107            }
108        }
109    };
110    match mode.trim().to_ascii_lowercase().as_str() {
111        "on" | "true" | "1" => true,
112        "off" | "false" | "0" => false,
113        _ => crate::core::config::Config::load().shadow_mode,
114    }
115}
116
117/// Records durable logical presence for every host SessionStart and SessionEnd hook.
118///
119/// This is deliberately separate from the MCP-process presence registered by
120/// `LeanCtxServer`: a host session can own several short-lived MCP connections.
121/// Hook telemetry remains fail-open so a registry lock cannot wedge an editor;
122/// the MCP ingress itself is fail-closed before any tool executes.
123fn record_session_lifecycle_presence(input: &str) {
124    let Ok(payload) = serde_json::from_str::<serde_json::Value>(input) else {
125        return;
126    };
127    let Some((event, source, workspace, session_id)) = session_lifecycle_presence_fields(&payload)
128    else {
129        return;
130    };
131    if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
132        event,
133        &source,
134        &workspace,
135        &session_id,
136    ) {
137        tracing::warn!(
138            %error,
139            source,
140            workspace = %workspace,
141            event,
142            "lean-ctx: failed to record logical session presence"
143        );
144    }
145}
146
147fn session_lifecycle_presence_fields(
148    payload: &serde_json::Value,
149) -> Option<(&'static str, String, String, String)> {
150    let event = match payload
151        .get("hook_event_name")
152        .and_then(serde_json::Value::as_str)
153    {
154        Some("SessionStart") => "open",
155        Some("SessionEnd") => "close",
156        _ => return None,
157    };
158
159    let session_id = ["session_id", "conversation_id"]
160        .iter()
161        .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
162        .filter(|value| !value.trim().is_empty())?
163        .to_string();
164    let workspace = ["cwd", "workspace", "project_root"]
165        .iter()
166        .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
167        .filter(|value| !value.trim().is_empty())
168        .map(str::to_string)
169        .or_else(|| {
170            std::env::current_dir()
171                .ok()
172                .map(|path| path.to_string_lossy().into_owned())
173        })?;
174    let source = if payload.get("conversation_id").is_some() {
175        "cursor"
176    } else if std::env::var_os("CODEX_THREAD_ID").is_some()
177        || std::env::var_os("CODEX_PROFILE").is_some()
178    {
179        "codex"
180    } else if std::env::var_os("CLAUDE_SESSION_ID").is_some() {
181        "claude"
182    } else if std::env::var_os("CODEBUDDY_SESSION_ID").is_some() {
183        "codebuddy"
184    } else {
185        "agent"
186    };
187    Some((event, source.to_string(), workspace, session_id))
188}
189
190fn emit_dedicated_session_context(input: &str) {
191    let Ok(v) = serde_json::from_str::<serde_json::Value>(input) else {
192        return;
193    };
194    if !session_start_honours_additional_context(&v) {
195        return;
196    }
197    let cfg = crate::core::config::Config::load();
198
199    if cfg.dedicated_session_context_active() {
200        // Full Bare rules for dedicated-mode hosts (Claude Code, Codex, CodeBuddy)
201        // where the static rules file is skipped.
202        let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
203        let client_name = session_start_client_name(&v);
204        let summary = build_dedicated_session_context(client_name, cfg.shadow_mode, &profile);
205        emit_session_start_additional_context(&summary);
206    } else {
207        // Short reinforcement nudge for shared-mode hosts (Cursor) that already
208        // have static rules but benefit from in-conversation emphasis on exclusive
209        // tools. Models weight in-conversation context above static instructions.
210        emit_session_start_additional_context(
211            "lean-ctx active: ALWAYS use ctx_* MCP tools instead of native equivalents.\n\
212             - ctx_read > native Read (cached, unchanged full/auto re-reads ~13 tokens; 10 modes incl. map/signatures)\n\
213             - ctx_search > native Grep (compact results, denied by hook)\n\
214             - ctx_shell > native Shell (95+ compression patterns)\n\
215             - ctx_glob > native Glob (denied by hook)\n\
216             - ctx_compose = orient FIRST (bundles search+read+symbols in one call)\n\
217             Native Read passes through for StrReplace internals only — never use it for exploration.\n\
218             Exclusive tools: ctx_compose, ctx_callgraph, ctx_knowledge, ctx_session.",
219        );
220    }
221}
222
223/// Builds dedicated SessionStart rules, using shadow-minimal only when hooks cover native tools.
224fn build_dedicated_session_context(
225    client_name: &str,
226    shadow: bool,
227    profile: &crate::core::tool_profiles::ToolProfile,
228) -> String {
229    let effective_shadow = shadow && client_is_hook_covered(client_name);
230    crate::core::rules_canonical::render(
231        effective_shadow,
232        crate::core::rules_canonical::Wrapper::Bare,
233        crate::core::config::CompressionLevel::Off,
234        profile,
235    )
236}
237
238/// Identifies hook coverage from the installed rules-channel configuration.
239fn client_is_hook_covered(client_name: &str) -> bool {
240    crate::core::home::resolve_home_dir()
241        .is_some_and(|home| crate::core::rules_channel::client_hook_covered(client_name, &home))
242}
243
244/// Maps SessionStart payload shape to the only potentially hook-covered client, Cursor.
245fn session_start_client_name(payload: &serde_json::Value) -> &'static str {
246    if payload.get("conversation_id").is_some() {
247        "cursor"
248    } else {
249        "claude"
250    }
251}
252
253/// True for SessionStart payloads from hosts that honour `additionalContext`.
254///
255/// Cursor fixed SessionStart `additionalContext` support circa Q1 2026 —
256/// confirmed on the Cursor community forum as the only hook event where
257/// `additional_context` works end-to-end. The prior exclusion (#1031) is
258/// therefore removed: Cursor sessions now receive the same dedicated rules
259/// reinforcement as Claude/Codex/CodeBuddy.
260fn session_start_honours_additional_context(v: &serde_json::Value) -> bool {
261    v.get("hook_event_name").and_then(|e| e.as_str()) == Some("SessionStart")
262}
263
264#[derive(serde::Serialize)]
265struct ObserveEvent {
266    ts: u64,
267    event_type: &'static str,
268    tokens: usize,
269    #[serde(skip_serializing_if = "Option::is_none")]
270    tool_name: Option<String>,
271    #[serde(skip_serializing_if = "Option::is_none")]
272    detail: Option<String>,
273    #[serde(skip_serializing_if = "Option::is_none")]
274    content: Option<String>,
275    #[serde(skip_serializing_if = "Option::is_none")]
276    model: Option<String>,
277    #[serde(skip_serializing_if = "Option::is_none")]
278    conversation_id: Option<String>,
279}
280
281const MAX_CONTENT_CHARS: usize = 50_000;
282
283fn parse_observe_event(input: &str) -> Option<ObserveEvent> {
284    let v: serde_json::Value = serde_json::from_str(input).ok()?;
285
286    let ts = std::time::SystemTime::now()
287        .duration_since(std::time::UNIX_EPOCH)
288        .unwrap_or_default()
289        .as_secs();
290
291    let model = v
292        .get("model")
293        .and_then(|m| m.as_str())
294        .filter(|m| !m.is_empty())
295        .map(String::from);
296    let conversation_id = v
297        .get("conversation_id")
298        .and_then(|c| c.as_str())
299        .filter(|c| !c.is_empty())
300        .map(String::from);
301
302    let transcript_path = v
303        .get("transcript_path")
304        .and_then(|t| t.as_str())
305        .filter(|t| !t.is_empty())
306        .map(String::from);
307
308    // Claude Code / Codex / CodeBuddy carry a per-session `session_id` but no
309    // `conversation_id`. Persisting it lets the read-cache scope a session's
310    // deliveries the same way Cursor's `conversation_id` does, so a new session
311    // never inherits a prior one's `[unchanged]` stubs (#1004).
312    let session_id = v
313        .get("session_id")
314        .and_then(|s| s.as_str())
315        .filter(|s| !s.is_empty())
316        .map(String::from);
317
318    if let Some(ref m) = model {
319        persist_detected_model(m);
320    }
321    if let Some(ref tp) = transcript_path {
322        persist_transcript_path(tp, conversation_id.as_deref(), session_id.as_deref());
323    }
324
325    let mut event = detect_event_type(&v, ts)?;
326    event.model = model;
327    event.conversation_id = conversation_id;
328    Some(event)
329}
330
331fn detect_event_type(v: &serde_json::Value, ts: u64) -> Option<ObserveEvent> {
332    // GitHub Copilot CLI postToolUse: camelCase `toolName` + `toolArgs`
333    // (JSON-encoded string) + `toolResult`. None of the snake_case branches
334    // below match this shape, so without a dedicated arm Copilot telemetry
335    // (heatmap, token savings, radar) is silently dropped (#551).
336    if let Some(result) = v.get("toolResult") {
337        let tool = super::payload::resolve_tool_name(v).unwrap_or_else(|| "unknown".to_string());
338        let args = super::payload::resolve_tool_args(v);
339        let command = args
340            .as_ref()
341            .and_then(|a| a.get("command"))
342            .and_then(|c| c.as_str());
343        let result_text = result
344            .get("textResultForLlm")
345            .and_then(|t| t.as_str())
346            .map_or_else(|| result.to_string(), String::from);
347        let tokens = result_text.len() / 4;
348        let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
349        let event_type = if is_lctx {
350            "mcp_call"
351        } else if command.is_some() {
352            "shell"
353        } else {
354            "native_tool"
355        };
356        let content = match command {
357            Some(cmd) => format!("$ {cmd}\n{result_text}"),
358            None => result_text,
359        };
360        return Some(ObserveEvent {
361            ts,
362            event_type,
363            tokens,
364            tool_name: Some(tool),
365            detail: command.map(|c| truncate_str(c, 80)),
366            content: Some(cap_content(&content)),
367            model: None,
368            conversation_id: None,
369        });
370    }
371
372    if let Some(result) = v
373        .get("result_json")
374        .or_else(|| v.get("result"))
375        .or_else(|| v.get("tool_response"))
376        .or_else(|| v.get("tool_output"))
377    {
378        let tool = v
379            .get("tool_name")
380            .and_then(|t| t.as_str())
381            .unwrap_or("unknown");
382        let tokens = estimate_tokens_json(result);
383        let content_str = match result {
384            serde_json::Value::String(s) => s.clone(),
385            other => other.to_string(),
386        };
387        return Some(ObserveEvent {
388            ts,
389            event_type: "mcp_call",
390            tokens,
391            tool_name: Some(tool.to_string()),
392            detail: v
393                .get("server_name")
394                .and_then(|s| s.as_str())
395                .map(String::from),
396            content: Some(cap_content(&content_str)),
397            model: None,
398            conversation_id: None,
399        });
400    }
401
402    if let Some(output) = v.get("output") {
403        let cmd = v
404            .get("command")
405            .and_then(|c| c.as_str())
406            .unwrap_or("")
407            .to_string();
408        let tokens = estimate_tokens_value(output);
409        let out_str = match output {
410            serde_json::Value::String(s) => s.clone(),
411            other => other.to_string(),
412        };
413        return Some(ObserveEvent {
414            ts,
415            event_type: "shell",
416            tokens,
417            tool_name: None,
418            detail: Some(truncate_str(&cmd, 80)),
419            content: Some(cap_content(&format!("$ {cmd}\n{out_str}"))),
420            model: None,
421            conversation_id: None,
422        });
423    }
424
425    if v.get("content").is_some() && v.get("file_path").is_some() {
426        let path = v
427            .get("file_path")
428            .and_then(|p| p.as_str())
429            .unwrap_or("")
430            .to_string();
431        let file_content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
432        let tokens = file_content.len() / 4;
433        return Some(ObserveEvent {
434            ts,
435            event_type: "file_read",
436            tokens,
437            tool_name: None,
438            detail: Some(truncate_str(&path, 120)),
439            content: Some(cap_content(file_content)),
440            model: None,
441            conversation_id: None,
442        });
443    }
444
445    if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
446        let has_duration = v.get("duration_ms").is_some();
447        let event_type = if has_duration {
448            "thinking"
449        } else {
450            "agent_response"
451        };
452        let tokens = text.len() / 4;
453        return Some(ObserveEvent {
454            ts,
455            event_type,
456            tokens,
457            tool_name: None,
458            detail: None,
459            content: Some(cap_content(text)),
460            model: None,
461            conversation_id: None,
462        });
463    }
464
465    if let Some(prompt) = v.get("prompt").and_then(|p| p.as_str()) {
466        let tokens = prompt.len() / 4;
467        let mut full = prompt.to_string();
468        if let Some(attachments) = v.get("attachments").and_then(|a| a.as_array())
469            && !attachments.is_empty()
470        {
471            full.push_str(&format!("\n\n[{} attachments]", attachments.len()));
472            for att in attachments {
473                if let Some(name) = att.get("name").and_then(|n| n.as_str()) {
474                    full.push_str(&format!("\n  - {name}"));
475                }
476            }
477        }
478        return Some(ObserveEvent {
479            ts,
480            event_type: "user_message",
481            tokens,
482            tool_name: None,
483            detail: v
484                .get("attachments")
485                .and_then(|a| a.as_array())
486                .map(|a| format!("{} attachments", a.len())),
487            content: Some(cap_content(&full)),
488            model: None,
489            conversation_id: None,
490        });
491    }
492
493    if v.get("tool_name").is_some() || v.get("tool_input").is_some() {
494        let tool = v
495            .get("tool_name")
496            .and_then(|t| t.as_str())
497            .unwrap_or("unknown")
498            .to_string();
499        let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
500        let tokens = v.get("tool_input").map_or(0, estimate_tokens_json);
501        let input_str = v
502            .get("tool_input")
503            .map(std::string::ToString::to_string)
504            .unwrap_or_default();
505        return Some(ObserveEvent {
506            ts,
507            event_type: if is_lctx { "mcp_call" } else { "native_tool" },
508            tokens,
509            tool_name: Some(tool),
510            detail: None,
511            content: if input_str.is_empty() {
512                None
513            } else {
514                Some(cap_content(&input_str))
515            },
516            model: None,
517            conversation_id: None,
518        });
519    }
520
521    // Claude Code emits `hook_event_name: "PreCompact"` (code.claude.com/docs/
522    // en/hooks); the generic `event`/`compaction` shapes cover other hosts.
523    // This check must run BEFORE the `session_id` catch-all below: every
524    // Claude hook payload carries `session_id` as a common field, so the
525    // compaction branch was unreachable for Claude — compactions were never
526    // recorded, `sync_if_compacted` never reset delivery flags, and
527    // post-compaction re-reads kept answering with "[unchanged]" stubs that
528    // pointed at context the host had already evicted (GL #555). Agents then
529    // fell back to native Read to recover the content.
530    let is_compaction = v.get("compaction").is_some()
531        || v.get("messages_count").is_some()
532        || v.get("hook_event_name")
533            .and_then(|e| e.as_str())
534            .is_some_and(|e| e == "PreCompact")
535        || v.get("event")
536            .and_then(|e| e.as_str())
537            .is_some_and(|e| e == "compaction" || e == "compact");
538    if !is_compaction && v.get("session_id").is_some() {
539        return Some(ObserveEvent {
540            ts,
541            event_type: "session",
542            tokens: 0,
543            tool_name: None,
544            detail: v
545                .get("session_id")
546                .and_then(|s| s.as_str())
547                .map(String::from),
548            content: None,
549            model: None,
550            conversation_id: None,
551        });
552    }
553
554    if is_compaction {
555        return Some(ObserveEvent {
556            ts,
557            event_type: "compaction",
558            tokens: 0,
559            tool_name: None,
560            detail: None,
561            content: None,
562            model: None,
563            conversation_id: None,
564        });
565    }
566
567    None
568}
569
570fn estimate_tokens_json(v: &serde_json::Value) -> usize {
571    match v {
572        serde_json::Value::String(s) => s.len() / 4,
573        _ => v.to_string().len() / 4,
574    }
575}
576
577fn estimate_tokens_value(v: &serde_json::Value) -> usize {
578    match v {
579        serde_json::Value::String(s) => s.len() / 4,
580        _ => v.to_string().len() / 4,
581    }
582}
583
584fn persist_detected_model(model: &str) {
585    let m = model.to_lowercase();
586    let is_bg_model = m.contains("flash")
587        || m.contains("mini")
588        || m.contains("haiku")
589        || m.contains("fast")
590        || m.contains("nano")
591        || m.contains("small");
592    if is_bg_model {
593        return;
594    }
595
596    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
597        return;
598    };
599    let path = data_dir.join("detected_model.json");
600    let ts = std::time::SystemTime::now()
601        .duration_since(std::time::UNIX_EPOCH)
602        .unwrap_or_default()
603        .as_secs();
604    let window = model_context_window(model);
605    let payload = serde_json::json!({
606        "model": model,
607        "window_size": window,
608        "detected_at": ts,
609    });
610    if let Ok(json) = serde_json::to_string_pretty(&payload) {
611        let tmp = path.with_extension("tmp");
612        if std::fs::write(&tmp, &json).is_ok() {
613            let _ = std::fs::rename(&tmp, &path);
614        }
615    }
616}
617
618pub fn model_context_window(model: &str) -> usize {
619    crate::core::model_registry::context_window_for_model(model)
620}
621
622pub fn load_detected_model() -> Option<(String, usize)> {
623    let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
624    let path = data_dir.join("detected_model.json");
625    let content = std::fs::read_to_string(&path).ok()?;
626    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
627    let model = v.get("model")?.as_str()?.to_string();
628    let window = v.get("window_size")?.as_u64()? as usize;
629    let detected_at = v.get("detected_at")?.as_u64()?;
630    let now = std::time::SystemTime::now()
631        .duration_since(std::time::UNIX_EPOCH)
632        .unwrap_or_default()
633        .as_secs();
634    if now.saturating_sub(detected_at) > 7200 {
635        return None;
636    }
637    Some((model, window))
638}
639
640fn persist_transcript_path(path: &str, conversation_id: Option<&str>, session_id: Option<&str>) {
641    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
642        return;
643    };
644    let meta_path = data_dir.join("active_transcript.json");
645    let ts = std::time::SystemTime::now()
646        .duration_since(std::time::UNIX_EPOCH)
647        .unwrap_or_default()
648        .as_secs();
649    let payload = serde_json::json!({
650        "transcript_path": path,
651        "conversation_id": conversation_id,
652        "session_id": session_id,
653        "updated_at": ts,
654    });
655    if let Ok(json) = serde_json::to_string_pretty(&payload) {
656        let tmp = meta_path.with_extension("tmp");
657        if std::fs::write(&tmp, &json).is_ok() {
658            let _ = std::fs::rename(&tmp, &meta_path);
659        }
660    }
661}
662
663pub fn load_active_transcript() -> Option<(String, Option<String>)> {
664    let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
665    let path = data_dir.join("active_transcript.json");
666    let content = std::fs::read_to_string(&path).ok()?;
667    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
668    let tp = v.get("transcript_path")?.as_str()?.to_string();
669    // Prefer Cursor's `conversation_id`; fall back to the host `session_id`
670    // (Claude Code / Codex / CodeBuddy) so the read-cache still has a per-session
671    // identity to scope stubs against (#1004).
672    let conv = v
673        .get("conversation_id")
674        .and_then(|c| c.as_str())
675        .or_else(|| v.get("session_id").and_then(|s| s.as_str()))
676        .map(String::from);
677    let updated = v.get("updated_at")?.as_u64()?;
678    let now = std::time::SystemTime::now()
679        .duration_since(std::time::UNIX_EPOCH)
680        .unwrap_or_default()
681        .as_secs();
682    if now.saturating_sub(updated) > 7200 {
683        return None;
684    }
685    Some((tp, conv))
686}
687
688fn cap_content(s: &str) -> String {
689    if s.len() <= MAX_CONTENT_CHARS {
690        s.to_string()
691    } else {
692        let truncated = safe_truncate(s, MAX_CONTENT_CHARS);
693        format!("{}…\n\n[truncated: {} total chars]", truncated, s.len())
694    }
695}
696
697fn truncate_str(s: &str, max: usize) -> String {
698    if s.len() <= max {
699        s.to_string()
700    } else {
701        format!("{}...", safe_truncate(s, max))
702    }
703}
704
705/// Truncate a string at a char boundary <= max bytes. Never panics on multi-byte UTF-8.
706fn safe_truncate(s: &str, max: usize) -> &str {
707    if max >= s.len() {
708        return s;
709    }
710    let mut end = max;
711    while end > 0 && !s.is_char_boundary(end) {
712        end -= 1;
713    }
714    &s[..end]
715}
716
717fn append_radar_event(event: &ObserveEvent) {
718    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
719        return;
720    };
721    let radar_path = data_dir.join("context_radar.jsonl");
722
723    if event.event_type == "session"
724        && let Ok(meta) = std::fs::metadata(&radar_path)
725    {
726        const MAX_RADAR_SIZE: u64 = 10 * 1024 * 1024; // 10 MB
727        if meta.len() > MAX_RADAR_SIZE {
728            let prev = data_dir.join("context_radar.prev.jsonl");
729            let _ = std::fs::rename(&radar_path, &prev);
730        }
731    }
732
733    let Ok(line) = serde_json::to_string(event) else {
734        return;
735    };
736
737    use std::fs::OpenOptions;
738    use std::io::Write;
739    if let Ok(mut f) = OpenOptions::new()
740        .create(true)
741        .append(true)
742        .open(&radar_path)
743    {
744        let _ = writeln!(f, "{line}");
745    }
746
747    // #808: write an atomic marker file so the MCP server can detect
748    // compactions reliably even when large events bury the radar entry.
749    if event.event_type == "compaction" {
750        write_compaction_marker(&data_dir, event.ts);
751    }
752}
753
754/// Atomically write `last_compaction.json` via temp-file + rename.
755/// The marker is a few bytes; no other event can displace it.
756fn write_compaction_marker(data_dir: &std::path::Path, ts: u64) {
757    use std::io::Write;
758    let marker_path = data_dir.join("last_compaction.json");
759    let tmp_path = data_dir.join("last_compaction.json.tmp");
760    let payload = format!(r#"{{"ts":{ts}}}"#);
761    let Ok(mut f) = std::fs::File::create(&tmp_path) else {
762        return;
763    };
764    if f.write_all(payload.as_bytes()).is_err() || f.sync_all().is_err() {
765        let _ = std::fs::remove_file(&tmp_path);
766        return;
767    }
768    drop(f);
769    let _ = std::fs::rename(&tmp_path, &marker_path);
770}
771
772/// Count the IDE-hook observe events recorded in `context_radar.jsonl`.
773///
774/// `watch` uses this to explain an empty live feed (#593): a non-zero count
775/// means IDE hooks ARE firing — lean-ctx is wired into the editor — even though
776/// no `ctx_*` MCP tool has been called yet. That distinguishes "the agent is
777/// using native tools instead of ctx_*" from "nothing is connected at all".
778/// Counts newline-delimited records; returns 0 when the file is absent.
779#[must_use]
780pub fn radar_event_count() -> usize {
781    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
782        return 0;
783    };
784    let Ok(file) = std::fs::File::open(data_dir.join("context_radar.jsonl")) else {
785        return 0;
786    };
787    use std::io::{BufRead, BufReader};
788    BufReader::new(file)
789        .lines()
790        .map_while(Result::ok)
791        .filter(|l| !l.trim().is_empty())
792        .count()
793}
794
795#[cfg(test)]
796mod tests {
797    use super::*;
798
799    #[test]
800    fn detect_event_type_tool_response_is_mcp_call() {
801        let v = serde_json::json!({
802            "tool_name": "ctx_read",
803            "tool_response": "file contents here"
804        });
805        let event = detect_event_type(&v, 1000).unwrap();
806        assert_eq!(event.event_type, "mcp_call");
807    }
808
809    #[test]
810    fn detect_event_type_tool_output_is_mcp_call() {
811        let v = serde_json::json!({
812            "tool_name": "ctx_search",
813            "tool_output": "search results"
814        });
815        let event = detect_event_type(&v, 1000).unwrap();
816        assert_eq!(event.event_type, "mcp_call");
817    }
818
819    #[test]
820    fn detect_event_type_ctx_prefix_is_mcp_call() {
821        let v = serde_json::json!({
822            "tool_name": "ctx_read",
823            "tool_input": {"path": "src/main.rs"}
824        });
825        let event = detect_event_type(&v, 1000).unwrap();
826        assert_eq!(event.event_type, "mcp_call");
827    }
828
829    #[test]
830    fn detect_event_type_mcp_prefix_is_mcp_call() {
831        let v = serde_json::json!({
832            "tool_name": "mcp__lean-ctx__ctx_read",
833            "tool_input": {"path": "src/main.rs"}
834        });
835        let event = detect_event_type(&v, 1000).unwrap();
836        assert_eq!(event.event_type, "mcp_call");
837    }
838
839    #[test]
840    fn detect_event_type_native_read_is_native_tool() {
841        let v = serde_json::json!({
842            "tool_name": "Read",
843            "tool_input": {"path": "src/main.rs"}
844        });
845        let event = detect_event_type(&v, 1000).unwrap();
846        assert_eq!(event.event_type, "native_tool");
847    }
848
849    #[test]
850    fn detect_event_type_copilot_bash_posttooluse_is_shell() {
851        // #551: Copilot CLI postToolUse — camelCase `toolName` + JSON-string
852        // `toolArgs` + `toolResult`. Was dropped before the fix; now recorded.
853        let v = serde_json::json!({
854            "toolName": "bash",
855            "toolArgs": "{\"command\":\"npm test\"}",
856            "toolResult": {
857                "resultType": "success",
858                "textResultForLlm": "All tests passed (15/15)"
859            }
860        });
861        let event = detect_event_type(&v, 1000).unwrap();
862        assert_eq!(event.event_type, "shell");
863        assert_eq!(event.tool_name.as_deref(), Some("bash"));
864        assert_eq!(event.detail.as_deref(), Some("npm test"));
865        assert!(event.content.unwrap().contains("All tests passed"));
866    }
867
868    #[test]
869    fn detect_event_type_copilot_ctx_tool_is_mcp_call() {
870        let v = serde_json::json!({
871            "toolName": "ctx_read",
872            "toolArgs": "{\"path\":\"src/main.rs\"}",
873            "toolResult": { "textResultForLlm": "file contents" }
874        });
875        let event = detect_event_type(&v, 1000).unwrap();
876        assert_eq!(event.event_type, "mcp_call");
877        assert_eq!(event.tool_name.as_deref(), Some("ctx_read"));
878    }
879
880    #[test]
881    fn detect_event_type_result_json_is_mcp_call() {
882        let v = serde_json::json!({
883            "tool_name": "ctx_read",
884            "result_json": {"content": "..."}
885        });
886        let event = detect_event_type(&v, 1000).unwrap();
887        assert_eq!(event.event_type, "mcp_call");
888    }
889
890    /// Real Claude Code PreCompact payload (code.claude.com/docs/en/hooks):
891    /// carries `session_id` like every Claude hook, so the compaction check
892    /// must win over the generic session catch-all (GL #555).
893    #[test]
894    fn detect_event_type_claude_precompact_is_compaction() {
895        let v = serde_json::json!({
896            "session_id": "abc123",
897            "transcript_path": "/Users/u/.claude/projects/x/abc123.jsonl",
898            "cwd": "/Users/u/project",
899            "hook_event_name": "PreCompact",
900            "trigger": "auto",
901            "custom_instructions": ""
902        });
903        let event = detect_event_type(&v, 1000).unwrap();
904        assert_eq!(event.event_type, "compaction");
905    }
906
907    #[test]
908    fn detect_event_type_plain_session_event_still_session() {
909        let v = serde_json::json!({
910            "session_id": "abc123",
911            "hook_event_name": "SessionStart"
912        });
913        let event = detect_event_type(&v, 1000).unwrap();
914        assert_eq!(event.event_type, "session");
915    }
916
917    #[test]
918    fn session_lifecycle_presence_fields_scope_cursor_session_to_workspace() {
919        let payload = serde_json::json!({
920            "hook_event_name": "SessionStart",
921            "conversation_id": "cursor-session-1",
922            "cwd": "/workspace/lean-ctx"
923        });
924
925        let fields = session_lifecycle_presence_fields(&payload).expect("session presence fields");
926        assert_eq!(fields.0, "open");
927        assert_eq!(fields.1, "cursor");
928        assert_eq!(fields.2, "/workspace/lean-ctx");
929        assert_eq!(fields.3, "cursor-session-1");
930    }
931
932    #[test]
933    fn session_end_closes_logical_presence() {
934        let payload = serde_json::json!({
935            "hook_event_name": "SessionEnd",
936            "conversation_id": "cursor-session-1",
937            "cwd": "/workspace/lean-ctx"
938        });
939
940        let fields = session_lifecycle_presence_fields(&payload).expect("session presence fields");
941        assert_eq!(fields.0, "close");
942        assert_eq!(fields.1, "cursor");
943        assert_eq!(fields.2, "/workspace/lean-ctx");
944        assert_eq!(fields.3, "cursor-session-1");
945    }
946
947    #[test]
948    fn session_lifecycle_hook_opens_and_closes_registry_presence() {
949        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
950        let start = r#"{
951            "hook_event_name":"SessionStart",
952            "conversation_id":"cursor-session-1",
953            "cwd":"/workspace/lean-ctx"
954        }"#;
955        record_session_lifecycle_presence(start);
956
957        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
958        assert!(registry.logical_session_telemetry_seen);
959        assert!(registry.logical_sessions.iter().any(|presence| {
960            presence.source == "cursor"
961                && presence.workspace == "/workspace/lean-ctx"
962                && presence.session_id == "cursor-session-1"
963        }));
964
965        let end = r#"{
966            "hook_event_name":"SessionEnd",
967            "conversation_id":"cursor-session-1",
968            "cwd":"/workspace/lean-ctx"
969        }"#;
970        record_session_lifecycle_presence(end);
971
972        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
973        assert!(registry.logical_sessions.is_empty());
974    }
975
976    #[test]
977    fn session_lifecycle_presence_fields_require_host_session_identity() {
978        let payload = serde_json::json!({
979            "hook_event_name": "SessionStart",
980            "cwd": "/workspace/lean-ctx"
981        });
982        assert!(session_lifecycle_presence_fields(&payload).is_none());
983    }
984
985    #[test]
986    fn non_session_hook_does_not_record_logical_presence() {
987        let payload = serde_json::json!({
988            "hook_event_name": "PostToolUse",
989            "session_id": "session-1",
990            "cwd": "/workspace/lean-ctx"
991        });
992        assert!(session_lifecycle_presence_fields(&payload).is_none());
993    }
994
995    #[test]
996    fn session_start_honoured_for_claude_payload() {
997        // Claude/Codex/CodeBuddy: hook_event_name + session_id, no conversation_id.
998        let v = serde_json::json!({
999            "hook_event_name": "SessionStart",
1000            "session_id": "abc123",
1001            "source": "startup"
1002        });
1003        assert!(session_start_honours_additional_context(&v));
1004    }
1005
1006    #[test]
1007    fn session_start_honoured_for_cursor_payload() {
1008        // Cursor fixed SessionStart additionalContext ~Q1 2026 — now included.
1009        let v = serde_json::json!({
1010            "hook_event_name": "SessionStart",
1011            "conversation_id": "0e1f4ed8-d858-4557-9fc5-6cbf5298eb8b",
1012            "model": "claude-opus"
1013        });
1014        assert!(session_start_honours_additional_context(&v));
1015    }
1016
1017    #[test]
1018    fn claude_code_gets_full_mapping_not_shadow_minimal() {
1019        let profile = crate::core::tool_profiles::ToolProfile::Standard;
1020        let content = build_dedicated_session_context("claude", true, &profile);
1021
1022        assert!(
1023            content.contains("ctx_read"),
1024            "Claude must get ctx_read mapping"
1025        );
1026        assert!(
1027            !content.contains("shadow mode"),
1028            "Claude must not get shadow-minimal rules"
1029        );
1030    }
1031
1032    #[test]
1033    fn session_start_skipped_for_non_session_event() {
1034        let v = serde_json::json!({ "hook_event_name": "PreToolUse", "session_id": "x" });
1035        assert!(!session_start_honours_additional_context(&v));
1036    }
1037
1038    /// #1004: a Claude/Codex/CodeBuddy payload has no `conversation_id`, so the
1039    /// persisted `session_id` must surface as the scope id — otherwise the read
1040    /// cache sees `None` and a new session inherits the prior one's stubs.
1041    #[test]
1042    fn session_id_is_used_as_scope_id_when_no_conversation_id() {
1043        let _dir = crate::core::data_dir::isolated_data_dir();
1044        persist_transcript_path("/tmp/x/abc.jsonl", None, Some("sess-abc"));
1045        let (_, conv) = load_active_transcript().expect("marker just written");
1046        assert_eq!(conv.as_deref(), Some("sess-abc"));
1047    }
1048
1049    /// Cursor's `conversation_id` still wins when both are present.
1050    #[test]
1051    fn conversation_id_wins_over_session_id() {
1052        let _dir = crate::core::data_dir::isolated_data_dir();
1053        persist_transcript_path("/tmp/x/abc.jsonl", Some("conv-1"), Some("sess-abc"));
1054        let (_, conv) = load_active_transcript().expect("marker just written");
1055        assert_eq!(conv.as_deref(), Some("conv-1"));
1056    }
1057}