dsh-rwkv-plugin 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/cordis.patch.yml +59 -0
  4. package/lib/client.js +3148 -0
  5. package/lib/client.js.map +7 -0
  6. package/lib/index.js +6294 -0
  7. package/lib/index.js.map +7 -0
  8. package/lib/line-edit.js +1423 -0
  9. package/lib/line-edit.js.map +7 -0
  10. package/lib/todo.js +610 -0
  11. package/lib/todo.js.map +7 -0
  12. package/package.json +72 -4
  13. package/scripts/build.mjs +77 -0
  14. package/scripts/headless.ts +279 -0
  15. package/scripts/link-dsh.sh +31 -0
  16. package/scripts/relay-e2e.mjs +157 -0
  17. package/scripts/smoke.ts +116 -0
  18. package/scripts/state.ts +39 -0
  19. package/scripts/tokenizer-parity.ts +107 -0
  20. package/scripts/trace-stats.ts +33 -0
  21. package/src/adapter.ts +388 -0
  22. package/src/backend/generator.ts +221 -0
  23. package/src/backend/irwkv.ts +117 -0
  24. package/src/backend/lightning.ts +228 -0
  25. package/src/backend/stream.ts +97 -0
  26. package/src/client/AdapterPicker.tsx +264 -0
  27. package/src/client/DeveloperPanel.tsx +403 -0
  28. package/src/client/FoldNode.tsx +82 -0
  29. package/src/client/ModelCard.tsx +230 -0
  30. package/src/client/RwkvSettings.tsx +265 -0
  31. package/src/client/Segment.tsx +15 -0
  32. package/src/client/StatePicker.tsx +248 -0
  33. package/src/client/TraceFrames.tsx +462 -0
  34. package/src/client/TraceView.tsx +77 -0
  35. package/src/client/WirePanel.tsx +566 -0
  36. package/src/client/fields.tsx +362 -0
  37. package/src/client/index.tsx +109 -0
  38. package/src/client/styles.ts +277 -0
  39. package/src/client/traces-api.ts +222 -0
  40. package/src/client/url.ts +20 -0
  41. package/src/core/agent.ts +586 -0
  42. package/src/core/defaults.ts +51 -0
  43. package/src/core/dsh-prompt.ts +32 -0
  44. package/src/core/edit-modes/index.ts +108 -0
  45. package/src/core/edit-modes/line-edit.ts +793 -0
  46. package/src/core/edit-modes/literal.ts +26 -0
  47. package/src/core/edit-modes/shared.ts +213 -0
  48. package/src/core/edit-modes/tolerant.ts +558 -0
  49. package/src/core/fold-pairs.ts +407 -0
  50. package/src/core/fold-window.ts +563 -0
  51. package/src/core/line-edit.ts +33 -0
  52. package/src/core/parse.ts +290 -0
  53. package/src/core/policy.ts +500 -0
  54. package/src/core/prompt.ts +220 -0
  55. package/src/core/relay.ts +400 -0
  56. package/src/core/step-gates.ts +371 -0
  57. package/src/core/time-zone.ts +32 -0
  58. package/src/core/todo-state.ts +227 -0
  59. package/src/core/tolerant-edit.ts +14 -0
  60. package/src/core/tool-mappings.ts +209 -0
  61. package/src/core/tool-repairs.ts +255 -0
  62. package/src/core/tools.ts +162 -0
  63. package/src/core/worklist.ts +606 -0
  64. package/src/dsh-host.ts +48 -0
  65. package/src/edit-modes/folded-read-guard.ts +32 -0
  66. package/src/edit-modes/index.ts +26 -0
  67. package/src/edit-modes/line-edit.ts +154 -0
  68. package/src/edit-modes/literal.ts +9 -0
  69. package/src/edit-modes/observations.ts +234 -0
  70. package/src/edit-modes/syntax-check.ts +226 -0
  71. package/src/edit-modes/tolerant.ts +232 -0
  72. package/src/folded-read-guard.ts +6 -0
  73. package/src/history.ts +163 -0
  74. package/src/index.ts +287 -0
  75. package/src/line-edit.ts +15 -0
  76. package/src/live-wire.ts +133 -0
  77. package/src/paths.ts +91 -0
  78. package/src/relay-store.ts +59 -0
  79. package/src/result-budget.ts +225 -0
  80. package/src/routes.ts +324 -0
  81. package/src/session-setup.ts +150 -0
  82. package/src/syntax-check.ts +2 -0
  83. package/src/todo.ts +328 -0
  84. package/src/tokenizer.ts +48 -0
  85. package/src/tolerant-edit.ts +2 -0
  86. package/src/trace-stats.ts +225 -0
  87. package/src/traces.ts +289 -0
  88. package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
  89. package/vendor/rwkv-tokenizer/package.json +5 -0
  90. package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
  91. package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
  92. package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
@@ -0,0 +1,558 @@
1
+ // Pure engine and specification for `editMode: 'tolerant'` (default).
2
+ //
3
+ // Keeps the standard `{ file_path, old_string, new_string }` contract unchanged
4
+ // and resolves near-miss `old_string` regions through a strict-to-loose
5
+ // uniqueness ladder:
6
+ // 1. single-line leading-indent alignment (prevents partial-indent substring hits);
7
+ // 2. Unicode/trailing-space fuzzy match;
8
+ // 3. indentation-insensitive match;
9
+ // 4. blank-line-insensitive match;
10
+ // 5. inner-whitespace-insensitive match;
11
+ // 6. unique close match (>= 90% bigram Dice similarity) guarded by dual
12
+ // boundary anchors (>= 88% on both first and last lines + split-anchor
13
+ // omitted-middle detection so shortened blocks never slide across
14
+ // repetitive lines).
15
+ //
16
+ // Replacements are automatically re-indented to the file's indentation style,
17
+ // and unchanged context lines keep the file's exact bytes so recall drift in
18
+ // surrounding lines never reaches disk.
19
+
20
+ import type { EditModeSpec } from './literal.ts'
21
+
22
+ export const TOLERANT_EDIT_MODE: EditModeSpec = {
23
+ id: 'tolerant',
24
+ excludedTools: ['edit_lines'],
25
+ mountsEditLinesPlugin: false,
26
+ usesTolerantHook: true,
27
+ }
28
+
29
+ export type MatchLevel = 'fuzzy' | 'indentation' | 'blank-lines' | 'whitespace' | 'similar'
30
+
31
+ const LEVEL_TEXT: Readonly<Record<MatchLevel, string>> = {
32
+ fuzzy: 'after normalizing trailing whitespace/quotes',
33
+ indentation: 'ignoring indentation',
34
+ 'blank-lines': 'ignoring blank lines',
35
+ whitespace: 'ignoring whitespace differences',
36
+ similar: 'as the closest match',
37
+ }
38
+
39
+ export interface RegionMatch {
40
+ readonly level: MatchLevel
41
+ /** Character offsets in the LF-normalized file. */
42
+ readonly start: number
43
+ readonly end: number
44
+ /** 1-based inclusive line range. */
45
+ readonly firstLine: number
46
+ readonly lastLine: number
47
+ /** Aligned [oldText line, file line] pairs of the matched lines. */
48
+ readonly pairs: readonly (readonly [string, string])[]
49
+ /** Blank lines in the file skipped between consecutive matched pairs. */
50
+ readonly gaps?: readonly (readonly string[])[]
51
+ readonly midStart?: boolean
52
+ readonly midEnd?: boolean
53
+ readonly similarity?: number
54
+ }
55
+
56
+ export type RegionResult =
57
+ | { readonly kind: 'match'; readonly match: RegionMatch }
58
+ | { readonly kind: 'ambiguous'; readonly level: MatchLevel; readonly lines: readonly number[] }
59
+ | { readonly kind: 'none'; readonly closest?: { readonly firstLine: number; readonly lastLine: number; readonly similarity: number } }
60
+
61
+ export type ResolvedTolerantEdit =
62
+ | { readonly kind: 'exact' }
63
+ | { readonly kind: 'repaired'; readonly oldString: string; readonly newString: string; readonly note: string }
64
+ | { readonly kind: 'refused'; readonly message: string }
65
+
66
+ export const toLF = (text: string): string => text.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
67
+ const indentOf = (line: string): string => /^[ \t]*/.exec(line)![0]
68
+ const isBlank = (line: string): boolean => line.trim() === ''
69
+ const trimKey = (line: string): string => line.trim()
70
+ const spaceKey = (line: string): string => line.replace(/\s+/g, ' ').trim()
71
+
72
+ function normalizeFuzzyLine(line: string): string {
73
+ return line
74
+ .normalize('NFKC')
75
+ .trimEnd()
76
+ .replace(/[\u2018\u2019\u201A\u201B]/g, "'")
77
+ .replace(/[\u201C\u201D\u201E\u201F]/g, '"')
78
+ .replace(/[\u2010-\u2015\u2212]/g, '-')
79
+ .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, ' ')
80
+ }
81
+
82
+ function bigrams(text: string): Map<string, number> {
83
+ const map = new Map<string, number>()
84
+ for (let i = 0; i < text.length - 1; i++) {
85
+ const gram = text.slice(i, i + 2)
86
+ map.set(gram, (map.get(gram) ?? 0) + 1)
87
+ }
88
+ return map
89
+ }
90
+
91
+ /** Dice coefficient over character bigrams. */
92
+ export function similarity(a: string, b: string): number {
93
+ if (a === b) return 1
94
+ if (a.length < 2 || b.length < 2) return 0
95
+ const x = bigrams(a)
96
+ const y = bigrams(b)
97
+ let shared = 0
98
+ for (const [gram, count] of x) shared += Math.min(count, y.get(gram) ?? 0)
99
+ return (2 * shared) / (a.length - 1 + b.length - 1)
100
+ }
101
+
102
+ interface Lines {
103
+ readonly text: readonly string[]
104
+ readonly starts: readonly number[]
105
+ }
106
+
107
+ function splitLines(content: string): Lines {
108
+ const text = content.split('\n')
109
+ const starts: number[] = []
110
+ let offset = 0
111
+ for (const line of text) {
112
+ starts.push(offset)
113
+ offset += line.length + 1
114
+ }
115
+ return { text, starts }
116
+ }
117
+
118
+ function blankGaps(file: Lines, window: readonly number[]): string[][] {
119
+ return window.map((line, t) => (t === 0 ? [] : file.text.slice(window[t - 1]! + 1, line) as string[]))
120
+ }
121
+
122
+ /**
123
+ * Locate `oldText` in LF-normalized `content` under the strictest tolerance
124
+ * level that finds a match. A level with multiple hits stops immediately as
125
+ * `ambiguous` instead of falling through to looser matching.
126
+ */
127
+ export function findRegion(content: string, oldText: string): RegionResult {
128
+ const file = splitLines(content)
129
+ const oldLF = toLF(oldText)
130
+ const endsWithNewline = oldLF.endsWith('\n')
131
+ const old = (endsWithNewline ? oldLF.slice(0, -1) : oldLF).split('\n')
132
+
133
+ const levels: readonly {
134
+ readonly level: MatchLevel
135
+ readonly key: (line: string) => string
136
+ readonly skipBlank: boolean
137
+ readonly partial: boolean
138
+ }[] = [
139
+ { level: 'fuzzy', key: normalizeFuzzyLine, skipBlank: false, partial: false },
140
+ { level: 'indentation', key: trimKey, skipBlank: false, partial: true },
141
+ { level: 'blank-lines', key: trimKey, skipBlank: true, partial: true },
142
+ { level: 'whitespace', key: spaceKey, skipBlank: true, partial: false },
143
+ ]
144
+
145
+ for (const { level, key, skipBlank, partial } of levels) {
146
+ const oldIndex = old.map((_, i) => i).filter(i => !skipBlank || !isBlank(old[i]!))
147
+ if (oldIndex.length === 0 || oldIndex.every(i => isBlank(old[i]!))) return { kind: 'none' }
148
+ const pool = file.text.map((_, i) => i).filter(i => !skipBlank || !isBlank(file.text[i]!))
149
+ const oldKeys = oldIndex.map(i => key(old[i]!))
150
+ const found: RegionMatch[] = []
151
+
152
+ for (let p = 0; p + oldIndex.length <= pool.length; p++) {
153
+ const window = pool.slice(p, p + oldIndex.length)
154
+ if (!skipBlank && window[window.length - 1]! - window[0]! !== oldIndex.length - 1) continue
155
+ const fileKeys = window.map(i => key(file.text[i]!))
156
+ const single = oldKeys.length === 1
157
+ let ok = true
158
+ for (let t = 0; t < oldKeys.length && ok; t++) {
159
+ const fileKey = fileKeys[t]!
160
+ const oldKey = oldKeys[t]!
161
+ if (single) ok = partial ? oldKey.length > 0 && fileKey.includes(oldKey) : fileKey === oldKey
162
+ else if (t === 0 && partial) ok = fileKey.endsWith(oldKey) && oldKey.length > 0
163
+ else if (t === oldKeys.length - 1 && partial) ok = fileKey.startsWith(oldKey) && oldKey.length > 0
164
+ else ok = fileKey === oldKey
165
+ }
166
+ if (!ok) continue
167
+
168
+ const first = window[0]!
169
+ const last = window[window.length - 1]!
170
+ const firstLine = file.text[first]!
171
+ const lastLine = file.text[last]!
172
+ const oldFirst = old[oldIndex[0]!]!
173
+ const oldLast = old[oldIndex[oldIndex.length - 1]!]!
174
+ const pairs = oldIndex.map((i, t) => [old[i]!, file.text[window[t]!]!] as const)
175
+ const gaps = skipBlank ? blankGaps(file, window) : undefined
176
+
177
+ if (single && partial && key(firstLine) !== key(oldFirst)) {
178
+ const needle = oldFirst.trim()
179
+ for (let at = firstLine.indexOf(needle); at >= 0; at = firstLine.indexOf(needle, at + 1)) {
180
+ let end = file.starts[first]! + at + needle.length
181
+ if (endsWithNewline && at + needle.length === firstLine.length && first < file.text.length - 1) end += 1
182
+ found.push({
183
+ level,
184
+ start: file.starts[first]! + at,
185
+ end,
186
+ firstLine: first + 1,
187
+ lastLine: first + 1,
188
+ pairs,
189
+ midStart: true,
190
+ midEnd: true,
191
+ })
192
+ }
193
+ continue
194
+ }
195
+
196
+ const midStart = partial && key(firstLine) !== key(oldFirst)
197
+ const start = midStart ? file.starts[first]! + firstLine.trimEnd().length - oldFirst.trim().length : file.starts[first]!
198
+ const midEnd = partial && key(lastLine) !== key(oldLast)
199
+ let end = midEnd ? file.starts[last]! + indentOf(lastLine).length + oldLast.trim().length : file.starts[last]! + lastLine.length
200
+ if (!midEnd && endsWithNewline && last < file.text.length - 1) end += 1
201
+ found.push({
202
+ level,
203
+ start,
204
+ end,
205
+ firstLine: first + 1,
206
+ lastLine: last + 1,
207
+ pairs,
208
+ ...gaps ? { gaps } : {},
209
+ ...midStart ? { midStart } : {},
210
+ ...midEnd ? { midEnd } : {},
211
+ })
212
+ }
213
+
214
+ if (found.length === 1) return { kind: 'match', match: found[0]! }
215
+ if (found.length > 1) return { kind: 'ambiguous', level, lines: found.map(m => m.firstLine) }
216
+ }
217
+
218
+ return similarRegion(file, old)
219
+ }
220
+
221
+ /**
222
+ * Unique non-blank region with >= 0.9 average per-line similarity, anchored on
223
+ * both boundary lines (>= 0.88) and guarded against omitted-middle sliding.
224
+ */
225
+ function similarRegion(file: Lines, old: readonly string[]): RegionResult {
226
+ const oldLines = old.filter(line => !isBlank(line))
227
+ const pool = file.text.map((_, i) => i).filter(i => !isBlank(file.text[i]!))
228
+ const n = oldLines.length
229
+ if (n === 0 || pool.length < n) return { kind: 'none' }
230
+
231
+ const oldKeys = oldLines.map(spaceKey)
232
+ const fileKeys = pool.map(i => spaceKey(file.text[i]!))
233
+ const firstScores = fileKeys.map(line => similarity(oldKeys[0]!, line))
234
+ const lastScores = fileKeys.map(line => similarity(oldKeys[n - 1]!, line))
235
+
236
+ const scored: { p: number; score: number }[] = []
237
+ for (let p = 0; p + n <= pool.length; p++) {
238
+ if (firstScores[p]! < 0.5 && lastScores[p + n - 1]! < 0.5) continue
239
+ let total = 0
240
+ for (let t = 0; t < n; t++) {
241
+ total += t === 0 ? firstScores[p]! : t === n - 1 ? lastScores[p + t]! : similarity(oldKeys[t]!, fileKeys[p + t]!)
242
+ }
243
+ scored.push({ p, score: total / n })
244
+ }
245
+ scored.sort((a, b) => b.score - a.score)
246
+ const best = scored[0]
247
+ if (!best) return { kind: 'none' }
248
+
249
+ const runner = scored.find(entry => Math.abs(entry.p - best.p) >= n)
250
+ let first = pool[best.p]!
251
+ let last = pool[best.p + n - 1]!
252
+
253
+ // Omitted-middle sliding-window detection: if oldText's first line matches
254
+ // strictly better earlier (or last line later) while the opposite end anchors
255
+ // `best`, middle lines were left out of a repetitive block.
256
+ let splitAnchor = false
257
+ if (firstScores[best.p]! < 1) {
258
+ for (let q = Math.max(0, best.p - n); q < best.p; q++) {
259
+ if (firstScores[q]! >= 0.95 && firstScores[q]! > firstScores[best.p]! + 0.03) {
260
+ first = pool[q]!
261
+ splitAnchor = true
262
+ break
263
+ }
264
+ }
265
+ }
266
+ if (lastScores[best.p + n - 1]! < 1) {
267
+ for (let r = Math.min(pool.length - 1, best.p + 2 * n - 1); r > best.p + n - 1; r--) {
268
+ if (lastScores[r]! >= 0.95 && lastScores[r]! > lastScores[best.p + n - 1]! + 0.03) {
269
+ last = pool[r]!
270
+ splitAnchor = true
271
+ break
272
+ }
273
+ }
274
+ }
275
+
276
+ const anchorsOk = !splitAnchor && firstScores[best.p]! >= 0.88 && lastScores[best.p + n - 1]! >= 0.88
277
+ const closest = { firstLine: first + 1, lastLine: last + 1, similarity: best.score }
278
+ const singleLineHighConf = n === 1
279
+ && oldKeys[0]!.length >= 36
280
+ && best.score >= 0.95
281
+ && (!runner || runner.score <= best.score - 0.14)
282
+ const multiLineOk = n >= 2
283
+ && best.score >= 0.9
284
+ && anchorsOk
285
+ && (!runner || runner.score <= best.score - (n >= 3 && best.score >= 0.96 ? 0.06 : 0.1))
286
+ if (!singleLineHighConf && !multiLineOk) {
287
+ return { kind: 'none', ...best.score >= 0.5 ? { closest } : {} }
288
+ }
289
+
290
+ return {
291
+ kind: 'match',
292
+ match: {
293
+ level: 'similar',
294
+ start: file.starts[first]!,
295
+ end: file.starts[last]! + file.text[last]!.length,
296
+ firstLine: first + 1,
297
+ lastLine: last + 1,
298
+ pairs: oldLines.map((line, t) => [line, file.text[pool[best.p + t]!]!] as const),
299
+ gaps: blankGaps(file, pool.slice(best.p, best.p + n)),
300
+ similarity: best.score,
301
+ },
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Re-indent `text` from the model's indentation to the file's indentation using
307
+ * matched `[oldLine, fileLine]` pairs, converting spaces <-> tabs for deeper nesting.
308
+ */
309
+ export function reindent(text: string, indents: readonly (readonly [string, string])[]): string {
310
+ if (indents.every(([from, to]) => from === to)) return text
311
+ const map = new Map<string, string>()
312
+ for (const [from, to] of indents) if (!map.has(from)) map.set(from, to)
313
+ let spacesPerTab = 0
314
+ let tabToSpaces = 0
315
+ for (const [from, to] of indents) {
316
+ if (!spacesPerTab && /^ +$/.test(from) && /^\t+$/.test(to) && from.length % to.length === 0) spacesPerTab = from.length / to.length
317
+ if (!tabToSpaces && /^\t+$/.test(from) && /^ +$/.test(to) && to.length % from.length === 0) tabToSpaces = to.length / from.length
318
+ }
319
+ return text.split('\n').map(line => {
320
+ if (isBlank(line)) return line
321
+ const ws = indentOf(line)
322
+ const mapped = map.get(ws)
323
+ if (mapped !== undefined) return mapped + line.slice(ws.length)
324
+ const from = [...map.keys()].filter(key => ws.startsWith(key)).sort((a, b) => b.length - a.length)[0]
325
+ if (from === undefined) return line
326
+ let rest = ws.slice(from.length)
327
+ if (spacesPerTab) rest = rest.replace(new RegExp(` {${spacesPerTab}}`, 'g'), '\t')
328
+ if (tabToSpaces) rest = rest.replace(/\t/g, ' '.repeat(tabToSpaces))
329
+ return map.get(from)! + rest + line.slice(ws.length)
330
+ }).join('\n')
331
+ }
332
+
333
+ /**
334
+ * Fit `newText` onto a matched region: re-indents whole lines to the file's
335
+ * indentation and keeps unchanged context lines verbatim as the file has them.
336
+ */
337
+ export function fitReplacement(
338
+ newText: string,
339
+ match: Pick<RegionMatch, 'pairs' | 'gaps' | 'midStart' | 'midEnd'>,
340
+ ): { text: string; reindented: boolean; kept: number } {
341
+ const { pairs, gaps, midStart = false, midEnd = false } = match
342
+ const lines = toLF(newText).split('\n')
343
+ const last = lines.length - 1
344
+ if (midStart) {
345
+ const lead = indentOf(pairs[0]![0])
346
+ if (lines[0]!.startsWith(lead)) lines[0] = lines[0]!.slice(lead.length)
347
+ }
348
+ if (midEnd) {
349
+ const trail = /[ \t]*$/.exec(pairs[pairs.length - 1]![0])![0]
350
+ if (trail && lines[last]!.endsWith(trail)) lines[last] = lines[last]!.slice(0, -trail.length)
351
+ }
352
+ const from = midStart ? 1 : 0
353
+ const seen = new Map<string, number>()
354
+ for (const [oldLine] of pairs) seen.set(oldLine, (seen.get(oldLine) ?? 0) + 1)
355
+ const context = new Map<string, number>()
356
+ pairs.forEach(([oldLine], t) => {
357
+ if (t >= from && !(midEnd && t === pairs.length - 1) && !isBlank(oldLine) && seen.get(oldLine) === 1) {
358
+ context.set(oldLine, t)
359
+ }
360
+ })
361
+ const indents = pairs.slice(from).map(([oldLine, fileLine]) => [indentOf(oldLine), indentOf(fileLine)] as const)
362
+ const reindented = indents.some(([a, b]) => a !== b)
363
+ const body = lines.slice(from)
364
+ const moved = [...lines.slice(0, from), ...(reindented ? reindent(body.join('\n'), indents).split('\n') : body)]
365
+ let kept = 0
366
+ let lastContext = -1
367
+ const out: string[] = []
368
+ moved.forEach((line, i) => {
369
+ const t = i >= from && !(midEnd && i === last) ? context.get(lines[i]!) : undefined
370
+ if (t === undefined) {
371
+ out.push(line)
372
+ return
373
+ }
374
+ if (out.length > 0 && !isBlank(out[out.length - 1]!) && t > lastContext) out.push(...(gaps?.[t] ?? []))
375
+ const fileLine = pairs[t]![1]
376
+ if (fileLine.trim() !== lines[i]!.trim()) kept++
377
+ out.push(fileLine)
378
+ lastContext = t
379
+ })
380
+ return { text: out.join('\n'), reindented, kept }
381
+ }
382
+
383
+ const lineAt = (content: string, offset: number): number => content.slice(0, offset).split('\n').length
384
+
385
+ const numberedExcerpt = (content: string, first: number, last: number): string =>
386
+ content.split('\n').slice(first - 1, last).map((line, i) => `${first + i}: ${line}`).join('\n')
387
+
388
+ function isSingleIndentedLine(oldText: string, newText: string): boolean {
389
+ const old = toLF(oldText)
390
+ const body = old.endsWith('\n') ? old.slice(0, -1) : old
391
+ return /^[ \t]/.test(body) && !body.includes('\n') && (old !== body || toLF(newText).includes('\n'))
392
+ }
393
+
394
+ function hasAllLineNumberPrefixes(text: string): boolean {
395
+ const nonEmpty = text.split('\n').filter(line => line !== '')
396
+ return nonEmpty.length > 0
397
+ && nonEmpty.every(line => /^\s*\d+: ?/.test(line))
398
+ && nonEmpty.some(line => /^\s*\d+: /.test(line))
399
+ }
400
+
401
+ function stripLineNumberPrefixes(text: string): string {
402
+ return text.split('\n').map(line => (line === '' ? '' : line.replace(/^\s*\d+: ?/, ''))).join('\n')
403
+ }
404
+
405
+ /**
406
+ * Resolve a single `{ oldString, newString }` edit against `rawContent`,
407
+ * preserving CRLF when present. Exact unique matches return `{ kind: 'exact' }`.
408
+ */
409
+ export function resolveTolerantEdit(
410
+ rawContent: string,
411
+ oldString: string,
412
+ newString: string,
413
+ displayPath: string,
414
+ ): ResolvedTolerantEdit {
415
+ if (oldString === '') return { kind: 'exact' }
416
+ const eol = rawContent.includes('\r\n') ? '\r\n' : '\n'
417
+ const restoreEol = (lf: string): string => (eol === '\r\n' ? lf.replace(/\n/g, '\r\n') : lf)
418
+ const content = toLF(rawContent.startsWith('\uFEFF') ? rawContent.slice(1) : rawContent)
419
+ const oldLF = toLF(oldString)
420
+ const newLF = toLF(newString)
421
+
422
+ // Widen a single indented line whose leading whitespace drifted short, so a
423
+ // multi-line replacement does not land under-indented inside the line's indent.
424
+ if (isSingleIndentedLine(oldLF, newLF)) {
425
+ const at = content.indexOf(oldLF)
426
+ if (at >= 0 && content.indexOf(oldLF, at + 1) < 0) {
427
+ const prefix = content.slice(content.lastIndexOf('\n', at - 1) + 1, at)
428
+ if (/^[ \t]+$/.test(prefix)) {
429
+ const line = oldLF.endsWith('\n') ? oldLF.slice(0, -1) : oldLF
430
+ const { text } = fitReplacement(newLF, { pairs: [[line, prefix + line]] })
431
+ return {
432
+ kind: 'repaired',
433
+ oldString: restoreEol(prefix + oldLF),
434
+ newString: restoreEol(text),
435
+ note: `Matched the edit at line ${lineAt(content, at)} of ${displayPath} ignoring indentation; re-indented the replacement to the file.`,
436
+ }
437
+ }
438
+ }
439
+ }
440
+
441
+ const exactAt = content.indexOf(oldLF)
442
+ if (exactAt >= 0) {
443
+ if (content.indexOf(oldLF, exactAt + 1) >= 0) {
444
+ const hitLines: number[] = []
445
+ let pos = exactAt
446
+ while (pos >= 0 && hitLines.length < 16) {
447
+ hitLines.push(lineAt(content, pos))
448
+ pos = content.indexOf(oldLF, pos + Math.max(1, oldLF.length))
449
+ }
450
+ const shown = hitLines.slice(0, 8).join(', ')
451
+ return {
452
+ kind: 'refused',
453
+ message: `Could not apply edit in ${displayPath}: old_string matched multiple places (lines ${shown}${hitLines.length > 8 ? ', ...' : ''}). `
454
+ + 'Include surrounding lines in old_string so it matches uniquely, or set replace_all: true if every occurrence should change.',
455
+ }
456
+ }
457
+ return eol === '\r\n' && (!oldString.includes('\r\n') || (newString.includes('\n') && !newString.includes('\r\n')))
458
+ ? {
459
+ kind: 'repaired',
460
+ oldString: restoreEol(oldLF),
461
+ newString: restoreEol(newLF),
462
+ note: `Matched the edit in ${displayPath} normalizing CRLF line endings.`,
463
+ }
464
+ : { kind: 'exact' }
465
+ }
466
+
467
+ // Strip accidental `123: ` line-number prefixes copied from `read` output.
468
+ let effectiveOldLF = oldLF
469
+ let effectiveNewLF = newLF
470
+ let strippedPrefixes = false
471
+ if (hasAllLineNumberPrefixes(oldLF) && !content.includes(oldLF)) {
472
+ const candidateOld = stripLineNumberPrefixes(oldLF)
473
+ if (candidateOld.trim() !== '') {
474
+ effectiveOldLF = candidateOld
475
+ strippedPrefixes = true
476
+ if (hasAllLineNumberPrefixes(newLF)) {
477
+ effectiveNewLF = stripLineNumberPrefixes(newLF)
478
+ }
479
+ const strippedAt = content.indexOf(effectiveOldLF)
480
+ if (strippedAt >= 0 && content.indexOf(effectiveOldLF, strippedAt + 1) < 0) {
481
+ if (effectiveOldLF === effectiveNewLF) {
482
+ return {
483
+ kind: 'refused',
484
+ message: `Could not apply edit in ${displayPath}: old_string and new_string are identical after stripping line-number prefixes.`,
485
+ }
486
+ }
487
+ return {
488
+ kind: 'repaired',
489
+ oldString: restoreEol(effectiveOldLF),
490
+ newString: restoreEol(effectiveNewLF),
491
+ note: `Matched the edit at line ${lineAt(content, strippedAt)} of ${displayPath} after stripping line-number prefixes.`,
492
+ }
493
+ }
494
+ }
495
+ }
496
+
497
+ const result = findRegion(content, effectiveOldLF)
498
+ if (result.kind === 'match') {
499
+ const { match } = result
500
+ const exact = content.slice(match.start, match.end)
501
+ const fit = fitReplacement(effectiveNewLF, match)
502
+ const range = match.firstLine === match.lastLine ? `line ${match.firstLine}` : `lines ${match.firstLine}-${match.lastLine}`
503
+ if (fit.text === exact) {
504
+ return {
505
+ kind: 'refused',
506
+ message: `Could not apply edit in ${displayPath}: old_string already contains the modified text instead of the current file text at ${range}. `
507
+ + `Copy old_string from these exact lines:\n${exact}`,
508
+ }
509
+ }
510
+ let note = `Matched the edit at ${range} of ${displayPath} ${LEVEL_TEXT[match.level]}`
511
+ if (strippedPrefixes) note += ' after stripping line-number prefixes'
512
+ if (match.similarity !== undefined) note += ` (${Math.round(match.similarity * 100)}% similar)`
513
+ if (fit.reindented) note += '; re-indented the replacement to the file'
514
+ if (fit.kept > 0) note += `; kept ${fit.kept} unchanged line(s) as the file has them`
515
+ note += '.'
516
+ if (match.level === 'similar') note += ` Replaced text:\n${exact}`
517
+ return {
518
+ kind: 'repaired',
519
+ oldString: restoreEol(exact),
520
+ newString: restoreEol(fit.text),
521
+ note,
522
+ }
523
+ }
524
+
525
+ if (result.kind === 'none' && result.closest && effectiveNewLF.trim().length >= 8) {
526
+ const present = findRegion(content, effectiveNewLF)
527
+ const { firstLine, lastLine } = result.closest
528
+ if (present.kind === 'match' && present.match.level !== 'similar' && present.match.firstLine <= lastLine && present.match.lastLine >= firstLine) {
529
+ return {
530
+ kind: 'refused',
531
+ message: `No edit needed in ${displayPath}: old_string is not in the file, and new_string is already present (line ${present.match.firstLine}). `
532
+ + 'This change is already applied; do not repeat this edit. Continue with any remaining changes, or answer the user directly if all work is done.',
533
+ }
534
+ }
535
+ }
536
+
537
+ if (result.kind === 'ambiguous') {
538
+ return {
539
+ kind: 'refused',
540
+ message: `Could not apply edit in ${displayPath}: when ${LEVEL_TEXT[result.level]}, old_string matches ${result.lines.length} places `
541
+ + `(lines ${result.lines.slice(0, 8).join(', ')}). Include more surrounding lines so it matches uniquely.`,
542
+ }
543
+ }
544
+
545
+ let message = `Could not find old_string in ${displayPath}.`
546
+ if (result.closest) {
547
+ const { firstLine, lastLine, similarity: score } = result.closest
548
+ const totalLines = content.split('\n').length
549
+ const ctxFirst = Math.max(1, firstLine - 2)
550
+ const ctxLast = Math.min(totalLines, lastLine + 2)
551
+ message += ` The closest text is lines ${firstLine}-${lastLine} (${Math.round(score * 100)}% similar). `
552
+ + `Current file around lines ${ctxFirst}-${ctxLast} (verify these are the intended lines before editing):\n`
553
+ + numberedExcerpt(content, ctxFirst, ctxLast)
554
+ } else {
555
+ message += ` Nothing similar was found; read ${displayPath} first to inspect its current content.`
556
+ }
557
+ return { kind: 'refused', message }
558
+ }