Class: SwarmMemory::Core::FrontmatterParser

Inherits:
Object
  • Object
show all
Defined in:
lib/swarm_memory/core/frontmatter_parser.rb

Overview

Parser for YAML frontmatter in memory entries

Parses markdown content with YAML frontmatter:

type: concept confidence: high tags: [ruby, testing]

# Title
Content here...

Constant Summary collapse

FRONTMATTER_PATTERN =

Regex pattern to match frontmatter (same as MarkdownParser)

/\A---\s*\n(.*?)\n---\s*\n(.*)\z/m

Class Method Summary collapse

Class Method Details

.extract_metadata(content) ⇒ Hash

Extract specific metadata fields from frontmatter

Examples:

 = FrontmatterParser.(content)
[:confidence] # => "high"
[:type] # => "concept"

Parameters:

  • content (String)

    Full entry content

Returns:

  • (Hash)

    Extracted metadata fields



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/swarm_memory/core/frontmatter_parser.rb', line 60

def (content)
  parsed = parse(content)
  fm = parsed[:frontmatter]

  {
    confidence: fm[:confidence]&.to_s&.downcase, # "high", "medium", "low"
    type: fm[:type]&.to_s&.downcase, # "concept", "fact", "skill", "experience"
    tags: Array(fm[:tags] || []),
    last_verified: parse_date(fm[:last_verified]),
    related: Array(fm[:related] || []),
    domain: fm[:domain]&.to_s,
    source: fm[:source]&.to_s,
  }
end

.parse(content) ⇒ Hash

Parse content and extract frontmatter

Examples:

parsed = FrontmatterParser.parse("---\ntype: fact\n---\nContent")
parsed[:frontmatter] # => { type: "fact" }
parsed[:body] # => "Content"

Parameters:

  • content (String)

    Full entry content

Returns:

  • (Hash)

    { frontmatter: Hash, body: String, error: nil|String }



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/swarm_memory/core/frontmatter_parser.rb', line 30

def parse(content)
  return { frontmatter: {}, body: content, error: nil } if content.nil? || content.empty?

  if content =~ FRONTMATTER_PATTERN
    frontmatter_yaml = Regexp.last_match(1)
    body = Regexp.last_match(2)

    begin
      frontmatter = YAML.safe_load(frontmatter_yaml, permitted_classes: [Symbol, Date, Time], aliases: true)
      frontmatter = symbolize_keys(frontmatter) if frontmatter.is_a?(Hash)
      { frontmatter: frontmatter || {}, body: body, error: nil }
    rescue StandardError => e
      # If YAML parsing fails, treat as body without frontmatter
      { frontmatter: {}, body: content, error: e.message }
    end
  else
    # No frontmatter
    { frontmatter: {}, body: content, error: nil }
  end
end