agentstatedeveloper-mcp 1.4.9

MCP server for AgentStateDeveloper — exposes asd tools over stdio
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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
//! In-process integration tests for the distilled-metrics endpoints:
//! `/api/v1/history/milestones`, `/api/v1/history/rollup`,
//! `/api/v1/commits`, `/api/v1/feedback`, `/api/v1/index-health` and
//! `/api/v1/scorecard`.
//!
//! Same shape as `http_lens_api.rs`: a hand-built in-memory engine and
//! `tower::ServiceExt::oneshot` dispatch, so the tests always run without a
//! pre-indexed fixture DB or a bound socket.
//!
//! The fixture writes commits under three agents and two intent categories,
//! including `Checkpoint` commits (which the ASG extractor lifts onto the
//! milestone spine), so the rollup/milestone/commit endpoints all have real
//! distilled rows to filter.

use std::path::PathBuf;
use std::sync::Arc;

use agentstatedeveloper_core::{
    AsgEffectStore, AsgFeedbackStore, AsgIndexStore, AsgLedgerStore, Author, AuthorKind, Effect,
    EffectCategory, EffectDecl, Engine, FeedbackEntry, FeedbackStore, FeedbackVerdict, IndexStore,
    LedgerEntry, LedgerKind, LedgerStore, Position, Symbol, SymbolKind,
};
use agentstatedeveloper_mcp::build_router;
use agentstategraph::CommitOptions;
use agentstategraph_core::{IntentCategory, TAG_GIT_REVISION, TAG_PIN_STATE};
use axum::body::Body;
use axum::http::{Request, StatusCode};
use chrono::{Duration, TimeZone, Utc};
use http_body_util::BodyExt;
use tokio::sync::Mutex;
use tower::ServiceExt;

fn sym_id(qname: &str) -> String {
    format!("id::{}", qname)
}

fn make_symbol(qname: &str, file: &str, line: u32) -> Symbol {
    Symbol {
        symbol_id: sym_id(qname),
        symbol_fp: format!("fp::{}", qname),
        qname: qname.to_string(),
        language: "python".to_string(),
        kind: SymbolKind::Function,
        file: file.to_string(),
        start: Position { line, col: 0 },
        end: Position {
            line: line + 10,
            col: 0,
        },
        signature: Some(format!("def {}()", qname.rsplit('.').next().unwrap())),
        doc: Some(format!("Doc for {}.", qname)),
    }
}

/// Write one commit with an explicit agent + intent so the distilled rollup
/// has something to group by.
fn commit(engine: &Engine, agent: &str, intent: IntentCategory, description: &str, n: u32) {
    commit_tagged(engine, agent, intent, description, n, Vec::new())
}

fn commit_tagged(
    engine: &Engine,
    agent: &str,
    intent: IntentCategory,
    description: &str,
    n: u32,
    tags: Vec<String>,
) {
    let opts = CommitOptions::new(agent, intent, description).with_tags(tags);
    engine
        .repo
        .set_json(
            &engine.ref_name,
            // Non-numeric leaf: a bare integer segment is read as a list
            // index, which collides with the map written by the first commit.
            &format!("/test/marker/m{}", n),
            &serde_json::json!({ "n": n }),
            opts,
        )
        .expect("commit marker");
}

fn put_feedback(
    engine: &Engine,
    qname: &str,
    entry_id: &str,
    query: &str,
    verdict: FeedbackVerdict,
    author: &str,
    note: Option<&str>,
    expires_in_days: Option<i64>,
) {
    let store = AsgFeedbackStore::from_engine(engine);
    let created = Utc.with_ymd_and_hms(2026, 3, 1, 12, 0, 0).unwrap();
    let entry = FeedbackEntry {
        entry_id: entry_id.to_string(),
        symbol_id: sym_id(qname),
        symbol_qname: qname.to_string(),
        query: query.to_string(),
        verdict,
        author: author.to_string(),
        created_at: created,
        note: note.map(str::to_string),
        file_scope: None,
        // Relative to *now*, not to `created_at`, so "expired" is
        // deterministic regardless of when the suite runs.
        expires_at: expires_in_days.map(|d| Utc::now() + Duration::days(d)),
        withdrawn_at: None,
        withdrawn_by: None,
        withdrawn_reason: None,
    };
    store
        .record(&engine.ref_name, &entry, "metrics-test")
        .expect("record feedback");
}

/// Build the fixture engine. Split out from [`router`] so a test can also
/// score it directly and compare against what the HTTP handler returns.
fn fixture_engine() -> Engine {
    let engine = Engine::open_in_memory().expect("open in-memory engine");
    let index_store = AsgIndexStore::new(&engine.repo);

    for (qname, file, line) in [
        ("app.main", "app.py", 1),
        ("pay.charge_card", "pay.py", 10),
        ("net.post", "net.py", 20),
        ("util.log", "util.py", 30),
    ] {
        index_store
            .put_symbol(
                &engine.ref_name,
                &make_symbol(qname, file, line),
                "metrics-test",
            )
            .expect("put symbol");
    }

    // One symbol carries a verified-effect decl and an ownership entry so the
    // scorecard's truth dimension is non-zero rather than trivially 0.
    {
        use agentstatedeveloper_core::EffectStore;
        let store = AsgEffectStore::new(&engine.repo);
        let decl = EffectDecl {
            symbol_id: sym_id("net.post"),
            declared: vec![Effect::new(EffectCategory::IoNetOut)],
            transitive: Vec::new(),
            verification: None,
            confidence: None,
            runtime: None,
            matched_policy: None,
        };
        store
            .put_effects(&engine.ref_name, &sym_id("net.post"), &decl, "metrics-test")
            .expect("put effects");
    }
    {
        let store = AsgLedgerStore::new(&engine.repo);
        let entry = LedgerEntry {
            entry_id: "e-own-1".to_string(),
            symbol_id: sym_id("pay.charge_card"),
            kind: LedgerKind::Ownership,
            summary: "payments team owns this".to_string(),
            body: None,
            author: Author {
                kind: AuthorKind::Agent,
                id: "metrics-test".to_string(),
            },
            confidence: Some(0.9),
            evidence: Vec::new(),
            supersedes: Vec::new(),
            created_at: Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(),
            tags: vec!["ctx:plan-t".to_string()],
            matched_policy: None,
            role: None,
            command: None,
        };
        store
            .append_entry(&engine.ref_name, &entry, "metrics-test")
            .expect("append ledger entry");
    }

    // Distilled-history fodder: two agents, two intent categories. The two
    // Checkpoint commits become milestones; the Refine ones stay rollup-only.
    commit(
        &engine,
        "alice",
        IntentCategory::Refine,
        "widen the parser",
        1,
    );
    commit(
        &engine,
        "alice",
        IntentCategory::Refine,
        "tighten the lexer",
        2,
    );
    commit(
        &engine,
        "bob",
        IntentCategory::Refine,
        "rename the adapter",
        3,
    );
    // A deliberate, human-named milestone: it opts into pinning its snapshot.
    commit_tagged(
        &engine,
        "alice",
        IntentCategory::Checkpoint,
        "checkpoint: parser stable",
        4,
        vec![TAG_PIN_STATE.to_string()],
    );
    // A routine checkpoint — on the spine, but it pins no state and instead
    // records the revision it was derived from.
    commit_tagged(
        &engine,
        "bob",
        IntentCategory::Checkpoint,
        "checkpoint: adapter stable",
        5,
        vec![format!("{TAG_GIT_REVISION}feed1234abcd5678")],
    );

    put_feedback(
        &engine,
        "pay.charge_card",
        "fb-1",
        "charge a card",
        FeedbackVerdict::Useful,
        "alice",
        Some("exactly the entry point"),
        None,
    );
    put_feedback(
        &engine,
        "util.log",
        "fb-2",
        "charge a card",
        FeedbackVerdict::Noisy,
        "bob",
        None,
        None,
    );
    put_feedback(
        &engine,
        "net.post",
        "fb-3",
        "outbound http",
        FeedbackVerdict::Useful,
        "alice",
        None,
        // Already lapsed — must still be listed, flagged `expired`.
        Some(-1),
    );

    engine
}

/// Build the fixture engine + router.
async fn router() -> axum::Router {
    build_router(
        Arc::new(Mutex::new(fixture_engine())),
        PathBuf::from(":memory:"),
        None,
        None,
        true,
    )
}

async fn get_body(app: axum::Router, uri: &str) -> (StatusCode, serde_json::Value) {
    let resp = app
        .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
        .await
        .unwrap();
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_else(
        |_| serde_json::json!({"_raw": String::from_utf8_lossy(&bytes).to_string()}),
    );
    (status, value)
}

/// Pull a facet axis into `(value, count)` pairs for easier assertions.
fn facet_pairs(body: &serde_json::Value, axis: &str) -> Vec<(String, u64)> {
    body["facets"][axis]
        .as_array()
        .unwrap_or_else(|| panic!("facet axis {} missing; body={}", axis, body))
        .iter()
        .map(|f| {
            (
                f["value"].as_str().unwrap().to_string(),
                f["count"].as_u64().unwrap(),
            )
        })
        .collect()
}

// ---------------------------------------------------------------------------
// /api/v1/history/milestones
// ---------------------------------------------------------------------------

/// The fixture's own two `Checkpoint` commits, plus the engine's `system`
/// "Initialize empty state" checkpoint. Asserted as a named constant because
/// several tests pivot on it and the engine's bookkeeping commits are not
/// this suite's to pin down.
const FIXTURE_MILESTONES: u64 = 3;

#[tokio::test]
async fn milestones_lists_checkpoint_commits_with_facets() {
    let (status, body) = get_body(router().await, "/api/v1/history/milestones").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);

    // Only Checkpoint-intent commits reach the spine — Refine ones do not.
    assert_eq!(body["total"], FIXTURE_MILESTONES, "body={}", body);
    assert_eq!(
        facet_pairs(&body, "kinds"),
        vec![("checkpoint".into(), FIXTURE_MILESTONES)],
        "body={}",
        body
    );
    let agents = facet_pairs(&body, "agents");
    for who in ["alice", "bob"] {
        assert_eq!(
            agents.iter().find(|(v, _)| v == who).map(|(_, c)| *c),
            Some(1),
            "{} should own exactly one milestone; body={}",
            who,
            body
        );
    }
}

#[tokio::test]
async fn milestones_report_whether_each_pins_a_state_root() {
    let (_, body) = get_body(router().await, "/api/v1/history/milestones").await;
    // Pinning is opt-in, so the two states must be told apart rather than
    // assumed: a tagged checkpoint names a snapshot, a routine one does not and
    // carries the revision to rebuild from instead. `unpinned` must agree with
    // the rows — it is what tells an operator how much a sweep can reclaim.
    for m in body["items"].as_array().unwrap() {
        assert_eq!(
            m["pins_state"],
            m["state_root"].is_string(),
            "pins_state must track state_root; body={}",
            body
        );
    }
    let pinned: Vec<_> = body["items"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|m| m["pins_state"] == true)
        .collect();
    let unpinned: Vec<_> = body["items"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|m| m["pins_state"] == false)
        .collect();

    // Only the tagged one pins.
    assert_eq!(pinned.len(), 1, "body={}", body);
    assert_eq!(pinned[0]["description"], "checkpoint: parser stable");
    assert!(pinned[0]["state_root"].is_string(), "body={}", body);

    // Two rows pin nothing: bob's routine checkpoint and the engine's own
    // "Initialize empty state", which is a checkpoint like any other and no
    // longer retains a snapshot just for existing.
    assert_eq!(unpinned.len(), 2, "body={}", body);
    let routine = unpinned
        .iter()
        .find(|m| m["description"] == "checkpoint: adapter stable")
        .expect("bob's routine checkpoint is on the spine");
    assert!(routine["state_root"].is_null(), "body={}", body);
    assert_eq!(
        routine["git_sha"], "feed1234abcd5678",
        "an unpinned milestone must still say what to rebuild from; body={}",
        body
    );

    assert_eq!(body["unpinned"], 2, "body={}", body);
}

#[tokio::test]
async fn milestones_free_text_search_narrows_results() {
    let (status, body) = get_body(router().await, "/api/v1/history/milestones?q=adapter").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert_eq!(body["total"], 1, "body={}", body);
    assert_eq!(body["items"][0]["agent"], "bob", "body={}", body);
    assert!(
        body["items"][0]["description"]
            .as_str()
            .unwrap()
            .contains("adapter"),
        "body={}",
        body
    );
}

#[tokio::test]
async fn milestones_agent_filter_does_not_collapse_its_own_facet() {
    // Facets are computed before the categorical filters precisely so the
    // sibling chips keep a usable count while one is selected. If this
    // regresses, selecting `alice` would report `bob: 0` and the UI's filter
    // chips become dead ends.
    let (status, body) = get_body(router().await, "/api/v1/history/milestones?agent=alice").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert_eq!(body["total"], 1, "body={}", body);

    let agents = facet_pairs(&body, "agents");
    assert_eq!(
        agents.iter().find(|(v, _)| v == "bob").map(|(_, c)| *c),
        Some(1),
        "bob's chip must keep its count while alice is selected; body={}",
        body
    );
    assert_eq!(
        agents.len() as u64,
        FIXTURE_MILESTONES,
        "every agent should still be offered; body={}",
        body
    );
}

#[tokio::test]
async fn milestones_agent_filter_is_case_insensitive() {
    let (_, body) = get_body(router().await, "/api/v1/history/milestones?agent=ALICE").await;
    assert_eq!(body["total"], 1, "body={}", body);
}

#[tokio::test]
async fn milestones_paginate_without_changing_total() {
    let (_, page1) = get_body(
        router().await,
        "/api/v1/history/milestones?limit=1&offset=0",
    )
    .await;
    let (_, page2) = get_body(
        router().await,
        "/api/v1/history/milestones?limit=1&offset=1",
    )
    .await;
    assert_eq!(page1["total"], FIXTURE_MILESTONES);
    assert_eq!(
        page2["total"], FIXTURE_MILESTONES,
        "total describes the set, not the page"
    );
    assert_eq!(page1["items"].as_array().unwrap().len(), 1);
    assert_eq!(page2["items"].as_array().unwrap().len(), 1);
    assert_ne!(
        page1["items"][0]["commit"], page2["items"][0]["commit"],
        "pages must not overlap"
    );
}

// ---------------------------------------------------------------------------
// /api/v1/history/rollup
// ---------------------------------------------------------------------------

#[tokio::test]
async fn rollup_groups_by_agent_and_intent() {
    let (status, body) = get_body(router().await, "/api/v1/history/rollup").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);

    // Facet counts are weighted by commit_count, not row count. The engine's
    // own bookkeeping commits inflate the absolutes, so assert against the
    // agents this fixture actually drives: alice made 2 Refine + 1 Checkpoint,
    // bob 1 of each.
    let agents = facet_pairs(&body, "agents");
    assert_eq!(
        agents.iter().find(|(v, _)| v == "alice").map(|(_, c)| *c),
        Some(3),
        "body={}",
        body
    );
    assert_eq!(
        agents.iter().find(|(v, _)| v == "bob").map(|(_, c)| *c),
        Some(2),
        "body={}",
        body
    );

    // The rollup splits an agent's commits across intent categories.
    let alice_rows: Vec<&serde_json::Value> = body["items"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|r| r["agent"] == "alice")
        .collect();
    let by_intent = |intent: &str| -> i64 {
        alice_rows
            .iter()
            .filter(|r| r["intent"] == intent)
            .map(|r| r["commits"].as_i64().unwrap())
            .sum()
    };
    assert_eq!(by_intent("Refine"), 2, "body={}", body);
    assert_eq!(by_intent("Checkpoint"), 1, "body={}", body);
}

#[tokio::test]
async fn rollup_totals_describe_the_filtered_set_not_the_page() {
    let (_, all) = get_body(router().await, "/api/v1/history/rollup").await;
    let full_total = all["totals"]["commits"].as_i64().unwrap();

    let (_, paged) = get_body(router().await, "/api/v1/history/rollup?limit=1").await;
    assert_eq!(paged["items"].as_array().unwrap().len(), 1);
    assert_eq!(
        paged["totals"]["commits"].as_i64().unwrap(),
        full_total,
        "a one-row page must still sum the whole filtered set"
    );
}

#[tokio::test]
async fn rollup_agent_filter_restricts_totals() {
    let (status, body) = get_body(router().await, "/api/v1/history/rollup?agent=bob").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    // bob: one Refine + one Checkpoint.
    assert_eq!(body["totals"]["commits"], 2, "body={}", body);
}

#[tokio::test]
async fn rollup_date_range_excludes_everything_outside_it() {
    let (_, body) = get_body(
        router().await,
        "/api/v1/history/rollup?from=1999-01-01&to=1999-12-31",
    )
    .await;
    assert_eq!(body["total"], 0, "body={}", body);
    assert_eq!(body["totals"]["commits"], 0, "body={}", body);
}

// ---------------------------------------------------------------------------
// /api/v1/commits
// ---------------------------------------------------------------------------

#[tokio::test]
async fn commits_marks_milestone_commits_as_on_spine() {
    let (status, body) = get_body(router().await, "/api/v1/commits").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);

    // Only Checkpoint commits are pinned. This is also the regression guard
    // for the endpoint refreshing the distilled tables itself: without that,
    // a store whose extractor has never run reports on_spine = 0 here.
    assert_eq!(body["on_spine"], FIXTURE_MILESTONES, "body={}", body);
    let pinned: Vec<&serde_json::Value> = body["items"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|c| c["on_spine"] == true)
        .collect();
    assert_eq!(pinned.len() as u64, FIXTURE_MILESTONES, "body={}", body);
    for c in &pinned {
        assert_eq!(c["intent"], "Checkpoint", "body={}", body);
    }
    for who in ["alice", "bob"] {
        assert!(
            pinned.iter().any(|c| c["agent"] == who),
            "{}'s checkpoint should be pinned; body={}",
            who,
            body
        );
    }
}

#[tokio::test]
async fn commits_on_spine_counts_the_filtered_set() {
    // `on_spine` is paired against `total` in the UI's summary line, so the
    // two must be filtered identically. Counting `on_spine` over the
    // pre-filter set would report "2 of 1 are pinned".
    let (_, body) = get_body(router().await, "/api/v1/commits?q=widen").await;
    let total = body["total"].as_u64().unwrap();
    let on_spine = body["on_spine"].as_u64().unwrap();
    assert_eq!(total, 1, "body={}", body);
    assert!(
        on_spine <= total,
        "on_spine ({}) must not exceed total ({}); body={}",
        on_spine,
        total,
        body
    );
    assert_eq!(on_spine, 0, "the matched Refine commit is not pinned");
}

#[tokio::test]
async fn commits_milestone_filter_selects_each_side() {
    let (_, pinned) = get_body(router().await, "/api/v1/commits?milestone=1").await;
    let (_, unpinned) = get_body(router().await, "/api/v1/commits?milestone=0").await;

    assert_eq!(pinned["total"], FIXTURE_MILESTONES, "body={}", pinned);
    assert!(
        pinned["items"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["on_spine"] == true),
        "body={}",
        pinned
    );
    assert!(
        unpinned["items"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["on_spine"] == false),
        "body={}",
        unpinned
    );
    // Every commit is on exactly one side of the split.
    let scanned = pinned["scanned"].as_u64().unwrap();
    assert_eq!(
        pinned["total"].as_u64().unwrap() + unpinned["total"].as_u64().unwrap(),
        scanned,
        "the two sides must partition the walk"
    );
}

#[tokio::test]
async fn commits_walk_reports_scan_window_honestly() {
    let (_, capped) = get_body(router().await, "/api/v1/commits?scan=2").await;
    assert_eq!(capped["scanned"], 2, "body={}", capped);
    assert_eq!(
        capped["capped"], true,
        "a walk cut short must say so; body={}",
        capped
    );

    let (_, full) = get_body(router().await, "/api/v1/commits?scan=1000").await;
    assert_eq!(
        full["capped"], false,
        "a walk that drained the frontier is not capped; body={}",
        full
    );
}

#[tokio::test]
async fn commits_reports_the_rollups_own_total_for_comparison() {
    // `distilled` is what lets the UI say "N commits are no longer reachable".
    // With nothing pruned, the walk and the rollup must agree.
    let (_, body) = get_body(router().await, "/api/v1/commits?scan=1000").await;
    assert_eq!(
        body["distilled"].as_i64().unwrap(),
        body["scanned"].as_i64().unwrap(),
        "nothing is unreachable in a fresh store; body={}",
        body
    );
}

#[tokio::test]
async fn commits_agent_filter_narrows_results() {
    let (_, body) = get_body(router().await, "/api/v1/commits?agent=bob").await;
    assert_eq!(body["total"], 2, "body={}", body);
    assert!(
        body["items"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["agent"] == "bob"),
        "body={}",
        body
    );
}

// ---------------------------------------------------------------------------
// /api/v1/feedback
// ---------------------------------------------------------------------------

#[tokio::test]
async fn feedback_lists_entries_with_verdict_and_author_facets() {
    let (status, body) = get_body(router().await, "/api/v1/feedback").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert_eq!(body["total"], 3, "body={}", body);

    let verdicts = facet_pairs(&body, "verdicts");
    assert_eq!(
        verdicts
            .iter()
            .find(|(v, _)| v == "Useful")
            .map(|(_, c)| *c),
        Some(2),
        "body={}",
        body
    );
    let authors = facet_pairs(&body, "authors");
    assert_eq!(
        authors.iter().find(|(v, _)| v == "alice").map(|(_, c)| *c),
        Some(2),
        "body={}",
        body
    );
}

#[tokio::test]
async fn feedback_flags_lapsed_entries_rather_than_hiding_them() {
    let (_, body) = get_body(router().await, "/api/v1/feedback").await;
    let items = body["items"].as_array().unwrap();
    let expired: Vec<&serde_json::Value> = items.iter().filter(|e| e["expired"] == true).collect();
    assert_eq!(
        expired.len(),
        1,
        "the lapsed entry must still be listed; body={}",
        body
    );
    assert_eq!(expired[0]["entry_id"], "fb-3", "body={}", body);
}

#[tokio::test]
async fn feedback_search_covers_query_symbol_author_and_note() {
    // "entry point" appears only in fb-1's note.
    let (_, by_note) = get_body(router().await, "/api/v1/feedback?q=entry%20point").await;
    assert_eq!(by_note["total"], 1, "body={}", by_note);
    assert_eq!(by_note["items"][0]["entry_id"], "fb-1");

    // The query text is shared by two entries.
    let (_, by_query) = get_body(router().await, "/api/v1/feedback?q=charge%20a%20card").await;
    assert_eq!(by_query["total"], 2, "body={}", by_query);
}

#[tokio::test]
async fn feedback_verdict_filter_selects_one_kind() {
    let (_, body) = get_body(router().await, "/api/v1/feedback?verdict=noisy").await;
    assert_eq!(body["total"], 1, "body={}", body);
    assert_eq!(body["items"][0]["verdict"], "Noisy", "body={}", body);
}

#[tokio::test]
async fn feedback_symbol_filter_matches_a_qname_substring() {
    let (_, body) = get_body(router().await, "/api/v1/feedback?symbol=charge").await;
    assert_eq!(body["total"], 1, "body={}", body);
    assert_eq!(body["items"][0]["symbol_qname"], "pay.charge_card");
}

// ---------------------------------------------------------------------------
// /api/v1/index-health
// ---------------------------------------------------------------------------

#[tokio::test]
async fn index_health_reports_the_asg_symbol_count() {
    let (status, body) = get_body(router().await, "/api/v1/index-health").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert_eq!(body["symbols"]["asg"], 4, "body={}", body);
    assert_eq!(body["ref_name"], "main", "body={}", body);
}

// ---------------------------------------------------------------------------
// /api/v1/scorecard
// ---------------------------------------------------------------------------

#[tokio::test]
async fn scorecard_returns_the_full_cli_shape() {
    let (status, body) = get_body(router().await, "/api/v1/scorecard").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);

    for key in [
        "capability_scores",
        "scores",
        "data_quality",
        "details",
        "token_economy",
    ] {
        assert!(body.get(key).is_some(), "missing {}; body={}", key, body);
    }
    for dim in [
        "truth",
        "feedback",
        "change",
        "uncertainty",
        "workflow",
        "overall",
    ] {
        let v = body["capability_scores"][dim]
            .as_u64()
            .unwrap_or_else(|| panic!("dimension {} not a number; body={}", dim, body));
        assert!(v <= 100, "{} out of range: {}", dim, v);
    }
    assert_eq!(body["details"]["total_symbols"], 4, "body={}", body);
    assert_eq!(body["details"]["owned_symbols"], 1, "body={}", body);
    assert_eq!(body["details"]["feedback_entries"], 3, "body={}", body);
    assert_eq!(
        body["details"]["ctx_tagged_ledger_entries"], 1,
        "body={}",
        body
    );
}

#[tokio::test]
async fn scorecard_token_economy_compares_index_against_source() {
    let (_, body) = get_body(router().await, "/api/v1/scorecard").await;
    let te = &body["token_economy"];
    assert!(
        te["structured_tokens"].as_u64().unwrap() > 0,
        "body={}",
        body
    );
    assert!(
        te["source_read_tokens_est"].as_u64().unwrap() > te["structured_tokens"].as_u64().unwrap(),
        "reading source should cost more than the index; body={}",
        body
    );
}

#[tokio::test]
async fn scorecard_drill_down_lists_gap_symbols() {
    let (status, body) =
        get_body(router().await, "/api/v1/scorecard?drill_down=truth&limit=2").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);

    let drill = &body["drill_down"];
    assert_eq!(drill["dimension"], "truth", "body={}", body);
    let shown = drill["shown"].as_u64().unwrap();
    let total_gaps = drill["total_gaps"].as_u64().unwrap();
    assert!(shown <= 2, "limit not honored; body={}", body);
    assert_eq!(
        drill["omitted"].as_u64().unwrap(),
        total_gaps - shown,
        "omitted must account for the truncation; body={}",
        body
    );
    assert_eq!(
        drill["gap_symbols"].as_array().unwrap().len() as u64,
        shown,
        "body={}",
        body
    );
}

#[tokio::test]
async fn scorecard_path_filter_that_matches_nothing_says_so() {
    let (status, body) = get_body(router().await, "/api/v1/scorecard?paths=no/such/dir/**").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert!(
        body["note"]
            .as_str()
            .unwrap_or_default()
            .contains("paths filter"),
        "body={}",
        body
    );
    assert_eq!(body["capability_scores"]["overall"], 0, "body={}", body);
    // A filter that matched nothing still returns the full envelope, so a
    // consumer needs one parser rather than two. Zero here means "nothing to
    // score", which `note` says out loud — not "scored zero".
    assert_eq!(body["details"]["total_symbols"], 0, "body={}", body);
    assert_eq!(
        body["data_quality"]["scope"],
        serde_json::json!(["no/such/dir/**"]),
        "the filter in force should be echoed back; body={}",
        body
    );
}

#[tokio::test]
async fn scorecard_path_filter_scopes_the_symbol_set() {
    let (_, body) = get_body(router().await, "/api/v1/scorecard?paths=pay.py").await;
    assert_eq!(body["details"]["total_symbols"], 1, "body={}", body);
    assert_eq!(body["details"]["owned_symbols"], 1, "body={}", body);
}

/// The reason `core::scorecard` exists: three surfaces used to carry their
/// own copy of this arithmetic, each with tests that agreed with their own
/// copy. This pins the HTTP handler to core's output so a future edit to one
/// cannot silently diverge from the other two — the envelope may differ
/// (timestamp, note), but every computed block must be identical.
#[tokio::test]
async fn scorecard_payload_matches_core_exactly() {
    use agentstatedeveloper_core::scorecard::{ScorecardOptions, compute};

    let engine = fixture_engine();
    let expected = compute(
        &engine,
        std::path::Path::new(":memory:"),
        &ScorecardOptions {
            drill_limit: 50,
            ..Default::default()
        },
    )
    .to_json();

    let app = build_router(
        Arc::new(Mutex::new(engine)),
        PathBuf::from(":memory:"),
        None,
        None,
        true,
    );
    let (status, body) = get_body(app, "/api/v1/scorecard").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);

    for block in [
        "capability_scores",
        "scores",
        "data_quality",
        "details",
        "token_economy",
    ] {
        assert_eq!(
            body[block], expected[block],
            "{block} drifted from core::scorecard; body={body}"
        );
    }
    // The handler's own additions, which core deliberately does not emit.
    assert!(body["timestamp"].is_string(), "body={}", body);
}

// ---------------------------------------------------------------------------
// Feedback lifecycle actions (plan feedback-lifecycle t-006)
// ---------------------------------------------------------------------------

async fn post_body(app: axum::Router, uri: &str) -> (StatusCode, serde_json::Value) {
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri(uri)
                .header("content-type", "application/json")
                .body(Body::from("{}"))
                .unwrap(),
        )
        .await
        .unwrap();
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_else(
        |_| serde_json::json!({"_raw": String::from_utf8_lossy(&bytes).to_string()}),
    );
    (status, value)
}

#[tokio::test]
async fn feedback_listing_exposes_lifecycle_state() {
    // The tab renders from these fields; if they are absent it silently shows
    // retired verdicts as live.
    let (status, body) = get_body(router().await, "/api/v1/feedback").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    let item = &body["items"][0];
    for field in ["expired", "withdrawn", "inert"] {
        assert!(
            item.get(field).is_some_and(|v| v.is_boolean()),
            "{field} missing from the listing; body={body}"
        );
    }
}

#[tokio::test]
async fn withdrawing_returns_the_updated_entry() {
    // Matching the approvals endpoints so the UI can patch one row rather
    // than refetching the whole list.
    let (status, body) = post_body(router().await, "/api/v1/feedback/fb-1/withdraw").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert_eq!(body["entry_id"], "fb-1", "body={}", body);
    assert_eq!(body["withdrawn"], true, "body={}", body);
    assert_eq!(body["inert"], true, "body={}", body);
    assert!(body["withdrawn_at"].is_string(), "body={}", body);
    // Defaulted attribution when the body carries none.
    assert_eq!(body["withdrawn_by"], "asd-lens", "body={}", body);
}

#[tokio::test]
async fn expiring_returns_the_updated_entry() {
    let (status, body) = post_body(router().await, "/api/v1/feedback/fb-1/expire").await;
    assert_eq!(status, StatusCode::OK, "body={}", body);
    assert_eq!(body["expired"], true, "body={}", body);
    assert_eq!(body["inert"], true, "body={}", body);
    assert_eq!(
        body["withdrawn"], false,
        "expire must not withdraw; body={}",
        body
    );
}

#[tokio::test]
async fn acting_on_an_unknown_entry_is_a_404_not_a_500() {
    for action in ["withdraw", "expire"] {
        let (status, body) = post_body(
            router().await,
            &format!("/api/v1/feedback/fb-nope/{action}"),
        )
        .await;
        assert_eq!(
            status,
            StatusCode::NOT_FOUND,
            "{action} on a missing entry; body={body}"
        );
    }
}

#[tokio::test]
async fn a_withdrawn_entry_stays_in_the_listing() {
    // The asymmetry the tab depends on: retired verdicts remain visible,
    // marked, because they still explain a past ranking.
    let app = router().await;
    let (_, before) = get_body(app.clone(), "/api/v1/feedback").await;
    let n = before["total"].as_u64().unwrap();

    let (status, _) = post_body(app.clone(), "/api/v1/feedback/fb-1/withdraw").await;
    assert_eq!(status, StatusCode::OK);

    let (_, after) = get_body(app, "/api/v1/feedback").await;
    assert_eq!(
        after["total"].as_u64().unwrap(),
        n,
        "entry vanished from the list"
    );
    let row = after["items"]
        .as_array()
        .unwrap()
        .iter()
        .find(|e| e["entry_id"] == "fb-1")
        .expect("fb-1 still listed");
    assert_eq!(row["withdrawn"], true);
}