Module: Ruby::Merge

Extended by:
Merge
Includes:
Ast::Merge::SourceRegionReportSupport
Included in:
Merge
Defined in:
lib/ruby/merge.rb,
lib/ruby/merge/version.rb,
lib/ruby/merge/gemspec_support.rb,
lib/ruby/merge/nocov_node_base.rb,
lib/ruby/merge/rescue_semantics.rb,
lib/ruby/merge/method_similarity.rb,
lib/ruby/merge/signature_support.rb,
lib/ruby/merge/nocov_wrapper_base.rb,
lib/ruby/merge/doc_comment_support.rb,
lib/ruby/merge/block_binding_support.rb,
lib/ruby/merge/magic_comment_support.rb,
lib/ruby/merge/scaffold_chunk_support.rb,
lib/ruby/merge/block_directive_detector.rb,
sig/ruby/merge.rbs

Defined Under Namespace

Modules: BlockBindingSupport, DocCommentSupport, GemspecSupport, MagicCommentSupport, ScaffoldChunkSupport, SignatureSupport, Version Classes: BlockDirectiveDetector, MethodSimilarity, NocovNodeBase, NocovWrapperBase, RescueSemantics, RubyHashLiteralProjector, RubyHashNode, RubyHashPair, RubyScalarNode, TslpImportItem, TslpProcessAnalysis, TslpSpan, TslpStructureItem

Constant Summary collapse

PACKAGE_NAME =
'ruby-merge'
TREE_SITTER_BACKEND =
TreeHaver::KREUZBERG_LANGUAGE_PACK_BACKEND
DESTINATION_WINS_ARRAY_POLICY =
{ surface: 'array', name: 'destination_wins_array' }.freeze
DEFAULT_METHOD_MOVE_POLICY =
'destination_order'
BACKEND_REGISTRY =
Struct.new(:registered, :mutex).new(false, Mutex.new)
PERCENT_ARRAY_DELIMITER_PAIRS =
{
  '[' => ']',
  '(' => ')',
  '{' => '}',
  '<' => '>'
}.freeze
REQUIRE_PATTERN =
/^\s*require(?:_relative)?\s+["']([^"']+)["']/
CLASS_PATTERN =
/^\s*class\s+([A-Z]\w*(?:::\w+)*)/
MODULE_PATTERN =
/^\s*module\s+([A-Z]\w*(?:::\w+)*)/
DEF_PATTERN =
%r{^\s*def\s+((?:self\.)?)([a-zA-Z_]\w*[!?=]?|\[\]=?|\+@|-@|\*\*|<<|>>|<=>|===|==|=~|!~|!=|[+\-*/%&|^<>]=?|[!~`])}
CONSTANT_ASSIGNMENT_PATTERN =
/^(\s*)([A-Z]\w*)\s*=/
CONSTANT_HASH_ASSIGNMENT_PATTERN =
/^(\s*)([A-Z]\w*)\s*=\s*\{/
VERSION =

Current gem version exposed at the traditional constant location.

Returns:

  • (String)
Version::VERSION

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.analyze_ruby_document(source, process_analysis: nil) ⇒ Object



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
# File 'lib/ruby/merge.rb', line 1226

def analyze_ruby_document(source, process_analysis: nil)
  lines = normalize_source(source).split("\n", -1)
  requires = ruby_analysis_require_owners(source, process_analysis)
  discovered_surfaces = []
  pending_comments = []

  lines.each_with_index do |line, index|
    line_number = index + 1
    stripped = line.strip

    if comment_line?(line)
      pending_comments << { line: line_number, raw: line }
      next
    end

    if stripped.empty?
      pending_comments = []
      next
    end

    if ruby_process_import_item_at_line(process_analysis,
                                        line_number) || legacy_require_line?(line, process_analysis)
      pending_comments = []
      next
    end

    declaration = ruby_process_structure_item_at_line(process_analysis, line_number)
    declaration ||= declaration_for_line(line) if Array(process_analysis&.structure).empty?
    if declaration
      surfaces = surfaces_for_owner(
        owner_name: declaration[:name],
        comment_entries: pending_comments
      )
      discovered_surfaces.concat(surfaces)
      pending_comments = []
      next
    end

    pending_comments = []
  end

  declaration_entries = ruby_process_owner_entries(process_analysis)
  declaration_entries = legacy_ruby_analysis_owner_entries(source) if declaration_entries.empty?
  declarations = declaration_entries.map do |entry|
    {
      path: entry[:path],
      owner_kind: 'declaration',
      match_key: entry[:name]
    }
  end

  {
    kind: 'ruby',
    dialect: 'ruby',
    root_kind: 'document',
    source: normalize_source(source),
    tree_haver_process_analysis: process_analysis,
    owners: (requires + declarations).sort_by { |owner| owner[:path] },
    discovered_surfaces: discovered_surfaces,
    method_shadowing: ruby_method_shadowing(source),
    diagnostics: ruby_method_shadowing_diagnostics(source)
  }
end

.apply_ruby_delegated_child_outputs(source, delegated_operations, apply_plan, applied_children) ⇒ Object



1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
# File 'lib/ruby/merge.rb', line 1071

def apply_ruby_delegated_child_outputs(source, delegated_operations, apply_plan, applied_children)
  lines = normalize_source(source).split("\n")
  operations_by_id = delegated_operations.to_h { |operation| [operation[:operation_id], operation] }
  outputs_by_id = applied_children.to_h { |entry| [entry[:operation_id], entry[:output]] }

  replacements = apply_plan[:entries].filter_map do |entry|
    operation = operations_by_id[entry.dig(:delegated_group, :child_operation_id)]
    output = outputs_by_id[entry.dig(:delegated_group, :child_operation_id)]
    span = operation&.dig(:surface, :span)
    next if operation.nil? || output.nil? || span.nil?

    { start: span[:start_line] - 1, finish: span[:end_line] - 1, output: output }
  end

  replacements.sort_by { |entry| -entry[:start] }.each do |entry|
    prefix = comment_prefix_for(lines[entry[:start]])
    replacement_lines = if entry[:output].empty?
                          []
                        else
                          entry[:output].sub(/\n\z/, '').split("\n").map do |line|
                            "#{prefix}#{line}"
                          end
                        end
    lines[entry[:start]..entry[:finish]] = replacement_lines
  end

  {
    ok: true,
    diagnostics: [],
    output: "#{lines.join("\n").sub(/\n+\z/, '')}\n",
    policies: [DESTINATION_WINS_ARRAY_POLICY]
  }
end

.available_ruby_backendsObject



67
68
69
# File 'lib/ruby/merge.rb', line 67

def available_ruby_backends
  ruby_backend_available_for_analysis?(TREE_SITTER_BACKEND.id) ? [TREE_SITTER_BACKEND] : []
end

.collect_ruby_declaration_entries(source, process_analysis: nil) ⇒ Object



1641
1642
1643
1644
1645
1646
# File 'lib/ruby/merge.rb', line 1641

def collect_ruby_declaration_entries(source, process_analysis: nil)
  process_entries = ruby_process_declaration_entries(source, process_analysis: process_analysis)
  return process_entries unless process_entries.empty?

  legacy_collect_ruby_declaration_entries(source)
end

.match_ruby_owners(template, destination) ⇒ Object



158
159
160
# File 'lib/ruby/merge.rb', line 158

def match_ruby_owners(template, destination)
  Ast::Merge::OwnerSelection.match_by_path(template, destination)
end

.merge_ruby(template_source, destination_source, dialect, merge_template_requires: false, method_move_policy: DEFAULT_METHOD_MOVE_POLICY) ⇒ Object



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
# File 'lib/ruby/merge.rb', line 214

def merge_ruby(template_source, destination_source, dialect, merge_template_requires: false,
               method_move_policy: DEFAULT_METHOD_MOVE_POLICY)
  template = parse_ruby(template_source, dialect)
  return template unless template[:ok]

  method_move_policy = normalize_method_move_policy(method_move_policy)

  destination = parse_ruby(destination_source, dialect)
  unless destination[:ok]
    return {
      ok: false,
      diagnostics: destination[:diagnostics].map do |diagnostic|
        diagnostic[:category] == 'parse_error' ? diagnostic.merge(category: 'destination_parse_error') : diagnostic
      end,
      policies: []
    }
  end

  destination_context = ruby_tslp_merge_context(destination.fetch(:analysis), role: 'destination')
  return destination_context unless destination_context[:ok]

  template_context = ruby_tslp_merge_context(template.fetch(:analysis), role: 'template')
  return template_context unless template_context[:ok]

  destination_requires = destination_context.fetch(:requires)
  template_requires = template_context.fetch(:requires)
  destination_declarations = destination_context.fetch(:declarations)
  template_declarations = template_context.fetch(:declarations)
  template_declarations_by_key = template_declarations.to_h { |entry| [entry[:merge_key], entry] }
  intra_owner_merges = ruby_intra_owner_merge_plan(template_declarations, destination_declarations)
  namespace_conflicts = ruby_namespace_form_conflicts(template_declarations, destination_declarations)
  unless namespace_conflicts.empty? || TreeHaver::BackendRegistry.tag_available?(:tslp_ruby_namespace_form_equivalence)
    conflicts = namespace_conflicts.join(', ')
    return unsupported_feature_result(
      'ruby-merge cannot reconcile equivalent Ruby namespace declaration forms with the active TSLP records: ' \
      "#{conflicts}. Use prism-merge for native Ruby merging, or report missing Ruby namespace ownership " \
      'records to tree-sitter-language-pack.'
    )
  end
  if !namespace_conflicts.empty? && TreeHaver::BackendRegistry.tag_available?(:tslp_ruby_namespace_form_equivalence)
    template_declarations += qualified_nested_declaration_entries(template_declarations)
    template_declarations_by_key = template_declarations.to_h { |entry| [entry[:merge_key], entry] }
  end
  destination_paths = destination_declarations.to_h { |entry| [entry[:merge_key], true] }
  sections = []
  preamble = destination_context.fetch(:preamble)
  sections << { text: preamble } unless preamble.empty?
  requires = if merge_template_requires
               merge_ruby_requires(destination_requires,
                                   template_requires)
             else
               destination_requires
             end
  require_block = requires.map { |entry| entry[:text] }.join("\n").strip
  sections << ruby_top_level_section(require_block, requires) unless require_block.empty?
  sections.concat(
    destination_declarations.map do |entry|
      ruby_top_level_section(
        merge_ruby_declaration_entry(template_declarations_by_key[entry[:merge_key]], entry)[:text],
        [entry]
      )
    end
  )
  sections.concat(
    template_declarations.reject do |entry|
      destination_paths[entry[:merge_key]] ||
        namespace_wrapper_matched?(entry, template_declarations, destination_paths)
    end.map { |entry| { text: entry[:text] } }
  )
  destination_footer = destination_context.fetch(:footer)
  sections << { text: destination_footer } unless destination_footer.empty?

  output = emit_ruby_top_level_sections(destination_source, sections)
  matching_reports = [ruby_method_move_detection(template_source, destination_source, dialect)]
  moved_method_count = matching_reports.sum do |report|
    Array(report[:matches]).count { |entry| entry[:moved] }
  end

  {
    ok: true,
    diagnostics: [],
    output: output,
    policies: [DESTINATION_WINS_ARRAY_POLICY],
    matching_reports: matching_reports,
    merge_planning: {
      method_move_policy: method_move_policy,
      method_move_detection: {
        matching_id: 'ruby-tslp-method-move-detection',
        moved_method_count: moved_method_count,
        preserves_destination_order: method_move_policy == DEFAULT_METHOD_MOVE_POLICY,
        suppresses_duplicate_moved_methods: method_move_policy == DEFAULT_METHOD_MOVE_POLICY,
        override_scope: 'per_file_recipe'
      },
      intra_owner_merges: {
        strategy: 'destination_wins_scoped_owner_body',
        merge_count: intra_owner_merges.length,
        merges: intra_owner_merges
      }
    }
  }
end

.merge_ruby_with_nested_outputs(template_source, destination_source, dialect, nested_outputs) ⇒ Object



1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
# File 'lib/ruby/merge.rb', line 1105

def merge_ruby_with_nested_outputs(template_source, destination_source, dialect, nested_outputs)
  Ast::Merge.execute_nested_merge(
    nested_outputs,
    default_family: 'ruby',
    request_id_prefix: 'nested_ruby_child',
    merge_parent: -> { merge_ruby(template_source, destination_source, dialect) },
    discover_operations: lambda { |merged_output|
      analysis = parse_ruby(merged_output, dialect)
      next { ok: false, diagnostics: analysis[:diagnostics] || [] } unless analysis[:ok]

      {
        ok: true,
        diagnostics: [],
        operations: ruby_delegated_child_operations(analysis[:analysis])
      }
    },
    apply_resolved_outputs: lambda { |merged_output, operations, apply_plan, applied_children|
      apply_ruby_delegated_child_outputs(
        merged_output,
        operations,
        apply_plan,
        applied_children
      )
    }
  )
end

.merge_ruby_with_reviewed_nested_outputs(template_source, destination_source, dialect, review_state, applied_children) ⇒ Object



1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'lib/ruby/merge.rb', line 1132

def merge_ruby_with_reviewed_nested_outputs(template_source, destination_source, dialect, review_state,
                                            applied_children)
  Ast::Merge.execute_reviewed_nested_merge(
    review_state,
    'ruby',
    applied_children,
    merge_parent: -> { merge_ruby(template_source, destination_source, dialect) },
    discover_operations: lambda { |merged_output|
      analysis = parse_ruby(merged_output, dialect)
      next({ ok: false, diagnostics: analysis[:diagnostics] || [] }) unless analysis[:ok]

      {
        ok: true,
        diagnostics: [],
        operations: ruby_delegated_child_operations(analysis[:analysis])
      }
    },
    apply_resolved_outputs: lambda { |merged_output, operations, apply_plan, resolved_children|
      apply_ruby_delegated_child_outputs(
        merged_output,
        operations,
        apply_plan,
        resolved_children
      )
    }
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_replay_bundle(template_source, destination_source, dialect, replay_bundle) ⇒ Object



1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
# File 'lib/ruby/merge.rb', line 1160

def merge_ruby_with_reviewed_nested_outputs_from_replay_bundle(template_source, destination_source, dialect,
                                                               replay_bundle)
  execution = Array(replay_bundle[:reviewed_nested_executions]).find { |entry| entry[:family] == 'ruby' }
  unless execution
    return { ok: false,
             diagnostics: [{ severity: 'error', category: 'configuration_error', message: 'review replay bundle does not include a reviewed nested execution for ruby.' }], policies: [] }
  end

  merge_ruby_with_reviewed_nested_outputs(
    template_source,
    destination_source,
    dialect,
    execution[:review_state],
    execution[:applied_children]
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_replay_bundle_envelope(template_source, destination_source, dialect, envelope) ⇒ Object



1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# File 'lib/ruby/merge.rb', line 1194

def merge_ruby_with_reviewed_nested_outputs_from_replay_bundle_envelope(template_source, destination_source,
                                                                        dialect, envelope)
  replay_bundle, import_error = Ast::Merge.import_review_replay_bundle_envelope(envelope)
  if import_error
    return { ok: false,
             diagnostics: [{ severity: 'error', category: import_error[:category], message: import_error[:message] }], policies: [] }
  end

  merge_ruby_with_reviewed_nested_outputs_from_replay_bundle(
    template_source,
    destination_source,
    dialect,
    replay_bundle
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_review_state(template_source, destination_source, dialect, review_state) ⇒ Object



1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/ruby/merge.rb', line 1177

def merge_ruby_with_reviewed_nested_outputs_from_review_state(template_source, destination_source, dialect,
                                                              review_state)
  execution = Array(review_state[:reviewed_nested_executions]).find { |entry| entry[:family] == 'ruby' }
  unless execution
    return { ok: false,
             diagnostics: [{ severity: 'error', category: 'configuration_error', message: 'review state does not include a reviewed nested execution for ruby.' }], policies: [] }
  end

  merge_ruby_with_reviewed_nested_outputs(
    template_source,
    destination_source,
    dialect,
    execution[:review_state],
    execution[:applied_children]
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_review_state_envelope(template_source, destination_source, dialect, envelope) ⇒ Object



1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
# File 'lib/ruby/merge.rb', line 1210

def merge_ruby_with_reviewed_nested_outputs_from_review_state_envelope(template_source, destination_source,
                                                                       dialect, envelope)
  review_state, import_error = Ast::Merge.import_conformance_manifest_review_state_envelope(envelope)
  if import_error
    return { ok: false,
             diagnostics: [{ severity: 'error', category: import_error[:category], message: import_error[:message] }], policies: [] }
  end

  merge_ruby_with_reviewed_nested_outputs_from_review_state(
    template_source,
    destination_source,
    dialect,
    review_state
  )
end

.parse_ruby(source, dialect, backend: nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/ruby/merge.rb', line 118

def parse_ruby(source, dialect, backend: nil)
  requested = backend.to_s.empty? ? nil : backend.to_s
  return unsupported_feature_result("Unsupported Ruby dialect #{dialect}.") unless dialect == 'ruby'

  unless ruby_backend_available_for_analysis?(requested)
    diagnostic_backend = requested || TreeHaver.current_backend_id || 'tree-sitter'
    return unsupported_feature_result("Unsupported Ruby backend #{diagnostic_backend}.")
  end

  tree = parse_tree_sitter_source(:ruby, source, backend: requested)
  collect_parse_errors(tree.root_node)

  process_analysis = ruby_process_analysis_from_tree(source, tree.root_node)
  {
    ok: true,
    diagnostics: [],
    analysis: analyze_ruby_document(source, process_analysis: process_analysis),
    policies: []
  }
rescue TreeHaver::Error, StandardError => e
  parse_failure_result(e)
end

.ruby_backend_feature_profile(backend: nil) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/ruby/merge.rb', line 78

def ruby_backend_feature_profile(backend: nil)
  requested = requested_tree_sitter_backend_id(backend)
  unless ruby_backend_available_for_analysis?(requested)
    return unsupported_feature_result("Unsupported Ruby backend #{requested}.")
  end

  ruby_feature_profile.merge(
    backend: requested,
    backend_ref: TREE_SITTER_BACKEND.to_h,
    supports_dialects: true
  )
end

.ruby_delegated_child_operations(analysis, parent_operation_id: 'ruby-document-0') ⇒ Object



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
# File 'lib/ruby/merge.rb', line 320

def ruby_delegated_child_operations(analysis, parent_operation_id: 'ruby-document-0')
  surfaces = ruby_discovered_surfaces(analysis)
  doc_operation_ids = {}
  operations = []

  surfaces.each_with_index do |surface, index|
    next unless surface[:surface_kind] == 'ruby_doc_comment'

    operation_id = "ruby-doc-comment-#{index}"
    doc_operation_ids[surface[:address]] = operation_id
    operations << Ast::Merge.delegated_child_operation(
      operation_id: operation_id,
      parent_operation_id: parent_operation_id,
      requested_strategy: 'delegate_child_surface',
      language_chain: ['ruby', surface[:effective_language]],
      surface: surface
    )
  end

  example_index = 0
  surfaces.each do |surface|
    next unless surface[:surface_kind] == 'yard_example_block'

    operations << Ast::Merge.delegated_child_operation(
      operation_id: "yard-example-#{example_index}",
      parent_operation_id: doc_operation_ids.fetch(surface[:parent_address], parent_operation_id),
      requested_strategy: 'delegate_child_surface',
      language_chain: ['ruby', 'yard', surface[:effective_language]],
      surface: surface
    )
    example_index += 1
  end

  operations
end

.ruby_discovered_surfaces(analysis) ⇒ Object



316
317
318
# File 'lib/ruby/merge.rb', line 316

def ruby_discovered_surfaces(analysis)
  analysis[:discovered_surfaces] || []
end

.ruby_feature_profileObject



59
60
61
62
63
64
65
# File 'lib/ruby/merge.rb', line 59

def ruby_feature_profile
  {
    family: 'ruby',
    supported_dialects: ['ruby'],
    supported_policies: [DESTINATION_WINS_ARRAY_POLICY]
  }
end

.ruby_method_move_detection(template_source, destination_source, dialect) ⇒ Object



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
# File 'lib/ruby/merge.rb', line 162

def ruby_method_move_detection(template_source, destination_source, dialect)
  return unsupported_feature_result("Unsupported Ruby dialect #{dialect}.") unless dialect == 'ruby'

  template_methods = ruby_method_projection(template_source, revision: 'template')
  destination_methods = ruby_method_projection(destination_source, revision: 'destination')
  destination_by_signature = destination_methods.to_h { |entry| [entry[:signature], entry] }
  template_signatures = template_methods.map { |entry| entry[:signature] }.to_h { |signature| [signature, true] }

  matches = template_methods.filter_map do |template_entry|
    destination_entry = destination_by_signature[template_entry[:signature]]
    next unless destination_entry

    moved = template_entry[:index] != destination_entry[:index] || template_entry[:parent_path] != destination_entry[:parent_path]
    Ast::Merge::MoveDetectionMatch.new(
      from_path: template_entry[:path],
      to_path: destination_entry[:path],
      from_node_id: template_entry[:node_id],
      to_node_id: destination_entry[:node_id],
      signature: template_entry[:signature],
      moved: moved,
      from_parent_path: template_entry[:parent_path],
      to_parent_path: destination_entry[:parent_path],
      from_index: template_entry[:index],
      to_index: destination_entry[:index],
      confidence: moved ? 0.98 : 0.9,
      diagnostics: [moved ? 'same Ruby method signature observed at a different sibling position' : 'same Ruby method signature observed at the same sibling position']
    )
  end

  matched_template_signatures = matches.map(&:signature).to_h { |signature| [signature, true] }
  Ast::Merge::MoveDetectionMatchingReport.new(
    matching_id: 'ruby-method-move-detection',
    strategy: 'move_detection',
    from_revision: 'template',
    to_revision: 'destination',
    capability: Ast::Merge::MoveDetectionCapability.new(
      name: 'move_detection',
      enabled: true,
      default_enabled: false,
      requires_stable_node_identity: true
    ),
    matches: matches,
    unmatched_from: template_methods.reject do |entry|
      matched_template_signatures[entry[:signature]]
    end.map { |entry| entry[:path] },
    unmatched_to: destination_methods.reject do |entry|
      template_signatures[entry[:signature]]
    end.map { |entry| entry[:path] },
    diagnostics: ['Ruby method move detection uses generic move-detection matching over receiver-aware method projections']
  ).to_h
end

.ruby_plan_context(backend: nil) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/ruby/merge.rb', line 91

def ruby_plan_context(backend: nil)
  profile = ruby_backend_feature_profile(backend: backend)
  return profile if profile[:ok] == false

  {
    family_profile: ruby_feature_profile,
    feature_profile: {
      backend: profile[:backend],
      supports_dialects: true,
      supported_policies: profile[:supported_policies]
    }
  }
end

.ruby_tslp_capability_profileObject



71
72
73
74
75
76
# File 'lib/ruby/merge.rb', line 71

def ruby_tslp_capability_profile
  {
    import_records: TreeHaver::BackendRegistry.tag_available?(:tslp_ruby_import_records),
    top_level_call_records: TreeHaver::BackendRegistry.tag_available?(:tslp_ruby_top_level_call_records)
  }
end

.unsupported_feature_result(message) ⇒ Object



2218
2219
2220
2221
2222
2223
2224
# File 'lib/ruby/merge.rb', line 2218

def unsupported_feature_result(message)
  {
    ok: false,
    diagnostics: [{ severity: 'error', category: 'unsupported_feature', message: message }],
    policies: []
  }
end

Instance Method Details

#add_source_owner_occurrence_indexes(identities) ⇒ Object



1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
# File 'lib/ruby/merge.rb', line 1925

def add_source_owner_occurrence_indexes(identities)
  counters = Hash.new(0)
  identities.map do |identity|
    occurrence_index = counters[identity[:structural_identity]]
    counters[identity[:structural_identity]] += 1
    identity.merge(
      occurrence_index: occurrence_index,
      address: occurrence_index.zero? ? identity[:address] : "#{identity[:address]}[#{occurrence_index}]"
    )
  end
end

#attached_comment_start_index(lines, declaration_index) ⇒ Object



1852
1853
1854
1855
1856
# File 'lib/ruby/merge.rb', line 1852

def attached_comment_start_index(lines, declaration_index)
  index = declaration_index.to_i
  index -= 1 while index.positive? && comment_line?(lines[index - 1])
  index
end

#collect_parse_errors(node) ⇒ Object

Raises:

  • (TreeHaver::NotAvailable)


1312
1313
1314
1315
1316
1317
1318
# File 'lib/ruby/merge.rb', line 1312

def collect_parse_errors(node)
  raise TreeHaver::NotAvailable, 'Ruby parse returned no root node' unless node
  return unless node.respond_to?(:has_error?) && node.has_error?

  raise TreeHaver::NotAvailable,
        'Ruby parse contains syntax errors'
end

#collect_ruby_preamble(source) ⇒ Object



1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
# File 'lib/ruby/merge.rb', line 1290

def collect_ruby_preamble(source)
  lines = normalize_source(source).split("\n")
  preamble = []
  lines.each do |line|
    break unless line.strip.empty? || comment_line?(line)

    preamble << line.rstrip
  end
  preamble.join("\n").strip
end

#coverage_directive_comment_line?(line) ⇒ Boolean

Returns:

  • (Boolean)


1477
1478
1479
# File 'lib/ruby/merge.rb', line 1477

def coverage_directive_comment_line?(line)
  BlockDirectiveDetector.coverage_directive_line?(line)
end

#direct_method_shadowing(declaration_entry) ⇒ Object



1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
# File 'lib/ruby/merge.rb', line 1974

def direct_method_shadowing(declaration_entry)
  grouped = direct_body_method_entries(declaration_entry[:text]).each_with_index.group_by do |(method_entry, _index)|
    method_entry[:signature]
  end

  grouped.filter_map do |signature, entries|
    next if entries.length < 2

    {
      owner_path: declaration_entry[:path],
      method_signature: signature,
      effective_index: entries.last[1],
      shadowed_indices: entries[0...-1].map { |_method_entry, index| index },
      shadowed_count: entries.length - 1
    }
  end
end

#emit_ruby_top_level_sections(destination_source, sections) ⇒ Object



1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'lib/ruby/merge.rb', line 1781

def emit_ruby_top_level_sections(destination_source, sections)
  lines = normalize_source(destination_source).split("\n", -1)
  emitted = sections.reject { |section| section[:text].to_s.strip.empty? }
  previous = nil
  output = +''

  emitted.each do |section|
    output << ruby_top_level_section_separator(lines, previous, section) if previous
    output << section.fetch(:text).strip
    previous = section
  end

  "#{output.strip}\n"
end

#legacy_collect_ruby_declaration_entries(source) ⇒ Object



1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
# File 'lib/ruby/merge.rb', line 1648

def legacy_collect_ruby_declaration_entries(source)
  # TSLP process records are the preferred substrate. This legacy scanner is
  # retained only for direct helper calls that do not have parser analysis.
  # Main merge paths must pass process_analysis and fail closed when TSLP
  # cannot provide readable structure records.
  lines = normalize_source(source).split("\n")
  entries = []
  pending_comments = []
  index = 0

  while index < lines.length
    line = lines[index]
    stripped = line.strip

    if comment_line?(line)
      pending_comments << index
      index += 1
      next
    end

    if stripped.empty?
      pending_comments = []
      index += 1
      next
    end

    if REQUIRE_PATTERN.match?(line)
      pending_comments = []
      index += 1
      next
    end

    declaration = declaration_for_line(line)
    unless declaration
      pending_comments = []
      index += 1
      next
    end

    start_index = pending_comments.first || index
    depth = 1
    cursor = index + 1
    while cursor < lines.length
      candidate = lines[cursor].strip
      depth += 1 if declaration_for_line(candidate)
      if candidate == 'end'
        depth -= 1
        if depth.zero?
          cursor += 1
          break
        end
      end
      cursor += 1
    end

    entries << {
      path: "/declarations/#{declaration[:name]}",
      name: declaration[:name],
      kind: declaration[:kind],
      merge_key: "#{declaration[:kind]}:#{declaration[:name]}",
      text: lines[start_index...cursor].join("\n").strip
    }
    pending_comments = []
    index = cursor
  end

  entries
end

#legacy_require_line?(line, process_analysis) ⇒ Boolean

Returns:

  • (Boolean)


1609
1610
1611
1612
1613
# File 'lib/ruby/merge.rb', line 1609

def legacy_require_line?(line, process_analysis)
  return false if process_analysis

  REQUIRE_PATTERN.match?(line)
end

#legacy_ruby_analysis_owner_entries(source) ⇒ Object



1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
# File 'lib/ruby/merge.rb', line 1717

def legacy_ruby_analysis_owner_entries(source)
  normalize_source(source).split("\n").filter_map do |line|
    declaration = declaration_for_line(line)
    next unless declaration

    {
      path: "/declarations/#{declaration[:name]}",
      name: declaration[:name],
      kind: declaration[:kind],
      merge_key: "#{declaration[:kind]}:#{declaration[:name]}"
    }
  end
end

#legacy_ruby_require_owners(source) ⇒ Object



1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
# File 'lib/ruby/merge.rb', line 1587

def legacy_ruby_require_owners(source)
  requires = []
  normalize_source(source).split("\n").each do |line|
    match = REQUIRE_PATTERN.match(line)
    next unless match

    requires << {
      path: "/requires/#{requires.length}",
      owner_kind: 'require',
      match_key: match[1]
    }
  end
  requires
end

#merge_array_constant_text(template_text, destination_text) ⇒ Object



2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
# File 'lib/ruby/merge.rb', line 2096

def merge_array_constant_text(template_text, destination_text)
  template_match = template_text.match(/\A(\s*[A-Z]\w*\s*=\s*)\[(.*)\]\z/)
  destination_match = destination_text.match(/\A(\s*[A-Z]\w*\s*=\s*)\[(.*)\]\z/)
  unless template_match && destination_match
    return merge_percent_array_constant_text(template_text,
                                             destination_text) || merge_multiline_array_constant_text(template_text,
                                                                                                      destination_text)
  end

  destination_elements = split_ruby_array_elements(destination_match[2])
  template_elements = split_ruby_array_elements(template_match[2])
  destination_keys = destination_elements.map do |element|
    normalize_array_element_key(element)
  end.to_h { |key| [key, true] }
  appended = template_elements.reject { |element| destination_keys[normalize_array_element_key(element)] }
  return destination_text if appended.empty?

  "#{destination_match[1]}[#{(destination_elements + appended).join(', ')}]"
end

#merge_declaration_body_constants(template_text, destination_text) ⇒ Object



2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
# File 'lib/ruby/merge.rb', line 2066

def merge_declaration_body_constants(template_text, destination_text)
  template_constants = direct_body_constant_entries(template_text)
  destination_constants = direct_body_constant_entries(destination_text)
  return destination_text if template_constants.empty?

  merged_text = merge_matched_array_constants(template_constants, destination_constants, destination_text)
  destination_names = destination_constants.map { |entry| entry[:name] }.to_h { |name| [name, true] }
  missing_constants = template_constants.reject { |entry| destination_names[entry[:name]] }
  return merged_text if missing_constants.empty?

  insert_declaration_body_blocks(merged_text, missing_constants.map do |entry|
    entry[:text]
  end, placement: :after_opening)
end

#merge_declaration_body_methods(template_text, destination_text) ⇒ Object



2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
# File 'lib/ruby/merge.rb', line 2163

def merge_declaration_body_methods(template_text, destination_text)
  template_methods = direct_body_method_entries(template_text)
  destination_methods = direct_body_method_entries(destination_text)
  return destination_text if template_methods.empty?

  destination_method_signatures = destination_methods.map do |entry|
    entry[:signature]
  end.to_h { |signature| [signature, true] }
  missing_methods = template_methods.reject { |entry| destination_method_signatures[entry[:signature]] }
  return destination_text if missing_methods.empty?

  public_methods, visibility_methods = missing_methods.partition { |entry| entry[:visibility] == 'public' }
  merged_text = destination_text
  unless public_methods.empty?
    merged_text = insert_declaration_body_blocks(
      merged_text,
      public_methods.map { |entry| entry[:body_text] },
      before_visibility: !direct_visibility_section_present?(merged_text, 'public')
    )
  end
  visibility_methods.group_by { |entry| entry[:visibility] }.each do |visibility, entries|
    blocks = if direct_visibility_section_present?(merged_text, visibility)
               merged_text = insert_declaration_body_blocks(merged_text, entries.map do |entry|
                 entry[:body_text]
               end, before_visibility: false)
               next
             else
               entries.map { |entry| entry[:text] }
             end
    merged_text = insert_declaration_body_blocks(merged_text, blocks)
  end
  merged_text
end

#merge_declaration_hash_constants(template_text, destination_text) ⇒ Object



2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
# File 'lib/ruby/merge.rb', line 2044

def merge_declaration_hash_constants(template_text, destination_text)
  template_blocks = constant_hash_blocks(template_text).to_h { |block| [block[:constant], block] }
  destination_blocks = constant_hash_blocks(destination_text)
  return destination_text if template_blocks.empty? || destination_blocks.empty?

  output = destination_text.dup
  destination_blocks.reverse_each do |destination_block|
    template_block = template_blocks[destination_block[:constant]]
    next unless template_block

    template_hash = RubyHashLiteralProjector.new(template_block[:hash_source]).call
    destination_hash = RubyHashLiteralProjector.new(destination_block[:hash_source]).call
    merged_hash = merge_ruby_hash_literals(template_hash, destination_hash)
    rendered = "#{destination_block[:prefix]}#{render_ruby_hash_literal(merged_hash,
                                                                        destination_block[:base_indent])}"
    output[destination_block[:range]] = rendered
  rescue ArgumentError
    next
  end
  output
end

#merge_matched_array_constants(template_constants, destination_constants, destination_text) ⇒ Object



2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
# File 'lib/ruby/merge.rb', line 2081

def merge_matched_array_constants(template_constants, destination_constants, destination_text)
  template_by_name = template_constants.to_h { |entry| [entry[:name], entry] }
  output = destination_text.dup
  destination_constants.reverse_each do |destination_entry|
    template_entry = template_by_name[destination_entry[:name]]
    next unless template_entry

    merged_text = merge_array_constant_text(template_entry[:text], destination_entry[:text])
    next unless merged_text

    output[destination_entry[:range]] = merged_text
  end
  output
end

#merge_multiline_array_constant_text(template_text, destination_text) ⇒ Object



2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
# File 'lib/ruby/merge.rb', line 2145

def merge_multiline_array_constant_text(template_text, destination_text)
  template_match = template_text.match(/\A(\s*[A-Z]\w*\s*=\s*\[\n)(.*)(\n\s*\])\z/m)
  destination_match = destination_text.match(/\A(\s*[A-Z]\w*\s*=\s*\[\n)(.*)(\n\s*\])\z/m)
  return unless template_match && destination_match

  destination_elements = multiline_array_elements(destination_match[2])
  template_elements = multiline_array_elements(template_match[2])
  destination_keys = destination_elements.map do |element|
    normalize_array_element_key(element[:value])
  end.to_h { |key| [key, true] }
  appended = template_elements.reject { |element| destination_keys[normalize_array_element_key(element[:value])] }
  return destination_text if appended.empty?

  insertion_prefix = destination_elements.last&.dig(:indent) || template_elements.first&.dig(:indent) || '  '
  body = append_multiline_array_elements(destination_match[2], appended, insertion_prefix)
  "#{destination_match[1]}#{body}#{destination_match[3]}"
end

#merge_nested_body_declarations(template_text, destination_text) ⇒ Object



2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
# File 'lib/ruby/merge.rb', line 2197

def merge_nested_body_declarations(template_text, destination_text)
  template_entries = direct_body_declaration_entries(template_text)
  destination_entries = direct_body_declaration_entries(destination_text)
  return destination_text if template_entries.empty? || destination_entries.empty?

  template_by_path = template_entries.to_h { |entry| [entry[:merge_key], entry] }
  output = destination_text.dup
  destination_entries.reverse_each do |destination_entry|
    template_entry = template_by_path[destination_entry[:merge_key]]
    next unless template_entry

    output[destination_entry[:range]] = merge_ruby_declaration_entry(template_entry, destination_entry)[:text]
  end

  destination_paths = destination_entries.map { |entry| entry[:merge_key] }.to_h { |path| [path, true] }
  missing_entries = template_entries.reject { |entry| destination_paths[entry[:merge_key]] }
  return output if missing_entries.empty?

  insert_declaration_body_blocks(output, missing_entries.map { |entry| entry[:text] })
end

#merge_percent_array_constant_text(template_text, destination_text) ⇒ Object



2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
# File 'lib/ruby/merge.rb', line 2116

def merge_percent_array_constant_text(template_text, destination_text)
  template_match = parse_percent_array_constant_text(template_text)
  destination_match = parse_percent_array_constant_text(destination_text)
  return unless template_match && destination_match

  destination_elements = destination_match[:body].split(/\s+/).reject(&:empty?)
  template_elements = template_match[:body].split(/\s+/).reject(&:empty?)
  destination_keys = destination_elements.to_h { |element| [element, true] }
  appended = template_elements.reject { |element| destination_keys[element] }
  return destination_text if appended.empty?

  "#{destination_match[:prefix]}#{(destination_elements + appended).join(' ')}#{destination_match[:closing]}"
end

#merge_ruby_declaration_entry(template_entry, destination_entry) ⇒ Object



1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
# File 'lib/ruby/merge.rb', line 1858

def merge_ruby_declaration_entry(template_entry, destination_entry)
  return destination_entry unless template_entry

  merged_text = merge_declaration_hash_constants(template_entry[:text], destination_entry[:text])
  merged_text = merge_declaration_body_constants(template_entry[:text], merged_text)
  merged_text = merge_declaration_body_methods(template_entry[:text], merged_text)
  merged_text = merge_nested_body_declarations(template_entry[:text], merged_text)
  destination_entry.merge(
    text: merged_text
  )
end

#merge_ruby_requires(destination_requires, template_requires) ⇒ Object



1507
1508
1509
1510
# File 'lib/ruby/merge.rb', line 1507

def merge_ruby_requires(destination_requires, template_requires)
  destination_paths = destination_requires.to_h { |entry| [entry[:path], true] }
  destination_requires + template_requires.reject { |entry| destination_paths[entry[:path]] }
end

#namespace_wrapper_matched?(entry, candidates, matched) ⇒ Boolean

Returns:

  • (Boolean)


2034
2035
2036
2037
2038
2039
2040
2041
2042
# File 'lib/ruby/merge.rb', line 2034

def namespace_wrapper_matched?(entry, candidates, matched)
  children = candidates.select { |candidate| candidate[:namespace_root_merge_key] == entry[:merge_key] }
  return false if children.empty?
  unless direct_body_method_entries(entry[:text]).empty? && direct_body_constant_entries(entry[:text]).empty?
    return false
  end

  children.all? { |child| matched[child[:merge_key]] }
end

#normalize_declaration_text_indent(text) ⇒ Object



2024
2025
2026
2027
2028
2029
2030
2031
2032
# File 'lib/ruby/merge.rb', line 2024

def normalize_declaration_text_indent(text)
  lines = text.to_s.split("\n")
  base_indent = lines.first.to_s[/\A\s*/].to_s
  return text if base_indent.empty?

  lines.map do |line|
    line.start_with?(base_indent) ? line[base_indent.length..].to_s : line
  end.join("\n")
end

#normalize_method_move_policy(policy) ⇒ Object

Raises:

  • (ArgumentError)


2226
2227
2228
2229
2230
2231
2232
# File 'lib/ruby/merge.rb', line 2226

def normalize_method_move_policy(policy)
  normalized = policy.to_s.strip
  normalized = DEFAULT_METHOD_MOVE_POLICY if normalized.empty?
  return normalized if normalized == DEFAULT_METHOD_MOVE_POLICY

  raise ArgumentError, "Unsupported Ruby method move policy #{policy.inspect}"
end

#normalized_method_body_identity(body_text) ⇒ Object



1950
1951
1952
1953
1954
1955
# File 'lib/ruby/merge.rb', line 1950

def normalized_method_body_identity(body_text)
  normalized_lines = body_text.to_s.lines.map.with_index do |line, index|
    index.zero? && DEF_PATTERN.match?(line) ? "#{line[/\A\s*/]}def __owner_name__\n" : line
  end
  "sha256:#{Digest::SHA256.hexdigest(normalized_lines.join)}"
end

#parse_failure_result(error) ⇒ Object



1320
1321
1322
1323
1324
1325
1326
# File 'lib/ruby/merge.rb', line 1320

def parse_failure_result(error)
  {
    ok: false,
    diagnostics: [{ severity: 'error', category: 'parse_error', message: error.message }],
    policies: []
  }
end

#parse_percent_array_constant_text(text) ⇒ Object



2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
# File 'lib/ruby/merge.rb', line 2130

def parse_percent_array_constant_text(text)
  match = text.match(/\A(?<head>\s*[A-Z]\w*\s*=\s*%[wWiI])(?<opening>[^\s[:alnum:]])(?<content>.*)\z/)
  return unless match

  closing = PERCENT_ARRAY_DELIMITER_PAIRS.fetch(match[:opening], match[:opening])
  content = match[:content]
  return unless content.end_with?(closing)

  {
    prefix: "#{match[:head]}#{match[:opening]}",
    body: content[0...-closing.length],
    closing: closing
  }
end

#qualified_nested_declaration_entries(entries) ⇒ Object



2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
# File 'lib/ruby/merge.rb', line 2007

def qualified_nested_declaration_entries(entries)
  entries.flat_map do |entry|
    direct_body_declaration_entries(entry[:text]).map do |nested_entry|
      root_name = entry[:name]
      nested_name = nested_entry[:name]
      qualified_name = nested_name.include?('::') ? nested_name : "#{root_name}::#{nested_name}"
      nested_entry.merge(
        name: qualified_name,
        path: "/declarations/#{qualified_name}",
        merge_key: "#{nested_entry[:kind]}:#{qualified_name}",
        text: normalize_declaration_text_indent(nested_entry[:text]),
        namespace_root_merge_key: entry[:merge_key]
      )
    end
  end
end

#register_backend!Object



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ruby/merge.rb', line 46

def register_backend!
  BACKEND_REGISTRY.mutex.synchronize do
    return if BACKEND_REGISTRY.registered

    TreeHaver::BackendRegistry.register(TREE_SITTER_BACKEND)

    grammar_finder = TreeHaver::GrammarFinder.new(:ruby)
    grammar_finder.register! if grammar_finder.available?

    BACKEND_REGISTRY.registered = true
  end
end

#ruby_ambiguous_source_owner_identity_report(source) ⇒ Object



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
# File 'lib/ruby/merge.rb', line 432

def ruby_ambiguous_source_owner_identity_report(source)
  identities = ruby_source_owner_identity_profile(source)
  ambiguities = identities
                .group_by { |identity| identity[:structural_identity] }
                .filter_map do |structural_identity, entries|
                  next if entries.length < 2

                  {
                    structural_identity: structural_identity,
                    occurrence_count: entries.length,
                    addresses: entries.map { |entry| entry[:address] },
                    ambiguity_kind: 'duplicate_structural_identity',
                    resolution_model: 'ordered_cursor',
                    confidence: 'structural_ordered'
                  }
                end

  {
    ambiguities: ambiguities,
    diagnostics: if ambiguities.empty?
                   []
                 else
                   [
                     {
                       severity: 'warning',
                       category: 'ambiguous_source_owner_identity',
                       message: 'Repeated Ruby source-owner identities require ordered cursor matching.'
                     }
                   ]
                 end
  }
end

#ruby_analysis_require_owners(source, process_analysis) ⇒ Object



1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
# File 'lib/ruby/merge.rb', line 1570

def ruby_analysis_require_owners(source, process_analysis)
  imports = Array(process_analysis&.imports)
  unless imports.empty?
    return imports.each_with_index.map do |item, index|
      {
        path: "/requires/#{index}",
        owner_kind: 'require',
        match_key: item.source.to_s
      }
    end
  end

  return [] if process_analysis

  legacy_ruby_require_owners(source)
end

#ruby_ast_node_merge_candidate_report(surface:, base:, template:, destination:, reconstruction_risk: false) ⇒ Object



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
# File 'lib/ruby/merge.rb', line 673

def ruby_ast_node_merge_candidate_report(surface:, base:, template:, destination:, reconstruction_risk: false)
  {
    surface: surface,
    strategy_profile: ruby_ast_node_merge_strategy_profile.fetch(:profile_id),
    candidate_strategy: reconstruction_risk ? 'fallback_or_scoped_conflict' : 'hybrid_ast_node_merge',
    owner_level_fallback_too_blunt: !reconstruction_risk,
    successor_ordering_available: true,
    pcs_like_strategy_available: true,
    public_contract_level: 'ruleset_and_fixture',
    backend_strategy_choices: ruby_ast_node_merge_strategy_profile.fetch(:backend_strategy_choices),
    inputs: {
      base: base,
      template: template,
      destination: destination
    },
    reconstruction: {
      risky: reconstruction_risk,
      outcome: reconstruction_risk ? 'fallback_or_scoped_conflict' : 'preserve_original_text_boundaries'
    },
    diagnostics: [
      {
        severity: reconstruction_risk ? 'warning' : 'info',
        category: reconstruction_risk ? 'ast_node_reconstruction_risk' : 'ast_node_merge_candidate',
        message: reconstruction_risk ? 'Ruby AST-node merge candidate has ambiguous whitespace, comment, or marker reconstruction boundaries.' : 'Ruby AST-node merge candidate can be considered when owner-level fallback would be too blunt.'
      }
    ]
  }
end

#ruby_ast_node_merge_strategy_profileObject



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/ruby/merge.rb', line 656

def ruby_ast_node_merge_strategy_profile
  {
    profile_id: 'ruby-optional-ast-node-merge',
    merge_surfaces: %w[owner ast_node line hybrid],
    optional_fine_grained_profiles: %w[expression argument_list hash_literal_pair],
    child_ordering_strategies: %w[destination_order successor_constraints pcs_like_triples],
    public_contract_level: 'ruleset_and_fixture',
    default_surface: 'owner',
    backend_strategy_choices: %w[entity_level ast_level line_level hybrid],
    reconstruction_policy: {
      preserve_original_text_unless_backend_declares_renderer: true,
      conflict_marker_placement_requires_text_boundary: true,
      risky_reconstruction_outcome: 'fallback_or_scoped_conflict'
    }
  }
end

#ruby_backend_available_for_analysis?(backend_id) ⇒ Boolean

Returns:

  • (Boolean)


105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/ruby/merge.rb', line 105

def ruby_backend_available_for_analysis?(backend_id)
  register_backend!

  if backend_id.to_s.empty?
    TreeHaver.parser_for(:ruby, backend_type: :tree_sitter)
  else
    TreeHaver.with_backend(backend_id) { TreeHaver.parser_for(:ruby, backend_type: :tree_sitter) }
  end
  true
rescue TreeHaver::Error, ArgumentError
  false
end

#ruby_blank_line_ownership_report(source) ⇒ Object



893
894
895
896
897
898
# File 'lib/ruby/merge.rb', line 893

def ruby_blank_line_ownership_report(source)
  regions = ruby_source_regions(source)[:regions]
  {
    blank_line_regions: source_blank_line_ownership_regions(regions: regions)
  }
end

#ruby_child_group_profileObject



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
# File 'lib/ruby/merge.rb', line 848

def ruby_child_group_profile
  {
    profile_id: 'ruby-source-child-groups',
    groups: [
      {
        owner_kind: 'class',
        child_group: 'methods',
        ordering: 'policy_ordered',
        ordering_policy: DEFAULT_METHOD_MOVE_POLICY,
        commutative: false,
        visibility_sections: %w[public protected private]
      },
      {
        owner_kind: 'class',
        child_group: 'constants',
        ordering: 'destination_order_then_template_additions',
        commutative: false
      },
      {
        owner_kind: 'module',
        child_group: 'declarations',
        ordering: 'destination_order_then_template_additions',
        commutative: false
      }
    ],
    diagnostics: [
      {
        severity: 'info',
        category: 'ruby_child_group_profile',
        message: 'Ruby child groups preserve destination order unless an explicit policy says otherwise.'
      }
    ]
  }
end

#ruby_conflict_diagnostics_profileObject



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
# File 'lib/ruby/merge.rb', line 575

def ruby_conflict_diagnostics_profile
  {
    profile_id: 'ruby-source-conflict-diagnostics',
    conflict_kinds: %w[
      both_modified
      both_added
      modify_delete
      rename_rename
      rename_modify
      order_sensitive_sibling_additions
      interstitial_conflict
      validation_failure
    ],
    risk_levels: %w[text_only syntax_level semantic_risk unknown],
    marker_compatibility: {
      standard_markers: true,
      enhanced_metadata: 'sidecar_or_review_state'
    },
    audit_fields: %w[
      owner_identity
      owner_kind
      strategy_chosen
      match_confidence
      fallback_reason
      validation_warnings
      conflict_kind
      conflict_scope
    ],
    stable_for_review_replay: true
  }
end

#ruby_cross_container_method_move_detection(template_source, destination_source) ⇒ Object



1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
# File 'lib/ruby/merge.rb', line 1021

def ruby_cross_container_method_move_detection(template_source, destination_source)
  template_methods = ruby_method_identity_entries(template_source)
  destination_methods = ruby_method_identity_entries(destination_source)
  destination_by_signature_and_body = destination_methods.group_by do |entry|
    [entry[:signature], entry[:normalized_body_identity]]
  end

  moves = template_methods.filter_map do |template_entry|
    destination_entry = destination_by_signature_and_body.fetch(
      [template_entry[:signature], template_entry[:normalized_body_identity]],
      []
    ).find { |entry| entry[:parent_scope] != template_entry[:parent_scope] }
    next unless destination_entry

    {
      from_address: template_entry[:address],
      to_address: destination_entry[:address],
      from_parent_scope: template_entry[:parent_scope],
      to_parent_scope: destination_entry[:parent_scope],
      signature: template_entry[:signature],
      moved: true,
      move_kind: 'cross_container',
      ordering_policy: DEFAULT_METHOD_MOVE_POLICY,
      preserves_destination_order: true,
      confidence: 'content_hash'
    }
  end

  {
    capability: {
      name: 'move_detection',
      enabled: true,
      default_enabled: false,
      requires_stable_node_identity: true
    },
    moves: moves,
    diagnostics: if moves.empty?
                   []
                 else
                   [
                     {
                       severity: 'info',
                       category: 'ruby_cross_container_method_move',
                       message: 'Ruby detected same-signature method movement across containers while preserving destination order.'
                     }
                   ]
                 end
  }
end

#ruby_declaration_name_node(node) ⇒ Object



1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
# File 'lib/ruby/merge.rb', line 1417

def ruby_declaration_name_node(node)
  case node.type
  when 'class', 'module'
    ruby_named_children(node).find do |child|
      %w[constant scope_resolution].include?(child.type)
    end
  when 'method'
    ruby_named_children(node).find do |child|
      %w[identifier method_identifier operator].include?(child.type)
    end
  when 'singleton_method'
    children = ruby_named_children(node)
    children.reverse.find do |child|
      %w[identifier method_identifier operator].include?(child.type)
    end
  end
end

#ruby_fallback_activation_report(reason:, scope:, selected_baseline: 'host_baseline_merge', structured_result_discarded: true) ⇒ Object



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/ruby/merge.rb', line 513

def ruby_fallback_activation_report(reason:, scope:, selected_baseline: 'host_baseline_merge',
                                    structured_result_discarded: true)
  {
    activated: true,
    reason: reason,
    scope: scope,
    selected_baseline: selected_baseline,
    structured_result_discarded: structured_result_discarded,
    policy_id: ruby_fallback_policy_profile.fetch(:policy_id),
    diagnostics: [
      {
        severity: 'warning',
        category: 'fallback_applied',
        message: "Ruby source fallback activated for #{reason} at #{scope} scope."
      }
    ]
  }
end

#ruby_fallback_policy_profileObject



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/ruby/merge.rb', line 492

def ruby_fallback_policy_profile
  {
    policy_id: 'ruby-source-fallback-policy',
    baseline_provider: {
      provider_id: 'host_baseline_merge',
      integration_point: true
    },
    scopes: %w[node subtree owned_region whole_file],
    triggers: [
      { reason: 'binary_input', scope: 'whole_file' },
      { reason: 'unsupported_structural_merge_capability', scope: 'whole_file' },
      { reason: 'no_structural_owners', scope: 'whole_file' },
      { reason: 'both_branches_create_file', scope: 'whole_file' },
      { reason: 'excessive_duplicate_identities', scope: 'owned_region' },
      { reason: 'timeout_or_resource_budget', scope: 'whole_file' },
      { reason: 'backend_diagnostic_threshold', scope: 'owned_region' }
    ],
    reporting_fields: %w[activated reason scope selected_baseline structured_result_discarded]
  }
end

#ruby_fallback_scope_guard_report(requested_scope:, declared_scope:) ⇒ Object



807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# File 'lib/ruby/merge.rb', line 807

def ruby_fallback_scope_guard_report(requested_scope:, declared_scope:)
  widened = ruby_fallback_scope_rank(requested_scope) > ruby_fallback_scope_rank(declared_scope)
  {
    requested_scope: requested_scope,
    declared_scope: declared_scope,
    widened: widened,
    activated: !widened,
    diagnostics: [
      {
        severity: widened ? 'error' : 'info',
        category: widened ? 'fallback_scope_widening_rejected' : 'fallback_scope_accepted',
        message: widened ? "Ruby fallback cannot widen from #{declared_scope} to #{requested_scope} without an explicit policy." : 'Ruby fallback scope is within the declared policy.'
      }
    ]
  }
end

#ruby_fallback_scope_rank(scope) ⇒ Object



1485
1486
1487
# File 'lib/ruby/merge.rb', line 1485

def ruby_fallback_scope_rank(scope)
  ruby_fallback_policy_profile.fetch(:scopes).index(scope.to_s) || Float::INFINITY
end


1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'lib/ruby/merge.rb', line 1301

def ruby_file_footer_text(source)
  regions = ruby_source_regions(source).fetch(:regions)
  footer = regions.reverse.find do |region|
    region[:region_kind] == 'interstitial' && region[:position] == 'file_footer'
  end
  content = footer.to_h.fetch(:content, '').strip
  return '' if content.empty?

  content.lines.any? { |line| !line.strip.empty? && !comment_line?(line) } ? '' : content
end

#ruby_first_descendant(node, &block) ⇒ Object



1435
1436
1437
1438
1439
1440
1441
1442
1443
# File 'lib/ruby/merge.rb', line 1435

def ruby_first_descendant(node, &block)
  ruby_named_children(node).each do |child|
    return child if yield(child)

    descendant = ruby_first_descendant(child, &block)
    return descendant if descendant
  end
  nil
end

#ruby_formatter_adapter_report(pre_format_output:, formatted_output:, policy: 'validate_only', conflict_scope: 'none') ⇒ Object



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
# File 'lib/ruby/merge.rb', line 626

def ruby_formatter_adapter_report(pre_format_output:, formatted_output:, policy: 'validate_only',
                                  conflict_scope: 'none')
  pre_format_owners = ruby_source_owner_identity_profile(pre_format_output)
  formatted_owners = ruby_source_owner_identity_profile(formatted_output)
  formatted_owner_signatures = stable_owner_signatures(formatted_owners)
  owners_preserved = stable_owner_signatures(pre_format_owners) == formatted_owner_signatures
  whitespace_repaired = pre_format_output != formatted_output

  {
    policy: policy,
    formatter_profile: ruby_formatter_policy_profile.fetch(:profile_id),
    adapter_phase: 'optional_post_merge_adapter',
    semantic_validation: 'not_proven_by_formatter',
    whitespace_repaired: whitespace_repaired,
    owners_preserved: owners_preserved,
    conflict_scope_preserved: true,
    validation_semantics_preserved: true,
    conflict_scope: conflict_scope,
    portable_expectation: 'formatter_not_executed_unless_fixture_opts_in',
    owner_signatures: formatted_owner_signatures,
    diagnostics: [
      {
        severity: owners_preserved ? 'info' : 'error',
        category: owners_preserved ? 'formatter_adapter_accepted' : 'formatter_adapter_rejected',
        message: owners_preserved ? 'Ruby formatter adapter preserved owner identity, conflict scope, and validation semantics.' : 'Ruby formatter adapter changed owner identity and cannot be accepted as a semantic merge.'
      }
    ]
  }
end

#ruby_formatter_policy_profileObject



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/ruby/merge.rb', line 607

def ruby_formatter_policy_profile
  {
    profile_id: 'ruby-source-formatter-policy',
    adapter_phase: 'optional_post_merge_adapter',
    semantic_validation: 'not_proven_by_formatter',
    policies: %w[
      no_formatter
      validate_only
      format_after_clean_merge
      format_after_fallback
      formatter_failure_is_warning
      formatter_failure_is_hard_error
    ],
    portable_fixture_default: 'no_formatter',
    formatter_execution_in_portable_expectations: 'only_when_fixture_opts_in',
    invariants: %w[owner_identity conflict_scope validation_semantics]
  }
end

#ruby_import_item_from_begin_node(source, node) ⇒ Object



1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
# File 'lib/ruby/merge.rb', line 1378

def ruby_import_item_from_begin_node(source, node)
  children = ruby_named_children(node)
  call_imports = children.filter_map do |child|
    ruby_import_item_from_node(source, child) if child.type == 'call'
  end
  return if call_imports.empty?

  unsupported = children.any? do |child|
    child.type != 'call' && !ruby_load_error_rescue_node?(source, child)
  end
  return if unsupported

  TslpImportItem.new(source: call_imports.map(&:source).join(','), span: ruby_span_for(node))
end

#ruby_import_item_from_modifier_node(source, node) ⇒ Object



1368
1369
1370
1371
1372
1373
1374
1375
1376
# File 'lib/ruby/merge.rb', line 1368

def ruby_import_item_from_modifier_node(source, node)
  call_node = ruby_named_children(node).first
  return unless call_node&.type == 'call'

  import = ruby_import_item_from_node(source, call_node)
  return unless import

  TslpImportItem.new(source: import.source, span: ruby_import_span_for(source, node))
end

#ruby_import_item_from_node(source, node) ⇒ Object



1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'lib/ruby/merge.rb', line 1352

def ruby_import_item_from_node(source, node)
  children = ruby_named_children(node)
  callee = children.first
  return unless callee && %w[identifier method_identifier].include?(callee.type)

  name = ruby_node_text(source, callee)
  return unless %w[require require_relative].include?(name)

  string_node = ruby_first_descendant(node) do |child|
    %w[string_content simple_symbol].include?(child.type)
  end
  return unless string_node

  TslpImportItem.new(source: ruby_node_text(source, string_node), span: ruby_import_span_for(source, node))
end

#ruby_import_span_for(source, node) ⇒ Object



1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
# File 'lib/ruby/merge.rb', line 1460

def ruby_import_span_for(source, node)
  span = ruby_span_for(node)
  lines = normalize_source(source).split("\n")
  start_row = span.start_row
  end_row = span.end_row

  start_row -= 1 while start_row.positive? && coverage_directive_comment_line?(lines[start_row - 1])
  end_row += 1 while end_row < lines.length - 1 && coverage_directive_comment_line?(lines[end_row + 1])

  TslpSpan.new(
    start_row: start_row,
    start_col: start_row == span.start_row ? span.start_col : 0,
    end_row: end_row,
    end_col: end_row == span.end_row ? span.end_col : lines[end_row].to_s.length
  )
end

#ruby_interstitial_comment_attachment_report(source) ⇒ Object



883
884
885
886
887
888
889
890
891
# File 'lib/ruby/merge.rb', line 883

def ruby_interstitial_comment_attachment_report(source)
  lines = normalize_source(source).lines(chomp: true)
  owners = top_level_source_region_owners(lines)
  source_comment_block_attachment_report(
    lines: lines,
    owners: owners,
    comment_line: method(:comment_line?)
  )
end

#ruby_interstitial_merge_policy_profileObject



824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
# File 'lib/ruby/merge.rb', line 824

def ruby_interstitial_merge_policy_profile
  {
    policy_id: 'ruby-source-interstitial-merge',
    separates_owner_merge: true,
    region_kinds: %w[file_header file_footer container_header container_footer between],
    owner_adjacency_fields: %w[previous_owner next_owner],
    rules: [
      {
        region_kind: 'require',
        ordering: 'destination_order_then_template_additions',
        duplicate_key: 'require_path'
      },
      {
        region_kind: 'blank_line',
        ownership: 'preserve_declared_region_owner'
      },
      {
        region_kind: 'comment',
        attachment: 'nearest_declared_owner_or_standalone'
      }
    ]
  }
end

#ruby_intra_owner_merge_plan(template_entries, destination_entries) ⇒ Object



1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
# File 'lib/ruby/merge.rb', line 1870

def ruby_intra_owner_merge_plan(template_entries, destination_entries)
  template_by_key = template_entries.to_h { |entry| [entry[:merge_key], entry] }
  destination_entries.flat_map do |destination_entry|
    template_entry = template_by_key[destination_entry[:merge_key]]
    next [] unless template_entry
    next [] unless %w[class module].include?(destination_entry[:kind])

    template_methods = direct_body_method_entries(template_entry[:text]).to_h { |entry| [entry[:signature], entry] }
    direct_body_method_entries(destination_entry[:text]).filter_map do |destination_method|
      template_method = template_methods[destination_method[:signature]]
      next unless template_method
      next if template_method[:body_text] == destination_method[:body_text]

      {
        owner_path: destination_entry[:path],
        owner_kind: destination_entry[:kind],
        owner_name: destination_entry[:name],
        child_group: 'methods',
        child_signature: destination_method[:signature],
        child_path: "#{destination_entry[:path]}/methods/#{destination_method[:signature]}",
        decision: 'destination_wins',
        scope: 'owner_body'
      }
    end
  end
end

#ruby_load_error_rescue_node?(source, node) ⇒ Boolean

Returns:

  • (Boolean)


1393
1394
1395
1396
1397
1398
# File 'lib/ruby/merge.rb', line 1393

def ruby_load_error_rescue_node?(source, node)
  return false unless node.type == 'rescue'
  return false unless ruby_named_children(node).all? { |child| child.type == 'exceptions' }

  ruby_node_text(source, node).match?(/\Arescue\s+LoadError\b/)
end

#ruby_method_identity_entries(source) ⇒ Object



1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
# File 'lib/ruby/merge.rb', line 1937

def ruby_method_identity_entries(source)
  collect_ruby_declaration_entries(source).flat_map do |declaration_entry|
    direct_body_method_entries(declaration_entry[:text]).map do |method_entry|
      {
        parent_scope: declaration_entry[:path],
        signature: method_entry[:signature],
        address: "#{declaration_entry[:path]}/methods/#{method_entry[:signature]}",
        normalized_body_identity: normalized_method_body_identity(method_entry[:body_text])
      }
    end
  end
end

#ruby_method_projection(source, revision:) ⇒ Object



1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
# File 'lib/ruby/merge.rb', line 1992

def ruby_method_projection(source, revision:)
  collect_ruby_declaration_entries(source).flat_map do |declaration_entry|
    direct_body_method_entries(declaration_entry[:text]).each_with_index.map do |method_entry, index|
      signature = "method:#{declaration_entry[:path]}:#{method_entry[:signature]}"
      {
        path: "#{declaration_entry[:path]}/methods/#{index}",
        parent_path: "#{declaration_entry[:path]}/methods",
        node_id: "#{revision}:#{signature}",
        signature: signature,
        index: index
      }
    end
  end
end

#ruby_method_shadowing(source) ⇒ Object



1957
1958
1959
1960
1961
# File 'lib/ruby/merge.rb', line 1957

def ruby_method_shadowing(source)
  collect_ruby_declaration_entries(source).flat_map do |entry|
    direct_method_shadowing(entry)
  end
end

#ruby_method_shadowing_diagnostics(source) ⇒ Object



1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
# File 'lib/ruby/merge.rb', line 1963

def ruby_method_shadowing_diagnostics(source)
  ruby_method_shadowing(source).map do |entry|
    {
      severity: 'warning',
      category: 'ruby_method_shadowing',
      path: "#{entry[:owner_path]}/methods/#{entry[:method_signature]}",
      message: "Ruby method #{entry[:method_signature]} is defined #{entry[:shadowed_count] + 1} times in #{entry[:owner_path]}; the last definition shadows earlier definitions."
    }
  end
end

#ruby_named_children(node) ⇒ Object



1445
1446
1447
# File 'lib/ruby/merge.rb', line 1445

def ruby_named_children(node)
  node.children.select { |child| !child.respond_to?(:named?) || child.named? }
end

#ruby_namespace_form_conflicts(template_entries, destination_entries) ⇒ Object



1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
# File 'lib/ruby/merge.rb', line 1897

def ruby_namespace_form_conflicts(template_entries, destination_entries)
  destination_names = destination_entries.to_h do |entry|
    ["#{entry[:kind]}:#{entry[:name]}", true]
  end
  template_entries.flat_map do |entry|
    direct_body_declaration_entries(entry[:text]).filter_map do |nested_entry|
      compact_key = "#{nested_entry[:kind]}:#{entry[:name]}::#{nested_entry[:name]}"
      next unless destination_names[compact_key]

      "#{entry[:name]}::#{nested_entry[:name]}"
    end
  end.uniq
end

#ruby_never_worse_fallback_modeObject



532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/ruby/merge.rb', line 532

def ruby_never_worse_fallback_mode
  {
    mode_id: 'never_worse_than_baseline',
    enabled: true,
    baseline_provider: ruby_fallback_policy_profile.dig(:baseline_provider, :provider_id),
    comparison: {
      conflict_count: 'structured_must_not_exceed_baseline',
      conflict_scope: 'structured_must_not_be_broader_than_baseline',
      data_loss: 'structured_must_not_drop_clean_branch_content'
    },
    fallback_action: 'discard_structured_result_and_use_baseline',
    diagnostics: [
      {
        severity: 'info',
        category: 'never_worse_fallback_mode',
        message: 'Ruby fallback comparison mode treats the host baseline merge as the safety floor.'
      }
    ]
  }
end

#ruby_node_text(source, node) ⇒ Object



1481
1482
1483
# File 'lib/ruby/merge.rb', line 1481

def ruby_node_text(source, node)
  source[node.start_byte...node.end_byte].to_s
end

#ruby_post_merge_validation_profileObject



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/ruby/merge.rb', line 553

def ruby_post_merge_validation_profile
  {
    profile_id: 'ruby-post-merge-validation',
    phase: 'post_merge_validation',
    separate_from: %w[merge_planning rendering],
    checks: %w[
      reparse_merged_output
      resolved_owners_present
      owner_count_not_unexpectedly_lower
      unchanged_significant_lines_preserved
      branch_added_significant_lines_preserved
      output_length_within_policy_bounds
      conflict_marker_shape_compatible
    ],
    failure_outcomes: %w[fallback_to_baseline scoped_conflict hard_diagnostic_failure],
    hooks: {
      ci: 'strict',
      exploratory: 'permissive_when_explicit'
    }
  }
end

#ruby_process_analysis_from_tree(source, root_node) ⇒ Object



1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
# File 'lib/ruby/merge.rb', line 1328

def ruby_process_analysis_from_tree(source, root_node)
  structure = []
  imports = []

  ruby_named_children(root_node).each do |node|
    case node.type
    when 'call'
      import = ruby_import_item_from_node(source, node)
      imports << import if import
    when 'if_modifier'
      import = ruby_import_item_from_modifier_node(source, node)
      imports << import if import
    when 'begin'
      import = ruby_import_item_from_begin_node(source, node)
      imports << import if import
    when 'class', 'module', 'method', 'singleton_method'
      item = ruby_structure_item_from_node(source, node)
      structure << item if item
    end
  end

  TslpProcessAnalysis.new(structure: structure, imports: imports)
end

#ruby_process_declaration_entries(source, process_analysis: nil) ⇒ Object



1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
# File 'lib/ruby/merge.rb', line 1746

def ruby_process_declaration_entries(source, process_analysis: nil)
  items = ruby_top_level_process_structure_items(process_analysis)
  return [] if items.empty?

  lines = normalize_source(source).split("\n")
  items.map do |item|
    start_index = attached_comment_start_index(lines, item.span.start_row)
    finish_index = item.span.end_row
    kind = ruby_process_structure_kind(item)
    name = item.name.to_s
    {
      path: "/declarations/#{name}",
      name: name,
      kind: kind,
      merge_key: "#{kind}:#{name}",
      text: lines[start_index..finish_index].to_a.join("\n").strip,
      start_index: start_index,
      end_index: finish_index
    }
  end
end

#ruby_process_import_entries(source, process_analysis) ⇒ Object



1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
# File 'lib/ruby/merge.rb', line 1557

def ruby_process_import_entries(source, process_analysis)
  lines = normalize_source(source).split("\n")
  Array(process_analysis&.imports).map do |item|
    text = lines[item.span.start_row..item.span.end_row].to_a.join("\n").rstrip
    {
      path: "/requires/#{item.source}",
      text: text,
      start_index: item.span.start_row,
      end_index: item.span.end_row
    }
  end
end

#ruby_process_import_item_at_line(process_analysis, line_number) ⇒ Object



1602
1603
1604
1605
1606
1607
# File 'lib/ruby/merge.rb', line 1602

def ruby_process_import_item_at_line(process_analysis, line_number)
  index = line_number.to_i - 1
  Array(process_analysis&.imports).find do |item|
    item.span.start_row <= index && item.span.end_row >= index
  end
end

#ruby_process_owner_entries(process_analysis) ⇒ Object



1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
# File 'lib/ruby/merge.rb', line 1731

def ruby_process_owner_entries(process_analysis)
  Array(process_analysis&.structure).filter_map do |item|
    kind = ruby_process_owner_kind(item)
    name = item.name.to_s
    next if kind.to_s.empty? || name.empty?

    {
      path: "/declarations/#{name}",
      name: name,
      kind: kind,
      merge_key: "#{kind}:#{name}"
    }
  end
end

#ruby_process_owner_kind(item) ⇒ Object



1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
# File 'lib/ruby/merge.rb', line 1830

def ruby_process_owner_kind(item)
  case item.kind.to_s
  when 'class'
    'class'
  when 'module'
    'module'
  when 'method', 'function'
    'def'
  end
end

#ruby_process_structure_item_at_line(process_analysis, line_number) ⇒ Object



1821
1822
1823
1824
1825
1826
1827
1828
# File 'lib/ruby/merge.rb', line 1821

def ruby_process_structure_item_at_line(process_analysis, line_number)
  Array(process_analysis&.structure).find do |item|
    ruby_process_owner_kind(item) &&
      item.span.start_row == line_number - 1
  end&.then do |item|
    { kind: ruby_process_owner_kind(item), name: item.name.to_s }
  end
end

#ruby_process_structure_kind(item) ⇒ Object



1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
# File 'lib/ruby/merge.rb', line 1841

def ruby_process_structure_kind(item)
  case item.kind.to_s
  when 'class'
    'class'
  when 'module'
    'module'
  when 'method', 'function'
    'def'
  end
end

#ruby_rename_detection(template_source, destination_source) ⇒ Object



916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
# File 'lib/ruby/merge.rb', line 916

def ruby_rename_detection(template_source, destination_source)
  template_methods = ruby_method_identity_entries(template_source)
  destination_methods = ruby_method_identity_entries(destination_source)
  destination_by_parent_and_body = destination_methods.group_by do |entry|
    [entry[:parent_scope], entry[:normalized_body_identity]]
  end
  destination_signature_keys = destination_methods.to_h do |entry|
    [[entry[:parent_scope], entry[:signature]], true]
  end
  matched_destination_addresses = {}

  renames = template_methods.filter_map do |template_entry|
    next if destination_signature_keys[[template_entry[:parent_scope], template_entry[:signature]]]

    destination_entry = destination_by_parent_and_body.fetch(
      [template_entry[:parent_scope], template_entry[:normalized_body_identity]],
      []
    ).find { |entry| entry[:signature] != template_entry[:signature] }
    next unless destination_entry

    matched_destination_addresses[destination_entry[:address]] = true
    {
      from_address: template_entry[:address],
      to_address: destination_entry[:address],
      from_name: template_entry[:signature],
      to_name: destination_entry[:signature],
      parent_scope: template_entry[:parent_scope],
      confidence: 'content_hash',
      signals: %w[body_hash_with_owner_name_normalization parent_scope_similarity],
      clean_rename: true
    }
  end

  {
    policy: ruby_rename_detection_policy_profile,
    renames: renames,
    diagnostics: if renames.empty?
                   []
                 else
                   [
                     {
                       severity: 'info',
                       category: 'ruby_rename_detection',
                       message: 'Ruby rename detection is explicit and reports clean same-parent method renames by normalized body hash.'
                     }
                   ]
                 end,
    unmatched_destination: destination_methods.reject do |entry|
      matched_destination_addresses[entry[:address]]
    end.map { |entry| entry[:address] }
  }
end

#ruby_rename_detection_policy_profileObject



900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
# File 'lib/ruby/merge.rb', line 900

def ruby_rename_detection_policy_profile
  {
    policy_id: 'ruby-source-rename-detection',
    capability: {
      name: 'rename_detection',
      enabled: true,
      default_enabled: false,
      explicit: true
    },
    signals: %w[body_hash_with_owner_name_normalization structural_hash token_similarity parent_scope_similarity
                backend_native_move_metadata],
    clean_rename_confidence: 'content_hash',
    conflict_policy: 'report_rename_plus_edit'
  }
end

#ruby_rename_plus_edit_conflicts(base_source, template_source, destination_source) ⇒ Object



969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'lib/ruby/merge.rb', line 969

def ruby_rename_plus_edit_conflicts(base_source, template_source, destination_source)
  base_methods = ruby_method_identity_entries(base_source)
  template_methods = ruby_method_identity_entries(template_source)
  destination_methods = ruby_method_identity_entries(destination_source)
  template_by_parent = template_methods.group_by { |entry| entry[:parent_scope] }
  destination_by_parent = destination_methods.group_by { |entry| entry[:parent_scope] }

  conflicts = base_methods.filter_map do |base_entry|
    template_candidates = template_by_parent.fetch(base_entry[:parent_scope], []).reject do |entry|
      entry[:signature] == base_entry[:signature]
    end
    destination_candidates = destination_by_parent.fetch(base_entry[:parent_scope], []).reject do |entry|
      entry[:signature] == base_entry[:signature]
    end
    next if template_candidates.empty? || destination_candidates.empty?

    template_candidate = template_candidates.first
    destination_candidate = destination_candidates.first
    next if template_candidate[:signature] == destination_candidate[:signature]

    {
      base_address: base_entry[:address],
      template_address: template_candidate[:address],
      destination_address: destination_candidate[:address],
      parent_scope: base_entry[:parent_scope],
      conflict_kind: 'rename_plus_edit',
      fallback_scope: 'owned_region',
      confidence: 'unresolved',
      diagnostics: [
        'both branches renamed the same Ruby owner differently',
        'method body identity changed on at least one side'
      ]
    }
  end

  {
    policy: ruby_rename_detection_policy_profile,
    conflicts: conflicts,
    diagnostics: if conflicts.empty?
                   []
                 else
                   [
                     {
                       severity: 'warning',
                       category: 'ruby_rename_plus_edit_conflict',
                       message: 'Ruby rename detection found incompatible rename-plus-edit changes.'
                     }
                   ]
                 end
  }
end

#ruby_silent_data_loss_validation_report(template_source:, destination_source:, output:) ⇒ Object



772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# File 'lib/ruby/merge.rb', line 772

def ruby_silent_data_loss_validation_report(template_source:, destination_source:, output:)
  significant_inputs = {
    template: significant_source_lines(template_source),
    destination: significant_source_lines(destination_source)
  }
  output_lines = significant_source_lines(output).to_h { |line| [line, true] }
  missing = significant_inputs.flat_map do |side, lines|
    lines.reject { |line| output_lines[line] }.map do |line|
      {
        side: side.to_s,
        line: line,
        check: 'branch_added_significant_lines_preserved'
      }
    end
  end

  {
    ok: missing.empty?,
    validation_profile: ruby_post_merge_validation_profile.fetch(:profile_id),
    failures: missing,
    outcome: missing.empty? ? 'accepted' : 'hard_diagnostic_failure',
    diagnostics: if missing.empty?
                   []
                 else
                   [
                     {
                       severity: 'error',
                       category: 'silent_data_loss_prevention',
                       message: 'Ruby post-merge validation detected significant input lines missing from output.'
                     }
                   ]
                 end
  }
end

#ruby_source_owner_identity_matches(template_source, destination_source) ⇒ Object



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
# File 'lib/ruby/merge.rb', line 389

def ruby_source_owner_identity_matches(template_source, destination_source)
  template_identities = ruby_source_owner_identity_profile(template_source)
  destination_identities = ruby_source_owner_identity_profile(destination_source)
  destination_groups = destination_identities.group_by { |identity| identity[:structural_identity] }
  template_identities.group_by { |identity| identity[:structural_identity] }
  matched_destination_addresses = {}

  matches = template_identities.filter_map do |template_identity|
    destination_identity = destination_groups.fetch(template_identity[:structural_identity], []).find do |candidate|
      candidate[:occurrence_index] == template_identity[:occurrence_index]
    end
    next unless destination_identity

    matched_destination_addresses[destination_identity[:address]] = true
    {
      template_address: template_identity[:address],
      destination_address: destination_identity[:address],
      structural_identity: template_identity[:structural_identity],
      occurrence_index: template_identity[:occurrence_index],
      confidence: 'structural_ordered'
    }
  end

  matched_template_addresses = matches.to_h { |match| [match[:template_address], true] }
  {
    confidence_profile: ruby_source_owner_match_confidence_profile,
    matches: matches,
    unmatched_template: template_identities.reject do |identity|
      matched_template_addresses[identity[:address]]
    end.map { |identity| identity[:address] },
    unmatched_destination: destination_identities.reject do |identity|
      matched_destination_addresses[identity[:address]]
    end.map { |identity| identity[:address] },
    diagnostics: [
      {
        severity: 'info',
        category: 'source_owner_identity_matching',
        message: 'Ruby source-owner matching reports confidence per match and uses ordered structural pairing for duplicate identities.'
      }
    ]
  }
end

#ruby_source_owner_identity_profile(source) ⇒ Object



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/ruby/merge.rb', line 366

def ruby_source_owner_identity_profile(source)
  identities = collect_ruby_declaration_entries(source).flat_map do |entry|
    declaration_identity = source_owner_identity_entry(
      kind: entry[:kind],
      name: entry[:name],
      parent_scope: '/',
      address: entry[:path],
      content: entry[:text]
    )
    method_identities = direct_body_method_entries(entry[:text]).map do |method_entry|
      source_owner_identity_entry(
        kind: 'method',
        name: method_entry[:signature],
        parent_scope: entry[:path],
        address: "#{entry[:path]}/methods/#{method_entry[:signature]}",
        content: method_entry[:body_text]
      )
    end
    [declaration_identity, *method_identities]
  end
  add_source_owner_occurrence_indexes(identities)
end

#ruby_source_owner_match_confidence_profileObject



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
# File 'lib/ruby/merge.rb', line 465

def ruby_source_owner_match_confidence_profile
  {
    levels: [
      {
        name: 'exact',
        meaning: 'same structural identity, occurrence index, and content identity'
      },
      {
        name: 'structural_ordered',
        meaning: 'same structural identity and occurrence index'
      },
      {
        name: 'content_hash',
        meaning: 'same content-derived identity when structural identity is ambiguous'
      },
      {
        name: 'token_similar',
        meaning: 'similar token content below exact content identity'
      },
      {
        name: 'unresolved',
        meaning: 'identity is ambiguous and must not be auto-matched'
      }
    ]
  }
end

#ruby_source_regions(source) ⇒ Object



356
357
358
359
360
361
362
363
364
# File 'lib/ruby/merge.rb', line 356

def ruby_source_regions(source)
  lines = normalize_source(source).lines(chomp: true)
  owners = top_level_source_region_owners(lines)

  {
    regions: source_interleaved_regions_for_report(lines: lines, owners: owners),
    trailing_newline: normalize_source(source).end_with?("\n")
  }
end

#ruby_span_for(node) ⇒ Object



1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
# File 'lib/ruby/merge.rb', line 1449

def ruby_span_for(node)
  start_point = node.start_point
  end_point = node.end_point
  TslpSpan.new(
    start_row: start_point.fetch(:row),
    start_col: start_point.fetch(:column),
    end_row: end_point.fetch(:row),
    end_col: end_point.fetch(:column)
  )
end

#ruby_structure_item_from_node(source, node) ⇒ Object



1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
# File 'lib/ruby/merge.rb', line 1400

def ruby_structure_item_from_node(source, node)
  kind = case node.type
         when 'class'
           'class'
         when 'module'
           'module'
         when 'method', 'singleton_method'
           'method'
         end
  return unless kind

  name_node = ruby_declaration_name_node(node)
  return unless name_node

  TslpStructureItem.new(kind: kind, name: ruby_node_text(source, name_node), span: ruby_span_for(node))
end

#ruby_top_level_process_structure_items(process_analysis) ⇒ Object



1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
# File 'lib/ruby/merge.rb', line 1806

def ruby_top_level_process_structure_items(process_analysis)
  items = Array(process_analysis&.structure).select do |item|
    ruby_process_structure_kind(item) && !item.name.to_s.empty?
  end
  items.reject do |item|
    items.any? do |candidate|
      next false if candidate.equal?(item)

      candidate.span.start_row <= item.span.start_row &&
        candidate.span.end_row >= item.span.end_row &&
        (candidate.span.start_row < item.span.start_row || candidate.span.end_row > item.span.end_row)
    end
  end.sort_by { |item| [item.span.start_row, item.span.start_col] }
end

#ruby_top_level_section(text, entries) ⇒ Object



1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
# File 'lib/ruby/merge.rb', line 1768

def ruby_top_level_section(text, entries)
  positioned_entries = entries.select do |entry|
    entry[:start_index].is_a?(Integer) && entry[:end_index].is_a?(Integer)
  end
  return { text: text } if positioned_entries.empty?

  {
    text: text,
    start_index: positioned_entries.map { |entry| entry[:start_index] }.min,
    end_index: positioned_entries.map { |entry| entry[:end_index] }.max
  }
end

#ruby_top_level_section_separator(lines, previous, current) ⇒ Object



1796
1797
1798
1799
1800
1801
1802
1803
1804
# File 'lib/ruby/merge.rb', line 1796

def ruby_top_level_section_separator(lines, previous, current)
  return "\n\n" unless previous[:end_index].is_a?(Integer) && current[:start_index].is_a?(Integer)
  return "\n\n" unless current[:start_index] > previous[:end_index]

  gap = lines[(previous[:end_index] + 1)...current[:start_index]].to_a
  return "\n\n" if gap.empty?

  "\n#{gap.join("\n")}\n"
end

#ruby_tslp_claimed_line_indexes(lines, process_analysis) ⇒ Object



1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
# File 'lib/ruby/merge.rb', line 1545

def ruby_tslp_claimed_line_indexes(lines, process_analysis)
  claimed = Set.new
  ruby_top_level_process_structure_items(process_analysis).each do |item|
    start_index = attached_comment_start_index(lines, item.span.start_row)
    (start_index..item.span.end_row).each { |line_index| claimed.add(line_index) }
  end
  Array(process_analysis&.imports).each do |item|
    (item.span.start_row..item.span.end_row).each { |line_index| claimed.add(line_index) }
  end
  claimed
end


1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
# File 'lib/ruby/merge.rb', line 1615

def ruby_tslp_file_footer_text(source, process_analysis)
  lines = normalize_source(source).split("\n")
  claimed = ruby_tslp_claimed_line_indexes(lines, process_analysis)
  footer_indexes = []
  (lines.length - 1).downto(0) do |index|
    break if claimed.include?(index)
    break unless lines[index].strip.empty? || comment_line?(lines[index])

    footer_indexes.unshift(index)
  end
  lines.values_at(*footer_indexes).join("\n").strip
end

#ruby_tslp_file_preamble_text(source, process_analysis) ⇒ Object



1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
# File 'lib/ruby/merge.rb', line 1628

def ruby_tslp_file_preamble_text(source, process_analysis)
  lines = normalize_source(source).split("\n")
  claimed = ruby_tslp_claimed_line_indexes(lines, process_analysis)
  preamble_indexes = []
  lines.each_index do |index|
    break if claimed.include?(index)
    break unless lines[index].strip.empty? || comment_line?(lines[index])

    preamble_indexes << index
  end
  lines.values_at(*preamble_indexes).join("\n").strip
end

#ruby_tslp_merge_context(analysis, role:) ⇒ Object



1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/ruby/merge.rb', line 1512

def ruby_tslp_merge_context(analysis, role:)
  source = analysis.fetch(:source)
  process_analysis = analysis[:tree_haver_process_analysis]
  unsupported_lines = ruby_tslp_unsupported_top_level_lines(source, process_analysis)
  unless unsupported_lines.empty?
    return unsupported_feature_result(
      "ruby-merge can only merge TSLP-record-backed top-level Ruby declarations and imports; #{role} has unsupported top-level content on line(s) #{unsupported_lines.join(', ')}. Use prism-merge for native Ruby merging, or report missing Ruby process records to tree-sitter-language-pack."
    )
  end

  {
    ok: true,
    source: source,
    preamble: ruby_tslp_file_preamble_text(source, process_analysis),
    requires: ruby_process_import_entries(source, process_analysis),
    declarations: collect_ruby_declaration_entries(source, process_analysis: process_analysis),
    footer: ruby_tslp_file_footer_text(source, process_analysis)
  }
end

#ruby_tslp_unsupported_top_level_lines(source, process_analysis) ⇒ Object



1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
# File 'lib/ruby/merge.rb', line 1532

def ruby_tslp_unsupported_top_level_lines(source, process_analysis)
  lines = normalize_source(source).split("\n", -1)
  claimed = ruby_tslp_claimed_line_indexes(lines, process_analysis)
  lines.each_index.filter_map do |index|
    next if claimed.include?(index)

    line = lines[index]
    next if line.strip.empty? || comment_line?(line)

    index + 1
  end
end

#ruby_vcs_tool_integration_profileObject



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
# File 'lib/ruby/merge.rb', line 702

def ruby_vcs_tool_integration_profile
  {
    profile_id: 'ruby-vcs-tool-integration',
    hosts: {
      git_merge_driver: {
        contract: 'git_merge_driver',
        placeholders: %w[%O %A %B %P],
        output_target: '%A',
        standard_marker_modes: %w[diff3 zdiff3 merge],
        marker_size: 'host_provided'
      },
      jujutsu_merge_tool: {
        contract: 'jj_merge_tool',
        roles: %w[base left right output path],
        output_target: 'output',
        standard_marker_modes: %w[diff3 merge],
        marker_size: 'host_provided'
      }
    },
    enhanced_markers: {
      optional: true,
      requires_host_tolerance: true,
      default: 'standard_markers'
    },
    audit_artifact: {
      enabled: true,
      formats: %w[json],
      fields: %w[host operation path fallback_reason validation_warnings conflict_kind timeout_ms]
    },
    resource_budget: {
      timeout_ms: 5000,
      timeout_outcome: 'fallback_or_driver_error',
      cannot_hang_vcs_operation: true
    },
    diagnostics: %w[
      structured_merge_skipped
      fallback_activated
      driver_invocation_error
      tool_invocation_error
      timeout_or_resource_budget
    ]
  }
end

#ruby_vcs_tool_invocation_report(host:, event:, path:, timeout_ms: 5000) ⇒ Object



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/ruby/merge.rb', line 746

def ruby_vcs_tool_invocation_report(host:, event:, path:, timeout_ms: 5000)
  severity = event.to_s.end_with?('error') ? 'error' : 'warning'

  {
    host: host,
    event: event,
    path: path,
    integration_profile: ruby_vcs_tool_integration_profile.fetch(:profile_id),
    marker_mode: 'standard_markers',
    marker_size: 'host_provided',
    audit_artifact: {
      format: 'json',
      required: true
    },
    timeout_ms: timeout_ms,
    resource_budget_enforced: true,
    diagnostics: [
      {
        severity: severity,
        category: event,
        message: "Ruby #{host} integration reported #{event} for #{path}."
      }
    ]
  }
end

#significant_source_lines(source) ⇒ Object



1501
1502
1503
1504
1505
# File 'lib/ruby/merge.rb', line 1501

def significant_source_lines(source)
  normalize_source(source).lines.map(&:strip).reject do |line|
    line.empty? || line.start_with?('#') || line == 'end'
  end
end

#source_owner_identity_entry(kind:, name:, parent_scope:, address:, content:) ⇒ Object



1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
# File 'lib/ruby/merge.rb', line 1911

def source_owner_identity_entry(kind:, name:, parent_scope:, address:, content:)
  normalized_kind = kind.to_s
  normalized_name = name.to_s
  {
    owner_kind: normalized_kind,
    owner_name: normalized_name,
    parent_scope: parent_scope,
    address: address,
    structural_identity: "#{parent_scope}:#{normalized_kind}:#{normalized_name}",
    content_identity: "sha256:#{Digest::SHA256.hexdigest(content.to_s)}",
    identity_components: %w[owner_kind owner_name parent_scope content_identity]
  }
end

#stable_owner_signatures(owner_identities) ⇒ Object



1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
# File 'lib/ruby/merge.rb', line 1489

def stable_owner_signatures(owner_identities)
  owner_identities.map do |identity|
    {
      owner_kind: identity.fetch(:owner_kind),
      owner_name: identity.fetch(:owner_name),
      parent_scope: identity.fetch(:parent_scope),
      structural_identity: identity.fetch(:structural_identity),
      occurrence_index: identity.fetch(:occurrence_index)
    }
  end
end