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
65    // One admission decision on the ORIGINAL payload (full native tool input
66    // and output), before anything text-bearing is derived from it. Solution
67    // capture, the radar's `detail`/`content` and echo analysis inherit it;
68    // content-free facts below (event type, tool name, token estimate, LOC
69    // metering, compaction marker) do not depend on it.
70    let admission = super::admission::admit_payload(&input);
71    super::solution_capture::maybe_capture_admitted(&input, admission.derivable(&input));
72
73    let Some(event) = parse_observe_event(&input) else {
74        return;
75    };
76    let event = admitted_event(event, &admission);
77    // Compaction evicts the conversation the read-dedup stubs would point into
78    // (GL #1140): purge the session's re-read records so every file delivers
79    // full content again, mirroring the MCP-side compaction sync (GL #555).
80    if event.event_type == "compaction"
81        && let Ok(v) = serde_json::from_str::<serde_json::Value>(&input)
82        && let Some(session_id) = v.get("session_id").and_then(|s| s.as_str())
83    {
84        super::read_dedup::purge_session(session_id);
85    }
86    append_radar_event(&event);
87
88    // Output-echo analysis (#501): measure how much of the agent's reply
89    // re-quotes content lean-ctx already delivered, and feed the adaptive
90    // mode policy with an automatic feedback event.
91    if event.event_type == "agent_response"
92        && let Some(text) = event.content.as_deref()
93    {
94        crate::core::output_echo::analyze_and_record(text);
95    }
96}
97
98/// Bind the text-bearing fields of a radar event to the payload's admission.
99/// The event itself (type, tool name, token estimate, ids) is content-free and
100/// always recorded; `detail` and `content` are text from the payload and are
101/// stored only as admitted: unchanged, re-derived from the redacted payload,
102/// or replaced by the typed, content-free reason.
103fn admitted_event(
104    mut event: ObserveEvent,
105    admission: &super::admission::PayloadAdmission,
106) -> ObserveEvent {
107    use super::admission::PayloadAdmission;
108    match admission {
109        PayloadAdmission::Unchanged => {}
110        PayloadAdmission::Rewritten(payload) => {
111            let redacted = serde_json::from_str::<serde_json::Value>(payload)
112                .ok()
113                .and_then(|value| detect_event_type(&value, event.ts));
114            event.detail = redacted.as_ref().and_then(|event| event.detail.clone());
115            event.content = redacted.and_then(|event| event.content);
116        }
117        PayloadAdmission::Withheld(withheld) => {
118            event.detail = Some(withheld.notice());
119            event.content = None;
120        }
121    }
122    event
123}
124
125/// #1288: emit a one-line tool-precedence reminder as `additionalContext` on
126/// UserPromptSubmit. Gated by `prompt_reinject` (on|off|auto; auto = only when
127/// shadow mode is active, i.e. the policy the line describes is mechanically
128/// enforced). Costs ~45 tokens per turn — kept to a single line by design.
129fn emit_prompt_submit_precedence(input: &str) {
130    // This is explicit rule/tool-precedence steering, not passive telemetry.
131    // Honour the same central opt-out as every other automatic steering channel.
132    if crate::core::config::Config::load().declines_rule_steering() {
133        return;
134    }
135
136    let Ok(v) = serde_json::from_str::<serde_json::Value>(input) else {
137        return;
138    };
139    if v.get("hook_event_name").and_then(|e| e.as_str()) != Some("UserPromptSubmit") {
140        return;
141    }
142    if !prompt_reinject_enabled() {
143        return;
144    }
145    println!(
146        "{}",
147        serde_json::json!({
148            "hookSpecificOutput": {
149                "hookEventName": "UserPromptSubmit",
150                "additionalContext": PROMPT_SUBMIT_PRECEDENCE
151            }
152        })
153    );
154}
155
156/// Effective `prompt_reinject` gate (#1288). Env wins over config; `auto`
157/// follows `shadow_mode` so the reminder only ships where the denies back it.
158fn prompt_reinject_enabled() -> bool {
159    let mode = match std::env::var("LEAN_CTX_PROMPT_REINJECT") {
160        Ok(v) if !v.trim().is_empty() => v,
161        _ => {
162            let cfg = crate::core::config::Config::load();
163            match cfg.prompt_reinject.as_deref() {
164                Some(m) if !m.trim().is_empty() => m.to_string(),
165                _ => return crate::core::config::Config::load().shadow_mode,
166            }
167        }
168    };
169    match mode.trim().to_ascii_lowercase().as_str() {
170        "on" | "true" | "1" => true,
171        "off" | "false" | "0" => false,
172        _ => crate::core::config::Config::load().shadow_mode,
173    }
174}
175
176/// Records durable logical presence for every host SessionStart and SessionEnd hook.
177///
178/// This is deliberately separate from the MCP-process presence registered by
179/// `LeanCtxServer`: a host session can own several short-lived MCP connections.
180/// Hook telemetry remains fail-open so a registry lock cannot wedge an editor;
181/// the MCP ingress itself is fail-closed before any tool executes.
182fn record_session_lifecycle_presence(input: &str) {
183    let Ok(payload) = serde_json::from_str::<serde_json::Value>(input) else {
184        return;
185    };
186    let Some((event, source, workspace, session_id)) = session_lifecycle_presence_fields(&payload)
187    else {
188        return;
189    };
190    if event == "close" {
191        // Queue the session's learnings for Hive (local only, no network).
192        crate::core::hive::knowledge::draft::on_session_event(
193            &workspace,
194            &session_id,
195            crate::core::hive::knowledge::draft::Trigger::SessionEnd,
196        );
197    }
198    if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
199        event,
200        &source,
201        &workspace,
202        &session_id,
203    ) {
204        tracing::warn!(
205            %error,
206            source,
207            workspace = %workspace,
208            event,
209            "lean-ctx: failed to record logical session presence"
210        );
211    }
212}
213
214fn session_lifecycle_presence_fields(
215    payload: &serde_json::Value,
216) -> Option<(&'static str, String, String, String)> {
217    let event = match payload
218        .get("hook_event_name")
219        .and_then(serde_json::Value::as_str)
220    {
221        Some("SessionStart") => "open",
222        Some("SessionEnd") => "close",
223        _ => return None,
224    };
225
226    let session_id = ["session_id", "conversation_id"]
227        .iter()
228        .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
229        .filter(|value| !value.trim().is_empty())?
230        .to_string();
231    let workspace = ["cwd", "workspace", "project_root"]
232        .iter()
233        .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
234        .filter(|value| !value.trim().is_empty())
235        .map(str::to_string)
236        .or_else(|| {
237            std::env::current_dir()
238                .ok()
239                .map(|path| path.to_string_lossy().into_owned())
240        })?;
241    let source = session_lifecycle_source(payload, &session_id, |key| {
242        std::env::var(key)
243            .ok()
244            .filter(|value| !value.trim().is_empty())
245    });
246    Some((event, source.to_string(), workspace, session_id))
247}
248
249/// Host session-id variables exported to hook subprocesses, per host.
250/// Sources: Claude Code env-vars reference (`CLAUDE_CODE_SESSION_ID`, "set
251/// automatically to the current session ID in … hook command subprocesses";
252/// `CLAUDE_SESSION_ID` kept for older builds), Gemini CLI hooks guide
253/// (`GEMINI_SESSION_ID`, `GEMINI_PROJECT_DIR`), and the Codex/CodeBuddy
254/// variables this module already relied on.
255const SESSION_ENV_SIGNALS: &[(&str, &[&str])] = &[
256    ("codex", &["CODEX_THREAD_ID"]),
257    ("gemini", &["GEMINI_SESSION_ID"]),
258    ("claude", &["CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"]),
259    ("codebuddy", &["CODEBUDDY_SESSION_ID"]),
260];
261
262/// Which host fired a SessionStart/SessionEnd hook. Cursor is recognised by
263/// its payload (`conversation_id`). Otherwise an env session id equal to the
264/// payload's `session_id` is decisive; failing that, presence decides in a
265/// fixed order. Gemini precedes Claude because Gemini CLI also exports
266/// `CLAUDE_PROJECT_DIR` to hooks for compatibility; neither that alias nor
267/// `CLAUDECODE` (also set in IDE terminals) is used as a signal.
268fn session_lifecycle_source(
269    payload: &serde_json::Value,
270    session_id: &str,
271    env: impl Fn(&str) -> Option<String>,
272) -> &'static str {
273    if payload.get("conversation_id").is_some() {
274        return "cursor";
275    }
276    if let Some((source, _)) = SESSION_ENV_SIGNALS.iter().find(|(_, keys)| {
277        keys.iter()
278            .any(|key| env(key).is_some_and(|value| value.trim() == session_id))
279    }) {
280        return source;
281    }
282    let present = |keys: &[&str]| keys.iter().any(|key| env(key).is_some());
283    if present(&["CODEX_THREAD_ID", "CODEX_PROFILE"]) {
284        "codex"
285    } else if present(&["GEMINI_SESSION_ID", "GEMINI_PROJECT_DIR"]) {
286        "gemini"
287    } else if present(&["CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"]) {
288        "claude"
289    } else if present(&["CODEBUDDY_SESSION_ID"]) {
290        "codebuddy"
291    } else {
292        "agent"
293    }
294}
295
296/// The SessionStart rules for this payload (`additionalContext`), if any.
297fn dedicated_session_context(input: &str) -> Option<String> {
298    // SessionStart additionalContext is model-visible rule steering.
299    // Do not emit it after the user explicitly declined that steering.
300    if crate::core::config::Config::load().declines_rule_steering() {
301        return None;
302    }
303
304    let v = serde_json::from_str::<serde_json::Value>(input).ok()?;
305    if !session_start_honours_additional_context(&v) {
306        return None;
307    }
308    let cfg = crate::core::config::Config::load();
309
310    if cfg.dedicated_session_context_active() {
311        // Full Bare rules for dedicated-mode hosts (Claude Code, Codex, CodeBuddy)
312        // where the static rules file is skipped.
313        let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
314        let client_name = session_start_client_name(&v);
315        Some(build_dedicated_session_context(
316            client_name,
317            cfg.shadow_mode,
318            &profile,
319        ))
320    } else {
321        // Short reinforcement nudge for shared-mode hosts (Cursor) that already
322        // have static rules but benefit from in-conversation emphasis on exclusive
323        // tools. Models weight in-conversation context above static instructions.
324        Some(SHARED_SESSION_CONTEXT.to_string())
325    }
326}
327
328/// Builds dedicated SessionStart rules, using shadow-minimal only when hooks cover native tools.
329fn build_dedicated_session_context(
330    client_name: &str,
331    shadow: bool,
332    profile: &crate::core::tool_profiles::ToolProfile,
333) -> String {
334    let effective_shadow = shadow && client_is_hook_covered(client_name);
335    crate::core::rules_canonical::render(
336        effective_shadow,
337        crate::core::rules_canonical::Wrapper::Bare,
338        crate::core::config::CompressionLevel::Off,
339        profile,
340    )
341}
342
343/// Identifies hook coverage from the installed rules-channel configuration.
344fn client_is_hook_covered(client_name: &str) -> bool {
345    crate::core::home::resolve_home_dir()
346        .is_some_and(|home| crate::core::rules_channel::client_hook_covered(client_name, &home))
347}
348
349/// Maps SessionStart payload shape to the only potentially hook-covered client, Cursor.
350fn session_start_client_name(payload: &serde_json::Value) -> &'static str {
351    if payload.get("conversation_id").is_some() {
352        "cursor"
353    } else {
354        "claude"
355    }
356}
357
358/// True for SessionStart payloads from hosts that honour `additionalContext`.
359///
360/// Cursor fixed SessionStart `additionalContext` support circa Q1 2026 —
361/// confirmed on the Cursor community forum as the only hook event where
362/// `additional_context` works end-to-end. The prior exclusion (#1031) is
363/// therefore removed: Cursor sessions now receive the same dedicated rules
364/// reinforcement as Claude/Codex/CodeBuddy.
365fn session_start_honours_additional_context(v: &serde_json::Value) -> bool {
366    v.get("hook_event_name").and_then(|e| e.as_str()) == Some("SessionStart")
367}
368
369#[derive(serde::Serialize)]
370struct ObserveEvent {
371    ts: u64,
372    event_type: &'static str,
373    tokens: usize,
374    #[serde(skip_serializing_if = "Option::is_none")]
375    tool_name: Option<String>,
376    #[serde(skip_serializing_if = "Option::is_none")]
377    detail: Option<String>,
378    #[serde(skip_serializing_if = "Option::is_none")]
379    content: Option<String>,
380    #[serde(skip_serializing_if = "Option::is_none")]
381    model: Option<String>,
382    #[serde(skip_serializing_if = "Option::is_none")]
383    conversation_id: Option<String>,
384}
385
386const MAX_CONTENT_CHARS: usize = 50_000;
387
388fn parse_observe_event(input: &str) -> Option<ObserveEvent> {
389    let v: serde_json::Value = serde_json::from_str(input).ok()?;
390
391    let ts = std::time::SystemTime::now()
392        .duration_since(std::time::UNIX_EPOCH)
393        .unwrap_or_default()
394        .as_secs();
395
396    let model = v
397        .get("model")
398        .and_then(|m| m.as_str())
399        .filter(|m| !m.is_empty())
400        .map(String::from);
401    let conversation_id = v
402        .get("conversation_id")
403        .and_then(|c| c.as_str())
404        .filter(|c| !c.is_empty())
405        .map(String::from);
406
407    let transcript_path = v
408        .get("transcript_path")
409        .and_then(|t| t.as_str())
410        .filter(|t| !t.is_empty())
411        .map(String::from);
412
413    // Claude Code / Codex / CodeBuddy carry a per-session `session_id` but no
414    // `conversation_id`. Persisting it lets the read-cache scope a session's
415    // deliveries the same way Cursor's `conversation_id` does, so a new session
416    // never inherits a prior one's `[unchanged]` stubs (#1004).
417    let session_id = v
418        .get("session_id")
419        .and_then(|s| s.as_str())
420        .filter(|s| !s.is_empty())
421        .map(String::from);
422
423    if let Some(ref m) = model {
424        persist_detected_model(m);
425    }
426    if let Some(ref tp) = transcript_path {
427        persist_transcript_path(tp, conversation_id.as_deref(), session_id.as_deref());
428    }
429
430    let mut event = detect_event_type(&v, ts)?;
431    event.model = model;
432    event.conversation_id = conversation_id;
433    Some(event)
434}
435
436fn detect_event_type(v: &serde_json::Value, ts: u64) -> Option<ObserveEvent> {
437    // GitHub Copilot CLI postToolUse: camelCase `toolName` + `toolArgs`
438    // (JSON-encoded string) + `toolResult`. None of the snake_case branches
439    // below match this shape, so without a dedicated arm Copilot telemetry
440    // (heatmap, token savings, radar) is silently dropped (#551).
441    if let Some(result) = v.get("toolResult") {
442        let tool = super::payload::resolve_tool_name(v).unwrap_or_else(|| "unknown".to_string());
443        let args = super::payload::resolve_tool_args(v);
444        let command = args
445            .as_ref()
446            .and_then(|a| a.get("command"))
447            .and_then(|c| c.as_str());
448        let result_text = result
449            .get("textResultForLlm")
450            .and_then(|t| t.as_str())
451            .map_or_else(|| result.to_string(), String::from);
452        let tokens = result_text.len() / 4;
453        let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
454        let event_type = if is_lctx {
455            "mcp_call"
456        } else if command.is_some() {
457            "shell"
458        } else {
459            "native_tool"
460        };
461        let content = match command {
462            Some(cmd) => format!("$ {cmd}\n{result_text}"),
463            None => result_text,
464        };
465        return Some(ObserveEvent {
466            ts,
467            event_type,
468            tokens,
469            tool_name: Some(tool),
470            detail: command.map(|c| truncate_str(c, 80)),
471            content: Some(cap_content(&content)),
472            model: None,
473            conversation_id: None,
474        });
475    }
476
477    if let Some(result) = v
478        .get("result_json")
479        .or_else(|| v.get("result"))
480        .or_else(|| v.get("tool_response"))
481        .or_else(|| v.get("tool_output"))
482    {
483        let tool = v
484            .get("tool_name")
485            .and_then(|t| t.as_str())
486            .unwrap_or("unknown");
487        let tokens = estimate_tokens_json(result);
488        let content_str = match result {
489            serde_json::Value::String(s) => s.clone(),
490            other => other.to_string(),
491        };
492        return Some(ObserveEvent {
493            ts,
494            event_type: "mcp_call",
495            tokens,
496            tool_name: Some(tool.to_string()),
497            detail: v
498                .get("server_name")
499                .and_then(|s| s.as_str())
500                .map(String::from),
501            content: Some(cap_content(&content_str)),
502            model: None,
503            conversation_id: None,
504        });
505    }
506
507    if let Some(output) = v.get("output") {
508        let cmd = v
509            .get("command")
510            .and_then(|c| c.as_str())
511            .unwrap_or("")
512            .to_string();
513        let tokens = estimate_tokens_value(output);
514        let out_str = match output {
515            serde_json::Value::String(s) => s.clone(),
516            other => other.to_string(),
517        };
518        return Some(ObserveEvent {
519            ts,
520            event_type: "shell",
521            tokens,
522            tool_name: None,
523            detail: Some(truncate_str(&cmd, 80)),
524            content: Some(cap_content(&format!("$ {cmd}\n{out_str}"))),
525            model: None,
526            conversation_id: None,
527        });
528    }
529
530    if v.get("content").is_some() && v.get("file_path").is_some() {
531        let path = v
532            .get("file_path")
533            .and_then(|p| p.as_str())
534            .unwrap_or("")
535            .to_string();
536        let file_content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
537        let tokens = file_content.len() / 4;
538        return Some(ObserveEvent {
539            ts,
540            event_type: "file_read",
541            tokens,
542            tool_name: None,
543            detail: Some(truncate_str(&path, 120)),
544            content: Some(cap_content(file_content)),
545            model: None,
546            conversation_id: None,
547        });
548    }
549
550    if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
551        let has_duration = v.get("duration_ms").is_some();
552        let event_type = if has_duration {
553            "thinking"
554        } else {
555            "agent_response"
556        };
557        let tokens = text.len() / 4;
558        return Some(ObserveEvent {
559            ts,
560            event_type,
561            tokens,
562            tool_name: None,
563            detail: None,
564            content: Some(cap_content(text)),
565            model: None,
566            conversation_id: None,
567        });
568    }
569
570    if let Some(prompt) = v.get("prompt").and_then(|p| p.as_str()) {
571        let tokens = prompt.len() / 4;
572        let mut full = prompt.to_string();
573        if let Some(attachments) = v.get("attachments").and_then(|a| a.as_array())
574            && !attachments.is_empty()
575        {
576            full.push_str(&format!("\n\n[{} attachments]", attachments.len()));
577            for att in attachments {
578                if let Some(name) = att.get("name").and_then(|n| n.as_str()) {
579                    full.push_str(&format!("\n  - {name}"));
580                }
581            }
582        }
583        return Some(ObserveEvent {
584            ts,
585            event_type: "user_message",
586            tokens,
587            tool_name: None,
588            detail: v
589                .get("attachments")
590                .and_then(|a| a.as_array())
591                .map(|a| format!("{} attachments", a.len())),
592            content: Some(cap_content(&full)),
593            model: None,
594            conversation_id: None,
595        });
596    }
597
598    if v.get("tool_name").is_some() || v.get("tool_input").is_some() {
599        let tool = v
600            .get("tool_name")
601            .and_then(|t| t.as_str())
602            .unwrap_or("unknown")
603            .to_string();
604        let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
605        let tokens = v.get("tool_input").map_or(0, estimate_tokens_json);
606        let input_str = v
607            .get("tool_input")
608            .map(std::string::ToString::to_string)
609            .unwrap_or_default();
610        return Some(ObserveEvent {
611            ts,
612            event_type: if is_lctx { "mcp_call" } else { "native_tool" },
613            tokens,
614            tool_name: Some(tool),
615            detail: None,
616            content: if input_str.is_empty() {
617                None
618            } else {
619                Some(cap_content(&input_str))
620            },
621            model: None,
622            conversation_id: None,
623        });
624    }
625
626    // Claude Code emits `hook_event_name: "PreCompact"` (code.claude.com/docs/
627    // en/hooks); the generic `event`/`compaction` shapes cover other hosts.
628    // This check must run BEFORE the `session_id` catch-all below: every
629    // Claude hook payload carries `session_id` as a common field, so the
630    // compaction branch was unreachable for Claude — compactions were never
631    // recorded, `sync_if_compacted` never reset delivery flags, and
632    // post-compaction re-reads kept answering with "[unchanged]" stubs that
633    // pointed at context the host had already evicted (GL #555). Agents then
634    // fell back to native Read to recover the content.
635    let is_compaction = v.get("compaction").is_some()
636        || v.get("messages_count").is_some()
637        || v.get("hook_event_name")
638            .and_then(|e| e.as_str())
639            .is_some_and(|e| e == "PreCompact")
640        || v.get("event")
641            .and_then(|e| e.as_str())
642            .is_some_and(|e| e == "compaction" || e == "compact");
643    if !is_compaction && v.get("session_id").is_some() {
644        return Some(ObserveEvent {
645            ts,
646            event_type: "session",
647            tokens: 0,
648            tool_name: None,
649            detail: v
650                .get("session_id")
651                .and_then(|s| s.as_str())
652                .map(String::from),
653            content: None,
654            model: None,
655            conversation_id: None,
656        });
657    }
658
659    if is_compaction {
660        return Some(ObserveEvent {
661            ts,
662            event_type: "compaction",
663            tokens: 0,
664            tool_name: None,
665            detail: None,
666            content: None,
667            model: None,
668            conversation_id: None,
669        });
670    }
671
672    None
673}
674
675fn estimate_tokens_json(v: &serde_json::Value) -> usize {
676    match v {
677        serde_json::Value::String(s) => s.len() / 4,
678        _ => v.to_string().len() / 4,
679    }
680}
681
682fn estimate_tokens_value(v: &serde_json::Value) -> usize {
683    match v {
684        serde_json::Value::String(s) => s.len() / 4,
685        _ => v.to_string().len() / 4,
686    }
687}
688
689fn persist_detected_model(model: &str) {
690    if crate::core::model_registry::is_background_model(model) {
691        return;
692    }
693
694    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
695        return;
696    };
697    let path = data_dir.join("detected_model.json");
698    let ts = std::time::SystemTime::now()
699        .duration_since(std::time::UNIX_EPOCH)
700        .unwrap_or_default()
701        .as_secs();
702    let window = model_context_window(model);
703    let payload = serde_json::json!({
704        "model": model,
705        "window_size": window,
706        "detected_at": ts,
707    });
708    if let Ok(json) = serde_json::to_string_pretty(&payload) {
709        let tmp = path.with_extension("tmp");
710        if std::fs::write(&tmp, &json).is_ok() {
711            let _ = std::fs::rename(&tmp, &path);
712        }
713    }
714}
715
716pub fn model_context_window(model: &str) -> usize {
717    crate::core::model_registry::context_window_for_model(model)
718}
719
720pub fn load_detected_model() -> Option<(String, usize)> {
721    let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
722    let path = data_dir.join("detected_model.json");
723    let content = std::fs::read_to_string(&path).ok()?;
724    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
725    let model = v.get("model")?.as_str()?.to_string();
726    let window = v.get("window_size")?.as_u64()? as usize;
727    let detected_at = v.get("detected_at")?.as_u64()?;
728    let now = std::time::SystemTime::now()
729        .duration_since(std::time::UNIX_EPOCH)
730        .unwrap_or_default()
731        .as_secs();
732    if now.saturating_sub(detected_at) > 7200 {
733        return None;
734    }
735    Some((model, window))
736}
737
738fn persist_transcript_path(path: &str, conversation_id: Option<&str>, session_id: Option<&str>) {
739    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
740        return;
741    };
742    let meta_path = data_dir.join("active_transcript.json");
743    let ts = std::time::SystemTime::now()
744        .duration_since(std::time::UNIX_EPOCH)
745        .unwrap_or_default()
746        .as_secs();
747    let payload = serde_json::json!({
748        "transcript_path": path,
749        "conversation_id": conversation_id,
750        "session_id": session_id,
751        "updated_at": ts,
752    });
753    if let Ok(json) = serde_json::to_string_pretty(&payload) {
754        let tmp = meta_path.with_extension("tmp");
755        if std::fs::write(&tmp, &json).is_ok() {
756            let _ = std::fs::rename(&tmp, &meta_path);
757        }
758    }
759}
760
761pub fn load_active_transcript() -> Option<(String, Option<String>)> {
762    let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
763    let path = data_dir.join("active_transcript.json");
764    let content = std::fs::read_to_string(&path).ok()?;
765    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
766    let tp = v.get("transcript_path")?.as_str()?.to_string();
767    // Prefer Cursor's `conversation_id`; fall back to the host `session_id`
768    // (Claude Code / Codex / CodeBuddy) so the read-cache still has a per-session
769    // identity to scope stubs against (#1004).
770    let conv = v
771        .get("conversation_id")
772        .and_then(|c| c.as_str())
773        .or_else(|| v.get("session_id").and_then(|s| s.as_str()))
774        .map(String::from);
775    let updated = v.get("updated_at")?.as_u64()?;
776    let now = std::time::SystemTime::now()
777        .duration_since(std::time::UNIX_EPOCH)
778        .unwrap_or_default()
779        .as_secs();
780    if now.saturating_sub(updated) > 7200 {
781        return None;
782    }
783    Some((tp, conv))
784}
785
786fn cap_content(s: &str) -> String {
787    if s.len() <= MAX_CONTENT_CHARS {
788        s.to_string()
789    } else {
790        let truncated = safe_truncate(s, MAX_CONTENT_CHARS);
791        format!("{}…\n\n[truncated: {} total chars]", truncated, s.len())
792    }
793}
794
795fn truncate_str(s: &str, max: usize) -> String {
796    if s.len() <= max {
797        s.to_string()
798    } else {
799        format!("{}...", safe_truncate(s, max))
800    }
801}
802
803/// Truncate a string at a char boundary <= max bytes. Never panics on multi-byte UTF-8.
804fn safe_truncate(s: &str, max: usize) -> &str {
805    if max >= s.len() {
806        return s;
807    }
808    let mut end = max;
809    while end > 0 && !s.is_char_boundary(end) {
810        end -= 1;
811    }
812    &s[..end]
813}
814
815fn append_radar_event(event: &ObserveEvent) {
816    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
817        return;
818    };
819    let radar_path = data_dir.join("context_radar.jsonl");
820
821    if event.event_type == "session"
822        && let Ok(meta) = std::fs::metadata(&radar_path)
823    {
824        const MAX_RADAR_SIZE: u64 = 10 * 1024 * 1024; // 10 MB
825        if meta.len() > MAX_RADAR_SIZE {
826            let prev = data_dir.join("context_radar.prev.jsonl");
827            let _ = std::fs::rename(&radar_path, &prev);
828        }
829    }
830
831    let Ok(line) = serde_json::to_string(event) else {
832        return;
833    };
834
835    use std::fs::OpenOptions;
836    use std::io::Write;
837    if let Ok(mut f) = OpenOptions::new()
838        .create(true)
839        .append(true)
840        .open(&radar_path)
841    {
842        let _ = writeln!(f, "{line}");
843    }
844
845    // #808: write an atomic marker file so the MCP server can detect
846    // compactions reliably even when large events bury the radar entry.
847    if event.event_type == "compaction" {
848        write_compaction_marker(&data_dir, event.ts);
849    }
850}
851
852/// Atomically write `last_compaction.json` via temp-file + rename.
853/// The marker is a few bytes; no other event can displace it.
854fn write_compaction_marker(data_dir: &std::path::Path, ts: u64) {
855    use std::io::Write;
856    let marker_path = data_dir.join("last_compaction.json");
857    let tmp_path = data_dir.join("last_compaction.json.tmp");
858    let payload = format!(r#"{{"ts":{ts}}}"#);
859    let Ok(mut f) = std::fs::File::create(&tmp_path) else {
860        return;
861    };
862    if f.write_all(payload.as_bytes()).is_err() || f.sync_all().is_err() {
863        let _ = std::fs::remove_file(&tmp_path);
864        return;
865    }
866    drop(f);
867    let _ = std::fs::rename(&tmp_path, &marker_path);
868}
869
870/// Count the IDE-hook observe events recorded in `context_radar.jsonl`.
871///
872/// `watch` uses this to explain an empty live feed (#593): a non-zero count
873/// means IDE hooks ARE firing — lean-ctx is wired into the editor — even though
874/// no `ctx_*` MCP tool has been called yet. That distinguishes "the agent is
875/// using native tools instead of ctx_*" from "nothing is connected at all".
876/// Counts newline-delimited records; returns 0 when the file is absent.
877#[must_use]
878pub fn radar_event_count() -> usize {
879    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
880        return 0;
881    };
882    let Ok(file) = std::fs::File::open(data_dir.join("context_radar.jsonl")) else {
883        return 0;
884    };
885    use std::io::{BufRead, BufReader};
886    BufReader::new(file)
887        .lines()
888        .map_while(Result::ok)
889        .filter(|l| !l.trim().is_empty())
890        .count()
891}
892
893#[cfg(test)]
894#[path = "observe_tests.rs"]
895mod tests;