comindly 0.1.0

Deterministic, always-fresh, cross-repo code intelligence for coding agents — self-hosted, single binary.
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Local web UI (`comindly ui --web`): one embedded page over a small JSON API, bound to
//! 127.0.0.1. Ledger reviews write to the index root like the terminal UI.

use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use anyhow::{Context, Result};
use axum::extract::{Query, State};
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::{json, Value};
use tokio::sync::{OnceCell, RwLock};

use crate::graph::{Node, Zoom};
use crate::ledger::{Entry, Provenance, Record, RelationKind, Status};
use crate::tui::Data;

mod aws;
mod repos;
mod settings;
mod team;

mod assets {
    include!(concat!(env!("OUT_DIR"), "/ui_assets.rs"));
}

/// Everything tied to one loaded index; replaced as a whole when the index changes.
struct Session {
    data: Data,
    entries: RwLock<Vec<Entry>>,
    manual: RwLock<Vec<crate::conventions::Manual>>,
    /// Loaded on first use: LLM summaries and flows, and the search model.
    extras: OnceCell<Extras>,
    search: OnceCell<Option<Search>>,
    /// The index's tables, held open so LanceDB caches their metadata and indexes.
    tables: Option<crate::index::Tables>,
    /// Org maps of earlier index versions, by position in `/api/versions`.
    past: tokio::sync::Mutex<HashMap<usize, Value>>,
}

#[derive(Default)]
struct Extras {
    enrichment: crate::search::Enrichment,
    flows: HashMap<String, (String, Vec<String>)>,
}

struct Search {
    embedder: crate::embed::Embedder,
    by_id: HashMap<String, crate::model::Symbol>,
}

impl Session {
    async fn extras(&self) -> &Extras {
        self.extras
            .get_or_init(|| async {
                let Some(uri) = graph_uri(self) else {
                    return Extras::default();
                };
                let enrichment = crate::index::read_enrichment(&uri).await.ok().flatten();
                let flows = crate::index::read_flows(&uri).await.ok().flatten();
                Extras {
                    enrichment: enrichment
                        .unwrap_or_default()
                        .into_iter()
                        .map(|(id, s, q)| (id.render(), (s, q)))
                        .collect(),
                    flows: flows
                        .unwrap_or_default()
                        .into_iter()
                        .map(|(id, n, q)| (id.render(), (n, q)))
                        .collect(),
                }
            })
            .await
    }

    async fn search(&self) -> Option<&Search> {
        self.search
            .get_or_init(|| async {
                let embedder = tokio::task::spawn_blocking(crate::embed::Embedder::load_default)
                    .await
                    .ok()?
                    .ok()?;
                let by_id = self
                    .data
                    .symbols
                    .iter()
                    .map(|s| (s.id.render(), s.clone()))
                    .collect();
                Some(Search { embedder, by_id })
            })
            .await
            .as_ref()
    }
}

struct AppState {
    current: RwLock<Arc<Session>>,
    job: tokio::sync::Mutex<repos::Job>,
    watch: tokio::sync::Mutex<repos::Watch>,
    signin: tokio::sync::Mutex<aws::SignIn>,
}

type Shared = Arc<AppState>;

/// The session a request works on: the index loaded when it arrived.
struct Cur(Arc<Session>);

impl axum::extract::FromRequestParts<Shared> for Cur {
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        _: &mut axum::http::request::Parts,
        app: &Shared,
    ) -> std::result::Result<Self, Self::Rejection> {
        Ok(Cur(app.current.read().await.clone()))
    }
}

impl Session {
    async fn open(mut data: Data) -> Session {
        let entries = std::mem::take(&mut data.entries);
        let manual = std::mem::take(&mut data.manual);
        let tables = match data.root.as_ref() {
            Some(r) => {
                let uri = format!("{}/_graph", r.trim_end_matches('/'));
                let fresh = crate::config::Config::load().fresh();
                crate::index::Tables::connect(&uri, fresh).await.ok()
            }
            None => None,
        };
        Session {
            data,
            entries: RwLock::new(entries),
            manual: RwLock::new(manual),
            extras: OnceCell::new(),
            search: OnceCell::new(),
            tables,
            past: Default::default(),
        }
    }
}

impl AppState {
    /// Load the index at `root` and make it the one every request sees.
    async fn reload(&self, root: &str) -> Result<()> {
        let root = root.to_string();
        let data = tokio::task::spawn_blocking(move || Data::load_or_empty(&root)).await?;
        *self.current.write().await = Arc::new(Session::open(data).await);
        Ok(())
    }
}

/// Serve the UI on `listener` (bound to 127.0.0.1) until the process ends. API calls must carry
/// `token` as a cookie; opening any page with `?token=` sets it.
pub fn serve(data: Data, listener: std::net::TcpListener, token: String) -> Result<()> {
    let rt = tokio::runtime::Runtime::new()?;
    let state = Arc::new(AppState {
        current: RwLock::new(Arc::new(rt.block_on(Session::open(data)))),
        job: Default::default(),
        watch: Default::default(),
        signin: Default::default(),
    });
    rt.spawn(repos::watch(state.clone()));
    let app = Router::new()
        .route("/api/overview", get(overview))
        .route("/api/orgmap", get(orgmap))
        .route("/api/versions", get(versions))
        .route("/api/contracts", get(contracts))
        .route("/api/ledger", get(ledger))
        .route("/api/conventions", get(conventions).post(change_convention))
        .route("/api/find", get(find))
        .route("/api/node", get(node))
        .route("/api/search", get(search))
        .route("/api/context", get(context))
        .route("/api/packages", get(packages))
        .route("/api/setup", get(setup))
        .route("/api/review", post(review))
        .route("/api/erase", post(erase))
        .route("/api/remember", post(remember))
        .route("/api/settings", get(settings::get).post(settings::save))
        .route("/api/settings/test", post(settings::test))
        .route("/api/repos", get(repos::list).post(repos::change))
        .route("/api/repos/scan", post(repos::scan))
        .route("/api/repos/clone", post(repos::clone))
        .route("/api/index", get(repos::job).post(repos::start))
        .route("/api/index/watch", get(repos::watch_state))
        .route("/api/team", get(team::get).post(team::save))
        .route("/api/team/key", post(team::key))
        .route("/api/join", post(team::join))
        .route("/api/aws", get(aws::status))
        .route("/api/aws/login", post(aws::start))
        .fallback(get(asset))
        .layer(axum::middleware::from_fn_with_state(Arc::new(token), guard))
        .layer(axum::middleware::from_fn(local_only))
        .with_state(state);
    listener.set_nonblocking(true)?;
    rt.block_on(async move {
        let listener = tokio::net::TcpListener::from_std(listener)?;
        axum::serve(listener, app).await.context("serve")
    })
}

/// A random token for one UI session.
pub fn new_token() -> String {
    uuid::Uuid::new_v4().simple().to_string()
}

/// `?token=` on a page sets the session cookie and redirects to the clean URL; `/api/` requires it.
async fn guard(
    State(token): State<Arc<String>>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let query = req.uri().query().unwrap_or("");
    if query.split('&').any(|kv| kv == format!("token={token}")) {
        let rest: Vec<&str> = query
            .split('&')
            .filter(|kv| !kv.starts_with("token="))
            .collect();
        let path = req.uri().path();
        let to = if rest.is_empty() {
            path.to_string()
        } else {
            format!("{path}?{}", rest.join("&"))
        };
        let cookie =
            format!("comindly_token={token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=31536000");
        return (
            StatusCode::SEE_OTHER,
            [(header::LOCATION, to), (header::SET_COOKIE, cookie)],
        )
            .into_response();
    }
    if req.uri().path().starts_with("/api/") {
        let want = format!("comindly_token={token}");
        let ok = req
            .headers()
            .get_all(header::COOKIE)
            .iter()
            .filter_map(|v| v.to_str().ok())
            .flat_map(|v| v.split(';'))
            .any(|c| c.trim() == want);
        if !ok {
            let msg =
                "open comindly with the link `comindly ui --web` printed (it carries the access token)";
            return (StatusCode::FORBIDDEN, Json(json!({ "error": msg }))).into_response();
        }
    }
    next.run(req).await
}

/// Reject requests whose `Host` is not loopback, so a DNS-rebinding page cannot read the API.
async fn local_only(
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let host = req
        .headers()
        .get(header::HOST)
        .and_then(|h| h.to_str().ok())
        .unwrap_or("");
    let name = host.rsplit_once(':').map_or(host, |(h, _)| h);
    if matches!(name, "127.0.0.1" | "localhost" | "[::1]") {
        next.run(req).await
    } else {
        (
            StatusCode::FORBIDDEN,
            "comindly web UI answers on localhost only",
        )
            .into_response()
    }
}

/// The embedded UI: a file by path, or `index.html` for client-side routes.
async fn asset(uri: axum::http::Uri) -> impl IntoResponse {
    let path = uri.path().trim_start_matches('/');
    let find = |p: &str| {
        assets::ASSETS
            .iter()
            .find(|(n, _)| *n == p)
            .map(|(_, b)| *b)
    };
    let (name, body) = match find(path) {
        Some(b) if !path.is_empty() => (path, b),
        _ if path.starts_with("api/") || path.starts_with("assets/") => {
            return (
                StatusCode::NOT_FOUND,
                [(header::CONTENT_TYPE, "text/plain")],
                &b"not found"[..],
            )
                .into_response();
        }
        _ => ("index.html", find("index.html").unwrap_or_default()),
    };
    let mime = match name.rsplit('.').next() {
        Some("html") => "text/html; charset=utf-8",
        Some("js") => "text/javascript",
        Some("css") => "text/css",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("json") => "application/json",
        Some("woff2") => "font/woff2",
        _ => "application/octet-stream",
    };
    // Bundled assets carry a content hash in their name; the page itself must stay fresh.
    let cache = if name.starts_with("assets/") {
        "public, max-age=31536000, immutable"
    } else {
        "no-cache"
    };
    (
        StatusCode::OK,
        [(header::CONTENT_TYPE, mime), (header::CACHE_CONTROL, cache)],
        body,
    )
        .into_response()
}

async fn overview(Cur(s): Cur) -> Json<Value> {
    let d = &s.data;
    let entries = s.entries.read().await;
    let mut status: BTreeMap<String, usize> = BTreeMap::new();
    for e in entries.iter() {
        *status
            .entry(format!("{:?}", e.status).to_lowercase())
            .or_default() += 1;
    }
    let linked = d
        .contracts
        .iter()
        .filter(|c| !c.providers.is_empty() && !c.consumers.is_empty())
        .count();
    let cross = d.edges.iter().filter(|e| e.cross_repo).count();
    let skew: Vec<Value> = d
        .deps
        .iter()
        .filter(|x| x.skewed())
        .map(|x| {
            json!({"package": x.name, "publisher": x.publisher, "published": x.published,
                   "consumer": x.consumer, "locked": x.locked})
        })
        .collect();
    Json(json!({
        "repos": d.graph.repos().into_iter().map(|(r, n)| json!({"repo": r, "symbols": n})).collect::<Vec<_>>(),
        "symbols": d.symbols.len(),
        "edges": d.edges.len(),
        "cross_repo_edges": cross,
        "contracts": d.contracts.len(),
        "linked_contracts": linked,
        "ledger": status,
        "skew": skew,
        "writable": d.root.is_some(),
        "root": d.root,
        "problem": d.problem,
    }))
}

#[derive(Deserialize)]
struct AtQ {
    /// Index into `/api/versions` (oldest first); absent = the loaded (latest) graph.
    at: Option<usize>,
}

/// An error for the UI: short, with S3 replies explained and credentials removed.
pub(crate) fn error_text(e: &anyhow::Error) -> String {
    crate::s3::explain(&format!("{e:#}"))
}

fn graph_uri(s: &Session) -> Option<String> {
    s.data
        .root
        .as_ref()
        .map(|r| format!("{}/_graph", r.trim_end_matches('/')))
}

async fn versions(Cur(s): Cur) -> Json<Value> {
    let list = match &s.tables {
        Some(t) => t.versions().await.unwrap_or_default(),
        None => Vec::new(),
    };
    Json(json!(list
        .into_iter()
        .map(|(_, _, t)| t)
        .collect::<Vec<_>>()))
}

async fn orgmap(Cur(s): Cur, Query(q): Query<AtQ>) -> impl IntoResponse {
    let d = &s.data;
    let Some(i) = q.at else {
        return (
            StatusCode::OK,
            Json(org(&d.graph, &d.symbols, &d.edges, &d.contracts)),
        );
    };
    let past = async {
        if let Some(v) = s.past.lock().await.get(&i) {
            return anyhow::Ok(v.clone());
        }
        let tables = s
            .tables
            .as_ref()
            .context("read-only UI has no index root")?;
        let list = tables.versions().await?;
        let (sv, ev, _) = *list.get(i).context("no such version")?;
        let (symbols, edges) = tables.graph_at((sv, ev)).await?;
        let graph = crate::graph::CodeGraph::build(&symbols, &edges);
        let contracts = graph.contracts(None, false);
        let v = org(&graph, &symbols, &edges, &contracts);
        s.past.lock().await.insert(i, v.clone());
        anyhow::Ok(v)
    };
    match past.await {
        Ok(v) => (StatusCode::OK, Json(v)),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": error_text(&e)})),
        ),
    }
}

/// Repos as nodes; edges aggregate cross-repo code dependencies and contract links.
fn org(
    graph: &crate::graph::CodeGraph,
    symbols: &[crate::model::Symbol],
    edges: &[crate::model::Edge],
    contracts: &[crate::graph::ContractView],
) -> Value {
    let repo_of: std::collections::HashMap<String, &str> = symbols
        .iter()
        .map(|x| (x.id.render(), x.repo.0.as_str()))
        .collect();
    let mut links: BTreeMap<(String, String, &str), usize> = BTreeMap::new();
    for e in edges.iter().filter(|e| e.cross_repo) {
        if let (Some(a), Some(b)) = (repo_of.get(&e.src.render()), repo_of.get(&e.dst.render())) {
            if *a != crate::resolve::CONTRACTS && *b != crate::resolve::CONTRACTS && a != b {
                *links
                    .entry((a.to_string(), b.to_string(), "code"))
                    .or_default() += 1;
            }
        }
    }
    let real = |n: &&Node| n.repo != crate::resolve::CONTRACTS;
    // A queue subscribed to a topic is a contract consuming a contract: its own consumers are
    // the topic's consumers too.
    let by_id: std::collections::HashMap<&str, &crate::graph::ContractView> = contracts
        .iter()
        .map(|c| (c.contract.id.as_str(), c))
        .collect();
    for c in contracts {
        let mut consumers: Vec<&Node> = c.consumers.iter().filter(real).collect();
        for via in c.consumers.iter().filter(|n| !real(n)) {
            if let Some(q) = by_id.get(via.id.as_str()) {
                consumers.extend(q.consumers.iter().filter(real));
            }
        }
        for u in consumers {
            for p in c.providers.iter().filter(real).filter(|p| p.repo != u.repo) {
                *links
                    .entry((u.repo.clone(), p.repo.clone(), "contract"))
                    .or_default() += 1;
            }
        }
    }
    let nodes: Vec<Value> = graph
        .repos()
        .into_iter()
        .map(|(r, n)| json!({"id": r, "name": format!("{r} ({n})"), "repo": r, "location": ""}))
        .collect();
    let edges: Vec<Value> = links
        .into_iter()
        .map(|((a, b, k), n)| json!({"src": a, "dst": b, "kind": k, "weight": n}))
        .collect();
    json!({"nodes": nodes, "edges": edges})
}

async fn contracts(Cur(s): Cur) -> Json<Value> {
    Json(json!(s.data.contracts))
}

async fn ledger(Cur(s): Cur) -> Json<Value> {
    let entries = s.entries.read().await;
    let mut v: Vec<&Entry> = entries.iter().collect();
    v.sort_by(|a, b| b.record.created.cmp(&a.record.created));
    Json(named(&s, &v))
}

/// Entries as JSON with each anchor named as the graph shows it (`Class.method`).
fn named(s: &Session, entries: &[&Entry]) -> Value {
    let mut v = json!(entries);
    for e in v.as_array_mut().into_iter().flatten() {
        for a in e["record"]["anchors"].as_array_mut().into_iter().flatten() {
            if let Some(i) = a["symbol"].as_str().and_then(|id| s.data.graph.lookup(id)) {
                a["name"] = json!(s.data.graph.node(i).name);
            }
        }
    }
    v
}

#[derive(Deserialize)]
struct RepoQ {
    repo: Option<String>,
}

async fn conventions(Cur(s): Cur, Query(q): Query<RepoQ>) -> Json<Value> {
    let manual = s.manual.read().await;
    let mine = |r: &str| q.repo.as_deref().is_none_or(|q| r == q);
    let shown: Vec<Value> = crate::conventions::apply(s.data.conventions.clone(), &manual)
        .into_iter()
        .filter(|c| mine(&c.repo))
        .map(|c| {
            let mut v = json!(c);
            v["id"] = json!(c.id());
            v
        })
        .collect();
    let hidden: Vec<_> = manual
        .iter()
        .filter(|m| m.hidden && mine(&m.repo))
        .collect();
    Json(json!({ "conventions": shown, "hidden": hidden }))
}

#[derive(Deserialize)]
struct ConventionBody {
    /// `add`, `edit`, `hide` or `restore`.
    action: String,
    #[serde(default)]
    id: String,
    #[serde(default)]
    repo: Option<String>,
    #[serde(default)]
    dimension: Option<String>,
    #[serde(default)]
    rule: String,
}

async fn change_convention(Cur(s): Cur, Json(b): Json<ConventionBody>) -> impl IntoResponse {
    match apply_convention(&s, b).await {
        Ok(msg) => (StatusCode::OK, Json(json!({"ok": true, "message": msg}))),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"ok": false, "message": error_text(&e)})),
        ),
    }
}

async fn apply_convention(s: &Session, b: ConventionBody) -> Result<String> {
    use crate::conventions::{change, Change, Manual, Write, ORG};
    let root = s.data.root.as_deref().context("read-only UI")?;
    let mut manual = s.manual.write().await;
    let w = if b.action == "add" {
        let dimension = b.dimension.as_deref().unwrap_or("team");
        Write::Put(Manual::new(
            b.repo.as_deref().unwrap_or(ORG),
            dimension,
            &b.rule,
        ))
    } else {
        let what = match b.action.as_str() {
            "edit" => Change::Edit(b.rule),
            "hide" => Change::Hide,
            "restore" => Change::Restore,
            other => anyhow::bail!("unknown action {other}"),
        };
        let current = crate::conventions::apply(s.data.conventions.clone(), &manual);
        change(&current, &manual, &b.id, what)?
    };
    crate::conventions::Store::open(root)?.write(&w).await?;
    Ok(match w {
        Write::Put(m) => {
            let id = m.id.clone();
            manual.retain(|x| x.id != id);
            let verb = if m.hidden { "hid" } else { "saved" };
            manual.push(m);
            format!("{verb} {id}")
        }
        Write::Delete(id) => {
            manual.retain(|x| x.id != id);
            format!("removed {id}")
        }
    })
}

#[derive(Deserialize)]
struct FindQ {
    q: String,
}

async fn find(Cur(s): Cur, Query(q): Query<FindQ>) -> Json<Value> {
    Json(json!(s.data.graph.find(&q.q, 40)))
}

#[derive(Deserialize)]
struct NodeQ {
    focus: String,
}

async fn node(Cur(s): Cur, Query(q): Query<NodeQ>) -> impl IntoResponse {
    let g = &s.data.graph;
    let Some(idx) = g.lookup(&q.focus) else {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "no such symbol"})),
        );
    };
    let z = g.zoom(idx);
    let ripple = g.ripple(idx, 4);
    let mut repos: BTreeMap<String, usize> = BTreeMap::new();
    for h in &ripple {
        *repos.entry(h.node.repo.clone()).or_default() += 1;
    }
    let mut ids = vec![q.focus.clone()];
    if let Some(f) = &z.focus {
        ids.push(f.id.clone());
        if let Some((_, scope)) = g.scope_of(&f.id) {
            ids.extend(scope);
        }
    }
    let extras = s.extras().await;
    let fid = z.focus.as_ref().map(|f| f.id.clone()).unwrap_or_default();
    let summary = extras.enrichment.get(&fid).map(|(s, _)| s);
    let flow = extras
        .flows
        .get(&fid)
        .map(|(n, q)| json!({"narration": n, "questions": q}));
    let entries = s.entries.read().await;
    let about: Vec<&Entry> = crate::ledger::about(&entries, &ids);
    (
        StatusCode::OK,
        Json(json!({
            "zoom": z,
            "graph": neighbourhood(&z),
            "ripple": {"total": ripple.len(), "repos": repos},
            "ledger": named(&s, &about),
            "summary": summary,
            "flow": flow,
        })),
    )
}

#[derive(Deserialize)]
struct SearchQ {
    q: String,
    repo: Option<String>,
}

/// Hybrid code search (BM25, vectors, centrality), as `comindly search` and the MCP tool.
async fn search(Cur(s): Cur, Query(q): Query<SearchQ>) -> impl IntoResponse {
    let run = async {
        let tables = s.tables.as_ref().context("no index root")?;
        let engine = s
            .search()
            .await
            .context("the embedding model could not be loaded")?;
        let extras = s.extras().await;
        let limit = if q.repo.is_some() { 60 } else { 20 };
        let mut hits = crate::search::hybrid(
            tables,
            &engine.by_id,
            &s.data.graph,
            &extras.enrichment,
            &engine.embedder,
            &q.q,
            limit,
        )
        .await
        .map_err(|e| match format!("{e:#}").contains("was not found") {
            true => {
                anyhow::anyhow!("this index has no search table: rebuild it without --no-embed")
            }
            false => e.context("hybrid search failed"),
        })?;
        if let Some(r) = &q.repo {
            hits.retain(|h| &h.repo == r);
            hits.truncate(20);
        }
        anyhow::Ok(
            hits.into_iter()
                .map(|h| {
                    json!({"id": h.id, "name": h.name, "kind": h.kind, "repo": h.repo,
                           "location": h.location, "signature": h.signature,
                           "summary": h.summary, "dependents": h.deps})
                })
                .collect::<Vec<_>>(),
        )
    };
    match run.await {
        Ok(v) => (StatusCode::OK, Json(json!(v))),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": error_text(&e)})),
        ),
    }
}

#[derive(Deserialize)]
struct ContextQ {
    focus: String,
    budget: Option<usize>,
}

/// The context pack for a symbol as markdown, ready to paste into an agent.
async fn context(Cur(s): Cur, Query(q): Query<ContextQ>) -> impl IntoResponse {
    let g = &s.data.graph;
    let Some(idx) = g.lookup(&q.focus) else {
        return (StatusCode::NOT_FOUND, "no such symbol".to_string());
    };
    let extras = s.extras().await;
    let focus = g.node(idx);
    let pack = g.context_pack(idx, q.budget.unwrap_or(1500));
    let mut o = format!(
        "## Context for changing `{}` ({} · {})\n\nRead these first:\n\n",
        focus.name, focus.repo, focus.location
    );
    for (n, _) in pack.iter().filter(|(n, _)| n.id != focus.id) {
        o.push_str(&format!("- `{}` ({} · {})", n.name, n.repo, n.location));
        if let Some((sum, _)) = extras.enrichment.get(&n.id) {
            o.push_str(&format!(": {sum}"));
        }
        o.push('\n');
    }
    let mut ids: Vec<String> = pack.iter().map(|(n, _)| n.id.clone()).collect();
    ids.push(focus.id.clone());
    let entries = s.entries.read().await;
    let known: Vec<String> = crate::ledger::about(&entries, &ids)
        .into_iter()
        .filter(|e| e.trust >= crate::ledger::Trust::T2)
        .filter(|e| !matches!(e.status, Status::Superseded | Status::Retracted))
        .take(6)
        .map(crate::ledger::line)
        .collect();
    if !known.is_empty() {
        o.push_str("\nRecorded by the team:\n\n");
        for k in known {
            o.push_str(&format!("- {k}\n"));
        }
    }
    (StatusCode::OK, o)
}

async fn packages(Cur(s): Cur) -> Json<Value> {
    Json(json!(s
        .data
        .deps
        .iter()
        .map(
            |d| json!({"ecosystem": d.ecosystem, "name": d.name, "publisher": d.publisher,
                        "published": d.published, "consumer": d.consumer,
                        "requirement": d.requirement, "locked": d.locked, "skewed": d.skewed()})
        )
        .collect::<Vec<_>>()))
}

/// Setup status and how to connect agents: index location, checks, MCP tools.
async fn setup(Cur(s): Cur) -> Json<Value> {
    let root = s.data.root.clone().unwrap_or_default();
    let checks = {
        let root = root.clone();
        tokio::task::spawn_blocking(move || {
            crate::doctor::run(&crate::config::Config::load(), &root)
        })
        .await
        .unwrap_or_default()
    };
    let tools: Vec<Value> = crate::mcp::tools()
        .into_iter()
        .map(|(name, description)| json!({"name": name, "description": description}))
        .collect();
    Json(json!({
        "index": root,
        "remote": crate::cache::is_remote(&root),
        "version": env!("CARGO_PKG_VERSION"),
        "checks": checks,
        "tools": tools,
    }))
}

/// Nodes and labelled edges around the focus, for the canvas graph.
fn neighbourhood(z: &Zoom) -> Value {
    let Some(f) = &z.focus else {
        return json!({"nodes": [], "edges": []});
    };
    let mut nodes: BTreeMap<&str, &Node> = BTreeMap::from([(f.id.as_str(), f)]);
    let mut edges: Vec<Value> = Vec::new();
    let mut add = |a: &Node, b: &Node, kind: &str| {
        edges.push(json!({"src": a.id, "dst": b.id, "kind": kind}));
    };
    const CAP: usize = 40;
    let groups: [(&[Node], bool, &str); 5] = [
        (&z.callers, false, "calls"),
        (&z.callees, true, "calls"),
        (&z.importers, false, "imports"),
        (&z.members, true, "contains"),
        (&z.consumers, false, "consumes"),
    ];
    for (list, outgoing, kind) in groups {
        for n in list.iter().take(CAP) {
            nodes.insert(&n.id, n);
            if outgoing {
                add(f, n, kind);
            } else {
                add(n, f, kind);
            }
        }
    }
    for p in z.providers.iter().take(CAP) {
        nodes.insert(&p.id, p);
        add(p, f, "provides");
    }
    if let Some(c) = &z.container {
        nodes.insert(&c.id, c);
        add(c, f, "contains");
    }
    for r in &z.contracts {
        nodes.insert(&r.contract.id, &r.contract);
        add(f, &r.contract, r.role.as_str());
        for c in r.counterparts.iter().take(CAP) {
            nodes.insert(&c.id, c);
            add(c, &r.contract, "counterpart");
        }
    }
    json!({"nodes": nodes.values().collect::<Vec<_>>(), "edges": edges, "focus": f.id})
}

#[derive(Deserialize)]
struct ReviewBody {
    id: String,
    action: String,
    #[serde(default)]
    reason: String,
}

async fn review(Cur(s): Cur, Json(b): Json<ReviewBody>) -> impl IntoResponse {
    match apply_review(&s, &b).await {
        Ok(msg) => (StatusCode::OK, Json(json!({"ok": true, "message": msg}))),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"ok": false, "message": error_text(&e)})),
        ),
    }
}

async fn apply_review(s: &Session, b: &ReviewBody) -> Result<String> {
    let root = s.data.root.as_deref().context("read-only UI")?;
    let (kind, _) = crate::ledger::review_action(&b.action).context("unknown action")?;
    let ledger = crate::ledger::Ledger::open(root)?;
    let target = {
        let entries = s.entries.read().await;
        entries
            .iter()
            .find(|e| e.record.id == b.id)
            .map(|e| e.record.clone())
            .context("no such record")?
    };
    if matches!(kind, RelationKind::Retracts) && target.kind == crate::ledger::Kind::Relation {
        anyhow::bail!("relations cannot be retracted");
    }
    let rec = Record::review(
        &target,
        &b.action,
        &b.reason,
        Provenance::human("comindly-web"),
    )?;
    ledger.put(&rec).await?;
    let records = ledger.all().await?;
    let fresh = crate::ledger::derive(&records, &s.data.symbols);
    let status = fresh
        .iter()
        .find(|e| e.record.id == b.id)
        .map_or(Status::Active, |e| e.status);
    *s.entries.write().await = fresh;
    Ok(format!("{} → {:?}", target.title, status))
}

#[derive(Deserialize)]
struct RememberBody {
    kind: String,
    /// Symbols the record is about: ids, names or `Class.method`.
    on: Vec<String>,
    title: String,
    #[serde(default)]
    body: String,
    #[serde(default)]
    trigger: Option<String>,
    #[serde(default)]
    evidence: Vec<String>,
    #[serde(default)]
    fields: BTreeMap<String, String>,
}

/// A record written by the person using the UI.
async fn remember(Cur(s): Cur, Json(b): Json<RememberBody>) -> impl IntoResponse {
    let run = async {
        let root = s.data.root.as_deref().context("read-only UI")?;
        let kind = crate::ledger::Kind::parse(&b.kind).context("unknown kind")?;
        let g = &s.data.graph;
        let mut anchors = Vec::new();
        for focus in &b.on {
            let id = g
                .lookup(focus)
                .map(|i| g.node(i).id)
                .with_context(|| format!("no symbol matches `{focus}`"))?;
            let sym = s.data.symbols.iter().find(|x| x.id.render() == id);
            anchors.push(crate::ledger::Anchor::of(sym.context("symbol not loaded")?));
        }
        let mut rec = Record::new(kind, &b.title, anchors, Provenance::human("comindly-web"));
        rec.body = b.body.trim().to_string();
        rec.trigger = b.trigger.filter(|t| !t.trim().is_empty());
        rec.evidence = b
            .evidence
            .into_iter()
            .filter(|e| !e.trim().is_empty())
            .collect();
        for (k, v) in b.fields.into_iter().filter(|(_, v)| !v.trim().is_empty()) {
            rec.fields.insert(k, Value::String(v));
        }
        let ledger = crate::ledger::Ledger::open(root)?;
        ledger.put(&rec).await?;
        let records = ledger.all().await?;
        *s.entries.write().await = crate::ledger::derive(&records, &s.data.symbols);
        anyhow::Ok(rec.id)
    };
    match run.await {
        Ok(id) => (StatusCode::OK, Json(json!({"ok": true, "id": id}))),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"ok": false, "message": error_text(&e)})),
        ),
    }
}

#[derive(Deserialize)]
struct EraseBody {
    id: String,
}

/// Permanently delete a record and the reviews about it.
async fn erase(Cur(s): Cur, Json(b): Json<EraseBody>) -> impl IntoResponse {
    let run = async {
        let root = s.data.root.as_deref().context("read-only UI")?;
        let ledger = crate::ledger::Ledger::open(root)?;
        let gone = ledger.erase(|r| r.id == b.id, true).await?;
        anyhow::ensure!(!gone.is_empty(), "no such record");
        let records = ledger.all().await?;
        *s.entries.write().await = crate::ledger::derive(&records, &s.data.symbols);
        anyhow::Ok(format!("deleted {} record(s)", gone.len()))
    };
    match run.await {
        Ok(msg) => (StatusCode::OK, Json(json!({"ok": true, "message": msg}))),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"ok": false, "message": error_text(&e)})),
        ),
    }
}

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

    fn n(id: &str, repo: &str) -> Node {
        Node {
            id: id.into(),
            name: id.into(),
            kind: "function".into(),
            repo: repo.into(),
            location: String::new(),
            signature: None,
        }
    }

    #[test]
    fn neighbourhood_links_focus_both_ways() {
        let z = Zoom {
            focus: Some(n("f", "a")),
            callers: vec![n("caller", "b")],
            callees: vec![n("callee", "a")],
            ..Default::default()
        };
        let g = neighbourhood(&z);
        assert_eq!(g["nodes"].as_array().unwrap().len(), 3);
        let edges: Vec<(String, String)> = g["edges"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| {
                (
                    e["src"].as_str().unwrap().into(),
                    e["dst"].as_str().unwrap().into(),
                )
            })
            .collect();
        assert!(edges.contains(&("caller".into(), "f".into())));
        assert!(edges.contains(&("f".into(), "callee".into())));
    }
}