62159
Sy
symb / files
symb / internal / hashline / hashline.go
4.6 KB
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. 7package hashline 8 9import ( 10 "crypto/sha256" 11 "encoding/hex" 12 "fmt" 13 "strconv" 14 "strings" 15) 16 17// HashLen is the number of hex characters per line hash (1 byte = 2 hex chars). 18const HashLen = 2 19 20// LineHash computes a short content hash for a single line. 21func LineHash(line string) string { 22 h := sha256.Sum256([]byte(line)) 23 return hex.EncodeToString(h[:1]) // first byte → 2 hex chars 24} 25 26// TaggedLine represents a line with its number and content hash. 27type TaggedLine struct { 28 Num int // 1-indexed line number 29 Hash string // 2-char hex hash 30 Content string // raw line content 31} 32 33// Tag formats a tagged line as "num:hash|content". 34func (t TaggedLine) Tag() string { 35 return fmt.Sprintf("%d:%s|%s", t.Num, t.Hash, t.Content) 36} 37 38// TagLines takes file content and returns tagged lines. 39// If startLine > 0, numbering begins at startLine (1-indexed). 40func TagLines(content string, startLine int) []TaggedLine { 41 if startLine <= 0 { 42 startLine = 1 43 } 44 45 lines := strings.Split(content, "\n") 46 tagged := make([]TaggedLine, len(lines)) 47 for i, line := range lines { 48 tagged[i] = TaggedLine{ 49 Num: startLine + i, 50 Hash: LineHash(line), 51 Content: line, 52 } 53 } 54 return tagged 55} 56 57// FormatTagged formats tagged lines into the string returned to the LLM. 58func FormatTagged(tagged []TaggedLine) string { 59 var b strings.Builder 60 for i, t := range tagged { 61 if i > 0 { 62 b.WriteByte('\n') 63 } 64 b.WriteString(t.Tag()) 65 } 66 return b.String() 67} 68 69// HashMismatchError is returned when an anchor's hash doesn't match the actual file content. 70type HashMismatchError struct { 71 Line int 72 Expected string 73 Got string 74 Content string 75} 76 77func (e *HashMismatchError) Error() string { 78 return fmt.Sprintf("hash mismatch at line %d: expected %s, got %s — actual: %q (re-Read the file to get fresh hashes)", e.Line, e.Expected, e.Got, e.Content) 79} 80 81// Anchor identifies a line by number and hash. 82type Anchor struct { 83 Num int `json:"line"` 84 Hash string `json:"hash"` 85} 86 87// Validate checks that the anchor matches the actual file lines. 88// lines is 0-indexed; anchor.Num is 1-indexed. 89// On hash mismatch, it attempts to relocate by scanning for a unique 90// line with the expected hash. If found, a.Num is updated in place. 91func (a *Anchor) Validate(lines []string) error { 92 idx := a.Num - 1 93 if idx >= 0 && idx < len(lines) && LineHash(lines[idx]) == a.Hash { 94 return nil 95 } 96 if idx < 0 || idx >= len(lines) { 97 // Out of range — still try relocation before giving up. 98 if n, ok := relocate(lines, a.Hash); ok { 99 a.Num = n + 1 100 return nil 101 } 102 return fmt.Errorf("line %d out of range (file has %d lines)", a.Num, len(lines)) 103 } 104 // Hash mismatch — try relocation. 105 if n, ok := relocate(lines, a.Hash); ok { 106 a.Num = n + 1 107 return nil 108 } 109 return &HashMismatchError{ 110 Line: a.Num, 111 Expected: a.Hash, 112 Got: LineHash(lines[idx]), 113 Content: lines[idx], 114 } 115} 116 117// relocate scans lines for a unique match of hash. 118// Returns the 0-indexed line number if exactly one match is found. 119func relocate(lines []string, hash string) (int, bool) { 120 found := -1 121 for i, l := range lines { 122 if LineHash(l) == hash { 123 if found >= 0 { 124 return 0, false // duplicate — ambiguous 125 } 126 found = i 127 } 128 } 129 return found, found >= 0 130} 131 132// ValidateRange checks that start and end anchors are valid and ordered. 133// Anchors may be relocated in place on hash mismatch. 134func ValidateRange(lines []string, start, end *Anchor) error { 135 if err := start.Validate(lines); err != nil { 136 return fmt.Errorf("start anchor: %w", err) 137 } 138 if err := end.Validate(lines); err != nil { 139 return fmt.Errorf("end anchor: %w", err) 140 } 141 if start.Num > end.Num { 142 return fmt.Errorf("start line %d is after end line %d", start.Num, end.Num) 143 } 144 return nil 145} 146 147// ParseAnchor parses a "line:hash" string (e.g. "5:ab") into an Anchor. 148func ParseAnchor(s string) (Anchor, error) { 149 parts := strings.SplitN(s, ":", 2) 150 if len(parts) != 2 { 151 return Anchor{}, fmt.Errorf("invalid anchor %q: expected line:hash", s) 152 } 153 n, err := strconv.Atoi(parts[0]) 154 if err != nil { 155 return Anchor{}, fmt.Errorf("invalid anchor %q: bad line number", s) 156 } 157 h := parts[1] 158 if len(h) != HashLen { 159 return Anchor{}, fmt.Errorf("invalid anchor %q: hash must be %d hex chars", s, HashLen) 160 } 161 return Anchor{Num: n, Hash: h}, nil 162}