Skip to content
Kward Search API index

Class: Kward::SessionDiff

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/session_diff.rb

Overview

Counts unified-diff additions and deletions for summaries.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(additions: 0, deletions: 0) ⇒ SessionDiff

Returns a new instance of SessionDiff.



7
8
9
10
11
# File 'lib/kward/session_diff.rb', line 7

def initialize(additions: 0, deletions: 0)
  @base_additions = additions.to_i
  @base_deletions = deletions.to_i
  @file_changes = Hash.new { |changes, path| changes[path] = { removed: [], added: [] } }
end

Class Method Details

.changed_lines_by_file(diff) ⇒ Object



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
# File 'lib/kward/session_diff.rb', line 148

def self.changed_lines_by_file(diff)
  current_path = nil
  changes = Hash.new { |file_changes, path| file_changes[path] = { removed: [], added: [] } }
  removed = []
  added = []
  flush = lambda do
    unmatched = unmatched_lines(removed, added)
    changes[current_path][:removed].concat(unmatched[:removed]) if current_path
    changes[current_path][:added].concat(unmatched[:added]) if current_path
    removed.clear
    added.clear
  end

  diff.to_s.each_line do |line|
    if line.start_with?("--- ")
      flush.call
      current_path = line[4..].to_s.chomp
    elsif line.start_with?("+") && !line.start_with?("+++")
      added << line[1..]
    elsif line.start_with?("-") && !line.start_with?("---")
      removed << line[1..]
    else
      flush.call
    end
  end
  flush.call
  changes.reject { |_path, lines| lines[:removed].empty? && lines[:added].empty? }
end

.common_line_count(left, right) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/kward/session_diff.rb', line 132

def self.common_line_count(left, right)
  previous = Array.new(right.length + 1, 0)
  left.each do |left_line|
    current = Array.new(right.length + 1, 0)
    right.each_with_index do |right_line, index|
      current[index + 1] = if left_line == right_line
                             previous[index] + 1
                           else
                             [current[index], previous[index + 1]].max
                           end
    end
    previous = current
  end
  previous.last
end

.common_line_indexes(left, right) ⇒ Object



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
# File 'lib/kward/session_diff.rb', line 187

def self.common_line_indexes(left, right)
  lengths = Array.new(left.length + 1) { Array.new(right.length + 1, 0) }
  left.each_with_index do |left_line, left_index|
    right.each_with_index do |right_line, right_index|
      lengths[left_index + 1][right_index + 1] = if left_line == right_line
                                                    lengths[left_index][right_index] + 1
                                                  else
                                                    [lengths[left_index + 1][right_index], lengths[left_index][right_index + 1]].max
                                                  end
    end
  end

  indexes = []
  left_index = left.length
  right_index = right.length
  while left_index.positive? && right_index.positive?
    if left[left_index - 1] == right[right_index - 1]
      indexes.unshift([left_index - 1, right_index - 1])
      left_index -= 1
      right_index -= 1
    elsif lengths[left_index - 1][right_index] >= lengths[left_index][right_index - 1]
      left_index -= 1
    else
      right_index -= 1
    end
  end
  indexes
end

.content_from_records(records) ⇒ Object



47
48
49
# File 'lib/kward/session_diff.rb', line 47

def self.content_from_records(records)
  records.filter_map { |record| record_diff(record) }.join("\n")
end

.content_from_session_file(path) ⇒ Object



28
29
30
31
32
33
# File 'lib/kward/session_diff.rb', line 28

def self.content_from_session_file(path)
  records = File.readlines(path, chomp: true).filter_map { |line| parse_record(line) }
  content_from_records(records)
rescue Errno::ENOENT, Errno::EACCES
  ""
end

.count(diff) ⇒ Object



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
# File 'lib/kward/session_diff.rb', line 59

def self.count(diff)
  if (stats = truncated_diff_stats(diff))
    return stats
  elsif truncated_diff?(diff)
    return { additions: 0, deletions: 0 }
  end

  additions = 0
  deletions = 0
  removed = []
  added = []
  flush = lambda do
    common = common_line_count(removed, added)
    additions += added.length - common
    deletions += removed.length - common
    removed.clear
    added.clear
  end

  diff.to_s.each_line do |line|
    if line.start_with?("+") && !line.start_with?("+++")
      added << line[1..]
    elsif line.start_with?("-") && !line.start_with?("---")
      removed << line[1..]
    else
      flush.call
    end
  end
  flush.call
  { additions: additions, deletions: deletions }
end

.from_records(records) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/kward/session_diff.rb', line 35

def self.from_records(records)
  execution_records = records.select { |record| record["type"] == "tool_execution_end" }
  source_records = execution_records.empty? ? records : execution_records
  source_records.each_with_object(new) do |record, diff|
    if record["type"] == "tool_execution_end"
      diff.add_diff(record_diff(record))
    elsif record["type"] == "message" && (record.dig("message", "role") == "tool" || record.dig("message", :role) == "tool")
      diff.add_tool_result(record.dig("message", "content") || record.dig("message", :content))
    end
  end
end

.from_session_file(path) ⇒ Object



21
22
23
24
25
26
# File 'lib/kward/session_diff.rb', line 21

def self.from_session_file(path)
  records = File.readlines(path, chomp: true).filter_map { |line| parse_record(line) }
  from_records(records)
rescue Errno::ENOENT, Errno::EACCES
  new
end

.parse_record(line) ⇒ Object



216
217
218
219
220
# File 'lib/kward/session_diff.rb', line 216

def self.parse_record(line)
  JSON.parse(line)
rescue JSON::ParserError
  nil
end

.record_diff(record) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/kward/session_diff.rb', line 51

def self.record_diff(record)
  return nil unless record["type"] == "tool_execution_end"
  return nil if record["isError"] || record.dig("result", "isError")

  diff = record.dig("result", "diff").to_s
  diff.empty? ? nil : diff
end

.truncated_diff?(diff) ⇒ Boolean

Returns:

  • (Boolean)


128
129
130
# File 'lib/kward/session_diff.rb', line 128

def self.truncated_diff?(diff)
  diff.to_s.match?(/^\.\.\. diff truncated to \d+ bytes;/)
end

.truncated_diff_stats(diff) ⇒ Object



121
122
123
124
125
126
# File 'lib/kward/session_diff.rb', line 121

def self.truncated_diff_stats(diff)
  match = diff.to_s.match(/^\.\.\. diff truncated to \d+ bytes; full diff stats: \+(\d+)\|-(\d+)\./)
  return nil unless match

  { additions: match[1].to_i, deletions: match[2].to_i }
end

.unmatched_lines(left, right) ⇒ Object



177
178
179
180
181
182
183
184
185
# File 'lib/kward/session_diff.rb', line 177

def self.unmatched_lines(left, right)
  matches = common_line_indexes(left, right)
  left_matches = matches.map(&:first)
  right_matches = matches.map(&:last)
  {
    removed: left.each_index.reject { |index| left_matches.include?(index) }.map { |index| left[index] },
    added: right.each_index.reject { |index| right_matches.include?(index) }.map { |index| right[index] }
  }
end

Instance Method Details

#add_diff(diff) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/kward/session_diff.rb', line 102

def add_diff(diff)
  if self.class.truncated_diff_stats(diff) || self.class.truncated_diff?(diff)
    counts = self.class.count(diff)
    return false if counts[:additions].zero? && counts[:deletions].zero?

    @base_additions += counts[:additions]
    @base_deletions += counts[:deletions]
    return true
  end

  changes = self.class.changed_lines_by_file(diff)
  return false if changes.empty?

  changes.each { |path, lines| apply_file_change(path, lines) }
  true
end

#add_tool_result(content) ⇒ Object



95
96
97
98
99
100
# File 'lib/kward/session_diff.rb', line 95

def add_tool_result(content)
  text = content.to_s
  return false if text.start_with?("Error:", "Declined:")

  add_diff(extract_unified_diff(text))
end

#additionsObject



13
14
15
# File 'lib/kward/session_diff.rb', line 13

def additions
  @base_additions + @file_changes.values.sum { |changes| changes[:added].length }
end

#deletionsObject



17
18
19
# File 'lib/kward/session_diff.rb', line 17

def deletions
  @base_deletions + @file_changes.values.sum { |changes| changes[:removed].length }
end

#empty?Boolean

Returns:

  • (Boolean)


91
92
93
# File 'lib/kward/session_diff.rb', line 91

def empty?
  additions.zero? && deletions.zero?
end