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,793 @@
1
+ // Pure engine, wire mapping, and argument aliases for `editMode: 'line-edit'`
2
+ // (Anchored Batch Line-Edit v2).
3
+ //
4
+ // Designed for RWKV-7's linear-state physics (empirically benchmarked on raw
5
+ // rwkv7-g1l-7.2b):
6
+ // - Semantic single-line anchors (`start_text`, optional `end_text`) achieve
7
+ // ~100% recall across long windows + noise, whereas bare integer line
8
+ // numbers drift by ±1..±5 lines (~93.5% silent corruption without anchors)
9
+ // and 2-hex hashline prefixes get 0% recall while destroying line tracking.
10
+ // - 3-tier self-healing:
11
+ // L1: exact `start_line` match (score >= 0.90)
12
+ // L2: local ±15 line window unique relocation (exact >= 0.98 strictly
13
+ // beats fuzzy runner-ups; >=2 local exact hits abort as ambiguous)
14
+ // L3: whole-file unique fallback for non-trivial anchors (trimmed len >= 10)
15
+ // - Atomic multi-hunk `edits[]`: all hunks resolved in pre-edit coordinates,
16
+ // overlap-checked, applied bottom-up, and syntax-checked once before write.
17
+ // - Defensive guards: auto-reindent on anchor indent drift, copied `N: ` line
18
+ // prefix stripping, elision placeholder guard (`...`), no-op guard,
19
+ // boundary duplication guard, and ±8 numbered context on error.
20
+ // - 100% backward compatible with single-hunk `{ start_line, end_line, new_text }`.
21
+
22
+ import type { EditModeSpec } from './literal.ts'
23
+ import {
24
+ joinDocumentLines,
25
+ pluralLines,
26
+ renderWindow,
27
+ splitDocumentLines,
28
+ type LineEdit,
29
+ type LineEditResult,
30
+ } from './shared.ts'
31
+ import { reindent, similarity } from './tolerant.ts'
32
+
33
+ /** Empirically verified RWKV-7 line-number fidelity ceiling (95.7% ±5 recall <=200 lines; 0% at 320 lines). */
34
+ export const MAX_LINE_EDIT_READ_LINES = 200
35
+
36
+ export const LINE_EDIT_MODE: EditModeSpec = {
37
+ id: 'line-edit',
38
+ excludedTools: [],
39
+ mountsEditLinesPlugin: true,
40
+ maxReadLines: MAX_LINE_EDIT_READ_LINES,
41
+ usesTolerantHook: false,
42
+ }
43
+
44
+ export const LINE_EDIT_CONTEXT_LINES = 3
45
+ const ANCHOR_SEARCH_RADIUS = 15
46
+ const END_ANCHOR_SEARCH_RADIUS = 10
47
+ const ERROR_WINDOW_RADIUS = 8
48
+ const MIN_WHOLE_FILE_ANCHOR_LEN = 10
49
+
50
+ const PATH_ALIASES = ['file_path', 'filepath', 'file', 'filename', 'file_name'] as const
51
+ const NATIVE_PATH_ALIASES = ['path', 'filepath', 'file', 'filename', 'file_name'] as const
52
+
53
+ export const LINE_EDIT_WIRE_SCHEMA: Record<string, unknown> = {
54
+ properties: {
55
+ path: { type: 'string' },
56
+ edits: {
57
+ type: 'array',
58
+ items: {
59
+ type: 'object',
60
+ properties: {
61
+ start_line: { type: 'integer' },
62
+ end_line: { type: 'integer' },
63
+ start_text: { type: 'string' },
64
+ end_text: { type: 'string' },
65
+ new_text: { type: 'string' },
66
+ },
67
+ },
68
+ },
69
+ start_line: { type: 'integer' },
70
+ end_line: { type: 'integer' },
71
+ start_text: { type: 'string' },
72
+ end_text: { type: 'string' },
73
+ new_text: { type: 'string' },
74
+ },
75
+ }
76
+
77
+ /**
78
+ * Canonical flat placeholder rendered for `edit_lines` under `toolNames: 'dsh'`.
79
+ * Keeps the nested `edits[]` hunk structure explicit instead of flattening it
80
+ * into `"optional array of object"` via generic JSON-schema summarization.
81
+ */
82
+ export const LINE_EDIT_DSH_WIRE_ARGUMENTS =
83
+ '{"file_path":"path to edit (read the file first)","edits":[{"start_line":"1-based first line","end_line":"1-based last line (start_line - 1 inserts)","start_text":"original text at start_line without line number","end_text":"optional original text at end_line","new_text":"replacement lines without line numbers (empty deletes)"}]}'
84
+
85
+ export const LINE_EDIT_TRAINED_ALIASES: Readonly<Record<string, readonly string[]>> = {
86
+ path: PATH_ALIASES,
87
+ start_line: ['startLine', 'line_start', 'from_line', 'start', 'line'],
88
+ end_line: ['endLine', 'line_end', 'to_line', 'end'],
89
+ start_text: ['startText', 'anchor', 'start_anchor', 'first_line'],
90
+ end_text: ['endText', 'end_anchor', 'last_line'],
91
+ new_text: ['newText', 'new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],
92
+ }
93
+
94
+ export const LINE_EDIT_NATIVE_ALIASES: Readonly<Record<string, readonly string[]>> = {
95
+ file_path: NATIVE_PATH_ALIASES,
96
+ start_line: ['startLine', 'line_start', 'from_line', 'start', 'line', 'offset'],
97
+ end_line: ['endLine', 'line_end', 'to_line', 'end'],
98
+ start_text: ['startText', 'anchor', 'start_anchor', 'first_line'],
99
+ end_text: ['endText', 'end_anchor', 'last_line'],
100
+ new_text: ['newText', 'new_string', 'new_str', 'text', 'content', 'replacement', 'lines'],
101
+ }
102
+
103
+ export interface RawLineEditHunk {
104
+ readonly start_line: number
105
+ readonly end_line: number
106
+ readonly start_text?: string
107
+ readonly end_text?: string
108
+ readonly new_text: string
109
+ }
110
+
111
+ export interface ResolvedLineEdit {
112
+ readonly index: number
113
+ readonly requestedStart: number
114
+ readonly requestedEnd: number
115
+ readonly startLine: number
116
+ readonly endLine: number
117
+ readonly newLines: readonly string[]
118
+ readonly removed: number
119
+ readonly added: number
120
+ readonly strippedLineNumbers: boolean
121
+ readonly reindented: boolean
122
+ readonly alignedNote?: string
123
+ readonly anchorVerified: boolean
124
+ readonly endAnchorVerified: boolean
125
+ }
126
+
127
+ export interface BatchLineEditResult {
128
+ readonly content: string
129
+ readonly before: readonly string[]
130
+ readonly after: readonly string[]
131
+ readonly hunks: readonly ResolvedLineEdit[]
132
+ readonly totalRemoved: number
133
+ readonly totalAdded: number
134
+ }
135
+
136
+ export interface ApplyLineEditsOptions {
137
+ /** Enable ±15 local and whole-file unique `start_text` self-healing + indent alignment (default true). */
138
+ readonly selfHeal?: boolean
139
+ }
140
+
141
+ // --- Normalization & anchor helpers -----------------------------------------
142
+
143
+ const TRIVIAL_ANCHORS = new Set([
144
+ '{', '}', '(', ')', '[', ']', '},', '],', ');', '};',
145
+ 'else:', 'else {', '} else {', 'try:', 'try {', 'finally:', 'finally {',
146
+ 'pass', 'break', 'continue', 'return', 'return;', 'return None', 'return true', 'return false',
147
+ 'end', 'fi', 'done', 'esac',
148
+ ])
149
+
150
+ const ELISION_LINE = /^\s*(?:\/\/|#|\/\*|--|<!--)?\s*(?:\.\.\.|…)\s*(?:existing|unchanged|rest|remaining|omitted|same|code|lines|more|snip|truncated)?[^\n]{0,40}(?:\*\/|-->)?\s*$/i
151
+
152
+ const NUMBERED_PREFIX = /^(\d+): ?(.*)$/
153
+
154
+ function indentOf(line: string): string {
155
+ return /^[ \t]*/.exec(line)?.[0] ?? ''
156
+ }
157
+
158
+ function normalizeAnchorLine(line: string): string {
159
+ return line
160
+ .normalize('NFKC')
161
+ .replace(/[\u2018\u2019\u201A\u201B]/g, "'")
162
+ .replace(/[\u201C\u201D\u201E\u201F]/g, '"')
163
+ .replace(/[\u2010-\u2015\u2212]/g, '-')
164
+ .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, ' ')
165
+ .replace(/\s+/g, ' ')
166
+ .trim()
167
+ }
168
+
169
+ function stripOptionalLinePrefix(text: string): string {
170
+ const m = /^\s*\d+:\s?(.*)$/.exec(text)
171
+ return m ? m[1]! : text
172
+ }
173
+
174
+ /** True when `anchor` carries enough semantic content to uniquely verify a target line. */
175
+ export function isNonTrivialAnchor(anchor: string | undefined, minLen = 8): boolean {
176
+ if (typeof anchor !== 'string') return false
177
+ const cleaned = normalizeAnchorLine(stripOptionalLinePrefix(anchor))
178
+ if (cleaned.length < minLen) return false
179
+ if (TRIVIAL_ANCHORS.has(cleaned)) return false
180
+ return /[A-Za-z0-9_\u4e00-\u9fff]{3,}/.test(cleaned)
181
+ }
182
+
183
+ function lineAnchorScore(anchor: string, fileLine: string): number {
184
+ const raw = stripOptionalLinePrefix(anchor)
185
+ const a = normalizeAnchorLine(raw)
186
+ const b = normalizeAnchorLine(fileLine)
187
+ if (a === '' && b === '') return 1
188
+ if (a === '' || b === '') return 0
189
+ if (a === b) return 1
190
+ // Allow truncated prefix anchors (model quoted first >= 16 chars of a long line).
191
+ if (a.length >= 16 && b.startsWith(a)) return 0.96
192
+ return similarity(a, b)
193
+ }
194
+
195
+ function newLinesOf(text: string): string[] {
196
+ if (text === '') return []
197
+ const normalized = text.replace(/\r\n/g, '\n')
198
+ return (normalized.endsWith('\n') ? normalized.slice(0, -1) : normalized).split('\n')
199
+ }
200
+
201
+ /**
202
+ * Strip accidentally copied `N: ` line-number prefixes from `new_text` when
203
+ * every non-empty line carries a sequential prefix near `startLine` and the
204
+ * original file doesn't use literal `N: ` lines there.
205
+ */
206
+ function stripNumberedReplacement(
207
+ newLines: readonly string[],
208
+ startLine: number,
209
+ before: readonly string[],
210
+ ): { readonly lines: string[]; readonly stripped: boolean } {
211
+ if (newLines.length === 0) return { lines: [], stripped: false }
212
+ const existingNear = before.slice(Math.max(0, startLine - 2), Math.min(before.length, startLine + 2))
213
+ if (existingNear.some(line => NUMBERED_PREFIX.test(line))) {
214
+ return { lines: [...newLines], stripped: false }
215
+ }
216
+ const out: string[] = []
217
+ let expected: number | undefined
218
+ let numberedCount = 0
219
+ for (const line of newLines) {
220
+ if (line === '') {
221
+ out.push('')
222
+ if (expected !== undefined) expected++
223
+ continue
224
+ }
225
+ const m = NUMBERED_PREFIX.exec(line)
226
+ if (!m) return { lines: [...newLines], stripped: false }
227
+ const num = Number(m[1])
228
+ if (expected === undefined) {
229
+ if (Math.abs(num - startLine) > 20) return { lines: [...newLines], stripped: false }
230
+ expected = num + 1
231
+ } else {
232
+ if (num !== expected) return { lines: [...newLines], stripped: false }
233
+ expected++
234
+ }
235
+ numberedCount++
236
+ out.push(m[2]!)
237
+ }
238
+ if (numberedCount === 0 || (numberedCount === 1 && newLines.length > 1)) {
239
+ return { lines: [...newLines], stripped: false }
240
+ }
241
+ return { lines: out, stripped: true }
242
+ }
243
+
244
+ function pickUniqueAnchorHit(
245
+ hits: readonly { readonly ln: number; readonly score: number }[],
246
+ ): { readonly kind: 'unique'; readonly ln: number } | { readonly kind: 'ambiguous'; readonly lines: readonly number[] } | { readonly kind: 'none' } {
247
+ if (hits.length === 0) return { kind: 'none' }
248
+ const exact = hits.filter(h => h.score >= 0.98)
249
+ if (exact.length === 1) return { kind: 'unique', ln: exact[0]!.ln }
250
+ if (exact.length > 1) return { kind: 'ambiguous', lines: exact.map(h => h.ln) }
251
+ const sorted = [...hits].sort((a, b) => b.score - a.score)
252
+ const best = sorted[0]!
253
+ const runner = sorted[1]
254
+ if (best.score >= 0.90 && (!runner || runner.score <= best.score - 0.08)) {
255
+ return { kind: 'unique', ln: best.ln }
256
+ }
257
+ return { kind: 'ambiguous', lines: sorted.slice(0, 4).map(h => h.ln) }
258
+ }
259
+
260
+ function refineEndLineWithEndText(
261
+ before: readonly string[],
262
+ resolvedStart: number,
263
+ resolvedEnd: number,
264
+ endText: string,
265
+ allowSelfHeal: boolean,
266
+ ): { readonly ok: true; readonly endLine: number; readonly note?: string } | { readonly ok: false } {
267
+ if (resolvedEnd < resolvedStart || resolvedEnd > before.length) return { ok: false }
268
+ if (lineAnchorScore(endText, before[resolvedEnd - 1]!) >= 0.90) {
269
+ return { ok: true, endLine: resolvedEnd }
270
+ }
271
+ if (!allowSelfHeal) return { ok: false }
272
+ const lo = Math.max(resolvedStart, resolvedEnd - END_ANCHOR_SEARCH_RADIUS)
273
+ const hi = Math.min(before.length, resolvedEnd + END_ANCHOR_SEARCH_RADIUS)
274
+ const hits: { ln: number; score: number }[] = []
275
+ for (let ln = lo; ln <= hi; ln++) {
276
+ const score = lineAnchorScore(endText, before[ln - 1]!)
277
+ if (score >= 0.90) hits.push({ ln, score })
278
+ }
279
+ const picked = pickUniqueAnchorHit(hits)
280
+ if (picked.kind === 'unique') {
281
+ return {
282
+ ok: true,
283
+ endLine: picked.ln,
284
+ note: `Auto-aligned edit end_line ${resolvedEnd} -> ${picked.ln} via end_text.`,
285
+ }
286
+ }
287
+ return { ok: false }
288
+ }
289
+
290
+ function resolveSingleHunk(
291
+ before: readonly string[],
292
+ displayPath: string,
293
+ edit: LineEdit,
294
+ index: number,
295
+ totalHunks: number,
296
+ allowSelfHeal: boolean,
297
+ ): ResolvedLineEdit | string {
298
+ const label = totalHunks > 1 ? `edit #${index + 1}` : 'edit'
299
+ const { startLine: start, endLine: end } = edit
300
+ const total = before.length
301
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {
302
+ return `${label}: start_line and end_line must be whole numbers`
303
+ }
304
+ if (start < 1) return `${label}: start_line must be 1 or more (got ${start})`
305
+ if (start > total + 1) return `${label}: start_line ${start} is past the end: ${displayPath} has ${total} lines`
306
+ if (end > total) return `${label}: end_line ${end} is past the end: ${displayPath} has ${total} lines`
307
+ if (end < start - 1) {
308
+ return `${label}: end_line ${end} is before start_line ${start}; use end_line = start_line - 1 to insert without replacing`
309
+ }
310
+
311
+ const isInsert = end === start - 1
312
+ const rawAnchor = typeof edit.startText === 'string' ? edit.startText : ''
313
+ const hasAnchor = rawAnchor.trim() !== ''
314
+
315
+ let resolvedStart = start
316
+ let resolvedEnd = end
317
+ let alignedNote: string | undefined
318
+ let anchorVerified = false
319
+ let endAnchorVerified = false
320
+ let matchedAnchorLine: string | undefined
321
+
322
+ if (hasAnchor && total > 0) {
323
+ const anchorTargetLine = isInsert ? (start <= total ? start : total) : start
324
+ const directLine = before[anchorTargetLine - 1]
325
+ if (directLine !== undefined && lineAnchorScore(rawAnchor, directLine) >= 0.90) {
326
+ anchorVerified = true
327
+ matchedAnchorLine = directLine
328
+ } else if (allowSelfHeal) {
329
+ // Tier 2: local ±15 line window search.
330
+ const lo = Math.max(1, anchorTargetLine - ANCHOR_SEARCH_RADIUS)
331
+ const hi = Math.min(total, anchorTargetLine + ANCHOR_SEARCH_RADIUS)
332
+ const localHits: { ln: number; score: number }[] = []
333
+ for (let ln = lo; ln <= hi; ln++) {
334
+ const score = lineAnchorScore(rawAnchor, before[ln - 1]!)
335
+ if (score >= 0.90) localHits.push({ ln, score })
336
+ }
337
+ const localExactHits = localHits.filter(h => h.score >= 0.98)
338
+ const localPick = pickUniqueAnchorHit(localHits)
339
+ const localIsExact = localExactHits.length === 1 && localPick.kind === 'unique' && localPick.ln === localExactHits[0]!.ln
340
+
341
+ if (localIsExact) {
342
+ const shift = localPick.ln - anchorTargetLine
343
+ const nextStart = start + shift
344
+ const nextEnd = end + shift
345
+ if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {
346
+ resolvedStart = nextStart
347
+ resolvedEnd = nextEnd
348
+ anchorVerified = true
349
+ matchedAnchorLine = before[localPick.ln - 1]
350
+ alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via start_text.`
351
+ }
352
+ } else if (localExactHits.length > 1) {
353
+ const win = renderWindow(displayPath, before, Math.max(1, anchorTargetLine - ERROR_WINDOW_RADIUS), Math.min(total, anchorTargetLine + ERROR_WINDOW_RADIUS))
354
+ return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine}, and matched multiple nearby lines (${localExactHits.map(h => h.ln).join(', ')}).\n\nCurrent lines around line ${anchorTargetLine}:\n${win}`
355
+ }
356
+
357
+ // Tier 3: whole-file unique fallback for non-trivial anchors (len >= 10) — exact file-wide match beats a fuzzy local hit.
358
+ if (!anchorVerified && isNonTrivialAnchor(rawAnchor, MIN_WHOLE_FILE_ANCHOR_LEN)) {
359
+ const globalHits: { ln: number; score: number }[] = []
360
+ for (let ln = 1; ln <= total; ln++) {
361
+ const score = lineAnchorScore(rawAnchor, before[ln - 1]!)
362
+ if (score >= 0.92) globalHits.push({ ln, score })
363
+ }
364
+ const globalExact = globalHits.filter(h => h.score >= 0.98)
365
+ const globalPick = pickUniqueAnchorHit(globalHits)
366
+ if (globalPick.kind === 'unique' && (globalExact.length === 1 || localPick.kind !== 'unique')) {
367
+ const shift = globalPick.ln - anchorTargetLine
368
+ const nextStart = start + shift
369
+ const nextEnd = end + shift
370
+ if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {
371
+ resolvedStart = nextStart
372
+ resolvedEnd = nextEnd
373
+ anchorVerified = true
374
+ matchedAnchorLine = before[globalPick.ln - 1]
375
+ alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via unique file-wide start_text.`
376
+ }
377
+ }
378
+ }
379
+
380
+ // Accept unique fuzzy local match if no exact file-wide match superseded it.
381
+ if (!anchorVerified && localPick.kind === 'unique') {
382
+ const shift = localPick.ln - anchorTargetLine
383
+ const nextStart = start + shift
384
+ const nextEnd = end + shift
385
+ if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {
386
+ resolvedStart = nextStart
387
+ resolvedEnd = nextEnd
388
+ anchorVerified = true
389
+ matchedAnchorLine = before[localPick.ln - 1]
390
+ alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via start_text.`
391
+ }
392
+ }
393
+
394
+ if (!anchorVerified) {
395
+ const win = renderWindow(displayPath, before, Math.max(1, anchorTargetLine - ERROR_WINDOW_RADIUS), Math.min(total, anchorTargetLine + ERROR_WINDOW_RADIUS))
396
+ const extraMatches: string[] = []
397
+ for (let ln = 1; ln <= total; ln++) {
398
+ if (lineAnchorScore(rawAnchor, before[ln - 1]!) >= 0.80) {
399
+ extraMatches.push(` ${ln}: ${before[ln - 1]!}`)
400
+ if (extraMatches.length >= 4) break
401
+ }
402
+ }
403
+ const candHint = extraMatches.length > 0
404
+ ? `\nMatching lines elsewhere in ${displayPath}:\n${extraMatches.join('\n')}`
405
+ : ''
406
+ return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine} (${JSON.stringify(before[anchorTargetLine - 1]?.trim() ?? '')}).${candHint}\n\nCurrent lines around line ${anchorTargetLine}:\n${win}`
407
+ }
408
+ } else {
409
+ const win = renderWindow(displayPath, before, Math.max(1, start - ERROR_WINDOW_RADIUS), Math.min(total, Math.max(end, start) + ERROR_WINDOW_RADIUS))
410
+ return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine} (${JSON.stringify(before[anchorTargetLine - 1]?.trim() ?? '')}).\n${win}`
411
+ }
412
+ }
413
+
414
+ // Optional `end_text` verification & end-line drift auto-alignment for multi-line spans.
415
+ if (!isInsert && typeof edit.endText === 'string' && edit.endText.trim() !== '') {
416
+ const endCheck = refineEndLineWithEndText(before, resolvedStart, resolvedEnd, edit.endText, allowSelfHeal)
417
+ if (!endCheck.ok) {
418
+ const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 3), Math.min(total, resolvedEnd + ERROR_WINDOW_RADIUS))
419
+ return `Your ${label} in ${displayPath} was NOT applied: end_text (${JSON.stringify(edit.endText.trim())}) did not match line ${resolvedEnd} (${JSON.stringify(before[resolvedEnd - 1]?.trim() ?? '')}).\n\nCurrent lines around line ${resolvedEnd}:\n${win}`
420
+ }
421
+ resolvedEnd = endCheck.endLine
422
+ endAnchorVerified = true
423
+ if (endCheck.note) {
424
+ alignedNote = alignedNote ? `${alignedNote} ${endCheck.note}` : endCheck.note
425
+ }
426
+ }
427
+
428
+ const rawNewLines = newLinesOf(edit.newText)
429
+ const { lines: strippedLines, stripped: strippedLineNumbers } = stripNumberedReplacement(rawNewLines, resolvedStart, before)
430
+ let newLines = strippedLines
431
+ let reindented = false
432
+
433
+ // Auto-align base indentation only when `start_text` itself carried non-empty
434
+ // leading whitespace (so trimmed anchors never push column-0 additions into an
435
+ // indented block).
436
+ if (allowSelfHeal && matchedAnchorLine !== undefined && newLines.length > 0 && hasAnchor) {
437
+ const anchorWithoutPrefix = stripOptionalLinePrefix(rawAnchor)
438
+ const oldIndent = indentOf(anchorWithoutPrefix)
439
+ const fileIndent = indentOf(matchedAnchorLine)
440
+ const firstNonBlank = newLines.find(line => line.trim() !== '')
441
+ if (
442
+ oldIndent !== fileIndent
443
+ && firstNonBlank !== undefined
444
+ && oldIndent.length > 0
445
+ && firstNonBlank.startsWith(oldIndent)
446
+ ) {
447
+ const moved = reindent(newLines.join('\n'), [[oldIndent, fileIndent]]).split('\n')
448
+ if (moved.join('\n') !== newLines.join('\n')) {
449
+ newLines = moved
450
+ reindented = true
451
+ }
452
+ }
453
+ }
454
+
455
+ const removedSlice = before.slice(resolvedStart - 1, resolvedEnd)
456
+ const oldTrimmedSet = new Set(removedSlice.map(line => line.trim()))
457
+ for (const nl of newLines) {
458
+ if (ELISION_LINE.test(nl) && !oldTrimmedSet.has(nl.trim())) {
459
+ return `Your ${label} in ${displayPath} was NOT applied: new_text contains an elision placeholder (${JSON.stringify(nl.trim())}), which would delete code. Narrow start_line..end_line to only the lines changing and write complete replacement code.`
460
+ }
461
+ }
462
+
463
+ if (removedSlice.length === newLines.length && removedSlice.every((line, i) => line === newLines[i])) {
464
+ const spanStr = resolvedStart === resolvedEnd ? `line ${resolvedStart}` : `lines ${resolvedStart}-${resolvedEnd}`
465
+ return `No edit needed in ${displayPath}: new_text is the same as ${spanStr}; nothing changed.`
466
+ }
467
+
468
+ // Off-by-one boundary duplication guard: catches accidentally duplicating untouched line start-1 or end+1.
469
+ if (newLines.length >= 2 && resolvedStart > 1) {
470
+ const above = before[resolvedStart - 2]!.trim()
471
+ if (above.length >= 8 && newLines[0]!.trim() === above && !oldTrimmedSet.has(above)) {
472
+ const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 4), Math.min(total, Math.max(resolvedEnd, resolvedStart) + 4))
473
+ return `Your ${label} in ${displayPath} was NOT applied: the first line of new_text duplicates line ${resolvedStart - 1} (${JSON.stringify(above)}) immediately above start_line=${resolvedStart}. Drop that unchanged line from new_text or adjust start_line.\n\n${win}`
474
+ }
475
+ }
476
+ if (newLines.length >= 2 && resolvedEnd < total) {
477
+ const below = before[resolvedEnd]!.trim()
478
+ if (below.length >= 8 && newLines[newLines.length - 1]!.trim() === below && !oldTrimmedSet.has(below)) {
479
+ const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 4), Math.min(total, Math.max(resolvedEnd, resolvedStart) + 4))
480
+ return `Your ${label} in ${displayPath} was NOT applied: the last line of new_text duplicates line ${resolvedEnd + 1} (${JSON.stringify(below)}) immediately below end_line=${resolvedEnd}. Drop that unchanged line from new_text or adjust end_line.\n\n${win}`
481
+ }
482
+ }
483
+
484
+ return {
485
+ index,
486
+ requestedStart: start,
487
+ requestedEnd: end,
488
+ startLine: resolvedStart,
489
+ endLine: resolvedEnd,
490
+ newLines,
491
+ removed: removedSlice.length,
492
+ added: newLines.length,
493
+ strippedLineNumbers,
494
+ reindented,
495
+ ...(alignedNote ? { alignedNote } : {}),
496
+ anchorVerified,
497
+ endAnchorVerified,
498
+ }
499
+ }
500
+
501
+ function hunksOverlap(a: ResolvedLineEdit, b: ResolvedLineEdit): boolean {
502
+ const aInsert = a.endLine < a.startLine
503
+ const bInsert = b.endLine < b.startLine
504
+ if (aInsert && bInsert) return a.startLine === b.startLine
505
+ if (aInsert) return a.startLine > b.startLine && a.startLine <= b.endLine
506
+ if (bInsert) return b.startLine > a.startLine && b.startLine <= a.endLine
507
+ return a.startLine <= b.endLine && b.startLine <= a.endLine
508
+ }
509
+
510
+ /**
511
+ * Atomically resolve and apply one or more non-overlapping anchored line edits
512
+ * against pre-edit file coordinates. Returns either the full batch result or a
513
+ * model-facing error string.
514
+ */
515
+ export function applyAnchoredLineEdits(
516
+ text: string,
517
+ displayPath: string,
518
+ edits: readonly LineEdit[],
519
+ options: ApplyLineEditsOptions = {},
520
+ ): BatchLineEditResult | string {
521
+ if (edits.length === 0) return 'edits must contain at least one edit hunk'
522
+ const allowSelfHeal = options.selfHeal !== false
523
+ const { eol, trailingNewline, lines: before } = splitDocumentLines(text)
524
+
525
+ const resolved: ResolvedLineEdit[] = []
526
+ for (let i = 0; i < edits.length; i++) {
527
+ const out = resolveSingleHunk(before, displayPath, edits[i]!, i, edits.length, allowSelfHeal)
528
+ if (typeof out === 'string') return out
529
+ resolved.push(out)
530
+ }
531
+
532
+ // Overlap check across all resolved pre-edit ranges.
533
+ const sortedAsc = [...resolved].sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine)
534
+ for (let i = 1; i < sortedAsc.length; i++) {
535
+ if (hunksOverlap(sortedAsc[i - 1]!, sortedAsc[i]!)) {
536
+ return `Your batch edit in ${displayPath} was NOT applied: edit #${sortedAsc[i - 1]!.index + 1} (lines ${sortedAsc[i - 1]!.startLine}-${sortedAsc[i - 1]!.endLine}) overlaps edit #${sortedAsc[i]!.index + 1} (lines ${sortedAsc[i]!.startLine}-${sortedAsc[i]!.endLine}). Combine overlapping edits into one range.`
537
+ }
538
+ }
539
+
540
+ // Apply bottom-up so earlier pre-edit line numbers stay valid.
541
+ const after = [...before]
542
+ const sortedDesc = [...sortedAsc].reverse()
543
+ for (const h of sortedDesc) {
544
+ after.splice(h.startLine - 1, h.removed, ...h.newLines)
545
+ }
546
+
547
+ const content = joinDocumentLines(after, eol, trailingNewline, before.length === 0)
548
+ const totalRemoved = resolved.reduce((acc, h) => acc + h.removed, 0)
549
+ const totalAdded = resolved.reduce((acc, h) => acc + h.added, 0)
550
+ return { content, before, after, hunks: sortedAsc, totalRemoved, totalAdded }
551
+ }
552
+
553
+ /** Backward-compatible single-hunk entry point (`applyLineEdit`). */
554
+ export function applyLineEdit(
555
+ text: string,
556
+ displayPath: string,
557
+ edit: LineEdit,
558
+ options: ApplyLineEditsOptions = {},
559
+ ): LineEditResult | string {
560
+ const batch = applyAnchoredLineEdits(text, displayPath, [edit], options)
561
+ if (typeof batch === 'string') return batch
562
+ const h = batch.hunks[0]!
563
+ return {
564
+ content: batch.content,
565
+ before: batch.before,
566
+ after: batch.after,
567
+ removed: h.removed,
568
+ added: h.added,
569
+ resolvedStart: h.startLine,
570
+ resolvedEnd: h.endLine,
571
+ ...(h.alignedNote ? { alignedNote: h.alignedNote } : {}),
572
+ anchorVerified: h.anchorVerified,
573
+ strippedLineNumbers: h.strippedLineNumbers,
574
+ reindented: h.reindented,
575
+ }
576
+ }
577
+
578
+ // --- Summaries & syntax-error messages --------------------------------------
579
+
580
+ function resultWindow(displayPath: string, start: number, added: number, after: readonly string[]): string {
581
+ return renderWindow(
582
+ displayPath,
583
+ after,
584
+ start - LINE_EDIT_CONTEXT_LINES,
585
+ start + Math.max(added, 1) - 1 + LINE_EDIT_CONTEXT_LINES,
586
+ )
587
+ }
588
+
589
+ /** Model-facing result of an applied single coordinate line edit. */
590
+ export function editSummary(displayPath: string, edit: LineEdit, result: LineEditResult): string {
591
+ const start = result.resolvedStart ?? edit.startLine
592
+ const end = result.resolvedEnd ?? edit.endLine
593
+ const { removed, added } = result
594
+ let what: string
595
+ if (removed === 0) what = start > 1 ? `Inserted ${pluralLines(added)} after line ${start - 1}` : `Inserted ${pluralLines(added)} at the start`
596
+ else if (added === 0) what = `Deleted lines ${start}-${end}`
597
+ else what = `Replaced lines ${start}-${end} with ${pluralLines(added)}`
598
+ const parts = [`File updated. ${what}.`]
599
+ if (result.alignedNote) parts.push(`(${result.alignedNote})`)
600
+ if (result.strippedLineNumbers) parts.push('(Stripped copied line-number prefixes from new_text.)')
601
+ if (result.reindented) parts.push('(Auto-aligned indentation to match the file.)')
602
+ const delta = added - removed
603
+ if (delta !== 0 && end < result.before.length) {
604
+ parts.push(`Lines after it moved ${delta > 0 ? 'down' : 'up'} by ${Math.abs(delta)}: old line ${end + 1} is now line ${end + 1 + delta}.`)
605
+ }
606
+ parts.push('Review the change (correct indentation, no duplicate or missing lines) and edit again if necessary.')
607
+ return `${parts.join(' ')}\n${resultWindow(displayPath, start, added, result.after)}`
608
+ }
609
+
610
+ /** Model-facing result of an applied atomic multi-hunk (or single-hunk) edit. */
611
+ export function batchEditSummary(displayPath: string, batch: BatchLineEditResult): string {
612
+ if (batch.hunks.length === 1) {
613
+ const h = batch.hunks[0]!
614
+ return editSummary(
615
+ displayPath,
616
+ { startLine: h.startLine, endLine: h.endLine, newText: h.newLines.join('\n') },
617
+ {
618
+ content: batch.content,
619
+ before: batch.before,
620
+ after: batch.after,
621
+ removed: h.removed,
622
+ added: h.added,
623
+ resolvedStart: h.startLine,
624
+ resolvedEnd: h.endLine,
625
+ ...(h.alignedNote ? { alignedNote: h.alignedNote } : {}),
626
+ anchorVerified: h.anchorVerified,
627
+ strippedLineNumbers: h.strippedLineNumbers,
628
+ reindented: h.reindented,
629
+ },
630
+ )
631
+ }
632
+ const notes: string[] = []
633
+ let cumulativeDelta = 0
634
+ const windows: string[] = []
635
+ for (const h of batch.hunks) {
636
+ const postStart = h.startLine + cumulativeDelta
637
+ if (h.alignedNote) notes.push(h.alignedNote)
638
+ if (h.strippedLineNumbers) notes.push(`Stripped copied line-number prefixes in edit #${h.index + 1}.`)
639
+ if (h.reindented) notes.push(`Auto-aligned indentation in edit #${h.index + 1}.`)
640
+ windows.push(resultWindow(displayPath, postStart, h.added, batch.after))
641
+ cumulativeDelta += h.added - h.removed
642
+ }
643
+ const parts = [`File updated with ${batch.hunks.length} atomic edits (${pluralLines(batch.totalRemoved)} removed, ${pluralLines(batch.totalAdded)} added).`]
644
+ if (notes.length > 0) parts.push(`(${notes.join(' ')})`)
645
+ parts.push('Review the updated windows below and edit again if necessary.')
646
+ return `${parts.join(' ')}\n${windows.join('\n\n')}`
647
+ }
648
+
649
+ /** Model-facing refusal of a single edit that would break the file's syntax (not applied). */
650
+ export function syntaxRejection(displayPath: string, edit: LineEdit, result: LineEditResult, error: string): string {
651
+ const start = result.resolvedStart ?? edit.startLine
652
+ const end = result.resolvedEnd ?? edit.endLine
653
+ const original = renderWindow(displayPath, result.before, start - LINE_EDIT_CONTEXT_LINES, Math.max(end, start) + LINE_EDIT_CONTEXT_LINES)
654
+ return [
655
+ 'Your edit was NOT applied: it introduces a syntax error.',
656
+ `ERROR: ${error}`,
657
+ '',
658
+ 'This is how the file would have looked:',
659
+ resultWindow(displayPath, start, result.added, result.after),
660
+ '',
661
+ 'This is the original code before your edit:',
662
+ original,
663
+ '',
664
+ 'Fix start_line/end_line or new_text (check the indentation) and try again. Do not repeat the same edit.',
665
+ ].join('\n')
666
+ }
667
+
668
+ /** Model-facing refusal of a batch edit that would break the file's syntax (not applied). */
669
+ export function batchSyntaxRejection(displayPath: string, batch: BatchLineEditResult, error: string): string {
670
+ if (batch.hunks.length === 1) {
671
+ const h = batch.hunks[0]!
672
+ return syntaxRejection(
673
+ displayPath,
674
+ { startLine: h.startLine, endLine: h.endLine, newText: h.newLines.join('\n') },
675
+ {
676
+ content: batch.content,
677
+ before: batch.before,
678
+ after: batch.after,
679
+ removed: h.removed,
680
+ added: h.added,
681
+ resolvedStart: h.startLine,
682
+ resolvedEnd: h.endLine,
683
+ },
684
+ error,
685
+ )
686
+ }
687
+ const first = batch.hunks[0]!
688
+ const last = batch.hunks[batch.hunks.length - 1]!
689
+ const delta = batch.totalAdded - batch.totalRemoved
690
+ const afterWin = renderWindow(displayPath, batch.after, first.startLine - LINE_EDIT_CONTEXT_LINES, last.endLine + delta + LINE_EDIT_CONTEXT_LINES)
691
+ const beforeWin = renderWindow(displayPath, batch.before, first.startLine - LINE_EDIT_CONTEXT_LINES, last.endLine + LINE_EDIT_CONTEXT_LINES)
692
+ return [
693
+ `Your batch edit (${batch.hunks.length} hunks) was NOT applied: it introduces a syntax error.`,
694
+ `ERROR: ${error}`,
695
+ '',
696
+ 'This is how the file would have looked:',
697
+ afterWin,
698
+ '',
699
+ 'This is the original code before your edit:',
700
+ beforeWin,
701
+ '',
702
+ 'Fix the affected hunk(s) and try again. Do not repeat the same edit.',
703
+ ].join('\n')
704
+ }
705
+
706
+ // --- Argument parsing & normalization (batch + single-hunk shorthand) -------
707
+
708
+ function toSafeInt(value: unknown): number | undefined {
709
+ if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value)
710
+ if (typeof value === 'string' && value.trim() !== '') {
711
+ const parsed = Number(value.replace(/,/g, '').trim())
712
+ if (Number.isFinite(parsed)) return Math.trunc(parsed)
713
+ }
714
+ return undefined
715
+ }
716
+
717
+ function normalizeRawHunk(raw: unknown): RawLineEditHunk | undefined {
718
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
719
+ const obj = raw as Record<string, unknown>
720
+ const sl = toSafeInt(obj.start_line ?? obj.startLine ?? obj.line_start ?? obj.from_line ?? obj.start ?? obj.line)
721
+ const el = toSafeInt(obj.end_line ?? obj.endLine ?? obj.line_end ?? obj.to_line ?? obj.end)
722
+ const ntRaw = obj.new_text ?? obj.newText ?? obj.new_string ?? obj.new_str ?? obj.text ?? obj.content ?? obj.replacement ?? obj.lines
723
+ if (sl === undefined || el === undefined || typeof ntRaw !== 'string') return undefined
724
+ const stRaw = obj.start_text ?? obj.startText ?? obj.anchor ?? obj.start_anchor ?? obj.first_line
725
+ const etRaw = obj.end_text ?? obj.endText ?? obj.end_anchor ?? obj.last_line
726
+ return {
727
+ start_line: sl,
728
+ end_line: el,
729
+ ...(typeof stRaw === 'string' ? { start_text: stRaw } : {}),
730
+ ...(typeof etRaw === 'string' ? { end_text: etRaw } : {}),
731
+ new_text: ntRaw,
732
+ }
733
+ }
734
+
735
+ /**
736
+ * Parse either canonical batch `edits[]` (array, single object, or JSON string)
737
+ * or single-hunk top-level `{ start_line, end_line, start_text?, end_text?, new_text }`
738
+ * into normalized `LineEdit[]` hunks.
739
+ */
740
+ export function parseLineEditHunks(args: Record<string, unknown>): LineEdit[] | string {
741
+ if (args.edits !== undefined) {
742
+ let source: unknown = args.edits
743
+ if (typeof source === 'string') {
744
+ try {
745
+ source = JSON.parse(source)
746
+ } catch {
747
+ return 'edits must be a valid JSON array of edit hunks'
748
+ }
749
+ }
750
+ const items = Array.isArray(source) ? source : (typeof source === 'object' && source !== null ? [source] : undefined)
751
+ if (!items || items.length === 0) return 'edits must be a non-empty array of { start_line, end_line, start_text?, new_text } hunks'
752
+ const out: LineEdit[] = []
753
+ for (let i = 0; i < items.length; i++) {
754
+ const normalized = normalizeRawHunk(items[i])
755
+ if (normalized === undefined) {
756
+ return `edits[${i}] is missing required start_line, end_line, or new_text`
757
+ }
758
+ out.push({
759
+ startLine: normalized.start_line,
760
+ endLine: normalized.end_line,
761
+ ...(normalized.start_text !== undefined ? { startText: normalized.start_text } : {}),
762
+ ...(normalized.end_text !== undefined ? { endText: normalized.end_text } : {}),
763
+ newText: normalized.new_text,
764
+ })
765
+ }
766
+ return out
767
+ }
768
+
769
+ const single = normalizeRawHunk(args)
770
+ if (single === undefined) {
771
+ return 'Provide either edits: [{ start_line, end_line, start_text, new_text }] or single-hunk start_line, end_line, new_text'
772
+ }
773
+ return [{
774
+ startLine: single.start_line,
775
+ endLine: single.end_line,
776
+ ...(single.start_text !== undefined ? { startText: single.start_text } : {}),
777
+ ...(single.end_text !== undefined ? { endText: single.end_text } : {}),
778
+ newText: single.new_text,
779
+ }]
780
+ }
781
+
782
+ /** Normalize raw model arguments for `edit_lines` (`edits[]` or single-hunk shorthand) into clean wire/DSH args. */
783
+ export function normalizeLineEditArgs(args: Record<string, unknown>): Record<string, unknown> {
784
+ if (args.edits === undefined) return args
785
+ let source: unknown = args.edits
786
+ if (typeof source === 'string') {
787
+ try { source = JSON.parse(source) } catch { return args }
788
+ }
789
+ const items = Array.isArray(source) ? source : (typeof source === 'object' && source !== null ? [source] : undefined)
790
+ if (!items || items.length === 0) return args
791
+ const normalized = items.map(item => normalizeRawHunk(item) ?? item)
792
+ return { ...args, edits: normalized }
793
+ }