splice 2.6.1

Span-safe refactoring kernel for 7 languages with Magellan code graph integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
# LLM Tool Ecosystem Alignment

**Created:** 2026-01-22
**Purpose:** Align JSON formats and data structures across the LLM-native toolset (Magellan, Splice, llmtransform, llmsearch, llmastsearch, llmfilewrite) to create a unified feedback loop where tools provide LSP/AST information to prevent errors and reduce token waste.

---

## Table of Contents

1. [Executive Summary]#executive-summary
2. [Tool Inventory]#tool-inventory
3. [Current State Analysis]#current-state-analysis
4. [Common Patterns]#common-patterns
5. [Key Differences]#key-differences
6. [Alignment Recommendations]#alignment-recommendations
7. [Proposed Standard Schema]#proposed-standard-schema
8. [Implementation Roadmap]#implementation-roadmap

---

## Executive Summary

### The Problem

The LLM tool ecosystem currently has inconsistent JSON output formats:
- Each tool uses different field names for the same concepts
- Coordinate representations vary (line_start vs start_line vs row)
- Error handling structures are not compatible
- Missing standardized metadata across tools
- This forces LLMs to re-read files and waste tokens on format translation

### The Vision

Create a unified feedback loop where:
1. Tools provide LSP/AST feedback in a **standard schema**
2. LLMs can consume output from any tool without format-specific parsing
3. Spans are consistent across all tools (byte + line/col)
4. Errors are structured and actionable
5. Execution IDs enable traceability across the entire workflow

**Result:** The LLM never edits or reads files blindly, never commits errors, and doesn't waste tokens re-reading files.

### Tools in Scope

| Tool | Purpose | Location | Status |
|------|---------|----------|--------|
| **Magellan** | Code indexing and symbol query | `/home/feanor/Projects/magellan` | Production |
| **Splice** | Span-safe refactoring with validation | `/home/feanor/Projects/splice` | Production |
| **llmtransform** | Span-safe text mutation | `/home/feanor/Projects/llmtransform` | Production |
| **llmsearch** | Structured text search | `/home/feanor/Projects/llmsearch` | Production |
| **llmastsearch** | AST-based code search (tree-sitter) | `/home/feanor/Projects/llmastsearch` | Production |
| **llmfilewrite** | Code creation with LSP validation | `/home/feanor/Projects/llmfilewrite` | Design Phase |

---

## Tool Inventory

### 1. Magellan (Code Indexing)

**Location:** `/home/feanor/Projects/magellan/src/output/command.rs`

**Key Structures:**

```rust
// Wrapper for all JSON responses
pub struct JsonResponse<T> {
    pub schema_version: String,      // "1.0"
    pub execution_id: String,         // UUID
    pub data: T,                      // Generic data payload
    pub partial: Option<bool>,        // Partial results indicator
}

// Span representation
pub struct Span {
    pub span_id: String,              // UUID
    pub file_path: String,
    pub byte_start: usize,
    pub byte_end: usize,
    pub start_line: usize,            // 1-indexed
    pub start_col: usize,             // 0-indexed
    pub end_line: usize,              // 1-indexed
    pub end_col: usize,               // 0-indexed
}

// Symbol match result
pub struct SymbolMatch {
    pub match_id: String,             // UUID
    pub span: Span,
    pub name: String,
    pub kind: String,                 // "function", "class", etc.
    pub parent: Option<String>,       // Parent symbol name
    pub symbol_id: Option<String>,    // Stable symbol identifier
}

// Reference match result
pub struct ReferenceMatch {
    pub match_id: String,
    pub span: Span,
    pub reference_type: String,
    def_symbol_id: String,
}
```

**Output Format:**
```json
{
  "schema_version": "1.0",
  "execution_id": "uuid-v4",
  "data": {
    "matches": [...]
  },
  "partial": false
}
```

---

### 2. Splice (Refactoring)

**Location:** `/home/feanor/Projects/splice/src/output.rs`

**Key Structures:**

```rust
// Top-level operation result
pub struct OperationResult {
    pub version: String,              // "2.0"
    pub operation_id: String,         // UUID
    pub operation_type: String,       // "patch", "delete", "rename"
    pub status: String,               // "success", "failure"
    pub message: String,
    pub timestamp: String,            // ISO 8601
    pub workspace: Option<String>,
    pub result: Option<OperationData>,
    pub error: Option<ErrorDetails>,
}

// Span result with checksums
pub struct SpanResult {
    pub file_path: String,
    pub byte_start: usize,
    pub byte_end: usize,
    pub line_start: usize,            // 1-indexed
    pub line_end: usize,              // 1-indexed
    pub col_start: usize,             // 0-indexed
    pub col_end: usize,               // 0-indexed
    pub span_id: String,              // UUID
    pub match_id: Option<String>,     // UUID
    pub content_checksum: String,     // SHA-256 of content
    pub surrounding_checksum: String, // SHA-256 with context
}

// Structured error payload
pub struct DiagnosticPayload {
    pub tool: String,                 // "splice"
    pub level: String,                // "error", "warning", "note"
    pub message: String,
    pub file: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    pub code: Option<String>,         // SPLICE_E001, etc.
    pub note: Option<String>,
    pub remediation: Option<String>,  // How to fix
}
```

**Output Format:**
```json
{
  "version": "2.0",
  "operation_id": "uuid-v4",
  "operation_type": "patch",
  "status": "success",
  "message": "...",
  "timestamp": "2026-01-22T10:00:00Z",
  "result": {
    "spans": [...],
    "checksums": {...}
  }
}
```

---

### 3. llmtransform (Text Mutation)

**Location:** `/home/feanor/Projects/llmtransform/llm-transform/src/json.rs`

**Key Structures:**

```rust
// Edit request (input)
pub struct EditRequest {
    pub execution_id: String,
    pub file_path: String,
    pub expected_checksum: String,    // SHA-256
    pub edits: Vec<EditJson>,
}

// Individual edit
pub struct EditJson {
    pub byte_start: usize,
    pub byte_end: usize,
    pub new_content: String,
}

// Edit response (output)
pub struct EditResponse {
    pub execution_id: String,         // Same as request
    pub success: bool,
    pub final_checksum: String,       // SHA-256 after edits
    pub total_byte_shift: i64,        // For adjusting subsequent edits
    pub applied_count: usize,
    pub skipped_count: usize,
    pub error_count: usize,
    pub edits: Vec<PerEditResultJson>,
    pub error: Option<String>,
}

// Per-edit result
pub struct PerEditResultJson {
    pub byte_start: usize,
    pub byte_end: usize,
    pub status: String,               // "applied", "skipped", "error"
    pub error: Option<String>,
}
```

**Output Format:**
```json
{
  "execution_id": "uuid-v4",
  "success": true,
  "final_checksum": "sha256-hash",
  "total_byte_shift": 12,
  "applied_count": 2,
  "skipped_count": 0,
  "error_count": 0,
  "edits": [...]
}
```

---

### 4. llmsearch (Text Search)

**Location:** `/home/feanor/Projects/llmsearch/src/main.rs`

**Key Structures:**

```rust
// Single match
struct Match {
    match_id: String,                // UUID
    file: String,                    // NOT "file_path"
    byte_start: usize,
    byte_end: usize,
    matched_text: String,
    line_number: usize,              // NOT "line_start"
    column_number: usize,            // NOT "col_start"
    context_before: String,
    context_after: String,
}

// Search output
struct SearchOutput {
    execution_id: String,            // UUID
    pattern: String,
    matches: Vec<Match>,
    match_count: usize,
}
```

**Output Format:**
```json
{
  "execution_id": "uuid-v4",
  "pattern": "search_pattern",
  "matches": [...],
  "match_count": 5
}
```

---

### 5. llmastsearch (AST Query)

**Locations:**
- `/home/feanor/Projects/llmastsearch/src/query/result.rs`
- `/home/feanor/Projects/llmastsearch/src/query/ast.rs`
- `/home/feanor/Projects/llmastsearch/src/query/position.rs`

**Key Structures:**

```rust
// Query result wrapper
pub struct QueryResult {
    pub execution_id: Uuid,           // UUID type (not String)
    pub file_path: PathBuf,           // PathBuf type (not String)
    pub language: Language,           // Enum: Rust, Python, C, etc.
    pub query: String,
    pub matches: Vec<Match>,
    pub match_count: usize,
}

// Single match
pub struct Match {
    pub pattern_index: u32,
    pub captures: Vec<Capture>,
    pub byte_start: usize,
    pub byte_end: usize,
    pub start: Position,              // Custom Position struct
    pub end: Position,
}

// Capture (named pattern match)
pub struct Capture {
    pub index: u32,
    pub name: String,
    pub byte_start: usize,
    pub byte_end: usize,
}

// Position (line:column)
pub struct Position {
    pub row: usize,                   // 1-indexed line (NOT "line")
    pub column: usize,                // 0-indexed column in line
}
```

**Output Format:**
```json
{
  "execution_id": "uuid-v4",
  "file_path": "src/main.rs",
  "language": "Rust",
  "query": "(function_item) @func",
  "matches": [
    {
      "pattern_index": 0,
      "captures": [...],
      "byte_start": 10,
      "byte_end": 50,
      "start": {"row": 2, "column": 0},
      "end": {"row": 5, "column": 1}
    }
  ],
  "match_count": 1
}
```

---

### 6. llmfilewrite (Code Creation)

**Location:** `/home/feanor/Projects/llmfilewrite/docs/llmfilewrite.md`

**Planned Structures:**

```rust
// Write request (proposed)
pub struct WriteRequest {
    pub path: String,
    pub language: String,             // or "auto"
    pub content: String,
    pub overwrite: bool,
}

// LSP diagnostic (proposed)
pub struct LspDiagnostic {
    pub severity: String,             // "error", "warning"
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub message: String,
    pub code: String,                 // Error code from LSP
}

// Write response (proposed)
pub struct WriteResponse {
    pub execution_id: String,
    pub path: String,
    pub language: String,
    pub lsp_used: String,             // LSP server name
    pub diagnostics: Vec<LspDiagnostic>,
    pub status: String,               // "approved", "rejected"
    pub magellan_hints: Option<Vec<MagellanHint>>,
}
```

**Planned Output Format:**
```json
{
  "execution_id": "uuid-v4",
  "path": "src/main.rs",
  "language": "Rust",
  "lsp_used": "rust-analyzer",
  "diagnostics": [],
  "status": "approved"
}
```

---

## Current State Analysis

### Coordinate Field Names

| Tool | Line Start | Line End | Col Start | Col End | Byte Start | Byte End |
|------|-----------|---------|-----------|---------|------------|----------|
| Magellan | `start_line` | `end_line` | `start_col` | `end_col` | `byte_start` | `byte_end` |
| Splice | `line_start` | `line_end` | `col_start` | `col_end` | `byte_start` | `byte_end` |
| llmtransform | N/A | N/A | N/A | N/A | `byte_start` | `byte_end` |
| llmsearch | `line_number` | N/A | `column_number` | N/A | `byte_start` | `byte_end` |
| llmastsearch | `start.row` | `end.row` | `start.column` | `end.column` | `byte_start` | `byte_end` |

**Issue:** 5 different conventions for the same concept.

### Path Field Names

| Tool | Field Name | Type |
|------|-----------|------|
| Magellan | `file_path` | String |
| Splice | `file_path` | String |
| llmtransform | `file_path` | String |
| llmsearch | `file` | String |
| llmastsearch | `file_path` | PathBuf |

**Issue:** Inconsistent naming (`file` vs `file_path`) and types (String vs PathBuf).

### Execution ID

| Tool | Field Name | Type |
|------|-----------|------|
| Magellan | `execution_id` | String |
| Splice | `operation_id` | String |
| llmtransform | `execution_id` | String |
| llmsearch | `execution_id` | String |
| llmastsearch | `execution_id` | Uuid |

**Issue:** Splice uses `operation_id` instead of `execution_id`. llmastsearch uses Uuid type instead of String.

### Match/Span IDs

| Tool | ID Field | ID Type |
|------|----------|---------|
| Magellan | `match_id`, `span_id` | String (UUID) |
| Splice | `span_id`, `match_id` | String (UUID) |
| llmsearch | `match_id` | String (UUID) |
| llmastsearch | None | N/A |

**Issue:** llmastsearch lacks stable IDs for matches.

### Error Handling

| Tool | Error Structure | Severity Levels |
|------|----------------|-----------------|
| Magellan | Not documented | Unknown |
| Splice | `DiagnosticPayload` | error/warning/note |
| llmtransform | `error: Option<String>` | Boolean (success/error) |
| llmsearch | Not documented | Unknown |
| llmastsearch | `QueryError` enum | InvalidQuery/ParseError |

**Issue:** Only Splice has structured, actionable error diagnostics.

### Metadata

| Tool | Schema Version | Timestamp | Language |
|------|----------------|-----------|----------|
| Magellan | Yes (`schema_version`) | No | No |
| Splice | Yes (`version`) | Yes (`timestamp`) | No |
| llmtransform | No | No | No |
| llmsearch | No | No | No |
| llmastsearch | No | No | Yes (`language`) |

**Issue:** Inconsistent metadata across tools.

---

## Common Patterns

### 1. UUID Execution IDs

All tools (except Splice's naming) use `execution_id` with UUID v4 format.
**Recommendation:** Standardize on `execution_id: String` (UUID v4).

### 2. Byte Offset Coordinates

All tools use `byte_start` and `byte_end` for UTF-8 byte offsets.
**Recommendation:** Continue this pattern.

### 3. Half-Open Ranges

All tools use half-open ranges `[start, end)` consistent with Rust.
**Recommendation:** Document this explicitly.

### 4. Line/Column Conventions

Most tools use:
- **Lines:** 1-indexed (for human-friendly display)
- **Columns:** 0-indexed (byte offset within line)

**Recommendation:** Standardize and document.

### 5. JSON Serialization

All tools use `serde` for JSON serialization with explicit `Serialize` derives.
**Recommendation:** Continue this pattern.

---

## Key Differences

### 1. Position Representation

**Three incompatible patterns:**

```rust
// Pattern 1: Magellan, Splice (flat fields)
pub struct Span {
    pub start_line: usize,
    pub end_line: usize,
    pub start_col: usize,
    pub end_col: usize,
}

// Pattern 2: llmsearch (single line)
struct Match {
    pub line_number: usize,
    pub column_number: usize,
}

// Pattern 3: llmastsearch (nested Position)
pub struct Match {
    pub start: Position,  // { row, column }
    pub end: Position,
}
```

**Alignment:** Adopt Pattern 1 (flat fields) for maximum compatibility.

### 2. Nested Data vs Wrapper Objects

**Magellan:**
```json
{
  "schema_version": "1.0",
  "execution_id": "...",
  "data": { "matches": [...] }  // Nested
}
```

**llmsearch:**
```json
{
  "execution_id": "...",
  "matches": [...]  // Flat
}
```

**Alignment:** Use flat structure for simplicity (llmsearch pattern).

### 3. Error Depth

**Splice:** Rich diagnostic payload with remediation hints
**Others:** Simple error string or enum

**Alignment:** All tools should adopt Splice's `DiagnosticPayload` pattern.

---

## Alignment Recommendations

### Priority 1: Coordinate Standardization (High Impact)

**Standard field names:**
```rust
pub struct SpanCoordinates {
    // Byte offsets (UTF-8)
    pub byte_start: usize,
    pub byte_end: usize,

    // Line numbers (1-indexed)
    pub line_start: usize,
    pub line_end: usize,

    // Column numbers (0-indexed, byte offset in line)
    pub col_start: usize,
    pub col_end: usize,
}
```

**Migration required:**
- Magellan: Rename `start_line``line_start`, `start_col``col_start`
- llmsearch: Rename `line_number``line_start`, `column_number``col_start`
- llmastsearch: Flatten `start.row``line_start`, `start.column``col_start`

### Priority 2: Path Field Standardization

**Standard:** `file_path: String` (not `file`, not `PathBuf`)

**Migration required:**
- llmsearch: `file``file_path`
- llmastsearch: `PathBuf``String`

### Priority 3: Execution ID Standardization

**Standard:** `execution_id: String` (UUID v4 format)

**Migration required:**
- Splice: `operation_id``execution_id`
- llmastsearch: `Uuid` type → `String`

### Priority 4: Match ID Standardization

All match results should have stable IDs:

```rust
pub struct IdentifiableMatch {
    pub match_id: String,  // UUID v4
    // ... other fields
}
```

**Migration required:**
- llmastsearch: Add `match_id` to `Match` struct

### Priority 5: Error Structure Alignment

Adopt Splice's `DiagnosticPayload` pattern across all tools:

```rust
pub struct DiagnosticPayload {
    pub tool: String,              // Tool name
    pub level: String,             // "error" | "warning" | "note"
    pub message: String,           // Primary message
    pub file: Option<String>,      // File path
    pub line: Option<usize>,       // 1-indexed
    pub column: Option<usize>,     // 0-indexed
    pub code: Option<String>,      // Stable error code
    pub note: Option<String>,      // Additional context
    pub remediation: Option<String>, // How to fix
}
```

### Priority 6: Metadata Standardization

All tools should include:

```rust
pub struct ResponseMetadata {
    pub schema_version: String,     // "1.0"
    pub execution_id: String,       // UUID v4
    pub timestamp: Option<String>,  // ISO 8601
    pub language: Option<String>,   // For code tools
}
```

---

## Proposed Standard Schema

### Unified Span Type

```rust
/// Standard span representation for all LLM tools.
///
/// Coordinate conventions:
/// - byte_start, byte_end: UTF-8 byte offsets, half-open range [start, end)
/// - line_start, line_end: 1-indexed line numbers
/// - col_start, col_end: 0-indexed byte offsets within each line
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StandardSpan {
    /// Stable identifier for this span (UUID v4)
    pub span_id: String,

    /// File path (relative to workspace root when possible)
    pub file_path: String,

    /// UTF-8 byte offset of span start (inclusive)
    pub byte_start: usize,

    /// UTF-8 byte offset of span end (exclusive)
    pub byte_end: usize,

    /// Line number where span starts (1-indexed)
    pub line_start: usize,

    /// Line number where span ends (1-indexed)
    pub line_end: usize,

    /// Column number at span start (0-indexed, byte offset in line)
    pub col_start: usize,

    /// Column number at span end (0-indexed, byte offset in line)
    pub col_end: usize,
}
```

### Unified Match Type

```rust
/// Standard match result for search/query tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandardMatch {
    /// Stable identifier for this match (UUID v4)
    pub match_id: String,

    /// Span information
    pub span: StandardSpan,

    /// Matched text content (for search) or capture name (for AST)
    pub content: String,

    /// Additional context (tool-specific)
    pub context: Option<MatchContext>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatchContext {
    /// Lines before the match
    pub before: Option<Vec<String>>,

    /// Lines after the match
    pub after: Option<Vec<String>>,

    /// Symbol kind (for AST queries: "function", "class", etc.)
    pub kind: Option<String>,

    /// Parent symbol name (for AST queries)
    pub parent: Option<String>,
}
```

### Unified Response Wrapper

```rust
/// Standard response wrapper for all LLM tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandardResponse<T> {
    /// Schema version (for backward compatibility)
    pub schema_version: String,

    /// Execution identifier (UUID v4)
    pub execution_id: String,

    /// Tool name that generated this response
    pub tool: String,

    /// Response timestamp (ISO 8601)
    pub timestamp: String,

    /// Response status
    pub status: ResponseStatus,

    /// Primary response data
    pub data: T,

    /// Diagnostics (errors, warnings, notes)
    pub diagnostics: Vec<DiagnosticPayload>,

    /// Partial results indicator (for streaming)
    pub partial: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ResponseStatus {
    #[serde(rename = "success")]
    Success,

    #[serde(rename = "failure")]
    Failure,

    #[serde(rename = "partial")]
    Partial,
}
```

### Unified Diagnostic

```rust
/// Standard diagnostic payload for all tools.
///
/// Used for errors, warnings, and informational notes.
/// Designed to be both human-readable and LLM-parsable.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticPayload {
    /// Tool that generated this diagnostic
    pub tool: String,

    /// Severity level
    pub level: DiagnosticLevel,

    /// Primary message
    pub message: String,

    /// File path (if applicable)
    pub file: Option<String>,

    /// Line number (1-indexed, if applicable)
    pub line: Option<usize>,

    /// Column number (0-indexed, if applicable)
    pub column: Option<usize>,

    /// Stable error code (e.g., "SPLICE_E001", "E0382")
    pub code: Option<String>,

    /// Additional context or notes
    pub note: Option<String>,

    /// Suggested remediation or fix
    pub remediation: Option<String>,

    /// Related span (if applicable)
    pub span: Option<StandardSpan>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DiagnosticLevel {
    #[serde(rename = "error")]
    Error,

    #[serde(rename = "warning")]
    Warning,

    #[serde(rename = "note")]
    Note,
}
```

---

## Implementation Roadmap

### Phase 1: Create Shared Types Crate (Week 1)

**Location:** New crate at `/home/feanor/Projects/llm-types` (or similar)

**Deliverables:**
1. `llm-types` crate with standard types
2. Published to local git registry or crates.io
3. Documentation of conventions

**Files:**
```
llm-types/
├── Cargo.toml
├── src/
│   ├── lib.rs
│   ├── span.rs
│   ├── match.rs
│   ├── response.rs
│   └── diagnostic.rs
└── README.md
```

### Phase 2: Migrate Tools (Weeks 2-3)

**Order:**
1. **llmsearch** (simplest, good starting point)
2. **llmastsearch** (medium complexity)
3. **llmtransform** (medium complexity)
4. **Magellan** (higher complexity, more consumers)
5. **Splice** (highest complexity, critical path)
6. **llmfilewrite** (new, implement with standard from start)

**Migration per tool:**
1. Add `llm-types` dependency
2. Update structs to use standard types
3. Add compatibility layer for old output format (deprecation period)
4. Update tests
5. Update documentation

### Phase 3: Validation & Testing (Week 4)

1. Cross-tool integration tests
2. LLM consumption tests (verify Claude/other LLMs can consume)
3. Performance regression tests
4. Documentation review

### Phase 4: Deprecate Old Formats (Week 6+)

1. Announce deprecation timeline
2. Add migration warnings to old output formats
3. Remove compatibility layers after deprecation period

---

## Implementation Details by Tool

### llmsearch

**Changes:**
```rust
// Before
struct Match {
    match_id: String,
    file: String,
    byte_start: usize,
    byte_end: usize,
    line_number: usize,
    column_number: usize,
    // ...
}

// After
struct Match {
    match_id: String,
    span: StandardSpan,
    matched_text: String,
    // ...
}
```

### llmastsearch

**Changes:**
```rust
// Before
pub struct Match {
    pub pattern_index: u32,
    pub captures: Vec<Capture>,
    pub byte_start: usize,
    pub byte_end: usize,
    pub start: Position,
    pub end: Position,
}

// After
pub struct Match {
    pub match_id: String,  // NEW
    pub pattern_index: u32,
    pub captures: Vec<Capture>,
    pub span: StandardSpan,  // REPLACES byte_start, byte_end, start, end
}
```

**Position type:** Keep for internal use, but convert to `StandardSpan` for JSON output.

### Magellan

**Changes:**
```rust
// Before
pub struct Span {
    pub span_id: String,
    pub file_path: String,
    pub byte_start: usize,
    pub byte_end: usize,
    pub start_line: usize,  // RENAME
    pub start_col: usize,   // RENAME
    pub end_line: usize,    // RENAME
    pub end_col: usize,     // RENAME
}

// After
pub struct Span {
    pub span_id: String,
    pub file_path: String,
    pub byte_start: usize,
    pub byte_end: usize,
    pub line_start: usize,  // RENAMED
    pub line_end: usize,    // RENAMED
    pub col_start: usize,   // RENAMED
    pub col_end: usize,     // RENAMED
}
```

### Splice

**Changes:**
```rust
// Before
pub struct OperationResult {
    pub version: String,
    pub operation_id: String,  // RENAME
    // ...
}

// After
pub struct OperationResult {
    pub schema_version: String,  // RENAME for consistency
    pub execution_id: String,    // RENAMED
    // ...
}
```

Add `DiagnosticPayload` export for use by other tools.

### llmfilewrite

**Implementation:** Use standard types from day one.
```rust
use llm_types::{StandardResponse, DiagnosticPayload, StandardSpan};

pub struct WriteResponse {
    pub execution_id: String,
    pub path: String,
    pub language: String,
    pub lsp_used: String,
    pub diagnostics: Vec<DiagnosticPayload>,  // Standard type
    pub status: WriteStatus,
}
```

---

## Success Criteria

### Technical

- [ ] All tools use `execution_id: String` (UUID v4)
- [ ] All tools use `file_path: String`
- [ ] All tools use `line_start`, `line_end`, `col_start`, `col_end`
- [ ] All tools use `byte_start`, `byte_end`
- [ ] All tools include `schema_version` in responses
- [ ] All tools use `DiagnosticPayload` for errors
- [ ] All matches have stable `match_id` (UUID v4)

### LLM Experience

- [ ] LLM can consume output from any tool without format-specific parsing
- [ ] LLM can correlate matches across tools (e.g., Magellan symbol → llmsearch result)
- [ ] LLM gets actionable error messages with remediation hints
- [ ] LLM doesn't need to re-read files (spans are consistent and accurate)
- [ ] Token waste is minimized (no format translation)

### Developer Experience

- [ ] Shared types crate is easy to include
- [ ] Documentation is clear and examples are provided
- [ ] Breaking changes are minimized via compatibility layers
- [ ] Migration path is clear for existing consumers

---

## Open Questions

1. **Shared crate location:** Should we create a separate repo or use a workspace?
   - **Recommendation:** Separate repo with git dependency for stability

2. **Deprecation timeline:** How long to maintain compatibility layers?
   - **Recommendation:** 3 months for major version bump

3. **Versioning strategy:** How to coordinate versions across tools?
   - **Recommendation:** Semantic versioning with coordinated releases

4. **Error code namespace:** How to avoid collisions between tools?
   - **Recommendation:** Prefix with tool name: `SPLICE_E001`, `MAGELLAN_E001`

---

## Appendix: Coordinate Semantics

### Half-Open Ranges

All tools use half-open ranges `[start, end)`:

```
Text: "hello world"
      ^     ^
      0     5

byte_start = 0
byte_end = 5
Content = "hello" (does NOT include byte at offset 5)
```

This is consistent with Rust's `Range<usize>` and slice indexing.

### UTF-8 Safety

Byte offsets are UTF-8 byte offsets, not character counts.

For converting between bytes and characters, use:
```rust
let text = "Hello 世界";  // 12 bytes, 8 characters
let byte_start = 6;       // Start of "世"
let char_start = text[..byte_start].chars().count();  // 2
```

### Line/Column Calculation

Lines are 1-indexed (for human-friendly display).
Columns are 0-indexed (byte offset within the line).

```
Line 1: "hello\n"   column 0-5
Line 2: "world\n"   column 0-5
```

When `byte_start = 6` (start of "world"):
- `line_start = 2`
- `col_start = 0`

---

*Document created: 2026-01-22*
*Last updated: 2026-01-22*
*Status: Ready for review and implementation*