Class: ContextSpook::Generator::Context

Inherits:
Object
  • Object
show all
Includes:
TOON, Utils, VerbosePuts, Term::ANSIColor, Tins::DSLAccessor, Tins::Scope
Defined in:
lib/context_spook/generator.rb

Overview

The Context class represents and manages project context data, providing structured storage for file contents, command outputs, variables, and metadata that can be serialized to JSON for AI assistance.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

#estimate_tokens, estimate_tokens, #format_size, format_size, #format_tokens, format_tokens

Methods included from TOON

#to_toon, #to_toon_stream, #toon_size

Methods included from VerbosePuts

#verbose_puts

Constructor Details

#initialize(generator:, &block) ⇒ Context

The initialize method sets up the object by evaluating the provided block in the object's context.

Parameters:

  • block (Proc) —

    a block of code to be evaluated within the object's context If no block is given, the method does nothing.



141
142
143
144
145
146
# File 'lib/context_spook/generator.rb', line 141

def initialize(generator:, &block)
  @generator = generator
  block and instance_eval(&block)
  meta(format: generator.format)
  meta(manifest: true) if generator.manifest
end

Instance Attribute Details

#generator ⇒ ContextSpook::Generator (readonly)

The generator method returns the generator object associated with this context.

Returns:



153
154
155
# File 'lib/context_spook/generator.rb', line 153

def generator
  @generator
end

Instance Method Details

#as_json(*ignored) ⇒ Hash

The as_json method converts the context's files, commands, and metadata into a hash representation.

Parameters:

  • ignored (Array) —

    ignored arguments

Returns:

  • (Hash) —

    a hash containing the files, commands, and metadata



365
366
367
368
369
370
371
372
# File 'lib/context_spook/generator.rb', line 365

def as_json(*ignored)
  {
    files:,
    commands:,
    metadata:,
    variables:
  }
end

#command(shell_command, tags: nil) ⇒ Hash

The command method executes a shell command and stores its result.

This method runs a given shell command and records the output, exit code, working directory, and optional tags in the commands hash.

with the command

and metadata

Parameters:

  • shell_command (String) —

    the shell command to execute

  • tags (Array<String>, nil) (defaults to: nil) —

    optional array of tags to associate

Returns:

  • (Hash) —

    the stored command result including output, exit code,



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/context_spook/generator.rb', line 325

def command(shell_command, tags: nil)
  output = `#{shell_command}`
  exit_code = $?&.exitstatus.to_i
  if exit_code != 0
    verbose_puts color(208) {
      "Executing #{shell_command.inspect} resulted in exit code #{exit_code}."
    }
  end
  output_size   = output.bytesize
  output_tokens = estimate_tokens(output_size)
  commands[shell_command] = {
    namespace:         scope_top,
    output:,
    size:              output_size,
    tokens:            output_tokens,
    exit_code:,
    working_directory: Dir.pwd,
    tags:              (Array(tags) if tags),
  }.compact
  verbose_puts "Executed #{shell_command.inspect} with output "\
    "(%s, %s) for context." %
    [ format_size(output_size), format_tokens(output_tokens) ]
  nil
end

#file(filename, tags: nil) ⇒ Hash

The file method associates a file with the current scope and stores its content.

It reads the specified file and creates an entry in the files hash with the file's content, along with its namespace and optional tags. In manifest mode, only metadata fields are stored.

Parameters:

  • filename (String) —

    the path to the file to be read and stored

  • tags (Array<String>, nil) (defaults to: nil) —

    optional array of tags to associate with the file

Returns:

  • (Hash) —

    the created file entry with content, namespace, and tags



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
# File 'lib/context_spook/generator.rb', line 270

def file(filename, tags: nil)
  size   = File.size(filename)
  tokens = estimate_tokens(size)
  if manifest
    files[filename] = {
      namespace:     scope_top,
      size:          ,
      tokens:        ,
      content_types: MIME::Types.type_for(filename)
                       .map(&:content_type).full?,
      tags:          (Array(tags) if tags),
    }.compact
  else
    content        = File.read(filename)
    content_lines  = content.lines
    numbered_lines = content_lines.each_with_index.map {
      { linenumber: _2 + 1, line: _1.chomp }
    }
    files[filename] = {
      namespace:     scope_top,
      content:       numbered_lines,
      size:          ,
      tokens:        ,
      lines:         content_lines.size,
      content_types: MIME::Types.type_for(filename)
                       .map(&:content_type).full?,
      tags:          (Array(tags) if tags),
    }.compact
  end
  verbose_puts "Read #{filename.inspect} (%s, %s) for context." %
    [ format_size(size), format_tokens(tokens) ]
  nil
rescue Errno::ENOENT => e
  verbose_puts color(208) { "Reading #{filename.inspect} caused #{e.class}: #{e}" }
end

#json(filename) ⇒ Object?

The json method reads and parses a JSON file, returning the parsed data structure.

This method attempts to load a JSON file from the specified path and returns the resulting Ruby data structure. It provides verbose output about the file size when successfully reading the file. In case of file not found errors, it outputs a colored warning message to standard error and returns nil.

Parameters:

  • filename (String) —

    the path to the JSON file to be read and parsed

Returns:

  • (Object, nil) —

    the parsed JSON data structure or nil if the file cannot be read



221
222
223
224
225
226
227
228
# File 'lib/context_spook/generator.rb', line 221

def json(filename)
  file_size = format_size(File.size(filename))
  verbose_puts "Read #{filename.inspect} as JSON (%s) for context." % file_size
  JSON.load_file(filename)
rescue Errno::ENOENT, JSON::ParserError => e
  verbose_puts color(208) { "Reading #{filename.inspect} as JSON caused #{e.class}: #{e}" }
  nil
end

#meta(**m) ⇒ Object

The meta method assigns metadata key-value pairs to the metadata hash.

Parameters:

  • m (Hash) —

    a hash of metadata key-value pairs to be added



201
202
203
204
205
206
# File 'lib/context_spook/generator.rb', line 201

def meta(**m)
  m.each do |name, value|
    [name.to_sym] = value
  end
  nil
end

#namespace(name) {|block| ... } ⇒ Object

The namespace method creates a scoped block with a given name.

Parameters:

  • name (Object) —

    the name to scope the block with

Yields:

  • (block) —

    executes the block within the created scope



164
165
166
167
168
169
170
# File 'lib/context_spook/generator.rb', line 164

def namespace(name, &block)
  name = name.to_sym
  scope_block(name) do
    instance_eval(&block)
  end
  nil
end

#size ⇒ Integer

The size method calculates and returns the byte size of the JSON representation of the context.

This method determines the size in bytes of the JSON-serialized version of the context object, which is useful for understanding the total data payload being sent to an AI assistant.

context

Returns:

  • (Integer) —

    the size in bytes of the JSON representation of the



383
384
385
# File 'lib/context_spook/generator.rb', line 383

def size
  to_json.bytesize
end

#variable(**v) ⇒ Object

The variable method assigns key-value pairs to the variables hash.

values

Parameters:

  • v (Hash) —

    a hash containing variable names as keys and their



184
185
186
187
188
189
# File 'lib/context_spook/generator.rb', line 184

def variable(**v)
  v.each do |name, value|
    variables[name.to_sym] = value
  end
  nil
end

#yaml(filename) ⇒ Object?

The yaml method reads and parses a YAML file, returning the resulting data structure.

This method attempts to load a YAML file from the specified path and returns the resulting Ruby data structure. It provides verbose output about the file size when successfully reading the file. In case of file not found errors or YAML syntax errors, it outputs a colored warning message to standard error and returns nil.

Parameters:

  • filename (String) —

    the path to the YAML file to be read and parsed

Returns:

  • (Object, nil) —

    the parsed YAML data structure or nil if the file cannot be read



243
244
245
246
247
248
249
250
# File 'lib/context_spook/generator.rb', line 243

def yaml(filename)
  file_size = format_size(File.size(filename))
  verbose_puts "Read #{filename.inspect} as YAML (%s) for context." % file_size
  YAML.load_file(filename)
rescue Errno::ENOENT, Psych::SyntaxError => e
  verbose_puts color(208) { "Reading #{filename.inspect} as YAML caused #{e.class}: #{e}" }
  nil
end