kazam 1.13.2

Local infrastructure for coding agents: context, visibility, durable execution. One Rust binary, no cloud.
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
1014
1015
1016
use anyhow::Result;
use serde_json::{json, Value};
use std::path::Path;
use walkdir::WalkDir;

use crate::annotations;
use crate::types::{
    Annotation, AnnotationSource, AnnotationStatus, Page, RefreshMode, RefreshStep, RefreshValue,
    Shell, SiteConfig,
};

use super::protocol::ToolResult;

// ── Tool definitions (JSON Schema) ──────────────────────

pub fn tool_definitions() -> Vec<super::protocol::Tool> {
    vec![
        super::protocol::Tool {
            name: "read_page".into(),
            description: "Read a page's YAML content and metadata. Returns raw YAML plus parsed metadata (title, shell, freshness).".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to the YAML file from the site root (e.g. 'customers/acme.yaml')"
                    }
                },
                "required": ["path"]
            }),
        },
        super::protocol::Tool {
            name: "list_pages".into(),
            description: "List all pages in the site or a subdirectory. Returns an array of objects with path, title, shell, and has_freshness.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "directory": {
                        "type": "string",
                        "description": "Optional subdirectory to list (e.g. 'customers'). Omit to list all pages."
                    }
                },
                "required": []
            }),
        },
        super::protocol::Tool {
            name: "get_config".into(),
            description: "Read the site configuration (kazam.yaml) as JSON.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {},
                "required": []
            }),
        },
        super::protocol::Tool {
            name: "search".into(),
            description: "Text search across page YAML content (case-insensitive, literal match). Returns matches with file path, title, and line context. If a query returns no results, try synonyms or broader terms (e.g. 'family leave' instead of 'maternity', 'PTO' instead of 'vacation'). Also try list_pages to browse by directory.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Text to search for (case-insensitive)"
                    }
                },
                "required": ["query"]
            }),
        },
        super::protocol::Tool {
            name: "write_page".into(),
            description: "Write or update a page YAML file. Validates the content parses as a valid Page before writing. Requires --allow-writes to be set.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Relative path to write (e.g. 'docs/auth.yaml')"
                    },
                    "content": {
                        "type": "string",
                        "description": "Full YAML content to write"
                    }
                },
                "required": ["path", "content"]
            }),
        },
        super::protocol::Tool {
            name: "annotate_page".into(),
            description: "Add an annotation to a page. Creates a sidecar YAML file in .kazam/annotations/<page-slug>/. Requires --allow-writes.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "page": {
                        "type": "string",
                        "description": "Relative path to the page YAML file (e.g. 'deals/acme.yaml')"
                    },
                    "text": {
                        "type": "string",
                        "description": "Annotation text"
                    },
                    "author": {
                        "type": "string",
                        "description": "Who is writing this annotation"
                    },
                    "section": {
                        "type": "string",
                        "description": "Optional section this annotation applies to (e.g. 'competitive', 'timeline')"
                    },
                    "source": {
                        "type": "string",
                        "enum": ["cli", "agent", "web"],
                        "description": "Where this annotation came from (default: agent)"
                    }
                },
                "required": ["page", "text", "author"]
            }),
        },
        super::protocol::Tool {
            name: "update_annotation".into(),
            description: "Update an annotation's status (e.g. after a refresh incorporates or ignores it). Requires --allow-writes.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "page": {
                        "type": "string",
                        "description": "Relative path to the page YAML file (e.g. 'deals/acme.yaml')"
                    },
                    "annotation_id": {
                        "type": "string",
                        "description": "Annotation ID (e.g. 'ann-20260507-a3f2')"
                    },
                    "status": {
                        "type": "string",
                        "enum": ["pending", "incorporated", "ignored", "stale"],
                        "description": "New status for the annotation"
                    }
                },
                "required": ["page", "annotation_id", "status"]
            }),
        },
        super::protocol::Tool {
            name: "list_annotations".into(),
            description: "List all annotations for a page. Returns an array of annotation objects from .kazam/annotations/<page-slug>/.".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "page": {
                        "type": "string",
                        "description": "Relative path to the page YAML file (e.g. 'deals/acme.yaml')"
                    }
                },
                "required": ["page"]
            }),
        },
    ]
}

// ── Helpers ───────────────────────────────────────────────

fn serialize_refresh(refresh: &Option<RefreshValue>) -> serde_json::Value {
    use serde_json::json;
    match refresh {
        None => serde_json::Value::Null,
        Some(RefreshValue::Prompt(s)) => json!(s),
        Some(RefreshValue::Full(config)) => {
            let mode = match config.mode {
                RefreshMode::Human => "human",
                RefreshMode::Auto => "auto",
                RefreshMode::Assisted => "assisted",
            };
            let steps: Vec<serde_json::Value> = config
                .steps
                .iter()
                .map(|s| match s {
                    RefreshStep::Run(v) => json!({"run": v}),
                    RefreshStep::Prompt(v) => json!({"prompt": v}),
                    RefreshStep::Review(v) => json!({"review": v}),
                })
                .collect();
            json!({
                "mode": mode,
                "steps": steps,
            })
        }
    }
}

// ── Tool implementations ─────────────────────────────────

pub fn read_page(dir: &Path, params: &Value) -> Result<ToolResult> {
    let path_str = params
        .get("path")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: path"))?;

    // Sanitize: reject paths that escape the site directory.
    if path_str.contains("..") {
        return Ok(ToolResult::error("path must not contain '..'"));
    }

    let full_path = dir.join(path_str);
    if !full_path.exists() {
        return Ok(ToolResult::error(format!("file not found: {}", path_str)));
    }

    // Verify the resolved path stays inside the site directory (guards against
    // symlink-based escapes and other canonicalization surprises).
    let site_root = dir
        .canonicalize()
        .map_err(|e| anyhow::anyhow!("canonicalizing site dir: {}", e))?;
    let canonical = full_path
        .canonicalize()
        .map_err(|e| anyhow::anyhow!("canonicalizing path: {}", e))?;
    if !canonical.starts_with(&site_root) {
        return Ok(ToolResult::error("path escapes site directory"));
    }

    let content = std::fs::read_to_string(&full_path)
        .map_err(|e| anyhow::anyhow!("reading {}: {}", path_str, e))?;

    // Parse for metadata extraction; surface parse errors as tool errors.
    let page_result: Result<Page, _> = serde_yaml::from_str(&content);
    let metadata = match page_result {
        Ok(page) => json!({
            "title": page.title,
            "shell": shell_name(page.shell).to_string(),
            "has_freshness": page.freshness.is_some(),
            "unlisted": page.unlisted,
            "freshness": page.freshness.as_ref().and_then(|fv| fv.as_full()).map(|f| json!({
                "owner": f.owner,
                "updated": f.updated,
                "review_every": f.review_every,
                "refresh": serialize_refresh(&f.refresh),
            })),
        }),
        Err(e) => json!({ "parse_error": e.to_string() }),
    };

    let output = json!({
        "path": path_str,
        "raw_yaml": content,
        "metadata": metadata,
    });

    Ok(ToolResult::text(serde_json::to_string_pretty(&output)?))
}

pub fn list_pages(dir: &Path, params: &Value) -> Result<ToolResult> {
    let subdir = params
        .get("directory")
        .and_then(Value::as_str)
        .unwrap_or("");

    let search_root = if subdir.is_empty() {
        dir.to_path_buf()
    } else {
        if subdir.contains("..") {
            return Ok(ToolResult::error("directory must not contain '..'"));
        }
        dir.join(subdir)
    };

    if !search_root.exists() {
        return Ok(ToolResult::error(format!(
            "directory not found: {}",
            subdir
        )));
    }

    let mut pages = Vec::new();

    for entry in WalkDir::new(&search_root)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| {
            if e.depth() > 0 {
                if let Some(name) = e.file_name().to_str() {
                    if name.starts_with('.') {
                        return false;
                    }
                }
            }
            true
        })
        .flatten()
    {
        let path = entry.path();
        if !entry.file_type().is_file() {
            continue;
        }

        let fname = path.file_name().unwrap_or_default();
        if fname == "kazam.yaml" || fname == "404.yaml" {
            continue;
        }

        if path.extension().map(|e| e == "yaml").unwrap_or(false) {
            let rel = path.strip_prefix(dir).unwrap_or(path);
            let rel_str = rel.to_string_lossy().replace('\\', "/");

            let content = match std::fs::read_to_string(path) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let (title, shell_str, has_freshness) = match serde_yaml::from_str::<Page>(&content) {
                Ok(page) => (
                    page.title.clone(),
                    shell_name(page.shell).to_string(),
                    page.freshness.is_some(),
                ),
                Err(_) => ("(unparseable)".into(), "unknown".into(), false),
            };

            pages.push(json!({
                "path": rel_str,
                "title": title,
                "shell": shell_str,
                "has_freshness": has_freshness,
            }));
        }
    }

    Ok(ToolResult::text(serde_json::to_string_pretty(&pages)?))
}

pub fn get_config(dir: &Path) -> Result<ToolResult> {
    let config_path = dir.join("kazam.yaml");
    if !config_path.exists() {
        // Return the default config as JSON
        let default = SiteConfig::default();
        let as_json = json!({
            "name": default.name,
            "theme": default.theme,
            "nav": null,
            "view_source": default.view_source,
            "_note": "No kazam.yaml found; showing defaults"
        });
        return Ok(ToolResult::text(serde_json::to_string_pretty(&as_json)?));
    }

    let content = std::fs::read_to_string(&config_path)
        .map_err(|e| anyhow::anyhow!("reading kazam.yaml: {}", e))?;

    // Parse YAML then round-trip through serde_json Value for clean output.
    let yaml_value: serde_yaml::Value =
        serde_yaml::from_str(&content).map_err(|e| anyhow::anyhow!("parsing kazam.yaml: {}", e))?;

    let json_value = yaml_to_json(yaml_value);
    Ok(ToolResult::text(serde_json::to_string_pretty(&json_value)?))
}

pub fn search(dir: &Path, params: &Value) -> Result<ToolResult> {
    let query = params
        .get("query")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: query"))?;

    if query.is_empty() {
        return Ok(ToolResult::error("query must not be empty"));
    }

    let query_lower = query.to_lowercase();
    let mut matches = Vec::new();

    for entry in WalkDir::new(dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| {
            if e.depth() > 0 {
                if let Some(name) = e.file_name().to_str() {
                    if name.starts_with('.') {
                        return false;
                    }
                }
            }
            true
        })
        .flatten()
    {
        let path = entry.path();
        if !entry.file_type().is_file() {
            continue;
        }

        let fname = path.file_name().unwrap_or_default();
        if fname == "kazam.yaml" || fname == "404.yaml" {
            continue;
        }

        if !path.extension().map(|e| e == "yaml").unwrap_or(false) {
            continue;
        }

        let rel = path.strip_prefix(dir).unwrap_or(path);
        let rel_str = rel.to_string_lossy().replace('\\', "/");

        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let title = serde_yaml::from_str::<Page>(&content)
            .map(|p| p.title)
            .unwrap_or_else(|_| "(unparseable)".into());

        let mut matching_lines = Vec::new();
        for (line_num, line) in content.lines().enumerate() {
            if line.to_lowercase().contains(&query_lower) {
                matching_lines.push(json!({
                    "line": line_num + 1,
                    "text": line.trim(),
                }));
            }
        }

        if !matching_lines.is_empty() {
            matches.push(json!({
                "path": rel_str,
                "title": title,
                "matches": matching_lines,
            }));
        }
    }

    Ok(ToolResult::text(serde_json::to_string_pretty(&matches)?))
}

pub fn write_page(dir: &Path, params: &Value, allow_writes: bool) -> Result<ToolResult> {
    if !allow_writes {
        return Ok(ToolResult::error(
            "write_page is disabled; restart kazam mcp with --allow-writes to enable it",
        ));
    }

    let path_str = params
        .get("path")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: path"))?;

    let content = params
        .get("content")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: content"))?;

    if path_str.contains("..") {
        return Ok(ToolResult::error("path must not contain '..'"));
    }

    // Validate it parses as a Page before writing anything.
    if let Err(e) = serde_yaml::from_str::<Page>(content) {
        return Ok(ToolResult::error(format!("invalid Page YAML: {}", e)));
    }

    let full_path = dir.join(path_str);
    if let Some(parent) = full_path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| anyhow::anyhow!("creating directories: {}", e))?;
    }

    // Verify the resolved path stays inside the site directory (guards against
    // symlink-based escapes and other canonicalization surprises). We
    // canonicalize the parent (which now exists after create_dir_all) and
    // append the filename so the target file itself need not exist yet.
    {
        let site_root = dir
            .canonicalize()
            .map_err(|e| anyhow::anyhow!("canonicalizing site dir: {}", e))?;
        let canonical_parent = full_path
            .parent()
            .unwrap_or(dir)
            .canonicalize()
            .map_err(|e| anyhow::anyhow!("canonicalizing parent dir: {}", e))?;
        let canonical_target = canonical_parent.join(
            full_path
                .file_name()
                .ok_or_else(|| anyhow::anyhow!("path has no filename"))?,
        );
        if !canonical_target.starts_with(&site_root) {
            return Ok(ToolResult::error("path escapes site directory"));
        }
    }

    std::fs::write(&full_path, content)
        .map_err(|e| anyhow::anyhow!("writing {}: {}", path_str, e))?;

    Ok(ToolResult::text(format!(
        "{{\"ok\": true, \"path\": \"{}\"}}",
        path_str
    )))
}

pub fn annotate_page(dir: &Path, params: &Value, allow_writes: bool) -> Result<ToolResult> {
    if !allow_writes {
        return Ok(ToolResult::error(
            "annotate_page is disabled; restart kazam mcp with --allow-writes to enable it",
        ));
    }

    let page = params
        .get("page")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: page"))?;
    let text = params
        .get("text")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: text"))?;
    let author = params
        .get("author")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: author"))?;

    if page.contains("..") {
        return Ok(ToolResult::error("page path must not contain '..'"));
    }

    let full_path = dir.join(page);
    if !full_path.exists() {
        return Ok(ToolResult::error(format!("page not found: {}", page)));
    }

    let section = params
        .get("section")
        .and_then(Value::as_str)
        .map(String::from);
    let source = match params.get("source").and_then(Value::as_str) {
        Some("cli") => AnnotationSource::Cli,
        Some("web") => AnnotationSource::Web,
        Some("agent") | None => AnnotationSource::Agent,
        Some(other) => {
            return Ok(ToolResult::error(format!(
                "invalid source '{}': expected cli, agent, or web",
                other
            )));
        }
    };

    let today = crate::freshness::today_iso();
    let id = annotations::generate_id(&today);
    let ann = Annotation {
        id: id.clone(),
        text: text.to_string(),
        author: author.to_string(),
        section,
        added: today,
        status: AnnotationStatus::Pending,
        source,
    };

    let slug = annotations::page_slug_from_path(page);
    let path = annotations::save_annotation(dir, &slug, &ann)?;

    let output = json!({
        "ok": true,
        "id": id,
        "path": path.strip_prefix(dir).unwrap_or(&path).to_string_lossy(),
    });
    Ok(ToolResult::text(serde_json::to_string_pretty(&output)?))
}

pub fn update_annotation(dir: &Path, params: &Value, allow_writes: bool) -> Result<ToolResult> {
    if !allow_writes {
        return Ok(ToolResult::error(
            "update_annotation is disabled; restart kazam mcp with --allow-writes to enable it",
        ));
    }

    let page = params
        .get("page")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: page"))?;
    let annotation_id = params
        .get("annotation_id")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: annotation_id"))?;
    let status_str = params
        .get("status")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: status"))?;

    if page.contains("..") {
        return Ok(ToolResult::error("page path must not contain '..'"));
    }

    let new_status = match status_str {
        "pending" => AnnotationStatus::Pending,
        "incorporated" => AnnotationStatus::Incorporated,
        "ignored" => AnnotationStatus::Ignored,
        "stale" => AnnotationStatus::Stale,
        other => {
            return Ok(ToolResult::error(format!(
                "invalid status '{}': expected pending, incorporated, ignored, or stale",
                other
            )));
        }
    };

    let slug = annotations::page_slug_from_path(page);
    let ann_dir = annotations::annotations_dir(dir, &slug);
    let ann_path = ann_dir.join(format!("{}.yaml", annotation_id));

    if !ann_path.exists() {
        return Ok(ToolResult::error(format!(
            "annotation not found: {}",
            annotation_id
        )));
    }

    let content = std::fs::read_to_string(&ann_path)
        .map_err(|e| anyhow::anyhow!("reading annotation: {}", e))?;
    let mut ann: Annotation =
        serde_yaml::from_str(&content).map_err(|e| anyhow::anyhow!("parsing annotation: {}", e))?;

    ann.status = new_status;
    let yaml = serde_yaml::to_string(&ann).map_err(|e| anyhow::anyhow!("serializing: {}", e))?;
    std::fs::write(&ann_path, yaml).map_err(|e| anyhow::anyhow!("writing annotation: {}", e))?;

    let output = json!({
        "ok": true,
        "id": annotation_id,
        "status": status_str,
    });
    Ok(ToolResult::text(serde_json::to_string_pretty(&output)?))
}

pub fn list_annotations(dir: &Path, params: &Value) -> Result<ToolResult> {
    let page = params
        .get("page")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("missing required parameter: page"))?;

    if page.contains("..") {
        return Ok(ToolResult::error("page path must not contain '..'"));
    }

    let slug = annotations::page_slug_from_path(page);
    let anns = annotations::load_annotations(dir, &slug)?;

    let items: Vec<Value> = anns
        .iter()
        .map(|a| {
            json!({
                "id": a.id,
                "text": a.text,
                "author": a.author,
                "section": a.section,
                "added": a.added,
                "status": format!("{:?}", a.status).to_lowercase(),
                "source": format!("{:?}", a.source).to_lowercase(),
            })
        })
        .collect();

    Ok(ToolResult::text(serde_json::to_string_pretty(&items)?))
}

fn shell_name(shell: Shell) -> &'static str {
    match shell {
        Shell::Standard => "standard",
        Shell::Document => "document",
        Shell::Deck => "deck",
        Shell::Hub => "hub",
    }
}

// ── YAML → JSON conversion ───────────────────────────────

fn yaml_to_json(value: serde_yaml::Value) -> Value {
    match value {
        serde_yaml::Value::Null => Value::Null,
        serde_yaml::Value::Bool(b) => Value::Bool(b),
        serde_yaml::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Number(i.into())
            } else if let Some(f) = n.as_f64() {
                serde_json::Number::from_f64(f)
                    .map(Value::Number)
                    .unwrap_or(Value::Null)
            } else {
                Value::Null
            }
        }
        serde_yaml::Value::String(s) => Value::String(s),
        serde_yaml::Value::Sequence(seq) => {
            Value::Array(seq.into_iter().map(yaml_to_json).collect())
        }
        serde_yaml::Value::Mapping(map) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in map {
                let key = match k {
                    serde_yaml::Value::String(s) => s,
                    other => format!("{:?}", other),
                };
                obj.insert(key, yaml_to_json(v));
            }
            Value::Object(obj)
        }
        serde_yaml::Value::Tagged(t) => yaml_to_json(t.value),
    }
}

// ── Tests ────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn make_temp_site() -> TempDir {
        let dir = tempfile::tempdir().unwrap();

        fs::write(
            dir.path().join("kazam.yaml"),
            "name: Test Site\ntheme: dark\n",
        )
        .unwrap();

        fs::write(
            dir.path().join("index.yaml"),
            "title: Home\nshell: standard\ncomponents:\n  - type: header\n    title: Welcome\n",
        )
        .unwrap();

        let sub = dir.path().join("docs");
        fs::create_dir_all(&sub).unwrap();
        fs::write(
            sub.join("auth.yaml"),
            "title: Auth Guide\nshell: document\ncomponents:\n  - type: markdown\n    body: Authentication docs\n",
        )
        .unwrap();

        dir
    }

    #[test]
    fn read_page_returns_content() {
        let site = make_temp_site();
        let result = read_page(site.path(), &json!({"path": "index.yaml"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("Home"));
        assert!(text.contains("raw_yaml"));
    }

    #[test]
    fn read_page_rejects_path_traversal() {
        let site = make_temp_site();
        let result = read_page(site.path(), &json!({"path": "../etc/passwd"})).unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn read_page_missing_file() {
        let site = make_temp_site();
        let result = read_page(site.path(), &json!({"path": "missing.yaml"})).unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn list_pages_returns_all() {
        let site = make_temp_site();
        let result = list_pages(site.path(), &json!({})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("index.yaml"));
        assert!(text.contains("docs/auth.yaml"));
    }

    #[test]
    fn list_pages_subdir() {
        let site = make_temp_site();
        let result = list_pages(site.path(), &json!({"directory": "docs"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("docs/auth.yaml"));
        assert!(!text.contains("index.yaml"));
    }

    #[test]
    fn list_pages_rejects_traversal() {
        let site = make_temp_site();
        let result = list_pages(site.path(), &json!({"directory": "../other"})).unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn get_config_returns_json() {
        let site = make_temp_site();
        let result = get_config(site.path()).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("Test Site"));
    }

    #[test]
    fn get_config_no_kazam_yaml_returns_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let result = get_config(dir.path()).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("_note"));
    }

    #[test]
    fn search_finds_matches() {
        let site = make_temp_site();
        let result = search(site.path(), &json!({"query": "authentication"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("auth.yaml"));
    }

    #[test]
    fn search_case_insensitive() {
        let site = make_temp_site();
        let result = search(site.path(), &json!({"query": "AUTHENTICATION"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("auth.yaml"));
    }

    #[test]
    fn search_no_results() {
        let site = make_temp_site();
        let result = search(site.path(), &json!({"query": "xyzzy_not_found"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        assert!(result.content[0].text.contains("[]"));
    }

    #[test]
    fn write_page_blocked_without_allow_writes() {
        let site = make_temp_site();
        let result = write_page(
            site.path(),
            &json!({"path": "new.yaml", "content": "title: X\nshell: standard\n"}),
            false,
        )
        .unwrap();
        assert_eq!(result.is_error, Some(true));
        assert!(result.content[0].text.contains("--allow-writes"));
    }

    #[test]
    fn write_page_rejects_invalid_yaml() {
        let site = make_temp_site();
        let result = write_page(
            site.path(),
            &json!({"path": "new.yaml", "content": "not valid page yaml: [[["}),
            true,
        )
        .unwrap();
        assert_eq!(result.is_error, Some(true));
        assert!(result.content[0].text.contains("invalid Page YAML"));
    }

    #[test]
    fn write_page_rejects_traversal() {
        let site = make_temp_site();
        let result = write_page(
            site.path(),
            &json!({"path": "../outside.yaml", "content": "title: X\nshell: standard\n"}),
            true,
        )
        .unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn write_page_creates_valid_page() {
        let site = make_temp_site();
        let content =
            "title: New Page\nshell: document\ncomponents:\n  - type: markdown\n    body: Hello\n";
        let result = write_page(
            site.path(),
            &json!({"path": "new.yaml", "content": content}),
            true,
        )
        .unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let written = fs::read_to_string(site.path().join("new.yaml")).unwrap();
        assert_eq!(written, content);
    }

    #[test]
    fn annotate_page_creates_sidecar_file() {
        let site = make_temp_site();
        let result = annotate_page(
            site.path(),
            &json!({
                "page": "index.yaml",
                "text": "Test annotation",
                "author": "tyler",
                "section": "competitive",
                "source": "agent"
            }),
            true,
        )
        .unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("\"ok\": true"));
        assert!(text.contains("ann-"));
    }

    #[test]
    fn annotate_page_blocked_without_allow_writes() {
        let site = make_temp_site();
        let result = annotate_page(
            site.path(),
            &json!({"page": "index.yaml", "text": "note", "author": "tyler"}),
            false,
        )
        .unwrap();
        assert_eq!(result.is_error, Some(true));
        assert!(result.content[0].text.contains("--allow-writes"));
    }

    #[test]
    fn annotate_page_missing_page() {
        let site = make_temp_site();
        let result = annotate_page(
            site.path(),
            &json!({"page": "nonexistent.yaml", "text": "note", "author": "tyler"}),
            true,
        )
        .unwrap();
        assert_eq!(result.is_error, Some(true));
        assert!(result.content[0].text.contains("not found"));
    }

    #[test]
    fn list_annotations_empty_page() {
        let site = make_temp_site();
        let result = list_annotations(site.path(), &json!({"page": "index.yaml"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        assert!(result.content[0].text.contains("[]"));
    }

    #[test]
    fn update_annotation_status() {
        let site = make_temp_site();
        // Create an annotation first
        let create_result = annotate_page(
            site.path(),
            &json!({
                "page": "index.yaml",
                "text": "Status update test",
                "author": "tyler",
            }),
            true,
        )
        .unwrap();
        let create_text = &create_result.content[0].text;
        let create_json: serde_json::Value = serde_json::from_str(create_text).unwrap();
        let ann_id = create_json["id"].as_str().unwrap();

        // Update status to incorporated
        let result = update_annotation(
            site.path(),
            &json!({
                "page": "index.yaml",
                "annotation_id": ann_id,
                "status": "incorporated",
            }),
            true,
        )
        .unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("incorporated"));

        // Verify via list
        let list_result = list_annotations(site.path(), &json!({"page": "index.yaml"})).unwrap();
        let list_text = &list_result.content[0].text;
        assert!(list_text.contains("incorporated"));
    }

    #[test]
    fn update_annotation_not_found() {
        let site = make_temp_site();
        let result = update_annotation(
            site.path(),
            &json!({
                "page": "index.yaml",
                "annotation_id": "ann-20260507-0000",
                "status": "incorporated",
            }),
            true,
        )
        .unwrap();
        assert_eq!(result.is_error, Some(true));
        assert!(result.content[0].text.contains("not found"));
    }

    #[test]
    fn annotate_then_list_round_trip() {
        let site = make_temp_site();
        annotate_page(
            site.path(),
            &json!({
                "page": "index.yaml",
                "text": "Round-trip test",
                "author": "tyler",
            }),
            true,
        )
        .unwrap();
        let result = list_annotations(site.path(), &json!({"page": "index.yaml"})).unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let text = &result.content[0].text;
        assert!(text.contains("Round-trip test"));
        assert!(text.contains("tyler"));
        assert!(text.contains("pending"));
    }
}