Class: RuboCop::Cop::Prompt::CriticalFirstLast

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/prompt/critical_first_last.rb

Overview

Checks that labeled sections (### Text) appear at the beginning or end of files, not in the middle.

This cop identifies code in classes, modules, or methods with “prompt” in their names and ensures that any labeled sections (lines starting with ###) are positioned at the beginning or end of the content, not in the middle sections.

Examples:

# bad
system: "# System Instructions\nYou are an AI assistant.\n### Important Note\nPlease follow these guidelines.\nMore instructions here.\n"

# good
system: "### Important Note\nPlease follow these guidelines.\n# System Instructions\nYou are an AI assistant.\n"

Constant Summary collapse

MSG =
"Labeled sections (### text) should appear at the beginning or end, not in the middle"

Instance Method Summary collapse

Instance Method Details

#on_dstr(node) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/prompt/critical_first_last.rb', line 57

def on_dstr(node)
  return unless in_prompt_context?(node)
  return if node.each_ancestor(:pair).any? { |ancestor| system_pair?(ancestor) }

  content = extract_content(node)
  return if content.nil? || content.strip.empty?

  check_labeled_sections(node, content)
end

#on_pair(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/prompt/critical_first_last.rb', line 35

def on_pair(node)
  return unless system_pair?(node)
  return unless in_prompt_context?(node)

  value_node = node.children[1]
  content = extract_content(value_node)

  return if content.nil? || content.strip.empty?

  check_labeled_sections(node, content)
end

#on_str(node) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/prompt/critical_first_last.rb', line 47

def on_str(node)
  return unless in_prompt_context?(node)
  return if node.each_ancestor(:pair).any? { |ancestor| system_pair?(ancestor) }

  content = node.children[0]
  return if content.nil? || content.strip.empty?

  check_labeled_sections(node, content)
end