xonecas.io
62159
Sy

symb / commit 6cd2ada

feat: edit with hash:line technique https://blog.can.ac/2026/02/12/the-harness-problem/

xonecas2026-02-13 6cd2adab4c67369bffb3392ff5b13e2ec382f316 parent f732085

13 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.

cmd/symb/main.go+8−1
@@ -91,14 +91,20 @@ func main() {
9191 defer proxy.Close()
9292
9393 // Register local tools
94+ fileTracker := mcp_tools.NewFileReadTracker()
95+
9496 openForUserTool := mcp_tools.NewOpenForUserTool()
95- openForUserHandler := mcp_tools.NewOpenForUserHandler()
97+ openForUserHandler := mcp_tools.NewOpenForUserHandler(fileTracker)
9698 proxy.RegisterTool(openForUserTool, openForUserHandler.Handle)
9799
98100 grepTool := mcp_tools.NewGrepTool()
99101 grepHandler := mcp_tools.MakeGrepHandler()
100102 proxy.RegisterTool(grepTool, grepHandler)
101103
104+ editTool := mcp_tools.NewEditTool()
105+ editHandler := mcp_tools.NewEditHandler(fileTracker)
106+ proxy.RegisterTool(editTool, editHandler.Handle)
107+
102108 // List all tools (local + upstream)
103109 tools, err := proxy.ListTools(context.Background())
104110 if err != nil {
@@ -116,6 +122,7 @@ func main() {
116122
117123 // Set program reference for tools that need it
118124 openForUserHandler.SetProgram(p)
125+ editHandler.SetProgram(p)
119126
120127 // Run the program
121128 if _, err := p.Run(); err != nil {
docs/EDIT_TOOLS.md+202−0
@@ -0,0 +1,202 @@
1+# Edit Tools: Hashline-Anchored File Editing
2+
3+## Background
4+
5+The standard approaches to LLM-driven file editing all share the same fundamental
6+weakness: they require the model to reproduce file content it already saw.
7+
8+- **str_replace** (Claude Code, OpenCode, most agents) makes the model reproduce
9+ the exact old text including whitespace. Multiple matches or slight misrecall
10+ cause failures. The "string not found" error is one of the most common complaints.
11+
12+- **apply_patch** (OpenAI Codex) expects models to produce a custom diff format.
13+ Models not specifically tuned for it fail catastrophically. Grok 4 had a 50.7%
14+ patch failure rate in benchmarks.
15+
16+- **Cursor's approach** trains a separate 70B model just to apply edits. Even then,
17+ full file rewrites outperform diffs for files under 400 lines.
18+
19+These are not model failures. They are harness failures. The model understood the
20+task but could not express the change reliably through the tool interface.
21+
22+Source: Can Boluk, "The Harness Problem" (Feb 2026). Benchmark of 16 models across
23+3 edit formats showed that format choice alone swings success rates by 10-60
24+percentage points.
25+
26+## Our Approach: Hashline
27+
28+Instead of making the model reproduce old content, we give it a stable, verifiable
29+identifier for every line. When the model reads a file, each line comes back tagged
30+with a 2-character content hash derived from SHA-256.
31+
32+The model references these tags to express edits. It never needs to reproduce
33+whitespace, indentation, or surrounding context. If it can recall a 2-char hex tag,
34+it knows what it is editing.
35+
36+If the file changed between the read and the edit, the hashes will not match and
37+the operation is rejected before any corruption can occur.
38+
39+## Open Tool
40+
41+**File:** `internal/mcp_tools/open.go`
42+
43+Opens a file in the TUI editor and returns hashline-tagged content to the LLM.
44+Each line is formatted as `linenum:hash|content`, where the hash is a 2-char hex
45+digest of that line's content.
46+
47+### Behaviour
48+
49+1. Validates the file path (absolute resolution, CWD-scoped, no traversal).
50+2. Reads the file from disk.
51+3. Records the file as "read" in the shared FileReadTracker.
52+4. Optionally extracts a line range (1-indexed start/end).
53+5. Sends the raw content to the TUI editor pane for display.
54+6. Computes hashline tags for each line.
55+7. Returns the tagged output to the LLM.
56+
57+The tagged output gives the model everything it needs for subsequent edits: line
58+numbers for positioning and content hashes for verification.
59+
60+### Parameters
61+
62+- **file** (required): Path to the file.
63+- **start** (optional): Starting line number, 1-indexed.
64+- **end** (optional): Ending line number, 1-indexed.
65+
66+## Edit Tool
67+
68+**File:** `internal/mcp_tools/edit.go`
69+
70+Modifies files using hash-anchored operations. Exactly one operation per call.
71+Returns the full updated file with fresh hashes after every edit.
72+
73+### Operations
74+
75+**Replace** removes lines from a start anchor to an end anchor (inclusive) and
76+inserts new content in their place. Both anchors are validated against the current
77+file before any modification. The replacement content may have more or fewer lines
78+than the range it replaces.
79+
80+**Insert** adds new content after a single anchored line. The anchor is validated,
81+then the new lines are spliced in immediately after it. Existing lines below shift
82+down.
83+
84+**Delete** removes lines from a start anchor to an end anchor (inclusive). Both
85+anchors are validated. The lines between them (inclusive) are removed and the file
86+is compacted.
87+
88+**Create** writes a brand new file. It fails if the file already exists. It does
89+not require a prior Open call since there is no existing content to read. Parent
90+directories are created automatically.
91+
92+### Anchors
93+
94+An anchor is a pair of line number (1-indexed) and hash (2-char hex). The hash is
95+the first byte of the SHA-256 digest of the line's content. Both values come from
96+the Open tool's output.
97+
98+Before any edit, the handler re-reads the file from disk and validates each anchor
99+against the current content. If a hash does not match, the edit is rejected with a
100+clear error indicating the file changed. The model must re-Open the file to get
101+fresh hashes.
102+
103+### Fresh Hashes After Edit
104+
105+Every successful edit returns the entire updated file with new hashline tags. This
106+is critical for chaining: if the model needs to make a second edit, it must use the
107+hashes from the edit response, not the original Open response. Line numbers shift
108+after inserts and deletes, and content hashes change after replacements.
109+
110+## Safety Layers
111+
112+The system enforces four independent safety checks, any one of which can reject a
113+bad edit.
114+
115+### Read-Before-Edit
116+
117+**File:** `internal/mcp_tools/filetrack.go`
118+
119+Open and Edit share a FileReadTracker. When Open successfully reads a file, it
120+records the absolute path. When Edit receives a replace, insert, or delete, it
121+checks that the file was previously opened. If not, it returns an error directing
122+the model to Open the file first.
123+
124+This prevents the model from guessing hashes or editing files it has not seen.
125+Create operations bypass this check since they target files that do not exist yet.
126+
127+The tracker is thread-safe (sync.RWMutex) and scoped to the session lifetime.
128+
129+### Hash Validation
130+
131+**File:** `internal/hashline/hashline.go`
132+
133+Before any modification, the edit handler re-reads the file and validates every
134+anchor. The Anchor.Validate method checks that the line number is in range and that
135+the hash matches the current content. ValidateRange additionally checks that start
136+comes before end.
137+
138+This catches concurrent modifications, external edits, or stale hashes from a
139+previous edit in a chain.
140+
141+### Path Traversal Prevention
142+
143+Both Open and Edit resolve paths to absolute form, then verify the result is within
144+or below the current working directory. Paths containing ".." that escape the CWD
145+are rejected.
146+
147+### Operation Count Enforcement
148+
149+Each Edit call must contain exactly one operation. Zero operations or multiple
150+operations are rejected before any file I/O occurs.
151+
152+## Hashline Package
153+
154+**File:** `internal/hashline/hashline.go`
155+
156+The hashline package is a standalone library with no dependencies on the tool layer.
157+
158+**LineHash** computes SHA-256 of a line's content and returns the first byte as
159+2 hex characters. This gives 256 possible values per line. Collisions are possible
160+but rare for lines in the same file, and a collision only means the edit is not
161+rejected when it perhaps should be. It never causes corruption since the line number
162+is also checked.
163+
164+**TagLines** splits content by newline and produces a TaggedLine for each, with
165+sequential numbering starting at a given offset.
166+
167+**FormatTagged** joins tagged lines into the string format returned to the LLM.
168+
169+**Anchor** pairs a line number and hash. Validate checks both against actual file
170+content. ValidateRange validates a start-end pair and checks ordering.
171+
172+## Registration
173+
174+**File:** `cmd/symb/main.go`
175+
176+A single FileReadTracker is created and shared between the Open and Edit handlers.
177+Both tools are registered on the MCP proxy. After the Bubbletea program is created,
178+both handlers receive a reference to it so they can send messages to the TUI.
179+
180+## Comparison With Other Approaches
181+
182+| Property | str_replace | apply_patch | Hashline |
183+|---|---|---|---|
184+| Model must reproduce old content | Yes | Yes (as diff context) | No |
185+| Sensitive to whitespace | Very | Somewhat | Not at all |
186+| Detects concurrent changes | No (silent corruption) | No | Yes (hash mismatch) |
187+| Requires model-specific tuning | No | Effectively yes | No |
188+| Enforces read-before-edit | Varies by agent | No | Yes |
189+| Token cost of anchoring | High (full old text) | Medium (context lines) | Low (2-char hash) |
190+
191+## Test Coverage
192+
193+**hashline package:** 7 tests, 96.7% coverage. Tests cover hashing determinism,
194+tag formatting, anchor validation (in range, out of range, wrong hash), range
195+validation, and a full round-trip from tagging to validation.
196+
197+**Edit tool:** 13 tests. Covers replace (single line, multi-line, expanding),
198+insert, delete, create, create-fails-if-exists, hash mismatch rejection, no
199+operation, multiple operations, path traversal rejection, read-before-edit
200+enforcement, and create bypassing the read check.
201+
202+References: https://blog.can.ac/2026/02/12/the-harness-problem/ and the opencode source code.
internal/hashline/hashline.go+100−0
@@ -0,0 +1,100 @@
1+// Package hashline provides content-addressed line tagging for reliable file editing.
2+//
3+// Each line gets a short hex hash derived from its content. The LLM references
4+// these hashes when editing, so it never needs to reproduce old content verbatim.
5+// If the file changed since the last read, hashes won't match and the edit is
6+// rejected before anything gets corrupted.
7+package hashline
8+
9+import (
10+ "crypto/sha256"
11+ "encoding/hex"
12+ "fmt"
13+ "strings"
14+)
15+
16+// HashLen is the number of hex characters per line hash (1 byte = 2 hex chars).
17+const HashLen = 2
18+
19+// LineHash computes a short content hash for a single line.
20+func LineHash(line string) string {
21+ h := sha256.Sum256([]byte(line))
22+ return hex.EncodeToString(h[:1]) // first byte → 2 hex chars
23+}
24+
25+// TaggedLine represents a line with its number and content hash.
26+type TaggedLine struct {
27+ Num int // 1-indexed line number
28+ Hash string // 2-char hex hash
29+ Content string // raw line content
30+}
31+
32+// Tag formats a tagged line as "num:hash|content".
33+func (t TaggedLine) Tag() string {
34+ return fmt.Sprintf("%d:%s|%s", t.Num, t.Hash, t.Content)
35+}
36+
37+// TagLines takes file content and returns tagged lines.
38+// If startLine > 0, numbering begins at startLine (1-indexed).
39+func TagLines(content string, startLine int) []TaggedLine {
40+ if startLine <= 0 {
41+ startLine = 1
42+ }
43+
44+ lines := strings.Split(content, "\n")
45+ tagged := make([]TaggedLine, len(lines))
46+ for i, line := range lines {
47+ tagged[i] = TaggedLine{
48+ Num: startLine + i,
49+ Hash: LineHash(line),
50+ Content: line,
51+ }
52+ }
53+ return tagged
54+}
55+
56+// FormatTagged formats tagged lines into the string returned to the LLM.
57+func FormatTagged(tagged []TaggedLine) string {
58+ var b strings.Builder
59+ for i, t := range tagged {
60+ if i > 0 {
61+ b.WriteByte('\n')
62+ }
63+ b.WriteString(t.Tag())
64+ }
65+ return b.String()
66+}
67+
68+// Anchor identifies a line by number and hash.
69+type Anchor struct {
70+ Num int `json:"line"`
71+ Hash string `json:"hash"`
72+}
73+
74+// Validate checks that the anchor matches the actual file lines.
75+// lines is 0-indexed; anchor.Num is 1-indexed.
76+func (a Anchor) Validate(lines []string) error {
77+ idx := a.Num - 1
78+ if idx < 0 || idx >= len(lines) {
79+ return fmt.Errorf("line %d out of range (file has %d lines)", a.Num, len(lines))
80+ }
81+ actual := LineHash(lines[idx])
82+ if actual != a.Hash {
83+ return fmt.Errorf("hash mismatch at line %d: expected %s, got %s (file changed since last read?)", a.Num, a.Hash, actual)
84+ }
85+ return nil
86+}
87+
88+// ValidateRange checks that start and end anchors are valid and ordered.
89+func ValidateRange(start, end Anchor, lines []string) error {
90+ if err := start.Validate(lines); err != nil {
91+ return fmt.Errorf("start anchor: %w", err)
92+ }
93+ if err := end.Validate(lines); err != nil {
94+ return fmt.Errorf("end anchor: %w", err)
95+ }
96+ if start.Num > end.Num {
97+ return fmt.Errorf("start line %d is after end line %d", start.Num, end.Num)
98+ }
99+ return nil
100+}
internal/hashline/hashline_test.go+162−0
@@ -0,0 +1,162 @@
1+package hashline
2+
3+import (
4+ "testing"
5+)
6+
7+func TestLineHash(t *testing.T) {
8+ // Deterministic: same input → same hash
9+ h1 := LineHash("hello world")
10+ h2 := LineHash("hello world")
11+ if h1 != h2 {
12+ t.Errorf("same input produced different hashes: %s vs %s", h1, h2)
13+ }
14+
15+ // Different input → (very likely) different hash
16+ h3 := LineHash("hello world!")
17+ if h1 == h3 {
18+ t.Errorf("different inputs produced same hash: %s", h1)
19+ }
20+
21+ // Always 2 hex chars
22+ if len(h1) != HashLen {
23+ t.Errorf("expected hash length %d, got %d", HashLen, len(h1))
24+ }
25+
26+ // Empty line gets a hash too
27+ h4 := LineHash("")
28+ if len(h4) != HashLen {
29+ t.Errorf("empty line hash length: expected %d, got %d", HashLen, len(h4))
30+ }
31+}
32+
33+func TestTagLines(t *testing.T) {
34+ content := "func hello() {\n return \"world\"\n}"
35+
36+ tagged := TagLines(content, 1)
37+ if len(tagged) != 3 {
38+ t.Fatalf("expected 3 tagged lines, got %d", len(tagged))
39+ }
40+
41+ // Check numbering
42+ for i, tl := range tagged {
43+ if tl.Num != i+1 {
44+ t.Errorf("line %d: expected Num=%d, got %d", i, i+1, tl.Num)
45+ }
46+ if len(tl.Hash) != HashLen {
47+ t.Errorf("line %d: expected hash length %d, got %d", i, HashLen, len(tl.Hash))
48+ }
49+ }
50+
51+ if tagged[0].Content != "func hello() {" {
52+ t.Errorf("line 0 content: %q", tagged[0].Content)
53+ }
54+ if tagged[2].Content != "}" {
55+ t.Errorf("line 2 content: %q", tagged[2].Content)
56+ }
57+}
58+
59+func TestTagLinesWithOffset(t *testing.T) {
60+ content := "line a\nline b"
61+ tagged := TagLines(content, 10)
62+
63+ if tagged[0].Num != 10 {
64+ t.Errorf("expected first line num 10, got %d", tagged[0].Num)
65+ }
66+ if tagged[1].Num != 11 {
67+ t.Errorf("expected second line num 11, got %d", tagged[1].Num)
68+ }
69+}
70+
71+func TestFormatTagged(t *testing.T) {
72+ tagged := []TaggedLine{
73+ {Num: 1, Hash: "a3", Content: "func hello() {"},
74+ {Num: 2, Hash: "f1", Content: " return \"world\""},
75+ {Num: 3, Hash: "0e", Content: "}"},
76+ }
77+
78+ output := FormatTagged(tagged)
79+ expected := "1:a3|func hello() {\n2:f1| return \"world\"\n3:0e|}"
80+ if output != expected {
81+ t.Errorf("FormatTagged:\ngot: %q\nwant: %q", output, expected)
82+ }
83+}
84+
85+func TestAnchorValidate(t *testing.T) {
86+ lines := []string{"func hello() {", " return \"world\"", "}"}
87+
88+ // Valid anchor
89+ hash := LineHash(lines[0])
90+ a := Anchor{Num: 1, Hash: hash}
91+ if err := a.Validate(lines); err != nil {
92+ t.Errorf("valid anchor failed: %v", err)
93+ }
94+
95+ // Out of range
96+ a2 := Anchor{Num: 0, Hash: "ff"}
97+ if err := a2.Validate(lines); err == nil {
98+ t.Error("line 0 should be out of range")
99+ }
100+
101+ a3 := Anchor{Num: 4, Hash: "ff"}
102+ if err := a3.Validate(lines); err == nil {
103+ t.Error("line 4 should be out of range")
104+ }
105+
106+ // Wrong hash (file changed)
107+ a4 := Anchor{Num: 1, Hash: "ff"}
108+ if err := a4.Validate(lines); err == nil {
109+ t.Error("wrong hash should fail validation")
110+ }
111+}
112+
113+func TestValidateRange(t *testing.T) {
114+ lines := []string{"aaa", "bbb", "ccc"}
115+ h1 := LineHash(lines[0])
116+ h2 := LineHash(lines[1])
117+ h3 := LineHash(lines[2])
118+
119+ // Valid range
120+ if err := ValidateRange(Anchor{1, h1}, Anchor{3, h3}, lines); err != nil {
121+ t.Errorf("valid range failed: %v", err)
122+ }
123+
124+ // Single line range
125+ if err := ValidateRange(Anchor{2, h2}, Anchor{2, h2}, lines); err != nil {
126+ t.Errorf("single line range failed: %v", err)
127+ }
128+
129+ // Inverted range
130+ if err := ValidateRange(Anchor{3, h3}, Anchor{1, h1}, lines); err == nil {
131+ t.Error("inverted range should fail")
132+ }
133+
134+ // Bad start hash
135+ if err := ValidateRange(Anchor{1, "ff"}, Anchor{3, h3}, lines); err == nil {
136+ t.Error("bad start hash should fail")
137+ }
138+
139+ // Bad end hash
140+ if err := ValidateRange(Anchor{1, h1}, Anchor{3, "ff"}, lines); err == nil {
141+ t.Error("bad end hash should fail")
142+ }
143+}
144+
145+func TestRoundTrip(t *testing.T) {
146+ // Simulate the full flow: tag lines, extract anchors, validate
147+ content := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hello\")\n}"
148+ tagged := TagLines(content, 1)
149+
150+ lines := make([]string, len(tagged))
151+ for i, tl := range tagged {
152+ lines[i] = tl.Content
153+ }
154+
155+ // Every tagged anchor should validate
156+ for _, tl := range tagged {
157+ a := Anchor{Num: tl.Num, Hash: tl.Hash}
158+ if err := a.Validate(lines); err != nil {
159+ t.Errorf("round-trip validation failed for line %d: %v", tl.Num, err)
160+ }
161+ }
162+}
internal/llm/anthropic.md+59−27
@@ -29,42 +29,74 @@ You are **Symb**, an AI coding assistant that helps users write, understand, and
2929
3030 ## Available Tools
3131
32-You have access to these tools for code exploration:
32+### `Open` — Read a file (required before editing)
33+Opens a file in the editor and returns **hashline-tagged** content to you.
3334
34-### `Open`
35-Opens files in the editor with syntax highlighting.
36-- Use when user asks to view/examine specific files
37-- Specify line ranges for large files: `{"file": "main.go", "start": 50, "end": 100}`
38-- File content is shown to user AND returned to you
35+Each line is returned as `linenum:hash|content`:
36+```
37+1:e3|package main
38+2:6a|
39+3:b2|import "fmt"
40+4:6a|
41+5:9f|func main() {
42+6:c1| fmt.Println("hello")
43+7:d4|}
44+```
45+
46+The 2-char hex hash is a content fingerprint for that line. You need both the line number and hash to edit.
47+
48+- `{"file": "main.go"}` — read entire file
49+- `{"file": "main.go", "start": 50, "end": 100}` — read line range
3950
40-### `Grep`
41-Searches for files or content with gitignore support.
51+**You MUST Open a file before editing it.** Edit will reject changes to files you haven't read.
52+
53+### `Grep` — Search files or content
4254 - Filename search: `{"pattern": "main\\.go", "content_search": false}`
4355 - Content search: `{"pattern": "func ProcessTurn", "content_search": true}`
4456 - Case sensitivity: `{"pattern": "Error", "case_sensitive": true}`
4557 - Limit results: `{"max_results": 50}` (default: 100)
4658
47-Use these tools proactively when users ask about code structure, specific files, or functionality.
59+### `Edit` — Modify files using hash anchors
60+**Prerequisite: Open the file first.** The hashes from Open output are your edit anchors.
61+
62+One operation per call. After each edit, you get back the updated file with fresh hashes.
63+
64+**Replace** lines 5-7 with new content:
65+```json
66+{"file": "f.go", "replace": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}, "content": "func main() {\n\tfmt.Println(\"world\")\n}"}}
67+```
68+
69+**Insert** after line 3:
70+```json
71+{"file": "f.go", "insert": {"after": {"line": 3, "hash": "b2"}, "content": "import \"os\""}}
72+```
73+
74+**Delete** lines 5-7:
75+```json
76+{"file": "f.go", "delete": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}}}
77+```
78+
79+**Create** a new file (fails if it exists):
80+```json
81+{"file": "new.go", "create": {"content": "package main\n"}}
82+```
83+
84+**Critical rules:**
85+- If a hash doesn't match, the file changed since you read it — re-Open and retry
86+- After each Edit, you get fresh hashes — use those for the next edit, not the old ones
87+- For multi-site changes, chain Edit calls sequentially
4888
4989 ## Working with Code
5090
51-**When examining code:**
52-1. Use `Grep` to locate relevant files/functions
53-2. Use `Open` to display code in the editor
54-3. Analyze and explain based on what you see
55-4. Reference specific lines: `main.go:42`
91+**Examining code:** Grep → Open → analyze → reference `file.go:42`
5692
57-**When suggesting changes:**
58-1. Show the specific code section
59-2. Explain what needs to change and why
60-3. Provide the corrected code
61-4. Let the user make the edit in their editor
93+**Editing code (the Open→Edit workflow):**
94+1. Open the file — read the hashline output
95+2. Identify the lines to change by their `line:hash` anchors
96+3. Call Edit with the exact anchors from step 1
97+4. If chaining edits, use the fresh hashes from the Edit response for subsequent calls
6298
63-**When debugging:**
64-1. Ask user to open relevant error logs/files
65-2. Analyze error messages and stack traces
66-3. Use `Grep` to find related code
67-4. Suggest specific fixes with line references
99+**Debugging:** Get error → Grep for related code → Open → identify fix → Edit
68100
69101 ## Tool Usage Patterns
70102
@@ -121,7 +153,7 @@ You: Displayed the main entry point. The event loop starts at line 120.
121153 - Go application using Bubbletea TUI framework (Elm architecture)
122154 - MCP (Model Context Protocol) for tool calling
123155 - LLM interaction via multiple providers (Ollama, OpenCode)
124-- Read-only tools for code exploration (no file modifications)
156+- Hash-anchored edit tool for reliable file modifications
125157
126158 **Code style:**
127159 - Go with golangci-lint enforcement
@@ -135,9 +167,9 @@ You: Displayed the main entry point. The event loop starts at line 120.
135167
136168 ## Constraints
137169
138-- **Read-only**: You can view and analyze code but not modify files directly
170+- **Edit via hashline**: You can modify files using the Edit tool with hash-anchored operations
139171 - **CWD-scoped**: All file operations are relative to current working directory
140-- **Security**: No shell execution, no file writes, path traversal prevention
172+- **Security**: No shell execution, path traversal prevention
141173 - **No guessing**: Always use tools to verify before making claims
142174
143175 ## Response Format
internal/llm/gemini.md+49−44
@@ -46,54 +46,60 @@ You are **Symb**, an AI coding assistant that helps users write, understand, and
4646
4747 ## Available Tools
4848
49-### `Open`
50-Opens files in the editor with syntax highlighting.
49+### `Open` — Read a file (required before editing)
50+Opens a file in the editor and returns **hashline-tagged** content.
51+
52+Each line is returned as `linenum:hash|content`:
53+```
54+1:e3|package main
55+2:6a|
56+3:b2|import "fmt"
57+4:6a|
58+5:9f|func main() {
59+6:c1| fmt.Println("hello")
60+7:d4|}
61+```
62+
63+The 2-char hex hash is a content fingerprint. You need both line number and hash to edit.
64+
5165 ```json
52-{
53- "file": "path/to/file.go",
54- "start": 50, // Optional: start line (1-indexed)
55- "end": 100 // Optional: end line (1-indexed)
56-}
66+{"file": "path/to/file.go", "start": 50, "end": 100}
5767 ```
58-- File content is displayed to user AND returned to you
59-- Use line ranges for large files to focus on relevant sections
60-- Supports all common programming languages with syntax highlighting
6168
62-### `Grep`
63-Searches for files or content patterns.
69+**You MUST Open a file before editing it.** Edit will reject changes to unread files.
70+
71+### `Grep` — Search files or content
6472 ```json
65-{
66- "pattern": "regex pattern",
67- "content_search": false, // false=filename, true=content
68- "max_results": 100, // Default: 100
69- "case_sensitive": false // Default: false
70-}
73+{"pattern": "regex pattern", "content_search": false, "max_results": 100, "case_sensitive": false}
7174 ```
72-- Respects `.gitignore` rules
73-- Filename search uses fuzzy matching
74-- Content search returns file paths with line numbers
75-- Use to locate code before examining it
75+Respects `.gitignore`. Filename search (default) or content search (`content_search: true`).
76+
77+### `Edit` — Modify files using hash anchors
78+**Prerequisite: Open the file first.** The hashes from Open output are your edit anchors.
79+
80+One operation per call. Returns updated file with fresh hashes after each edit.
81+
82+- **replace**: `{"file": "f.go", "replace": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}, "content": "new code"}}`
83+- **insert**: `{"file": "f.go", "insert": {"after": {"line": 3, "hash": "b2"}, "content": "new line"}}`
84+- **delete**: `{"file": "f.go", "delete": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}}}`
85+- **create**: `{"file": "new.go", "create": {"content": "package main\n"}}`
86+
87+**Critical rules:**
88+- If a hash doesn't match, the file changed — re-Open and retry
89+- After each Edit, use the fresh hashes for subsequent edits
90+- Chain Edit calls sequentially for multi-site changes
7691
7792 ## Working with Code
7893
79-**When user asks about code:**
80-1. Use `Grep` to find relevant files/functions
81-2. Use `Open` to display code
82-3. Analyze and explain concisely
83-4. Reference specific lines: `file.go:42`
84-
85-**When user reports bugs:**
86-1. Ask for error messages/stack traces
87-2. Use `Grep` to locate related code
88-3. Use `Open` to examine the problematic section
89-4. Identify the issue with line references
90-5. Suggest specific fixes
91-
92-**When suggesting changes:**
93-1. Show the current code (use `Open`)
94-2. Explain what's wrong
95-3. Provide corrected code
96-4. User makes the edit in their editor
94+**Examining code:** Grep → Open → analyze → reference `file.go:42`
95+
96+**Editing code (Open→Edit workflow):**
97+1. Open the file — read the hashline output
98+2. Identify lines by their `line:hash` anchors
99+3. Call Edit with exact anchors from step 1
100+4. For subsequent edits, use fresh hashes from Edit response
101+
102+**Debugging:** Get error → Grep → Open → identify fix → Edit
97103
98104 ## Tool Usage Patterns
99105
@@ -136,7 +142,7 @@ Always include file:line references:
136142 - Elm architecture pattern (Model-Update-View)
137143 - MCP (Model Context Protocol) for tool calling
138144 - Multiple LLM provider support (Ollama, OpenCode)
139-- Read-only code exploration tools
145+- Hash-anchored edit tool for reliable file modifications
140146
141147 **Code Quality:**
142148 - Go with golangci-lint enforcement
@@ -148,8 +154,7 @@ Always include file:line references:
148154 - All file operations are CWD-scoped
149155 - No path traversal allowed
150156 - No shell execution capabilities
151-- No file write/delete operations
152-- Read-only by design
157+- File editing via hash-anchored Edit tool only
153158
154159 ## Response Format
155160
@@ -172,7 +177,7 @@ responses. Uses context for cancellation.
172177
173178 ## Constraints
174179
175-- **Read-only**: Can view code, cannot modify
180+- **Edit via hashline**: Hash-anchored file editing (Open first, then Edit)
176181 - **CWD-scoped**: All paths relative to working directory
177182 - **No execution**: Cannot run code or shell commands
178183 - **No guessing**: Always verify with tools before claiming facts
internal/llm/gpt.md+58−45
@@ -41,52 +41,64 @@ A: [Uses Open tool] "Displayed main.go (287 lines)"
4141
4242 ## Tool Arsenal
4343
44-### `Open` - File Viewer
45-Opens files in the integrated editor with syntax highlighting.
44+### `Open` — Read a file (required before editing)
45+Opens a file in the editor and returns **hashline-tagged** content.
46+
47+Each line is returned as `linenum:hash|content`:
48+```
49+1:e3|package main
50+2:6a|
51+3:b2|import "fmt"
52+4:6a|
53+5:9f|func main() {
54+6:c1| fmt.Println("hello")
55+7:d4|}
56+```
57+
58+The 2-char hex hash is a content fingerprint. You need both line number and hash to edit.
4659
4760 **Parameters:**
4861 ```json
49-{
50- "file": "path/to/file.go", // Required: file path
51- "start": 50, // Optional: start line (1-indexed)
52- "end": 100 // Optional: end line (1-indexed)
53-}
62+{"file": "path/to/file.go", "start": 50, "end": 100}
5463 ```
5564
56-**Behavior:**
57-- File displayed to user in editor panel with syntax highlighting
58-- Full content (or line range) returned to you for analysis
59-- Use line ranges for large files to focus on relevant sections
65+**You MUST Open a file before editing it.** Edit will reject changes to unread files.
66+
67+### `Grep` — Search files or content
68+```json
69+{"pattern": "regex_pattern", "content_search": false, "max_results": 100, "case_sensitive": false}
70+```
71+Respects `.gitignore`. Filename search (default) or content search (`content_search: true`).
6072
61-**Use cases:**
62-- User requests to see specific files
63-- Examining code after finding it with Grep
64-- Displaying code context for explanations
73+### `Edit` — Modify files using hash anchors
74+**Prerequisite: Open the file first.** The hashes from Open output are your edit anchors.
6575
66-### `Grep` - Code Search
67-Searches filesystem for files or content patterns.
76+One operation per call. Returns updated file with fresh hashes after each edit.
6877
69-**Parameters:**
78+**Replace** lines 5-7:
7079 ```json
71-{
72- "pattern": "regex_pattern", // Required: search pattern
73- "content_search": false, // false=filenames, true=file contents
74- "max_results": 100, // Default: 100
75- "case_sensitive": false // Default: false
76-}
77-```
78-
79-**Behavior:**
80-- Respects `.gitignore` rules
81-- Filename search uses fuzzy matching
82-- Content search returns `file:line` with context
83-- Results truncated if exceeding max_results
84-
85-**Use cases:**
86-- Locating files by name pattern
87-- Finding function/type definitions
88-- Searching for specific code patterns
89-- Identifying files containing errors/imports
80+{"file": "f.go", "replace": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}, "content": "new code"}}
81+```
82+
83+**Insert** after line 3:
84+```json
85+{"file": "f.go", "insert": {"after": {"line": 3, "hash": "b2"}, "content": "new line"}}
86+```
87+
88+**Delete** lines 5-7:
89+```json
90+{"file": "f.go", "delete": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}}}
91+```
92+
93+**Create** a new file:
94+```json
95+{"file": "new.go", "create": {"content": "package main\n"}}
96+```
97+
98+**Critical rules:**
99+- If a hash doesn't match, the file changed — re-Open and retry
100+- After each Edit, use the fresh hashes for subsequent edits
101+- Chain Edit calls sequentially for multi-site changes
90102
91103 ## Operational Workflow
92104
@@ -109,12 +121,13 @@ Searches filesystem for files or content patterns.
109121 6. You: Suggest specific fix with code example
110122 ```
111123
112-### Change Suggestion Pattern
124+### Edit Pattern (Open→Edit workflow)
113125 ```
114-1. You: Open file to show current code
115-2. You: Explain what's wrong (1-2 sentences)
116-3. You: Provide corrected code block
117-4. User: Makes edit in their editor
126+1. You: Open file — read the hashline output
127+2. You: Identify lines by their line:hash anchors
128+3. You: Call Edit with exact anchors from step 1
129+4. You: For subsequent edits, use fresh hashes from Edit response
130+5. You: Explain what changed
118131 ```
119132
120133 ## Tool Execution Strategy
@@ -177,7 +190,7 @@ Always reference code with `file:line` notation:
177190 - **Style**: Follow existing patterns in codebase
178191
179192 ### Security Model
180-- **Read-only**: No file write/delete capabilities
193+- **Edit via hashline**: Hash-anchored file editing (Open first, then Edit)
181194 - **Scoped**: CWD and subdirectories only (no path traversal)
182195 - **Safe**: No shell execution, no dangerous operations
183196 - **Bounded**: Search results capped, file sizes checked
@@ -209,13 +222,13 @@ from 429 responses. Context-aware for cancellation.
209222 ### What You CAN Do
210223 ✓ View any file in the working directory
211224 ✓ Search codebase for patterns
225+✓ Edit files using hash-anchored operations
226+✓ Create new files
212227 ✓ Analyze code structure and logic
213228 ✓ Explain functionality with references
214-✓ Suggest code improvements
215229 ✓ Debug issues with tool assistance
216230
217231 ### What You CANNOT Do
218-✗ Modify files (read-only access)
219232 ✗ Execute code or shell commands
220233 ✗ Access files outside CWD
221234 ✗ Guess or infer without tool verification
internal/llm/qwen.md+35−33
@@ -30,47 +30,49 @@ Examples:
3030
3131 ## Tools
3232
33-### `Open` - Display files in editor
33+### `Open` — Read a file (required before editing)
34+Returns **hashline-tagged** content. Each line as `linenum:hash|content`:
35+```
36+1:e3|package main
37+2:6a|
38+3:b2|import "fmt"
39+5:9f|func main() {
40+6:c1| fmt.Println("hello")
41+7:d4|}
42+```
43+The 2-char hex hash is a content fingerprint. You need both line number and hash to edit.
3444 ```json
35-{
36- "file": "path/to/file.go",
37- "start": 50, // optional line range
38- "end": 100
39-}
45+{"file": "path/to/file.go", "start": 50, "end": 100}
4046 ```
41-Shows file in editor with syntax highlighting. You also receive the content.
47+**You MUST Open a file before editing it.** Edit rejects changes to unread files.
4248
43-### `Grep` - Search files/content
49+### `Grep` — Search files/content
4450 ```json
45-{
46- "pattern": "search pattern",
47- "content_search": false, // false=filename, true=content
48- "max_results": 100,
49- "case_sensitive": false
50-}
51+{"pattern": "search pattern", "content_search": false, "max_results": 100, "case_sensitive": false}
5152 ```
5253 Finds files or content. Respects `.gitignore`.
5354
55+### `Edit` — Modify files using hash anchors
56+**Open the file first.** One operation per call. Returns fresh hashes after each edit.
57+
58+- **replace**: `{"file": "f.go", "replace": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}, "content": "new code"}}`
59+- **insert**: `{"file": "f.go", "insert": {"after": {"line": 3, "hash": "b2"}, "content": "new line"}}`
60+- **delete**: `{"file": "f.go", "delete": {"start": {"line": 5, "hash": "9f"}, "end": {"line": 7, "hash": "d4"}}}`
61+- **create**: `{"file": "new.go", "create": {"content": "package main\n"}}`
62+
63+Hash mismatch = file changed since read → re-Open and retry. Use fresh hashes for chained edits.
64+
5465 ## Workflow
5566
56-**When user asks about code:**
57-1. `Grep` to find relevant files
58-2. `Open` to display code
59-3. Analyze and explain
60-4. Reference: `file.go:42`
61-
62-**When debugging:**
63-1. Get error message from user
64-2. `Grep` for related code
65-3. `Open` to examine
66-4. Identify issue with line reference
67-5. Suggest fix
68-
69-**When suggesting changes:**
70-1. Show current code (`Open`)
71-2. Explain the problem
72-3. Provide corrected code
73-4. User edits in their editor
67+**Examining code:** Grep → Open → analyze → reference `file.go:42`
68+
69+**Editing code (Open→Edit):**
70+1. Open file — read hashline output
71+2. Identify lines by `line:hash` anchors
72+3. Call Edit with exact anchors
73+4. Use fresh hashes from Edit response for next edit
74+
75+**Debugging:** Get error → Grep → Open → Edit fix
7476
7577 ## Tool Usage
7678
@@ -111,7 +113,7 @@ Always include file:line:
111113 - `make lint` and `make test`
112114
113115 **Constraints:**
114-- Read-only (no file writes)
116+- File editing via hash-anchored Edit tool
115117 - CWD-scoped (no path traversal)
116118 - No shell execution
117119 - Security: defensive only
internal/mcp_tools/edit.go+344−0
@@ -0,0 +1,344 @@
1+package mcp_tools
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "os"
8+ "path/filepath"
9+ "strings"
10+
11+ tea "github.com/charmbracelet/bubbletea"
12+ "github.com/xonecas/symb/internal/hashline"
13+ "github.com/xonecas/symb/internal/mcp"
14+)
15+
16+// EditArgs represents arguments for the Edit tool.
Cut short: this commit's diff is over 1000 lines.
internal/mcp_tools/edit_test.go+397−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp_tools/filetrack.go+30−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp_tools/open.go+19−10
Cut short: this commit's diff is over 1000 lines.
test-edit-file.md+7−0
Cut short: this commit's diff is over 1000 lines.