summaryrefslogtreecommitdiff
path: root/llm-tools-hl.el
blob: b4ca40aaf67d0767147590ab3f40e3cc31dbaa0e (plain)
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
(defvar llm-tools--hl-bigrams
  (list "aa" "ab" "ac" "ad" "ae" "af" "ag" "ah" "ai" "aj" "ak" "al" "am" "an"
	"ao" "ap" "aq" "ar" "as" "at" "au" "av" "aw" "ax" "ay" "az" "ba" "bb"
	"bc" "bd" "be" "bf" "bg" "bh" "bi" "bj" "bk" "bl" "bm" "bn" "bo" "bp"
	"br" "bs" "bt" "bu" "bv" "bw" "bx" "by" "bz" "ca" "cb" "cc" "cd" "ce"
	"cf" "cg" "ch" "ci" "cj" "ck" "cl" "cm" "cn" "co" "cp" "cq" "cr" "cs"
	"ct" "cu" "cv" "cw" "cx" "cy" "cz" "da" "db" "dc" "dd" "de" "df" "dg"
	"dh" "di" "dj" "dk" "dl" "dm" "dn" "do" "dp" "dq" "dr" "ds" "dt" "du"
	"dv" "dw" "dx" "dy" "dz" "ea" "eb" "ec" "ed" "ee" "ef" "eg" "eh" "ei"
	"ej" "ek" "el" "em" "en" "eo" "ep" "eq" "er" "es" "et" "eu" "ev" "ew"
	"ex" "ey" "ez" "fa" "fb" "fc" "fd" "fe" "ff" "fg" "fh" "fi" "fj" "fk"
	"fl" "fm" "fn" "fo" "fp" "fq" "fr" "fs" "ft" "fu" "fv" "fw" "fx" "fy"
	"fz" "ga" "gb" "gc" "gd" "ge" "gf" "gg" "gh" "gi" "gj" "gl" "gm" "gn"
	"go" "gp" "gr" "gs" "gt" "gu" "gv" "gw" "gx" "gy" "gz" "ha" "hb" "hc"
	"hd" "he" "hf" "hg" "hh" "hi" "hj" "hk" "hl" "hm" "hn" "ho" "hp" "hq"
	"hr" "hs" "ht" "hu" "hv" "hw" "hx" "hy" "hz" "ia" "ib" "ic" "id" "ie"
	"if" "ig" "ih" "ii" "ij" "ik" "il" "im" "in" "io" "ip" "iq" "ir" "is"
	"it" "iu" "iv" "iw" "ix" "iy" "iz" "ja" "jb" "jc" "jd" "je" "jf" "jg"
	"jh" "ji" "jj" "jk" "jl" "jm" "jn" "jo" "jp" "jq" "jr" "js" "jt" "ju"
	"jw" "jx" "jy" "ka" "kb" "kc" "kd" "ke" "kf" "kg" "kh" "ki" "kj" "kk"
	"kl" "km" "kn" "ko" "kp" "kr" "ks" "kt" "ku" "kv" "kw" "kx" "ky" "la"
	"lb" "lc" "ld" "le" "lf" "lg" "lh" "li" "lj" "lk" "ll" "lm" "ln" "lo"
	"lp" "lr" "ls" "lt" "lu" "lv" "lw" "lx" "ly" "lz" "ma" "mb" "mc" "md"
	"me" "mf" "mg" "mh" "mi" "mj" "mk" "ml" "mm" "mn" "mo" "mp" "mq" "mr"
	"ms" "mt" "mu" "mv" "mw" "mx" "my" "mz" "na" "nb" "nc" "nd" "ne" "nf"
	"ng" "nh" "ni" "nj" "nk" "nl" "nm" "nn" "no" "np" "nr" "ns" "nt" "nu"
	"nv" "nw" "nx" "ny" "nz" "oa" "ob" "oc" "od" "oe" "of" "og" "oh" "oi"
	"oj" "ok" "ol" "om" "on" "oo" "op" "oq" "or" "os" "ot" "ou" "ov" "ow"
	"ox" "oy" "oz" "pa" "pb" "pc" "pd" "pe" "pf" "pg" "ph" "pi" "pj" "pk"
	"pl" "pm" "pn" "po" "pp" "pq" "pr" "ps" "pt" "pu" "pv" "pw" "px" "py"
	"pz" "qa" "qb" "qc" "qd" "qe" "qh" "qi" "ql" "qm" "qn" "qo" "qp" "qq"
	"qr" "qs" "qt" "qu" "qw" "qx" "qy" "ra" "rb" "rc" "rd" "re" "rf" "rg"
	"rh" "ri" "rk" "rl" "rm" "rn" "ro" "rp" "rq" "rr" "rs" "rt" "ru" "rv"
	"rw" "rx" "ry" "rz" "sa" "sb" "sc" "sd" "se" "sf" "sg" "sh" "si" "sj"
	"sk" "sl" "sm" "sn" "so" "sp" "sq" "sr" "ss" "st" "su" "sv" "sw" "sx"
	"sy" "sz" "ta" "tb" "tc" "td" "te" "tf" "tg" "th" "ti" "tj" "tk" "tl"
	"tm" "tn" "to" "tp" "tr" "ts" "tt" "tu" "tv" "tw" "tx" "ty" "tz" "ua"
	"ub" "uc" "ud" "ue" "uf" "ug" "uh" "ui" "uj" "uk" "ul" "um" "un" "uo"
	"up" "uq" "ur" "us" "ut" "uu" "uv" "uw" "ux" "uy" "uz" "va" "vb" "vc"
	"vd" "ve" "vf" "vg" "vh" "vi" "vj" "vk" "vl" "vm" "vn" "vo" "vp" "vq"
	"vr" "vs" "vt" "vu" "vv" "vw" "vx" "vy" "vz" "wa" "wb" "wc" "wd" "we"
	"wf" "wg" "wh" "wi" "wj" "wk" "wl" "wm" "wn" "wo" "wp" "wr" "ws" "wt"
	"wu" "wv" "ww" "wx" "wy" "xa" "xb" "xc" "xd" "xe" "xf" "xh" "xi" "xl"
	"xm" "xn" "xo" "xp" "xr" "xs" "xt" "xu" "xx" "xy" "xz" "ya" "yb" "yc"
	"yd" "ye" "yf" "yg" "yh" "yi" "yj" "yk" "yl" "ym" "yn" "yo" "yp" "yr"
	"ys" "yt" "yu" "yv" "yw" "yx" "yy" "yz" "za" "zb" "zc" "zd" "ze" "zf"
	"zg" "zh" "zi" "zk" "zl" "zm" "zn" "zo" "zp" "zr" "zs" "zt" "zu" "zw"
	"zx" "zy" "zz")
  "List of bigrams for use with hashline reads/writes.

Each of the bigrams resolve to a single token in standard LLM
vocabulary, unlike a hash's hex digits.

Taken from https://github.com/can1357/oh-my-pi.
Precisely: https://raw.githubusercontent.com/can1357/oh-my-pi/85003ca/packages/coding-agent/src/hashline/bigrams.json")

(defun llm-tools--hl-hash (line)
  ;; logand is to force unsigned number
  (elt llm-tools--hl-bigrams (% (logand (sxhash line) #xffffffff) 647)))

(defun llm-tools--hl-file-lines (file &optional beg end)
  "Return FILE contents as a list of strings.
With optional BEG and END (inclusive, 1-based), return the lines between that range."
  (with-temp-buffer
    (insert-file-contents-literally file)
    (let ((lines (string-lines (buffer-string))))
      (if beg
	  (cl-subseq lines (1- beg) end)
	lines))))

(defun llm-tools--hl-format-lines (lines &optional start include-content?)
  "Format LINES in hashline format.
START is 1-based (default 1).
If INCLUDE-CONTENT is non-nil, append `|LINE' after each hash."
  (string-join
   (cl-mapcar (lambda (line i)
		(if include-content?
		    (format "%d%2s|%s" i (llm-tools--hl-hash line) line)
		  (format "%d%2s" i (llm-tools--hl-hash line))))
	      lines
	      (number-sequence (or start 1) (+ (or start 1) (1- (length lines)))))
   "\n"))

(defun llm-tools--hl-file-read (file)
  "Return FILE contents in hashline format."
  (llm-tools--hl-format-lines (llm-tools--hl-file-lines file) nil t))

(defun llm-tools--hl-file-read-range (file beg end)
  "Return FILE contents in hashline format from lines BEG to END."
  (llm-tools--hl-format-lines (llm-tools--hl-file-lines file beg end) beg t))

(defun llm-tools--hl-file-read-hashes (file)
  "Return FILE contents as a list of hashline strings without line content.
Each element is a line number and two-character hash, like `1vx'."
  (string-lines (llm-tools--hl-format-lines (llm-tools--hl-file-lines file))))

(defun llm-tools--hl-file-line-hash (file n)
  "Return the hash of the Nth line in FILE."
  (let ((lines (llm-tools--hl-file-lines file)))
      (llm-tools--hl-hash (elt lines (1- n)))))

;;;; Diff Parsing
(defun llm-tools--split-patch-sections (patch)
  "Return a list of (FILENAME . REST) cons cells from PATCH.
Each section starts with '@@ PATH' on the first line; the car is PATH
and the cdr is the remainder of that section."
  (let ((pos (string-match "^@@" patch)))
    (when pos
      (let (sections
            (start pos))
        (while (string-match "\n@@" patch (1+ pos))
          (let ((nl (match-beginning 0)))
            (push (substring patch start (1+ nl)) sections)
            (setq start (1+ nl)))
          (setq pos (match-end 0)))
        (push (substring patch start) sections)
        (mapcar (lambda (sec)
                  (let ((end (string-match "\n" sec)))
                    (cons (substring sec 3 end)
                          (substring sec end))))
                (nreverse sections))))))

(defun llm-tools--hl-get-anchors (patch)
  "Returns an alist of (FILENAME . ANCHORS) from PATCH.
ANCHORS is a sorted, deduplicated list of all line anchors referenced by
the operations in that file's sections.  Each anchor is a string like
\"5ff\" or a list of two strings from a range like
(\"3gv\" \"6be\")."
  (let ((sections (split-patch-sections patch)))
    (delete-dups
     (mapcar (lambda (patch)
	       (cons (car patch)
		     (delete-dups
		      (sort
		       (flatten-list
			(mapcar (lambda (line)
				  (if (length> line 0)
				      (let ((op (char-to-string (elt line 0)))
					    (anchor (substring line 2)))
					(pcase op
					  ((or "+" "<") anchor)
					  ((or "-" "=") (split-string anchor "\\.\\."))))))
				(string-lines (cdr patch))))))))
	     sections))))

(defun llm-tools--hl-verify-anchors (patch)
  "Verify that all anchors in PATCH match the current file contents.
Returns a list of booleans, one per file, indicating whether every
anchor in that file's patch sections still matches the corresponding
line in the on-disk file."
  (let ((patch-anchors (llm-tools--hl-get-anchors patch)))
    (mapcar (lambda (section)
	      (let* ((file (car section))
		     (anchors (delete "EOF" (cdr section)))
		     (hl (llm-tools--hl-file-read-hashes file)))
		;; cl-subsetp uses eql by default which compares by identity and not content
		(cons file (cl-subsetp anchors hl :test #'equal))))
	    patch-anchors)))

(defun llm-tools--hl-verify (patch)
  "Verify if the files in PATCH need to be re-read.
Returns a string message that states which files need to be re-read.
Empty string means no files need to be re-read."
  (string-join
   (delete-dups
    (remq nil
	  (mapcar (lambda (elem)
		    (unless (cdr elem)
		      (format "%s had incorrect anchors. Use the 'read_file' tool to get correct anchors."
			      (car elem))))
		  (llm-tools--hl-verify-anchors patch))))
   "\n"))

(defun llm-tools--hl-parse-section (section)
  "Parses operation and optional payload from SECTION."
  )

(defun llm-tools--hl-apply (patch)
  "TODO rewrite docstring. Applies a patch."
  ;; when performing each operation, I need to make sure that the line
  ;; numbers of subsequent operations in same file also get updated.
  (let ((sections (split-patch-sections patch)))
    (llm-tools--hl-parse sections)))

(defun llm-tools--hl-edit (patch)
  "TODO write better docstring. First verifies if any files in PATCH needs
to be re-read. Then, applies the changes in PATCH. If any files need to
be re-read, the edit operation is cancelled for all files."
  (let ((msg (llm-tools--hl-verify patch)))
    (if (string= msg "")
	(progn
	  (llm-tools--hl-apply patch)
	  (format "Finished applying patch."))
      (format "%s" msg))))

(let* ((patch "\
# Replace one line (the payload must re-emit the original indentation)
@@ mod.ts
= 1vx..1vx
~const TITLE = \"Mrs\";

# Replace a full multiline statement (widen to a self-contained boundary)
@@ mod.ts
= 3gv..6be
~	return [
~		\"Mrs\",
~		name?.trim() || \"guest\",
~	].join(\" \");

# Insert AFTER/BEFORE a line
@@ mod.ts
+ 4ei
~		\"Dr\",
< 5ff
~		\"Dr\",

# Append to file
@@ mod.ts
+ EOF
~export const done = true;

# Delete a line
@@ mod.ts
- 5ff..5ff

# Blank a line (replace with LF)
@@ mod.ts
= 5ff..5ff
"))
  (llm-tools--hl-apply patch))

(provide 'llm-tools-hl)