rufio 1.5.1 → 1.6.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 (49) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +8 -3
  4. data/README_ja.md +7 -3
  5. data/Rakefile +5 -0
  6. data/SECURITY.md +2 -2
  7. data/docs/guide.md +41 -8
  8. data/docs/guide_ja.md +41 -8
  9. data/docs/native_fuzzy_search_design_ja.md +684 -0
  10. data/info/help.md +13 -4
  11. data/info/keybindings.md +5 -3
  12. data/info/welcome.md +2 -2
  13. data/lib/rufio/config.rb +0 -2
  14. data/lib/rufio/config_loader.rb +24 -4
  15. data/lib/rufio/fuzzy_candidate_block.rb +131 -0
  16. data/lib/rufio/fuzzy_candidate_cache.rb +258 -0
  17. data/lib/rufio/fuzzy_file_source.rb +180 -0
  18. data/lib/rufio/fuzzy_finder.rb +313 -0
  19. data/lib/rufio/fuzzy_preview_loader.rb +107 -0
  20. data/lib/rufio/fuzzy_search.rb +327 -0
  21. data/lib/rufio/fuzzy_search_session.rb +426 -0
  22. data/lib/rufio/global_search.rb +292 -51
  23. data/lib/rufio/health_checker.rb +0 -22
  24. data/lib/rufio/help_menu.rb +5 -4
  25. data/lib/rufio/keybind_handler.rb +6 -5
  26. data/lib/rufio/native/aarch64-linux-gnu/librufio_zig.so +0 -0
  27. data/lib/rufio/native/aarch64-linux-musl/librufio_zig.so +0 -0
  28. data/lib/rufio/native/aarch64-macos/librufio_zig.dylib +0 -0
  29. data/lib/rufio/native/aarch64-windows/rufio_zig.dll +0 -0
  30. data/lib/rufio/native/x86_64-linux-gnu/librufio_zig.so +0 -0
  31. data/lib/rufio/native/x86_64-linux-musl/librufio_zig.so +0 -0
  32. data/lib/rufio/native/x86_64-macos/librufio_zig.dylib +0 -0
  33. data/lib/rufio/native/x86_64-windows/rufio_zig.dll +0 -0
  34. data/lib/rufio/native_content_search.rb +43 -7
  35. data/lib/rufio/native_scanner_zig.rb +17 -0
  36. data/lib/rufio/rga_result_source.rb +89 -0
  37. data/lib/rufio/screen.rb +5 -1
  38. data/lib/rufio/search_controller.rb +56 -54
  39. data/lib/rufio/terminal_ui.rb +70 -8
  40. data/lib/rufio/ui_renderer.rb +1 -1
  41. data/lib/rufio/version.rb +1 -1
  42. data/lib/rufio.rb +6 -0
  43. data/lib_zig/rufio_native/Makefile +16 -2
  44. data/lib_zig/rufio_native/build.zig +8 -0
  45. data/lib_zig/rufio_native/src/fuzzy.zig +520 -0
  46. data/lib_zig/rufio_native/src/fuzzy_test.zig +212 -0
  47. data/lib_zig/rufio_native/src/main.zig +27 -0
  48. data/lib_zig/rufio_native/src/search.zig +221 -44
  49. metadata +13 -2
@@ -0,0 +1,327 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fiddle'
4
+ require 'fiddle/import'
5
+ require 'thread'
6
+ require_relative 'native_scanner'
7
+ require_relative 'native_scanner_zig'
8
+
9
+ module Rufio
10
+ # Persistent candidate index. No subprocesses; native and Ruby return the same
11
+ # scores and UTF-8 byte offsets. A session serializes access to its native handle.
12
+ # A query that extends the previous one (the previous query is a subsequence of it)
13
+ # only scores the previous matches plus candidates added since; see #scanned.
14
+ class FuzzySearch
15
+ MAX_QUERY_BYTES = 1024
16
+ MAX_CANDIDATE_BYTES = 65_536
17
+ MAX_RESULTS = 10_000
18
+ NEGATIVE = -(1 << 60)
19
+ SEPARATORS = [47, 92, 95, 45, 46, 32].freeze
20
+
21
+ attr_reader :total_matches
22
+
23
+ # Candidates scored by the last query. nil when an older native library cannot report it.
24
+ attr_reader :scanned
25
+
26
+ def initialize(native: true, library: nil)
27
+ @mutex = Mutex.new
28
+ @closed = false
29
+ @total_matches = 0
30
+ @candidates = []
31
+ @previous_query = nil
32
+ @previous_ids = nil
33
+ @previous_count = 0
34
+ @scanned = 0
35
+ if native && ENV['RUFIO_NATIVE_FUZZY'] != '0'
36
+ @api = load_api(library || NativeScannerZigFFI.library_path)
37
+ @handle = @api.core_fuzzy_create if @api
38
+ raise NoMemoryError, 'Cannot create fuzzy index' if @handle == 0
39
+ ObjectSpace.define_finalizer(self, self.class.finalizer(@api, @handle)) if @api
40
+ end
41
+ end
42
+
43
+ def self.finalizer(api, handle)
44
+ proc { api.core_fuzzy_destroy(handle) }
45
+ end
46
+
47
+ def native?
48
+ !@api.nil?
49
+ end
50
+
51
+ def add(candidates)
52
+ @mutex.synchronize do
53
+ ensure_open!
54
+ strings = candidates.map { |text| validate_text(text, MAX_CANDIDATE_BYTES) }
55
+ if native?
56
+ unless strings.empty?
57
+ packed = strings.join("\0") + "\0"
58
+ check_status(@api.core_fuzzy_add(@handle, packed, packed.bytesize))
59
+ end
60
+ else
61
+ @candidates.concat(strings.map { |text| prepare(text) })
62
+ end
63
+ end
64
+ self
65
+ end
66
+
67
+ # 「候補 NUL」を連結した 1 本のバイト列をそのまま登録する(add(packed.split("\0")) と同じ結果)。
68
+ # 候補ごとの Ruby 文字列を作らないので、件数が多いときは add より速い。
69
+ def add_packed(packed)
70
+ @mutex.synchronize do
71
+ ensure_open!
72
+ raise ArgumentError, 'Expected packed candidates' unless packed.is_a?(String)
73
+ next if packed.empty?
74
+ raise ArgumentError, 'Packed candidates must end with NUL' unless packed.end_with?("\0")
75
+
76
+ if native?
77
+ # UTF-8 と長さは Zig 側が全件を確認し、1 件でも不正なら何も登録しない
78
+ check_status(@api.core_fuzzy_add(@handle, packed, packed.bytesize))
79
+ else
80
+ strings = packed.b.split("\0".b, -1)
81
+ strings.pop
82
+ prepared = strings.map { |text| prepare(validate_text(text.force_encoding(Encoding::UTF_8), MAX_CANDIDATE_BYTES)) }
83
+ @candidates.concat(prepared)
84
+ end
85
+ end
86
+ self
87
+ end
88
+
89
+ # positions: 一致位置を求める上位の件数(既定は limit)。それより後の結果の :positions は nil になり、
90
+ # 表示するときに FuzzySearch.positions で求める(同じ結果になる)。
91
+ def query(text, limit: 100, positions: nil)
92
+ @mutex.synchronize do
93
+ ensure_open!
94
+ text = validate_text(text, MAX_QUERY_BYTES)
95
+ raise ArgumentError, 'Invalid result limit' unless limit.is_a?(Integer) && limit.between?(0, MAX_RESULTS)
96
+
97
+ positions = limit if positions.nil?
98
+ raise ArgumentError, 'Invalid position limit' unless positions.is_a?(Integer) && positions >= 0
99
+
100
+ positions = [positions, limit].min
101
+ native? ? query_native(text, limit, positions) : query_ruby(text, limit, positions)
102
+ end
103
+ end
104
+
105
+ # text の中で query が一致する位置(UTF-8 の先頭バイトオフセット)。query の結果と同じ位置を返す。
106
+ # 一致しなければ nil
107
+ def self.positions(text, query)
108
+ (@position_engine ||= new(native: false)).send(:positions_for, text, query)
109
+ end
110
+
111
+ def close
112
+ @mutex.synchronize do
113
+ return if @closed
114
+
115
+ if native?
116
+ ObjectSpace.undefine_finalizer(self)
117
+ @api.core_fuzzy_destroy(@handle)
118
+ end
119
+ @candidates.clear
120
+ @closed = true
121
+ end
122
+ end
123
+
124
+ private
125
+
126
+ def ensure_open!
127
+ raise IOError, 'Fuzzy index is closed' if @closed
128
+ end
129
+
130
+ def validate_text(text, max_bytes)
131
+ raise ArgumentError, 'Expected UTF-8 text' unless text.is_a?(String)
132
+
133
+ # Candidates are usually UTF-8 already; copying each one only to relabel it is wasted work.
134
+ utf8 = text.encoding == Encoding::UTF_8 ? text : text.dup.force_encoding(Encoding::UTF_8)
135
+ unless utf8.valid_encoding? && !utf8.include?("\0") && utf8.bytesize <= max_bytes
136
+ raise ArgumentError, 'Invalid UTF-8, NUL, or text too long'
137
+ end
138
+ utf8
139
+ end
140
+
141
+ def load_api(path)
142
+ return unless path && File.file?(path)
143
+
144
+ Module.new do
145
+ extend Fiddle::Importer
146
+ dlload path
147
+ extern 'uint64_t core_fuzzy_create()'
148
+ extern 'int32_t core_fuzzy_add(uint64_t, const char*, size_t)'
149
+ extern 'int32_t core_fuzzy_query(uint64_t, const char*, size_t, uint32_t)'
150
+ extern 'void* core_fuzzy_results(uint64_t, void*)'
151
+ extern 'void core_fuzzy_destroy(uint64_t)'
152
+ begin
153
+ extern 'uint64_t core_fuzzy_scanned(uint64_t)'
154
+ rescue Fiddle::DLError
155
+ nil # 1.6.0 development builds before narrowing
156
+ end
157
+ begin
158
+ extern 'int32_t core_fuzzy_query_positions(uint64_t, const char*, size_t, uint32_t, uint32_t)'
159
+ rescue Fiddle::DLError
160
+ nil # 1.6.0 development builds before position limits: every result gets positions
161
+ end
162
+ end
163
+ rescue Fiddle::DLError
164
+ nil
165
+ end
166
+
167
+ def check_status(status)
168
+ raise ArgumentError, 'Native fuzzy search rejected input' if status == -1
169
+ raise NoMemoryError, 'Native fuzzy search allocation failed' if status != 0
170
+ end
171
+
172
+ def query_native(text, limit, position_limit)
173
+ status = if position_limit < limit && @api.respond_to?(:core_fuzzy_query_positions)
174
+ @api.core_fuzzy_query_positions(@handle, text, text.bytesize, limit, position_limit)
175
+ else
176
+ @api.core_fuzzy_query(@handle, text, text.bytesize, limit)
177
+ end
178
+ check_status(status)
179
+ length = Fiddle::Pointer.malloc(Fiddle::SIZEOF_SIZE_T, Fiddle::RUBY_FREE)
180
+ pointer = @api.core_fuzzy_results(@handle, length)
181
+ bytes = length[0, Fiddle::SIZEOF_SIZE_T].unpack1(Fiddle::SIZEOF_SIZE_T == 8 ? 'Q' : 'L')
182
+ data = pointer.to_str(bytes)
183
+ @scanned = @api.respond_to?(:core_fuzzy_scanned) ? @api.core_fuzzy_scanned(@handle) : nil
184
+ @total_matches, count = data.unpack('Q<L<')
185
+ offset = 12
186
+ Array.new(count) do |rank|
187
+ id, score, size = data.byteslice(offset, 20).unpack('Q<q<L<')
188
+ positions = size.zero? && !text.empty? && rank >= position_limit ? nil : data.byteslice(offset + 20, size * 4).unpack('L<*')
189
+ offset += 20 + size * 4
190
+ { id: id, score: score, positions: positions }
191
+ end
192
+ end
193
+
194
+ def fold(codepoint)
195
+ codepoint.between?(65, 90) ? codepoint + 32 : codepoint
196
+ end
197
+
198
+ def prepare(text)
199
+ chars = text.codepoints
200
+ basename = (chars.rindex { |c| c == 47 || c == 92 } || -1) + 1
201
+ bytes = 0
202
+ offsets = chars.map do |char|
203
+ position = bytes
204
+ bytes += char.chr(Encoding::UTF_8).bytesize
205
+ position
206
+ end
207
+ bonuses = chars.each_index.map do |i|
208
+ boundary = i.zero? || SEPARATORS.include?(chars[i - 1]) ||
209
+ (chars[i - 1].between?(97, 122) && chars[i].between?(65, 90))
210
+ 16 + (i >= basename ? 8 : 0) + (boundary ? 8 : 0) + (i == basename ? 8 : 0)
211
+ end
212
+ [chars.map { |c| fold(c) }, offsets, bonuses]
213
+ end
214
+
215
+ # Two rolling rows for scoring; only retained candidates need backtracking.
216
+ def score(candidate, query, trace: false)
217
+ chars, offsets, bonuses = candidate
218
+ return [0, []] if query.empty?
219
+ return if query.length > chars.length
220
+
221
+ matched = 0
222
+ chars.each do |char|
223
+ matched += 1 if char == query[matched]
224
+ break if matched == query.length
225
+ end
226
+ return unless matched == query.length
227
+
228
+ previous = Array.new(chars.length, NEGATIVE)
229
+ parents = []
230
+ query.each_with_index do |char, row|
231
+ current = Array.new(chars.length, NEGATIVE)
232
+ parent = trace ? Array.new(chars.length, -1) : nil
233
+ prefix_score = NEGATIVE
234
+ prefix_index = -1
235
+ chars.each_index do |i|
236
+ if i >= 2 && previous[i - 2] != NEGATIVE && previous[i - 2] + i - 2 > prefix_score
237
+ prefix_score = previous[i - 2] + i - 2
238
+ prefix_index = i - 2
239
+ end
240
+ next unless chars[i] == char
241
+
242
+ if row.zero?
243
+ current[i] = bonuses[i]
244
+ else
245
+ value = prefix_score == NEGATIVE ? NEGATIVE : prefix_score - i + 1
246
+ source = prefix_index
247
+ if i > 0 && previous[i - 1] != NEGATIVE && previous[i - 1] + 24 > value
248
+ value = previous[i - 1] + 24
249
+ source = i - 1
250
+ end
251
+ next if value == NEGATIVE
252
+
253
+ current[i] = value + bonuses[i]
254
+ parent[i] = source if trace
255
+ end
256
+ end
257
+ parents << parent if trace
258
+ previous = current
259
+ end
260
+ best = previous.max
261
+ return if best == NEGATIVE
262
+
263
+ positions = []
264
+ if trace
265
+ index = previous.index(best)
266
+ (query.length - 1).downto(0) do |row|
267
+ positions << offsets[index]
268
+ index = parents[row][index]
269
+ end
270
+ positions.reverse!
271
+ end
272
+ [best - chars.length + (query.length == chars.length ? 64 : 0), positions]
273
+ end
274
+
275
+ def subsequence?(small, large)
276
+ matched = 0
277
+ large.each { |char| matched += 1 if matched < small.length && char == small[matched] }
278
+ matched == small.length
279
+ end
280
+
281
+ def positions_for(text, query)
282
+ raise ArgumentError, 'Expected UTF-8 text' unless text.is_a?(String) && query.is_a?(String)
283
+
284
+ folded = query.codepoints.map { |c| fold(c) }
285
+ return [] if folded.empty?
286
+
287
+ matched = score(prepare(text), folded, trace: true)
288
+ matched && matched[1]
289
+ end
290
+
291
+ def query_ruby(text, limit, position_limit)
292
+ query = text.codepoints.map { |c| fold(c) }
293
+ narrow = @previous_query && !query.empty? && subsequence?(@previous_query, query)
294
+ ids = narrow ? @previous_ids + (@previous_count...@candidates.length).to_a : (0...@candidates.length)
295
+ @scanned = ids.size
296
+ @previous_query = nil
297
+ matched_ids = []
298
+ @total_matches = 0
299
+ # Bounded sorted list: the fallback favors simplicity, while Zig uses a heap.
300
+ best = []
301
+ ids.each do |id|
302
+ candidate = @candidates[id]
303
+ matched = score(candidate, query)
304
+ next unless matched
305
+
306
+ matched_ids << id
307
+ @total_matches += 1
308
+ next if limit.zero?
309
+
310
+ key = [-matched[0], id]
311
+ at = best.bsearch_index { |item| ([-item[:score], item[:id]] <=> key) > 0 } || best.length
312
+ next if at >= limit
313
+
314
+ best.insert(at, { id: id, score: matched[0] })
315
+ best.pop if best.length > limit
316
+ end
317
+ unless query.empty?
318
+ @previous_query = query
319
+ @previous_ids = matched_ids
320
+ @previous_count = @candidates.length
321
+ end
322
+ best.each_with_index do |item, rank|
323
+ item[:positions] = rank < position_limit || query.empty? ? score(@candidates[item[:id]], query, trace: true)[1] : nil
324
+ end
325
+ end
326
+ end
327
+ end