lean-ctx 3.9.20

Local Context SDK for AI agents. Select, shape, reuse, recover, and measure context before inference.
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
//! Dashboard leaderboard API (#466) — submit this machine's recap to the public
//! board, flip auto-submit, and link multiple machines (GH #736), without
//! dropping to `lean-ctx gain --publish` or `--link`.
//!
//! - `GET  /api/leaderboard/status` → current publish / leaderboard / auto-submit
//!   state ([`wrapped_publish::leaderboard_status`]) the card renders.
//! - `POST /api/leaderboard/submit` → sign + publish the all-time recap with
//!   leaderboard opt-in (optional `{ "name": "handle" }`); returns the permalink.
//! - `POST /api/leaderboard/auto`   → `{ "on": true|false }` flips `[gain]
//!   auto_publish` (and opts in to the board when turning it on).
//! - `POST /api/leaderboard/link/start`    → mint a pairing code for this card.
//! - `POST /api/leaderboard/link/complete` → `{ "code": "XXXX-XXXX" }` joins
//!   this card into the initiator's link group (login-less machine linking).
//!
//! Security: like every dashboard mutation, the POSTs are Bearer-token gated and
//! CSRF-`Origin` checked *before* the router runs (see `dashboard/mod.rs`). The
//! submit body is the *same* minimal, whitelisted aggregate the CLI sends — only
//! tokens saved, est. USD, compression rate and the chosen handle, never code,
//! paths or prompts (enforced by `cli::wrapped_publish::build_payload` + the
//! server whitelist).

use serde::Deserialize;

use super::helpers::json_err;
use crate::cli::wrapped_publish;

pub(super) fn handle(
    path: &str,
    _query_str: &str,
    method: &str,
    body: &str,
) -> Option<(&'static str, &'static str, String)> {
    match path {
        "/api/leaderboard" => Some(get_board()),
        "/api/leaderboard/status" => Some(get_status()),
        "/api/leaderboard/submit" if method.eq_ignore_ascii_case("POST") => Some(post_submit(body)),
        "/api/leaderboard/submit" => Some(method_not_allowed("submit a leaderboard entry")),
        "/api/leaderboard/auto" if method.eq_ignore_ascii_case("POST") => Some(post_auto(body)),
        "/api/leaderboard/auto" => Some(method_not_allowed("toggle auto-submit")),
        "/api/leaderboard/link/start" if method.eq_ignore_ascii_case("POST") => {
            Some(post_link_start())
        }
        "/api/leaderboard/link/start" => Some(method_not_allowed("start a machine link")),
        "/api/leaderboard/link/complete" if method.eq_ignore_ascii_case("POST") => {
            Some(post_link_complete(body))
        }
        "/api/leaderboard/link/complete" => Some(method_not_allowed("complete a machine link")),
        "/api/leaderboard/phrase" => Some(get_phrase()),
        "/api/leaderboard/rejoin" if method.eq_ignore_ascii_case("POST") => Some(post_rejoin(body)),
        "/api/leaderboard/rejoin" => Some(method_not_allowed("rejoin with a recovery phrase")),
        _ => None,
    }
}

/// A GET on a mutating endpoint is a client bug; say so explicitly (with the
/// right verb) instead of a generic 404 so the mistake is obvious.
fn method_not_allowed(action: &str) -> (&'static str, &'static str, String) {
    (
        "405 Method Not Allowed",
        "application/json",
        json_err(&format!("use POST to {action}")),
    )
}

fn get_phrase() -> (&'static str, &'static str, String) {
    let agent_id = crate::cli::wrapped_publish::publisher_agent_id_for_dashboard();
    let phrase = crate::core::agent_identity::stored_recovery_phrase(&agent_id);
    let json = serde_json::json!({
        "has_phrase": phrase.is_some(),
        "phrase": phrase,
    });
    ("200 OK", "application/json", json.to_string())
}

fn post_rejoin(body: &str) -> (&'static str, &'static str, String) {
    #[derive(Deserialize)]
    struct RejoinBody {
        phrase: String,
    }
    let parsed: RejoinBody = match serde_json::from_str(body) {
        Ok(p) => p,
        Err(e) => {
            return (
                "400 Bad Request",
                "application/json",
                json_err(&format!("invalid body: {e}")),
            );
        }
    };
    let phrase = parsed.phrase.trim();
    if phrase.is_empty() {
        return (
            "400 Bad Request",
            "application/json",
            json_err("phrase must not be empty"),
        );
    }
    let word_count = phrase.split_whitespace().count();
    if word_count < 4 {
        return (
            "400 Bad Request",
            "application/json",
            json_err(&format!("expected 4 words, got {word_count}")),
        );
    }
    let agent_id = crate::cli::wrapped_publish::publisher_agent_id_for_dashboard();
    match crate::core::agent_identity::import_phrase_identity(&agent_id, phrase) {
        Ok(key) => {
            let pub_hex = crate::core::agent_identity::hex_encode(&key.verifying_key().to_bytes());
            let json = serde_json::json!({
                "ok": true,
                "publisher_id_prefix": &pub_hex[..16.min(pub_hex.len())],
            });
            ("200 OK", "application/json", json.to_string())
        }
        Err(e) => (
            "500 Internal Server Error",
            "application/json",
            json_err(&e),
        ),
    }
}

/// Same-origin proxy for the public community board (`GET /api/leaderboard`).
/// The dashboard CSP pins `connect-src` to `'self'`, so the browser cannot fetch
/// `api.leanctx.com` directly — we fetch it here and pass the JSON straight
/// through. A 502 (with the upstream error) lets the UI show "couldn't load the
/// board" without breaking the rest of the view.
fn get_board() -> (&'static str, &'static str, String) {
    match crate::cloud_client::fetch_leaderboard() {
        Ok(json) => ("200 OK", "application/json", json.to_string()),
        Err(e) => (
            "502 Bad Gateway",
            "application/json",
            json_err(&format!("could not load leaderboard: {e}")),
        ),
    }
}

fn get_status() -> (&'static str, &'static str, String) {
    let status = wrapped_publish::leaderboard_status();
    serde_json::to_string(&status).map_or_else(
        |e| {
            (
                "500 Internal Server Error",
                "application/json",
                json_err(&format!("failed to serialize leaderboard status: {e}")),
            )
        },
        |body| ("200 OK", "application/json", body),
    )
}

/// An empty body is a valid "submit with my saved handle" request, so `name`
/// defaults to `None` rather than being required.
#[derive(Deserialize, Default)]
struct SubmitReq {
    #[serde(default)]
    name: Option<String>,
}

fn post_submit(body: &str) -> (&'static str, &'static str, String) {
    let req: SubmitReq = if body.trim().is_empty() {
        SubmitReq::default()
    } else {
        match serde_json::from_str(body) {
            Ok(r) => r,
            Err(e) => {
                return (
                    "400 Bad Request",
                    "application/json",
                    json_err(&format!("invalid JSON: {e}")),
                );
            }
        }
    };

    match wrapped_publish::submit_leaderboard(req.name.as_deref()) {
        Ok(card) => {
            let body = serde_json::json!({
                "ok": true,
                "url": card.url,
                "id": card.id,
            })
            .to_string();
            ("200 OK", "application/json", body)
        }
        // "Nothing to publish yet" is a client-state problem (no savings), not an
        // upstream failure — distinguish it so the UI can word the message right.
        Err(e) if e.starts_with("Nothing to publish") => {
            ("409 Conflict", "application/json", json_err(&e))
        }
        Err(e) => (
            "502 Bad Gateway",
            "application/json",
            json_err(&format!("leaderboard submit failed: {e}")),
        ),
    }
}

#[derive(Deserialize)]
struct AutoReq {
    on: bool,
}

fn post_auto(body: &str) -> (&'static str, &'static str, String) {
    let req: AutoReq = match serde_json::from_str(body) {
        Ok(r) => r,
        Err(e) => {
            return (
                "400 Bad Request",
                "application/json",
                json_err(&format!(
                    "invalid JSON (expected {{\"on\":true|false}}): {e}"
                )),
            );
        }
    };

    match wrapped_publish::set_auto_submit(req.on) {
        // Echo the fresh state so the UI repaints from the source of truth.
        Ok(()) => get_status(),
        Err(e) => (
            "500 Internal Server Error",
            "application/json",
            json_err(&e),
        ),
    }
}

// ─── Login-less machine linking (GH #736) ─────────────────────────────────────

/// Mint a pairing code for this machine’s card. The dashboard proxies the cloud
/// API so the browser never reaches `api.leanctx.com` directly (CSP `connect-src`
/// = `'self'`). Auth is the card’s `edit_token`, not the dashboard bearer token.
fn post_link_start() -> (&'static str, &'static str, String) {
    match wrapped_publish::link_start() {
        Ok(minted) => {
            let body = serde_json::json!({
                "ok": true,
                "code": minted.code,
                "expires_in_secs": minted.expires_in_secs,
            })
            .to_string();
            ("200 OK", "application/json", body)
        }
        Err(e) if e.contains("No published card") => {
            ("409 Conflict", "application/json", json_err(&e))
        }
        Err(e) => (
            "502 Bad Gateway",
            "application/json",
            json_err(&format!("link start failed: {e}")),
        ),
    }
}

#[derive(Deserialize)]
struct LinkCompleteReq {
    code: String,
}

/// Complete a machine link using a pairing code from another machine. The
/// dashboard sends `{ "code": "XXXX-XXXX" }` and this proxies the cloud API.
fn post_link_complete(body: &str) -> (&'static str, &'static str, String) {
    let req: LinkCompleteReq = match serde_json::from_str(body) {
        Ok(r) => r,
        Err(e) => {
            return (
                "400 Bad Request",
                "application/json",
                json_err(&format!(
                    "invalid JSON (expected {{\"code\":\"XXXX-XXXX\"}}): {e}"
                )),
            );
        }
    };

    match wrapped_publish::link_complete(&req.code) {
        Ok(()) => {
            let body = serde_json::json!({ "ok": true, "linked": true }).to_string();
            ("200 OK", "application/json", body)
        }
        Err(e) if e.contains("No published card") => {
            ("409 Conflict", "application/json", json_err(&e))
        }
        Err(e) if e.contains("invalid or expired") => {
            ("410 Gone", "application/json", json_err(&e))
        }
        Err(e) => (
            "502 Bad Gateway",
            "application/json",
            json_err(&format!("link complete failed: {e}")),
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn status_returns_expected_shape() {
        let (status, mime, body) =
            handle("/api/leaderboard/status", "", "GET", "").expect("route matches");
        assert_eq!(status, "200 OK");
        assert_eq!(mime, "application/json");
        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
        // The four bool/flag fields the card always renders must be present and
        // correctly typed regardless of this machine's publish history.
        assert!(v["published"].is_boolean(), "published must be a bool");
        assert!(v["on_leaderboard"].is_boolean(), "on_leaderboard bool");
        assert!(v["auto_submit"].is_boolean(), "auto_submit must be a bool");
        // display_name / url / last_published_at are nullable — keys must exist.
        for key in ["display_name", "url", "last_published_at"] {
            assert!(v.get(key).is_some(), "status must carry '{key}'");
        }
    }

    #[test]
    fn submit_rejects_get_with_405() {
        let (status, _mime, body) =
            handle("/api/leaderboard/submit", "", "GET", "").expect("route matches");
        assert_eq!(status, "405 Method Not Allowed");
        assert!(
            body.contains("POST"),
            "the 405 must hint at the right method"
        );
    }

    #[test]
    fn auto_rejects_get_with_405() {
        let (status, _mime, _body) =
            handle("/api/leaderboard/auto", "", "GET", "").expect("route matches");
        assert_eq!(status, "405 Method Not Allowed");
    }

    #[test]
    fn auto_rejects_invalid_json_with_400() {
        let (status, _mime, body) =
            handle("/api/leaderboard/auto", "", "POST", "not json").expect("route matches");
        assert_eq!(status, "400 Bad Request");
        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON error");
        assert!(v["error"].is_string(), "400 must carry an error message");
    }

    #[test]
    fn submit_rejects_malformed_json_with_400() {
        // A non-empty, non-JSON body is a client error — must not reach the network.
        let (status, _mime, _body) =
            handle("/api/leaderboard/submit", "", "POST", "{bad").expect("route matches");
        assert_eq!(status, "400 Bad Request");
    }

    /// The board proxy is wired and degrades gracefully: pointed at an
    /// unreachable upstream it returns a well-formed 502 JSON instead of
    /// hanging or panicking (no real network needed — the connection refuses
    /// immediately).
    #[test]
    fn board_proxy_is_wired_and_degrades_to_502() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_API_URL", "http://127.0.0.1:1");
        let res = handle("/api/leaderboard", "", "GET", "");
        crate::test_env::remove_var("LEAN_CTX_API_URL");
        let (status, mime, body) = res.expect("route matches /api/leaderboard");
        assert_eq!(mime, "application/json");
        assert_eq!(status, "502 Bad Gateway");
        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON error");
        assert!(v["error"].is_string(), "502 must carry an error message");
    }

    #[test]
    fn unrelated_paths_pass_through() {
        assert!(handle("/api/stats", "", "GET", "").is_none());
        assert!(handle("/api/leaderboardx", "", "GET", "").is_none());
        assert!(handle("/", "", "GET", "").is_none());
    }

    #[test]
    fn link_start_rejects_get_with_405() {
        let (status, _mime, body) =
            handle("/api/leaderboard/link/start", "", "GET", "").expect("route matches");
        assert_eq!(status, "405 Method Not Allowed");
        assert!(body.contains("POST"), "405 must hint at POST");
    }

    #[test]
    fn link_complete_rejects_get_with_405() {
        let (status, _mime, _body) =
            handle("/api/leaderboard/link/complete", "", "GET", "").expect("route matches");
        assert_eq!(status, "405 Method Not Allowed");
    }

    #[test]
    fn link_complete_rejects_invalid_json_with_400() {
        let (status, _mime, body) =
            handle("/api/leaderboard/link/complete", "", "POST", "not json")
                .expect("route matches");
        assert_eq!(status, "400 Bad Request");
        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON error");
        assert!(v["error"].is_string(), "400 must carry an error message");
    }
}