### Install ctxray CLI
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Install the core package or optional features using pip.
```bash
pip install ctxray # core (all features, zero config)
pip install ctxray[chinese] # + Chinese prompt analysis (jieba)
pip install ctxray[mcp] # + MCP server for Claude Code / Continue.dev / Zed
```
--------------------------------
### Install and Run ctxray Commands
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Install the package via pip and execute core diagnostic and analysis commands.
```bash
pip install ctxray
ctxray scan # discover prompts from your AI tools
ctxray wrapped # your AI coding persona + shareable card
ctxray insights # your patterns vs research-optimal
ctxray privacy # what sensitive data you've exposed
```
--------------------------------
### Install ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Install the core package or include optional extras for specific features like Chinese support or MCP server integration.
```bash
# Core installation (all features, zero config)
pip install ctxray
# With Chinese prompt analysis support
pip install ctxray[chinese]
# With MCP server for Claude Code / Continue.dev / Zed integration
pip install ctxray[mcp]
# Development installation with all extras
pip install ctxray[dev]
```
--------------------------------
### Install Ctxray Post-Session Hooks
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Install hooks for automatic scanning after sessions. Options include including a digest summary.
```bash
# Install Claude Code hook
ctxray install-hook
```
```bash
# Include digest summary after each session
ctxray install-hook --with-digest
```
--------------------------------
### Start MCP Server for Integrations
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Starts the MCP (Multi-Chat Protocol) server, enabling integration with tools like Claude Code, Continue.dev, and Zed. Requires `fastmcp` optional dependency.
```bash
reprompt mcp-serve
```
--------------------------------
### Run Demo Report with Sample Data
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Executes a full report using built-in sample data, requiring no existing session history. This is ideal for quickly demonstrating reprompt's capabilities or for testing without setup.
```bash
reprompt demo
```
--------------------------------
### Install OpenAI Embedding Backend
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Installs the OpenAI embedding backend. This option uses OpenAI's API for generating embeddings, requiring an API key and potentially incurring costs. Requires `pip install reprompt-cli[openai]`.
```bash
pip install reprompt-cli[openai]
```
--------------------------------
### Install Local Embedding Backend
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Installs the local embedding backend using `sentence-transformers`. This allows reprompt to generate embeddings without relying on external APIs. Requires `pip install reprompt-cli[local]`.
```bash
pip install reprompt-cli[local]
```
--------------------------------
### Get prompting insights with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Use `ctxray insights` to analyze your prompting patterns against research-backed benchmarks. It provides a score, specificity, position, and repetition metrics, along with actionable effectiveness tips. Insights can be filtered by source and output as JSON.
```bash
# Get personal prompting insights
ctxray insights
# Output:
# Your Patterns vs Research-Optimal
# ─────────────────────────────────
# Avg Score: 62/100 (benchmark: 70)
# Specificity: 0.45 (benchmark: 0.6)
# Position: 0.72 (optimal: instruction at start)
# Repetition: 0.12 (Google: 0.3 can add +76%)
#
# Effectiveness:
# Your "debug" prompts score 15% lower than "implement"
# → Try adding error messages to debug prompts
#
# Cross-Session Repetition:
# 23% of prompts recur across sessions (8 topics)
# → Consider saving as templates
# Filter by source
ctxray insights --source claude-code --json
```
--------------------------------
### Install Reprompt Git Hook
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Installs the reprompt Git hook, which can automate prompt scanning or other actions upon commit. The command will prompt for configuration if it hasn't been set up yet.
```bash
reprompt install-hook
```
--------------------------------
### Score Prompt Quality
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Generates an instant quality score for a given prompt, including a breakdown of specificity, position bias, repetition, and perplexity. No specific setup is required beyond having the reprompt CLI installed.
```bash
reprompt score "prompt"
```
--------------------------------
### Install Reprompt CLI with MCP Support
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Installs the reprompt CLI with optional MCP (Multi-Chat Protocol) support for enhanced integration capabilities. This includes the necessary dependencies for the MCP server and tools.
```bash
pip install reprompt-cli[mcp]
```
--------------------------------
### Lint Prompts with GitHub Action Integration
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Integrates prompt quality linting into GitHub Actions workflows. This command helps maintain high prompt quality automatically within CI/CD pipelines. Requires `reprompt` to be installed in the GitHub Actions environment.
```bash
reprompt lint
```
--------------------------------
### View session quality overview with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Use `ctxray sessions` to get an overview of recent session quality, including composite scores and frustration signals. You can list recent sessions, perform a deep-dive into a specific session, or filter by source and output as JSON.
```bash
# List recent sessions with quality scores
ctxray sessions --last 10
# Output:
# Session Quality Overview
# ────────────────────────
# ID Source Quality Efficiency Focus Frustration
# a1b2c3d4 claude-code 78 82 71 none
# e5f6g7h8 cursor 45 38 52 stall, abandon
# i9j0k1l2 claude-code 91 95 88 none
# Deep-dive into a specific session
ctxray sessions --detail a1b2c3d4
# Filter by source
ctxray sessions --source cursor --json
```
--------------------------------
### Clone and Set Up Development Environment
Source: https://github.com/reprompt-dev/reprompt/blob/main/CONTRIBUTING.md
Clone the repository and set up the development environment using uv for virtual environment and dependency management.
```bash
git clone https://github.com/ctxray/ctxray
cd reprompt
uv venv
uv pip install -e ".[dev]"
```
--------------------------------
### Configure project settings
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Initialize project configuration and define linting rules.
```bash
ctxray init # generates .ctxray.toml with all rules documented
```
```toml
# .ctxray.toml (or [tool.ctxray.lint] in pyproject.toml)
[lint]
score-threshold = 50
[lint.rules]
min-length = 20
short-prompt = 40
vague-prompt = true
debug-needs-reference = true
```
--------------------------------
### Initialize configuration file
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Generates a .reprompt.toml configuration file with default settings.
```bash
reprompt init
```
--------------------------------
### Build and Test Workflow
Source: https://github.com/reprompt-dev/reprompt/blob/main/CLAUDE.md
Use these commands to manage the development environment, execute tests with coverage, perform linting, and build the project.
```bash
uv venv && uv pip install -e ".[dev]"
uv run pytest tests/ -v # run tests
uv run pytest tests/ -v --cov=ctxray # with coverage
uv run ruff check src/ tests/ # lint
uv run ruff format src/ tests/ # format
uv run mypy src/ctxray/ # type check (strict)
uv run python -m build # build wheel
```
--------------------------------
### Generate Ctxray Configuration File
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Initialize a project with a `.ctxray.toml` configuration file. Use --force to overwrite an existing file.
```bash
# Generate config file
ctxray init
```
```bash
# Overwrite existing config
ctxray init --force
```
--------------------------------
### Build a prompt from components
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Assembles a prompt from specific task, file, error, and constraint inputs.
```bash
reprompt build "task" --file src/auth.ts --error "TypeError" --constraint "keep tests"
```
--------------------------------
### Explain prompt quality
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Provides educational feedback on prompt quality in plain English.
```bash
reprompt explain "prompt"
```
--------------------------------
### Configure Project Settings via TOML
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Define linting rules and model parameters in .ctxray.toml or pyproject.toml.
```toml
# .ctxray.toml
[lint]
score-threshold = 50
model = "claude"
max-tokens = 4096
[lint.rules]
min-length = 20
short-prompt = 40
vague-prompt = true
debug-needs-reference = true
file-extensions = [".py", ".ts", ".js", ".go", ".rs"]
```
--------------------------------
### Run Prompt Diagnostic
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Score, lint, and rewrite a prompt locally in under 50ms.
```bash
ctxray check "your prompt"
```
--------------------------------
### Configure ctxray Environment Variables
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Set global configuration options using the CTXRAY_ prefix.
```bash
# Database location
export CTXRAY_DB_PATH=~/.config/ctxray/prompts.db
# Embedding backend (tfidf, ollama, local, openai)
export CTXRAY_EMBEDDING_BACKEND=tfidf
# Deduplication threshold (0.0-1.0)
export CTXRAY_DEDUP_THRESHOLD=0.85
# Ollama URL (if using ollama backend)
export CTXRAY_OLLAMA_URL=http://localhost:11434
```
--------------------------------
### Manage Ctxray Templates
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Save, list, and use prompt templates. Templates support variable substitution for dynamic prompt generation. Use --copy to copy the rendered template to the clipboard.
```bash
# Save a prompt as template
ctxray template save "Debug {error} in {file} by checking {area}" \
--name debug-template \
--category debug
```
```bash
# List all templates
ctxray template list
```
```bash
# List templates by category
ctxray template list --category debug
```
```bash
# Use a template with variable substitution
ctxray template use debug-template \
error="TypeError" \
file="auth.ts" \
area="null checks"
```
```bash
# Copy rendered template to clipboard
ctxray template use debug-template error="crash" --copy
```
--------------------------------
### Build a structured prompt with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Use `ctxray build` to construct a well-organized prompt from various components like task, context, files, errors, and constraints. It provides a score indicating prompt quality and can copy the built prompt to the clipboard.
```bash
# Build from task only
ctxray build "fix the auth bug"
# Build with all components for maximum score
ctxray build "fix the crash" \
--file src/auth.ts \
--file src/token.ts \
--error "TypeError: Cannot read property 'token' of undefined" \
--context "User sessions expire after 1 hour" \
--constraint "keep tests" \
--constraint "no breaking changes" \
--model claude
# Output:
# Score: 82/100 (EXPERT)
# Components: task, files, error, context, constraints
#
#
# User sessions expire after 1 hour
# TypeError: Cannot read property 'token' of undefined
#
#
# Fix the crash.
# Files: src/auth.ts, src/token.ts
#
#
# - keep tests
# - no breaking changes
#
# Copy built prompt to clipboard
ctxray build "implement feature" -f main.py --copy
```
--------------------------------
### Manage browser extension
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Commands to connect and verify the browser extension status.
```bash
ctxray install-extension
ctxray extension-status
```
--------------------------------
### Import Prompts
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Import prompts from existing Chat AI export files.
```bash
# Import ChatGPT conversations export
ctxray import ~/Downloads/conversations.json
# Import Claude.ai export (auto-detected)
ctxray import ~/Downloads/claude-export.zip
# Explicitly specify source format
ctxray import ~/Downloads/export.json --source chatgpt
```
--------------------------------
### Aggregate project quality metrics
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Displays session quality, efficiency, and focus scores for projects.
```bash
reprompt projects
```
--------------------------------
### Rewrite Prompts
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Improve prompt quality using rule-based optimization layers.
```bash
# Rewrite with before/after comparison
ctxray rewrite "I was wondering if you could fix the authentication bug"
# Show unified diff (red/green)
ctxray rewrite --file prompt.txt --diff
# Copy rewritten prompt to clipboard
ctxray rewrite "please help me refactor this code to be better" --copy
```
--------------------------------
### Preview prompt rewrites with diffs
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Displays a git-style unified diff showing changes between the original and rewritten prompt.
```bash
reprompt rewrite --diff
```
--------------------------------
### Recommend Better Prompts
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Suggests improved prompts based on effectiveness, category balance, and specificity. This command aids in optimizing prompts for better AI performance. Requires historical session data to be available.
```bash
reprompt recommend
```
--------------------------------
### Configure CI/CD Quality Gates
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Integrate prompt linting into GitHub Actions or local pre-commit workflows.
```yaml
# .github/workflows/prompt-lint.yml
name: Prompt Quality
on: pull_request
jobs:
lint:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4
- uses: ctxray/ctxray@main
with:
score-threshold: 50 # Fail if avg score < 50
strict: true # Fail on warnings too
comment-on-pr: true # Post results as PR comment
```
```yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/ctxray/ctxray
rev: v3.0.0
hooks:
- id: ctxray-lint
args: [--score-threshold, '50']
```
--------------------------------
### Build Structured Prompts
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Assembles well-structured prompts from various components like task, context, files, and constraints. It provides a quality score and lists suggestions for missing components.
```python
from ctxray.core.build import build_prompt, BuildResult
result: BuildResult = build_prompt(
task="fix the authentication timeout",
context="Users are being logged out after 5 minutes",
files=["src/auth.ts", "src/middleware.ts"],
error="JWT TokenExpiredError: jwt expired",
constraints=["keep backward compatibility", "don't modify tests"],
role="senior security engineer",
model="claude" # Uses XML tags for Claude
)
print(f"Score: {result.score}/100 ({result.tier})")
print(f"Components: {result.components_used}")
print(f"\n{result.prompt}")
# Suggestions for missing components
for suggestion in result.suggestions:
print(f" → {suggestion}")
```
--------------------------------
### Configure post-session hook
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Enable automatic prompt scanning after every session.
```bash
ctxray install-hook # adds post-session hook to Claude Code
```
--------------------------------
### Project Directory Structure
Source: https://github.com/reprompt-dev/reprompt/blob/main/CLAUDE.md
The project is organized into functional modules including CLI commands, core analysis logic, data adapters for various AI tools, and embedding engines.
```text
src/ctxray/
├── cli.py # Typer CLI (scan, import, report, search, demo, status, purge, install-hook, install-extension, extension-status, score, compare, check, insights, digest, style, template [save|list|use], privacy, compress, distill, agent, sessions, repetition, lint, wrapped, telemetry, mcp-serve, rewrite, init, projects, build, feedback) + bare `ctxray` dashboard + plugin loading
├── config.py # pydantic-settings, env vars (CTXRAY_ prefix) + TOML config
├── demo.py # Built-in demo data generator (no network required)
├── core/
│ ├── models.py # Prompt dataclass (auto SHA-256 hash)
│ ├── build.py # Prompt builder — assemble from components (task, context, files, error, constraints)
│ ├── check.py # Unified diagnostic — score + lint + rewrite in one pass
│ ├── dedup.py # Two-layer dedup: exact hash + TF-IDF cosine
│ ├── analyzer.py # TF-IDF hot terms + K-means clustering
│ ├── library.py # Pattern extraction + keyword categorization
│ ├── recommend.py # Prompt recommendations based on history + effectiveness
│ ├── pipeline.py # Orchestrator: scan → dedup → store → analyze → cluster
│ ├── prompt_dna.py # PromptDNA dataclass (30+ features per prompt)
│ ├── extractors.py # Tier 1 feature extraction (regex, <1ms)
│ ├── scorer.py # Research-calibrated scoring (0-100)
│ ├── segmenter.py # Three-pass prompt segmentation
│ ├── insights.py # Personal insights vs research-optimal
│ ├── digest.py # Two-window comparison for weekly digest
│ ├── style.py # Personal prompting style fingerprint
│ ├── lang_detect.py # Language detection (zh/ja/ko/en) via Unicode ranges
│ ├── extractors_zh.py # Chinese feature extraction (jieba + Chinese regex)
│ ├── persona.py # 6 prompt personas (Architect/Debugger/Explorer/Novelist/Sniper/Teacher)
│ ├── wrapped.py # WrappedReport dataclass + build_wrapped(db) aggregation
│ ├── privacy.py # Privacy metadata registry + exposure summary per adapter
│ ├── privacy_scan.py # Sensitive content detection (API keys, tokens, PII) via regex
│ ├── compress.py # 4-layer prompt compression (char norm + phrase simplify + filler delete + structure cleanup)
│ ├── suggestions.py # Command journey suggestions ("→ Try:" hints for 7 core commands)
│ ├── conversation.py # ConversationTurn, Conversation, DistillResult dataclasses
│ ├── distill.py # 6-signal importance scoring + filtering + summary generation
│ ├── agent.py # Agent workflow analysis: error loop detection, tool distribution, efficiency
│ ├── session_quality.py # Session-level composite scoring (0-100) + frustration signals
│ ├── repetition.py # Cross-session prompt repetition detection via TF-IDF clustering
│ ├── rewrite.py # Rule-based prompt rewriting (4 layers: compress, front-load, echo, hedging)
│ ├── lint.py # Configurable prompt linter with .ctxray.toml / pyproject.toml support
│ └── cost.py # Token cost estimation (locale-aware counting, multi-model pricing)
├── adapters/
│ ├── base.py # BaseAdapter ABC + parse_conversation() default
│ ├── claude_code.py # Claude Code JSONL parser (full conversation + tool names)
│ ├── codex.py # Codex CLI JSONL rollout parser (full conversation + shell/function calls)
│ ├── openclaw.py # OpenClaw JSON parser (supports ~/.openclaw/ + legacy ~/.opencode/)
│ ├── cursor.py # Cursor IDE .vscdb parser (cursorDiskKV + legacy ItemTable)
│ ├── aider.py # Aider markdown chat history parser (.aider.chat.history.md)
│ ├── gemini.py # Gemini CLI JSON session parser (~/.gemini/tmp/)
│ ├── cline.py # Cline VS Code agent task parser (globalStorage/saoudrizwan.claude-dev/)
│ ├── chatgpt.py # ChatGPT conversations.json export parser
│ └── claude_chat.py # Claude.ai web chat export parser (JSON/ZIP)
├── embeddings/
│ ├── base.py # BaseEmbedder ABC
│ ├── tfidf.py # Default (sklearn, zero config)
│ ├── ollama.py # Optional: pip install ctxray[ollama]
│ ├── local_embed.py # Optional: pip install ctxray[local] (sentence-transformers)
│ └── openai_embed.py # Optional: pip install ctxray[openai]
├── bridge/
│ ├── protocol.py # Native Messaging stdio protocol (4-byte length-prefixed JSON)
│ ├── handler.py # Message handler (ping, sync_prompts, get_status)
│ ├── host.py # Entry point launched by Chrome/Firefox as subprocess
│ └── manifest.py # Manifest generator for Chrome/Firefox/Chromium
├── commands/
│ ├── wrapped.py # `ctxray wrapped` CLI command (--json, --html, --share)
│ └── telemetry.py # `ctxray telemetry on|off|status` subcommands
└── telemetry/
├── consent.py # TelemetryConsent enum, install_id, TOML persistence
└── events.py # Pydantic TelemetryEvent model, bucketing helpers
```
--------------------------------
### Lint Prompts with Ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Check prompt quality against configurable rules. Supports CI/GitHub Action integration, model-specific rules, and strict mode. Includes token budget warnings.
```bash
# Lint stored prompts
ctxray lint
```
```bash
# With model-specific rules
ctxray lint --model claude
```
```bash
# CI mode: fail if average score below threshold
ctxray lint --score-threshold 50
```
```bash
# Strict mode: fail on warnings too
ctxray lint --strict --json
```
```bash
# With token budget warning
ctxray lint --max-tokens 4096
```
--------------------------------
### Implement Custom Adapter in Python
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Extend ctxray by subclassing BaseAdapter to parse custom session formats and conversation turns.
```python
from pathlib import Path
from ctxray.adapters.base import BaseAdapter
from ctxray.core.models import Prompt
from ctxray.core.conversation import ConversationTurn
class CustomToolAdapter(BaseAdapter):
name = "custom-tool"
default_session_path = "~/.custom-tool/sessions"
def detect_installed(self) -> bool:
"""Check if the tool's session directory exists."""
return Path(self.default_session_path).expanduser().exists()
def parse_session(self, path: Path) -> list[Prompt]:
"""Parse a session file and return prompts."""
prompts = []
# Parse your tool's session format
with open(path) as f:
for line in f:
prompts.append(Prompt(
text=line.strip(),
source=self.name,
project=path.parent.name,
session_id=path.stem,
))
return prompts
def parse_conversation(self, path: Path) -> list[ConversationTurn]:
"""Parse full conversation with both user and assistant turns."""
turns = []
# Override if your tool captures assistant responses
with open(path) as f:
for i, line in enumerate(f):
turns.append(ConversationTurn(
role="user",
text=line.strip(),
turn_index=i,
))
return turns
```
--------------------------------
### Lint and Format Code with Ruff
Source: https://github.com/reprompt-dev/reprompt/blob/main/CONTRIBUTING.md
Use ruff for checking code style and formatting. Run these commands before submitting code.
```bash
uv run ruff check src/ tests/
```
```bash
uv run ruff format src/ tests/
```
--------------------------------
### Configure MCP Server for Ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Register Ctxray as an MCP server in your `.mcp.json` file. This enables integration with tools like Claude Code and Continue.dev.
```json
{
"mcpServers": {
"ctxray": {
"type": "stdio",
"command": "ctxray",
"args": ["mcp-serve"]
}
}
}
```
--------------------------------
### Run linting via CLI
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Execute linting commands directly from the terminal.
```bash
ctxray lint --score-threshold 50 # exit 1 if avg score < 50
ctxray lint --strict # exit 1 on warnings
ctxray lint --json # machine-readable output
```
--------------------------------
### Integrate with pre-commit
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Add the linting hook to your pre-commit configuration.
```yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/ctxray/ctxray
rev: v3.0.0
hooks:
- id: ctxray-lint
```
--------------------------------
### Apply rule-based prompt rewrites
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Performs automated transformations on a prompt without using an LLM.
```bash
reprompt rewrite "prompt"
```
--------------------------------
### Check Prompts
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Perform a full diagnostic including scoring, linting, and rewrite suggestions.
```bash
# Complete diagnostic with auto-rewrite preview
ctxray check "fix the auth bug in login.ts"
# With model-specific lint rules
ctxray check "refactor the middleware" --model claude
# JSON output for programmatic use
ctxray check "help me debug this crash" --json
# Copy rewritten prompt to clipboard
ctxray check "please help fix this" --copy
```
--------------------------------
### Test User Creation in UserService
Source: https://github.com/reprompt-dev/reprompt/blob/main/tests/fixtures/aider_chat_history.md
Verifies that the UserService correctly creates a user with the provided email address.
```python
def test_create_user():
user = UserService.create("test@example.com")
assert user.email == "test@example.com"
```
--------------------------------
### Lint prompts with token budget
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Warns if a prompt exceeds the specified token limit.
```bash
reprompt lint --max-tokens 4096
```
--------------------------------
### Integrate with GitHub Actions
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Configure a GitHub Action to lint prompts on pull requests.
```yaml
# .github/workflows/prompt-lint.yml
name: Prompt Quality
on: pull_request
jobs:
lint:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4
- uses: ctxray/ctxray@main
with:
score-threshold: 50
strict: true
comment-on-pr: true
```
--------------------------------
### Analyze agent workflow patterns with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Utilize `ctxray agent` to analyze agent workflow patterns, including error loops, tool distribution, and session efficiency. The command can analyze a specified number of recent agent sessions.
```bash
# Analyze recent agent sessions
ctxray agent --last 5
# Output:
# Agent Workflow Analysis (5 sessions)
# ────────────────────────────────────
# Error Loops Detected: 2
```
--------------------------------
### Lint prompts for specific models
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Checks prompts against best practices for Claude, GPT, or Gemini.
```bash
reprompt lint --model claude/gpt/gemini
```
--------------------------------
### ctxray template
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Manages reusable prompt templates including saving, listing, and variable substitution.
```APIDOC
## ctxray template
### Description
Manages reusable prompt templates.
### Method
CLI Command
### Parameters
#### Subcommands
- **save** - Saves a prompt as a template.
- **list** - Lists all templates.
- **use** - Uses a template with variable substitution.
#### Options
- **--name** (string) - Required for save - Name of the template.
- **--category** (string) - Optional - Category for the template.
- **--copy** (flag) - Optional - Copies rendered template to clipboard.
```
--------------------------------
### Save and Reuse Prompt Templates
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Allows users to save and reuse prompt templates. Use `reprompt templates` to manage templates and `reprompt save` to store new ones. This streamlines the creation of consistent prompts.
```bash
reprompt templates
```
```bash
reprompt save
```
--------------------------------
### Register Ctxray Browser Extension Host
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Register the Native Messaging host for browser extension integration. Supports Chrome and Firefox. Check extension status with `ctxray extension-status`.
```bash
# Install for Chrome
ctxray install-extension --browser chrome
```
```bash
# Install for Firefox
ctxray install-extension --browser firefox
```
```bash
# Check extension status
ctxray extension-status
```
--------------------------------
### Configure Reprompt with TOML
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Supports TOML configuration files for customizing reprompt's behavior. The default location is `~/.config/reprompt/config.toml`. This allows for persistent settings across sessions.
```toml
# Example config.toml content
[openai]
api_key = "YOUR_API_KEY"
```
--------------------------------
### Run Tests Locally
Source: https://github.com/reprompt-dev/reprompt/blob/main/CONTRIBUTING.md
Execute tests using pytest. Includes a command to run tests with coverage and enforce a minimum coverage gate.
```bash
uv run pytest tests/ -v
```
```bash
uv run pytest tests/ -v --cov=reprompt --cov-fail-under=88 # with coverage gate
```
--------------------------------
### Score Prompts
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Analyze a prompt to receive a 0-100 score and a breakdown of five quality dimensions.
```bash
# Score a prompt with detailed breakdown
ctxray score "Fix the auth bug in login.ts where JWT expires too early"
# Read prompt from file
ctxray score --file prompt.txt --json
# Copy result to clipboard
ctxray score "Fix bug" --copy
```
--------------------------------
### Run a unified prompt diagnostic
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Executes score, lint, and rewrite operations in a single command.
```bash
reprompt check "prompt"
```
--------------------------------
### Compress a verbose prompt with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Use `ctxray compress` to reduce prompt length by removing filler words and simplifying phrases. It offers different output formats and can copy the result to the clipboard.
```bash
# Compress a verbose prompt
ctxray compress "Can you please help me with refactoring this code to make it better?"
# Output:
# Original: 12 tokens
# Compressed: 6 tokens
# Savings: 50%
#
# Result: Refactor this code.
#
# Changes:
# ✓ layer1: filler word deletion
# ✓ layer2: phrase simplification
# JSON output for pipeline integration
ctxray compress --file long_prompt.txt --json
# Copy compressed text to clipboard
ctxray compress "verbose prompt here" --copy
```
--------------------------------
### Run Privacy Scan
Source: https://github.com/reprompt-dev/reprompt/blob/main/README.md
Scan prompts for sensitive information like API keys and PII.
```bash
ctxray privacy --deep
```
--------------------------------
### Generate Prompt Insights
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Provides insights into personal prompt patterns compared to research-optimal benchmarks. This command is integrated with `reprompt scan` and helps identify areas for prompt improvement.
```bash
reprompt insights
```
--------------------------------
### Compare Two Prompts
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Performs a side-by-side feature comparison of two prompts to highlight their differences. This is useful for understanding how prompt variations affect AI responses. Ensure both prompts are valid strings.
```bash
reprompt compare "a" "b"
```
--------------------------------
### Compare Prompts
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Compare two prompts side-by-side or automatically compare the best and worst prompts from history.
```bash
# Compare two prompts
ctxray compare "fix bug" "Fix the login timeout in auth.py by adding retry logic"
# Auto-select your best vs worst prompts from history
ctxray compare --best-worst
# Filter by source when using auto-select
ctxray compare --best-worst --source cursor
```
--------------------------------
### Implement Async Context Manager for AsyncPool
Source: https://github.com/reprompt-dev/reprompt/blob/main/tests/fixtures/aider_chat_history.md
Refactors the connection pool to support asynchronous context management.
```python
class AsyncPool:
async def __aenter__(self):
return self
```
--------------------------------
### MCP Server Tools
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Tools available via the MCP server for integration with Claude Code, Continue.dev, and Zed.
```APIDOC
## MCP Tools
### Description
Functions available via the ctxray MCP server for prompt analysis and management.
### Tools
- **score_prompt(text, model)** - Performs full quality analysis.
- **search_prompts(query, category, top)** - Searches history and patterns.
- **compare_prompts(prompt_a, prompt_b)** - Performs side-by-side comparison.
- **compress_prompt(text)** - Removes filler and simplifies prompts.
- **build_prompt_from_parts(...)** - Assembles an optimized prompt from components.
- **check_privacy(limit)** - Scans for sensitive content.
- **scan_sessions(source)** - Imports new prompts.
```
--------------------------------
### ctxray lint
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Checks prompt quality against configurable lint rules with support for CI/GitHub Actions.
```APIDOC
## ctxray lint
### Description
Checks prompt quality against configurable lint rules.
### Method
CLI Command
### Parameters
#### Options
- **--model** (string) - Optional - Applies model-specific rules.
- **--score-threshold** (integer) - Optional - CI mode: fails if average score is below this threshold.
- **--strict** (flag) - Optional - Fails on warnings as well as errors.
- **--json** (flag) - Optional - Outputs results in JSON format.
- **--max-tokens** (integer) - Optional - Sets a token budget warning limit.
```
--------------------------------
### Distill AI conversations with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Employ `ctxray distill` to extract the most critical turns from AI conversations using a 6-signal importance scoring system. Options include distilling recent sessions, exporting context recovery documents, adjusting the importance threshold, and showing signal weights.
```bash
# Distill the most recent session
ctxray distill
# Distill last 3 sessions with summary
ctxray distill --last 3 --summary
# Export context recovery document for new session
ctxray distill --export --full
# Output (--export):
# ## Context Recovery
#
# Session: my-project (claude-code)
#
# ### Key Decisions
# 1. Implemented JWT refresh token flow
# 2. Fixed race condition in token validation
# 3. Added retry logic for network failures
#
# ### Files Changed
# src/auth.ts, src/middleware.ts, tests/auth.test.ts
# Adjust importance threshold (0.0-1.0)
ctxray distill --threshold 0.5
# Show signal weights
ctxray distill --show-weights
```
--------------------------------
### Keyword Search Across Prompt History
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Performs a keyword search across all historical prompts. This command is useful for finding specific prompts or topics within your session history. Requires an index or database of prompts.
```bash
reprompt search
```
--------------------------------
### Generate HTML Dashboard Report
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Renders an interactive HTML report of prompt analysis using Chart.js. This provides a visual overview of prompt performance and trends. Use the `--html` flag after running `reprompt report`.
```bash
reprompt report --html
```
--------------------------------
### Scan AI Sessions
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Scan AI tool logs to extract and deduplicate prompts into a local SQLite database.
```bash
# Scan all detected AI tools
ctxray scan
# Scan only a specific source
ctxray scan --source cursor
# Scan with custom path
ctxray scan --source chatgpt-export --path ~/Downloads/conversations.json
# Quiet mode (skip auto-report)
ctxray scan --quiet
```
--------------------------------
### Filter Agent Loops and Sources
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Use these commands to filter agent loops by specific sources or to view only error loops.
```bash
ctxray agent --loops-only
```
```bash
ctxray agent --source claude-code --json
```
--------------------------------
### Python Script for Generating Demo Data
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
A Python script located in `scripts/generate_demo_data.py` used for generating sample data, specifically utilizing the CodeAlpaca-20K dataset. This script is helpful for testing and demonstration purposes.
```python
# scripts/generate_demo_data.py
# ... script content ...
from datasets import load_dataset
dataset = load_dataset("CodeAlpaca-20K")
# ... rest of the script ...
```
--------------------------------
### Generate Ctxray Reports
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Generate comprehensive analytics reports in various formats. Use the --html flag to open a dashboard in your browser or --format json for pipeline integration.
```bash
ctxray report
```
```bash
ctxray report --html
```
```bash
ctxray report --html --output my-report.html
```
```bash
ctxray report --format json
```
```bash
ctxray report --source cursor --clusters 8
```
--------------------------------
### MCP Tools for Prompt Analysis
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Utilize MCP tools for various prompt analysis tasks, including scoring, searching, comparison, compression, building, privacy checks, and session scanning.
```python
# score_prompt - Full quality analysis
# Returns tier, breakdown, strengths, suggestions, lint issues, and auto-rewrite
score_prompt(text="Fix the auth bug", model="claude")
```
```python
# search_prompts - Search history and patterns
search_prompts(query="auth") # keyword search
search_prompts(category="debug", top=True) # browse top patterns
```
```python
# compare_prompts - Side-by-side comparison
compare_prompts(
prompt_a="fix bug",
prompt_b="Fix the JWT validation bug in auth.ts"
)
```
```python
# compress_prompt - Remove filler and simplify
compress_prompt(text="Could you please help me fix this?")
```
```python
# build_prompt_from_parts - Assemble optimized prompt
build_prompt_from_parts(
task="fix the crash",
files="src/auth.ts,src/token.ts",
error="TypeError: undefined",
constraints="keep tests,no breaking changes",
model="claude"
)
```
```python
# check_privacy - Scan for sensitive content
check_privacy(limit=100)
```
```python
# scan_sessions - Import new prompts
scan_sessions(source="claude-code")
```
--------------------------------
### Track Prompt Evolution
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Tracks prompt evolution over time, including specificity scoring and delta arrows. This command provides insights into how prompts change and their impact. Requires historical prompt data.
```bash
reprompt trends
```
--------------------------------
### Compress Prompt Text
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Compresses prompt text by removing filler words and simplifying phrases. Shows original and compressed text, token savings, and the layers of compression applied.
```python
from ctxray.core.compress import compress_text, CompressResult
result: CompressResult = compress_text(
"I was wondering if you could please help me understand how to fix this bug"
)
print(f"Original: {result.original}")
print(f"Compressed: {result.compressed}")
print(f"Savings: {result.savings_pct}%")
print(f"Tokens: {result.original_tokens} → {result.compressed_tokens}")
# Changes applied
for change in result.changes:
print(f" ✓ {change}")
```
--------------------------------
### Analyze privacy exposure with ctxray
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Use `ctxray privacy` to examine the data sent to AI tools and scan for sensitive content. It provides a summary of privacy exposure by source, retention policies, and can perform a deep scan for sensitive information like API keys or PII. JSON output is available for CI/auditing.
```bash
# Show privacy exposure summary
ctxray privacy
# Output:
# Privacy Exposure by Source
# ──────────────────────────
# claude-code: 1,234 prompts
# Data sent: file paths, error messages, code snippets
# Retention: local JSONL (no cloud sync)
#
# cursor: 567 prompts
# Data sent: file paths, selections, completions
# Retention: local .vscdb + telemetry
# Deep scan for sensitive content
ctxray privacy --deep
# Output:
# Sensitive Content Scan (500 prompts)
# ────────────────────────────────────
# Category Count Sources
# API Keys 3 claude-code, cursor
# JWT Tokens 7 claude-code
# Email Addresses 2 chatgpt
# IP Addresses 1 cursor
#
# High-risk finding:
# AWS_SECRET_KEY in claude-code prompt (2024-03-15)
# JSON output for CI/audit
ctxray privacy --deep --json
```
--------------------------------
### Scan Sessions and Show Report
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Scans session history and automatically displays a report. Use the `--quiet` flag to skip the automatic report display. This command is central to analyzing prompt usage over time.
```bash
reprompt scan
```
--------------------------------
### Score Prompts Programmatically with Ctxray Python API
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Programmatically score prompts using the Ctxray core functions. This includes extracting features, scoring, and determining prompt tiers.
```python
from ctxray.core.extractors import extract_features
from ctxray.core.scorer import score_prompt, get_tier, ScoreBreakdown
```
--------------------------------
### Merge Near-Duplicate Prompts
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Clusters near-duplicate prompts and selects canonical versions, helping to consolidate and refine prompt libraries. This command is useful for managing large collections of prompts.
```bash
reprompt merge-view
```
--------------------------------
### Extract Features and Score Prompt
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Extracts features from a given text and then scores the prompt based on these features. Provides a detailed breakdown of the score and suggestions for improvement.
```python
dna = extract_features(
text="Fix the JWT validation bug in src/auth.ts",
source="manual",
session_id="example"
)
# Score the prompt
breakdown: ScoreBreakdown = score_prompt(dna)
print(f"Total: {breakdown.total}/100")
print(f"Tier: {get_tier(breakdown.total)}") # EXPERT, STRONG, GOOD, BASIC, or DRAFT
print(f"Clarity: {breakdown.clarity}/25")
print(f"Context: {breakdown.context}/25")
print(f"Position: {breakdown.position}/20")
print(f"Structure: {breakdown.structure}/15")
print(f"Repetition: {breakdown.repetition}/15")
# Access suggestions for improvement
for suggestion in breakdown.suggestions:
print(f"→ {suggestion.message} (+{suggestion.points} pts)")
print(f" Paper: {suggestion.paper}")
# Access confirmations (what's working well)
for confirmation in breakdown.confirmations:
print(f"✓ {confirmation.message} ({confirmation.score})")
```
--------------------------------
### Rewrite Prompt for Quality Improvement
Source: https://context7.com/reprompt-dev/reprompt/llms.txt
Rewrites a prompt using rule-based transformations to improve its quality score. Displays the score before and after rewriting, the score delta, and the rewritten prompt.
```python
from ctxray.core.rewrite import rewrite_prompt, RewriteResult
result: RewriteResult = rewrite_prompt(
"I was wondering if maybe you could possibly help me fix the auth bug"
)
print(f"Before: {result.score_before}")
print(f"After: {result.score_after}")
print(f"Delta: +{result.score_delta}")
print(f"Rewritten: {result.rewritten}")
# Changes applied
for change in result.changes:
print(f" ✓ {change}")
# Manual suggestions (require human input)
for suggestion in result.manual_suggestions:
print(f" → {suggestion}")
```
--------------------------------
### Perform Type Checking with Mypy
Source: https://github.com/reprompt-dev/reprompt/blob/main/CONTRIBUTING.md
Ensure type correctness by running mypy in strict mode on the source code.
```bash
uv run mypy src/ctxray/
```
--------------------------------
### Python DataClass for Prompt Features
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Defines the `PromptDNA` dataclass, which stores over 30 extracted features for each prompt. These features are extracted at scan time and used for analysis. This is a Python class definition.
```python
from dataclasses import dataclass
@dataclass
class PromptDNA:
# ... (30+ features)
pass
```
--------------------------------
### Score Session Quality
Source: https://github.com/reprompt-dev/reprompt/blob/main/CHANGELOG.md
Calculates session quality scores based on heuristics like clean exit, error ratio, and duration. This helps in evaluating the overall effectiveness of AI interactions. Requires session metadata.
```bash
reprompt effectiveness
```