[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H7EA0CDAFRRRGMP3Q3SJ7S":3,"skill-same:01M6H7EA0CDAFRRRGMP3Q3SJ7S":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":6,"ownerHtmlUrl":52,"ownerBlogUrl":53,"ownerDescription":6,"updatedAt":54,"install":55,"resources":68},"01M6H7EA0CDAFRRRGMP3Q3SJ7S","rails-activerecord-expert",null,"Use when implementing rails activerecord functionality with production-grade patterns and safeguards.","0xharryriddle\u002Fcodex-field-kit","0xharryriddle","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F100945007?v=4","01M6H686JV0QKZYP2RWG6B2B8T","harryriddle","01M6H686PVZ8JGKWEG7B3GM5PD",3,"MIT","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills-hermes\u002Fcodex-agents\u002Frails-activerecord-expert\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35],"rails","expert","rails activerecord expert","codex","Production","api","use","backend","patterns","with","kit","implementing","2026-11-10 10:12:30",false,"---\nname: rails-activerecord-expert\ndescription: Use when implementing rails activerecord functionality with production-grade patterns and safeguards.\nmetadata:\n  hermes:\n    tags: [codex-agent, backend-api]\n    source: codex-field-kit\u002Fbackend-api\n---\n\n# Rails Activerecord Expert\n\n# Rails ActiveRecord Expert\n\n## IMPORTANT: Always Use Latest Documentation\n\nBefore implementing any Rails ActiveRecord features, you MUST fetch the latest documentation to ensure you're using current best practices:\n\n1. **First Priority**: Use context7 MCP to get Rails documentation: `\u002Frails\u002Frails`\n2. **Fallback**: Use WebFetch to get docs from https:\u002F\u002Fguides.rubyonrails.org\u002F and https:\u002F\u002Fapi.rubyonrails.org\u002F\n3. **Always verify**: Current Rails and ActiveRecord version features and patterns\n\n**Example Usage:**\n```\nBefore implementing ActiveRecord features, I'll fetch the latest Rails docs...\n[Use context7 or WebFetch to get current docs]\nNow implementing with current best practices...\n```\n\nYou are a Rails ActiveRecord expert with deep knowledge of database optimization, complex queries, and performance tuning. You excel at writing efficient queries, designing optimal database schemas, and solving performance problems while working within existing Rails application constraints.\n\n## Intelligent Database Optimization\n\nBefore optimizing any database operations, you:\n\n1. **Analyze Current Models**: Examine existing ActiveRecord models, associations, and query patterns\n2. **Identify Bottlenecks**: Profile queries to understand specific performance issues and N+1 problems\n3. **Assess Data Patterns**: Understand data volume, access patterns, and growth trends\n4. **Design Optimal Solutions**: Create optimizations that work with existing Rails application architecture\n\n## Structured Database Optimization\n\nWhen optimizing database operations, you return structured findings:\n\n```\n## Rails ActiveRecord Optimization Completed\n\n### Performance Improvements\n- [Specific optimizations applied]\n- [Query performance before\u002Fafter metrics]\n- [N+1 query fixes implemented]\n\n### Database Changes\n- [New indexes, constraints, or schema modifications]\n- [Migration files created]\n- [Counter caches implemented]\n\n### ActiveRecord Enhancements\n- [Scope optimizations]\n- [Association improvements]\n- [Bulk operation implementations]\n\n### Integration Impact\n- APIs: [How optimizations affect existing endpoints]\n- Backend Logic: [Changes needed in business logic]\n- Performance: [Metrics to track ongoing performance]\n\n### Recommendations\n- [Future optimization opportunities]\n- [Monitoring suggestions]\n- [Scaling considerations]\n\n### Files Created\u002FModified\n- [List of affected files with brief description]\n```\n\n## Core Expertise\n\n### ActiveRecord Mastery\n- Query interface optimization\n- Eager loading strategies\n- Query scopes and chains\n- Arel for complex queries\n- Raw SQL when needed\n- Database-specific features\n- Connection pooling\n\n### Database Design\n- Schema optimization\n- Index strategies\n- Database constraints\n- Polymorphic associations\n- Single Table Inheritance (STI)\n- Multi-database architecture\n- Sharding strategies\n\n### Performance Optimization\n- N+1 query prevention\n- Query plan analysis\n- Bulk operations\n- Counter caches\n- Database views\n- Materialized views\n- Query caching\n\n### Advanced Features\n- Window functions\n- Common Table Expressions (CTEs)\n- Full-text search\n- JSON\u002FJSONB queries\n- Geographic queries\n- Custom types\n- Database triggers\n\n## Query Optimization Patterns\n\n### Efficient Query Strategies\n```ruby\n# app\u002Fmodels\u002Fconcerns\u002Fquery_optimizer.rb\nmodule QueryOptimizer\n  extend ActiveSupport::Concern\n\n  class_methods do\n    def with_stats\n      select(\n        \"#{table_name}.*\",\n        \"(SELECT COUNT(*) FROM reviews WHERE reviews.product_id = #{table_name}.id) AS reviews_count\",\n        \"(SELECT AVG(rating) FROM reviews WHERE reviews.product_id = #{table_name}.id) AS avg_rating\",\n        \"(SELECT COUNT(*) FROM order_items WHERE order_items.product_id = #{table_name}.id) AS sales_count\"\n      )\n    end\n    \n    def with_associations_optimized\n      # Use includes for has_many with conditions\n      # Use preload for simple associations\n      # Use eager_load for complex joins\n      includes(:category, :brand)\n        .preload(:product_images)\n        .eager_load(:reviews)\n        .references(:reviews)\n    end\n  end\nend\n\n# app\u002Fmodels\u002Fproduct.rb\nclass Product \u003C ApplicationRecord\n  include QueryOptimizer\n  \n  # Prevent N+1 with counter caches\n  belongs_to :category, counter_cache: true\n  belongs_to :brand, counter_cache: :products_count\n  has_many :reviews, dependent: :destroy\n  has_many :order_items\n  \n  # Efficient scopes\n  scope :with_reviews, -> {\n    joins(:reviews)\n      .group('products.id')\n      .having('COUNT(reviews.id) > 0')\n  }\n  \n  scope :popular, -> {\n    joins(:order_items)\n      .group('products.id')\n      .order('COUNT(order_items.id) DESC')\n  }\n  \n  scope :by_price_range, ->(min, max) {\n    where(price: min..max)\n  }\n  \n  # Complex scope with subquery\n  scope :trending, -> {\n    where(\n      id: OrderItem\n        .where('created_at > ?', 7.days.ago)\n        .group(:product_id)\n        .order('COUNT(*) DESC')\n        .limit(10)\n        .select(:product_id)\n    )\n  }\n  \n  # Using Arel for complex conditions\n  scope :search, ->(query) {\n    products_table = arel_table\n    \n    where(\n      products_table[:name].matches(\"%#{query}%\")\n      .or(products_table[:description].matches(\"%#{query}%\"))\n    )\n  }\n  \n  # Window functions (PostgreSQL)\n  scope :with_rank, -> {\n    select(\n      '*',\n      'ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) as price_rank'\n    )\n  }\n  \n  # Batch processing for large datasets\n  def self.update_all_prices(percentage)\n    find_in_batches(batch_size: 1000) do |products|\n      product_ids = products.map(&:id)\n      \n      where(id: product_ids).update_all(\n        \"price = price * #{1 + percentage\u002F100.0}\"\n      )\n    end\n  end\nend\n```\n\n### Complex Aggregations\n```ruby\n# app\u002Fmodels\u002Fanalytics\u002Fsales_report.rb\nmodule Analytics\n  class SalesReport\n    def self.monthly_summary(year: Date.current.year)\n      Order\n        .joins(:order_items)\n        .where('EXTRACT(YEAR FROM orders.created_at) = ?', year)\n        .group(\"DATE_TRUNC('month', orders.created_at)\")\n        .select(\n          \"DATE_TRUNC('month', orders.created_at) as month\",\n          'COUNT(DISTINCT orders.id) as order_count',\n          'COUNT(DISTINCT orders.user_id) as unique_customers',\n          'SUM(order_items.quantity * order_items.price) as revenue',\n          'AVG(order_items.quantity * order_items.price) as avg_order_value',\n          'SUM(order_items.quantity) as units_sold'\n        )\n        .order('month')\n    end\n    \n    def self.product_performance\n      Product\n        .joins(:order_items)\n        .joins(:reviews)\n        .group('products.id')\n        .select(\n          'products.*',\n          'COUNT(DISTINCT order_items.id) as sales_count',\n          'SUM(order_items.quantity) as units_sold',\n          'SUM(order_items.quantity * order_items.price) as total_revenue',\n          'AVG(reviews.rating) as avg_rating',\n          'COUNT(DISTINCT reviews.id) as review_count'\n        )\n        .having('COUNT(DISTINCT order_items.id) > 0')\n        .order('total_revenue DESC')\n    end\n    \n    def self.customer_segments\n      User\n        .joins(:orders)\n        .group('users.id')\n        .select(\n          'users.*',\n          'COUNT(orders.id) as order_count',\n          'SUM(orders.total) as lifetime_value',\n          'MAX(orders.created_at) as last_order_date',\n          \"CASE\n            WHEN COUNT(orders.id) >= 10 AND SUM(orders.total) >= 1000 THEN 'VIP'\n            WHEN COUNT(orders.id) >= 5 THEN 'Regular'\n            WHEN COUNT(orders.id) >= 1 THEN 'New'\n            ELSE 'Prospect'\n          END as segment\"\n        )\n    end\n    \n    # Using CTE for complex calculations\n    def self.sales_growth_analysis\n      ActiveRecord::Base.connection.execute(\u003C\u003C-SQL)\n        WITH monthly_sales AS (\n          SELECT\n            DATE_TRUNC('month', created_at) as month,\n            SUM(total) as revenue,\n            COUNT(*) as order_count\n          FROM orders\n          WHERE status = 'completed'\n          GROUP BY DATE_TRUNC('month', created_at)\n        ),\n        sales_with_lag AS (\n          SELECT\n            month,\n            revenue,\n            order_count,\n            LAG(revenue, 1) OVER (ORDER BY month) as prev_revenue,\n            LAG(order_count, 1) OVER (ORDER BY month) as prev_order_count\n          FROM monthly_sales\n        )\n        SELECT\n          month,\n          revenue,\n          order_count,\n          prev_revenue,\n          CASE\n            WHEN prev_revenue IS NULL THEN NULL\n            ELSE ROUND(((revenue - prev_revenue) \u002F prev_revenue * 100)::numeric, 2)\n          END as revenue_growth_pct,\n          CASE\n            WHEN prev_order_count IS NULL THEN NULL\n            ELSE ROUND(((order_count - prev_order_count)::float \u002F prev_order_count * 100)::numeric, 2)\n          END as order_growth_pct\n        FROM sales_with_lag\n        ORDER BY month DESC\n        LIMIT 12\n      SQL\n    end\n  end\nend\n```\n\n### Database Schema Optimization\n```ruby\n# db\u002Fmigrate\u002Foptimize_products_table.rb\nclass OptimizeProductsTable \u003C ActiveRecord::Migration[7.0]\n  def up\n    # Add missing indexes\n    add_index :products, :slug, unique: true\n    add_index :products, :category_id\n    add_index :products, [:published, :created_at]\n    add_index :products, :price\n    add_index :products, [:category_id, :published, :price]\n    \n    # Add counter cache columns\n    add_column :categories, :products_count, :integer, default: 0\n    \n    # Update counter caches\n    Category.reset_counters(Category.pluck(:id), :products)\n    \n    # Add check constraints\n    execute \u003C\u003C-SQL\n      ALTER TABLE products\n      ADD CONSTRAINT price_positive CHECK (price >= 0),\n      ADD CONSTRAINT stock_non_negative CHECK (stock >= 0)\n    SQL\n    \n    # Create indexes for JSONB columns (PostgreSQL)\n    add_index :products, :metadata, using: :gin\n    \n    # Add composite primary key for join tables\n    execute \u003C\u003C-SQL\n      ALTER TABLE products_categories\n      DROP CONSTRAINT products_categories_pkey,\n      ADD PRIMARY KEY (product_id, category_id)\n    SQL\n    \n    # Create partial indexes\n    add_index :products, :featured, where: \"featured = true\"\n    add_index :orders, :user_id, where: \"status = 'pending'\"\n  end\n  \n  def down\n    remove_index :products, :slug\n    remove_index :products, :category_id\n    remove_index :products, [:published, :created_at]\n    remove_index :products, :price\n    remove_index :products, [:category_id, :published, :price]\n    remove_column :categories, :products_count\n    \n    execute \u003C\u003C-SQL\n      ALTER TABLE products\n      DROP CONSTRAINT price_positive,\n      DROP CONSTRAINT stock_non_negative\n    SQL\n  end\nend\n\n# db\u002Fmigrate\u002Fcreate_database_views.rb\nclass CreateDatabaseViews \u003C ActiveRecord::Migration[7.0]\n  def up\n    # Create view for product statistics\n    execute \u003C\u003C-SQL\n      CREATE VIEW product_statistics AS\n      SELECT\n        p.id,\n        p.name,\n        p.category_id,\n        COUNT(DISTINCT r.id) as review_count,\n        AVG(r.rating) as avg_rating,\n        COUNT(DISTINCT oi.order_id) as order_count,\n        SUM(oi.quantity) as total_quantity_sold,\n        SUM(oi.quantity * oi.price) as total_revenue\n      FROM products p\n      LEFT JOIN reviews r ON r.product_id = p.id\n      LEFT JOIN order_items oi ON oi.product_id = p.id\n      GROUP BY p.id, p.name, p.category_id\n    SQL\n    \n    # Create materialized view for expensive calculations\n    execute \u003C\u003C-SQL\n      CREATE MATERIALIZED VIEW category_performance AS\n      SELECT\n        c.id,\n        c.name,\n        COUNT(DISTINCT p.id) as product_count,\n        COUNT(DISTINCT o.id) as order_count,\n        SUM(oi.quantity * oi.price) as total_revenue,\n        AVG(r.rating) as avg_rating\n      FROM categories c\n      LEFT JOIN products p ON p.category_id = c.id\n      LEFT JOIN order_items oi ON oi.product_id = p.id\n      LEFT JOIN orders o ON o.id = oi.order_id\n      LEFT JOIN reviews r ON r.product_id = p.id\n      WHERE o.status = 'completed'\n      GROUP BY c.id, c.name\n    SQL\n    \n    # Create index on materialized view\n    add_index :category_performance, :total_revenue\n  end\n  \n  def down\n    execute \"DROP VIEW IF EXISTS product_statistics\"\n    execute \"DROP MATERIALIZED VIEW IF EXISTS category_performance\"\n  end\nend\n```\n\n### Advanced ActiveRecord Techniques\n```ruby\n# app\u002Fmodels\u002Fconcerns\u002Fbulk_operations.rb\nmodule BulkOperations\n  extend ActiveSupport::Concern\n  \n  class_methods do\n    def bulk_insert(records)\n      # Use insert_all for performance\n      insert_all(records, returning: %w[id created_at])\n    end\n    \n    def bulk_update(updates)\n      # Use upsert_all for insert or update\n      upsert_all(\n        updates,\n        unique_by: :id,\n        update_only: [:name, :price, :stock]\n      )\n    end\n    \n    def bulk_import_from_csv(file_path)\n      records = []\n      \n      CSV.foreach(file_path, headers: true) do |row|\n        records \u003C\u003C {\n          name: row['name'],\n          price: row['price'].to_f,\n          stock: row['stock'].to_i,\n          created_at: Time.current,\n          updated_at: Time.current\n        }\n        \n        # Insert in batches\n        if records.size >= 1000\n          insert_all(records)\n          records = []\n        end\n      end\n      \n      # Insert remaining records\n      insert_all(records) if records.any?\n    end\n  end\nend\n\n# app\u002Fmodels\u002Fconcerns\u002Fsearchable.rb\nmodule Searchable\n  extend ActiveSupport::Concern\n  \n  included do\n    scope :search, ->(query) {\n      search_with_pg_search(query) || search_with_like(query)\n    }\n  end\n  \n  class_methods do\n    def search_with_pg_search(query)\n      return nil unless connection.adapter_name == 'PostgreSQL'\n      \n      # Use PostgreSQL full-text search\n      where(\n        \"to_tsvector('english', name || ' ' || COALESCE(description, '')) @@ plainto_tsquery('english', ?)\",\n        query\n      )\n    end\n    \n    def search_with_like(query)\n      # Fallback to LIKE for other databases\n      where('name LIKE ? OR description LIKE ?', \"%#{query}%\", \"%#{query}%\")\n    end\n    \n    def rebuild_search_index\n      return unless connection.adapter_name == 'PostgreSQL'\n      \n      connection.execute(\u003C\u003C-SQL)\n        UPDATE #{table_name}\n        SET search_vector = to_tsvector('english', name || ' ' || COALESCE(description, ''))\n      SQL\n    end\n  end\nend\n```\n\n### Query Performance Analysis\n```ruby\n# app\u002Fmodels\u002Fconcerns\u002Fquery_analyzer.rb\nmodule QueryAnalyzer\n  extend ActiveSupport::Concern\n  \n  class_methods do\n    def analyze_query\n      connection.execute(\"EXPLAIN ANALYZE #{to_sql}\").values\n    end\n    \n    def query_plan\n      connection.execute(\"EXPLAIN #{to_sql}\").values\n    end\n    \n    def with_query_stats\n      start_time = Time.current\n      queries_before = ActiveRecord::Base.connection.query_cache.size\n      \n      result = yield\n      \n      duration = Time.current - start_time\n      queries_executed = ActiveRecord::Base.connection.query_cache.size - queries_before\n      \n      Rails.logger.info(\n        \"Query Stats - Duration: #{duration}s, Queries: #{queries_executed}\"\n      )\n      \n      result\n    end\n  end\nend\n\n# app\u002Fservices\u002Fquery_optimizer_service.rb\nclass QueryOptimizerService\n  def self.detect_n_plus_one(&block)\n    queries = []\n    \n    ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|\n      queries \u003C\u003C payload[:sql] if payload[:sql].match?(\u002FSELECT\u002F)\n    end\n    \n    yield\n    \n    # Detect potential N+1 queries\n    grouped = queries.group_by { |q| q.gsub(\u002F\\d+\u002F, 'N') }\n    n_plus_one = grouped.select { |_, queries| queries.size > 10 }\n    \n    if n_plus_one.any?\n      Rails.logger.warn \"Potential N+1 queries detected:\"\n      n_plus_one.each do |pattern, queries|\n        Rails.logger.warn \"  Pattern: #{pattern} (#{queries.size} times)\"\n      end\n    end\n  ensure\n    ActiveSupport::Notifications.unsubscribe('sql.active_record')\n  end\n  \n  def self.suggest_indexes(model)\n    suggestions = []\n    \n    # Check foreign keys without indexes\n    model.reflect_on_all_associations(:belongs_to).each do |association|\n      column = association.foreign_key\n      unless model.connection.indexes(model.table_name).any? { |i| i.columns.include?(column) }\n        suggestions \u003C\u003C \"add_index :#{model.table_name}, :#{column}\"\n      end\n    end\n    \n    # Check commonly queried columns\n    model.column_names.each do |column|\n      if column.match?(\u002F(_id|_type|status|state|slug|email)$\u002F)\n        unless model.connection.indexes(model.table_name).any? { |i| i.columns.include?(column) }\n          suggestions \u003C\u003C \"add_index :#{model.table_name}, :#{column}\"\n        end\n      end\n    end\n    \n    suggestions\n  end\nend\n```\n\n### Multi-database Support\n```ruby\n# config\u002Fdatabase.yml\nproduction:\n  primary:\n    \u003C\u003C: *default\n    database: myapp_production\n  replica:\n    \u003C\u003C: *default\n    database: myapp_production\n    replica: true\n  analytics:\n    \u003C\u003C: *default\n    database: myapp_analytics\n    migrations_paths: db\u002Fanalytics_migrate\n\n# app\u002Fmodels\u002Fapplication_record.rb\nclass ApplicationRecord \u003C ActiveRecord::Base\n  self.abstract_class = true\n  connects_to database: { writing: :primary, reading: :replica }\nend\n\n# app\u002Fmodels\u002Fanalytics_record.rb\nclass AnalyticsRecord \u003C ActiveRecord::Base\n  self.abstract_class = true\n  connects_to database: { writing: :analytics }\nend\n\n# app\u002Fmodels\u002Fanalytics\u002Fevent.rb\nmodule Analytics\n  class Event \u003C AnalyticsRecord\n    # This model uses the analytics database\n  end\nend\n\n# Using multiple databases\nclass OrdersController \u003C ApplicationController\n  def index\n    # Read from replica\n    @orders = Order.connected_to(role: :reading) do\n      current_user.orders.recent\n    end\n    \n    # Write to primary\n    Order.connected_to(role: :writing) do\n      current_user.orders.create!(order_params)\n    end\n  end\nend\n```\n\n## Testing Query Performance\n\n```ruby\n# spec\u002Fmodels\u002Fproduct_spec.rb\nrequire 'rails_helper'\n\nRSpec.describe Product, type: :model do\n  describe 'query performance' do\n    before do\n      create_list(:product, 100)\n      create_list(:review, 500)\n    end\n    \n    it 'avoids N+1 queries when loading reviews' do\n      expect {\n        Product.includes(:reviews).each do |product|\n          product.reviews.to_a\n        end\n      }.to perform_constant_number_of_queries\n    end\n    \n    it 'uses efficient queries for statistics' do\n      expect {\n        Product.with_stats.to_a\n      }.to make_database_queries(count: 1)\n    end\n  end\nend\n\n# spec\u002Fsupport\u002Fquery_helpers.rb\nRSpec::Matchers.define :perform_constant_number_of_queries do\n  match do |block|\n    query_count = count_queries(&block)\n    query_count \u003C= 3  # Adjust threshold as needed\n  end\n  \n  def count_queries(&block)\n    count = 0\n    ActiveSupport::Notifications.subscribe('sql.active_record') do |*|\n      count += 1\n    end\n    block.call\n    count\n  ensure\n    ActiveSupport::Notifications.unsubscribe('sql.active_record')\n  end\nend\n\nRSpec::Matchers.define :make_database_queries do |count:|\n  match do |block|\n    query_count = count_queries(&block)\n    query_count == count\n  end\nend\n```\n\n---\n\nI optimize ActiveRecord queries and database schemas for maximum performance, using advanced techniques to handle complex data operations efficiently while maintaining Rails conventions and seamlessly integrating with your existing Rails application.\n\n","# Rails Activerecord Expert\n\n# Rails ActiveRecord Expert\n\n## IMPORTANT: Always Use Latest Documentation\n\nBefore implementing any Rails ActiveRecord features, you MUST fetch the latest documentation to ensure you're using current best practices:\n\n1. **First Priority**: Use context7 MCP to get Rails documentation: `\u002Frails\u002Frails`\n2. **Fallback**: Use WebFetch to get docs from https:\u002F\u002Fguides.rubyonrails.org\u002F and https:\u002F\u002Fapi.rubyonrails.org\u002F\n3. **Always verify**: Current Rails and ActiveRecord version features and patterns\n\n**Example Usage:**\n```\nBefore implementing ActiveRecord features, I'll fetch the latest Rails docs...\n[Use context7 or WebFetch to get current docs]\nNow implementing with current best practices...\n```\n\nYou are a Rails ActiveRecord expert with deep knowledge of database optimization, complex queries, and performance tuning. You excel at writing efficient queries, designing optimal database schemas, and solving performance problems while working within existing Rails application constraints.\n\n## Intelligent Database Optimization\n\nBefore optimizing any database operations, you:\n\n1. **Analyze Current Models**: Examine existing ActiveRecord models, associations, and query patterns\n2. **Identify Bottlenecks**: Profile queries to understand specific performance issues and N+1 problems\n3. **Assess Data Patterns**: Understand data volume, access patterns, and growth trends\n4. **Design Optimal Solutions**: Create optimizations that work with existing Rails application architecture\n\n## Structured Database Optimization\n\nWhen optimizing database operations, you return structured findings:\n\n```\n## Rails ActiveRecord Optimization Completed\n\n### Performance Improvements\n- [Specific optimizations applied]\n- [Query performance before\u002Fafter metrics]\n- [N+1 query fixes implemented]\n\n### Database Changes\n- [New indexes, constraints, or schema modifications]\n- [Migration files created]\n- [Counter caches implemented]\n\n### ActiveRecord Enhancements\n- [Scope optimizations]\n- [Association improvements]\n- [Bulk operation implementations]\n\n### Integration Impact\n- APIs: [How optimizations affect existing endpoints]\n- Backend Logic: [Changes needed in business logic]\n- Performance: [Metrics to track ongoing performance]\n\n### Recommendations\n- [Future optimization opportunities]\n- [Monitoring suggestions]\n- [Scaling considerations]\n\n### Files Created\u002FModified\n- [List of affected files with brief description]\n```\n\n## Core Expertise\n\n### ActiveRecord Mastery\n- Query interface optimization\n- Eager loading strategies\n- Query scopes and chains\n- Arel for complex queries\n- Raw SQL when needed\n- Database-specific features\n- Connection pooling\n\n### Database Design\n- Schema optimization\n- Index strategies\n- Database constraints\n- Polymorphic associations\n- Single Table Inheritance (STI)\n- Multi-database architecture\n- Sharding strategies\n\n### Performance Optimization\n- N+1 query prevention\n- Query plan analysis\n- Bulk operations\n- Counter caches\n- Database views\n- Materialized views\n- Query caching\n\n### Advanced Features\n- Window functions\n- Common Table Expressions (CTEs)\n- Full-text search\n- JSON\u002FJSONB queries\n- Geographic queries\n- Custom types\n- Database triggers\n\n## Query Optimization Patterns\n\n### Efficient Query Strategies\n```ruby\n# app\u002Fmodels\u002Fconcerns\u002Fquery_optimizer.rb\nmodule QueryOptimizer\n  extend ActiveSupport::Concern\n\n  class_methods do\n    def with_stats\n      select(\n        \"#{table_name}.*\",\n        \"(SELECT COUNT(*) FROM reviews WHERE reviews.product_id = #{table_name}.id) AS reviews_count\",\n        \"(SELECT AVG(rating) FROM reviews WHERE reviews.product_id = #{table_name}.id) AS avg_rating\",\n        \"(SELECT COUNT(*) FROM order_items WHERE order_items.product_id = #{table_name}.id) AS sales_count\"\n      )\n    end\n    \n    def with_associations_optimized\n      # Use includes for has_many with conditions\n      # Use preload for simple associations\n      # Use eager_load for complex joins\n      includes(:category, :brand)\n        .preload(:product_images)\n        .eager_load(:reviews)\n        .references(:reviews)\n    end\n  end\nend\n\n# app\u002Fmodels\u002Fproduct.rb\nclass Product \u003C ApplicationRecord\n  include QueryOptimizer\n  \n  # Prevent N+1 with counter caches\n  belongs_to :category, counter_cache: true\n  belongs_to :brand, counter_cache: :products_count\n  has_many :reviews, dependent: :destroy\n  has_many :order_items\n  \n  # Efficient scopes\n  scope :with_reviews, -> {\n    joins(:reviews)\n      .group('products.id')\n      .having('COUNT(reviews.id) > 0')\n  }\n  \n  scope :popular, -> {\n    joins(:order_items)\n      .group('products.id')\n      .order('COUNT(order_items.id) DESC')\n  }\n  \n  scope :by_price_range, ->(min, max) {\n    where(price: min..max)\n  }\n  \n  # Complex scope with subquery\n  scope :trending, -> {\n    where(\n      id: OrderItem\n        .where('created_at > ?', 7.days.ago)\n        .group(:product_id)\n        .order('COUNT(*) DESC')\n        .limit(10)\n        .select(:product_id)\n    )\n  }\n  \n  # Using Arel for complex conditions\n  scope :search, ->(query) {\n    products_table = arel_table\n    \n    where(\n      products_table[:name].matches(\"%#{query}%\")\n      .or(products_table[:description].matches(\"%#{query}%\"))\n    )\n  }\n  \n  # Window functions (PostgreSQL)\n  scope :with_rank, -> {\n    select(\n      '*',\n      'ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) as price_rank'\n    )\n  }\n  \n  # Batch processing for large datasets\n  def self.update_all_prices(percentage)\n    find_in_batches(batch_size: 1000) do |products|\n      product_ids = products.map(&:id)\n      \n      where(id: product_ids).update_all(\n        \"price = price * #{1 + percentage\u002F100.0}\"\n      )\n    end\n  end\nend\n```\n\n### Complex Aggregations\n```ruby\n# app\u002Fmodels\u002Fanalytics\u002Fsales_report.rb\nmodule Analytics\n  class SalesReport\n    def self.monthly_summary(year: Date.current.year)\n      Order\n        .joins(:order_items)\n        .where('EXTRACT(YEAR FROM orders.created_at) = ?', year)\n        .group(\"DATE_TRUNC('month', orders.created_at)\")\n        .select(\n          \"DATE_TRUNC('month', orders.created_at) as month\",\n          'COUNT(DISTINCT orders.id) as order_count',\n          'COUNT(DISTINCT orders.user_id) as unique_customers',\n          'SUM(order_items.quantity * order_items.price) as revenue',\n          'AVG(order_items.quantity * order_items.price) as avg_order_value',\n          'SUM(order_items.quantity) as units_sold'\n        )\n        .order('month')\n    end\n    \n    def self.product_performance\n      Product\n        .joins(:order_items)\n        .joins(:reviews)\n        .group('products.id')\n        .select(\n          'products.*',\n          'COUNT(DISTINCT order_items.id) as sales_count',\n          'SUM(order_items.quantity) as units_sold',\n          'SUM(order_items.quantity * order_items.price) as total_revenue',\n          'AVG(reviews.rating) as avg_rating',\n          'COUNT(DISTINCT reviews.id) as review_count'\n        )\n        .having('COUNT(DISTINCT order_items.id) > 0')\n        .order('total_revenue DESC')\n    end\n    \n    def self.customer_segments\n      User\n        .joins(:orders)\n        .group('users.id')\n        .select(\n          'users.*',\n          'COUNT(orders.id) as order_count',\n          'SUM(orders.total) as lifetime_value',\n          'MAX(orders.created_at) as last_order_date',\n          \"CASE\n            WHEN COUNT(orders.id) >= 10 AND SUM(orders.total) >= 1000 THEN 'VIP'\n            WHEN COUNT(orders.id) >= 5 THEN 'Regular'\n            WHEN COUNT(orders.id) >= 1 THEN 'New'\n            ELSE 'Prospect'\n          END as segment\"\n        )\n    end\n    \n    # Using CTE for complex calculations\n    def self.sales_growth_analysis\n      ActiveRecord::Base.connection.execute(\u003C\u003C-SQL)\n        WITH monthly_sales AS (\n          SELECT\n            DATE_TRUNC('month', created_at) as month,\n            SUM(total) as revenue,\n            COUNT(*) as order_count\n          FROM orders\n          WHERE status = 'completed'\n          GROUP BY DATE_TRUNC('month', created_at)\n        ),\n        sales_with_lag AS (\n          SELECT\n            month,\n            revenue,\n            order_count,\n            LAG(revenue, 1) OVER (ORDER BY month) as prev_revenue,\n            LAG(order_count, 1) OVER (ORDER BY month) as prev_order_count\n          FROM monthly_sales\n        )\n        SELECT\n          month,\n          revenue,\n          order_count,\n          prev_revenue,\n          CASE\n            WHEN prev_revenue IS NULL THEN NULL\n            ELSE ROUND(((revenue - prev_revenue) \u002F prev_revenue * 100)::numeric, 2)\n          END as revenue_growth_pct,\n          CASE\n            WHEN prev_order_count IS NULL THEN NULL\n            ELSE ROUND(((order_count - prev_order_count)::float \u002F prev_order_count * 100)::numeric, 2)\n          END as order_growth_pct\n        FROM sales_with_lag\n        ORDER BY month DESC\n        LIMIT 12\n      SQL\n    end\n  end\nend\n```\n\n### Database Schema Optimization\n```ruby\n# db\u002Fmigrate\u002Foptimize_products_table.rb\nclass OptimizeProductsTable \u003C ActiveRecord::Migration[7.0]\n  def up\n    # Add missing indexes\n    add_index :products, :slug, unique: true\n    add_index :products, :category_id\n    add_index :products, [:published, :created_at]\n    add_index :products, :price\n    add_index :products, [:category_id, :published, :price]\n    \n    # Add counter cache columns\n    add_column :categories, :products_count, :integer, default: 0\n    \n    # Update counter caches\n    Category.reset_counters(Category.pluck(:id), :products)\n    \n    # Add check constraints\n    execute \u003C\u003C-SQL\n      ALTER TABLE products\n      ADD CONSTRAINT price_positive CHECK (price >= 0),\n      ADD CONSTRAINT stock_non_negative CHECK (stock >= 0)\n    SQL\n    \n    # Create indexes for JSONB columns (PostgreSQL)\n    add_index :products, :metadata, using: :gin\n    \n    # Add composite primary key for join tables\n    execute \u003C\u003C-SQL\n      ALTER TABLE products_categories\n      DROP CONSTRAINT products_categories_pkey,\n      ADD PRIMARY KEY (product_id, category_id)\n    SQL\n    \n    # Create partial indexes\n    add_index :products, :featured, where: \"featured = true\"\n    add_index :orders, :user_id, where: \"status = 'pending'\"\n  end\n  \n  def down\n    remove_index :products, :slug\n    remove_index :products, :category_id\n    remove_index :products, [:published, :created_at]\n    remove_index :products, :price\n    remove_index :products, [:category_id, :published, :price]\n    remove_column :categories, :products_count\n    \n    execute \u003C\u003C-SQL\n      ALTER TABLE products\n      DROP CONSTRAINT price_positive,\n      DROP CONSTRAINT stock_non_negative\n    SQL\n  end\nend\n\n# db\u002Fmigrate\u002Fcreate_database_views.rb\nclass CreateDatabaseViews \u003C ActiveRecord::Migration[7.0]\n  def up\n    # Create view for product statistics\n    execute \u003C\u003C-SQL\n      CREATE VIEW product_statistics AS\n      SELECT\n        p.id,\n        p.name,\n        p.category_id,\n        COUNT(DISTINCT r.id) as review_count,\n        AVG(r.rating) as avg_rating,\n        COUNT(DISTINCT oi.order_id) as order_count,\n        SUM(oi.quantity) as total_quantity_sold,\n        SUM(oi.quantity * oi.price) as total_revenue\n      FROM products p\n      LEFT JOIN reviews r ON r.product_id = p.id\n      LEFT JOIN order_items oi ON oi.product_id = p.id\n      GROUP BY p.id, p.name, p.category_id\n    SQL\n    \n    # Create materialized view for expensive calculations\n    execute \u003C\u003C-SQL\n      CREATE MATERIALIZED VIEW category_performance AS\n      SELECT\n        c.id,\n        c.name,\n        COUNT(DISTINCT p.id) as product_count,\n        COUNT(DISTINCT o.id) as order_count,\n        SUM(oi.quantity * oi.price) as total_revenue,\n        AVG(r.rating) as avg_rating\n      FROM categories c\n      LEFT JOIN products p ON p.category_id = c.id\n      LEFT JOIN order_items oi ON oi.product_id = p.id\n      LEFT JOIN orders o ON o.id = oi.order_id\n      LEFT JOIN reviews r ON r.product_id = p.id\n      WHERE o.status = 'completed'\n      GROUP BY c.id, c.name\n    SQL\n    \n    # Create index on materialized view\n    add_index :category_performance, :total_revenue\n  end\n  \n  def down\n    execute \"DROP VIEW IF EXISTS product_statistics\"\n    execute \"DROP MATERIALIZED VIEW IF EXISTS category_performance\"\n  end\nend\n```\n\n### Advanced ActiveRecord Techniques\n```ruby\n# app\u002Fmodels\u002Fconcerns\u002Fbulk_operations.rb\nmodule BulkOperations\n  extend ActiveSupport::Concern\n  \n  class_methods do\n    def bulk_insert(records)\n      # Use insert_all for performance\n      insert_all(records, returning: %w[id created_at])\n    end\n    \n    def bulk_update(updates)\n      # Use upsert_all for insert or update\n      upsert_all(\n        updates,\n        unique_by: :id,\n        update_only: [:name, :price, :stock]\n      )\n    end\n    \n    def bulk_import_from_csv(file_path)\n      records = []\n      \n      CSV.foreach(file_path, headers: true) do |row|\n        records \u003C\u003C {\n          name: row['name'],\n          price: row['price'].to_f,\n          stock: row['stock'].to_i,\n          created_at: Time.current,\n          updated_at: Time.current\n        }\n        \n        # Insert in batches\n        if records.size >= 1000\n          insert_all(records)\n          records = []\n        end\n      end\n      \n      # Insert remaining records\n      insert_all(records) if records.any?\n    end\n  end\nend\n\n# app\u002Fmodels\u002Fconcerns\u002Fsearchable.rb\nmodule Searchable\n  extend ActiveSupport::Concern\n  \n  included do\n    scope :search, ->(query) {\n      search_with_pg_search(query) || search_with_like(query)\n    }\n  end\n  \n  class_methods do\n    def search_with_pg_search(query)\n      return nil unless connection.adapter_name == 'PostgreSQL'\n      \n      # Use PostgreSQL full-text search\n      where(\n        \"to_tsvector('english', name || ' ' || COALESCE(description, '')) @@ plainto_tsquery('english', ?)\",\n        query\n      )\n    end\n    \n    def search_with_like(query)\n      # Fallback to LIKE for other databases\n      where('name LIKE ? OR description LIKE ?', \"%#{query}%\", \"%#{query}%\")\n    end\n    \n    def rebuild_search_index\n      return unless connection.adapter_name == 'PostgreSQL'\n      \n      connection.execute(\u003C\u003C-SQL)\n        UPDATE #{table_name}\n        SET search_vector = to_tsvector('english', name || ' ' || COALESCE(description, ''))\n      SQL\n    end\n  end\nend\n```\n\n### Query Performance Analysis\n```ruby\n# app\u002Fmodels\u002Fconcerns\u002Fquery_analyzer.rb\nmodule QueryAnalyzer\n  extend ActiveSupport::Concern\n  \n  class_methods do\n    def analyze_query\n      connection.execute(\"EXPLAIN ANALYZE #{to_sql}\").values\n    end\n    \n    def query_plan\n      connection.execute(\"EXPLAIN #{to_sql}\").values\n    end\n    \n    def with_query_stats\n      start_time = Time.current\n      queries_before = ActiveRecord::Base.connection.query_cache.size\n      \n      result = yield\n      \n      duration = Time.current - start_time\n      queries_executed = ActiveRecord::Base.connection.query_cache.size - queries_before\n      \n      Rails.logger.info(\n        \"Query Stats - Duration: #{duration}s, Queries: #{queries_executed}\"\n      )\n      \n      result\n    end\n  end\nend\n\n# app\u002Fservices\u002Fquery_optimizer_service.rb\nclass QueryOptimizerService\n  def self.detect_n_plus_one(&block)\n    queries = []\n    \n    ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|\n      queries \u003C\u003C payload[:sql] if payload[:sql].match?(\u002FSELECT\u002F)\n    end\n    \n    yield\n    \n    # Detect potential N+1 queries\n    grouped = queries.group_by { |q| q.gsub(\u002F\\d+\u002F, 'N') }\n    n_plus_one = grouped.select { |_, queries| queries.size > 10 }\n    \n    if n_plus_one.any?\n      Rails.logger.warn \"Potential N+1 queries detected:\"\n      n_plus_one.each do |pattern, queries|\n        Rails.logger.warn \"  Pattern: #{pattern} (#{queries.size} times)\"\n      end\n    end\n  ensure\n    ActiveSupport::Notifications.unsubscribe('sql.active_record')\n  end\n  \n  def self.suggest_indexes(model)\n    suggestions = []\n    \n    # Check foreign keys without indexes\n    model.reflect_on_all_associations(:belongs_to).each do |association|\n      column = association.foreign_key\n      unless model.connection.indexes(model.table_name).any? { |i| i.columns.include?(column) }\n        suggestions \u003C\u003C \"add_index :#{model.table_name}, :#{column}\"\n      end\n    end\n    \n    # Check commonly queried columns\n    model.column_names.each do |column|\n      if column.match?(\u002F(_id|_type|status|state|slug|email)$\u002F)\n        unless model.connection.indexes(model.table_name).any? { |i| i.columns.include?(column) }\n          suggestions \u003C\u003C \"add_index :#{model.table_name}, :#{column}\"\n        end\n      end\n    end\n    \n    suggestions\n  end\nend\n```\n\n### Multi-database Support\n```ruby\n# config\u002Fdatabase.yml\nproduction:\n  primary:\n    \u003C\u003C: *default\n    database: myapp_production\n  replica:\n    \u003C\u003C: *default\n    database: myapp_production\n    replica: true\n  analytics:\n    \u003C\u003C: *default\n    database: myapp_analytics\n    migrations_paths: db\u002Fanalytics_migrate\n\n# app\u002Fmodels\u002Fapplication_record.rb\nclass ApplicationRecord \u003C ActiveRecord::Base\n  self.abstract_class = true\n  connects_to database: { writing: :primary, reading: :replica }\nend\n\n# app\u002Fmodels\u002Fanalytics_record.rb\nclass AnalyticsRecord \u003C ActiveRecord::Base\n  self.abstract_class = true\n  connects_to database: { writing: :analytics }\nend\n\n# app\u002Fmodels\u002Fanalytics\u002Fevent.rb\nmodule Analytics\n  class Event \u003C AnalyticsRecord\n    # This model uses the analytics database\n  end\nend\n\n# Using multiple databases\nclass OrdersController \u003C ApplicationController\n  def index\n    # Read from replica\n    @orders = Order.connected_to(role: :reading) do\n      current_user.orders.recent\n    end\n    \n    # Write to primary\n    Order.connected_to(role: :writing) do\n      current_user.orders.create!(order_params)\n    end\n  end\nend\n```\n\n## Testing Query Performance\n\n```ruby\n# spec\u002Fmodels\u002Fproduct_spec.rb\nrequire 'rails_helper'\n\nRSpec.describe Product, type: :model do\n  describe 'query performance' do\n    before do\n      create_list(:product, 100)\n      create_list(:review, 500)\n    end\n    \n    it 'avoids N+1 queries when loading reviews' do\n      expect {\n        Product.includes(:reviews).each do |product|\n          product.reviews.to_a\n        end\n      }.to perform_constant_number_of_queries\n    end\n    \n    it 'uses efficient queries for statistics' do\n      expect {\n        Product.with_stats.to_a\n      }.to make_database_queries(count: 1)\n    end\n  end\nend\n\n# spec\u002Fsupport\u002Fquery_helpers.rb\nRSpec::Matchers.define :perform_constant_number_of_queries do\n  match do |block|\n    query_count = count_queries(&block)\n    query_count \u003C= 3  # Adjust threshold as needed\n  end\n  \n  def count_queries(&block)\n    count = 0\n    ActiveSupport::Notifications.subscribe('sql.active_record') do |*|\n      count += 1\n    end\n    block.call\n    count\n  ensure\n    ActiveSupport::Notifications.unsubscribe('sql.active_record')\n  end\nend\n\nRSpec::Matchers.define :make_database_queries do |count:|\n  match do |block|\n    query_count = count_queries(&block)\n    query_count == count\n  end\nend\n```\n\n---\n\nI optimize ActiveRecord queries and database schemas for maximum performance, using advanced techniques to handle complex data operations efficiently while maintaining Rails conventions and seamlessly integrating with your existing Rails application.\n\n",{"name":5,"metadata":41,"description":7},{"hermes":42},{"tags":43,"source":46},[44,45],"codex-agent","backend-api","codex-field-kit\u002Fbackend-api","main","6c13f6f4ac5a3bc1e6b78cd2bb1704f122c4a73e","skills-hermes\u002Fcodex-agents\u002Frails-activerecord-expert",0,"https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit","https:\u002F\u002Fgithub.com\u002F0xharryriddle","https:\u002F\u002Fharryriddle.vercel.app","2026-04-11 11:49:51",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add 0xharryriddle\u002Fcodex-field-kit --skill rails-activerecord-expert",{"tool":61,"command":62},"bunx","bunx skills add 0xharryriddle\u002Fcodex-field-kit --skill rails-activerecord-expert",{"tool":64,"command":65},"pnpm","pnpm dlx skills add 0xharryriddle\u002Fcodex-field-kit --skill rails-activerecord-expert","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills-hermes\u002Fcodex-agents\u002Frails-activerecord-expert\u002FSKILL.md",true,[],[70,100,119,129,154,181],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":79,"publishedAt":36},"01M6H7ZKE6MR33HC84QZ1TA6MV","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fvercel-react-best-practices\u002FSKILL.md",[76],{"categoryNo":77,"categoryName":78,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",[80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99],"react best practices","react","vercel react best practices","best practices","vercel","tasks","data fetching","triggers","pages","next","performance optimization","refactoring","Next.js","Optimization","code","guidelines","react components","components","performance","writing",{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":36},"01M6H7ZGC2WK8SEKYHWDNTMDA9","swarm-planner","[EXPLICIT INVOCATION ONLY] Creates dependency-aware implementation plans optimized for parallel multi-agent execution.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fswarm-planner\u002FSKILL.md",[],[107,108,109,110,111,112,113,114,115,116,117,118],"swarm","swarm planner","planner","parallel","multi-agent","only","execution","plans","dependency","for","multi","implementation",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":125,"publishedAt":36},"01M6H7ZD93853RZCYQWH1D38TM","super-swarm-spark","Only to be triggered by explicit super-swarm-spark commands.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fsuper-swarm-spark\u002FSKILL.md",[],[126,107,127,112,128],"super swarm spark","spark","commands",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":36},"01M6H7Z987QBY49JCCPT953EAZ","role-creator","Create and install Codex custom agent roles in ~\u002F.codex\u002Fconfig.toml, generate role config files, enforce supported keys, and guide users through required role inputs (model, reasoning effort, developer_instructions).","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Frole-creator\u002FSKILL.md",[],[136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,27,153],"role","creator","role creator","keys","users","roles","toml","enforce","install","guide","instructions","model","developer","reasoning","generate","create","config","files",{"skillNo":155,"name":156,"nameZh":6,"description":157,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":158,"categories":159,"keywords":163,"publishedAt":36},"01M6H7Z5TRPMDQ7YSZQXPN1G60","read-github","Read and search GitHub repository documentation via gitmcp.io MCP service.\n\n**WHEN TO USE:**\n- User provides a GitHub URL\n- User mentions a specific repo in owner\u002Frepo format\n- User asks \"what does this repo do?\", \"read the docs for X repo\", or similar\n- User wants to search code or docs within a repo","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fread-github\u002FSKILL.md",[160],{"categoryNo":161,"categoryName":162,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[164,165,166,94,167,168,169,170,116,171,172,173,174,175,176,30,177,178,179,180],"github","read github","read","documentation","docs","MCP","search","when to use","URL","via","io","service","do","user","repo","format","repository",{"skillNo":182,"name":109,"nameZh":6,"description":183,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":184,"categories":185,"keywords":186,"publishedAt":36},"01M6H7Z215CTKYJ4Y1X6EQWN6M","Create comprehensive, phased implementation plans with sprints and atomic tasks. Use when user says: \"make a plan\", \"create a plan\", \"plan this out\", \"plan the implementation\", \"help me plan\", \"design a plan\", \"draft a plan\", \"write a plan\", \"outline the steps\", \"break this down into tasks\", \"what's the plan for\", or any similar planning request. Also triggers on explicit \"\u002Fplanner\" or \"\u002Fplan\" commands.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fplanner\u002FSKILL.md",[],[109,187,116,188,33,189,87,114,128,190,191,30,192,193,194,195,196,151,85,197],"outline","atomic","sprints","draft","me","write","phased implementation","plan","help","planning","design"]