lean-ctx 3.12.3

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. 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
// SPDX-License-Identifier: Apache-2.0
use chrono::Utc;
use serde::Deserialize;
use std::path::Path;

use super::helpers::{detect_project_root_for_dashboard, json_err, json_ok};

pub(super) fn handle(
    path: &str,
    _query_str: &str,
    method: &str,
    body: &str,
) -> Option<(&'static str, &'static str, String)> {
    match path {
        "/api/session/note" if method.eq_ignore_ascii_case("POST") => Some(post_session_note(body)),
        "/api/episodes/annotate" if method.eq_ignore_ascii_case("POST") => {
            Some(retired_memory_route())
        }
        _ => get_routes(path),
    }
}

fn with_dashboard_project<T>(
    root: &str,
    operation: impl FnOnce(
        &str,
        &lean_ctx::core::context_admission::stores::StoreAdmission,
        &lean_ctx::core::policy::runtime::PublicationAuthority,
    ) -> Result<T, String>,
) -> Result<T, String> {
    let root_path = Path::new(root);
    if lean_ctx::core::pathutil::is_broad_or_unsafe_root(root_path) {
        return Err("dashboard project scope unavailable".into());
    }
    let canonical_root = root_path
        .canonicalize()
        .map_err(|_| "dashboard project scope unavailable".to_string())?;
    let project_hash = lean_ctx::core::project_hash::hash_project_root(root);
    let admission = lean_ctx::core::context_admission::stores::StoreAdmission::current();

    lean_ctx::core::policy::runtime::with_explicit_project_source_view(
        &canonical_root,
        |authority| {
            let result = operation(&project_hash, &admission, authority)?;
            admission.authorize_publication(authority)?;
            Ok(result)
        },
    )?
}

fn admitted_dashboard_text(text: &str) -> Result<String, String> {
    // The project's own memory, rendered for the dashboard.
    let result = lean_ctx::core::context_admission::admit_tool_output_as(
        text,
        lean_ctx::core::context_admission::OutputCompleteness::complete(),
        &lean_ctx::core::context_admission::carrier::INSTANCE,
    );
    result
        .text
        .ok_or_else(|| "dashboard content withheld by current policy".to_string())
}

fn admitted_dashboard_json(value: &serde_json::Value) -> Result<String, String> {
    let raw =
        serde_json::to_string(value).map_err(|_| "dashboard response unavailable".to_string())?;
    let admitted = admitted_dashboard_text(&raw)?;
    if admitted != raw {
        return Err("dashboard response would require policy redaction".into());
    }
    Ok(raw)
}

fn dashboard_json_response(
    response: Result<String, String>,
) -> (&'static str, &'static str, String) {
    match response {
        Ok(json) => ("200 OK", "application/json", json),
        Err(_) => (
            "503 Service Unavailable",
            "application/json",
            json_err("dashboard memory unavailable under current policy"),
        ),
    }
}

/// `/api/episodes`, `/api/procedures` and `POST /api/episodes/annotate`: the
/// episode and procedure memory is retired (DEPRECATIONS.toml
/// `http-dashboard-episodes-procedures`). Accepted with this notice and no
/// effect; files under `memory/episodes` and `memory/procedures` stay on disk
/// untouched.
fn retired_memory_route() -> (&'static str, &'static str, String) {
    (
        "200 OK",
        "application/json",
        serde_json::json!({
            "retired": true,
            "message": "The episode and procedure memory is retired; decisions, findings and gotchas live in project knowledge (/api/knowledge, /api/gotchas).",
        })
        .to_string(),
    )
}

fn intent_json(root: &str) -> Result<String, String> {
    with_dashboard_project(root, |_hash, _admission, _authority| {
        let session = lean_ctx::core::session::SessionState::load_latest_for_project_root(root)
            .map(|session| lean_ctx::core::session::admission::for_delivery(&session))
            .transpose()?
            .filter(|session| session.active_structured_intent.is_some());
        let payload = match session {
            Some(session) => serde_json::json!({
                "active": true,
                "intent": session.active_structured_intent,
            }),
            None => serde_json::json!({ "active": false }),
        };
        admitted_dashboard_json(&payload)
    })
}

/// #1284: today's (UTC) totals from metering.jsonl. Unlike the savings ledger,
/// metering records EVERY ctx_* call including zero-saving ones, so this is
/// the honest denominator. Only today's tail of the file is read; the result is
/// cached on (file length, day) because the Live view polls every few seconds.
/// Today's metered totals: the device's, or for a named project its share.
fn today_metering_summary(
    scope: Option<&lean_ctx::core::savings_ledger::ProjectScope>,
) -> lean_ctx::core::metering::DayTotals {
    use lean_ctx::core::metering::{DayTotals, MeterStore};
    use std::sync::Mutex;
    static CACHE: Mutex<Option<(u64, chrono::NaiveDate, DayTotals)>> = Mutex::new(None);

    if let Some(scope) = scope {
        let Ok(store) = MeterStore::from_data_dir() else {
            return DayTotals::default();
        };
        let keys = scope.repo_hashes();
        return store.day_totals_where(Utc::now().date_naive(), |key| {
            key.is_some_and(|key| keys.iter().any(|k| k == key))
        });
    }

    let Ok(store) = MeterStore::from_data_dir() else {
        return DayTotals::default();
    };
    let len = std::fs::metadata(store.path())
        .map(|m| m.len())
        .unwrap_or(0);
    let today = Utc::now().date_naive();
    if let Ok(guard) = CACHE.lock()
        && let Some((cached_len, cached_day, totals)) = *guard
        && cached_len == len
        && cached_day == today
    {
        return totals;
    }
    let totals = store.day_totals(today);
    if let Ok(mut guard) = CACHE.lock() {
        *guard = Some((len, today, totals));
    }
    totals
}

fn get_routes(path: &str) -> Option<(&'static str, &'static str, String)> {
    match path {
        "/api/episodes" | "/api/procedures" => Some(retired_memory_route()),
        "/api/session" => {
            // The status bar promises "the task your most recent agent session
            // is working on". `load_latest()` matches sessions against THIS
            // process's cwd — but the dashboard usually runs from HOME (a
            // broad root that rightly matches nothing), so it permanently
            // showed "No session" while agents were active. Fall back to the
            // most recently updated session rooted in a real project
            // (skipping broad/unsafe roots like HOME or test-sandbox temp dirs).
            // A read for a named project (`X-LeanCTX-Project`) never falls
            // back to another project's session.
            let named_project = matches!(
                super::helpers::dashboard_project_binding().1,
                super::helpers::DashboardProjectSource::Request
            );
            let mut session = lean_ctx::core::session::SessionState::load_latest()
                .or_else(|| {
                    if named_project {
                        return None;
                    }
                    lean_ctx::core::session::SessionState::list_sessions()
                        .iter()
                        .find_map(|summary| {
                            let sess =
                                lean_ctx::core::session::SessionState::load_by_id(&summary.id)?;
                            let root = sess.project_root.as_deref()?;
                            if lean_ctx::core::pathutil::is_broad_or_unsafe_root(
                                std::path::Path::new(root),
                            ) {
                                return None;
                            }
                            Some(sess)
                        })
                })
                .unwrap_or_default();

            // Capture session-only stats BEFORE global enrichment.
            let session_stats =
                serde_json::to_value(&session.stats).unwrap_or_else(|_| serde_json::json!({}));

            // Today's verified savings from the savings ledger (written by all
            // processes — MCP server, proxy, CLI). This is the source of truth;
            // for a named project, only its events.
            let summary = lean_ctx::core::savings_ledger::summary_for(
                super::helpers::request_ledger_scope().as_ref(),
            );
            let today = chrono::Utc::now().format("%Y-%m-%d").to_string();
            let (today_saved, today_usd, today_baseline) = summary
                .by_day
                .iter()
                .find(|(d, ..)| d == &today)
                .map(|(_, s, u, b)| (*s, *u, *b))
                .unwrap_or((0, 0.0, 0));
            // #1284: the ledger only records calls that saved something, so its
            // percentage is "of compression events", not "of everything the
            // agent did". Ship the metering view (ALL metered ctx_* calls,
            // zero-saving ones included) and the native-passthrough count next
            // to it so the panel can label the denominator honestly.
            let metered = today_metering_summary(super::helpers::request_ledger_scope().as_ref());
            let (metered_input, metered_saved) = (metered.input_tokens, metered.savings_tokens);
            let reach =
                lean_ctx::core::gain::reach::reach_view(lean_ctx::core::gain::reach::ReachCounts {
                    routed_calls: metered.routed_calls,
                    native_passthrough_calls: metered.native_passthrough_calls,
                });
            let compression_session = serde_json::json!({
                "savings_tokens": today_saved,
                "total_raw": today_baseline,
                "total_compressed": today_baseline.saturating_sub(today_saved),
                "savings_percent": if today_baseline > 0 {
                    today_saved as f64 * 100.0 / today_baseline as f64
                } else { 0.0 },
                "savings_usd": today_usd,
                // #1284 honesty fields (today, UTC):
                "scope": "savings ledger — compression events only; metered_* covers every metered ctx_* call incl. zero-saving ones",
                "metered_input_tokens": metered_input,
                "metered_saved_tokens": metered_saved,
                "savings_percent_of_metered": if metered_input > 0 {
                    metered_saved as f64 * 100.0 / metered_input as f64
                } else { 0.0 },
                "native_passthrough_calls": metered.native_passthrough_calls,
                "reach": reach,
            });

            // A named project's session is enriched with that project's own
            // counters, never the device's.
            let global = match super::helpers::request_ledger_scope() {
                Some(scope) if named_project => lean_ctx::core::stats::load_for_project(&scope),
                _ => lean_ctx::core::stats::load_for_display(),
            };
            let g_cmds = global.total_commands;
            let g_input = global.total_input_tokens;
            let g_output = global.total_output_tokens;
            let g_saved = g_input.saturating_sub(g_output);
            if g_cmds > session.stats.total_tool_calls as u64 {
                session.stats.total_tool_calls = g_cmds as u32;
            }
            if g_saved > session.stats.total_tokens_saved {
                session.stats.total_tokens_saved = g_saved;
            }
            if g_input > session.stats.total_tokens_input {
                session.stats.total_tokens_input = g_input;
            }
            if let Some(lu) = &global.last_use
                && let Ok(ts) = chrono::DateTime::parse_from_rfc3339(lu)
            {
                let utc = ts.with_timezone(&chrono::Utc);
                if utc > session.updated_at {
                    session.updated_at = utc;
                }
            }
            let mut payload =
                serde_json::to_value(&session).unwrap_or_else(|_| serde_json::json!({}));
            if let Some(object) = payload.as_object_mut() {
                object.insert("session_stats".to_string(), session_stats);
                object.insert("compression_session".to_string(), compression_session);
            }
            let json = serde_json::to_string(&payload)
                .unwrap_or_else(|_| "{\"error\":\"failed to serialize session\"}".to_string());
            Some(("200 OK", "application/json", json))
        }
        // Multi-window visibility (GH #694): every workspace that has a
        // session, newest first, so users with several IDE windows can see
        // which projects lean-ctx serves and how fresh each one is.
        "/api/workspaces" => {
            let last_use = lean_ctx::core::stats::load_for_display()
                .last_use
                .as_deref()
                .and_then(|lu| chrono::DateTime::parse_from_rfc3339(lu).ok())
                .map(|ts| ts.with_timezone(&Utc));
            let workspaces = collect_workspaces(
                Utc::now(),
                lean_ctx::core::session::SessionState::list_sessions(),
                last_use,
            );
            let json = serde_json::to_string(&serde_json::json!({ "workspaces": workspaces }))
                .unwrap_or_else(|_| "{}".to_string());
            Some(("200 OK", "application/json", json))
        }
        "/api/memory" => {
            let snap = lean_ctx::core::memory_guard::MemorySnapshot::capture();
            let allocator = if cfg!(all(
                feature = "jemalloc",
                not(windows),
                not(target_env = "musl")
            )) {
                "jemalloc (dirty_decay: 1s)"
            } else {
                "system"
            };
            let payload = if let Some(s) = snap {
                serde_json::json!({
                    "rss_bytes": s.rss_bytes,
                    "rss_mb": format!("{:.1}", s.rss_bytes as f64 / 1_048_576.0),
                    "peak_rss_bytes": s.peak_rss_bytes,
                    "peak_rss_mb": format!("{:.1}", s.peak_rss_bytes as f64 / 1_048_576.0),
                    "system_ram_bytes": s.system_ram_bytes,
                    "system_ram_gb": format!("{:.1}", s.system_ram_bytes as f64 / 1_073_741_824.0),
                    "rss_limit_bytes": s.rss_limit_bytes,
                    "rss_limit_mb": format!("{:.1}", s.rss_limit_bytes as f64 / 1_048_576.0),
                    "rss_percent": format!("{:.2}", s.rss_percent),
                    "pressure_level": s.pressure_level,
                    "allocator": allocator,
                    "max_sessions": lean_ctx::core::context_os::SharedSessionStore::max_sessions(),
                })
            } else {
                serde_json::json!({
                    "available": false,
                    "reason": "RSS monitoring not supported on this platform",
                    "allocator": allocator,
                })
            };
            let json = serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string());
            Some(("200 OK", "application/json", json))
        }
        "/api/intent" => {
            let root = detect_project_root_for_dashboard();
            Some(dashboard_json_response(intent_json(&root)))
        }
        _ => None,
    }
}

#[derive(Deserialize)]
struct SessionNoteReq {
    note: String,
}

fn post_session_note(body: &str) -> (&'static str, &'static str, String) {
    let req: SessionNoteReq = match serde_json::from_str(body) {
        Ok(r) => r,
        Err(e) => {
            return (
                "400 Bad Request",
                "application/json",
                json_err(&format!("invalid JSON: {e}")),
            );
        }
    };
    let note = req.note.trim();
    if note.is_empty() {
        return (
            "400 Bad Request",
            "application/json",
            json_err("note must not be empty"),
        );
    }
    // The note goes to the newest session of the dashboard's project (or the
    // project the request names), admitted before it is stored.
    let root = detect_project_root_for_dashboard();
    if root.is_empty() {
        return (
            "400 Bad Request",
            "application/json",
            json_err("no project to attach note to"),
        );
    }
    match append_session_note(&root, note) {
        Ok(true) => ("200 OK", "application/json", json_ok()),
        Ok(false) => (
            "400 Bad Request",
            "application/json",
            json_err("no session to attach note to"),
        ),
        Err(_) => (
            "503 Service Unavailable",
            "application/json",
            json_err("session note unavailable under current policy"),
        ),
    }
}

/// Append `note` to the newest session of the project at `root`. `Ok(false)`
/// when the project has no session. The note is admitted for storage under
/// the project's policy before it is written, and the write is published only
/// while that policy still holds.
fn append_session_note(root: &str, note: &str) -> Result<bool, String> {
    with_dashboard_project(root, |_hash, admission, _authority| {
        let Some(mut session) =
            lean_ctx::core::session::SessionState::load_latest_for_project_root(root)
        else {
            return Ok(false);
        };
        let note = lean_ctx::core::session::admission::admit_store_text(admission, note)
            .ok_or_else(|| "session note withheld by current policy".to_string())?;
        let now = Utc::now();
        session.updated_at = now;
        session
            .progress
            .push(lean_ctx::core::session::ProgressEntry {
                action: "note".to_string(),
                detail: Some(note),
                timestamp: now,
            });
        session.save()?;
        Ok(true)
    })
}

/// Canonical grouping key for a workspace root (#717). Sessions persisted on
/// Windows carry `C:\proj`, `C:/proj` and `c:/proj` variants of the same
/// workspace; the previous exact-string dedup rendered duplicate cards where
/// the stale twin sat on "idle" right next to the active one. Lexical-only —
/// no filesystem access, because the daemon may not be allowed to stat the
/// path (TCC, #356) and the root may even belong to another machine.
/// Drive-letter paths are Windows paths and case-insensitive as a whole.
fn workspace_canonical_key(root: &str) -> String {
    let p = lean_ctx::core::pathutil::normalize_tool_path_lexical(root);
    let is_drive_path =
        p.len() >= 2 && p.as_bytes()[0].is_ascii_alphabetic() && p.as_bytes()[1] == b':';
    if is_drive_path {
        p.to_ascii_lowercase()
    } else {
        p
    }
}

/// Builds the `/api/workspaces` entries: one card per canonical workspace
/// (#717), newest first. Within a group the freshest session wins
/// `updated_at`/root/task and counters take the max across variants. The
/// globally freshest workspace additionally absorbs `stats.last_use`
/// (`last_use` parameter) — the proxy bumps that on every request while
/// session JSONs lag behind the batch-save window, which is exactly the
/// "active session shown as idle" gap from the report. Same heuristic as
/// `/api/session`.
fn collect_workspaces(
    now: chrono::DateTime<Utc>,
    sessions: Vec<lean_ctx::core::session::SessionSummary>,
    last_use: Option<chrono::DateTime<Utc>>,
) -> Vec<serde_json::Value> {
    struct Group {
        root: String,
        updated_at: chrono::DateTime<Utc>,
        task: Option<String>,
        tool_calls: u32,
        tokens_saved: u64,
    }
    let mut groups: std::collections::HashMap<String, Group> = std::collections::HashMap::new();
    for s in sessions {
        let Some(root) = s.project_root.clone().filter(|r| !r.is_empty()) else {
            continue;
        };
        if lean_ctx::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(&root)) {
            continue;
        }
        let key = workspace_canonical_key(&root);
        // Render the normalized form so Windows separator variants display
        // uniformly regardless of which session happens to be freshest.
        let display_root = lean_ctx::core::pathutil::normalize_tool_path_lexical(&root);
        match groups.entry(key) {
            std::collections::hash_map::Entry::Occupied(mut e) => {
                let g = e.get_mut();
                if s.updated_at > g.updated_at {
                    g.updated_at = s.updated_at;
                    g.root = display_root;
                    if s.task.is_some() {
                        g.task.clone_from(&s.task);
                    }
                }
                if g.task.is_none() {
                    g.task.clone_from(&s.task);
                }
                g.tool_calls = g.tool_calls.max(s.tool_calls);
                g.tokens_saved = g.tokens_saved.max(s.tokens_saved);
            }
            std::collections::hash_map::Entry::Vacant(v) => {
                v.insert(Group {
                    root: display_root,
                    updated_at: s.updated_at,
                    task: s.task,
                    tool_calls: s.tool_calls,
                    tokens_saved: s.tokens_saved,
                });
            }
        }
    }
    let mut list: Vec<Group> = groups.into_values().collect();
    list.sort_by_key(|g| std::cmp::Reverse(g.updated_at));
    if let Some(first) = list.first_mut()
        && let Some(lu) = last_use
        && lu > first.updated_at
    {
        first.updated_at = lu;
    }
    list.into_iter()
        .map(|g| {
            let age_minutes = now.signed_duration_since(g.updated_at).num_minutes();
            let status = if age_minutes < 10 {
                "active"
            } else if age_minutes < 24 * 60 {
                "idle"
            } else {
                "stale"
            };
            let name = std::path::Path::new(&g.root)
                .file_name()
                .map_or_else(|| g.root.clone(), |n| n.to_string_lossy().into_owned());
            serde_json::json!({
                "root": g.root,
                "name": name,
                "status": status,
                "last_activity": g.updated_at,
                "age_minutes": age_minutes,
                "task": g.task,
                "tool_calls": g.tool_calls,
                "tokens_saved": g.tokens_saved,
            })
        })
        .collect()
}

#[cfg(test)]
mod workspace_tests {
    use super::*;
    use chrono::Duration;
    use lean_ctx::core::session::SessionSummary;

    fn summary(root: &str, updated_min_ago: i64, calls: u32, task: Option<&str>) -> SessionSummary {
        let ts = Utc::now() - Duration::minutes(updated_min_ago);
        SessionSummary {
            id: format!("s-{root}-{updated_min_ago}"),
            started_at: ts,
            updated_at: ts,
            version: 1,
            task: task.map(str::to_string),
            tool_calls: calls,
            tokens_saved: calls as u64 * 100,
            project_root: Some(root.to_string()),
        }
    }

    #[test]
    fn canonical_key_folds_windows_variants() {
        // #717: all spellings of the same Windows workspace share one key.
        let variants = [
            r"C:\Users\dev\proj",
            "C:/Users/dev/proj",
            "c:/Users/dev/proj",
            r"c:\Users\dev\proj/",
        ];
        let keys: std::collections::HashSet<String> = variants
            .iter()
            .map(|v| workspace_canonical_key(v))
            .collect();
        assert_eq!(keys.len(), 1, "expected one canonical key, got {keys:?}");
        // Unix paths stay case-sensitive (a real FS distinction there).
        assert_ne!(
            workspace_canonical_key("/home/dev/Proj"),
            workspace_canonical_key("/home/dev/proj")
        );
    }

    #[test]
    fn windows_path_variants_dedupe_to_one_entry() {
        // #717 repro: the same workspace persisted under three spellings must
        // render one card carrying the freshest timestamp and max counters.
        let sessions = vec![
            summary(r"C:\Users\dev\proj", 120, 40, None),
            summary("c:/Users/dev/proj", 60, 10, Some("older task")),
            summary("C:/Users/dev/proj", 2, 25, Some("current task")),
        ];
        let out = collect_workspaces(Utc::now(), sessions, None);
        assert_eq!(out.len(), 1, "expected dedupe to one entry: {out:?}");
        let ws = &out[0];
        assert_eq!(ws["status"], "active");
        assert_eq!(ws["task"], "current task");
        assert_eq!(ws["tool_calls"], 40);
        assert_eq!(ws["root"], "C:/Users/dev/proj");
    }

    #[test]
    fn stats_last_use_promotes_freshest_workspace() {
        // #717: batch-save lag means the session JSON can be minutes old
        // while the proxy is actively serving — stats.last_use closes the gap.
        let sessions = vec![
            summary("/home/dev/alpha", 30, 5, None),
            summary("/home/dev/beta", 90, 3, None),
        ];
        let out = collect_workspaces(Utc::now(), sessions.clone(), Some(Utc::now()));
        assert_eq!(out[0]["root"], "/home/dev/alpha");
        assert_eq!(
            out[0]["status"], "active",
            "last_use must lift idle → active"
        );
        // Second workspace keeps its own (idle) freshness.
        assert_eq!(out[1]["status"], "idle");
        // Without last_use the same input stays idle.
        let out = collect_workspaces(Utc::now(), sessions, None);
        assert_eq!(out[0]["status"], "idle");
    }

    #[test]
    fn broad_roots_and_rootless_sessions_are_skipped() {
        let mut no_root = summary("/home/dev/proj", 5, 1, None);
        no_root.project_root = None;
        let sessions = vec![no_root, summary("/", 5, 1, None)];
        {
            let found = &collect_workspaces(Utc::now(), sessions, None);
            assert!(found.is_empty(), "{found:?}");
        }
    }
}

#[cfg(test)]
mod dashboard_memory_admission_tests {
    use super::*;
    use lean_ctx::core::data_dir::isolated_data_dir;

    #[test]
    fn dashboard_intent_reads_only_admitted_project_session() {
        let _isolated = isolated_data_dir();
        let project = tempfile::tempdir().expect("project root");
        let root = project.path().to_str().expect("UTF-8 project root");
        let mut session = lean_ctx::core::session::SessionState::new();
        session.project_root = Some(root.to_string());
        session.shell_cwd = session.project_root.clone();
        let mut intent =
            lean_ctx::core::intent_engine::StructuredIntent::from_query("ordinary task");
        intent.keywords = vec!["TOP SECRET\nprivate intent".to_string()];
        session.active_structured_intent = Some(intent);

        let sessions_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()
            .expect("isolated data directory")
            .join("sessions");
        std::fs::create_dir_all(&sessions_dir).expect("create sessions directory");
        let path = sessions_dir.join(format!("{}.json", session.id));
        std::fs::write(
            &path,
            serde_json::to_string(&session).expect("serialize raw fixture"),
        )
        .expect("write raw session fixture");

        let body = intent_json(root).expect("admitted intent response");
        assert!(!body.contains("TOP SECRET"), "restricted intent escaped");
        let payload: serde_json::Value =
            serde_json::from_str(&body).expect("dashboard response remains JSON");
        assert_eq!(payload["active"], true);
        assert!(payload["intent"]["keywords"].as_array().unwrap().is_empty());
    }

    #[test]
    fn dashboard_rejects_policy_change_before_returning_content() {
        let _isolated = isolated_data_dir();
        let project = tempfile::tempdir().expect("project root");
        let root = project.path().to_str().expect("UTF-8 project root");
        let config_dir =
            lean_ctx::core::paths::config_dir_read_only().expect("isolated config dir");
        std::fs::create_dir_all(&config_dir).expect("create config dir");
        std::fs::write(
            config_dir.join("config.toml"),
            "[context_gateway]\nenabled = true\nmode = \"developer\"\n",
        )
        .expect("initial gateway policy");

        let result = with_dashboard_project(root, |_hash, _admission, _authority| {
            std::fs::write(
                config_dir.join("config.toml"),
                "[context_gateway]\nenabled = true\nmode = \"governed\"\n",
            )
            .map_err(|error| error.to_string())?;
            Ok(())
        });
        assert!(result.is_err(), "stale policy snapshot was accepted");
    }

    fn project_with_session(parent: &Path, name: &str) -> String {
        let root = parent.join(name);
        std::fs::create_dir_all(root.join(".git")).expect("project root");
        let root = root.to_string_lossy().into_owned();
        let mut session = lean_ctx::core::session::SessionState::new();
        session.project_root = Some(root.clone());
        session.save().expect("save session");
        root
    }

    fn notes(root: &str) -> Vec<String> {
        lean_ctx::core::session::SessionState::load_latest_for_project_root(root)
            .expect("project session")
            .progress
            .into_iter()
            .filter(|entry| entry.action == "note")
            .filter_map(|entry| entry.detail)
            .collect()
    }

    /// F12b: a session note goes to the named project's newest session, never
    /// to the newest session of another project.
    #[test]
    fn dashboard_session_note_goes_to_the_projects_own_session() {
        let _isolated = isolated_data_dir();
        let projects = tempfile::tempdir().expect("projects");
        let alpha = project_with_session(projects.path(), "alpha");
        // Beta's session is the newest one of any project.
        let beta = project_with_session(projects.path(), "beta");

        assert!(append_session_note(&alpha, "alpha note").expect("admitted note"));
        assert_eq!(notes(&alpha), vec!["alpha note".to_string()]);
        assert!(notes(&beta).is_empty(), "the note went to another project");

        let empty = projects.path().join("empty");
        std::fs::create_dir_all(empty.join(".git")).expect("empty project");
        assert!(
            !append_session_note(&empty.to_string_lossy(), "nowhere").expect("no session"),
            "a project without a session takes no note"
        );

        let refused = lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
            std::cell::RefCell::new(Some(std::path::PathBuf::from(&beta))),
            || append_session_note(&alpha, "crossed"),
        );
        assert!(refused.is_err(), "a foreign request project was accepted");
        assert_eq!(notes(&alpha), vec!["alpha note".to_string()]);
    }

    #[test]
    fn retired_episode_and_procedure_routes_answer_the_retirement_only() {
        let _isolated = isolated_data_dir();
        for (path, method) in [
            ("/api/episodes", "GET"),
            ("/api/procedures", "GET"),
            ("/api/episodes/annotate", "POST"),
        ] {
            let (status, kind, body) = handle(
                path,
                "task=x",
                method,
                r#"{"episode_index":0,"outcome":"success"}"#,
            )
            .expect("retired route stays accepted");
            assert_eq!((status, kind), ("200 OK", "application/json"), "{path}");
            let value: serde_json::Value = serde_json::from_str(&body).expect("JSON");
            assert_eq!(value["retired"], serde_json::json!(true), "{path}");
            assert!(
                value["message"]
                    .as_str()
                    .is_some_and(|m| m.contains("/api/knowledge")),
                "{path}: {body}"
            );
        }
    }

    #[test]
    fn dashboard_rejects_foreign_request_project() {
        let _isolated = isolated_data_dir();
        let project = tempfile::tempdir().expect("selected project");
        let foreign = tempfile::tempdir().expect("foreign project");
        let selected_root = project.path().to_str().expect("selected root");
        let result = lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
            std::cell::RefCell::new(Some(foreign.path().to_path_buf())),
            || intent_json(selected_root),
        );
        assert!(result.is_err(), "foreign request root was accepted");
    }
}