lagrange-library 0.3.3

A WASI-rendered Markdown static site facility — multilingual out of the box
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
//! Dev-server MCP surface — the agent-facing half of `lagrange dev --mcp`.
//!
//! Scope and shape (P2 of the knowledge-base repositioning):
//!
//! - **Lifetime**: the MCP surface exists only inside `lagrange dev`. There
//!   is no standalone MCP service and no production write path; tools read
//!   the build artifacts (`knowledge.json`, `build_status.json`) and the
//!   docs tree, and `build.trigger` reuses the very build the watch loop
//!   runs — one index, never two.
//! - **Transport**: stdio, line-delimited JSON-RPC 2.0 (see [`protocol`]).
//!   The static HTTP server and the watch loop keep running unchanged
//!   alongside; stdout belongs to the protocol, all logging goes to stderr.
//! - **Citations**: a citation is the five-tuple
//!   `{document_id, lang, revision, span, anchor}` — exactly the fields
//!   every chunk in `knowledge.json` already carries. `docs.fetch` validates
//!   the tuple against BOTH the built index and the current file bytes and
//!   refuses stale revisions explicitly (never silently serving newer
//!   content).
//!
//! Concurrency posture: one MCP session per `--mcp` process; requests are
//! handled strictly in order on the session thread. The only cross-thread
//! shared resource is the build, serialized by [`McpState::build_lock`] so
//! a `build.trigger` cannot interleave with a watch-loop rebuild (both
//! clear and repopulate the output directory).

pub mod activity;
mod ops;
mod protocol;
mod query;
mod tools;
mod write;

use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use serde_json::{json, Value};

use crate::site::BuildOptions;
use protocol::RpcError;

/// Latest MCP protocol revision this server speaks. Older revisions from
/// the official set are accepted by echoing the client's request back.
const PROTOCOL_VERSION: &str = "2025-06-18";
const KNOWN_PROTOCOL_VERSIONS: [&str; 3] = ["2024-11-05", "2025-03-26", "2025-06-18"];

/// Shared context for the MCP session, built once by `lagrange dev --mcp`.
pub struct McpState {
    /// Docs tree root (`BuildOptions::src`).
    pub src: PathBuf,
    /// Output directory (`BuildOptions::out`) — `knowledge.json` and
    /// `build_status.json` are read from here.
    pub out: PathBuf,
    /// Full options for `build.trigger` (same ones the dev command uses).
    pub build_opts: BuildOptions,
    /// `[mcp] write_paths` from lagrange.toml — empty means the whole docs
    /// root is writable (single-agent local-dev posture).
    pub write_paths: Vec<String>,
    /// Build mutex shared with the watch loop: the build clears and
    /// repopulates the output directory, so two concurrent builds would
    /// corrupt it. Poisoning is tolerated (dev server resilience).
    pub build_lock: Arc<Mutex<()>>,
    /// Agent activity telemetry, shared with the dev HTTP server for the
    /// console's agent-activity view. Optional: absent when MCP runs
    /// without an HTTP surface (unit tests).
    pub activity: Option<Arc<activity::ActivityLog>>,
}

impl McpState {
    /// Load `knowledge.json` from the output directory.
    fn knowledge(&self) -> anyhow::Result<crate::knowledge::KnowledgeBase> {
        crate::knowledge::read_json(&self.out)
    }
}

/// Names of the served tools, for startup logging.
pub fn tool_names() -> &'static [&'static str] {
    &tools::TOOL_NAMES
}

/// Run the stdio JSON-RPC loop until stdin closes.
///
/// Returns `Ok` on EOF (client disconnected — the dev server keeps
/// running); returns `Err` on I/O failure.
pub fn run_stdio(state: Arc<McpState>) -> anyhow::Result<()> {
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    for line in stdin.lock().lines() {
        let line = line?;
        let state_for_cb = state.clone();
        if let Some(response) = protocol::process_line(&line, |method, params| {
            dispatch(&state_for_cb, method, params)
        }) {
            out.write_all(response.as_bytes())?;
            out.flush()?;
        }
    }
    Ok(())
}

/// Method-level dispatch (one level above tools): the MCP handshake core.
fn dispatch(state: &McpState, method: &str, params: &Value) -> Result<Value, RpcError> {
    match method {
        "initialize" => Ok(initialize_result(params)),
        "ping" => Ok(json!({})),
        "tools/list" => Ok(json!({ "tools": tools::descriptors() })),
        "tools/call" => {
            let tool = params
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("?")
                .to_string();
            let detail = params
                .get("arguments")
                .map(|a| {
                    let a = a.clone();
                    let q = a
                        .get("query")
                        .or_else(|| a.get("document_id"))
                        .or_else(|| a.get("path"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    if q.is_empty() {
                        serde_json::to_string(&a).unwrap_or_default()
                    } else {
                        q
                    }
                })
                .unwrap_or_default();
            let result = tools::call(state, params);
            let ok = !result
                .as_ref()
                .map(|v| {
                    v.get("structuredContent")
                        .and_then(|s| s.get("isError"))
                        .and_then(|e| e.as_bool())
                        .unwrap_or(false)
                })
                .unwrap_or(false);
            let truncated: String = detail.chars().take(120).collect();
            if let Some(log) = &state.activity {
                log.record(&tool, ok, truncated);
            }
            result
        }
        // Notifications (initialized, cancelled, …) are observed here and
        // intentionally produce no output.
        _ if method.starts_with("notifications/") => Ok(Value::Null),
        _ => Err(RpcError::new(
            protocol::error_code::METHOD_NOT_FOUND,
            format!("unknown method `{method}`"),
        )),
    }
}

/// Build the `initialize` result, negotiating the protocol revision.
fn initialize_result(params: &Value) -> Value {
    let requested = params
        .get("protocolVersion")
        .and_then(|v| v.as_str())
        .unwrap_or(PROTOCOL_VERSION);
    let negotiated = if KNOWN_PROTOCOL_VERSIONS.contains(&requested) {
        requested
    } else {
        PROTOCOL_VERSION
    };
    json!({
        "protocolVersion": negotiated,
        "capabilities": { "tools": { "listChanged": false } },
        "serverInfo": { "name": "lagrange", "version": env!("CARGO_PKG_VERSION") },
        "instructions": "lagrange dev docs surface. Search with docs.search, then fetch exact source text with docs.fetch by echoing the citation five-tuple (document_id, lang, revision, span, anchor). docs.fetch refuses mismatched revisions with a STALE error instead of returning different content. docs.write edits markdown under the docs root (scope may be narrowed by [mcp] write_paths in lagrange.toml); trigger build.trigger to rebuild, then docs.status reports the build outcome, freshness, missing translations and broken links."
    })
}

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

    fn state_fixture() -> McpState {
        McpState {
            activity: None,
            src: PathBuf::from("/nonexistent"),
            out: PathBuf::from("/nonexistent"),
            build_opts: BuildOptions {
                src: PathBuf::from("/nonexistent"),
                out: PathBuf::from("/nonexistent"),
                site_url: None,
                default_lang: None,
            },
            write_paths: Vec::new(),
            build_lock: Arc::new(Mutex::new(())),
        }
    }

    #[test]
    fn initialize_negotiates_known_versions_and_defaults_on_unknown() {
        for known in KNOWN_PROTOCOL_VERSIONS {
            let r = initialize_result(&json!({"protocolVersion": known}));
            assert_eq!(r["protocolVersion"], known);
        }
        let r = initialize_result(&json!({"protocolVersion": "1999-01-01"}));
        assert_eq!(r["protocolVersion"], PROTOCOL_VERSION);
        // No version at all → ours.
        let r = initialize_result(&json!({}));
        assert_eq!(r["protocolVersion"], PROTOCOL_VERSION);
    }

    #[test]
    fn initialize_result_shape_is_the_mcp_contract() {
        let r = initialize_result(&json!({"protocolVersion": PROTOCOL_VERSION}));
        assert_eq!(r["serverInfo"]["name"], "lagrange");
        assert_eq!(r["capabilities"]["tools"]["listChanged"], false);
        assert!(r["instructions"].as_str().unwrap().contains("STALE"));
    }

    #[test]
    fn dispatch_covers_the_handshake_core() {
        let st = state_fixture();
        assert_eq!(dispatch(&st, "ping", &json!({})).unwrap(), json!({}));
        let list = dispatch(&st, "tools/list", &json!({})).unwrap();
        let names: Vec<&str> = list["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap())
            .collect();
        assert_eq!(
            names,
            vec![
                "docs.search",
                "docs.fetch",
                "docs.tree",
                "docs.write",
                "docs.status",
                "build.trigger"
            ]
        );
        // notifications are absorbed without a response payload
        assert_eq!(
            dispatch(&st, "notifications/initialized", &json!({})).unwrap(),
            Value::Null
        );
        let err = dispatch(&st, "no/such/method", &json!({})).unwrap_err();
        assert_eq!(err.code, protocol::error_code::METHOD_NOT_FOUND);
    }

    #[test]
    fn tools_call_with_unknown_tool_is_invalid_params() {
        let st = state_fixture();
        let err = tools::call(&st, &json!({"name": "docs.nope", "arguments": {}})).unwrap_err();
        assert_eq!(err.code, protocol::error_code::INVALID_PARAMS);
    }
}

/// End-to-end tool tests against a REAL tempdir docs tree and a REAL
/// build: these exercise the whole read path (knowledge.json + source
/// slicing), not mocks.
#[cfg(test)]
mod tool_tests {
    use super::*;
    use serde_json::json;

    /// A tree with: one fully-translated document, one English-only
    /// document (missing zh-Hans), a working SUMMARY link and a broken one.
    fn fixture() -> (tempfile::TempDir, McpState) {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("docs");
        let out = dir.path().join("dist");
        std::fs::create_dir_all(src.join("en/guides")).unwrap();
        std::fs::create_dir_all(src.join("zh-Hans/guides")).unwrap();
        std::fs::write(
            src.join("en/SUMMARY.md"),
            "- [Quickstart](guides/quickstart.md)\n- [Nowhere](guides/missing.md)\n",
        )
        .unwrap();
        std::fs::write(
            src.join("en/index.md"),
            "---\ntitle: Home\n---\nIntro paragraph before the heading.\n\n# Home\n\nWelcome to the docs.\n",
        )
        .unwrap();
        // An id-less page: its identity is path-derived ("plain"), which is
        // what the ADD-direction identity guard protects.
        std::fs::write(
            src.join("en/plain.md"),
            "# Plain page\n\nNo explicit id here.\n",
        )
        .unwrap();
        std::fs::write(
            src.join("en/guides/quickstart.md"),
            "---\ntitle: Quickstart\nid: guides/quickstart\n---\n# Quickstart\n\nInstall the tool in your home directory.\n\n## Next steps\n\nConfigure it.\n",
        )
        .unwrap();
        std::fs::write(
            src.join("zh-Hans/guides/quickstart.md"),
            "---\ntitle: 快速开始\n---\n# 快速开始\n\n安装工具。\n\n## 下一步\n\n配置它。\n",
        )
        .unwrap();
        let opts = BuildOptions {
            src: src.clone(),
            out: out.clone(),
            site_url: None,
            default_lang: Some("en".to_string()),
        };
        crate::site::build_with_status(&opts).expect("fixture build");
        let state = McpState {
            activity: Some(Arc::new(crate::mcp::activity::ActivityLog::default())),
            src,
            out,
            build_opts: opts,
            write_paths: Vec::new(),
            build_lock: Arc::new(Mutex::new(())),
        };
        (dir, state)
    }

    fn call(state: &McpState, name: &str, args: Value) -> Value {
        tools::call(state, &json!({"name": name, "arguments": args})).unwrap()
    }

    #[test]
    fn search_ranks_heading_matches_above_body_matches() {
        let (_dir, st) = fixture();
        // Two candidates for the token "home": the index document's H1
        // HEADING is "Home" (heading match), and quickstart's body says
        // "…in your home directory." (body match). The heading match must
        // rank first — this is the pin that makes the 3x/1x weighting
        // mutation-detectable (swapping them flips the order).
        let r = call(&st, "docs.search", json!({"query": "home", "lang": "en"}));
        let hits = r["structuredContent"]["results"].as_array().unwrap();
        let order: Vec<&str> = hits.iter().map(|h| h["anchor"].as_str().unwrap()).collect();
        assert_eq!(
            order.first(),
            Some(&"home"),
            "heading match must outrank body match; got order: {order:?}"
        );
        assert!(
            order.contains(&"quickstart"),
            "the body match must also be a hit; got order: {order:?}"
        );
    }

    #[test]
    fn search_returns_chunk_citations_with_source_true_snippets() {
        let (_dir, st) = fixture();
        let r = call(
            &st,
            "docs.search",
            json!({"query": "quickstart", "lang": "en"}),
        );
        assert_eq!(r["isError"], false, "raw: {r}");
        let hits = r["structuredContent"]["results"].as_array().unwrap();
        assert!(!hits.is_empty());
        let top = &hits[0];
        assert_eq!(top["document_id"], "guides/quickstart");
        assert_eq!(top["lang"], "en");
        assert_eq!(top["anchor"], "quickstart");
        // Snippet truth: the reported span slices the REAL file bytes, and
        // the snippet is the projection of exactly that slice (integration
        // pin — an off-by-one in the span usage shows up here as a
        // mismatch, not only in docs.fetch).
        let span = &top["span"];
        let source = std::fs::read_to_string(st.src.join("en/guides/quickstart.md")).unwrap();
        let sliced = &source[span["start_byte"].as_u64().unwrap() as usize
            ..span["end_byte"].as_u64().unwrap() as usize];
        assert_eq!(
            top["snippet"].as_str().unwrap(),
            crate::search::truncate_chars(
                &crate::search::plain_text(sliced),
                crate::search::SNIPPET_CHARS
            ),
            "snippet must be the projection of the span's own bytes"
        );
        // …and the citation five-tuple is complete.
        for f in ["document_id", "lang", "revision", "span", "anchor"] {
            assert!(top.get(f).is_some_and(|v| !v.is_null()), "field {f}");
        }
    }

    #[test]
    fn search_supports_cjk_and_path_prefix_filters() {
        let (_dir, st) = fixture();
        let r = call(
            &st,
            "docs.search",
            json!({"query": "安装", "lang": "zh-Hans"}),
        );
        let hits = r["structuredContent"]["results"].as_array().unwrap();
        assert!(!hits.is_empty());
        assert_eq!(hits[0]["lang"], "zh-Hans");
        // path_prefix excludes the guides subtree → nothing matches.
        let r = call(
            &st,
            "docs.search",
            json!({"query": "quickstart", "path_prefix": "nope/"}),
        );
        assert!(r["structuredContent"]["results"]
            .as_array()
            .unwrap()
            .is_empty());
    }

    #[test]
    fn fetch_by_anchor_returns_the_exact_cited_bytes() {
        let (_dir, st) = fixture();
        let s = call(&st, "docs.search", json!({"query": "Configure"}));
        let hit = &s["structuredContent"]["results"][0];
        let f = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": hit["document_id"],
                "lang": hit["lang"],
                "revision": hit["revision"],
                "anchor": hit["anchor"],
            }),
        );
        assert_eq!(f["isError"], false, "raw: {f}");
        let cited = f["structuredContent"]["content"].as_str().unwrap();
        let source = std::fs::read_to_string(st.src.join("en/guides/quickstart.md")).unwrap();
        let span = &hit["span"];
        assert_eq!(
            cited,
            &source[span["start_byte"].as_u64().unwrap() as usize
                ..span["end_byte"].as_u64().unwrap() as usize],
            "fetched content must be the exact cited span"
        );
    }

    #[test]
    fn fetch_by_span_equivalence() {
        let (_dir, st) = fixture();
        let s = call(&st, "docs.search", json!({"query": "Install"}));
        let hit = &s["structuredContent"]["results"][0];
        let f = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": hit["document_id"],
                "lang": hit["lang"],
                "revision": hit["revision"],
                "span": hit["span"],
            }),
        );
        assert_eq!(f["isError"], false, "raw: {f}");
    }

    /// THE acceptance line: a stale revision must be an explicit error,
    /// never silently-newer content. Gate 2: the index still holds the
    /// requested revision, the FILE moved on.
    #[test]
    fn fetch_reports_stale_when_the_file_changed_after_the_build() {
        let (_dir, st) = fixture();
        let s = call(&st, "docs.search", json!({"query": "Install"}));
        let hit = &s["structuredContent"]["results"][0];
        // Edit the file on disk WITHOUT rebuilding.
        let path = st.src.join("en/guides/quickstart.md");
        let mut text = std::fs::read_to_string(&path).unwrap();
        text.push_str("\nAppended after the build.\n");
        std::fs::write(&path, text).unwrap();
        let f = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": hit["document_id"],
                "lang": hit["lang"],
                "revision": hit["revision"],
                "anchor": hit["anchor"],
            }),
        );
        assert_eq!(f["isError"], true, "stale must be isError");
        let msg = f["content"][0]["text"].as_str().unwrap();
        assert!(msg.starts_with("STALE:"), "message: {msg}");
        assert!(
            msg.contains("re-cite"),
            "message must say what to do: {msg}"
        );
        // And crucially: no content rode along.
        assert!(f.get("structuredContent").is_none());
    }

    /// Gate 1: the index side drifted (citation older or newer than the
    /// built knowledge) — requested revision != chunk revision.
    #[test]
    fn fetch_reports_stale_when_the_index_revision_differs() {
        let (_dir, st) = fixture();
        let s = call(&st, "docs.search", json!({"query": "Install"}));
        let hit = &s["structuredContent"]["results"][0];
        let bogus = "0".repeat(64);
        let f = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": hit["document_id"],
                "lang": hit["lang"],
                "revision": bogus,
                "anchor": hit["anchor"],
            }),
        );
        assert_eq!(f["isError"], true);
        let msg = f["content"][0]["text"].as_str().unwrap();
        assert!(msg.starts_with("STALE:"), "message: {msg}");
        assert!(msg.contains("index"), "must name the index side: {msg}");
    }

    #[test]
    fn fetch_rejects_bad_references() {
        let (_dir, st) = fixture();
        let r = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": "nope", "lang": "en", "revision": "0".repeat(64), "anchor": "x"
            }),
        );
        assert_eq!(r["isError"], true);
        assert!(r["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("unknown document_id"));

        // both selector args → error; neither → error
        let s = call(&st, "docs.search", json!({"query": "Install"}));
        let hit = &s["structuredContent"]["results"][0];
        let r = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": hit["document_id"], "lang": "en",
                "revision": hit["revision"], "anchor": "quickstart", "span": hit["span"]
            }),
        );
        assert!(r["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("not both"));
        let r = call(
            &st,
            "docs.fetch",
            json!({
                "document_id": hit["document_id"], "lang": "en", "revision": hit["revision"]
            }),
        );
        assert!(r["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("required"));
    }

    #[test]
    fn tree_reports_freshness_and_missing_translations() {
        let (_dir, st) = fixture();
        let t = call(&st, "docs.tree", json!({}));
        let docs = t["structuredContent"]["documents"].as_array().unwrap();
        let index_doc = docs
            .iter()
            .find(|d| d["document_id"] == "index")
            .expect("index doc");
        assert_eq!(
            index_doc["missing_langs"],
            json!(["zh-Hans"]),
            "en-only document must flag the missing translation"
        );
        let qs = docs
            .iter()
            .find(|d| d["document_id"] == "guides/quickstart")
            .unwrap();
        assert_eq!(qs["translations"]["en"]["freshness"], "fresh");
        // Now edit the en translation without rebuilding → stale.
        let p = st.src.join("en/guides/quickstart.md");
        let mut text = std::fs::read_to_string(&p).unwrap();
        text.push_str("\nchanged\n");
        std::fs::write(&p, text).unwrap();
        let t = call(&st, "docs.tree", json!({}));
        let docs = t["structuredContent"]["documents"].as_array().unwrap();
        let qs = docs
            .iter()
            .find(|d| d["document_id"] == "guides/quickstart")
            .unwrap();
        assert_eq!(qs["translations"]["en"]["freshness"], "stale");
    }

    #[test]
    fn write_creates_files_and_respects_scope() {
        let (_dir, st) = fixture();
        // In-scope create works.
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/agent-notes.md",
                "content": "# Agent notes\n\nWritten by the tool.\n"
            }),
        );
        assert_eq!(w["isError"], false, "raw: {w}");
        assert_eq!(w["structuredContent"]["created"], true);
        assert!(st.src.join("en/agent-notes.md").is_file());

        // Narrowed scope rejects out-of-prefix writes with a clear message.
        let narrowed = McpState {
            activity: st.activity.clone(),
            src: st.src.clone(),
            out: st.out.clone(),
            build_opts: st.build_opts.clone(),
            write_paths: vec!["zh-Hans/agent".to_string()],
            build_lock: st.build_lock.clone(),
        };
        let w = call(
            &narrowed,
            "docs.write",
            json!({
                "path": "en/agent-notes-2.md",
                "content": "# x\n"
            }),
        );
        assert_eq!(w["isError"], true);
        let msg = w["content"][0]["text"].as_str().unwrap();
        assert!(
            msg.contains("outside the configured write scope"),
            "msg: {msg}"
        );
        assert!(
            msg.contains("write_paths"),
            "must name the config knob: {msg}"
        );
        // The matching prefix still works.
        let w = call(
            &narrowed,
            "docs.write",
            json!({
                "path": "zh-Hans/agent/notes.md",
                "content": "# x\n"
            }),
        );
        assert_eq!(w["isError"], false, "raw: {w}");
    }

    #[test]
    fn write_rejects_escapes_wrong_lang_and_non_markdown() {
        let (_dir, st) = fixture();
        for (path, needle) in [
            ("../escape.md", ".."),
            ("/abs.md", "tree-RELATIVE"),
            ("fr/nouveau.md", "not a language directory"),
            ("en/logo.png", "markdown file"),
        ] {
            let w = call(&st, "docs.write", json!({"path": path, "content": "# x\n"}));
            assert_eq!(w["isError"], true, "{path} must be rejected");
            let msg = w["content"][0]["text"].as_str().unwrap();
            assert!(msg.contains(needle), "path {path}: message was {msg}");
        }
    }

    /// A symlink FILE inside the tree must not be written through — the
    /// write would land wherever the link points (possibly outside the
    /// docs root), which the parent-directory containment cannot see.
    #[cfg(unix)]
    #[test]
    fn write_refuses_symlink_files() {
        let (dir, st) = fixture();
        let outside = dir.path().join("outside.md");
        std::fs::write(&outside, "# outside\n").unwrap();
        let link = st.src.join("en/evil.md");
        std::os::unix::fs::symlink(&outside, &link).unwrap();
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/evil.md",
                "content": "# injected\n"
            }),
        );
        assert_eq!(w["isError"], true, "symlink write must be refused");
        assert!(w["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("symbolic link"));
        // And the outside file was NOT touched.
        assert_eq!(
            std::fs::read_to_string(&outside).unwrap(),
            "# outside\n",
            "the write must not have landed through the link"
        );
    }

    #[test]
    fn write_guards_the_document_identity() {
        let (_dir, st) = fixture();
        let p = st.src.join("en/guides/quickstart.md");
        let original = std::fs::read_to_string(&p).unwrap();

        // Dropping the id → refused.
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/guides/quickstart.md",
                "content": "---\ntitle: Quickstart\n---\n# Quickstart\n\nNew body.\n"
            }),
        );
        assert_eq!(w["isError"], true);
        assert!(w["content"][0]["text"].as_str().unwrap().contains("DROP"));

        // Changing the id → refused.
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/guides/quickstart.md",
                "content": "---\ntitle: Quickstart\nid: other/id\n---\n# Quickstart\n\nNew body.\n"
            }),
        );
        assert_eq!(w["isError"], true);
        assert!(w["content"][0]["text"].as_str().unwrap().contains("CHANGE"));

        // Keeping the id → allowed; content lands.
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/guides/quickstart.md",
                "content": "---\ntitle: Quickstart\nid: guides/quickstart\n---\n# Quickstart\n\nNew body.\n"
            }),
        );
        assert_eq!(w["isError"], false, "raw: {w}");
        assert!(std::fs::read_to_string(&p).unwrap().contains("New body."));
        assert_ne!(std::fs::read_to_string(&p).unwrap(), original);
    }

    /// Review R2 S1: the ADD direction. `en/plain.md` has no explicit id,
    /// so its identity is path-derived (`plain`). Writing content that ADDS
    /// `id: evil/moved` would re-key the document under a different id —
    /// `plain` vanishes from the knowledge base, `evil/moved` appears, and
    /// every existing citation to `plain` strands. Must be refused with the
    /// rule named.
    #[test]
    fn write_refuses_adding_a_rekeying_id() {
        let (_dir, st) = fixture();
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/plain.md",
                "content": "---\nid: evil/moved\n---\n# Plain page\n\nRe-keyed.\n"
            }),
        );
        assert_eq!(w["isError"], true, "re-keying ADD must be refused");
        let msg = w["content"][0]["text"].as_str().unwrap();
        assert!(msg.contains("re-key"), "message must name the rule: {msg}");
        assert!(msg.contains("`plain`"), "must name the derived id: {msg}");
        // The file is untouched.
        let on_disk = std::fs::read_to_string(st.src.join("en/plain.md")).unwrap();
        assert!(on_disk.contains("No explicit id here."));
        // End-to-end proof of the harm the guard prevents: with the write
        // REFUSED, the built knowledge still knows `plain` (and NOT
        // `evil/moved`).
        let kb = st.knowledge().unwrap();
        assert!(kb.documents.iter().any(|d| d.document_id == "plain"));
        assert!(!kb.documents.iter().any(|d| d.document_id == "evil/moved"));
    }

    /// The idempotent half of the ADD ruling: adding `id:` with EXACTLY
    /// the path-derived value changes nothing (it makes the implicit
    /// identity explicit) and is allowed. Rationale: forbidding it would
    /// block the legitimate "pin my derived identity down before a future
    /// rename" move, and identity-wise `plain` == `plain`.
    #[test]
    fn write_allows_adding_the_idempotent_derived_id() {
        let (_dir, st) = fixture();
        let w = call(
            &st,
            "docs.write",
            json!({
                "path": "en/plain.md",
                "content": "---\nid: plain\n---\n# Plain page\n\nNow explicit, same identity.\n"
            }),
        );
        assert_eq!(w["isError"], false, "raw: {w}");
        // Identity is unchanged: after a rebuild the knowledge base still
        // has exactly one `plain` document with the en translation.
        let t = call(&st, "build.trigger", json!({}));
        assert_eq!(t["isError"], false, "raw: {t}");
        let kb = st.knowledge().unwrap();
        let doc = kb
            .documents
            .iter()
            .find(|d| d.document_id == "plain")
            .expect("plain survives");
        assert!(doc.translations.contains_key("en"));
    }

    /// Review R2 S3-1: a symlinked DIRECTORY component must be caught
    /// BEFORE any directory creation runs — otherwise create_dir_all
    /// happily builds the missing tail components inside whatever the
    /// link points at (outside the docs root).
    #[cfg(unix)]
    #[test]
    fn write_refuses_symlink_dir_components_before_creating_anything() {
        let (dir, st) = fixture();
        // docs/en/agent → outside-tree (pre-existing symlink DIRECTORY).
        let outside_root = dir.path().join("outside-tree");
        std::fs::create_dir_all(&outside_root).unwrap();
        std::os::unix::fs::symlink(&outside_root, st.src.join("en/agent")).unwrap();
        let w = call(
            &st,
            "docs.write",
            json!({
                // Nested: the pre-creation check is the ONLY thing standing
                // between create_dir_all and building `sub/` inside the
                // symlink target (a single-level path would no-op in
                // create_dir_all and hide the ordering bug).
                "path": "en/agent/sub/new-notes.md",
                "content": "# x\n"
            }),
        );
        assert_eq!(
            w["isError"], true,
            "write through symlink dir must be refused"
        );
        let msg = w["content"][0]["text"].as_str().unwrap();
        assert!(msg.contains("outside the docs root"), "msg: {msg}");
        // And nothing was created on the other side of the link.
        assert!(
            std::fs::read_dir(&outside_root).unwrap().count() == 0,
            "no directories may be created outside the docs root"
        );
    }

    /// Review R2 S3-2: span pins must also cover a chunk that starts with
    /// BODY text (not a `#` heading marker) — a start+1 offset on a
    /// heading chunk is masked by the plain-text projection (the marker is
    /// stripped anyway), so this pin is what makes that mutation visible.
    #[test]
    fn search_snippet_pin_covers_a_body_starting_chunk() {
        let (_dir, st) = fixture();
        // index.md's prologue ("Intro paragraph before the heading.")
        // starts with body text, before any heading.
        let r = call(&st, "docs.search", json!({"query": "intro", "lang": "en"}));
        let hits = r["structuredContent"]["results"].as_array().unwrap();
        assert!(!hits.is_empty(), "raw: {r}");
        let top = &hits[0];
        assert_eq!(top["anchor"], "prologue");
        assert_eq!(top["document_id"], "index");
        let span = &top["span"];
        let source = std::fs::read_to_string(st.src.join("en/index.md")).unwrap();
        let sliced = &source[span["start_byte"].as_u64().unwrap() as usize
            ..span["end_byte"].as_u64().unwrap() as usize];
        assert!(
            sliced.starts_with('I'),
            "this fixture chunk must start with body text, not a heading marker"
        );
        assert_eq!(
            top["snippet"].as_str().unwrap(),
            crate::search::truncate_chars(
                &crate::search::plain_text(sliced),
                crate::search::SNIPPET_CHARS
            ),
            "snippet must be the projection of the span's own bytes"
        );
    }

    #[test]
    fn status_reports_build_diagnostics() {
        let (_dir, st) = fixture();
        let s = call(&st, "docs.status", json!({}));
        assert_eq!(s["isError"], false, "raw: {s}");
        let sc = &s["structuredContent"];
        assert_eq!(sc["build"]["ok"], true);
        assert!(sc["build"]["pages"].as_u64().unwrap() >= 2);
        // The fixture's SUMMARY references guides/missing.md → broken.
        let broken = sc["broken_links"].as_array().unwrap();
        assert!(
            broken
                .iter()
                .any(|b| b["target"].as_str().unwrap() == "guides/missing.html"),
            "broken: {broken:?}"
        );
        // index.md exists only in en → missing translation.
        let missing = sc["missing_translations"].as_array().unwrap();
        assert!(missing.iter().any(|m| m["document_id"] == "index"
            && m["missing"].as_array().unwrap().contains(&json!("zh-Hans"))));
        // Freshness tallies: 4 translations (en+zh quickstart, en index,
        // en plain), all fresh right after the build.
        assert_eq!(sc["freshness"]["fresh"].as_u64().unwrap(), 4);
    }

    #[test]
    fn status_without_any_build_tells_you_to_trigger_one() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("en")).unwrap();
        std::fs::write(dir.path().join("en/a.md"), "# A\n").unwrap();
        let st = McpState {
            activity: Some(Arc::new(crate::mcp::activity::ActivityLog::default())),
            src: dir.path().join("docs"),
            out: dir.path().join("dist"),
            build_opts: BuildOptions {
                src: dir.path().join("docs"),
                out: dir.path().join("dist"),
                site_url: None,
                default_lang: None,
            },
            write_paths: Vec::new(),
            build_lock: Arc::new(Mutex::new(())),
        };
        let s = call(&st, "docs.status", json!({}));
        assert_eq!(s["isError"], true);
        assert!(s["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("build.trigger"));
    }

    #[test]
    fn trigger_rebuilds_and_failure_is_recorded_and_visible() {
        let (_dir, st) = fixture();
        // Happy path: the trigger rebuilds and reports counts.
        let t = call(&st, "build.trigger", json!({}));
        assert_eq!(t["isError"], false, "raw: {t}");
        assert_eq!(t["structuredContent"]["ok"], true);
        assert_eq!(t["structuredContent"]["documents"].as_u64().unwrap(), 3);

        // Failure path: empty the docs root so the build fails ("no
        // language directories"); the failure must be recorded and surface
        // through docs.status.
        std::fs::remove_dir_all(st.src.join("zh-Hans")).unwrap();
        std::fs::remove_dir_all(st.src.join("en")).unwrap();
        let t = call(&st, "build.trigger", json!({}));
        assert_eq!(t["isError"], true);
        assert!(t["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("build failed"));
        let s = call(&st, "docs.status", json!({}));
        assert_eq!(s["isError"], false, "status itself must answer");
        assert_eq!(s["structuredContent"]["build"]["ok"], false);
        assert!(s["structuredContent"]["build"]["error"]
            .as_str()
            .unwrap()
            .contains("language"));
    }

    #[test]
    fn tool_call_is_recorded_in_activity_log() {
        let (_dir, state) = fixture();
        let log = state.activity.as_ref().expect("fixture carries a log");
        let params = serde_json::json!({
            "name": "docs.tree",
            "arguments": {}
        });
        let result = dispatch(&state, "tools/call", &params);
        assert!(result.is_ok(), "docs.tree should succeed: {result:?}");
        let snap = log.snapshot();
        assert_eq!(snap.len(), 1, "one call recorded");
        assert_eq!(snap[0].tool, "docs.tree");
        assert!(snap[0].ok);
        assert!(!snap[0].ts.is_empty());
    }
}