Skip to content

Source Inspection

_source_for returns the source code for any method -- both LLM-generated and file-defined methods.

Instance-Level Inspection

Call _source_for on an instance to retrieve source code:

class MathHelper
  include SelfAgency

  # Multiplies a number by two.
  def double(n)
    n * 2
  end
end

helper = MathHelper.new
helper._("an instance method named 'square' that accepts an integer n and returns n * n")

For LLM-generated methods, _source_for returns the code with the original description as a comment header:

puts helper._source_for(:square)
# >> # an instance method named 'square' that accepts an integer n and returns n * n
# >> def square(n)
# >>   n * n
# >> end

Class-Level Inspection

_source_for is also available as a class method:

puts MathHelper._source_for(:square)
# >> # an instance method named 'square' that accepts an integer n and returns n * n
# >> def square(n)
# >>   n * n
# >> end

Both instance and class level lookups return the same source for LLM-generated methods.

File-Defined Methods

For methods defined in source files (not generated by the LLM), _source_for falls back to the method_source gem. It includes any comments directly above the method definition:

puts helper._source_for(:double)
# >> # Multiplies a number by two.
# >> def double(n)
# >>   n * 2
# >> end

Unknown Methods

If a method doesn't exist or its source is unavailable, _source_for returns nil:

helper._source_for(:nonexistent)  #=> nil

Version History

When a method is regenerated (e.g., with a refined description), SelfAgency tracks each version. Use _source_versions_for at the class level to retrieve the history:

helper._("an instance method named 'square' that accepts n and returns n * n")
helper._("an instance method named 'square' that accepts n, raises ArgumentError if n < 0, and returns n * n")

versions = MathHelper._source_versions_for(:square)
versions.size  #=> 2

versions.each do |v|
  puts "#{v[:at]}#{v[:description]}"
  puts v[:code]
  puts
end

Each version entry is a Hash with keys :code, :description, :instance_id, and :at.

Returns an empty array if no versions exist for the method.

How It Works

_source_for checks two sources in order:

  1. LLM-generated source -- Stored in an internal hash when _() creates the method
  2. File source -- Falls back to method_source gem for methods defined in .rb files

If both lookups fail (method doesn't exist or source file can't be located), nil is returned.