Semantic code search with multiple modes: semantic (embedding similarity for conceptual queries), fulltext (FTS5 keyword matching for exact identifiers), and hybrid (combined - best of both). JSON output for AI tools.

GitHub stars
6

Install

/plugin install ogrep@ogrep-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add gplv2/ogrep-marketplace.

Contents

Discovered from source

Skills 1

Mandatory: Use the Search Agent

YOU MUST dispatch the ogrep-search agent for any semantic code search.

Announce: "Dispatching ogrep search agent to find [topic]."

Then use the Agent tool with subagent_type: "ogrep-search":

Agent tool:
  description: "Search codebase for [topic]"
  prompt: "Search for [specific query]. Focus on [what you're looking for - e.g., implementation details, architecture, data flow, error handling]."
  subagent_type: "ogrep-search"

The agent will:

  1. Call ogrep_query(summarize=true) for a cheap file-level overview
  2. Narrow to the most relevant files
  3. Expand specific chunks for evidence
  4. Return synthesized findings with file:line references

Saves context vs. running ogrep commands directly in your conversation.

When to Use

Use ogrep when:

  • "Where is error handling done?"
  • "How does caching work here?"
  • "What validates user input?"
  • Exploring unfamiliar code
  • User asks a conceptual question about the codebase
  • You'd need to guess multiple terms for grep

Use grep/Glob instead when:

  • You know the exact class/function name (class ErrorHandler)
  • Looking for specific imports or string literals
  • Simple identifier searches

Rule of thumb: If you'd need to guess multiple terms for grep, dispatch the ogrep agent.

Direct MCP Access (Simple Queries)

For simple, quick lookups you CAN call MCP tools directly without dispatching the agent:

ogrep_query(query="where is auth?")
ogrep_status()

This is appropriate for quick checks. For deeper exploration, always dispatch the agent.

Direct CLI Access (Discouraged)

You CAN run ogrep commands directly via Bash, but DON'T — MCP tools are faster (persistent process, warm models) and return structured data. Always prefer MCP tools or the agent.

Exception: ogrep index . for first-time indexing can be run directly if the agent reports no index exists, or use ogrep_index() via MCP.

Commands 9

ogrep chunk

Retrieve chunks by reference (path:index) or raw ID, with optional neighboring chunks for context.

Usage

ogrep chunk "path/to/file.py:N"     # By chunk reference (N is 0-based chunk index)
ogrep chunk 42                       # By raw chunk ID

# With context
ogrep chunk "auth.py:2" --before 1   # + 1 chunk before
ogrep chunk "auth.py:2" --after 1    # + 1 chunk after
ogrep chunk "auth.py:2" --context 1  # + 1 before AND after

Options

FlagAliasDefaultDescription
--before N-B0Include N chunks before the requested chunk
--after N-A0Include N chunks after the requested chunk
--context N-C0Include N chunks before AND after (shorthand for -B N -A N)
--json-yesOutput as JSON (default for AI/machine use)
--no-json--Output as human-readable text instead of JSON

Output Format

Returns JSON with the requested chunk and any context:

{
  "requested": {
    "chunk_ref": "src/auth.py:2",
    "chunk_id": 42,
    "chunk_index": 2,
    "path": "/home/user/repo/src/auth.py",
    "relative_path": "src/auth.py",
    "start_line": 61,
    "end_line": 120,
    "language": "python",
    "text": "def authenticate_user(...):\n    ..."
  },
  "before": [
    {
      "chunk_ref": "src/auth.py:1",
      "chunk_id": 41,
      "start_line": 1,
      "end_line": 60,
      "text": "import hashlib\n..."
    }
  ],
  "after": []
}

Common Patterns

Expand Context After Query

# Query found something interesting
ogrep query "database connection"
# Result: chunk_ref: "db.py:3"

# Get context above (imports, setup)
ogrep chunk "db.py:3" --before 1

Trace Code Flow

# See what comes after a function definition
ogrep chunk "handler.py:2" --after 2

Full Section Context

# Get surrounding context
ogrep chunk "auth.py:4" --context 1

Advanced Flags

FlagPurpose
--db PATHExplicit SQLite DB path (overrides scope options)
--profile NAMENamed profile for multiple indexes per repo
--global-cacheUse ~/.cache/ogrep/<repo_hash>/index.sqlite
--repo-root PATHExplicit repository root

Notes

  • The chunk index in chunk_ref (e.g., "file.py:2") is 0-based, not a line number
  • The chunk_ref comes from query results - use it directly
  • If chunk not found, verify the ref from query results or run ogrep status

Clean up the index by removing entries for files that have been deleted and pruning deleted git branches.

Commands

# Clean stale entries (JSON output is default)
ogrep clean

# Clean and compact database
ogrep clean --vacuum

# Clean with human-readable output
ogrep clean --no-json

Flags

FlagDescription
--vacuumCompact the SQLite database after cleaning
--no-jsonOutput as human-readable text instead of JSON (default is JSON)

Branch Pruning

The clean command automatically detects and removes entries for git branches that no longer exist:

  • Queries indexed branches from the database
  • Compares against current git branches
  • Removes file entries for deleted branches
  • Shared embeddings (chunks) are preserved if used by other branches

This is especially useful after merging and deleting feature branches.

JSON Output

{
  "status": "success",
  "removed_count": 3,
  "removed_paths": ["/path/to/deleted1.py", "/path/to/deleted2.py"],
  "pruned_branches": ["feature/old-auth"],
  "pruned_files": 15,
  "vacuumed": true
}

ogrep device

Detect GPU/CPU capabilities for cross-encoder reranking. Useful for understanding performance expectations and troubleshooting.

Usage

# Check hardware (JSON output is default)
ogrep device

# Human-readable output
ogrep device --no-json

Options

FlagDefaultDescription
--jsonyesOutput as JSON (default for AI/machine use)
--no-json-Output as human-readable text

JSON Output

{
  "device": "cuda",
  "device_name": "NVIDIA GeForce RTX 3080",
  "cuda_available": true,
  "mps_available": false,
  "recommendation": "GPU acceleration available. Reranking will be fast."
}

Or on CPU-only:

{
  "device": "cpu",
  "device_name": null,
  "cuda_available": false,
  "mps_available": false,
  "recommendation": "No GPU detected. Reranking will work but be slower. Consider --rerank-top 20 for faster results."
}

Hardware Performance

HardwareReranking SpeedNotes
NVIDIA GPU (CUDA)~10x fasterRequires CUDA 12.x drivers
Apple Silicon (MPS)~3-5x fasterAutomatic on macOS 12.3+
CPU onlyBaselineWorks but slower (2-5 seconds per query)

When to Use

  • Before using --rerank - understand what performance to expect
  • Troubleshooting slow queries - check if GPU is being detected
  • Setting up a new machine - verify CUDA/MPS is working

Notes

  • This command loads PyTorch to detect GPU capabilities
  • If no GPU is detected, reranking still works (just slower)
  • Use --rerank-top 20 on CPU for faster results
  • ogrep gracefully falls back to CPU if GPU detection fails

Display comprehensive database diagnostics including table sizes, indexes, SQLite info, FTS5 stats, and integrity checks.

Commands

# Full diagnostic output (JSON is default)
ogrep health

# With human-readable output
ogrep health --no-json

Repair Options

FlagDescription
--vacuumReclaim space and defragment database
--rebuild-ftsDrop and rebuild FTS5 full-text index
--integrityRun full integrity check (slow on large DBs)
--fullAll repairs: vacuum + rebuild-fts + integrity
--no-jsonOutput as human-readable text instead of JSON (default is JSON)

JSON Output

{
  "database": "/path/to/.ogrep/index.sqlite",
  "tables": {
    "chunks": {"rows": 217, "size_bytes": 1782579},
    "files": {"rows": 42, "size_bytes": 8192}
  },
  "branch_info": {
    "current": "main",
    "branches": {"main": 35, "feature/auth": 7}
  },
  "dedup_stats": {
    "total_chunks": 217,
    "unique_hashes": 200,
    "duplicates": 17,
    "savings_percent": 7.8
  },
  "fts5": {"rows": 217, "tokens_estimate": 54073},
  "sqlite_info": {"version": "3.45.0", "page_size": 4096},
  "integrity": "ok",
  "operations": {"vacuum": true, "rebuild_fts": false}
}

Branch info fields:

  • current: Current git branch name
  • branches: Map of all indexed branches to their file counts

Run indexing with ogrep. If no path is provided, index the current directory.

Commands

# Index current directory (JSON output is default)
ogrep index ${1:-.}

# Preview files before indexing (recommended for new repos)
ogrep index ${1:-.} --list

# Index without MIME detection (faster)
ogrep index ${1:-.} --no-detect

# Index with human-readable output
ogrep index ${1:-.} --no-json

Flags

FlagDescription
--list, -lPreview files with detection results (dry run)
--no-detectDisable MIME type detection (faster, null-byte only)
--no-jsonOutput as human-readable text instead of JSON (default is JSON)
--no-astDisable AST chunking (use line-based instead)
-m MODELEmbedding model: voyage-code-3 (best), small (OpenAI), nomic (local)
-e PATTERNAdd exclude patterns
-i PATTERNInclude patterns (override excludes)

JSON Output

JSON is the default output format:

{
  "status": "success",
  "path": "/path/to/repo",
  "files_indexed": 42,
  "files_skipped": 5,
  "chunks_total": 217,
  "chunks_reused": 150,
  "chunks_embedded": 67,
  "tokens_saved_estimate": 15000,
  "model": "text-embedding-3-small",
  "dimensions": 1536
}

Notes

  • AST chunking is default when tree-sitter is available (pip install "ogrep[ast]")
  • Use --list first to see what will be indexed
  • Create .ogrepignore for permanent exclusions
  • Binary files are auto-detected and excluded
  • YAML files (*.yaml, *.yml) are now indexed by default

See CLAUDE.md for embedding provider recommendations.

If ogrep is not installed, run: pip install ogrep

Run:

  • ogrep query "$ARGUMENTS" --top 15 --refresh

Flags explained:

  • --refresh ensures results reflect current code by checking for changed files and reindexing them before querying
  • JSON output is the default (use --no-json for human-readable text)
  • --mode MODE (optional) selects search mode: semantic, fulltext, or hybrid (default)
  • --branch BRANCH (optional) query a specific branch instead of current branch
  • --summarize (optional) return file-level overview instead of full chunks (~85% token savings)
  • --glob PATTERN (optional) filter results to matching files (e.g., --glob "*.py")
  • --exclude PATTERN (optional) exclude matching files (e.g., --exclude "tests/*")
  • --rerank (optional) apply cross-encoder reranking. Only use with local embeddings (nomic); skip with Voyage/OpenAI.
  • --rerank-model MODEL (optional) reranker: flashrank (default), voyage, minilm

Search modes:

  • semantic: Embedding similarity only (conceptual questions)
  • fulltext: FTS5 keyword matching (exact identifiers)
  • hybrid: Combined scoring (default, best of both)

Cross-branch queries:

# Query current branch (default)
ogrep query "authentication"

# Query a specific branch
ogrep query "authentication" --branch main

JSON output structure:

{
  "query": "...",
  "results": [
    {
      "rank": 1,
      "chunk_ref": "src/file.py:2",
      "path": "/absolute/path/to/file.py",
      "relative_path": "src/file.py",
      "start_line": 10,
      "end_line": 70,
      "score": 0.42,
      "confidence": {
        "level": "high",
        "signal": "top_result_in_typical_range"
      },
      "language": "python",
      "text": "full chunk content..."
    }
  ],
  "stats": {
    "total_results": 15,
    "search_mode": "hybrid",
    "confidence_summary": {"high": 3, "medium": 5, "low": 2}
  }
}

Confidence signals: top_result_strong_match (trust it), top_result_in_typical_range (good), top_result_weak_absolute (verify), close_to_top (alternative), score_drop_from_top (lower priority)

Using chunk_ref: After finding a result, use ogrep chunk "src/file.py:2" to get more context.

If it fails because the DB doesn't exist:

  1. Run /ogrep:index
  2. Retry the query.

Completely rebuild the index by removing it and reindexing from scratch.

Commands

# Rebuild index for current directory (JSON output is default)
ogrep reindex ${1:-.}

# Rebuild with human-readable output
ogrep reindex ${1:-.} --no-json

Flags

FlagDescription
--no-jsonOutput as human-readable text instead of JSON (default is JSON)
--no-astDisable AST chunking, use line-based instead (AST is default when tree-sitter is available)
-m MODELEmbedding model: voyage-code-3 (best), small (OpenAI), nomic (local)
--chunk-lines NLines per chunk (default: 60)
--overlap NOverlap lines between chunks (default: 10)

JSON Output

{
  "status": "success",
  "path": "/path/to/repo",
  "files_indexed": 42,
  "files_skipped": 5,
  "chunks_total": 217,
  "chunks_embedded": 217,
  "model": "text-embedding-3-small",
  "dimensions": 1536
}

This is equivalent to ogrep reset --force && ogrep index.

Remove the semantic search index.

Commands

# Reset current branch only (requires -f in non-interactive mode)
ogrep reset -f

# Reset entire database (all branches)
ogrep reset -f --all

# Reset with human-readable output
ogrep reset -f --no-json

Flags

FlagDescription
-f, --forceSkip confirmation (required in non-interactive mode)
--allDelete entire database (all branches). Without this, only current branch is cleared
--no-jsonOutput as human-readable text instead of JSON (default is JSON)

Branch-Aware Behavior

By default, ogrep reset -f clears only the current git branch from the index:

  • Files indexed on the current branch are removed
  • Files indexed on other branches are preserved
  • Shared embeddings (chunks) remain available for other branches

Use --all to delete the entire database including all branches.

JSON Output

{
  "status": "success",
  "database": "/path/to/.ogrep/index.sqlite",
  "removed": true,
  "branch": "main",
  "files_removed": 42,
  "size_bytes": 1048576,
  "size_human": "1.0 MB"
}

The -f flag is required in non-interactive mode (like Claude Code).

Display information about the current index including file count, chunk count, model used, and database size.

Commands

# Show status (JSON is default)
ogrep status

# Show status as human-readable text
ogrep status --no-json

JSON Output

JSON is the default output format:

{
  "database": "/path/to/.ogrep/index.sqlite",
  "status": "indexed",
  "indexed": true,
  "branch": "main",
  "branch_files": 42,
  "files": 42,
  "branches": {"main": 42},
  "chunks": 217,
  "model": "text-embedding-3-small",
  "dimensions": 1536,
  "size_bytes": 1048576,
  "size_human": "1.0 MB"
}

Branch fields:

  • branch: Current git branch name (or "default" if not in a git repo)
  • branch_files: Number of files indexed on the current branch
  • branches: Map of all indexed branches to their file counts

If no index exists:

{
  "database": "/path/to/.ogrep/index.sqlite",
  "status": "not_indexed",
  "indexed": false,
  "message": "No index found at ..."
}

Agents 1

ogrep Semantic Search Agent

You are a semantic code search agent. Your job is to find relevant code using ogrep's MCP tools and return a concise synthesis to the parent conversation.

Critical Rules

ALWAYS start with summarize=true to get a cheap file-level overview before drilling into chunks.

Use MCP tools directly — they return structured data, no JSON parsing needed.

Search Workflow

Follow this workflow for every search request:

Step 1: Summarize (mandatory first step)

Get a file-level overview — this is cheap and narrows the search space:

ogrep_query(query="your search terms", summarize=true)

If the request targets specific file types or paths, filter early:

ogrep_query(query="your search terms", summarize=true, glob="*.py")
ogrep_query(query="your search terms", summarize=true, exclude="tests/*")

Step 2: Narrow

Based on the summary, target the most relevant files:

ogrep_query(query="refined terms", glob="src/relevant/path/*")

Focus on results where confidence.level is high or medium.

SignalAction
top_result_strong_matchTrust it, use directly
top_result_in_typical_rangeUse confidently
top_result_weak_absoluteMay need verification
close_to_topConsider as alternative
score_drop_from_topLower priority

Step 3: Drill

Expand context around the best hits using chunk_ref from the results:

ogrep_chunk(ref="path/to/file.py:N", context=1)

If chunk retrieval fails, fall back to the Read tool with offset and limit parameters.

Step 4: Refine if needed

If results are insufficient:

  • Try alternate query terms (synonyms, related concepts)
  • Broaden: remove filters, use more general terms
  • Narrow: add identifiers, restrict to specific paths
  • Try different search modes: mode="semantic", mode="fulltext", mode="hybrid"

Query Strategy

Translate the search request into 1-3 queries:

  • Include intent ("authentication", "retry logic", "billing state")
  • Include known identifiers if any (function names, class names, error strings)
  • If the user gave a concrete identifier, include it as one query verbatim

Search Modes

ModeBest forParameter
hybrid (default)Most questions(none needed)
semanticPure conceptualmode="semantic"
fulltextKnown terms/identifiersmode="fulltext"

Reranking

Do NOT use rerank=true by default. With high-quality embeddings (Voyage, OpenAI), reranking often degrades results. Only use rerank=true if you're getting poor results with local/nomic embeddings.

Output Format

Return your findings in this structure:

Findings

[Synthesize what you found in 200-800 words. Be specific — include function names, class names, line numbers. Adapt structure to the query:

  • Direct answer? 1-2 paragraphs with code references.
  • Architecture question? Describe the flow with file references.
  • Multiple relevant areas? List each with file:line references.]

Key Locations

[List the most relevant code locations:]

  • path/to/file.py:120-185 — description of what's here
  • path/to/other.py:45-60 — description of what's here

Search Details

  • Queries used: [list queries run]
  • Files examined: [count]
  • Confidence: [high/medium/low based on result signals]

What NOT to do

  • Do NOT paste entire files or large code blocks — synthesize instead
  • Do NOT skip the summarize=true step — it saves tokens and improves targeting
  • Do NOT return raw tool results to the parent — synthesize into findings
  • Do NOT use rerank=true unless results are poor with local embeddings

MCP servers 1

Sponsors

Details

Marketplace
gplv2/ogrep-marketplace
Source
plugins/ogrep
Category
Community