rubyn-code 0.7.0 → 0.8.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 (62) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +17 -1
  3. data/lib/rubyn_code/agent/conversation.rb +11 -1
  4. data/lib/rubyn_code/agent/dynamic_tool_schema.rb +1 -1
  5. data/lib/rubyn_code/agent/llm_caller.rb +5 -1
  6. data/lib/rubyn_code/agent/loop.rb +57 -3
  7. data/lib/rubyn_code/agent/response_parser.rb +8 -0
  8. data/lib/rubyn_code/agent/system_prompt_builder.rb +3 -0
  9. data/lib/rubyn_code/agent/tool_processor.rb +10 -0
  10. data/lib/rubyn_code/autonomous/daemon.rb +1 -1
  11. data/lib/rubyn_code/cli/commands/context.rb +27 -0
  12. data/lib/rubyn_code/cli/commands/custom_command.rb +44 -2
  13. data/lib/rubyn_code/cli/commands/custom_loader.rb +36 -5
  14. data/lib/rubyn_code/cli/commands/effort.rb +47 -0
  15. data/lib/rubyn_code/cli/commands/export.rb +174 -0
  16. data/lib/rubyn_code/cli/commands/mcp.rb +32 -8
  17. data/lib/rubyn_code/cli/commands/resume.rb +97 -26
  18. data/lib/rubyn_code/cli/commands/think.rb +47 -0
  19. data/lib/rubyn_code/cli/first_run.rb +1 -1
  20. data/lib/rubyn_code/cli/mention_expander.rb +19 -0
  21. data/lib/rubyn_code/cli/repl.rb +31 -1
  22. data/lib/rubyn_code/cli/repl_commands.rb +1 -1
  23. data/lib/rubyn_code/cli/repl_setup.rb +8 -6
  24. data/lib/rubyn_code/config/defaults.rb +2 -1
  25. data/lib/rubyn_code/config/schema.json +5 -0
  26. data/lib/rubyn_code/config/settings.rb +4 -2
  27. data/lib/rubyn_code/context/auto_compact.rb +1 -1
  28. data/lib/rubyn_code/context/manual_compact.rb +1 -1
  29. data/lib/rubyn_code/index/codebase_index.rb +64 -3
  30. data/lib/rubyn_code/index/prism_extractor.rb +82 -0
  31. data/lib/rubyn_code/learning/injector.rb +1 -2
  32. data/lib/rubyn_code/llm/adapters/anthropic.rb +107 -17
  33. data/lib/rubyn_code/llm/adapters/anthropic_streaming.rb +13 -0
  34. data/lib/rubyn_code/llm/adapters/base.rb +2 -1
  35. data/lib/rubyn_code/llm/adapters/openai.rb +1 -1
  36. data/lib/rubyn_code/llm/adapters/openai_message_translator.rb +21 -0
  37. data/lib/rubyn_code/llm/client.rb +16 -3
  38. data/lib/rubyn_code/llm/image_reader.rb +60 -0
  39. data/lib/rubyn_code/llm/message_builder.rb +21 -1
  40. data/lib/rubyn_code/llm/model_router.rb +4 -4
  41. data/lib/rubyn_code/mcp/discovery.rb +93 -0
  42. data/lib/rubyn_code/memory/session_persistence.rb +1 -1
  43. data/lib/rubyn_code/observability/cost_calculator.rb +6 -3
  44. data/lib/rubyn_code/protocols/RUBYN.md +0 -3
  45. data/lib/rubyn_code/tasks/models.rb +0 -16
  46. data/lib/rubyn_code/teams/teammate.rb +0 -15
  47. data/lib/rubyn_code/tools/RUBYN.md +2 -2
  48. data/lib/rubyn_code/tools/bash.rb +3 -3
  49. data/lib/rubyn_code/tools/code_graph.rb +134 -0
  50. data/lib/rubyn_code/tools/executor.rb +4 -1
  51. data/lib/rubyn_code/tools/todo_store.rb +55 -0
  52. data/lib/rubyn_code/tools/todo_write.rb +88 -0
  53. data/lib/rubyn_code/version.rb +1 -1
  54. data/lib/rubyn_code.rb +13 -8
  55. data/skills/rubyn_self_test.md +140 -0
  56. metadata +10 -7
  57. data/lib/rubyn_code/context/context_budget.rb +0 -183
  58. data/lib/rubyn_code/context/schema_filter.rb +0 -64
  59. data/lib/rubyn_code/learning/shortcut.rb +0 -95
  60. data/lib/rubyn_code/llm/adapters/token_caching.rb +0 -54
  61. data/lib/rubyn_code/llm/streaming.rb +0 -10
  62. data/lib/rubyn_code/protocols/plan_approval.rb +0 -72
@@ -449,6 +449,146 @@ fast and need no API calls.
449
449
  '
450
450
  ```
451
451
 
452
+ #### 17k. Extended thinking + `/think` toggle (PRs #132, #138)
453
+ - **bash**: confirms `LLM::ThinkingBlock` is defined, the Anthropic adapter
454
+ translates `thinking: {budget_tokens}` into the request body, and `/think`
455
+ toggles state on `LLM::Client`. PASS if the final line is `THINKING: PASS`.
456
+
457
+ ```bash
458
+ bundle exec ruby -Ilib -rrubyn_code -rrubyn_code/llm/message_builder -e '
459
+ tb = RubynCode::LLM::ThinkingBlock.new(text: "plan")
460
+ adapter = RubynCode::LLM::Adapters::Anthropic.allocate
461
+ body = {}
462
+ adapter.send(:apply_thinking, body, budget_tokens: 4096)
463
+ client = RubynCode::LLM::Client.allocate
464
+ client.thinking_budget_tokens = 4096
465
+ ok = (tb.type == "thinking") &&
466
+ (body[:thinking] == { type: "enabled", budget_tokens: 4096 }) &&
467
+ (client.thinking_budget_tokens == 4096)
468
+ puts(ok ? "THINKING: PASS" : "THINKING: FAIL")
469
+ '
470
+ ```
471
+
472
+ #### 17l. Image / vision input (`@image.png`) (PRs #133, #140, #141)
473
+ - **bash**: confirms `LLM::ImageBlock`, `LLM::ImageReader`, and
474
+ `MentionExpander#expand_images` are wired and base64-encode PNGs.
475
+ PASS if the final line is `IMAGES: PASS`.
476
+
477
+ ```bash
478
+ bundle exec ruby -Ilib -rrubyn_code -rrubyn_code/llm/message_builder -e '
479
+ require "tmpdir"
480
+ Dir.mktmpdir do |dir|
481
+ path = File.join(dir, "p.png")
482
+ File.binwrite(path, "\x89PNG\r\n\x1a\n".dup)
483
+ block = RubynCode::LLM::ImageReader.for_path(path)
484
+ ex = RubynCode::CLI::MentionExpander.new(project_root: dir).expand_images("look @p.png")
485
+ ok = (block.is_a?(RubynCode::LLM::ImageBlock)) &&
486
+ (block.media_type == "image/png") &&
487
+ (ex.size == 1)
488
+ puts(ok ? "IMAGES: PASS" : "IMAGES: FAIL")
489
+ end
490
+ '
491
+ ```
492
+
493
+ #### 17m. TodoWrite live checklist (PR #134)
494
+ - **bash**: confirms `Tools::TodoWrite` is registered and mutates a shared
495
+ `Tools::TodoStore`. PASS if the final line is `TODOWRITE: PASS`.
496
+
497
+ ```bash
498
+ bundle exec ruby -Ilib -rrubyn_code -rrubyn_code/tools/todo_write -rrubyn_code/tools/todo_store -e '
499
+ store = RubynCode::Tools::TodoStore.new
500
+ tool = RubynCode::Tools::TodoWrite.new(project_root: Dir.pwd, store: store)
501
+ out = tool.execute(todos: [{ "content" => "a", "status" => "in_progress", "active_form" => "A" }])
502
+ ok = (out.include?("[~] a")) && (store.current.first[:status] == "in_progress") &&
503
+ (RubynCode::Tools::Registry.get("TodoWrite") == RubynCode::Tools::TodoWrite)
504
+ puts(ok ? "TODOWRITE: PASS" : "TODOWRITE: FAIL")
505
+ '
506
+ ```
507
+
508
+ #### 17n. Custom-command frontmatter (argument-hint, allowed-tools, model:) (PRs #135, #138)
509
+ - **bash**: confirms `CustomCommand` exposes all three frontmatter keys and
510
+ `Agent::Loop` honors the per-prompt override setters.
511
+ PASS if the final line is `FRONTMATTER: PASS`.
512
+
513
+ ```bash
514
+ bundle exec ruby -Ilib -rrubyn_code -rrubyn_code/agent/loop -e '
515
+ loop = RubynCode::Agent::Loop.allocate
516
+ loop.allowed_tools_override = %w[bash read]
517
+ loop.model_override = "claude-opus-4-8"
518
+ at = loop.instance_variable_get(:@allowed_tools_override)
519
+ mo = loop.instance_variable_get(:@model_override)
520
+ cmd = RubynCode::CLI::Commands::CustomCommand.new(
521
+ name: "d", description: "d", body: "b",
522
+ argument_hint: "[env]", allowed_tools: %w[bash read], model: "claude-opus-4-8"
523
+ )
524
+ ok = (at == %w[bash read]) && (mo == "claude-opus-4-8") &&
525
+ (cmd.argument_hint == "[env]") && (cmd.allowed_tools == %w[bash read]) &&
526
+ (cmd.model == "claude-opus-4-8")
527
+ puts(ok ? "FRONTMATTER: PASS" : "FRONTMATTER: FAIL")
528
+ '
529
+ ```
530
+
531
+ #### 17o. `.mcp.json` auto-discovery (PRs #136, #138, #139)
532
+ - **bash**: writes a project-root `.mcp.json`, calls `MCP::Discovery.discover`,
533
+ and asserts the entry is tagged `:project`.
534
+ PASS if the final line is `MCP-DISCOVERY: PASS`.
535
+
536
+ ```bash
537
+ bundle exec ruby -Ilib -rrubyn_code -rrubyn_code/mcp/discovery -e '
538
+ require "tmpdir"; require "json"
539
+ Dir.mktmpdir do |dir|
540
+ File.write(File.join(dir, ".mcp.json"),
541
+ JSON.generate(mcpServers: { "p" => { command: "p" } }))
542
+ entries = RubynCode::MCP::Discovery.discover(dir)
543
+ ok = (entries.any? { |e| e.name == "p" && e.source == :project })
544
+ puts(ok ? "MCP-DISCOVERY: PASS" : "MCP-DISCOVERY: FAIL")
545
+ end
546
+ '
547
+ ```
548
+
549
+ #### 17p. `/export` transcript (markdown / jsonl) (PR #137)
550
+ - **bash**: drives `Commands::Export` against a synthetic conversation with
551
+ a `thinking` block and a `tool_use`. Writes a markdown file and asserts
552
+ the file contains role sections, the thinking `<details>`, and the
553
+ fenced-JSON tool_use. PASS if the final line is `EXPORT: PASS`.
554
+
555
+ ```bash
556
+ bundle exec ruby -Ilib -rrubyn_code -rrubyn_code/cli/commands/export -e '
557
+ require "tmpdir"
558
+ Dir.mktmpdir do |dir|
559
+ msgs = [
560
+ { role: "user", content: "hi" },
561
+ { role: "assistant", content: [
562
+ { type: "thinking", text: "plan" },
563
+ { type: "text", text: "ok" },
564
+ { type: "tool_use", name: "bash", input: { cmd: "ls" } }
565
+ ] }
566
+ ]
567
+ conv = Object.new
568
+ conv.define_singleton_method(:to_a) { msgs }
569
+ renderer = Object.new
570
+ renderer.define_singleton_method(:info) { |*_| nil }
571
+ renderer.define_singleton_method(:warning) { |*_| nil }
572
+ renderer.define_singleton_method(:ask) { |*_| true }
573
+ ctx = RubynCode::CLI::Commands::Context.new(
574
+ renderer: renderer, conversation: conv, agent_loop: nil,
575
+ context_manager: nil, budget_enforcer: nil, llm_client: nil,
576
+ db: nil, session_id: nil, project_root: nil, skill_loader: nil,
577
+ session_persistence: nil, background_worker: nil, permission_tier: nil,
578
+ plan_mode: false, message_handler: nil, hook_registry: nil,
579
+ checkpoint_manager: nil
580
+ )
581
+ path = File.join(dir, "x.md")
582
+ RubynCode::CLI::Commands::Export.new.execute([path], ctx)
583
+ body = File.read(path)
584
+ ok = body.include?("## User") &&
585
+ body.include?("<details><summary>thinking</summary>") &&
586
+ body.include?("[tool: bash]")
587
+ puts(ok ? "EXPORT: PASS" : "EXPORT: FAIL")
588
+ end
589
+ '
590
+ ```
591
+
452
592
  ### 18. Chisel — Minimal-Code Enforcement (opt-in)
453
593
 
454
594
  Chisel is rubyn-code's "write the minimum that works" layer. It is **off by
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rubyn-code
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - fadedmaturity
@@ -240,6 +240,8 @@ files:
240
240
  - lib/rubyn_code/cli/commands/custom_loader.rb
241
241
  - lib/rubyn_code/cli/commands/diff.rb
242
242
  - lib/rubyn_code/cli/commands/doctor.rb
243
+ - lib/rubyn_code/cli/commands/effort.rb
244
+ - lib/rubyn_code/cli/commands/export.rb
243
245
  - lib/rubyn_code/cli/commands/goal.rb
244
246
  - lib/rubyn_code/cli/commands/help.rb
245
247
  - lib/rubyn_code/cli/commands/install_skills.rb
@@ -262,6 +264,7 @@ files:
262
264
  - lib/rubyn_code/cli/commands/skills.rb
263
265
  - lib/rubyn_code/cli/commands/spawn.rb
264
266
  - lib/rubyn_code/cli/commands/tasks.rb
267
+ - lib/rubyn_code/cli/commands/think.rb
265
268
  - lib/rubyn_code/cli/commands/tokens.rb
266
269
  - lib/rubyn_code/cli/commands/undo.rb
267
270
  - lib/rubyn_code/cli/commands/version.rb
@@ -289,13 +292,11 @@ files:
289
292
  - lib/rubyn_code/context/RUBYN.md
290
293
  - lib/rubyn_code/context/auto_compact.rb
291
294
  - lib/rubyn_code/context/compactor.rb
292
- - lib/rubyn_code/context/context_budget.rb
293
295
  - lib/rubyn_code/context/context_collapse.rb
294
296
  - lib/rubyn_code/context/decision_compactor.rb
295
297
  - lib/rubyn_code/context/manager.rb
296
298
  - lib/rubyn_code/context/manual_compact.rb
297
299
  - lib/rubyn_code/context/micro_compact.rb
298
- - lib/rubyn_code/context/schema_filter.rb
299
300
  - lib/rubyn_code/db/RUBYN.md
300
301
  - lib/rubyn_code/db/connection.rb
301
302
  - lib/rubyn_code/db/migrator.rb
@@ -338,12 +339,12 @@ files:
338
339
  - lib/rubyn_code/ide/protocol.rb
339
340
  - lib/rubyn_code/ide/server.rb
340
341
  - lib/rubyn_code/index/codebase_index.rb
342
+ - lib/rubyn_code/index/prism_extractor.rb
341
343
  - lib/rubyn_code/learning/RUBYN.md
342
344
  - lib/rubyn_code/learning/extractor.rb
343
345
  - lib/rubyn_code/learning/injector.rb
344
346
  - lib/rubyn_code/learning/instinct.rb
345
347
  - lib/rubyn_code/learning/porter.rb
346
- - lib/rubyn_code/learning/shortcut.rb
347
348
  - lib/rubyn_code/llm/RUBYN.md
348
349
  - lib/rubyn_code/llm/adapters/anthropic.rb
349
350
  - lib/rubyn_code/llm/adapters/anthropic_compatible.rb
@@ -355,14 +356,14 @@ files:
355
356
  - lib/rubyn_code/llm/adapters/openai_message_translator.rb
356
357
  - lib/rubyn_code/llm/adapters/openai_streaming.rb
357
358
  - lib/rubyn_code/llm/adapters/prompt_caching.rb
358
- - lib/rubyn_code/llm/adapters/token_caching.rb
359
359
  - lib/rubyn_code/llm/client.rb
360
+ - lib/rubyn_code/llm/image_reader.rb
360
361
  - lib/rubyn_code/llm/message_builder.rb
361
362
  - lib/rubyn_code/llm/model_router.rb
362
- - lib/rubyn_code/llm/streaming.rb
363
363
  - lib/rubyn_code/mcp/RUBYN.md
364
364
  - lib/rubyn_code/mcp/client.rb
365
365
  - lib/rubyn_code/mcp/config.rb
366
+ - lib/rubyn_code/mcp/discovery.rb
366
367
  - lib/rubyn_code/mcp/server_extras_bridge.rb
367
368
  - lib/rubyn_code/mcp/sse_transport.rb
368
369
  - lib/rubyn_code/mcp/stdio_transport.rb
@@ -393,7 +394,6 @@ files:
393
394
  - lib/rubyn_code/permissions/tier.rb
394
395
  - lib/rubyn_code/protocols/RUBYN.md
395
396
  - lib/rubyn_code/protocols/interrupt_handler.rb
396
- - lib/rubyn_code/protocols/plan_approval.rb
397
397
  - lib/rubyn_code/protocols/shutdown_handshake.rb
398
398
  - lib/rubyn_code/self_test.rb
399
399
  - lib/rubyn_code/skills/RUBYN.md
@@ -430,6 +430,7 @@ files:
430
430
  - lib/rubyn_code/tools/bash.rb
431
431
  - lib/rubyn_code/tools/bundle_add.rb
432
432
  - lib/rubyn_code/tools/bundle_install.rb
433
+ - lib/rubyn_code/tools/code_graph.rb
433
434
  - lib/rubyn_code/tools/compact.rb
434
435
  - lib/rubyn_code/tools/db_migrate.rb
435
436
  - lib/rubyn_code/tools/edit_file.rb
@@ -459,6 +460,8 @@ files:
459
460
  - lib/rubyn_code/tools/spawn_teammate.rb
460
461
  - lib/rubyn_code/tools/spec_output_parser.rb
461
462
  - lib/rubyn_code/tools/task.rb
463
+ - lib/rubyn_code/tools/todo_store.rb
464
+ - lib/rubyn_code/tools/todo_write.rb
462
465
  - lib/rubyn_code/tools/web_fetch.rb
463
466
  - lib/rubyn_code/tools/web_search.rb
464
467
  - lib/rubyn_code/tools/write_file.rb
@@ -1,183 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module RubynCode
4
- module Context
5
- # Budget-aware context loader that prioritizes which related files
6
- # to load fully vs. as signatures-only. Prevents context bloat by
7
- # capping auto-loaded context at a configurable token budget.
8
- class ContextBudget
9
- CHARS_PER_TOKEN = 4
10
- DEFAULT_BUDGET = 4000 # tokens
11
-
12
- # Rails convention-based priority for related files.
13
- # Lower number = higher priority = loaded first.
14
- PRIORITY_MAP = {
15
- 'spec' => 1, # tests for the file
16
- 'factory' => 2, # FactoryBot factories
17
- 'service' => 3, # service objects
18
- 'model' => 4, # related models
19
- 'controller' => 5, # controllers
20
- 'serializer' => 6, # serializers
21
- 'concern' => 7, # concerns/mixins
22
- 'helper' => 8, # helpers
23
- 'migration' => 9 # migrations
24
- }.freeze
25
-
26
- attr_reader :loaded_files, :signature_files, :tokens_used
27
-
28
- def initialize(budget: DEFAULT_BUDGET, codebase_index: nil)
29
- @budget = budget
30
- @codebase_index = codebase_index
31
- @loaded_files = []
32
- @signature_files = []
33
- @tokens_used = 0
34
- end
35
-
36
- # Load context for a primary file, filling budget with related files.
37
- # Returns array of { file:, content:, mode: :full|:signatures }
38
- #
39
- # When a codebase_index is available and no related_files are supplied,
40
- # uses impact_analysis to auto-discover related files (specs,
41
- # associated models, controllers, etc.).
42
- def load_for(file_path, related_files: [])
43
- results = []
44
-
45
- # Primary file always loads fully
46
- primary_content = safe_read(file_path)
47
- return results unless primary_content
48
-
49
- primary_tokens = estimate_tokens(primary_content)
50
- @tokens_used = primary_tokens
51
- @loaded_files << file_path
52
- results << { file: file_path, content: primary_content, mode: :full }
53
-
54
- # Auto-discover related files from the index when none supplied
55
- related_files = discover_related_files(file_path) if related_files.empty? && @codebase_index
56
-
57
- # Sort related files by priority and fill remaining budget
58
- sorted = prioritize(related_files)
59
- remaining = @budget - @tokens_used
60
- remaining = load_full_files(sorted, results, remaining)
61
- load_signature_files(sorted, results, remaining)
62
-
63
- results
64
- end
65
-
66
- # Extract method signatures and class structure without method bodies.
67
- # Much more compact than full source — typically 10-20% of original size.
68
- def extract_signatures(content)
69
- signatures = []
70
- indent_stack = []
71
-
72
- content.lines.each do |line|
73
- process_signature_line(line, signatures, indent_stack)
74
- end
75
-
76
- signatures.join
77
- end
78
-
79
- # Returns budget utilization stats.
80
- def stats
81
- {
82
- budget: @budget,
83
- tokens_used: @tokens_used,
84
- utilization: @budget.positive? ? (@tokens_used.to_f / @budget).round(3) : 0.0,
85
- full_files: @loaded_files.size,
86
- signature_files: @signature_files.size
87
- }
88
- end
89
-
90
- private
91
-
92
- def discover_related_files(file_path)
93
- analysis = @codebase_index.impact_analysis(file_path)
94
- analysis[:affected_files].reject { |f| f == file_path }
95
- rescue StandardError
96
- []
97
- end
98
-
99
- def load_full_files(sorted, results, remaining)
100
- sorted.each do |rel_path|
101
- content = safe_read(rel_path)
102
- next unless content
103
-
104
- size = estimate_tokens(content)
105
- next unless size <= remaining
106
-
107
- results << { file: rel_path, content: content, mode: :full }
108
- @loaded_files << rel_path
109
- @tokens_used += size
110
- remaining -= size
111
- end
112
- remaining
113
- end
114
-
115
- def load_signature_files(sorted, results, remaining)
116
- sorted.each do |rel_path|
117
- next if @loaded_files.include?(rel_path)
118
-
119
- content = safe_read(rel_path)
120
- next unless content
121
-
122
- sigs = extract_signatures(content)
123
- sig_size = estimate_tokens(sigs)
124
- next unless sig_size <= remaining
125
-
126
- results << { file: rel_path, content: sigs, mode: :signatures }
127
- @signature_files << rel_path
128
- @tokens_used += sig_size
129
- remaining -= sig_size
130
- end
131
- end
132
-
133
- # -- signature extraction dispatch
134
- def process_signature_line(line, signatures, indent_stack)
135
- stripped = line.strip
136
- if signature_line?(stripped)
137
- signatures << line
138
- indent_stack << current_indent(line) if block_opener?(stripped)
139
- elsif stripped == 'end' && indent_stack.any? && current_indent(line) <= indent_stack.last
140
- signatures << line
141
- indent_stack.pop
142
- elsif class_or_module_line?(stripped)
143
- signatures << line
144
- indent_stack << current_indent(line)
145
- end
146
- end
147
-
148
- def prioritize(files)
149
- files.sort_by do |path|
150
- basename = File.basename(path, '.*').downcase
151
- priority = PRIORITY_MAP.find { |key, _| basename.include?(key) }&.last || 10
152
- priority
153
- end
154
- end
155
-
156
- def signature_line?(stripped)
157
- stripped.match?(/\A\s*(def\s|attr_|include\s|extend\s|has_|belongs_|validates|scope\s|delegate\s)/)
158
- end
159
-
160
- def class_or_module_line?(stripped)
161
- stripped.match?(/\A\s*(class|module)\s/)
162
- end
163
-
164
- def block_opener?(stripped)
165
- stripped.match?(/\Adef\s/)
166
- end
167
-
168
- def current_indent(line)
169
- line.match(/\A(\s*)/)[1].length
170
- end
171
-
172
- def safe_read(path)
173
- File.read(path)
174
- rescue StandardError
175
- nil
176
- end
177
-
178
- def estimate_tokens(text)
179
- (text.bytesize.to_f / CHARS_PER_TOKEN).ceil
180
- end
181
- end
182
- end
183
- end
@@ -1,64 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module RubynCode
4
- module Context
5
- # Extracts only the relevant table definitions from db/schema.rb
6
- # based on which models are currently in context. Loading the full
7
- # schema for a large Rails app can be 5-10K tokens; filtering to
8
- # relevant tables typically reduces this to 200-500 tokens.
9
- module SchemaFilter
10
- TABLE_PATTERN = /create_table\s+"([^"]+)"/
11
- END_PATTERN = /\A\s+end\s*\z/
12
-
13
- class << self
14
- # Returns schema definitions for only the specified table names.
15
- #
16
- # @param schema_path [String] path to db/schema.rb
17
- # @param table_names [Array<String>] table names to include
18
- # @return [String] filtered schema content
19
- def filter(schema_path, table_names:)
20
- return '' if table_names.empty?
21
- return '' unless File.exist?(schema_path)
22
-
23
- lines = File.readlines(schema_path)
24
- extract_tables(lines, table_names.to_set(&:to_s))
25
- end
26
-
27
- # Derives table names from model class names using Rails conventions.
28
- #
29
- # @param model_names [Array<String>] e.g., ["User", "OrderItem"]
30
- # @return [Array<String>] e.g., ["users", "order_items"]
31
- def tableize(model_names)
32
- model_names.map { |name| "#{name.gsub(/([a-z])([A-Z])/, '\1_\2').downcase}s" }
33
- end
34
-
35
- # Convenience: filter schema by model names instead of table names.
36
- def filter_for_models(schema_path, model_names:)
37
- tables = tableize(model_names)
38
- filter(schema_path, table_names: tables)
39
- end
40
-
41
- private
42
-
43
- def extract_tables(lines, table_set)
44
- result = []
45
- capturing = false
46
-
47
- lines.each do |line|
48
- match = TABLE_PATTERN.match(line)
49
- capturing = true if match && table_set.include?(match[1])
50
-
51
- result << line if capturing
52
-
53
- if capturing && END_PATTERN.match?(line)
54
- capturing = false
55
- result << "\n"
56
- end
57
- end
58
-
59
- result.join
60
- end
61
- end
62
- end
63
- end
64
- end
@@ -1,95 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module RubynCode
4
- module Learning
5
- # Uses learned instincts to skip redundant discovery steps. For example,
6
- # if we know the project uses FactoryBot, skip checking test_helper.rb
7
- # and looking for factories/ — just generate FactoryBot-style specs.
8
- class Shortcut
9
- SHORTCUT_RULES = {
10
- 'uses_factory_bot' => {
11
- skip: %w[test_helper factories_check],
12
- apply: { spec_template: :factory_bot_rspec }
13
- },
14
- 'uses_rspec' => {
15
- skip: %w[framework_detection],
16
- apply: { test_framework: :rspec }
17
- },
18
- 'uses_minitest' => {
19
- skip: %w[framework_detection],
20
- apply: { test_framework: :minitest }
21
- },
22
- 'uses_service_objects' => {
23
- skip: %w[pattern_detection],
24
- apply: { service_pattern: 'app/services/**/*_service.rb' }
25
- },
26
- 'uses_devise' => {
27
- skip: %w[auth_detection],
28
- apply: { auth_framework: :devise }
29
- },
30
- 'uses_grape' => {
31
- skip: %w[api_detection],
32
- apply: { api_framework: :grape }
33
- },
34
- 'uses_sidekiq' => {
35
- skip: %w[job_detection],
36
- apply: { job_framework: :sidekiq }
37
- }
38
- }.freeze
39
-
40
- attr_reader :applied_shortcuts, :tokens_saved_estimate
41
-
42
- def initialize
43
- @applied_shortcuts = []
44
- @tokens_saved_estimate = 0
45
- end
46
-
47
- # Apply shortcuts based on instinct patterns.
48
- #
49
- # @param instinct_patterns [Array<String>] patterns from the instincts table
50
- # @return [Hash] aggregated settings from applied shortcuts
51
- def apply(instinct_patterns)
52
- settings = {}
53
-
54
- instinct_patterns.each do |pattern|
55
- rule_key = match_rule(pattern)
56
- next unless rule_key
57
-
58
- rule = SHORTCUT_RULES[rule_key]
59
- settings.merge!(rule[:apply])
60
- @applied_shortcuts << { rule: rule_key, skipped: rule[:skip] }
61
- @tokens_saved_estimate += rule[:skip].size * 500
62
- end
63
-
64
- settings
65
- end
66
-
67
- # Check if a discovery step should be skipped.
68
- #
69
- # @param step_name [String] the discovery step name
70
- # @return [Boolean]
71
- def skip?(step_name)
72
- @applied_shortcuts.any? { |s| s[:skipped].include?(step_name.to_s) }
73
- end
74
-
75
- # Returns stats about shortcuts applied this session.
76
- def stats
77
- {
78
- shortcuts_applied: @applied_shortcuts.size,
79
- steps_skipped: @applied_shortcuts.sum { |s| s[:skipped].size },
80
- tokens_saved_estimate: @tokens_saved_estimate
81
- }
82
- end
83
-
84
- private
85
-
86
- def match_rule(pattern)
87
- normalized = pattern.to_s.downcase
88
- SHORTCUT_RULES.each_key do |key|
89
- return key if normalized.include?(key.tr('_', ' ')) || normalized.include?(key)
90
- end
91
- nil
92
- end
93
- end
94
- end
95
- end
@@ -1,54 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module RubynCode
4
- module LLM
5
- module Adapters
6
- # Cached access to the Anthropic credential.
7
- #
8
- # TokenStore.load shells out to the macOS keychain, so the loaded
9
- # tokens are cached per adapter instance. The cache drops itself once
10
- # the token nears expiry (picking up an externally refreshed
11
- # credential) and must be invalidated on 401 responses.
12
- module TokenCaching
13
- private
14
-
15
- def oauth_token?
16
- return @oauth_token unless @oauth_token.nil?
17
-
18
- @oauth_token = access_token.include?('sk-ant-oat')
19
- end
20
-
21
- def ensure_valid_token!
22
- return if Auth::TokenStore.valid_tokens?(tokens)
23
-
24
- raise Client::AuthExpiredError,
25
- 'No valid authentication. Run `rubyn-code --auth` or set ANTHROPIC_API_KEY.'
26
- end
27
-
28
- def access_token
29
- token = tokens&.fetch(:access_token, nil)
30
- raise Client::AuthExpiredError, 'No stored access token' unless token
31
-
32
- token
33
- end
34
-
35
- def tokens
36
- invalidate_token_cache! if token_cache_stale?
37
- @tokens ||= Auth::TokenStore.load
38
- end
39
-
40
- def token_cache_stale?
41
- expires_at = @tokens&.fetch(:expires_at, nil)
42
- return false unless expires_at
43
-
44
- expires_at <= Time.now + Auth::TokenStore::EXPIRY_BUFFER_SECONDS
45
- end
46
-
47
- def invalidate_token_cache!
48
- @tokens = nil
49
- @oauth_token = nil
50
- end
51
- end
52
- end
53
- end
54
- end
@@ -1,10 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module RubynCode
4
- module LLM
5
- # Backward-compatibility shim.
6
- # Delegates to Adapters::AnthropicStreaming so existing references
7
- # to LLM::Streaming keep working during the migration.
8
- Streaming = Adapters::AnthropicStreaming
9
- end
10
- end