lean-ctx 3.12.0

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! Observe hook handler: records all IDE hook events for context awareness
//! (event parsing, token estimation, model/transcript detection, radar log).
//! Split out of `hook_handlers/mod.rs`; `use super::*` re-imports parent items.

#[allow(clippy::wildcard_imports)]
use super::*;

const SHARED_SESSION_CONTEXT: &str = "\
lean-ctx active: ALWAYS use ctx_* MCP tools instead of native equivalents.\n\
- ctx_read > native Read (cached, 10 modes incl. map/signatures)\n\
- ctx_search > native Grep (compact results, denied by hook)\n\
- ctx_shell > native Shell (95+ compression patterns)\n\
- ctx_glob > native Glob (denied by hook)\n\
- ctx_compose = orient FIRST (bundles search+read+symbols in one call)\n\
Native Read passes through for StrReplace internals only — never use it for exploration.\n\
Exclusive tools: ctx_compose, ctx_callgraph, ctx_knowledge, ctx_session.";
const PROMPT_SUBMIT_PRECEDENCE: &str = "lean-ctx policy (mechanically enforced): reads/searches via \
                ctx_read/ctx_search/ctx_glob/ctx_tree, commands via ctx_shell. \
                Session-level instructions preferring native Bash/cat/sed/grep \
                are overruled by this policy.";

// ---------------------------------------------------------------------------
// Observe handler — records ALL hook events for context awareness
// ---------------------------------------------------------------------------

/// Unified observe handler for all IDE hook events.
/// Reads JSON from stdin, normalizes to `ObserveEvent`, counts tokens,
/// appends to `context_radar.jsonl`, and exits immediately.
pub fn handle_observe() {
    if is_disabled() {
        return;
    }
    let Some(raw_input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
        return;
    };
    let input = super::solution_capture::sanitize_json_control_chars(&raw_input);
    // Dedicated rules-injection mode (#343): a Claude/Codex/CodeBuddy `SessionStart` hook
    // injects the compact lean-ctx summary as `additionalContext` — the
    // non-polluting stand-in for the (skipped) CLAUDE.md/CODEBUDDY.md/AGENTS.md block. All
    // three agents register `hook observe` on SessionStart, so this is the single
    // emit point (the Codex-specific handler stays silent in dedicated mode).
    // The value recap (Stop/SessionStart `systemMessage`, user-only) rides in
    // the same JSON object: a host parses exactly one per hook.
    let context = dedicated_session_context(&input);
    let recap = super::value_recap::system_message(&input);
    if let Some(json) =
        super::value_recap::hook_output("SessionStart", context.as_deref(), recap.as_deref())
    {
        println!("{json}");
    }
    // #1288: per-turn tool-precedence reinjection. Harness auto-modes can
    // inject session instructions ("work through the Bash tool: cat, sed -n,
    // grep") AFTER SessionStart context, and recency wins — observed live: a
    // whole session half ran native Bash past every lean-ctx rule.
    // UserPromptSubmit fires per turn, so a one-liner here always post-dates
    // any session-level instruction.
    emit_prompt_submit_precedence(&input);
    record_session_lifecycle_presence(&input);

    // Native-edit code-health notice (#1085): when the agent edits code with the
    // host's native Edit/MultiEdit tools (bypassing ctx_edit's gate), surface an
    // advisory complexity-regression notice via PostToolUse additionalContext.
    super::edit_health::maybe_emit(&input);

    // One admission decision on the ORIGINAL payload (full native tool input
    // and output), before anything text-bearing is derived from it. Solution
    // capture, the radar's `detail`/`content` and echo analysis inherit it;
    // content-free facts below (event type, tool name, token estimate, LOC
    // metering, compaction marker) do not depend on it.
    let admission = super::admission::admit_payload(&input);
    super::solution_capture::maybe_capture_admitted(&input, admission.derivable(&input));

    let Some(event) = parse_observe_event(&input) else {
        return;
    };
    let event = admitted_event(event, &admission);
    // Compaction evicts the conversation the read-dedup stubs would point into
    // (GL #1140): purge the session's re-read records so every file delivers
    // full content again, mirroring the MCP-side compaction sync (GL #555).
    if event.event_type == "compaction"
        && let Ok(v) = serde_json::from_str::<serde_json::Value>(&input)
        && let Some(session_id) = v.get("session_id").and_then(|s| s.as_str())
    {
        super::read_dedup::purge_session(session_id);
    }
    append_radar_event(&event);

    // Output-echo analysis (#501): measure how much of the agent's reply
    // re-quotes content lean-ctx already delivered, and feed the adaptive
    // mode policy with an automatic feedback event.
    if event.event_type == "agent_response"
        && let Some(text) = event.content.as_deref()
    {
        crate::core::output_echo::analyze_and_record(text);
    }
}

/// Bind the text-bearing fields of a radar event to the payload's admission.
/// The event itself (type, tool name, token estimate, ids) is content-free and
/// always recorded; `detail` and `content` are text from the payload and are
/// stored only as admitted: unchanged, re-derived from the redacted payload,
/// or replaced by the typed, content-free reason.
fn admitted_event(
    mut event: ObserveEvent,
    admission: &super::admission::PayloadAdmission,
) -> ObserveEvent {
    use super::admission::PayloadAdmission;
    match admission {
        PayloadAdmission::Unchanged => {}
        PayloadAdmission::Rewritten(payload) => {
            let redacted = serde_json::from_str::<serde_json::Value>(payload)
                .ok()
                .and_then(|value| detect_event_type(&value, event.ts));
            event.detail = redacted.as_ref().and_then(|event| event.detail.clone());
            event.content = redacted.and_then(|event| event.content);
        }
        PayloadAdmission::Withheld(withheld) => {
            event.detail = Some(withheld.notice());
            event.content = None;
        }
    }
    event
}

/// #1288: emit a one-line tool-precedence reminder as `additionalContext` on
/// UserPromptSubmit. Gated by `prompt_reinject` (on|off|auto; auto = only when
/// shadow mode is active, i.e. the policy the line describes is mechanically
/// enforced). Costs ~45 tokens per turn — kept to a single line by design.
fn emit_prompt_submit_precedence(input: &str) {
    // This is explicit rule/tool-precedence steering, not passive telemetry.
    // Honour the same central opt-out as every other automatic steering channel.
    if crate::core::config::Config::load().declines_rule_steering() {
        return;
    }

    let Ok(v) = serde_json::from_str::<serde_json::Value>(input) else {
        return;
    };
    if v.get("hook_event_name").and_then(|e| e.as_str()) != Some("UserPromptSubmit") {
        return;
    }
    if !prompt_reinject_enabled() {
        return;
    }
    println!(
        "{}",
        serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "UserPromptSubmit",
                "additionalContext": PROMPT_SUBMIT_PRECEDENCE
            }
        })
    );
}

/// Effective `prompt_reinject` gate (#1288). Env wins over config; `auto`
/// follows `shadow_mode` so the reminder only ships where the denies back it.
fn prompt_reinject_enabled() -> bool {
    let mode = match std::env::var("LEAN_CTX_PROMPT_REINJECT") {
        Ok(v) if !v.trim().is_empty() => v,
        _ => {
            let cfg = crate::core::config::Config::load();
            match cfg.prompt_reinject.as_deref() {
                Some(m) if !m.trim().is_empty() => m.to_string(),
                _ => return crate::core::config::Config::load().shadow_mode,
            }
        }
    };
    match mode.trim().to_ascii_lowercase().as_str() {
        "on" | "true" | "1" => true,
        "off" | "false" | "0" => false,
        _ => crate::core::config::Config::load().shadow_mode,
    }
}

/// Records durable logical presence for every host SessionStart and SessionEnd hook.
///
/// This is deliberately separate from the MCP-process presence registered by
/// `LeanCtxServer`: a host session can own several short-lived MCP connections.
/// Hook telemetry remains fail-open so a registry lock cannot wedge an editor;
/// the MCP ingress itself is fail-closed before any tool executes.
fn record_session_lifecycle_presence(input: &str) {
    let Ok(payload) = serde_json::from_str::<serde_json::Value>(input) else {
        return;
    };
    let Some((event, source, workspace, session_id)) = session_lifecycle_presence_fields(&payload)
    else {
        return;
    };
    if event == "close" {
        // Queue the session's learnings for Hive (local only, no network).
        crate::core::hive::knowledge::draft::on_session_event(
            &workspace,
            &session_id,
            crate::core::hive::knowledge::draft::Trigger::SessionEnd,
        );
    }
    if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
        event,
        &source,
        &workspace,
        &session_id,
    ) {
        tracing::warn!(
            %error,
            source,
            workspace = %workspace,
            event,
            "lean-ctx: failed to record logical session presence"
        );
    }
}

fn session_lifecycle_presence_fields(
    payload: &serde_json::Value,
) -> Option<(&'static str, String, String, String)> {
    let event = match payload
        .get("hook_event_name")
        .and_then(serde_json::Value::as_str)
    {
        Some("SessionStart") => "open",
        Some("SessionEnd") => "close",
        _ => return None,
    };

    let session_id = ["session_id", "conversation_id"]
        .iter()
        .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
        .filter(|value| !value.trim().is_empty())?
        .to_string();
    let workspace = ["cwd", "workspace", "project_root"]
        .iter()
        .find_map(|key| payload.get(*key).and_then(serde_json::Value::as_str))
        .filter(|value| !value.trim().is_empty())
        .map(str::to_string)
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .map(|path| path.to_string_lossy().into_owned())
        })?;
    let source = session_lifecycle_source(payload, &session_id, |key| {
        std::env::var(key)
            .ok()
            .filter(|value| !value.trim().is_empty())
    });
    Some((event, source.to_string(), workspace, session_id))
}

/// Host session-id variables exported to hook subprocesses, per host.
/// Sources: Claude Code env-vars reference (`CLAUDE_CODE_SESSION_ID`, "set
/// automatically to the current session ID in … hook command subprocesses";
/// `CLAUDE_SESSION_ID` kept for older builds), Gemini CLI hooks guide
/// (`GEMINI_SESSION_ID`, `GEMINI_PROJECT_DIR`), and the Codex/CodeBuddy
/// variables this module already relied on.
const SESSION_ENV_SIGNALS: &[(&str, &[&str])] = &[
    ("codex", &["CODEX_THREAD_ID"]),
    ("gemini", &["GEMINI_SESSION_ID"]),
    ("claude", &["CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"]),
    ("codebuddy", &["CODEBUDDY_SESSION_ID"]),
];

/// Which host fired a SessionStart/SessionEnd hook. Cursor is recognised by
/// its payload (`conversation_id`). Otherwise an env session id equal to the
/// payload's `session_id` is decisive; failing that, presence decides in a
/// fixed order. Gemini precedes Claude because Gemini CLI also exports
/// `CLAUDE_PROJECT_DIR` to hooks for compatibility; neither that alias nor
/// `CLAUDECODE` (also set in IDE terminals) is used as a signal.
fn session_lifecycle_source(
    payload: &serde_json::Value,
    session_id: &str,
    env: impl Fn(&str) -> Option<String>,
) -> &'static str {
    if payload.get("conversation_id").is_some() {
        return "cursor";
    }
    if let Some((source, _)) = SESSION_ENV_SIGNALS.iter().find(|(_, keys)| {
        keys.iter()
            .any(|key| env(key).is_some_and(|value| value.trim() == session_id))
    }) {
        return source;
    }
    let present = |keys: &[&str]| keys.iter().any(|key| env(key).is_some());
    if present(&["CODEX_THREAD_ID", "CODEX_PROFILE"]) {
        "codex"
    } else if present(&["GEMINI_SESSION_ID", "GEMINI_PROJECT_DIR"]) {
        "gemini"
    } else if present(&["CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"]) {
        "claude"
    } else if present(&["CODEBUDDY_SESSION_ID"]) {
        "codebuddy"
    } else {
        "agent"
    }
}

/// The SessionStart rules for this payload (`additionalContext`), if any.
fn dedicated_session_context(input: &str) -> Option<String> {
    // SessionStart additionalContext is model-visible rule steering.
    // Do not emit it after the user explicitly declined that steering.
    if crate::core::config::Config::load().declines_rule_steering() {
        return None;
    }

    let v = serde_json::from_str::<serde_json::Value>(input).ok()?;
    if !session_start_honours_additional_context(&v) {
        return None;
    }
    let cfg = crate::core::config::Config::load();

    if cfg.dedicated_session_context_active() {
        // Full Bare rules for dedicated-mode hosts (Claude Code, Codex, CodeBuddy)
        // where the static rules file is skipped.
        let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
        let client_name = session_start_client_name(&v);
        Some(build_dedicated_session_context(
            client_name,
            cfg.shadow_mode,
            &profile,
        ))
    } else {
        // Short reinforcement nudge for shared-mode hosts (Cursor) that already
        // have static rules but benefit from in-conversation emphasis on exclusive
        // tools. Models weight in-conversation context above static instructions.
        Some(SHARED_SESSION_CONTEXT.to_string())
    }
}

/// Builds dedicated SessionStart rules, using shadow-minimal only when hooks cover native tools.
fn build_dedicated_session_context(
    client_name: &str,
    shadow: bool,
    profile: &crate::core::tool_profiles::ToolProfile,
) -> String {
    let effective_shadow = shadow && client_is_hook_covered(client_name);
    crate::core::rules_canonical::render(
        effective_shadow,
        crate::core::rules_canonical::Wrapper::Bare,
        crate::core::config::CompressionLevel::Off,
        profile,
    )
}

/// Identifies hook coverage from the installed rules-channel configuration.
fn client_is_hook_covered(client_name: &str) -> bool {
    crate::core::home::resolve_home_dir()
        .is_some_and(|home| crate::core::rules_channel::client_hook_covered(client_name, &home))
}

/// Maps SessionStart payload shape to the only potentially hook-covered client, Cursor.
fn session_start_client_name(payload: &serde_json::Value) -> &'static str {
    if payload.get("conversation_id").is_some() {
        "cursor"
    } else {
        "claude"
    }
}

/// True for SessionStart payloads from hosts that honour `additionalContext`.
///
/// Cursor fixed SessionStart `additionalContext` support circa Q1 2026 —
/// confirmed on the Cursor community forum as the only hook event where
/// `additional_context` works end-to-end. The prior exclusion (#1031) is
/// therefore removed: Cursor sessions now receive the same dedicated rules
/// reinforcement as Claude/Codex/CodeBuddy.
fn session_start_honours_additional_context(v: &serde_json::Value) -> bool {
    v.get("hook_event_name").and_then(|e| e.as_str()) == Some("SessionStart")
}

#[derive(serde::Serialize)]
struct ObserveEvent {
    ts: u64,
    event_type: &'static str,
    tokens: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    conversation_id: Option<String>,
}

const MAX_CONTENT_CHARS: usize = 50_000;

fn parse_observe_event(input: &str) -> Option<ObserveEvent> {
    let v: serde_json::Value = serde_json::from_str(input).ok()?;

    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let model = v
        .get("model")
        .and_then(|m| m.as_str())
        .filter(|m| !m.is_empty())
        .map(String::from);
    let conversation_id = v
        .get("conversation_id")
        .and_then(|c| c.as_str())
        .filter(|c| !c.is_empty())
        .map(String::from);

    let transcript_path = v
        .get("transcript_path")
        .and_then(|t| t.as_str())
        .filter(|t| !t.is_empty())
        .map(String::from);

    // Claude Code / Codex / CodeBuddy carry a per-session `session_id` but no
    // `conversation_id`. Persisting it lets the read-cache scope a session's
    // deliveries the same way Cursor's `conversation_id` does, so a new session
    // never inherits a prior one's `[unchanged]` stubs (#1004).
    let session_id = v
        .get("session_id")
        .and_then(|s| s.as_str())
        .filter(|s| !s.is_empty())
        .map(String::from);

    if let Some(ref m) = model {
        persist_detected_model(m);
    }
    if let Some(ref tp) = transcript_path {
        persist_transcript_path(tp, conversation_id.as_deref(), session_id.as_deref());
    }

    let mut event = detect_event_type(&v, ts)?;
    event.model = model;
    event.conversation_id = conversation_id;
    Some(event)
}

fn detect_event_type(v: &serde_json::Value, ts: u64) -> Option<ObserveEvent> {
    // GitHub Copilot CLI postToolUse: camelCase `toolName` + `toolArgs`
    // (JSON-encoded string) + `toolResult`. None of the snake_case branches
    // below match this shape, so without a dedicated arm Copilot telemetry
    // (heatmap, token savings, radar) is silently dropped (#551).
    if let Some(result) = v.get("toolResult") {
        let tool = super::payload::resolve_tool_name(v).unwrap_or_else(|| "unknown".to_string());
        let args = super::payload::resolve_tool_args(v);
        let command = args
            .as_ref()
            .and_then(|a| a.get("command"))
            .and_then(|c| c.as_str());
        let result_text = result
            .get("textResultForLlm")
            .and_then(|t| t.as_str())
            .map_or_else(|| result.to_string(), String::from);
        let tokens = result_text.len() / 4;
        let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
        let event_type = if is_lctx {
            "mcp_call"
        } else if command.is_some() {
            "shell"
        } else {
            "native_tool"
        };
        let content = match command {
            Some(cmd) => format!("$ {cmd}\n{result_text}"),
            None => result_text,
        };
        return Some(ObserveEvent {
            ts,
            event_type,
            tokens,
            tool_name: Some(tool),
            detail: command.map(|c| truncate_str(c, 80)),
            content: Some(cap_content(&content)),
            model: None,
            conversation_id: None,
        });
    }

    if let Some(result) = v
        .get("result_json")
        .or_else(|| v.get("result"))
        .or_else(|| v.get("tool_response"))
        .or_else(|| v.get("tool_output"))
    {
        let tool = v
            .get("tool_name")
            .and_then(|t| t.as_str())
            .unwrap_or("unknown");
        let tokens = estimate_tokens_json(result);
        let content_str = match result {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        return Some(ObserveEvent {
            ts,
            event_type: "mcp_call",
            tokens,
            tool_name: Some(tool.to_string()),
            detail: v
                .get("server_name")
                .and_then(|s| s.as_str())
                .map(String::from),
            content: Some(cap_content(&content_str)),
            model: None,
            conversation_id: None,
        });
    }

    if let Some(output) = v.get("output") {
        let cmd = v
            .get("command")
            .and_then(|c| c.as_str())
            .unwrap_or("")
            .to_string();
        let tokens = estimate_tokens_value(output);
        let out_str = match output {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        return Some(ObserveEvent {
            ts,
            event_type: "shell",
            tokens,
            tool_name: None,
            detail: Some(truncate_str(&cmd, 80)),
            content: Some(cap_content(&format!("$ {cmd}\n{out_str}"))),
            model: None,
            conversation_id: None,
        });
    }

    if v.get("content").is_some() && v.get("file_path").is_some() {
        let path = v
            .get("file_path")
            .and_then(|p| p.as_str())
            .unwrap_or("")
            .to_string();
        let file_content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
        let tokens = file_content.len() / 4;
        return Some(ObserveEvent {
            ts,
            event_type: "file_read",
            tokens,
            tool_name: None,
            detail: Some(truncate_str(&path, 120)),
            content: Some(cap_content(file_content)),
            model: None,
            conversation_id: None,
        });
    }

    if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
        let has_duration = v.get("duration_ms").is_some();
        let event_type = if has_duration {
            "thinking"
        } else {
            "agent_response"
        };
        let tokens = text.len() / 4;
        return Some(ObserveEvent {
            ts,
            event_type,
            tokens,
            tool_name: None,
            detail: None,
            content: Some(cap_content(text)),
            model: None,
            conversation_id: None,
        });
    }

    if let Some(prompt) = v.get("prompt").and_then(|p| p.as_str()) {
        let tokens = prompt.len() / 4;
        let mut full = prompt.to_string();
        if let Some(attachments) = v.get("attachments").and_then(|a| a.as_array())
            && !attachments.is_empty()
        {
            full.push_str(&format!("\n\n[{} attachments]", attachments.len()));
            for att in attachments {
                if let Some(name) = att.get("name").and_then(|n| n.as_str()) {
                    full.push_str(&format!("\n  - {name}"));
                }
            }
        }
        return Some(ObserveEvent {
            ts,
            event_type: "user_message",
            tokens,
            tool_name: None,
            detail: v
                .get("attachments")
                .and_then(|a| a.as_array())
                .map(|a| format!("{} attachments", a.len())),
            content: Some(cap_content(&full)),
            model: None,
            conversation_id: None,
        });
    }

    if v.get("tool_name").is_some() || v.get("tool_input").is_some() {
        let tool = v
            .get("tool_name")
            .and_then(|t| t.as_str())
            .unwrap_or("unknown")
            .to_string();
        let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
        let tokens = v.get("tool_input").map_or(0, estimate_tokens_json);
        let input_str = v
            .get("tool_input")
            .map(std::string::ToString::to_string)
            .unwrap_or_default();
        return Some(ObserveEvent {
            ts,
            event_type: if is_lctx { "mcp_call" } else { "native_tool" },
            tokens,
            tool_name: Some(tool),
            detail: None,
            content: if input_str.is_empty() {
                None
            } else {
                Some(cap_content(&input_str))
            },
            model: None,
            conversation_id: None,
        });
    }

    // Claude Code emits `hook_event_name: "PreCompact"` (code.claude.com/docs/
    // en/hooks); the generic `event`/`compaction` shapes cover other hosts.
    // This check must run BEFORE the `session_id` catch-all below: every
    // Claude hook payload carries `session_id` as a common field, so the
    // compaction branch was unreachable for Claude — compactions were never
    // recorded, `sync_if_compacted` never reset delivery flags, and
    // post-compaction re-reads kept answering with "[unchanged]" stubs that
    // pointed at context the host had already evicted (GL #555). Agents then
    // fell back to native Read to recover the content.
    let is_compaction = v.get("compaction").is_some()
        || v.get("messages_count").is_some()
        || v.get("hook_event_name")
            .and_then(|e| e.as_str())
            .is_some_and(|e| e == "PreCompact")
        || v.get("event")
            .and_then(|e| e.as_str())
            .is_some_and(|e| e == "compaction" || e == "compact");
    if !is_compaction && v.get("session_id").is_some() {
        return Some(ObserveEvent {
            ts,
            event_type: "session",
            tokens: 0,
            tool_name: None,
            detail: v
                .get("session_id")
                .and_then(|s| s.as_str())
                .map(String::from),
            content: None,
            model: None,
            conversation_id: None,
        });
    }

    if is_compaction {
        return Some(ObserveEvent {
            ts,
            event_type: "compaction",
            tokens: 0,
            tool_name: None,
            detail: None,
            content: None,
            model: None,
            conversation_id: None,
        });
    }

    None
}

fn estimate_tokens_json(v: &serde_json::Value) -> usize {
    match v {
        serde_json::Value::String(s) => s.len() / 4,
        _ => v.to_string().len() / 4,
    }
}

fn estimate_tokens_value(v: &serde_json::Value) -> usize {
    match v {
        serde_json::Value::String(s) => s.len() / 4,
        _ => v.to_string().len() / 4,
    }
}

fn persist_detected_model(model: &str) {
    if crate::core::model_registry::is_background_model(model) {
        return;
    }

    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
        return;
    };
    let path = data_dir.join("detected_model.json");
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let window = model_context_window(model);
    let payload = serde_json::json!({
        "model": model,
        "window_size": window,
        "detected_at": ts,
    });
    if let Ok(json) = serde_json::to_string_pretty(&payload) {
        let tmp = path.with_extension("tmp");
        if std::fs::write(&tmp, &json).is_ok() {
            let _ = std::fs::rename(&tmp, &path);
        }
    }
}

pub fn model_context_window(model: &str) -> usize {
    crate::core::model_registry::context_window_for_model(model)
}

pub fn load_detected_model() -> Option<(String, usize)> {
    let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
    let path = data_dir.join("detected_model.json");
    let content = std::fs::read_to_string(&path).ok()?;
    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
    let model = v.get("model")?.as_str()?.to_string();
    let window = v.get("window_size")?.as_u64()? as usize;
    let detected_at = v.get("detected_at")?.as_u64()?;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    if now.saturating_sub(detected_at) > 7200 {
        return None;
    }
    Some((model, window))
}

fn persist_transcript_path(path: &str, conversation_id: Option<&str>, session_id: Option<&str>) {
    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
        return;
    };
    let meta_path = data_dir.join("active_transcript.json");
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let payload = serde_json::json!({
        "transcript_path": path,
        "conversation_id": conversation_id,
        "session_id": session_id,
        "updated_at": ts,
    });
    if let Ok(json) = serde_json::to_string_pretty(&payload) {
        let tmp = meta_path.with_extension("tmp");
        if std::fs::write(&tmp, &json).is_ok() {
            let _ = std::fs::rename(&tmp, &meta_path);
        }
    }
}

pub fn load_active_transcript() -> Option<(String, Option<String>)> {
    let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
    let path = data_dir.join("active_transcript.json");
    let content = std::fs::read_to_string(&path).ok()?;
    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
    let tp = v.get("transcript_path")?.as_str()?.to_string();
    // Prefer Cursor's `conversation_id`; fall back to the host `session_id`
    // (Claude Code / Codex / CodeBuddy) so the read-cache still has a per-session
    // identity to scope stubs against (#1004).
    let conv = v
        .get("conversation_id")
        .and_then(|c| c.as_str())
        .or_else(|| v.get("session_id").and_then(|s| s.as_str()))
        .map(String::from);
    let updated = v.get("updated_at")?.as_u64()?;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    if now.saturating_sub(updated) > 7200 {
        return None;
    }
    Some((tp, conv))
}

fn cap_content(s: &str) -> String {
    if s.len() <= MAX_CONTENT_CHARS {
        s.to_string()
    } else {
        let truncated = safe_truncate(s, MAX_CONTENT_CHARS);
        format!("{}…\n\n[truncated: {} total chars]", truncated, s.len())
    }
}

fn truncate_str(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("{}...", safe_truncate(s, max))
    }
}

/// Truncate a string at a char boundary <= max bytes. Never panics on multi-byte UTF-8.
fn safe_truncate(s: &str, max: usize) -> &str {
    if max >= s.len() {
        return s;
    }
    let mut end = max;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

fn append_radar_event(event: &ObserveEvent) {
    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
        return;
    };
    let radar_path = data_dir.join("context_radar.jsonl");

    if event.event_type == "session"
        && let Ok(meta) = std::fs::metadata(&radar_path)
    {
        const MAX_RADAR_SIZE: u64 = 10 * 1024 * 1024; // 10 MB
        if meta.len() > MAX_RADAR_SIZE {
            let prev = data_dir.join("context_radar.prev.jsonl");
            let _ = std::fs::rename(&radar_path, &prev);
        }
    }

    let Ok(line) = serde_json::to_string(event) else {
        return;
    };

    use std::fs::OpenOptions;
    use std::io::Write;
    if let Ok(mut f) = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&radar_path)
    {
        let _ = writeln!(f, "{line}");
    }

    // #808: write an atomic marker file so the MCP server can detect
    // compactions reliably even when large events bury the radar entry.
    if event.event_type == "compaction" {
        write_compaction_marker(&data_dir, event.ts);
    }
}

/// Atomically write `last_compaction.json` via temp-file + rename.
/// The marker is a few bytes; no other event can displace it.
fn write_compaction_marker(data_dir: &std::path::Path, ts: u64) {
    use std::io::Write;
    let marker_path = data_dir.join("last_compaction.json");
    let tmp_path = data_dir.join("last_compaction.json.tmp");
    let payload = format!(r#"{{"ts":{ts}}}"#);
    let Ok(mut f) = std::fs::File::create(&tmp_path) else {
        return;
    };
    if f.write_all(payload.as_bytes()).is_err() || f.sync_all().is_err() {
        let _ = std::fs::remove_file(&tmp_path);
        return;
    }
    drop(f);
    let _ = std::fs::rename(&tmp_path, &marker_path);
}

/// Count the IDE-hook observe events recorded in `context_radar.jsonl`.
///
/// `watch` uses this to explain an empty live feed (#593): a non-zero count
/// means IDE hooks ARE firing — lean-ctx is wired into the editor — even though
/// no `ctx_*` MCP tool has been called yet. That distinguishes "the agent is
/// using native tools instead of ctx_*" from "nothing is connected at all".
/// Counts newline-delimited records; returns 0 when the file is absent.
#[must_use]
pub fn radar_event_count() -> usize {
    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
        return 0;
    };
    let Ok(file) = std::fs::File::open(data_dir.join("context_radar.jsonl")) else {
        return 0;
    };
    use std::io::{BufRead, BufReader};
    BufReader::new(file)
        .lines()
        .map_while(Result::ok)
        .filter(|l| !l.trim().is_empty())
        .count()
}

#[cfg(test)]
#[path = "observe_tests.rs"]
mod tests;