File size: 29,272 Bytes
b8370f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import Foundation
import OpenClawKit

enum ChatToolDiffLineKind: Equatable, Sendable {
    case add
    case del
    case ctx
    case file
    case skip
}

struct ChatToolDiffLine: Equatable, Sendable {
    let kind: ChatToolDiffLineKind
    let lineNo: Int?
    let text: String

    init(kind: ChatToolDiffLineKind, lineNo: Int? = nil, text: String) {
        self.kind = kind
        self.lineNo = lineNo
        self.text = text
    }
}

struct ChatToolDiffStat: Equatable, Hashable, Sendable {
    let files: Int?
    let added: Int
    let removed: Int

    init(files: Int? = nil, added: Int, removed: Int) {
        self.files = files
        self.added = added
        self.removed = removed
    }
}

enum ChatToolDiff {
    private struct EditPair {
        let oldText: String
        let newText: String
    }

    private struct ParsedDetailsDiff {
        let lines: [ChatToolDiffLine]
        let truncated: Bool
    }

    private enum PatchOperation {
        case add
        case delete
        case update
    }

    private struct PatchSection {
        var operation: PatchOperation
        let sourcePath: String
        var path: String
        var lines: [ChatToolDiffLine] = []
        var added = 0
        var removed = 0
    }

    private struct PatchHunk {
        var oldLine: Int?
        var newLine: Int?
    }

    private static let maxInputLines = 600
    private static let maxRenderLines = 400
    private static let maxLocalPairs = 8
    private static let maxWritePreviewLines = 80
    private static let maxLocalInputCharacters = 120_000

    private static let editToolNames: Set<String> = [
        "edit",
        "edit_file",
        "multiedit",
        "multi_edit",
        "notebookedit",
        "notebook_edit",
    ]
    private static let textEditorToolNames: Set<String> = [
        "str_replace_editor",
        "str_replace_based_edit_tool",
    ]
    private static let writeToolNames: Set<String> = ["write", "write_file", "create_file"]
    private static let patchToolNames: Set<String> = ["apply_patch", "applypatch", "patch"]

    private static func parseDetailsDiffResult(_ diff: String) -> ParsedDetailsDiff? {
        guard !diff.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }

        var lines: [ChatToolDiffLine] = []
        var truncated = diff.components(separatedBy: "\n").contains { raw in
            raw.trimmingCharacters(in: .whitespacesAndNewlines) == "...(truncated)..."
        }
        for raw in diff.components(separatedBy: "\n") {
            guard !raw.isEmpty else { continue }
            let marker = raw.trimmingCharacters(in: .whitespacesAndNewlines)
            let line: ChatToolDiffLine
            if marker == "..." || marker == "...(truncated)..." {
                line = ChatToolDiffLine(kind: .skip, text: "")
            } else {
                guard let numberedLine = self.parseNumberedLine(raw) else { return nil }
                line = numberedLine
            }
            if lines.count >= self.maxRenderLines {
                truncated = true
                if lines.last?.kind != .skip {
                    lines.append(ChatToolDiffLine(kind: .skip, text: ""))
                }
                break
            }
            lines.append(line)
        }

        guard lines.contains(where: { $0.kind == .add || $0.kind == .del }) else { return nil }
        return ParsedDetailsDiff(lines: lines, truncated: truncated)
    }

    static func computeLineDiff(old: String, new: String) -> [ChatToolDiffLine] {
        let allOldLines = self.splitLines(old)
        let allNewLines = self.splitLines(new)
        let inputTruncated = allOldLines.count > self.maxInputLines || allNewLines.count > self.maxInputLines
        let oldLines = Array(allOldLines.prefix(self.maxInputLines))
        let newLines = Array(allNewLines.prefix(self.maxInputLines))
        let oldCount = oldLines.count
        let newCount = newLines.count
        let width = newCount + 1
        var lcs = Array(repeating: 0, count: (oldCount + 1) * width)

        if oldCount > 0, newCount > 0 {
            for oldIndex in stride(from: oldCount - 1, through: 0, by: -1) {
                for newIndex in stride(from: newCount - 1, through: 0, by: -1) {
                    let index = oldIndex * width + newIndex
                    if oldLines[oldIndex] == newLines[newIndex] {
                        lcs[index] = lcs[(oldIndex + 1) * width + newIndex + 1] + 1
                    } else {
                        lcs[index] = max(
                            lcs[(oldIndex + 1) * width + newIndex],
                            lcs[oldIndex * width + newIndex + 1])
                    }
                }
            }
        }

        var lines: [ChatToolDiffLine] = []
        var oldIndex = 0
        var newIndex = 0
        while oldIndex < oldCount, newIndex < newCount {
            if oldLines[oldIndex] == newLines[newIndex] {
                lines.append(ChatToolDiffLine(kind: .ctx, text: oldLines[oldIndex]))
                oldIndex += 1
                newIndex += 1
            } else if lcs[(oldIndex + 1) * width + newIndex] >= lcs[oldIndex * width + newIndex + 1] {
                lines.append(ChatToolDiffLine(kind: .del, text: oldLines[oldIndex]))
                oldIndex += 1
            } else {
                lines.append(ChatToolDiffLine(kind: .add, text: newLines[newIndex]))
                newIndex += 1
            }
        }
        while oldIndex < oldCount {
            lines.append(ChatToolDiffLine(kind: .del, text: oldLines[oldIndex]))
            oldIndex += 1
        }
        while newIndex < newCount {
            lines.append(ChatToolDiffLine(kind: .add, text: newLines[newIndex]))
            newIndex += 1
        }
        return self.compact(lines, inputTruncated: inputTruncated)
    }

    static func resolveDiff(
        name: String?,
        arguments: AnyCodable?,
        details: AnyCodable?,
        isError: Bool = false) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        let normalizedName = name?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? ""
        let argumentsRecord = arguments?.dictionaryValue
        if self.textEditorToolNames.contains(normalizedName) {
            if let detailsDiff = self.resolveDetailsDiff(details) {
                // Applied diff details stay authoritative even when the result reports an error.
                return detailsDiff
            }
            // Failed args describe a proposal, not a mutation known to have been applied.
            guard !isError else { return nil }
            switch self.string(in: argumentsRecord, keys: ["command"])?
                .trimmingCharacters(in: .whitespacesAndNewlines)
                .lowercased()
            {
            case "create":
                return self.resolveWriteDiff(
                    argumentsRecord,
                    keys: ["file_text", "content"],
                    details: details)
            case "insert":
                return self.resolveInsertionDiff(argumentsRecord, details: details)
            default:
                return self.resolveEditDiff(argumentsRecord, details: details)
            }
        }

        // Plugin tools own their details schema; only edit-family tools may
        // interpret details.diff as a filesystem diff (mirrors the web guard).
        if self.editToolNames.contains(normalizedName) {
            if let detailsDiff = self.resolveDetailsDiff(details) {
                return detailsDiff
            }
            guard !isError else { return nil }
            return self.resolveEditDiff(argumentsRecord, details: nil)
        }
        if self.writeToolNames.contains(normalizedName) {
            if let detailsDiff = self.resolveDetailsDiff(details) {
                return detailsDiff
            }
            guard !isError else { return nil }
            return self.resolveWriteDiff(
                argumentsRecord,
                keys: ["content", "text", "file_text"],
                details: details)
        }
        if self.patchToolNames.contains(normalizedName) {
            if let detailsDiff = self.resolveDetailsDiff(details) {
                return detailsDiff
            }
            guard !isError else { return nil }
            return self.resolvePatchDiff(argumentsRecord)
        }
        return nil
    }

    private static func parseNumberedLine(_ raw: String) -> ChatToolDiffLine? {
        guard let sign = raw.first, sign == "+" || sign == "-" || sign == " " else { return nil }
        var remainder = raw.dropFirst()
        while remainder.first?.isWhitespace == true {
            remainder = remainder.dropFirst()
        }
        let digits = remainder.prefix { character in
            character >= "0" && character <= "9"
        }
        guard !digits.isEmpty, let lineNo = Int(digits) else { return nil }
        remainder = remainder.dropFirst(digits.count)
        if remainder.first == " " {
            remainder = remainder.dropFirst()
        }
        let kind: ChatToolDiffLineKind = switch sign {
        case "+": .add
        case "-": .del
        default: .ctx
        }
        return ChatToolDiffLine(kind: kind, lineNo: lineNo, text: String(remainder))
    }

    private static func resolvePatchDiff(
        _ arguments: [String: AnyCodable]?) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        // First NON-BLANK alias, matching the transcript cache's selection so a
        // cold-cache reload renders the same envelope as the live row.
        guard let patch = self.firstNonBlankString(in: arguments, keys: ["input", "patch", "diff"])
        else { return nil }

        let inputClipped = patch.utf16.count > self.maxLocalInputCharacters
        let text = inputClipped
            ? String(decoding: patch.utf16.prefix(self.maxLocalInputCharacters), as: UTF16.self)
            : patch
        var sections: [PatchSection] = []
        var current: PatchSection?
        var hunk = PatchHunk()
        var storedRows = 0
        var clipped = inputClipped

        for raw in self.splitLines(text) {
            let structural = current?.operation == .update
                ? raw.replacingOccurrences(of: #"[ \t]+$"#, with: "", options: .regularExpression)
                : raw.trimmingCharacters(in: .whitespaces)
            if structural == "...(truncated)..." {
                // Cached envelopes use this marker to make an unknown patch tail explicit.
                clipped = true
                continue
            }
            if let header = self.patchFileHeader(structural) {
                if let current { sections.append(current) }
                current = PatchSection(
                    operation: header.operation,
                    sourcePath: header.path,
                    path: header.path)
                hunk = PatchHunk()
                continue
            }
            if current?.operation == .update,
               structural.hasPrefix("*** Move to: "),
               case let path = String(structural.dropFirst("*** Move to: ".count))
                   .trimmingCharacters(in: .whitespacesAndNewlines),
                   !path.isEmpty
            {
                current?.path = path
                continue
            }
            if structural == "*** Begin Patch" || structural == "*** End Patch" ||
                structural == "*** End of File" || structural.hasPrefix("*** Environment ID:")
            {
                continue
            }
            guard var section = current else { continue }

            if section.operation == .update, raw.hasPrefix("@@") {
                if !section.lines.isEmpty, section.lines.last?.kind != .skip {
                    self.pushPatchLine(
                        ChatToolDiffLine(kind: .skip, text: ""),
                        section: &section,
                        storedRows: &storedRows,
                        clipped: &clipped)
                }
                hunk = self.parsePatchHunk(raw)
            } else if section.operation == .add, raw.hasPrefix("+") {
                self.pushPatchLine(
                    ChatToolDiffLine(kind: .add, lineNo: section.added + 1, text: String(raw.dropFirst())),
                    section: &section,
                    storedRows: &storedRows,
                    clipped: &clipped)
            } else if section.operation == .delete, raw.hasPrefix("-") {
                self.pushPatchLine(
                    ChatToolDiffLine(kind: .del, lineNo: section.removed + 1, text: String(raw.dropFirst())),
                    section: &section,
                    storedRows: &storedRows,
                    clipped: &clipped)
            } else if section.operation == .update,
                      raw.isEmpty || raw.hasPrefix("+") || raw.hasPrefix("-") || raw.hasPrefix(" ")
            {
                self.pushPatchHunkLine(
                    raw,
                    hunk: &hunk,
                    section: &section,
                    storedRows: &storedRows,
                    clipped: &clipped)
            }
            current = section
        }
        if let current { sections.append(current) }
        return self.finishPatch(sections, clipped: clipped)
    }

    private static func patchFileHeader(
        _ raw: String) -> (operation: PatchOperation, path: String)?
    {
        let headers: [(String, PatchOperation)] = [
            ("*** Update File: ", .update),
            ("*** Add File: ", .add),
            ("*** Delete File: ", .delete),
        ]
        for (prefix, operation) in headers where raw.hasPrefix(prefix) {
            let path = raw.dropFirst(prefix.count).trimmingCharacters(in: .whitespacesAndNewlines)
            guard !path.isEmpty else { return nil }
            return (operation, path)
        }
        return nil
    }

    private static func pushPatchLine(
        _ line: ChatToolDiffLine,
        section: inout PatchSection,
        storedRows: inout Int,
        clipped: inout Bool)
    {
        switch line.kind {
        case .add:
            section.added += 1
        case .del:
            section.removed += 1
        case .ctx, .file, .skip:
            break
        }
        if storedRows < self.maxRenderLines {
            section.lines.append(line)
            storedRows += 1
        } else {
            clipped = true
        }
    }

    private static func parsePatchHunk(_ raw: String) -> PatchHunk {
        guard raw.hasPrefix("@@ -") else { return PatchHunk() }
        let body = raw.dropFirst(4)
        guard let plus = body.range(of: " +"),
              let end = body[plus.upperBound...].range(of: " @@")
        else { return PatchHunk() }
        let old = body[..<plus.lowerBound]
        let new = body[plus.upperBound..<end.lowerBound]

        func line(_ rangeText: Substring) -> Int? {
            Int(rangeText.split(separator: ",", maxSplits: 1).first ?? "")
        }
        guard let oldLine = line(old), let newLine = line(new) else { return PatchHunk() }
        return PatchHunk(oldLine: oldLine, newLine: newLine)
    }

    private static func pushPatchHunkLine(
        _ raw: String,
        hunk: inout PatchHunk,
        section: inout PatchSection,
        storedRows: inout Int,
        clipped: inout Bool)
    {
        let kind: ChatToolDiffLineKind
        let lineNo: Int?
        if raw.hasPrefix("+") {
            kind = .add
            lineNo = hunk.newLine
            if let newLine = hunk.newLine {
                hunk.newLine = newLine + 1
            }
        } else if raw.hasPrefix("-") {
            kind = .del
            lineNo = hunk.oldLine
            if let oldLine = hunk.oldLine {
                hunk.oldLine = oldLine + 1
            }
        } else {
            kind = .ctx
            lineNo = hunk.newLine
            if let oldLine = hunk.oldLine, let newLine = hunk.newLine {
                hunk.oldLine = oldLine + 1
                hunk.newLine = newLine + 1
            }
        }
        self.pushPatchLine(
            ChatToolDiffLine(kind: kind, lineNo: lineNo, text: raw.isEmpty ? "" : String(raw.dropFirst())),
            section: &section,
            storedRows: &storedRows,
            clipped: &clipped)
    }

    private static func finishPatch(
        _ sections: [PatchSection],
        clipped initialClipped: Bool) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        guard !sections.isEmpty else { return nil }

        var lines: [ChatToolDiffLine] = []
        var clipped = initialClipped
        let hasHeaderOnlyDelete = sections.contains { section in
            section.operation == .delete && !section.lines.contains(where: { $0.kind == .del })
        }
        func append(_ line: ChatToolDiffLine) {
            if lines.count < self.maxRenderLines {
                lines.append(line)
            } else {
                clipped = true
            }
        }
        for section in sections {
            // Header rows also carry move-only and header-only sections that
            // would otherwise render nothing.
            let isHeaderOnly = section.lines.isEmpty &&
                (section.operation == .delete || section.path != section.sourcePath)
            if sections.count > 1 || isHeaderOnly {
                if !lines.isEmpty, lines.last?.kind != .skip {
                    append(ChatToolDiffLine(kind: .skip, text: ""))
                }
                append(ChatToolDiffLine(kind: .file, text: self.patchSectionLabel(section)))
            }
            section.lines.forEach(append)
        }
        if clipped, lines.last?.kind != .skip {
            lines.append(ChatToolDiffLine(kind: .skip, text: ""))
        }
        guard lines.contains(where: { $0.kind == .add || $0.kind == .del || $0.kind == .file }) else { return nil }
        let stat = self.stat(for: lines)
        // Zero/zero (move-only) and unknowable header-only-delete stats read as noise or lies.
        let statMeaningful = !clipped && !hasHeaderOnlyDelete && (stat.added > 0 || stat.removed > 0)
        return (lines, statMeaningful ? stat : nil)
    }

    private static func patchSectionLabel(_ section: PatchSection) -> String {
        if section.operation == .update, section.path != section.sourcePath {
            return "Move \(section.sourcePath) → \(section.path)"
        }
        let verb = switch section.operation {
        case .add: "Add"
        case .delete: "Delete"
        case .update: "Update"
        }
        return "\(verb) \(section.path)"
    }

    private static func splitLines(_ text: String) -> [String] {
        let normalized = text
            .replacingOccurrences(of: "\r\n", with: "\n")
            .replacingOccurrences(of: "\r", with: "\n")
        guard !normalized.isEmpty else { return [] }
        var lines = normalized.components(separatedBy: "\n")
        if lines.count > 1, lines.last?.isEmpty == true {
            lines.removeLast()
        }
        return lines
    }

    private static func compact(
        _ lines: [ChatToolDiffLine],
        inputTruncated: Bool) -> [ChatToolDiffLine]
    {
        if lines.count <= self.maxRenderLines, !inputTruncated {
            return lines
        }
        let hasChange = lines.contains { $0.kind == .add || $0.kind == .del }
        guard hasChange else {
            return inputTruncated
                ? [ChatToolDiffLine(kind: .skip, text: "")]
                : Array(lines.prefix(self.maxRenderLines)) + [ChatToolDiffLine(kind: .skip, text: "")]
        }

        var keep = Array(repeating: false, count: lines.count)
        for index in lines.indices where lines[index].kind == .add || lines[index].kind == .del {
            let start = max(0, index - 3)
            let end = min(lines.count, index + 4)
            for contextIndex in start..<end {
                keep[contextIndex] = true
            }
        }

        var preview: [ChatToolDiffLine] = []
        var gap = false
        var clipped = inputTruncated
        for index in lines.indices {
            guard keep[index] else {
                gap = true
                clipped = true
                continue
            }
            if gap, preview.last?.kind != .skip {
                preview.append(ChatToolDiffLine(kind: .skip, text: ""))
            }
            gap = false
            if preview.count >= self.maxRenderLines {
                clipped = true
                break
            }
            preview.append(lines[index])
        }
        if clipped, preview.last?.kind != .skip {
            preview.append(ChatToolDiffLine(kind: .skip, text: ""))
        }
        return preview
    }

    private static func resolveDetailsDiff(
        _ details: AnyCodable?) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        guard let diff = details?.dictionaryValue?["diff"]?.stringValue,
              !diff.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
              let parsed = self.parseDetailsDiffResult(diff)
        else {
            return nil
        }
        // Only explicit truncation or the render cap makes a persisted stat incomplete.
        return (parsed.lines, parsed.truncated ? nil : self.stat(for: parsed.lines))
    }

    private static func resolveInsertionDiff(
        _ arguments: [String: AnyCodable]?,
        details: AnyCodable?) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        if let detailsDiff = self.resolveDetailsDiff(details) {
            return detailsDiff
        }
        guard let insertText = self.string(in: arguments, keys: ["insert_text"]) else { return nil }
        let lines = self.computeLineDiff(old: "", new: insertText)
        // The inserted text is known, but its final placement is not, so keep the stat absent.
        return lines.isEmpty ? nil : (lines, nil)
    }

    private static func resolveWriteDiff(
        _ arguments: [String: AnyCodable]?,
        keys: [String],
        details: AnyCodable?) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        let detailValues = details?.dictionaryValue
        guard detailValues?["changed"]?.boolValue != false else { return nil }
        guard let content = self.string(in: arguments, keys: keys) else { return nil }
        let allLines = self.splitLines(content)
        guard !allLines.isEmpty else { return nil }
        // Written content is fully known, so number additions from line 1 and
        // keep the exact stat even when the rendered preview is clipped.
        var lines: [ChatToolDiffLine] = []
        var remainingCharacters = self.maxLocalInputCharacters
        for (index, text) in allLines.prefix(self.maxWritePreviewLines).enumerated() {
            let lineCharacters = text.utf16.count
            guard lineCharacters <= remainingCharacters else { break }
            remainingCharacters -= lineCharacters
            lines.append(ChatToolDiffLine(kind: .add, lineNo: index + 1, text: text))
        }
        if lines.count < allLines.count {
            lines.append(ChatToolDiffLine(kind: .skip, text: ""))
        }
        // Present details need created=true before zero removals are authoritative.
        let stat = detailValues != nil && detailValues?["created"]?.boolValue != true
            ? nil
            : ChatToolDiffStat(added: allLines.count, removed: 0)
        return (lines, stat)
    }

    private static func resolveEditDiff(
        _ arguments: [String: AnyCodable]?,
        details: AnyCodable?) -> (lines: [ChatToolDiffLine], stat: ChatToolDiffStat?)?
    {
        // Persisted details are authoritative; args are a local fallback for live/foreign harnesses.
        if let detailsDiff = self.resolveDetailsDiff(details) {
            return detailsDiff
        }
        guard let arguments else { return nil }
        let resolved = self.readEditPairs(arguments)
        guard !resolved.pairs.isEmpty else {
            return resolved.truncated
                ? ([ChatToolDiffLine(kind: .skip, text: "")], nil)
                : nil
        }

        let sections = resolved.pairs.map { pair in
            self.computeLineDiff(old: pair.oldText, new: pair.newText)
        }
        let sectionTruncated = sections.contains { section in
            section.contains(where: { $0.kind == .skip })
        }
        let joined = self.join(sections, truncated: resolved.truncated)
        guard !joined.lines.isEmpty else { return nil }
        let truncated = resolved.truncated || sectionTruncated || joined.truncated
        let stat = truncated ? nil : sections.reduce(ChatToolDiffStat(added: 0, removed: 0)) { sum, section in
            let sectionStat = self.stat(for: section)
            return ChatToolDiffStat(
                added: sum.added + sectionStat.added,
                removed: sum.removed + sectionStat.removed)
        }
        return (joined.lines, stat)
    }

    private static func readEditPairs(
        _ arguments: [String: AnyCodable]) -> (pairs: [EditPair], truncated: Bool)
    {
        var pairs: [EditPair] = []
        var inputCharacters = 0
        var truncated = false

        func appendPair(oldValue: AnyCodable?, newValue: AnyCodable?) {
            guard let oldText = oldValue?.stringValue, let newText = newValue?.stringValue else { return }
            let pairCharacters = oldText.utf16.count + newText.utf16.count
            guard pairCharacters <= self.maxLocalInputCharacters - inputCharacters else {
                truncated = true
                return
            }
            inputCharacters += pairCharacters
            pairs.append(EditPair(oldText: oldText, newText: newText))
        }

        if let edits = arguments["edits"]?.arrayValue {
            for (index, edit) in edits.enumerated() {
                guard index < self.maxLocalPairs else {
                    truncated = true
                    break
                }
                guard let record = edit.dictionaryValue else { continue }
                appendPair(
                    oldValue: self.firstValue(in: record, keys: ["oldText", "old_string", "oldString", "old_str"]),
                    newValue: self.firstValue(in: record, keys: ["newText", "new_string", "newString", "new_str"]))
                if truncated { break }
            }
        } else {
            appendPair(
                oldValue: self.firstValue(
                    in: arguments,
                    keys: ["oldText", "old_string", "oldString", "old_str"]),
                newValue: self.firstValue(
                    in: arguments,
                    keys: ["newText", "new_string", "newString", "new_str"]))
        }
        return (pairs, truncated)
    }

    private static func join(
        _ sections: [[ChatToolDiffLine]],
        truncated initialTruncated: Bool) -> (lines: [ChatToolDiffLine], truncated: Bool)
    {
        var joined: [ChatToolDiffLine] = []
        var truncated = initialTruncated
        for section in sections where !section.isEmpty {
            if !joined.isEmpty {
                guard joined.count < self.maxRenderLines else {
                    truncated = true
                    break
                }
                joined.append(ChatToolDiffLine(kind: .skip, text: ""))
            }
            let remaining = self.maxRenderLines - joined.count
            guard section.count <= remaining else {
                joined.append(contentsOf: section.prefix(remaining))
                truncated = true
                break
            }
            joined.append(contentsOf: section)
        }
        if truncated, joined.last?.kind != .skip {
            joined.append(ChatToolDiffLine(kind: .skip, text: ""))
        }
        return (joined, truncated)
    }

    private static func stat(for lines: [ChatToolDiffLine]) -> ChatToolDiffStat {
        lines.reduce(ChatToolDiffStat(added: 0, removed: 0)) { stat, line in
            switch line.kind {
            case .add:
                ChatToolDiffStat(added: stat.added + 1, removed: stat.removed)
            case .del:
                ChatToolDiffStat(added: stat.added, removed: stat.removed + 1)
            case .ctx, .file, .skip:
                stat
            }
        }
    }

    private static func firstNonBlankString(
        in record: [String: AnyCodable]?,
        keys: [String]) -> String?
    {
        guard let record else { return nil }
        for key in keys {
            if let value = record[key]?.stringValue,
               !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
            {
                return value
            }
        }
        return nil
    }

    private static func string(in record: [String: AnyCodable]?, keys: [String]) -> String? {
        guard let record else { return nil }
        return self.firstValue(in: record, keys: keys)?.stringValue
    }

    private static func firstValue(in record: [String: AnyCodable], keys: [String]) -> AnyCodable? {
        for key in keys {
            if let value = record[key] {
                return value
            }
        }
        return nil
    }
}