hank 0.4.0

In-memory, multi-tenant code-analysis engine — the structural signal for the Bobbin × Quipu stack
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
//! FR-3 enforcement: every `hank_*` MCP response carries its provenance tier
//! (aegis-8yrn). Child module of `server`, so it can drive the private tool
//! handlers directly; size-exempt (`_test.rs`).
//!
//! The bug this pins: `hank_impact`, `hank_callers`, `hank_callees` and
//! `hank_dataflow` served an unlabelled tree-sitter approximation — no `tier`
//! anywhere — which FR-3 exists to forbid, and which is worse on `hank_impact`
//! precisely because it is the trust-boundary/capability-scoping surface. This
//! walk asserts the served WIRE JSON, so a future response type that omits the
//! tag fails here rather than shipping silent.

use super::HankMcpServer;
use crate::mcp::tools::{
    AnalyzeRequest, CommunitiesRequest, DataflowRequest, ImpactRequest, NeighborsRequest,
    ReferencesRequest, SymbolsRequest, VerifyRequest,
};
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::CallToolResult;

const KNOWN_TIERS: &[&str] = &["treesitter", "lsp", "cpg"];

/// A two-function project: `a` calls `b`, so `b` has a caller and the graph is
/// non-empty. Fresh temp dir per test.
fn fixture() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("x.rs"), "fn a() { b(); }\nfn b() {}\n").unwrap();
    dir
}

fn server(dir: &tempfile::TempDir) -> HankMcpServer {
    HankMcpServer::new(dir.path().to_path_buf(), None, None)
}

/// The served JSON payload, parsed out of the MCP `CallToolResult` wire form
/// (`{ "content": [ { "type": "text", "text": "<json>" } ] }`). Asserting the
/// actual wire bytes is the point — a `tier` field that exists on the struct but
/// is dropped in serialization would still be caught.
fn served(result: Result<CallToolResult, rmcp::ErrorData>) -> serde_json::Value {
    let result = result.expect("handler returned Ok");
    let wire = serde_json::to_value(&result).expect("CallToolResult serializes");
    let text = wire
        .pointer("/content/0/text")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_else(|| panic!("no text content in result: {wire}"));
    serde_json::from_str(text).expect("served payload is JSON")
}

/// Does any object in the tree carry a `tier` key? Covers both per-item tags
/// (symbols/references) and the top-level tag (graph responses).
fn carries_tier(v: &serde_json::Value) -> bool {
    match v {
        serde_json::Value::Object(m) => m.contains_key("tier") || m.values().any(carries_tier),
        serde_json::Value::Array(a) => a.iter().any(carries_tier),
        _ => false,
    }
}

/// A top-level `tier` that is one of the known tiers. Used for the graph
/// responses, where the top-level tag is what makes an EMPTY / not-found answer
/// still declare its provenance.
fn assert_top_level_tier(payload: &serde_json::Value, tool: &str) {
    let tier = payload
        .get("tier")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_else(|| panic!("{tool}: no top-level `tier` in {payload}"));
    assert!(
        KNOWN_TIERS.contains(&tier),
        "{tool}: tier {tier:?} is not one of {KNOWN_TIERS:?}"
    );
}

#[tokio::test]
async fn impact_carries_a_top_level_tier() {
    let dir = fixture();
    let payload = served(
        server(&dir)
            .hank_impact(Parameters(ImpactRequest {
                symbol: "b".into(),
                path: None,
                hops: None,
                cochange: None,
            }))
            .await,
    );
    // The bug was that this — the trust-boundary surface — served no tier at all.
    assert_top_level_tier(&payload, "hank_impact");
    // And the per-item reach facts carry it too.
    let first = &payload["reachable"][0];
    assert_eq!(
        first["tier"], "treesitter",
        "reach item missing tier: {first}"
    );
}

#[tokio::test]
async fn impact_on_a_missing_symbol_still_declares_its_tier() {
    // The empty-case hole: a not-found answer has no items to tag, so without the
    // top-level tag it would arrive unlabelled and read as authoritative.
    let dir = fixture();
    let payload = served(
        server(&dir)
            .hank_impact(Parameters(ImpactRequest {
                symbol: "does_not_exist".into(),
                path: None,
                hops: None,
                cochange: None,
            }))
            .await,
    );
    assert_eq!(payload["found"], false);
    assert_top_level_tier(&payload, "hank_impact(not-found)");
}

#[tokio::test]
async fn callers_and_callees_carry_a_top_level_tier() {
    let dir = fixture();
    let callers = served(
        server(&dir)
            .hank_callers(Parameters(NeighborsRequest {
                symbol: "b".into(),
                path: None,
            }))
            .await,
    );
    assert_top_level_tier(&callers, "hank_callers");

    let callees = served(
        server(&dir)
            .hank_callees(Parameters(NeighborsRequest {
                symbol: "a".into(),
                path: None,
            }))
            .await,
    );
    assert_top_level_tier(&callees, "hank_callees");
}

// --- Stage 3c wiring (aegis-1qze): resident daemon vs. transient fallback ----
//
// Multi-thread runtime on purpose: the tool handlers call the SYNC daemon
// client in-line, so the daemon must be able to accept on another worker while
// the handler's thread blocks on the socket.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_unscoped_query_uses_the_daemon_and_a_path_scoped_one_never_does() {
    let dir = fixture(); // x.rs: a calls b
    let engine = crate::daemon::ResidentEngine::build(dir.path(), None).unwrap();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    tokio::spawn(async move {
        let _ = axum::serve(listener, crate::daemon::http::router(engine)).await;
    });
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Config override EXPECTING that daemon (override path, so no user-config
    // layering can leak in).
    let config = dir.path().join("daemon-config.toml");
    std::fs::write(
        &config,
        format!(
            "[hank.serve]\nuse_daemon = true\nbind_address = \"127.0.0.1\"\n\
             mcp_http_port = {port}\n"
        ),
    )
    .unwrap();
    let server = HankMcpServer::new(dir.path().to_path_buf(), None, Some(config));

    // Grow the tree AFTER the resident graph was built: a transient build sees
    // `late`, the daemon cannot. Which graph answered is therefore observable.
    std::fs::write(dir.path().join("late.rs"), "fn late() { b(); }\n").unwrap();

    // Unscoped -> the RESIDENT graph answers (no `late`).
    let resident = served(
        server
            .hank_callers(Parameters(NeighborsRequest {
                symbol: "b".into(),
                path: None,
            }))
            .await,
    );
    let names: Vec<&str> = resident["neighbors"]
        .as_array()
        .unwrap()
        .iter()
        .map(|n| n["name"].as_str().unwrap())
        .collect();
    assert!(names.contains(&"a"), "got {names:?}");
    assert!(
        !names.contains(&"late"),
        "`late` postdates the resident graph; its presence means the transient \
         path answered an unscoped query despite a usable daemon: {names:?}"
    );
    assert_top_level_tier(&resident, "hank_callers(resident)");

    // Path-scoped -> NEVER the daemon (whole-root graph ≠ subtree graph): the
    // transient build answers and sees `late`.
    let scoped = served(
        server
            .hank_callers(Parameters(NeighborsRequest {
                symbol: "b".into(),
                path: Some(".".into()),
            }))
            .await,
    );
    let names: Vec<&str> = scoped["neighbors"]
        .as_array()
        .unwrap()
        .iter()
        .map(|n| n["name"].as_str().unwrap())
        .collect();
    assert!(
        names.contains(&"late"),
        "a path-scoped query must be answered transiently, not by the daemon: {names:?}"
    );
}

#[tokio::test]
async fn dataflow_carries_a_top_level_tier() {
    let dir = fixture();
    let payload = served(
        server(&dir)
            .hank_dataflow(Parameters(DataflowRequest {
                function: "a".into(),
                path: None,
                var: None,
                forward: None,
                hops: None,
            }))
            .await,
    );
    assert_top_level_tier(&payload, "hank_dataflow");
}

#[tokio::test]
async fn every_fact_serving_response_carries_a_tier() {
    // The walk: each fact-serving tool's WIRE response must carry a tier somewhere
    // (top-level for graph/summary responses, per-item for symbol lists). If a new
    // response type omits it, its line here fails rather than shipping unlabelled.
    let dir = fixture();
    let s = server(&dir);

    let cases: Vec<(&str, serde_json::Value)> = vec![
        (
            "hank_symbols",
            served(
                s.hank_symbols(Parameters(SymbolsRequest {
                    file: "x.rs".into(),
                }))
                .await,
            ),
        ),
        (
            "hank_references",
            served(
                s.hank_references(Parameters(ReferencesRequest {
                    symbol: Some("a".into()),
                    path: None,
                    at_file: None,
                    at_line: None,
                }))
                .await,
            ),
        ),
        (
            "hank_analyze",
            served(
                s.hank_analyze(Parameters(AnalyzeRequest { path: None }))
                    .await,
            ),
        ),
        (
            "hank_communities",
            served(
                s.hank_communities(Parameters(CommunitiesRequest { path: None }))
                    .await,
            ),
        ),
        (
            "hank_verify",
            served(
                s.hank_verify(Parameters(VerifyRequest {
                    file: "x.rs".into(),
                    buffer: "fn a() { b(); }\nfn b() {}\n".into(),
                }))
                .await,
            ),
        ),
        (
            "hank_callers",
            served(
                s.hank_callers(Parameters(NeighborsRequest {
                    symbol: "b".into(),
                    path: None,
                }))
                .await,
            ),
        ),
        (
            "hank_impact",
            served(
                s.hank_impact(Parameters(ImpactRequest {
                    symbol: "b".into(),
                    path: None,
                    hops: None,
                    cochange: None,
                }))
                .await,
            ),
        ),
        (
            "hank_dataflow",
            served(
                s.hank_dataflow(Parameters(DataflowRequest {
                    function: "a".into(),
                    path: None,
                    var: None,
                    forward: None,
                    hops: None,
                }))
                .await,
            ),
        ),
    ];

    for (tool, payload) in &cases {
        assert!(
            carries_tier(payload),
            "{tool}: served response carries NO tier anywhere: {payload}"
        );
    }
}

#[tokio::test]
async fn status_advertises_only_implemented_tiers() {
    // aegis-qe5z: hank_status must claim a tier only when it is real. The extractor
    // assigns TreeSitter alone, so status advertises exactly ["treesitter"] — never
    // lsp/cpg, which have no implementation and are no longer even Cargo features.
    let dir = fixture();
    let payload = served(server(&dir).hank_status().await);
    assert_eq!(
        payload["tiers"],
        serde_json::json!(["treesitter"]),
        "status advertised a tier with no implementation: {payload}"
    );
}

#[tokio::test]
async fn references_declares_its_tier_at_the_top_level() {
    // The empty-answer hole, on the references surface. `ReferencesResponse`
    // tagged each `RefItem` and nothing else, so the one reply with no items —
    // "this symbol has no definitions" — was served with no tier at all. That is
    // the answer most likely to be acted on ("it does not exist"), and it was the
    // only one FR-3 did not cover.
    let dir = fixture();
    let payload = served(
        server(&dir)
            .hank_references(Parameters(ReferencesRequest {
                symbol: Some("definitely_not_here".into()),
                path: None,
                at_file: None,
                at_line: None,
            }))
            .await,
    );
    assert_eq!(payload["count"], 0, "fixture has no such symbol: {payload}");
    assert_top_level_tier(&payload, "hank_references");
}

#[tokio::test]
#[cfg(feature = "langs-extra")] // needs the python grammar compiled in
async fn references_resolves_a_non_rust_definition_on_the_transient_path() {
    // hank #76 on the MCP surface. The transient fallback walked `rust_files()`
    // and parsed every hit as "rust" — so this path answered "no definitions" for
    // every Python/Go/TypeScript symbol in the tree. A `path`-scoped request ALWAYS
    // lands here (it never consults the daemon, by design), so this was not merely
    // the no-daemon case: it was every scoped reference query.
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("quipu.py"),
        "def derive_agents(cfg):\n    return cfg\n",
    )
    .unwrap();
    let s = HankMcpServer::new(dir.path().to_path_buf(), None, None);

    let payload = served(
        s.hank_references(Parameters(ReferencesRequest {
            symbol: Some("derive_agents".into()),
            // Scoped on purpose: pins the TRANSIENT path, not the resident one.
            at_file: None,
            at_line: None,
            path: Some(".".into()),
        }))
        .await,
    );

    assert_eq!(payload["count"], 1, "python definition missed: {payload}");
    assert_eq!(payload["definitions"][0]["file"], "quipu.py");
    assert_eq!(payload["definitions"][0]["start_line"], 1);
    // The searched-set size is knowable on this path, so it is served — the
    // discriminator between "absent name" and "nothing was parseable".
    assert_eq!(payload["searched_symbols"], 1, "{payload}");
}

#[tokio::test]
async fn references_by_position_answers_with_the_one_symbol_pointed_at() {
    // hank #8 / FR-4 on the agent-facing surface. `x.rs` in `fixture()` defines
    // `a` and `b`; a real tree has twelve `build`s, and an agent reading code
    // knows WHERE it is, not which one. Position must answer with that symbol —
    // resolving it to a name and looking the name up would hand back the whole
    // name class, which is the ambiguity the position was given to remove.
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("x.rs"),
        "struct Alpha;\nimpl Alpha {\n    fn build() {}\n}\nstruct Beta;\nimpl Beta {\n    fn build() {}\n}\n",
    )
    .unwrap();
    let s = HankMcpServer::new(dir.path().to_path_buf(), None, None);

    // By name: ambiguous, both sites.
    let by_name = served(
        s.hank_references(Parameters(ReferencesRequest {
            symbol: Some("build".into()),
            path: Some(".".into()),
            at_file: None,
            at_line: None,
        }))
        .await,
    );
    assert_eq!(by_name["count"], 2, "name is ambiguous here: {by_name}");

    // By position: exactly the one enclosing that line.
    let by_pos = served(
        s.hank_references(Parameters(ReferencesRequest {
            symbol: None,
            path: Some(".".into()),
            at_file: Some("x.rs".into()),
            at_line: Some(7),
        }))
        .await,
    );
    assert_eq!(by_pos["count"], 1, "position must disambiguate: {by_pos}");
    assert_eq!(by_pos["definitions"][0]["start_line"], 7, "{by_pos}");
    assert_top_level_tier(&by_pos, "hank_references");
}

#[tokio::test]
async fn references_refuses_half_a_position_rather_than_downgrading_to_a_name() {
    // `at_file` without `at_line` is not a position. Falling back to a name
    // lookup would answer "which one is here?" with "all of them" — a silent
    // downgrade to the very over-connection the parameter exists to cut.
    let dir = fixture();
    let err = server(&dir)
        .hank_references(Parameters(ReferencesRequest {
            symbol: Some("a".into()),
            path: Some(".".into()),
            at_file: Some("x.rs".into()),
            at_line: None,
        }))
        .await;
    assert!(err.is_err(), "half a position must be refused, not guessed");
}