xonecas.io
62159
Sy

symb / commit 9422835

fix: simpler api for edit tool

xonecas2026-02-15 942283592d91641c07c1f490f151867f714be907 parent 8563662

5 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

internal/hashline/hashline.go+18−0
@@ -10,6 +10,7 @@ import (
1010 "crypto/sha256"
1111 "encoding/hex"
1212 "fmt"
13+ "strconv"
1314 "strings"
1415 )
1516
@@ -115,3 +116,20 @@ func ValidateRange(start, end Anchor, lines []string) error {
115116 }
116117 return nil
117118 }
119+
120+// ParseAnchor parses a "line:hash" string (e.g. "5:ab") into an Anchor.
121+func ParseAnchor(s string) (Anchor, error) {
122+ parts := strings.SplitN(s, ":", 2)
123+ if len(parts) != 2 {
124+ return Anchor{}, fmt.Errorf("invalid anchor %q: expected line:hash", s)
125+ }
126+ n, err := strconv.Atoi(parts[0])
127+ if err != nil {
128+ return Anchor{}, fmt.Errorf("invalid anchor %q: bad line number", s)
129+ }
130+ h := parts[1]
131+ if len(h) != HashLen {
132+ return Anchor{}, fmt.Errorf("invalid anchor %q: hash must be %d hex chars", s, HashLen)
133+ }
134+ return Anchor{Num: n, Hash: h}, nil
135+}
internal/hashline/hashline_test.go+17−0
@@ -172,3 +172,20 @@ func TestRoundTrip(t *testing.T) {
172172 }
173173 }
174174 }
175+
176+func TestParseAnchor(t *testing.T) {
177+ a, err := ParseAnchor("5:ab")
178+ if err != nil {
179+ t.Fatal(err)
180+ }
181+ if a.Num != 5 || a.Hash != "ab" {
182+ t.Errorf("got %+v", a)
183+ }
184+
185+ // errors
186+ for _, bad := range []string{"", "5", ":ab", "ab:5", "5:abc", "5:a"} {
187+ if _, err := ParseAnchor(bad); err == nil {
188+ t.Errorf("expected error for %q", bad)
189+ }
190+ }
191+}
internal/llm/prompts/base.md+6−6
@@ -95,26 +95,26 @@ Use this for multi-step tasks (3+ steps) to track goals and progress. Rewrite it
9595 ### `Edit` — Modify files using hash anchors
9696 **Prerequisite: Read the file first.** The hashes from Read output are your edit anchors.
9797
98-One operation per call. After each edit, you get back the updated file with fresh hashes.
98+One operation per call. Anchors use `"line:hash"` strings matching the Read output format. After each edit, you get back the updated file with fresh hashes.
9999
100100 **Replace** lines 5-7 with new content:
101101 ```json
102-{"file": "f.go", "replace": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}, "content": "func main() {\n\tfmt.Println(\"world\")\n}"}}
102+{"file": "f.go", "operation": "replace", "start": "5:9f", "end": "7:d4", "content": "func main() {\n\tfmt.Println(\"world\")\n}"}
103103 ```
104104
105105 **Insert** after line 3:
106106 ```json
107-{"file": "f.go", "insert": {"after": {"line": 3, "hash": "b2"}, "content": "import \"os\""}}
107+{"file": "f.go", "operation": "insert", "after": "3:b2", "content": "import \"os\""}
108108 ```
109109
110110 **Delete** lines 5-7:
111111 ```json
112-{"file": "f.go", "delete": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}}}
112+{"file": "f.go", "operation": "delete", "start": "5:9f", "end": "7:d4"}
113113 ```
114114
115-**Create** a new file (fails if it exists). Note: `create` is an object with a `content` key, not a bare string:
115+**Create** a new file (fails if it exists):
116116 ```json
117-{"file": "new.go", "create": {"content": "package main\n"}}
117+{"file": "new.go", "operation": "create", "content": "package main\n"}
118118 ```
119119
120120 **Critical rules:**
internal/mcptools/edit.go+72−151
@@ -29,94 +29,36 @@ type editRegion struct {
2929 end int // last affected line
3030 }
3131
32-// EditArgs represents arguments for the Edit tool.
33-// Exactly one of the operation fields (Replace, Insert, Delete) must be set.
32+// EditArgs represents arguments for the Edit tool (flat schema).
3433 type EditArgs struct {
35- File string `json:"file"`
36- Replace *ReplaceOp `json:"replace,omitempty"`
37- Insert *InsertOp `json:"insert,omitempty"`
38- Delete *DeleteOp `json:"delete,omitempty"`
39- Create *CreateOp `json:"create,omitempty"`
34+ File string `json:"file"`
35+ Operation string `json:"operation"`
36+ Start string `json:"start,omitempty"` // "line:hash" anchor
37+ End string `json:"end,omitempty"` // "line:hash" anchor
38+ After string `json:"after,omitempty"` // "line:hash" anchor (insert)
39+ Content string `json:"content,omitempty"` // text content
4040 }
4141
42-// ReplaceOp replaces lines between start and end (inclusive) with new content.
43-type ReplaceOp struct {
44- Start hashline.Anchor `json:"start"` // anchor for first line to replace
45- End hashline.Anchor `json:"end"` // anchor for last line to replace
46- Content string `json:"content"` // replacement text (may be multiple lines)
47-}
48-
49-// InsertOp inserts new lines after the anchored line.
50-type InsertOp struct {
51- After hashline.Anchor `json:"after"` // anchor for the line to insert after
52- Content string `json:"content"` // text to insert (may be multiple lines)
53-}
54-
55-// DeleteOp deletes lines between start and end (inclusive).
56-type DeleteOp struct {
57- Start hashline.Anchor `json:"start"` // anchor for first line to delete
58- End hashline.Anchor `json:"end"` // anchor for last line to delete
59-}
60-
61-// CreateOp creates a new file with the given content.
62-type CreateOp struct {
63- Content string `json:"content"` // full file content
64-}
65-
66-// anchor is the JSON schema fragment for a hashline anchor object.
67-const anchorSchema = `{"type": "object", "properties": {"line": {"type": "integer", "description": "1-indexed line number"}, "hash": {"type": "string", "description": "2-char hex hash from Read output"}}, "required": ["line", "hash"]}`
68-
6942 // NewEditTool creates the Edit tool definition.
7043 func NewEditTool() mcp.Tool {
7144 return mcp.Tool{
7245 Name: "Edit",
7346 Description: `Edit a file using hash-anchored operations. You MUST Read the file first to get line hashes.
74-Each line from Read is tagged as "linenum:hash|content". Use the line number and hash as anchors.
47+Each line from Read is tagged as "linenum:hash|content". Use "line:hash" strings as anchors.
7548 Exactly one operation per call: replace, insert, delete, or create.
7649 If a hash does not match, the file changed since you read it — re-Read and retry.
7750 After each edit you receive fresh hashes — use those for subsequent edits, not the old ones.`,
7851 InputSchema: json.RawMessage(`{
7952 "type": "object",
8053 "properties": {
81- "file": {"type": "string", "description": "Path to the file to edit"},
82- "replace": {
83- "type": "object",
84- "description": "Replace lines from start to end (inclusive) with new content",
85- "properties": {
86- "start": ` + anchorSchema + `,
87- "end": ` + anchorSchema + `,
88- "content": {"type": "string", "description": "Replacement text (may be multiple lines)"}
89- },
90- "required": ["start", "end", "content"]
91- },
92- "insert": {
93- "type": "object",
94- "description": "Insert new lines after the anchored line",
95- "properties": {
96- "after": ` + anchorSchema + `,
97- "content": {"type": "string", "description": "Text to insert (may be multiple lines)"}
98- },
99- "required": ["after", "content"]
100- },
101- "delete": {
102- "type": "object",
103- "description": "Delete lines from start to end (inclusive)",
104- "properties": {
105- "start": ` + anchorSchema + `,
106- "end": ` + anchorSchema + `
107- },
108- "required": ["start", "end"]
109- },
110- "create": {
111- "type": "object",
112- "description": "Create a new file (fails if file already exists)",
113- "properties": {
114- "content": {"type": "string", "description": "Full file content"}
115- },
116- "required": ["content"]
117- }
54+ "file": {"type": "string", "description": "Path to the file to edit"},
55+ "operation": {"type": "string", "enum": ["replace", "insert", "delete", "create"], "description": "The edit operation to perform"},
56+ "start": {"type": "string", "description": "Start anchor as 'line:hash' (replace, delete)"},
57+ "end": {"type": "string", "description": "End anchor as 'line:hash' (replace, delete)"},
58+ "after": {"type": "string", "description": "Insert-after anchor as 'line:hash' (insert)"},
59+ "content": {"type": "string", "description": "Text content (replace, insert, create)"}
11860 },
119- "required": ["file"]
61+ "required": ["file", "operation"]
12062 }`),
12163 }
12264 }
@@ -141,13 +83,13 @@ func (h *EditHandler) SetTSIndex(idx *treesitter.Index) { h.tsIndex = idx }
14183 func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
14284 var args EditArgs
14385 if err := json.Unmarshal(arguments, &args); err != nil {
144- return toolError("%s", editUnmarshalHint(arguments, err)), nil
86+ return toolError("Invalid arguments: %v", err), nil
14587 }
14688 if args.File == "" {
147- return toolError("File path cannot be empty"), nil
89+ return toolError("file is required"), nil
14890 }
149- if err := validateEditOps(args); err != nil {
150- return toolError("%v", err), nil
91+ if args.Operation == "" {
92+ return toolError("operation is required (replace, insert, delete, or create)"), nil
15193 }
15294
15395 absPath, err := validatePath(args.File)
@@ -155,8 +97,8 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
15597 return toolError("%v", err), nil
15698 }
15799
158- if args.Create != nil {
159- return h.handleCreate(ctx, absPath, args.File, args.Create)
100+ if args.Operation == "create" {
101+ return h.handleCreate(ctx, absPath, args.File, args.Content)
160102 }
161103
162104 if !h.tracker.WasRead(absPath) {
@@ -166,49 +108,6 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
166108 return h.applyEdit(ctx, absPath, args)
167109 }
168110
169-// validateEditOps ensures exactly one operation is specified.
170-func validateEditOps(args EditArgs) error {
171- ops := 0
172- if args.Replace != nil {
173- ops++
174- }
175- if args.Insert != nil {
176- ops++
177- }
178- if args.Delete != nil {
179- ops++
180- }
181- if args.Create != nil {
182- ops++
183- }
184- if ops != 1 {
185- return fmt.Errorf("exactly one operation (replace, insert, delete, or create) must be specified")
186- }
187- return nil
188-}
189-
190-// editUnmarshalHint returns an actionable error when JSON unmarshalling fails.
191-// It detects common mistakes like passing a string for create instead of an object.
192-func editUnmarshalHint(raw json.RawMessage, original error) string {
193- var probe map[string]json.RawMessage
194- if json.Unmarshal(raw, &probe) == nil {
195- for _, key := range []string{"create", "replace", "insert", "delete"} {
196- v, ok := probe[key]
197- if !ok || len(v) == 0 {
198- continue
199- }
200- // If the value starts with '"' it's a string, but the schema expects an object.
201- if v[0] == '"' {
202- return fmt.Sprintf(
203- `invalid %s: expected an object, got a string. Use {"file":"path", "%s":{"content":"..."}}`,
204- key, key,
205- )
206- }
207- }
208- }
209- return fmt.Sprintf("invalid arguments: %v", original)
210-}
211-
212111 // applyEdit reads the file, applies the edit operation, writes it back, and returns fresh hashes.
213112 func (h *EditHandler) applyEdit(ctx context.Context, absPath string, args EditArgs) (*mcp.ToolResult, error) {
214113 content, err := os.ReadFile(absPath)
@@ -219,13 +118,15 @@ func (h *EditHandler) applyEdit(ctx context.Context, absPath string, args EditAr
219118
220119 var result string
221120 var region editRegion
222- switch {
223- case args.Replace != nil:
224- result, region, err = applyReplace(lines, args.Replace)
225- case args.Insert != nil:
226- result, region, err = applyInsert(lines, args.Insert)
227- case args.Delete != nil:
228- result, region, err = applyDelete(lines, args.Delete)
121+ switch args.Operation {
122+ case "replace":
123+ result, region, err = applyReplace(lines, args)
124+ case "insert":
125+ result, region, err = applyInsert(lines, args)
126+ case "delete":
127+ result, region, err = applyDelete(lines, args)
128+ default:
129+ return toolError("unknown operation %q: use replace, insert, delete, or create", args.Operation), nil
229130 }
230131 if err != nil {
231132 return toolError("%v", err), nil
@@ -255,7 +156,7 @@ func (h *EditHandler) applyEdit(ctx context.Context, absPath string, args EditAr
255156 }, nil
256157 }
257158
258-func (h *EditHandler) handleCreate(ctx context.Context, absPath, displayPath string, op *CreateOp) (*mcp.ToolResult, error) {
159+func (h *EditHandler) handleCreate(ctx context.Context, absPath, displayPath, content string) (*mcp.ToolResult, error) {
259160 // Fail if file already exists
260161 if _, err := os.Stat(absPath); err == nil {
261162 return toolError("File already exists: %s (use replace/insert/delete to modify)", displayPath), nil
@@ -271,11 +172,11 @@ func (h *EditHandler) handleCreate(ctx context.Context, absPath, displayPath str
271172 h.deltaTracker.RecordCreate(absPath)
272173 }
273174
274- if err := os.WriteFile(absPath, []byte(op.Content), 0600); err != nil {
175+ if err := os.WriteFile(absPath, []byte(content), 0600); err != nil {
275176 return toolError("Failed to create file: %v", err), nil
276177 }
277178
278- tagged := hashline.TagLines(op.Content, 1)
179+ tagged := hashline.TagLines(content, 1)
279180 taggedOutput := hashline.FormatTagged(tagged)
280181
281182 text := fmt.Sprintf("Created %s (%d lines):\n\n%s", displayPath, len(tagged), taggedOutput)
@@ -316,53 +217,73 @@ func formatEditResponse(displayPath string, tagged []hashline.TaggedLine, region
316217 displayPath, total, winStart, winEnd, hashline.FormatTagged(window))
317218 }
318219
319-func applyReplace(lines []string, op *ReplaceOp) (string, editRegion, error) {
320- if err := hashline.ValidateRange(op.Start, op.End, lines); err != nil {
220+func applyReplace(lines []string, args EditArgs) (string, editRegion, error) {
221+ start, err := hashline.ParseAnchor(args.Start)
222+ if err != nil {
223+ return "", editRegion{}, fmt.Errorf("replace start: %w", err)
224+ }
225+ end, err := hashline.ParseAnchor(args.End)
226+ if err != nil {
227+ return "", editRegion{}, fmt.Errorf("replace end: %w", err)
228+ }
229+ if err := hashline.ValidateRange(start, end, lines); err != nil {
321230 return "", editRegion{}, fmt.Errorf("replace: %w", err)
322231 }
323232
324- inserted := strings.Split(op.Content, "\n")
233+ inserted := strings.Split(args.Content, "\n")
325234 newLines := make([]string, 0, len(lines))
326- newLines = append(newLines, lines[:op.Start.Num-1]...)
235+ newLines = append(newLines, lines[:start.Num-1]...)
327236 newLines = append(newLines, inserted...)
328- newLines = append(newLines, lines[op.End.Num:]...)
237+ newLines = append(newLines, lines[end.Num:]...)
329238
330239 region := editRegion{
331- start: op.Start.Num,
332- end: op.Start.Num + len(inserted) - 1,
240+ start: start.Num,
241+ end: start.Num + len(inserted) - 1,
333242 }
334243 return strings.Join(newLines, "\n"), region, nil
335244 }
336245
337-func applyInsert(lines []string, op *InsertOp) (string, editRegion, error) {
338- if err := op.After.Validate(lines); err != nil {
246+func applyInsert(lines []string, args EditArgs) (string, editRegion, error) {
247+ after, err := hashline.ParseAnchor(args.After)
248+ if err != nil {
249+ return "", editRegion{}, fmt.Errorf("insert after: %w", err)
250+ }
251+ if err := after.Validate(lines); err != nil {
339252 return "", editRegion{}, fmt.Errorf("insert: after anchor: %w", err)
340253 }
341254
342- inserted := strings.Split(op.Content, "\n")
255+ inserted := strings.Split(args.Content, "\n")
343256 newLines := make([]string, 0, len(lines)+len(inserted))
344- newLines = append(newLines, lines[:op.After.Num]...)
257+ newLines = append(newLines, lines[:after.Num]...)
345258 newLines = append(newLines, inserted...)
346- newLines = append(newLines, lines[op.After.Num:]...)
259+ newLines = append(newLines, lines[after.Num:]...)
347260
348261 region := editRegion{
349- start: op.After.Num + 1,
350- end: op.After.Num + len(inserted),
262+ start: after.Num + 1,
263+ end: after.Num + len(inserted),
351264 }
352265 return strings.Join(newLines, "\n"), region, nil
353266 }
354267
355-func applyDelete(lines []string, op *DeleteOp) (string, editRegion, error) {
356- if err := hashline.ValidateRange(op.Start, op.End, lines); err != nil {
268+func applyDelete(lines []string, args EditArgs) (string, editRegion, error) {
269+ start, err := hashline.ParseAnchor(args.Start)
270+ if err != nil {
271+ return "", editRegion{}, fmt.Errorf("delete start: %w", err)
272+ }
273+ end, err := hashline.ParseAnchor(args.End)
274+ if err != nil {
275+ return "", editRegion{}, fmt.Errorf("delete end: %w", err)
276+ }
277+ if err := hashline.ValidateRange(start, end, lines); err != nil {
357278 return "", editRegion{}, fmt.Errorf("delete: %w", err)
358279 }
359280
360281 newLines := make([]string, 0, len(lines))
361- newLines = append(newLines, lines[:op.Start.Num-1]...)
362- newLines = append(newLines, lines[op.End.Num:]...)
282+ newLines = append(newLines, lines[:start.Num-1]...)
283+ newLines = append(newLines, lines[end.Num:]...)
363284
364285 // The "region" is where the deletion happened — show surrounding context.
365- regionLine := op.Start.Num - 1
286+ regionLine := start.Num - 1
366287 if regionLine < 1 {
367288 regionLine = 1
368289 }
internal/mcptools/edit_test.go+274−397
@@ -3,513 +3,390 @@ package mcptools
33 import (
44 "context"
55 "encoding/json"
6- "fmt"
76 "os"
87 "path/filepath"
98 "strings"
109 "testing"
1110
1211 "github.com/xonecas/symb/internal/hashline"
12+ "github.com/xonecas/symb/internal/mcp"
1313 )
1414
15-const threeLineContent = "line one\nline two\nline three"
15+const threeLineContent = "aaa\nbbb\nccc\n"
1616
17-// setupTestFile creates a temp file with the given content and returns its path and cleanup func.
18-func setupTestFile(t *testing.T, content string) (string, func()) {
17+func setupTestFile(t *testing.T) (string, string) {
1918 t.Helper()
2019 dir := t.TempDir()
21- path := filepath.Join(dir, "test.go")
22- if err := os.WriteFile(path, []byte(content), 0644); err != nil {
23- t.Fatalf("write test file: %v", err)
24- }
25-
26- // Change to temp dir so path validation passes
27- origDir, _ := os.Getwd()
28- if err := os.Chdir(dir); err != nil {
29- t.Fatalf("chdir: %v", err)
30- }
31-
32- return path, func() {
33- os.Chdir(origDir) //nolint:errcheck
20+ path := filepath.Join(dir, "test.txt")
21+ if err := os.WriteFile(path, []byte(threeLineContent), 0644); err != nil {
22+ t.Fatal(err)
3423 }
24+ return dir, path
3525 }
3626
37-// newTrackedHandler creates an EditHandler with a tracker where the file is already marked as read.
38-func newTrackedHandler(t *testing.T, absPath string) *EditHandler {
27+func newTrackedHandler(t *testing.T, dir string) *EditHandler {
3928 t.Helper()
4029 tracker := NewFileReadTracker()
41- tracker.MarkRead(absPath)
42- return NewEditHandler(tracker, nil, nil)
30+ oldDir, _ := os.Getwd()
31+ if err := os.Chdir(dir); err != nil {
32+ t.Fatal(err)
33+ }
34+ t.Cleanup(func() { os.Chdir(oldDir) })
35+ h := NewEditHandler(tracker, nil, nil)
36+ return h
4337 }
4438
45-func callEdit(t *testing.T, handler *EditHandler, args EditArgs) (string, bool) {
39+func callEdit(t *testing.T, handler *EditHandler, jsonStr string) *mcp.ToolResult {
4640 t.Helper()
47- argsJSON, err := json.Marshal(args)
48- if err != nil {
49- t.Fatalf("marshal args: %v", err)
50- }
51-
52- result, err := handler.Handle(context.Background(), argsJSON)
41+ result, err := handler.Handle(context.Background(), json.RawMessage(jsonStr))
5342 if err != nil {
5443 t.Fatalf("handler error: %v", err)
5544 }
45+ return result
46+}
5647
57- text := ""
58- if len(result.Content) > 0 {
59- text = result.Content[0].Text
48+// hashFor returns the hash for a given line in content.
49+func hashFor(content string, lineNum int) string {
50+ tagged := hashline.TagLines(content, 1)
51+ if lineNum < 1 || lineNum > len(tagged) {
52+ panic("line out of range")
6053 }
61- return text, result.IsError
54+ return tagged[lineNum-1].Hash
6255 }
6356
6457 func TestEditReplace(t *testing.T) {
65- content := "line one\nline two\nline three\nline four"
66- path, cleanup := setupTestFile(t, content)
67- defer cleanup()
68-
69- lines := strings.Split(content, "\n")
70- h2 := hashline.LineHash(lines[1])
71- h3 := hashline.LineHash(lines[2])
72-
73- handler := newTrackedHandler(t, path)
74- text, isErr := callEdit(t, handler, EditArgs{
75- File: filepath.Base(path),
76- Replace: &ReplaceOp{
77- Start: hashline.Anchor{Num: 2, Hash: h2},
78- End: hashline.Anchor{Num: 3, Hash: h3},
79- Content: "replaced line",
80- },
81- })
82-
83- if isErr {
84- t.Fatalf("replace failed: %s", text)
85- }
58+ dir, path := setupTestFile(t)
59+ handler := newTrackedHandler(t, dir)
60+ handler.tracker.MarkRead(path)
8661
87- got, _ := os.ReadFile(path)
88- expected := "line one\nreplaced line\nline four"
89- if string(got) != expected {
90- t.Errorf("file content:\ngot: %q\nwant: %q", string(got), expected)
62+ h1 := hashFor(threeLineContent, 1)
63+ h2 := hashFor(threeLineContent, 2)
64+
65+ result := callEdit(t, handler, `{
66+ "file": "test.txt",
67+ "operation": "replace",
68+ "start": "1:`+h1+`",
69+ "end": "2:`+h2+`",
70+ "content": "xxx\nyyy"
71+ }`)
72+
73+ if result.IsError {
74+ t.Fatalf("unexpected error: %s", result.Content[0].Text)
9175 }
9276
93- // Result should contain hashline-tagged output
94- if !strings.Contains(text, "Edited") {
95- t.Errorf("result should mention 'Edited': %s", text)
77+ got, _ := os.ReadFile(path)
78+ if string(got) != "xxx\nyyy\nccc\n" {
79+ t.Errorf("unexpected content: %q", got)
9680 }
9781 }
9882
99-func TestEditInsert(t *testing.T) {
100- content := threeLineContent
101- path, cleanup := setupTestFile(t, content)
102- defer cleanup()
103-
104- lines := strings.Split(content, "\n")
105- h1 := hashline.LineHash(lines[0])
106-
107- handler := newTrackedHandler(t, path)
108- text, isErr := callEdit(t, handler, EditArgs{
109- File: filepath.Base(path),
110- Insert: &InsertOp{
111- After: hashline.Anchor{Num: 1, Hash: h1},
112- Content: "inserted a\ninserted b",
113- },
114- })
115-
116- if isErr {
117- t.Fatalf("insert failed: %s", text)
83+func TestEditReplaceSingleLine(t *testing.T) {
84+ dir, path := setupTestFile(t)
85+ handler := newTrackedHandler(t, dir)
86+ handler.tracker.MarkRead(path)
87+
88+ h2 := hashFor(threeLineContent, 2)
89+
90+ result := callEdit(t, handler, `{
91+ "file": "test.txt",
92+ "operation": "replace",
93+ "start": "2:`+h2+`",
94+ "end": "2:`+h2+`",
95+ "content": "BBB"
96+ }`)
97+
98+ if result.IsError {
99+ t.Fatalf("unexpected error: %s", result.Content[0].Text)
118100 }
119101
120102 got, _ := os.ReadFile(path)
121- expected := "line one\ninserted a\ninserted b\nline two\nline three"
122- if string(got) != expected {
123- t.Errorf("file content:\ngot: %q\nwant: %q", string(got), expected)
103+ if string(got) != "aaa\nBBB\nccc\n" {
104+ t.Errorf("unexpected content: %q", got)
124105 }
125106 }
126107
127-func TestEditDelete(t *testing.T) {
128- content := "line one\nline two\nline three\nline four"
129- path, cleanup := setupTestFile(t, content)
130- defer cleanup()
131-
132- lines := strings.Split(content, "\n")
133- h2 := hashline.LineHash(lines[1])
134- h3 := hashline.LineHash(lines[2])
135-
136- handler := newTrackedHandler(t, path)
137- text, isErr := callEdit(t, handler, EditArgs{
138- File: filepath.Base(path),
139- Delete: &DeleteOp{
140- Start: hashline.Anchor{Num: 2, Hash: h2},
141- End: hashline.Anchor{Num: 3, Hash: h3},
142- },
143- })
144-
145- if isErr {
146- t.Fatalf("delete failed: %s", text)
108+func TestEditReplaceWithMoreLines(t *testing.T) {
109+ dir, path := setupTestFile(t)
110+ handler := newTrackedHandler(t, dir)
111+ handler.tracker.MarkRead(path)
112+
113+ h2 := hashFor(threeLineContent, 2)
114+
115+ result := callEdit(t, handler, `{
116+ "file": "test.txt",
117+ "operation": "replace",
118+ "start": "2:`+h2+`",
119+ "end": "2:`+h2+`",
120+ "content": "B1\nB2\nB3"
121+ }`)
122+
123+ if result.IsError {
124+ t.Fatalf("unexpected error: %s", result.Content[0].Text)
147125 }
148126
149127 got, _ := os.ReadFile(path)
150- expected := "line one\nline four"
151- if string(got) != expected {
152- t.Errorf("file content:\ngot: %q\nwant: %q", string(got), expected)
128+ if string(got) != "aaa\nB1\nB2\nB3\nccc\n" {
129+ t.Errorf("unexpected content: %q", got)
153130 }
154131 }
155132
156-func TestEditCreate(t *testing.T) {
157- dir := t.TempDir()
158- origDir, _ := os.Getwd()
159- if err := os.Chdir(dir); err != nil {
160- t.Fatalf("chdir: %v", err)
161- }
162- defer os.Chdir(origDir) //nolint:errcheck
133+func TestEditInsert(t *testing.T) {
134+ dir, path := setupTestFile(t)
135+ handler := newTrackedHandler(t, dir)
136+ handler.tracker.MarkRead(path)
163137
164- tracker := NewFileReadTracker()
165- handler := NewEditHandler(tracker, nil, nil)
166- text, isErr := callEdit(t, handler, EditArgs{
167- File: "newfile.go",
168- Create: &CreateOp{Content: "package main\n\nfunc main() {}\n"},
169- })
170-
171- if isErr {
172- t.Fatalf("create failed: %s", text)
173- }
138+ h1 := hashFor(threeLineContent, 1)
174139
175- got, err := os.ReadFile(filepath.Join(dir, "newfile.go"))
176- if err != nil {
177- t.Fatalf("read created file: %v", err)
140+ result := callEdit(t, handler, `{
141+ "file": "test.txt",
142+ "operation": "insert",
143+ "after": "1:`+h1+`",
144+ "content": "inserted"
145+ }`)
146+
147+ if result.IsError {
148+ t.Fatalf("unexpected error: %s", result.Content[0].Text)
178149 }
179- expected := "package main\n\nfunc main() {}\n"
180- if string(got) != expected {
181- t.Errorf("file content:\ngot: %q\nwant: %q", string(got), expected)
150+
151+ got, _ := os.ReadFile(path)
152+ if string(got) != "aaa\ninserted\nbbb\nccc\n" {
153+ t.Errorf("unexpected content: %q", got)
182154 }
183155 }
184156
185-func TestEditCreateFailsIfExists(t *testing.T) {
186- _, cleanup := setupTestFile(t, "existing content")
187- defer cleanup()
157+func TestEditDelete(t *testing.T) {
158+ dir, path := setupTestFile(t)
159+ handler := newTrackedHandler(t, dir)
160+ handler.tracker.MarkRead(path)
188161
189- tracker := NewFileReadTracker()
190- handler := NewEditHandler(tracker, nil, nil)
191- _, isErr := callEdit(t, handler, EditArgs{
192- File: "test.go",
193- Create: &CreateOp{Content: "new content"},
194- })
195-
196- if !isErr {
197- t.Error("create should fail if file already exists")
162+ h2 := hashFor(threeLineContent, 2)
163+
164+ result := callEdit(t, handler, `{
165+ "file": "test.txt",
166+ "operation": "delete",
167+ "start": "2:`+h2+`",
168+ "end": "2:`+h2+`"
169+ }`)
170+
171+ if result.IsError {
172+ t.Fatalf("unexpected error: %s", result.Content[0].Text)
198173 }
199-}
200174
201-func TestEditHashMismatch(t *testing.T) {
202- content := threeLineContent
203- path, cleanup := setupTestFile(t, content)
204- defer cleanup()
205-
206- handler := newTrackedHandler(t, path)
207- _, isErr := callEdit(t, handler, EditArgs{
208- File: "test.go",
209- Replace: &ReplaceOp{
210- Start: hashline.Anchor{Num: 1, Hash: "ff"},
211- End: hashline.Anchor{Num: 2, Hash: "ff"},
212- Content: "whatever",
213- },
214- })
215-
216- if !isErr {
217- t.Error("should fail on hash mismatch")
175+ got, _ := os.ReadFile(path)
176+ if string(got) != "aaa\nccc\n" {
177+ t.Errorf("unexpected content: %q", got)
218178 }
219179 }
220180
221-func TestEditNoOperation(t *testing.T) {
222- _, cleanup := setupTestFile(t, "single line")
223- defer cleanup()
181+func TestEditCreate(t *testing.T) {
182+ dir, _ := setupTestFile(t)
183+ handler := newTrackedHandler(t, dir)
224184
225- tracker := NewFileReadTracker()
226- handler := NewEditHandler(tracker, nil, nil)
227- _, isErr := callEdit(t, handler, EditArgs{
228- File: "test.go",
229- })
185+ result := callEdit(t, handler, `{
186+ "file": "new.txt",
187+ "operation": "create",
188+ "content": "hello\nworld"
189+ }`)
230190
231- if !isErr {
232- t.Error("should fail when no operation specified")
191+ if result.IsError {
192+ t.Fatalf("unexpected error: %s", result.Content[0].Text)
233193 }
234-}
235194
236-func TestEditMultipleOperations(t *testing.T) {
237- testContent := "single line"
238- path, cleanup := setupTestFile(t, testContent)
239- defer cleanup()
240-
241- lines := strings.Split(testContent, "\n")
242- h1 := hashline.LineHash(lines[0])
243-
244- handler := newTrackedHandler(t, path)
245- _, isErr := callEdit(t, handler, EditArgs{
246- File: "test.go",
247- Replace: &ReplaceOp{
248- Start: hashline.Anchor{Num: 1, Hash: h1},
249- End: hashline.Anchor{Num: 1, Hash: h1},
250- Content: "new",
251- },
252- Delete: &DeleteOp{
253- Start: hashline.Anchor{Num: 1, Hash: h1},
254- End: hashline.Anchor{Num: 1, Hash: h1},
255- },
256- })
257-
258- if !isErr {
259- t.Error("should fail when multiple operations specified")
195+ got, _ := os.ReadFile(filepath.Join(dir, "new.txt"))
196+ if string(got) != "hello\nworld" {
197+ t.Errorf("unexpected content: %q", got)
260198 }
261199 }
262200
263-func TestEditPathTraversal(t *testing.T) {
264- _, cleanup := setupTestFile(t, "single line")
265- defer cleanup()
201+func TestEditCreateFailsIfExists(t *testing.T) {
202+ dir, _ := setupTestFile(t)
203+ handler := newTrackedHandler(t, dir)
266204
267- tracker := NewFileReadTracker()
268- handler := NewEditHandler(tracker, nil, nil)
269- _, isErr := callEdit(t, handler, EditArgs{
270- File: "../../../etc/passwd",
271- Create: &CreateOp{Content: "hacked"},
272- })
273-
274- if !isErr {
275- t.Error("should reject path traversal")
205+ result := callEdit(t, handler, `{
206+ "file": "test.txt",
207+ "operation": "create",
208+ "content": "overwrite"
209+ }`)
210+
211+ if !result.IsError {
212+ t.Fatal("should fail when file exists")
276213 }
277214 }
278215
279-func TestEditReplaceSingleLine(t *testing.T) {
280- content := "aaa\nbbb\nccc"
281- path, cleanup := setupTestFile(t, content)
282- defer cleanup()
283-
284- lines := strings.Split(content, "\n")
285- h2 := hashline.LineHash(lines[1])
286-
287- handler := newTrackedHandler(t, path)
288- _, isErr := callEdit(t, handler, EditArgs{
289- File: filepath.Base(path),
290- Replace: &ReplaceOp{
291- Start: hashline.Anchor{Num: 2, Hash: h2},
292- End: hashline.Anchor{Num: 2, Hash: h2},
293- Content: "BBB",
294- },
295- })
296-
297- if isErr {
298- t.Fatal("single line replace should work")
299- }
216+func TestEditHashMismatch(t *testing.T) {
217+ dir, path := setupTestFile(t)
218+ handler := newTrackedHandler(t, dir)
219+ handler.tracker.MarkRead(path)
220+
221+ result := callEdit(t, handler, `{
222+ "file": "test.txt",
223+ "operation": "replace",
224+ "start": "1:zz",
225+ "end": "1:zz",
226+ "content": "xxx"
227+ }`)
300228
301- got, _ := os.ReadFile(path)
302- if string(got) != "aaa\nBBB\nccc" {
303- t.Errorf("got: %q", string(got))
229+ if !result.IsError {
230+ t.Fatal("should fail with hash mismatch")
304231 }
305232 }
306233
307-func TestEditReplaceWithMoreLines(t *testing.T) {
308- content := "aaa\nbbb\nccc"
309- path, cleanup := setupTestFile(t, content)
310- defer cleanup()
311-
312- lines := strings.Split(content, "\n")
313- h2 := hashline.LineHash(lines[1])
314-
315- handler := newTrackedHandler(t, path)
316- _, isErr := callEdit(t, handler, EditArgs{
317- File: filepath.Base(path),
318- Replace: &ReplaceOp{
319- Start: hashline.Anchor{Num: 2, Hash: h2},
320- End: hashline.Anchor{Num: 2, Hash: h2},
321- Content: "BBB\nDDD\nEEE",
322- },
323- })
324-
325- if isErr {
326- t.Fatal("replace expanding lines should work")
234+func TestEditNoOperation(t *testing.T) {
235+ dir, _ := setupTestFile(t)
236+ handler := newTrackedHandler(t, dir)
237+
238+ result := callEdit(t, handler, `{"file": "test.txt"}`)
239+
240+ if !result.IsError {
241+ t.Fatal("should fail without operation")
327242 }
243+}
328244
329- got, _ := os.ReadFile(path)
330- if string(got) != "aaa\nBBB\nDDD\nEEE\nccc" {
331- t.Errorf("got: %q", string(got))
245+func TestEditPathTraversal(t *testing.T) {
246+ dir, _ := setupTestFile(t)
247+ handler := newTrackedHandler(t, dir)
248+
249+ result := callEdit(t, handler, `{
250+ "file": "../../../etc/passwd",
251+ "operation": "create",
252+ "content": "bad"
253+ }`)
254+
255+ if !result.IsError {
256+ t.Fatal("should reject path traversal")
332257 }
333258 }
334259
335260 func TestEditRequiresReadFirst(t *testing.T) {
336- content := "line one\nline two"
337- path, cleanup := setupTestFile(t, content)
338- defer cleanup()
261+ dir, _ := setupTestFile(t)
262+ handler := newTrackedHandler(t, dir)
339263
340- lines := strings.Split(content, "\n")
341- h1 := hashline.LineHash(lines[0])
264+ h1 := hashFor(threeLineContent, 1)
342265
343- // Handler with empty tracker — file NOT read
344- tracker := NewFileReadTracker()
345- handler := NewEditHandler(tracker, nil, nil)
346-
347- text, isErr := callEdit(t, handler, EditArgs{
348- File: filepath.Base(path),
349- Replace: &ReplaceOp{
350- Start: hashline.Anchor{Num: 1, Hash: h1},
351- End: hashline.Anchor{Num: 1, Hash: h1},
352- Content: "replaced",
353- },
354- })
355-
356- if !isErr {
357- t.Fatal("should fail when file was not read first")
358- }
359- if !strings.Contains(text, "Read") {
360- t.Errorf("error should mention Read tool: %s", text)
361- }
266+ result := callEdit(t, handler, `{
267+ "file": "test.txt",
268+ "operation": "replace",
269+ "start": "1:`+h1+`",
270+ "end": "1:`+h1+`",
271+ "content": "xxx"
272+ }`)
362273
363- // Now mark as read and retry — should succeed
364- absPath, _ := filepath.Abs(filepath.Base(path))
365- tracker.MarkRead(absPath)
366-
367- _, isErr = callEdit(t, handler, EditArgs{
368- File: filepath.Base(path),
369- Replace: &ReplaceOp{
370- Start: hashline.Anchor{Num: 1, Hash: h1},
371- End: hashline.Anchor{Num: 1, Hash: h1},
372- Content: "replaced",
373- },
374- })
375-
376- if isErr {
377- t.Fatal("should succeed after file was read")
274+ if !result.IsError {
275+ t.Fatal("should require Read first")
276+ }
277+ if !strings.Contains(result.Content[0].Text, "must Read") {
278+ t.Errorf("unexpected error: %s", result.Content[0].Text)
378279 }
379280 }
380281
381282 func TestEditCreateBypassesReadCheck(t *testing.T) {
382- dir := t.TempDir()
383- origDir, _ := os.Getwd()
384- if err := os.Chdir(dir); err != nil {
385- t.Fatalf("chdir: %v", err)
386- }
387- defer os.Chdir(origDir) //nolint:errcheck
283+ dir, _ := setupTestFile(t)
284+ handler := newTrackedHandler(t, dir)
388285
389- // Empty tracker — no file read. Create should still work.
390- tracker := NewFileReadTracker()
391- handler := NewEditHandler(tracker, nil, nil)
392- _, isErr := callEdit(t, handler, EditArgs{
393- File: "brand-new.go",
394- Create: &CreateOp{Content: "package new\n"},
395- })
396-
Cut short: this commit's diff is over 1000 lines.