codetopo-server 0.5.0

codetopo's HTTP API server: the same code-graph queries over REST, with bearer-key auth and per-key metering
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
// Copyright (C) 2026 Nrupal Akolkar
// SPDX-License-Identifier: AGPL-3.0-or-later
// Part of codetopo — Owned by Nrupal Akolkar (https://nrupalakolkar.com) · Built with Muse by Meta (https://muse.ai/join) — join Muse, then redeem code 101EEK in Settings within 48 hours of joining and we both earn tokens.

//! The eight request handlers of the Phase 2 API (design §3).
//!
//! This module owns no graph logic. Every route is a transport rename of a
//! command the CLI already runs: the same `codetopo_core` query answers it, and
//! the same `codetopo_store` read backs it. That is deliberate — §3.2 makes
//! CLI/API parity an exit criterion, and shared code is the only way to make
//! parity true by construction rather than by two implementations that happen
//! to agree today.
//!
//! Three rules shape the code below:
//!
//! * **Aggregate first.** A closure response always carries `total`, the full
//!   size of the answer, before any list. An agent learns the shape of the
//!   result from one integer and decides whether it can afford the list; a
//!   response that is only a list forces it to page before it knows the size.
//! * **Blocking work leaves the async runtime.** `rusqlite` and tree walking
//!   are synchronous, and §6 requires every db-touching handler to run inside
//!   `spawn_blocking` so a slow query cannot stall the accept loop.
//! * **Errors are flat and coded.** Every failure path returns [`ApiError`],
//!   whose body is `{"error": "<code>", "message": "…"}` (see [`crate::error`]
//!   for why the body is flat rather than nested).

use std::collections::BTreeMap;
use std::path::{Path as FsPath, PathBuf};
use std::sync::Arc;

use axum::extract::{Path as UrlPath, Query, State};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use codetopo_cli::{
    default_package_name, describe_schema, index_repo, load_graph_from_db, render_path,
    require_node, CliError,
};
use codetopo_core::graph::{Graph, PathStep};
use codetopo_core::schema::{EdgeKind, NodeKind};
use codetopo_core::snapshot::Snapshot;
use codetopo_store::Store;

use crate::config::Config;
use crate::error::ApiError;

/// Default `limit` for closure queries, matching the CLI's `--limit` default.
const DEFAULT_LIMIT: usize = 20;

/// Upper bound on `limit` (§3.1). A closure over a whole repository can hold
/// hundreds of thousands of ids, and an unbounded `limit` would let one request
/// allocate the whole graph's id set — the id list is the response, so the cap
/// is the only thing between a query and an out-of-memory.
const MAX_LIMIT: usize = 1000;

/// Shared, immutable server state.
///
/// Only the resolved configuration: keys and the metering log are owned by the
/// auth layer, which is applied around the router rather than inside it, so a
/// handler physically cannot reach a secret.
#[derive(Debug, Clone)]
pub struct AppState {
    config: Arc<Config>,
}

impl AppState {
    /// Wraps a resolved [`Config`] for use as axum state.
    ///
    /// Takes the `Arc` the process already holds rather than a `Config` by
    /// value, so the state and the configuration `main` logs at startup are
    /// provably the same value and building a router in a test does not require
    /// cloning one.
    pub fn new(config: Arc<Config>) -> Self {
        AppState { config }
    }

    /// Database path for one index id (§6: `<data_dir>/<id>.db`).
    fn db_path(&self, index_id: &str) -> PathBuf {
        self.config.index_db_path(index_id)
    }
}

/// Build the unauthenticated route table.
///
/// [`crate::auth::metered`] wraps the result; this function only decides which
/// paths exist, so that auth coverage is a property of the wrapper rather than
/// something each route has to opt into.
pub fn router(state: AppState) -> Router {
    Router::new()
        .route("/v1/index", post(index))
        .route("/v1/graphs/:id/descendants", get(descendants))
        .route("/v1/graphs/:id/ancestors", get(ancestors))
        .route("/v1/graphs/:id/blast-radius", get(blast_radius))
        .route("/v1/graphs/:id/path", get(path))
        .route("/v1/graphs/:id/stats", get(stats))
        .route("/v1/graphs/:id/verify", get(verify))
        .route("/v1/graphs/:id/snapshot", get(snapshot))
        .route("/v1/graphs/:id/neighborhood", get(neighborhood))
        .route("/v1/graphs/:id/symbol", get(symbol))
        .route("/v1/graphs/:id/search", get(search))
        .route("/v1/schema", get(schema))
        .with_state(state)
}

// ---------------------------------------------------------------------------
// POST /v1/index
// ---------------------------------------------------------------------------

/// Body of `POST /v1/index`.
///
/// Every field is optional at the type level so that a *missing* field is
/// reported as `invalid_repo_path` with a message naming it, rather than as
/// axum's generic JSON rejection, which arrives before any handler code runs.
#[derive(Debug, Default, Deserialize)]
struct IndexRequest {
    repo_path: Option<String>,
    package: Option<String>,
}

// Package name recorded for the index when the request omits one:
// the shared default every surface uses
// (`codetopo_cli::default_package_name` — the repository directory's
// file stem). Before this was unified, the same fixture indexed as
// `fixture-repo::…` via CLI/MCP but `unknown::…` here, so node ids —
// and every query keyed on them — disagreed by surface.

/// `POST /v1/index` — index a repository tree into a new index id.
///
/// Walks the tree, writes `<data_dir>/<index_id>.db`, and returns the CLI's own
/// `IndexReport` fields, so API stats and CLI stats come from one computation.
async fn index(
    State(state): State<AppState>,
    Json(request): Json<IndexRequest>,
) -> Result<Json<Value>, ApiError> {
    let repo = request
        .repo_path
        .as_deref()
        .map(str::trim)
        .filter(|raw| !raw.is_empty())
        .ok_or_else(|| ApiError::invalid_repo_path("repo_path is required"))?;
    let repo = PathBuf::from(repo);
    if !repo.is_dir() {
        return Err(ApiError::invalid_repo_path(&format!(
            "not a directory: {}",
            repo.display()
        )));
    }

    let package = request
        .package
        .as_deref()
        .map(str::trim)
        .filter(|raw| !raw.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| default_package_name(&repo));

    // §6: a UUID v4 rather than a repo name, so re-indexing the same tree does
    // not clobber the previous index and no customer directory layout leaks
    // into a URL or a log line.
    let index_id = uuid::Uuid::new_v4().to_string();
    let db = state.db_path(&index_id);

    let report = tokio::task::spawn_blocking(move || index_repo(&repo, &db, &package, None, None))
        .await
        .map_err(|err| ApiError::internal(format!("index task failed: {err}")))?
        .map_err(|err| ApiError::internal(format!("cannot index repository: {err}")))?;

    Ok(Json(json!({
        "index_id": index_id,
        "files_indexed": report.files_indexed,
        "files_failed": report.files_failed,
        "nodes": report.nodes,
        "edges": report.edges,
        "diagnostics": report.diagnostics,
    })))
}

// ---------------------------------------------------------------------------
// Closure routes: descendants / ancestors / blast-radius
// ---------------------------------------------------------------------------

/// Raw query string for a closure route.
///
/// `expand` and `limit` are read as strings so a bad value is reported as
/// `invalid_param` naming the parameter, instead of being turned into a
/// deserialization error before a handler sees it.
#[derive(Debug, Default, Deserialize)]
struct ClosureQuery {
    node: Option<String>,
    expand: Option<String>,
    limit: Option<String>,
}

/// Validated closure parameters.
#[derive(Debug)]
struct ClosureParams {
    node: String,
    expand: bool,
    limit: usize,
}

/// Which direction a closure walks.
#[derive(Debug, Clone, Copy)]
enum Direction {
    /// Outgoing edges: what this node affects.
    Downstream,
    /// Incoming edges: what depends on this node.
    Upstream,
}

/// Parse `node`, `expand`, and `limit` per §3.1.
///
/// Absent and empty are treated alike, so `?limit=` means "use the default"
/// rather than "reject", which keeps a client that templates optional query
/// parameters from failing on the empty string.
fn closure_params(query: &ClosureQuery) -> Result<ClosureParams, ApiError> {
    let node = query
        .node
        .as_deref()
        .map(str::trim)
        .filter(|raw| !raw.is_empty())
        .ok_or_else(|| ApiError::missing_param("node"))?
        .to_string();

    let expand = match query.expand.as_deref().map(str::trim) {
        None | Some("") => false,
        Some("true") => true,
        Some("false") => false,
        Some(other) => {
            return Err(ApiError::invalid_param(
                "expand",
                &format!("expected 'true' or 'false', got '{other}'"),
            ))
        }
    };

    let limit = match query.limit.as_deref().map(str::trim) {
        None | Some("") => DEFAULT_LIMIT,
        Some(raw) => {
            let parsed: usize = raw.parse().map_err(|_| {
                ApiError::invalid_param("limit", &format!("expected an integer, got '{raw}'"))
            })?;
            if parsed == 0 || parsed > MAX_LIMIT {
                return Err(ApiError::invalid_param(
                    "limit",
                    &format!("must be 1..={MAX_LIMIT}, got {parsed}"),
                ));
            }
            parsed
        }
    };

    Ok(ClosureParams {
        node,
        expand,
        limit,
    })
}

/// Aggregate-first closure response.
///
/// `total` is the size of the *whole* closure; `nodes` is a possibly-truncated
/// view of it. `truncated` says which of the two the client got, so a client
/// never has to infer it by comparing two numbers.
#[derive(Debug, Serialize)]
struct ClosureResponse {
    index_id: String,
    relation: &'static str,
    node: String,
    total: usize,
    expand: bool,
    limit: usize,
    truncated: bool,
    nodes: Vec<String>,
}

/// `GET /v1/graphs/{id}/descendants?node=&expand=&limit=`.
///
/// What this node affects: the transitive closure of its outgoing call and
/// import edges.
async fn descendants(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<ClosureQuery>,
) -> Result<Json<ClosureResponse>, ApiError> {
    closure(state, index_id, query, "descendants", Direction::Downstream).await
}

/// `GET /v1/graphs/{id}/ancestors?node=&expand=&limit=`.
///
/// The reverse closure: everything that transitively reaches this node.
async fn ancestors(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<ClosureQuery>,
) -> Result<Json<ClosureResponse>, ApiError> {
    closure(state, index_id, query, "ancestors", Direction::Upstream).await
}

/// `GET /v1/graphs/{id}/blast-radius?node=&expand=&limit=`.
///
/// Breakage propagation: the dependency-side closure a failure of this node
/// would take with it.
async fn blast_radius(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<ClosureQuery>,
) -> Result<Json<ClosureResponse>, ApiError> {
    closure(
        state,
        index_id,
        query,
        "blast_radius",
        Direction::Downstream,
    )
    .await
}

/// Shared body of the three closure routes.
///
/// ## Deviation from §3.1
///
/// §3.1 says `expand=true` returns "the full id list" and, in the same table,
/// that `limit` is the "max ids returned when `expand=true`". Those two
/// statements cannot both hold, and the design gives no tie-breaker. CLI
/// parity (§3.2) is the tie-breaker used here: `print_id_list` caps the list at
/// `limit` by default and returns everything under `--expand`. So `limit` caps
/// the default list and `expand=true` lifts the cap. Nothing is lost either way,
/// because `total` is always the full size — which is the reason the aggregate
/// comes first.
async fn closure(
    state: AppState,
    index_id: String,
    query: ClosureQuery,
    relation: &'static str,
    direction: Direction,
) -> Result<Json<ClosureResponse>, ApiError> {
    let ClosureParams {
        node,
        expand,
        limit,
    } = closure_params(&query)?;
    let db = state.db_path(&index_id);
    let graph = load_graph_blocking(&db, &index_id)?;

    // The walk owns the graph and a copy of the id: `spawn_blocking` needs a
    // `'static` closure, so neither can be borrowed from this frame. The
    // response still reports the caller's `node`, so the copy is the only
    // duplicate of the id that crosses the boundary.
    let walk_node = node.clone();
    let ids = spawn_blocking(move || {
        Ok(match direction {
            Direction::Downstream if relation == "blast_radius" => graph.blast_radius(&walk_node),
            Direction::Downstream => graph.descendants(&walk_node),
            Direction::Upstream => graph.ancestors(&walk_node),
        })
    })
    .await?;

    let total = ids.len();
    let truncated = !expand && total > limit;
    let shown = if expand {
        ids
    } else {
        ids[..total.min(limit)].to_vec()
    };

    Ok(Json(ClosureResponse {
        index_id,
        relation,
        node,
        total,
        expand,
        limit,
        truncated,
        nodes: shown,
    }))
}

// ---------------------------------------------------------------------------
// GET /v1/graphs/{id}/path
// ---------------------------------------------------------------------------

/// Raw query string for `path`. Read as strings for the same reason as
/// [`ClosureQuery`]: a missing `from` must be `missing_param`, not a serde
/// error from the extractor.
#[derive(Debug, Default, Deserialize)]
struct PathQuery {
    from: Option<String>,
    to: Option<String>,
}

/// `GET /v1/graphs/{id}/path?from=&to=` — the shortest typed path between two
/// nodes.
///
/// The response is deliberately the *whole* path rather than a capped prefix:
/// a path is a sequence whose meaning depends on every step, so truncating it
/// would produce a well-formed but false answer.
#[derive(Debug, Serialize)]
struct PathResponse {
    index_id: String,
    from: String,
    to: String,
    steps: Vec<PathStep>,
    rendered: String,
}

async fn path(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<PathQuery>,
) -> Result<Json<PathResponse>, ApiError> {
    let from = required_param(query.from.as_deref(), "from")?;
    let to = required_param(query.to.as_deref(), "to")?;
    let db = state.db_path(&index_id);
    let graph = load_graph_blocking(&db, &index_id)?;

    let steps = graph
        .path(&from, &to)
        .ok_or_else(|| ApiError::no_path(&from, &to))?;
    let rendered = render_path(&steps);

    Ok(Json(PathResponse {
        index_id,
        from,
        to,
        steps,
        rendered,
    }))
}

fn required_param(raw: Option<&str>, name: &str) -> Result<String, ApiError> {
    raw.map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .ok_or_else(|| ApiError::missing_param(name))
}

// ---------------------------------------------------------------------------
// GET /v1/graphs/{id}/stats
// ---------------------------------------------------------------------------

/// Aggregate counts: totals plus per-kind breakdowns.
///
/// The breakdown omits zero kinds, matching `print_stats` (§3.2 parity), and
/// `by_kind` is a map rather than an array so a client can read a single kind
/// without walking a list to find it.
#[derive(Debug, Serialize)]
struct StatsResponse {
    index_id: String,
    nodes: KindCounts,
    edges: KindCounts,
}

#[derive(Debug, Serialize)]
struct KindCounts {
    total: usize,
    by_kind: BTreeMap<String, usize>,
}

async fn stats(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
) -> Result<Json<StatsResponse>, ApiError> {
    let db = state.db_path(&index_id);
    let graph = load_graph_blocking(&db, &index_id)?;

    let mut node_kinds = BTreeMap::new();
    for kind in ALL_NODE_KINDS {
        let count = graph.nodes().filter(|node| node.kind == kind).count();
        if count > 0 {
            node_kinds.insert(node_kind_name(kind).to_string(), count);
        }
    }

    let mut edge_kinds = BTreeMap::new();
    for kind in ALL_EDGE_KINDS {
        let count = graph.edge_count_by_kind(kind);
        if count > 0 {
            edge_kinds.insert(kind.as_str().to_string(), count);
        }
    }

    Ok(Json(StatsResponse {
        index_id,
        nodes: KindCounts {
            total: graph.node_count(),
            by_kind: node_kinds,
        },
        edges: KindCounts {
            total: graph.edge_count(),
            by_kind: edge_kinds,
        },
    }))
}

/// Every node kind, in schema declaration order.
const ALL_NODE_KINDS: [NodeKind; 10] = [
    NodeKind::Package,
    NodeKind::Module,
    NodeKind::File,
    NodeKind::Class,
    NodeKind::Interface,
    NodeKind::Function,
    NodeKind::Method,
    NodeKind::Variable,
    NodeKind::External,
    NodeKind::Doc,
];

/// Every edge kind, in schema declaration order.
const ALL_EDGE_KINDS: [EdgeKind; 9] = [
    EdgeKind::Imports,
    EdgeKind::Calls,
    EdgeKind::Inherits,
    EdgeKind::Implements,
    EdgeKind::Defines,
    EdgeKind::References,
    EdgeKind::Contains,
    EdgeKind::Reads,
    EdgeKind::Writes,
];

/// Snake_case wire name of a node kind.
///
/// `NodeKind` has no `as_str` of its own (unlike `EdgeKind`), so the names
/// live here; they are kept in step with the schema's `rename_all =
/// "snake_case"` serialization, which is what clients see.
fn node_kind_name(kind: NodeKind) -> &'static str {
    match kind {
        NodeKind::Package => "package",
        NodeKind::Module => "module",
        NodeKind::File => "file",
        NodeKind::Class => "class",
        NodeKind::Interface => "interface",
        NodeKind::Function => "function",
        NodeKind::Method => "method",
        NodeKind::Variable => "variable",
        NodeKind::External => "external",
        NodeKind::Doc => "doc",
    }
}

// ---------------------------------------------------------------------------
// GET /v1/graphs/{id}/verify
// ---------------------------------------------------------------------------

/// Audit-chain verification: entry count, chain validity, and head hash.
///
/// The same three facts `verify_db` prints. This is the route an agent calls
/// before trusting a snapshot it was handed.
#[derive(Debug, Serialize)]
struct VerifyResponse {
    index_id: String,
    entries: usize,
    chain_valid: bool,
    head: String,
}

async fn verify(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
) -> Result<Json<VerifyResponse>, ApiError> {
    let db = state.db_path(&index_id);
    require_index(&db, &index_id)?;

    let (entries, chain_valid, head) = spawn_blocking(move || {
        let store = Store::open(&db).map_err(|err| ApiError::internal(err.to_string()))?;
        let audit = store
            .load_audit()
            .map_err(|err| ApiError::internal(err.to_string()))?;
        Ok::<_, ApiError>((audit.len(), audit.verify(), audit.head().to_string()))
    })
    .await?;

    Ok(Json(VerifyResponse {
        index_id,
        entries,
        chain_valid,
        head,
    }))
}

// ---------------------------------------------------------------------------
// GET /v1/graphs/{id}/snapshot
// ---------------------------------------------------------------------------

/// `GET /v1/graphs/{id}/snapshot` — portable frozen export of the whole graph.
///
/// Serialized as the `Snapshot` struct itself rather than wrapped, so the
/// response is byte-compatible with what `codetopo restore` accepts: a client
/// can pipe this body straight to a file and restore it with no translation
/// step. The snapshot binds `audit_head`, so a consumer can tell which audit
/// chain it came from.
async fn snapshot(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
) -> Result<Json<Snapshot>, ApiError> {
    let db = state.db_path(&index_id);
    require_index(&db, &index_id)?;

    spawn_blocking(move || {
        let store = Store::open(&db).map_err(|err| ApiError::internal(err.to_string()))?;
        let graph = store
            .load_graph()
            .map_err(|err| ApiError::internal(err.to_string()))?;
        let audit = store
            .load_audit()
            .map_err(|err| ApiError::internal(err.to_string()))?;
        Ok::<_, ApiError>(Snapshot::from_graph(&graph, &audit.snapshot_entries()))
    })
    .await
    .map(Json)
}

// ---------------------------------------------------------------------------
// shared helpers
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// GET /v1/graphs/{id}/neighborhood, /symbol, /search; GET /v1/schema
// ---------------------------------------------------------------------------

/// Query for `neighborhood`: the shared closure params plus `depth`.
#[derive(Debug, Default, Deserialize)]
struct NeighborhoodQuery {
    node: Option<String>,
    depth: Option<String>,
}

/// `GET /v1/graphs/{id}/neighborhood?node=&depth=` — the subgraph
/// within `depth` hops of a node, both directions (CODE_SCHEMA §6's
/// neighborhood query; the CLI and MCP serve the same computation).
async fn neighborhood(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<NeighborhoodQuery>,
) -> Result<Json<Value>, ApiError> {
    let node = query
        .node
        .as_deref()
        .map(str::trim)
        .filter(|raw| !raw.is_empty())
        .ok_or_else(|| ApiError::missing_param("node"))?
        .to_string();
    let depth: u32 = match query.depth.as_deref().map(str::trim) {
        None | Some("") => 1,
        Some(raw) => raw.parse().map_err(|_| {
            ApiError::invalid_param("depth", &format!("expected a non-negative integer, got '{raw}'"))
        })?,
    };
    let db = state.db_path(&index_id);
    let graph = load_graph_blocking(&db, &index_id)?;
    require_node(&graph, &node).map_err(|e| map_cli_error(&index_id, e))?;
    let sub = graph.neighborhood(&node, depth);
    Ok(Json(json!({
        "index_id": index_id,
        "node": node,
        "depth": depth,
        "nodes": sub.nodes,
        "edges": sub.edges,
    })))
}

/// `GET /v1/graphs/{id}/symbol?node=` — one node in full.
async fn symbol(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<ClosureQuery>,
) -> Result<Json<Value>, ApiError> {
    let node_id = query
        .node
        .as_deref()
        .map(str::trim)
        .filter(|raw| !raw.is_empty())
        .ok_or_else(|| ApiError::missing_param("node"))?
        .to_string();
    let db = state.db_path(&index_id);
    let graph = load_graph_blocking(&db, &index_id)?;
    let node = require_node(&graph, &node_id).map_err(|e| map_cli_error(&index_id, e))?;
    Ok(Json(json!({"index_id": index_id, "node": node})))
}

/// Query for `search`.
#[derive(Debug, Default, Deserialize)]
struct SearchQuery {
    q: Option<String>,
    limit: Option<String>,
}

/// `GET /v1/graphs/{id}/search?q=&limit=` — name discovery: the step
/// the exact-id queries always assumed a caller had already done.
async fn search(
    State(state): State<AppState>,
    UrlPath(index_id): UrlPath<String>,
    Query(query): Query<SearchQuery>,
) -> Result<Json<Value>, ApiError> {
    let q = query
        .q
        .as_deref()
        .map(str::trim)
        .filter(|raw| !raw.is_empty())
        .ok_or_else(|| ApiError::missing_param("q"))?
        .to_string();
    let limit: usize = match query.limit.as_deref().map(str::trim) {
        None | Some("") => 20,
        Some(raw) => raw.parse().map_err(|_| {
            ApiError::invalid_param("limit", &format!("expected a positive integer, got '{raw}'"))
        })?,
    };
    let db = state.db_path(&index_id);
    let graph = load_graph_blocking(&db, &index_id)?;
    let hits = graph.search_symbols(&q, limit);
    Ok(Json(json!({
        "index_id": index_id,
        "query": q,
        "total": hits.len(),
        "results": hits,
    })))
}

/// `GET /v1/schema` — the schema description, identical to the CLI's
/// `schema` command and the MCP `codetopo_describe_schema` tool
/// (one generator in the CLI library serves all three).
async fn schema() -> Json<Value> {
    Json(describe_schema())
}

/// Open an index database, mapping "no such file" to `unknown_index`.
fn require_index(db: &FsPath, index_id: &str) -> Result<(), ApiError> {
    if !db.is_file() {
        return Err(ApiError::unknown_index(index_id));
    }
    Ok(())
}

/// Load a graph off the runtime, mapping store and id failures to API errors.
fn load_graph_blocking(db: &FsPath, index_id: &str) -> Result<Graph, ApiError> {
    require_index(db, index_id)?;
    load_graph_from_db(db).map_err(|err| map_cli_error(index_id, err))
}

/// Translate a CLI-layer error into the API's error vocabulary.
///
/// Only `UnknownId` is a client mistake: the queried node is not in the graph,
/// which is the same `404 unknown_node` the CLI signals with exit code 2.
/// Everything else is the server's problem — a store or io failure behind a
/// request that was otherwise well-formed.
fn map_cli_error(index_id: &str, err: CliError) -> ApiError {
    match err {
        CliError::UnknownId(id) => ApiError::unknown_node(&id),
        other => ApiError::internal(format!("index {index_id}: {other}")),
    }
}

/// Run synchronous work on the blocking pool and propagate a join failure.
///
/// A `JoinError` means the worker panicked or was cancelled; there is no
/// request left to answer, so it is reported as `internal` rather than
/// silently swallowed.
async fn spawn_blocking<T, F>(work: F) -> Result<T, ApiError>
where
    F: FnOnce() -> Result<T, ApiError> + Send + 'static,
    T: Send + 'static,
{
    tokio::task::spawn_blocking(work)
        .await
        .map_err(|err| ApiError::internal(format!("worker task failed: {err}")))?
}