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