context_drop 0.1.4 → 0.3.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 (50) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +330 -116
  3. data/Rakefile +110 -1
  4. data/SPEC.md +74 -26
  5. data/app/assets/javascripts/context_drop/context_drop.js +6329 -682
  6. data/app/controllers/context_drop/agent_controller.rb +170 -0
  7. data/app/controllers/context_drop/application_controller.rb +52 -3
  8. data/app/controllers/context_drop/configs_controller.rb +12 -2
  9. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  10. data/app/controllers/context_drop/feedbacks_controller.rb +396 -20
  11. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  12. data/app/helpers/context_drop/widget_helper.rb +11 -1
  13. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  14. data/app/javascript/context_drop/__tests__/widget.test.ts +1015 -89
  15. data/app/javascript/context_drop/api-client.ts +422 -19
  16. data/app/javascript/context_drop/element-picker.ts +186 -34
  17. data/app/javascript/context_drop/icons.ts +28 -0
  18. data/app/javascript/context_drop/markdown.ts +146 -0
  19. data/app/javascript/context_drop/sanitizer.ts +413 -2
  20. data/app/javascript/context_drop/screenshot.ts +103 -9
  21. data/app/javascript/context_drop/styles.ts +1705 -248
  22. data/app/javascript/context_drop/types.ts +243 -6
  23. data/app/javascript/context_drop/widget.ts +3318 -294
  24. data/app/models/context_drop/feedback.rb +88 -8
  25. data/app/services/context_drop/ownership_token.rb +114 -0
  26. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +13 -0
  27. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +19 -0
  28. data/app/views/layouts/context_drop/application.html.erb +6 -0
  29. data/config/routes.rb +22 -0
  30. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  31. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  32. data/lib/context_drop/agent/key_store.rb +290 -0
  33. data/lib/context_drop/agent/llm_client.rb +413 -0
  34. data/lib/context_drop/agent/orchestrator.rb +314 -0
  35. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  36. data/lib/context_drop/configuration.rb +242 -3
  37. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  38. data/lib/context_drop/mcp/environment_router.rb +115 -0
  39. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +90 -9
  40. data/lib/context_drop/mcp/remote_client.rb +120 -0
  41. data/lib/context_drop/mcp/server.rb +9 -2
  42. data/lib/context_drop/mcp/tools/get_feedback.rb +62 -5
  43. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +29 -4
  44. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  45. data/lib/context_drop/mcp/tools/list_feedbacks.rb +195 -23
  46. data/lib/context_drop/mcp/tools/update_feedback_status.rb +48 -5
  47. data/lib/context_drop/version.rb +1 -1
  48. data/lib/context_drop.rb +8 -2
  49. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  50. metadata +14 -2
@@ -0,0 +1,499 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "securerandom"
6
+
7
+ module ContextDrop
8
+ module Agent
9
+ class WorkspaceSandbox
10
+ class SandboxError < ContextDrop::Error; end
11
+
12
+ MAX_FILE_BYTES = 256 * 1024 # 256 KB
13
+ MAX_STAGED_EDITS = 100
14
+
15
+ BLOCKED_RELATIVE_PATTERNS = [
16
+ %r{\A\.git(?:/|\z)}i,
17
+ %r{(?:^|/)\.env(?:\.(?!example\z|sample\z|template\z)[^/]+)?\z}i,
18
+ %r{\Aconfig/master\.key\z}i,
19
+ %r{\Aconfig/credentials(?:/|\.yml\.enc\z)}i,
20
+ %r{\Atmp/context_drop_}i,
21
+ %r{\.(?:pem|key|p12|pfx|jks|sqlite3|db)\z}i,
22
+ %r{(?:^|/)id_(?:rsa|ed25519|ecdsa|dsa)}i,
23
+ %r{\A(?:node_modules|vendor/bundle|vendor/cache|storage|log|tmp/cache|pkg)(?:/|\z)}i
24
+ ].freeze
25
+
26
+ SKIPPED_DIR_NAMES = %w[
27
+ .git
28
+ node_modules
29
+ vendor
30
+ storage
31
+ log
32
+ tmp
33
+ pkg
34
+ coverage
35
+ .bundle
36
+ ].freeze
37
+
38
+ @edits_mutex = Mutex.new
39
+ @staged_edits = {}
40
+
41
+ class << self
42
+ def staged_edits_store
43
+ @staged_edits
44
+ end
45
+
46
+ def edits_mutex
47
+ @edits_mutex
48
+ end
49
+
50
+ def clear_staged_edits!
51
+ @edits_mutex.synchronize { @staged_edits.clear }
52
+ end
53
+ end
54
+
55
+ attr_reader :root_realpath
56
+
57
+ def initialize(workspace_root = nil)
58
+ raw_root = (workspace_root || ContextDrop.config.resolved_workspace_root).to_s
59
+ raise SandboxError, "Workspace root does not exist" unless Dir.exist?(raw_root)
60
+
61
+ @root_realpath = File.realpath(raw_root)
62
+ end
63
+
64
+ def resolve_safe_path!(relative_path, allow_nonexistent: false)
65
+ raw = relative_path.to_s.strip
66
+ raise SandboxError, "File path is required" if raw.empty?
67
+ raise SandboxError, "Invalid null byte in path" if raw.include?("\0")
68
+
69
+ cleaned = raw.sub(%r{\A/+}, "")
70
+ expanded = File.expand_path(cleaned, @root_realpath)
71
+ ensure_inside_root!(expanded)
72
+
73
+ rel_from_root = strip_root_prefix(expanded)
74
+ ensure_not_denylisted!(rel_from_root)
75
+
76
+ if File.exist?(expanded) || File.symlink?(expanded)
77
+ real = File.realpath(expanded)
78
+ ensure_inside_root!(real)
79
+ real_rel = strip_root_prefix(real)
80
+ ensure_not_denylisted!(real_rel)
81
+ [real, real_rel]
82
+ elsif allow_nonexistent
83
+ parent = find_existing_ancestor(File.dirname(expanded))
84
+ real_parent = File.realpath(parent)
85
+ ensure_inside_root!(real_parent)
86
+ remainder = expanded.delete_prefix(parent).sub(%r{\A/+}, "")
87
+ target_abs = remainder.empty? ? real_parent : File.join(real_parent, remainder)
88
+ ensure_inside_root!(target_abs)
89
+ target_rel = strip_root_prefix(target_abs)
90
+ ensure_not_denylisted!(target_rel)
91
+ [target_abs, target_rel]
92
+ else
93
+ raise SandboxError, "File not found: #{rel_from_root}"
94
+ end
95
+ end
96
+
97
+ def list_files(directory: ".", pattern: nil, limit: 200)
98
+ abs_dir, _rel_dir = if directory.to_s.strip.empty? || directory.to_s.strip == "."
99
+ [@root_realpath, "."]
100
+ else
101
+ resolve_safe_path!(directory)
102
+ end
103
+ raise SandboxError, "Not a directory: #{directory}" unless File.directory?(abs_dir)
104
+
105
+ capped_limit = limit.to_i.clamp(1, 500)
106
+ results = []
107
+ matcher = pattern.to_s.strip.empty? ? nil : pattern.to_s.strip
108
+
109
+ walk_workspace(abs_dir) do |abs_file, rel_file|
110
+ if matcher
111
+ next unless File.fnmatch?(matcher, rel_file, File::FNM_PATHNAME | File::FNM_EXTGLOB) ||
112
+ File.fnmatch?(matcher, File.basename(rel_file), File::FNM_EXTGLOB) ||
113
+ rel_file.include?(matcher)
114
+ end
115
+
116
+ results << rel_file
117
+ break if results.size >= capped_limit
118
+ end
119
+
120
+ { files: results.sort, truncated: results.size >= capped_limit }
121
+ end
122
+
123
+ def read_file(path:, start_line: 1, end_line: 250)
124
+ abs_path, rel_path = resolve_safe_path!(path)
125
+ raise SandboxError, "Cannot read directory as file: #{rel_path}" if File.directory?(abs_path)
126
+
127
+ size = File.size(abs_path)
128
+ if size > MAX_FILE_BYTES
129
+ raise SandboxError, "File #{rel_path} exceeds 256 KB safety limit (#{size} bytes)"
130
+ end
131
+
132
+ raw = File.binread(abs_path)
133
+ raise SandboxError, "Binary file cannot be read as text: #{rel_path}" if binary_bytes?(raw)
134
+
135
+ text = raw.force_encoding("UTF-8")
136
+ text = text.encode("UTF-8", invalid: :replace, undef: :replace) unless text.valid_encoding?
137
+
138
+ lines = text.lines
139
+ total = lines.size
140
+ s_line = [start_line.to_i, 1].max
141
+ e_line = [end_line.to_i, s_line].max
142
+ e_line = [e_line, s_line + 399, [total, 1].max].min
143
+
144
+ slice = total.zero? ? [] : (lines[(s_line - 1)..(e_line - 1)] || [])
145
+ numbered = slice.each_with_index.map do |line, idx|
146
+ "#{s_line + idx}: #{line.chomp}"
147
+ end.join("\n")
148
+
149
+ {
150
+ path: rel_path,
151
+ total_lines: total,
152
+ start_line: s_line,
153
+ end_line: total.zero? ? 0 : [e_line, total].min,
154
+ content: numbered
155
+ }
156
+ end
157
+
158
+ def search_code(query:, directory: ".", max_results: 40)
159
+ q = query.to_s
160
+ raise SandboxError, "Search query cannot be empty" if q.strip.empty?
161
+
162
+ abs_dir, _rel = if directory.to_s.strip.empty? || directory.to_s.strip == "."
163
+ [@root_realpath, "."]
164
+ else
165
+ resolve_safe_path!(directory)
166
+ end
167
+ raise SandboxError, "Not a directory: #{directory}" unless File.directory?(abs_dir)
168
+
169
+ capped = max_results.to_i.clamp(1, 100)
170
+ matches = []
171
+ down_q = q.downcase
172
+
173
+ walk_workspace(abs_dir) do |abs_file, rel_file|
174
+ next if File.size(abs_file) > MAX_FILE_BYTES
175
+
176
+ raw = File.binread(abs_file)
177
+ next if binary_bytes?(raw)
178
+
179
+ text = raw.force_encoding("UTF-8")
180
+ next unless text.valid_encoding?
181
+
182
+ text.each_line.with_index(1) do |line, line_num|
183
+ next unless line.downcase.include?(down_q)
184
+
185
+ matches << {
186
+ path: rel_file,
187
+ line: line_num,
188
+ snippet: line.chomp.strip[0, 220]
189
+ }
190
+ break if matches.size >= capped
191
+ end
192
+ break if matches.size >= capped
193
+ end
194
+
195
+ { query: q, matches: matches, truncated: matches.size >= capped }
196
+ end
197
+
198
+ # Stages a proposed file edit WITHOUT modifying disk. Requires explicit human approval via `apply_edit!`.
199
+ def stage_edit(path:, old_string:, new_string:, summary: nil)
200
+ old_s = old_string.to_s
201
+ new_s = new_string.to_s
202
+ creating_new = old_s.empty?
203
+
204
+ abs_path, rel_path = resolve_safe_path!(path, allow_nonexistent: creating_new)
205
+ raise SandboxError, "Cannot edit a directory: #{rel_path}" if File.directory?(abs_path)
206
+
207
+ if File.exist?(abs_path)
208
+ size = File.size(abs_path)
209
+ raise SandboxError, "File #{rel_path} exceeds 256 KB limit" if size > MAX_FILE_BYTES
210
+
211
+ raw = File.binread(abs_path)
212
+ raise SandboxError, "Binary file cannot be edited: #{rel_path}" if binary_bytes?(raw)
213
+
214
+ original_content = raw.force_encoding("UTF-8")
215
+ raise SandboxError, "File #{rel_path} is not valid UTF-8" unless original_content.valid_encoding?
216
+
217
+ if creating_new
218
+ raise SandboxError, "File #{rel_path} already exists; provide `old_string` with exact context lines to replace."
219
+ end
220
+
221
+ occurrences = count_exact_occurrences(original_content, old_s)
222
+ if occurrences.zero?
223
+ raise SandboxError, "Could not find exact `old_string` match in #{rel_path}. Read the file first to verify exact whitespace."
224
+ elsif occurrences > 1
225
+ raise SandboxError, "`old_string` matched #{occurrences} places in #{rel_path}; include more surrounding context lines."
226
+ end
227
+
228
+ proposed_content = original_content.sub(old_s) { new_s }
229
+ original_sha = Digest::SHA256.hexdigest(original_content)
230
+ else
231
+ raise SandboxError, "File #{rel_path} does not exist" unless creating_new
232
+
233
+ original_content = ""
234
+ proposed_content = new_s
235
+ original_sha = "NEW_FILE"
236
+ end
237
+
238
+ if proposed_content.bytesize > MAX_FILE_BYTES
239
+ raise SandboxError, "Proposed content exceeds 256 KB limit"
240
+ end
241
+
242
+ diff_info = build_unified_diff(rel_path, original_content, proposed_content, is_new: original_sha == "NEW_FILE")
243
+ edit_id = "edit_#{SecureRandom.hex(8)}"
244
+
245
+ record = {
246
+ id: edit_id,
247
+ workspace_root: @root_realpath,
248
+ path: rel_path,
249
+ summary: summary.to_s.strip.empty? ? "Update #{rel_path}" : summary.to_s.strip,
250
+ is_new_file: original_sha == "NEW_FILE",
251
+ original_sha256: original_sha,
252
+ original_content: original_content,
253
+ proposed_content: proposed_content,
254
+ applied_sha256: nil,
255
+ diff: diff_info[:diff],
256
+ added_lines: diff_info[:added],
257
+ removed_lines: diff_info[:removed],
258
+ status: "pending",
259
+ created_at: Time.now.utc.iso8601
260
+ }
261
+
262
+ self.class.edits_mutex.synchronize do
263
+ store = self.class.staged_edits_store
264
+ store.shift while store.size >= MAX_STAGED_EDITS
265
+ store[edit_id] = record
266
+ end
267
+
268
+ serialize_edit_record(record)
269
+ end
270
+
271
+ def apply_edit!(edit_id)
272
+ record = fetch_workspace_edit!(edit_id)
273
+ unless record[:status] == "pending"
274
+ raise SandboxError, "Edit #{edit_id} cannot be applied (current status: #{record[:status]})"
275
+ end
276
+
277
+ abs_path, _rel = resolve_safe_path!(record[:path], allow_nonexistent: record[:is_new_file])
278
+
279
+ if record[:is_new_file]
280
+ if File.exist?(abs_path)
281
+ raise SandboxError, "Conflict: #{record[:path]} was created after this edit was proposed"
282
+ end
283
+ else
284
+ raise SandboxError, "Conflict: #{record[:path]} no longer exists" unless File.exist?(abs_path)
285
+
286
+ current_content = File.binread(abs_path).force_encoding("UTF-8")
287
+ current_sha = Digest::SHA256.hexdigest(current_content)
288
+ if current_sha != record[:original_sha256]
289
+ raise SandboxError, "Conflict: #{record[:path]} has been modified on disk since this diff was proposed"
290
+ end
291
+ end
292
+
293
+ atomic_write_text!(abs_path, record[:proposed_content])
294
+ self.class.edits_mutex.synchronize do
295
+ record[:applied_sha256] = Digest::SHA256.hexdigest(record[:proposed_content])
296
+ record[:status] = "applied"
297
+ record[:applied_at] = Time.now.utc.iso8601
298
+ end
299
+
300
+ serialize_edit_record(record)
301
+ end
302
+
303
+ def reject_edit!(edit_id)
304
+ record = fetch_workspace_edit!(edit_id)
305
+ unless record[:status] == "pending"
306
+ raise SandboxError, "Edit #{edit_id} is already #{record[:status]}"
307
+ end
308
+
309
+ self.class.edits_mutex.synchronize do
310
+ record[:status] = "rejected"
311
+ end
312
+ serialize_edit_record(record)
313
+ end
314
+
315
+ def revert_edit!(edit_id)
316
+ record = fetch_workspace_edit!(edit_id)
317
+ unless record[:status] == "applied"
318
+ raise SandboxError, "Only applied edits can be reverted (current status: #{record[:status]})"
319
+ end
320
+
321
+ abs_path, _rel = resolve_safe_path!(record[:path], allow_nonexistent: false)
322
+ current_content = File.binread(abs_path).force_encoding("UTF-8")
323
+ current_sha = Digest::SHA256.hexdigest(current_content)
324
+
325
+ if current_sha != record[:applied_sha256]
326
+ raise SandboxError, "Conflict: #{record[:path]} was modified again after applying; refusing to overwrite"
327
+ end
328
+
329
+ if record[:is_new_file]
330
+ File.delete(abs_path)
331
+ else
332
+ atomic_write_text!(abs_path, record[:original_content])
333
+ end
334
+
335
+ self.class.edits_mutex.synchronize do
336
+ record[:status] = "reverted"
337
+ end
338
+
339
+ serialize_edit_record(record)
340
+ end
341
+
342
+ private
343
+
344
+ def fetch_workspace_edit!(edit_id)
345
+ rec = self.class.edits_mutex.synchronize { self.class.staged_edits_store[edit_id.to_s] }
346
+ raise SandboxError, "Edit proposal '#{edit_id}' not found or expired" unless rec
347
+ if rec[:workspace_root] != @root_realpath
348
+ raise SandboxError, "Edit proposal belongs to a different workspace"
349
+ end
350
+
351
+ rec
352
+ end
353
+
354
+ def serialize_edit_record(rec)
355
+ {
356
+ id: rec[:id],
357
+ path: rec[:path],
358
+ summary: rec[:summary],
359
+ is_new_file: rec[:is_new_file],
360
+ diff: rec[:diff],
361
+ added_lines: rec[:added_lines],
362
+ removed_lines: rec[:removed_lines],
363
+ status: rec[:status],
364
+ created_at: rec[:created_at]
365
+ }
366
+ end
367
+
368
+ def atomic_write_text!(abs_path, content)
369
+ dir = File.dirname(abs_path)
370
+ FileUtils.mkdir_p(dir)
371
+ mode = File.exist?(abs_path) ? (File.stat(abs_path).mode & 0o777) : 0o644
372
+ tmp = File.join(dir, ".cd_edit_#{SecureRandom.hex(6)}.tmp")
373
+ File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC, mode) do |f|
374
+ f.write(content)
375
+ end
376
+ File.rename(tmp, abs_path)
377
+ end
378
+
379
+ def count_exact_occurrences(haystack, needle)
380
+ count = 0
381
+ idx = 0
382
+ while (found = haystack.index(needle, idx))
383
+ count += 1
384
+ idx = found + [needle.length, 1].max
385
+ end
386
+ count
387
+ end
388
+
389
+ def build_unified_diff(rel_path, before_text, after_text, is_new: false)
390
+ old_lines = before_text.lines.map(&:chomp)
391
+ new_lines = after_text.lines.map(&:chomp)
392
+
393
+ prefix = 0
394
+ while prefix < old_lines.size && prefix < new_lines.size && old_lines[prefix] == new_lines[prefix]
395
+ prefix += 1
396
+ end
397
+
398
+ old_suffix = old_lines.size - 1
399
+ new_suffix = new_lines.size - 1
400
+ while old_suffix >= prefix && new_suffix >= prefix && old_lines[old_suffix] == new_lines[new_suffix]
401
+ old_suffix -= 1
402
+ new_suffix -= 1
403
+ end
404
+
405
+ removed = prefix <= old_suffix ? old_lines[prefix..old_suffix] : []
406
+ added = prefix <= new_suffix ? new_lines[prefix..new_suffix] : []
407
+
408
+ ctx_before_start = [prefix - 3, 0].max
409
+ ctx_before = prefix.positive? ? old_lines[ctx_before_start...prefix] : []
410
+ ctx_after = (old_suffix + 1) < old_lines.size ? old_lines[(old_suffix + 1)..[old_suffix + 3, old_lines.size - 1].min] : []
411
+
412
+ old_start = is_new ? 0 : ctx_before_start + 1
413
+ new_start = ctx_before_start + 1
414
+ old_len = is_new ? 0 : (ctx_before.size + removed.size + ctx_after.size)
415
+ new_len = ctx_before.size + added.size + ctx_after.size
416
+
417
+ header = [
418
+ "--- #{is_new ? '/dev/null' : "a/#{rel_path}"}",
419
+ "+++ b/#{rel_path}",
420
+ "@@ -#{old_start},#{old_len} +#{new_start},#{new_len} @@"
421
+ ]
422
+
423
+ body = []
424
+ ctx_before.each { |l| body << " #{l}" }
425
+ removed.each { |l| body << "-#{l}" }
426
+ added.each { |l| body << "+#{l}" }
427
+ ctx_after.each { |l| body << " #{l}" }
428
+
429
+ {
430
+ diff: (header + body).join("\n"),
431
+ added: added.size,
432
+ removed: removed.size
433
+ }
434
+ end
435
+
436
+ def walk_workspace(start_dir, &block)
437
+ queue = [start_dir]
438
+ until queue.empty?
439
+ current_dir = queue.shift
440
+ entries = Dir.children(current_dir).sort
441
+ entries.each do |entry|
442
+ full = File.join(current_dir, entry)
443
+ next if File.symlink?(full)
444
+
445
+ rel = strip_root_prefix(full)
446
+ if File.directory?(full)
447
+ next if SKIPPED_DIR_NAMES.include?(entry)
448
+ next if denylisted?(rel)
449
+
450
+ queue << full
451
+ elsif File.file?(full)
452
+ next if denylisted?(rel)
453
+
454
+ block.call(full, rel)
455
+ end
456
+ end
457
+ end
458
+ end
459
+
460
+ def binary_bytes?(raw)
461
+ sample = raw.byteslice(0, 4096) || ""
462
+ sample.include?("\0")
463
+ end
464
+
465
+ def find_existing_ancestor(dir)
466
+ curr = dir
467
+ while !File.exist?(curr) && curr != "/" && curr != "."
468
+ parent = File.dirname(curr)
469
+ break if parent == curr
470
+
471
+ curr = parent
472
+ end
473
+ curr
474
+ end
475
+
476
+ def ensure_inside_root!(path_str)
477
+ return if path_str == @root_realpath || path_str.start_with?("#{@root_realpath}/")
478
+
479
+ raise SandboxError, "Access denied: path escapes workspace root"
480
+ end
481
+
482
+ def strip_root_prefix(abs_path)
483
+ return "." if abs_path == @root_realpath
484
+
485
+ abs_path.delete_prefix("#{@root_realpath}/")
486
+ end
487
+
488
+ def denylisted?(rel_path)
489
+ BLOCKED_RELATIVE_PATTERNS.any? { |re| re.match?(rel_path) }
490
+ end
491
+
492
+ def ensure_not_denylisted!(rel_path)
493
+ return unless denylisted?(rel_path)
494
+
495
+ raise SandboxError, "Access denied: '#{rel_path}' is protected by ContextDrop security policy"
496
+ end
497
+ end
498
+ end
499
+ end