agent-file-tools 0.13.1

Agent File Tools — tree-sitter powered code analysis for AI agents
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
//! Handler for the `add_member` command: insert a method, field, or function
//! into a scope container (class, struct, impl block) with correct indentation.
//!
//! Supports TS/JS classes, Python classes, Rust structs/impl blocks, and Go
//! structs. Resolves insertion position via `first`, `last`, `before:name`,
//! `after:name`.

use std::path::Path;

use tree_sitter::{Node, Parser};

use crate::context::AppContext;
use crate::edit;
use crate::error::AftError;
use crate::indent::{detect_indent, IndentStyle};
use crate::parser::{detect_language, grammar_for, node_text, LangId};
use crate::protocol::{RawRequest, Response};

/// Handle an `add_member` request.
///
/// Params:
///   - `file` (string, required) — target file path
///   - `scope` (string, required) — name of class/struct/impl to target
///   - `code` (string, required) — the member code to insert
///   - `position` (string, optional) — `first`, `last`, `before:name`, `after:name` (default `last`)
///
/// Returns: `{ file, scope, position, syntax_valid?, backup_id? }`
pub fn handle_add_member(req: &RawRequest, ctx: &AppContext) -> Response {
    // --- Extract params ---
    let file = match req.params.get("file").and_then(|v| v.as_str()) {
        Some(f) => f,
        None => {
            return Response::error(
                &req.id,
                "invalid_request",
                "add_member: missing required param 'file'",
            );
        }
    };

    let scope_name = match req.params.get("scope").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => {
            return Response::error(
                &req.id,
                "invalid_request",
                "add_member: missing required param 'scope'",
            );
        }
    };

    let code = match req.params.get("code").and_then(|v| v.as_str()) {
        Some(c) => c,
        None => {
            return Response::error(
                &req.id,
                "invalid_request",
                "add_member: missing required param 'code'",
            );
        }
    };

    let position = req
        .params
        .get("position")
        .and_then(|v| v.as_str())
        .unwrap_or("last");

    // --- Validate ---
    let path = match ctx.validate_path(&req.id, Path::new(file)) {
        Ok(path) => path,
        Err(resp) => return resp,
    };
    if !path.exists() {
        return Response::error(
            &req.id,
            "file_not_found",
            format!("add_member: file not found: {}", file),
        );
    }

    let lang = match detect_language(&path) {
        Some(l) => l,
        None => {
            return Response::error(
                &req.id,
                "invalid_request",
                format!(
                    "add_member: unsupported file extension: {}",
                    path.extension()
                        .and_then(|e| e.to_str())
                        .unwrap_or("<none>")
                ),
            );
        }
    };

    // --- Parse ---
    let source = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) => {
            return Response::error(
                &req.id,
                "file_not_found",
                format!("add_member: cannot read file: {}", e),
            );
        }
    };

    let grammar = grammar_for(lang);
    let mut parser = Parser::new();
    if let Err(e) = parser.set_language(&grammar) {
        return Response::error(
            &req.id,
            "parse_error",
            format!("add_member: grammar init failed: {}", e),
        );
    }

    let tree = match parser.parse(&source, None) {
        Some(t) => t,
        None => {
            return Response::error(
                &req.id,
                "parse_error",
                format!("add_member: parse failed for {}", file),
            );
        }
    };

    let root = tree.root_node();

    // --- Find scope container ---
    let (scope_node_result, available) = find_scope_container(&root, &source, scope_name, lang);
    let (body_node_start, body_node_end, body_children) = match scope_node_result {
        Some(info) => info,
        None => {
            let err = AftError::ScopeNotFound {
                scope: scope_name.to_string(),
                available,
                file: file.to_string(),
            };
            return Response::error(&req.id, err.code(), err.to_string());
        }
    };

    // --- Detect indentation ---
    let file_indent = detect_indent(&source, lang);
    let member_indent = detect_member_indent(&source, &body_children, &file_indent, lang);

    // --- Resolve insertion position ---
    let insert_offset = match resolve_position(
        &source,
        position,
        body_node_start,
        body_node_end,
        &body_children,
        lang,
        scope_name,
        file,
    ) {
        Ok(offset) => offset,
        Err(err) => {
            return Response::error(&req.id, err.code(), err.to_string());
        }
    };

    // --- Indent the provided code ---
    let indented_code = indent_code(
        code,
        &member_indent,
        &source,
        insert_offset,
        position,
        body_node_start,
        body_node_end,
        &body_children,
        lang,
    );

    // --- Auto-backup (skip for dry-run) ---
    let backup_id = if !edit::is_dry_run(&req.params) {
        match edit::auto_backup(ctx, &path, "add_member: pre-edit backup") {
            Ok(id) => id,
            Err(e) => {
                return Response::error(&req.id, e.code(), e.to_string());
            }
        }
    } else {
        None
    };

    // --- Insert ---
    let new_source =
        match edit::replace_byte_range(&source, insert_offset, insert_offset, &indented_code) {
            Ok(s) => s,
            Err(e) => return Response::error(&req.id, e.code(), e.to_string()),
        };

    // Dry-run: return diff without modifying disk
    if edit::is_dry_run(&req.params) {
        let dr = edit::dry_run_diff(&source, &new_source, &path);
        return Response::success(
            &req.id,
            serde_json::json!({
                "ok": true, "dry_run": true, "diff": dr.diff, "syntax_valid": dr.syntax_valid,
            }),
        );
    }

    // --- Write, format, and validate ---
    let mut write_result =
        match edit::write_format_validate(&path, &new_source, &ctx.config(), &req.params) {
            Ok(r) => r,
            Err(e) => {
                return Response::error(&req.id, e.code(), e.to_string());
            }
        };

    if let Ok(final_content) = std::fs::read_to_string(&path) {
        write_result.lsp_diagnostics = ctx.lsp_post_write(&path, &final_content, &req.params);
    }

    log::debug!("add_member: {}", file);

    // --- Build response ---
    let mut result = serde_json::json!({
        "file": file,
        "scope": scope_name,
        "position": position,
        "formatted": write_result.formatted,
    });

    if let Some(valid) = write_result.syntax_valid {
        result["syntax_valid"] = serde_json::json!(valid);
    }

    if let Some(ref reason) = write_result.format_skipped_reason {
        result["format_skipped_reason"] = serde_json::json!(reason);
    }

    if write_result.validate_requested {
        result["validation_errors"] = serde_json::json!(write_result.validation_errors);
    }
    if let Some(ref reason) = write_result.validate_skipped_reason {
        result["validate_skipped_reason"] = serde_json::json!(reason);
    }

    if let Some(ref id) = backup_id {
        result["backup_id"] = serde_json::json!(id);
    }

    write_result.append_lsp_diagnostics_to(&mut result);
    Response::success(&req.id, result)
}

/// Info about a body: (body_start_byte, body_end_byte, named_children)
/// where named_children are (name, start_byte, end_byte) tuples.
type BodyInfo = (usize, usize, Vec<BodyChild>);

#[derive(Debug)]
struct BodyChild {
    name: String,
    start_byte: usize,
    end_byte: usize,
}

/// Find a scope container node by name, returning body info and available scope names.
fn find_scope_container(
    root: &Node,
    source: &str,
    scope_name: &str,
    lang: LangId,
) -> (Option<BodyInfo>, Vec<String>) {
    let mut available: Vec<String> = Vec::new();

    match lang {
        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
            // Walk for class_declaration matching name
            let mut cursor = root.walk();
            if cursor.goto_first_child() {
                loop {
                    let node = cursor.node();
                    if node.kind() == "class_declaration" {
                        if let Some(name) =
                            find_child_text(&node, source, &["type_identifier", "identifier"])
                        {
                            available.push(name.clone());
                            if name == scope_name {
                                if let Some(body) = find_child_by_kind(&node, "class_body") {
                                    let children = extract_body_children_ts(&body, source);
                                    return (
                                        Some((body.start_byte(), body.end_byte(), children)),
                                        available,
                                    );
                                }
                            }
                        }
                    }
                    // Also check export_statement wrapping class
                    if node.kind() == "export_statement" {
                        let mut inner = node.walk();
                        if inner.goto_first_child() {
                            loop {
                                let child = inner.node();
                                if child.kind() == "class_declaration" {
                                    if let Some(name) = find_child_text(
                                        &child,
                                        source,
                                        &["type_identifier", "identifier"],
                                    ) {
                                        if !available.contains(&name) {
                                            available.push(name.clone());
                                        }
                                        if name == scope_name {
                                            if let Some(body) =
                                                find_child_by_kind(&child, "class_body")
                                            {
                                                let children =
                                                    extract_body_children_ts(&body, source);
                                                return (
                                                    Some((
                                                        body.start_byte(),
                                                        body.end_byte(),
                                                        children,
                                                    )),
                                                    available,
                                                );
                                            }
                                        }
                                    }
                                }
                                if !inner.goto_next_sibling() {
                                    break;
                                }
                            }
                        }
                    }
                    if !cursor.goto_next_sibling() {
                        break;
                    }
                }
            }
        }
        LangId::Python => {
            // Walk for class_definition matching identifier
            fn walk_py_classes<'a>(
                node: &Node<'a>,
                source: &str,
                scope_name: &str,
                available: &mut Vec<String>,
            ) -> Option<BodyInfo> {
                let mut cursor = node.walk();
                if cursor.goto_first_child() {
                    loop {
                        let child = cursor.node();
                        if child.kind() == "class_definition" {
                            if let Some(name) = find_child_text(&child, source, &["identifier"]) {
                                available.push(name.clone());
                                if name == scope_name {
                                    if let Some(body) = find_child_by_kind(&child, "block") {
                                        let children = extract_body_children_py(&body, source);
                                        return Some((
                                            body.start_byte(),
                                            body.end_byte(),
                                            children,
                                        ));
                                    }
                                }
                            }
                        }
                        // Also handle decorated_definition wrapping class_definition
                        if child.kind() == "decorated_definition" {
                            if let Some(result) =
                                walk_py_classes(&child, source, scope_name, available)
                            {
                                return Some(result);
                            }
                        }
                        if !cursor.goto_next_sibling() {
                            break;
                        }
                    }
                }
                None
            }
            if let Some(info) = walk_py_classes(root, source, scope_name, &mut available) {
                return (Some(info), available);
            }
        }
        LangId::Rust => {
            // Walk for impl_item first (more common target for add_member),
            // then struct_item. This means `impl Config` is found before `struct Config`.
            let mut struct_match: Option<BodyInfo> = None;
            let mut cursor = root.walk();
            if cursor.goto_first_child() {
                loop {
                    let node = cursor.node();
                    if node.kind() == "impl_item" {
                        let impl_name = extract_impl_name(&node, source);
                        if let Some(ref name) = impl_name {
                            if !available.contains(name) {
                                available.push(name.clone());
                            }
                            if name == scope_name {
                                if let Some(body) = find_child_by_kind(&node, "declaration_list") {
                                    let children = extract_body_children_rs_impl(&body, source);
                                    return (
                                        Some((body.start_byte(), body.end_byte(), children)),
                                        available,
                                    );
                                }
                            }
                        }
                    }
                    if node.kind() == "struct_item" {
                        if let Some(name) = find_child_text(&node, source, &["type_identifier"]) {
                            if !available.contains(&name) {
                                available.push(name.clone());
                            }
                            if name == scope_name && struct_match.is_none() {
                                if let Some(body) =
                                    find_child_by_kind(&node, "field_declaration_list")
                                {
                                    let children = extract_body_children_rs_struct(&body, source);
                                    struct_match =
                                        Some((body.start_byte(), body.end_byte(), children));
                                }
                            }
                        }
                    }
                    if !cursor.goto_next_sibling() {
                        break;
                    }
                }
            }
            // If no impl matched but a struct did, use the struct
            if let Some(info) = struct_match {
                return (Some(info), available);
            }
        }
        LangId::Go => {
            // Walk for type_declaration → type_spec → struct_type
            let mut cursor = root.walk();
            if cursor.goto_first_child() {
                loop {
                    let node = cursor.node();
                    if node.kind() == "type_declaration" {
                        if let Some(info) =
                            find_go_struct(&node, source, scope_name, &mut available)
                        {
                            return (Some(info), available);
                        }
                    }
                    if !cursor.goto_next_sibling() {
                        break;
                    }
                }
            }
        }
        LangId::C
        | LangId::Cpp
        | LangId::Zig
        | LangId::CSharp
        | LangId::Bash
        | LangId::Html
        | LangId::Markdown => {}
    }

    (None, available)
}

/// Extract the name for a Rust impl block.
/// `impl Foo { ... }` → "Foo"
/// `impl Trait for Foo { ... }` → "Foo" (match on the target type)
fn extract_impl_name(node: &Node, source: &str) -> Option<String> {
    let mut type_names: Vec<String> = Vec::new();
    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            if child.kind() == "type_identifier" || child.kind() == "generic_type" {
                type_names.push(node_text(source, &child).to_string());
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    // For `impl Foo`, return "Foo"
    // For `impl Trait for Foo`, return "Foo" (last type name)
    type_names.last().cloned()
}

/// Find a Go struct within a type_declaration node.
fn find_go_struct(
    type_decl: &Node,
    source: &str,
    scope_name: &str,
    available: &mut Vec<String>,
) -> Option<BodyInfo> {
    let mut cursor = type_decl.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            if child.kind() == "type_spec" {
                // type_spec has name (type_identifier) and type (struct_type)
                if let Some(name_node) = find_child_by_kind(&child, "type_identifier") {
                    let name = node_text(source, &name_node).to_string();
                    available.push(name.clone());
                    if name == scope_name {
                        if let Some(struct_type) = find_child_by_kind(&child, "struct_type") {
                            if let Some(body) =
                                find_child_by_kind(&struct_type, "field_declaration_list")
                            {
                                let children = extract_body_children_go(&body, source);
                                return Some((body.start_byte(), body.end_byte(), children));
                            }
                        }
                    }
                }
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    None
}

// --- Body child extraction per language ---

fn extract_body_children_ts(body: &Node, source: &str) -> Vec<BodyChild> {
    let mut children = Vec::new();
    let mut cursor = body.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            // Skip delimiters
            if child.kind() == "{" || child.kind() == "}" || child.kind() == ";" {
                if !cursor.goto_next_sibling() {
                    break;
                }
                continue;
            }
            let name = extract_member_name_ts(&child, source);
            children.push(BodyChild {
                name,
                start_byte: child.start_byte(),
                end_byte: child.end_byte(),
            });
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    children
}

fn extract_member_name_ts(node: &Node, source: &str) -> String {
    // method_definition → name is property_identifier
    // public_field_definition → name is property_identifier
    if let Some(name_node) = node.child_by_field_name("name") {
        return node_text(source, &name_node).to_string();
    }
    // Fallback: first named child
    if node.named_child_count() > 0 {
        if let Some(child) = node.named_child(0) {
            return node_text(source, &child).to_string();
        }
    }
    String::new()
}

fn extract_body_children_py(body: &Node, source: &str) -> Vec<BodyChild> {
    let mut children = Vec::new();
    let mut cursor = body.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            let name = extract_member_name_py(&child, source);
            if !name.is_empty() {
                children.push(BodyChild {
                    name,
                    start_byte: child.start_byte(),
                    end_byte: child.end_byte(),
                });
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    children
}

fn extract_member_name_py(node: &Node, source: &str) -> String {
    match node.kind() {
        "function_definition" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                return node_text(source, &name_node).to_string();
            }
        }
        "decorated_definition" => {
            // Find the inner function_definition
            let mut cursor = node.walk();
            if cursor.goto_first_child() {
                loop {
                    let child = cursor.node();
                    if child.kind() == "function_definition" || child.kind() == "class_definition" {
                        if let Some(name_node) = child.child_by_field_name("name") {
                            return node_text(source, &name_node).to_string();
                        }
                    }
                    if !cursor.goto_next_sibling() {
                        break;
                    }
                }
            }
        }
        "expression_statement" => {
            // Assignment like `x = 1` — name is the left side
            if let Some(assign) = node.named_child(0) {
                if assign.kind() == "assignment" {
                    if let Some(left) = assign.child_by_field_name("left") {
                        return node_text(source, &left).to_string();
                    }
                }
            }
        }
        _ => {}
    }
    String::new()
}

fn extract_body_children_rs_struct(body: &Node, source: &str) -> Vec<BodyChild> {
    let mut children = Vec::new();
    let mut cursor = body.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            if child.kind() == "field_declaration" {
                let name = if let Some(name_node) = child.child_by_field_name("name") {
                    node_text(source, &name_node).to_string()
                } else {
                    String::new()
                };
                children.push(BodyChild {
                    name,
                    start_byte: child.start_byte(),
                    end_byte: child.end_byte(),
                });
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    children
}

fn extract_body_children_rs_impl(body: &Node, source: &str) -> Vec<BodyChild> {
    let mut children = Vec::new();
    let mut cursor = body.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            if child.kind() == "function_item" {
                let name = if let Some(name_node) = child.child_by_field_name("name") {
                    node_text(source, &name_node).to_string()
                } else {
                    String::new()
                };
                children.push(BodyChild {
                    name,
                    start_byte: child.start_byte(),
                    end_byte: child.end_byte(),
                });
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    children
}

fn extract_body_children_go(body: &Node, source: &str) -> Vec<BodyChild> {
    let mut children = Vec::new();
    let mut cursor = body.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            if child.kind() == "field_declaration" {
                // Go field names are field_identifier
                let name = if let Some(name_node) = find_child_by_kind(&child, "field_identifier") {
                    node_text(source, &name_node).to_string()
                } else {
                    String::new()
                };
                children.push(BodyChild {
                    name,
                    start_byte: child.start_byte(),
                    end_byte: child.end_byte(),
                });
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    children
}

// --- Helpers ---

/// Find a direct child node of a given kind.
fn find_child_by_kind<'a>(node: &Node<'a>, kind: &str) -> Option<Node<'a>> {
    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            if cursor.node().kind() == kind {
                return Some(cursor.node());
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    None
}

/// Find the text of the first child matching one of the given kinds.
fn find_child_text(node: &Node, source: &str, kinds: &[&str]) -> Option<String> {
    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            let child = cursor.node();
            if kinds.contains(&child.kind()) {
                return Some(node_text(source, &child).to_string());
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    None
}

/// Detect the indentation used by existing body children.
/// If the body is empty, return one level of the file's indent style.
fn detect_member_indent(
    source: &str,
    children: &[BodyChild],
    file_indent: &IndentStyle,
    _lang: LangId,
) -> String {
    if let Some(first_child) = children.first() {
        // Extract the leading whitespace of the first child's line
        let line_start = source[..first_child.start_byte]
            .rfind('\n')
            .map(|p| p + 1)
            .unwrap_or(0);
        let line = &source[line_start..first_child.start_byte];
        let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
        if !indent.is_empty() {
            return indent;
        }
    }
    // Empty body — use one level of file indent
    file_indent.as_str().to_string()
}

/// Resolve the byte offset for the insertion position.
fn resolve_position(
    source: &str,
    position: &str,
    body_start: usize,
    body_end: usize,
    children: &[BodyChild],
    lang: LangId,
    scope_name: &str,
    file: &str,
) -> Result<usize, AftError> {
    match position {
        "first" => Ok(resolve_first(source, body_start, lang)),
        "last" => Ok(resolve_last(source, body_end, children, lang)),
        pos if pos.starts_with("before:") => {
            let member_name = &pos["before:".len()..];
            let child = children.iter().find(|c| c.name == member_name);
            match child {
                Some(c) => {
                    // Insert before this child's line
                    let line_start = source[..c.start_byte]
                        .rfind('\n')
                        .map(|p| p + 1)
                        .unwrap_or(0);
                    Ok(line_start)
                }
                None => Err(AftError::MemberNotFound {
                    member: member_name.to_string(),
                    scope: scope_name.to_string(),
                    file: file.to_string(),
                }),
            }
        }
        pos if pos.starts_with("after:") => {
            let member_name = &pos["after:".len()..];
            let child = children.iter().find(|c| c.name == member_name);
            match child {
                Some(c) => {
                    // Insert after this child's end, on a new line
                    // Find the end of the line containing the child's end
                    let line_end = source[c.end_byte..]
                        .find('\n')
                        .map(|p| c.end_byte + p + 1)
                        .unwrap_or(c.end_byte);
                    Ok(line_end)
                }
                None => Err(AftError::MemberNotFound {
                    member: member_name.to_string(),
                    scope: scope_name.to_string(),
                    file: file.to_string(),
                }),
            }
        }
        _ => Err(AftError::InvalidRequest {
            message: format!(
                "add_member: invalid position '{}', expected first|last|before:name|after:name",
                position
            ),
        }),
    }
}

/// Resolve "first" position: right after the opening delimiter.
fn resolve_first(source: &str, body_start: usize, lang: LangId) -> usize {
    match lang {
        LangId::Python => {
            // Python: body starts right after the colon + newline
            // body_start is the start of the block node, which is the first
            // content line. We insert at body_start.
            body_start
        }
        _ => {
            // Brace-delimited: find the opening `{` and insert after the newline following it
            if let Some(brace_pos) = source[body_start..].find('{') {
                let after_brace = body_start + brace_pos + 1;
                // Find the newline after the brace
                if let Some(nl_pos) = source[after_brace..].find('\n') {
                    after_brace + nl_pos + 1
                } else {
                    after_brace
                }
            } else {
                body_start
            }
        }
    }
}

/// Resolve "last" position: before the closing delimiter.
fn resolve_last(source: &str, body_end: usize, children: &[BodyChild], lang: LangId) -> usize {
    match lang {
        LangId::Python => {
            // Python: insert after the last child's line
            if let Some(last) = children.last() {
                // Find end of the last child's line
                source[last.end_byte..]
                    .find('\n')
                    .map(|p| last.end_byte + p + 1)
                    .unwrap_or(last.end_byte)
            } else {
                // Empty body — insert at body_start
                body_start_for_empty_py(source, body_end)
            }
        }
        _ => {
            // Brace-delimited: insert before the closing `}`
            // Find the `}` searching backward from body_end
            let closing = source[..body_end].rfind('}').unwrap_or(body_end);
            // Insert at the start of the line containing `}`
            let line_start = source[..closing]
                .rfind('\n')
                .map(|p| p + 1)
                .unwrap_or(closing);
            line_start
        }
    }
}

/// For an empty Python class body, find the insertion point.
fn body_start_for_empty_py(_source: &str, body_end: usize) -> usize {
    // The body_end is the end of the block. For empty Python blocks
    // (which have `pass` or nothing), we insert at body start.
    // Walk backward to find the start of the block.
    body_end
}

/// Indent the provided code to match the target indentation.
fn indent_code(
    code: &str,
    member_indent: &str,
    _source: &str,
    _insert_offset: usize,
    _position: &str,
    _body_start: usize,
    _body_end: usize,
    children: &[BodyChild],
    lang: LangId,
) -> String {
    let mut result = String::new();
    let lines: Vec<&str> = code.lines().collect();
    let is_empty = children.is_empty();

    // For empty brace-delimited containers at "last" position,
    // we're inserting at the line of `}` — no special leading newline needed.
    let _needs_trailing_newline = is_empty && !matches!(lang, LangId::Python);

    for line in &lines {
        if line.trim().is_empty() {
            result.push('\n');
        } else {
            result.push_str(member_indent);
            result.push_str(line.trim_start());
            result.push('\n');
        }
    }

    // Ensure the code doesn't end with a double newline if inserting at "last"
    // but ensure there's always a trailing newline
    if result.is_empty() {
        result.push('\n');
    }

    result
}