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