/cxq - Context Query (Anti-Forgetting Memory System)
Search and query the unified message database with full-text search, semantic search, knowledge extraction, and analytics. Part of the CODITECT anti-forgetting system.
Usage
# Basic search
/cxq "error"
/cxq "git commit"
# Project filtering (ADR-156)
/cxq --decisions --filter-project CUST-avivatec-fpa # Filter by project
/cxq --decisions --project-only # Exclude global scope
/cxq --decisions --all-projects # Show all (ignore filter)
/cxq "error" # Auto-uses CODITECT_PROJECT env var
# LLM Source Filtering (ADR-122)
/cxq "error" --llm claude # Claude sessions only
/cxq "api" --llm codex # Codex sessions only
/cxq "test" --llm gemini # Gemini sessions only
/cxq --by-llm # Show breakdown by LLM source
/cxq --llm-stats # LLM source distribution
# Semantic search (requires embeddings)
/cxq --semantic "how to fix authentication"
# RAG retrieval (messages + decisions + patterns + errors)
/cxq --recall "database migration"
# Knowledge queries
/cxq --decisions
/cxq --patterns --language python
/cxq --errors "TypeError"
# Inter-Session Message Bus (ADR-173)
/cxq --bus-messages # Recent session messages
/cxq --bus-alerts # Operator alerts
/cxq --bus-lifecycle # Session lifecycle events
/cxq --bus-unread # Unread messages for this session
/cxq --bus-stats # Messaging bus statistics
/cxq --bus-feed # Chronological activity timeline (all events)
# Get help
/cxq -h
/cxq --examples
System Prompt
System Prompt
⚠️ EXECUTION DIRECTIVE: When the user invokes this command, you MUST:
- IMMEDIATELY execute - no questions, no explanations first
- ALWAYS show full output from script/tool execution
- ALWAYS provide summary after execution completes
DO NOT:
- Say "I don't need to take action" - you ALWAYS execute when invoked
- Ask for confirmation unless
requires_confirmation: truein frontmatter - Skip execution even if it seems redundant - run it anyway
The user invoking the command IS the confirmation.
You are querying the CODITECT context database for session history search.
Databases (ADR-118 Four-Tier Architecture):
- sessions.db (Tier 3) - Messages, token economics, tool analytics
- org.db (Tier 2) - Decisions, skill learnings, error solutions
- platform.db (Tier 1) - Component data: agents, skills, commands, scripts, hooks
- messaging.db (ADR-160/173) - Session messages, operator alerts, lifecycle events, file locks, task claims
Execute the context query:
# ADR-118 compliant (REQUIRED):
python3 scripts/context-query.py $ARGS
First-time setup: Run /cx to extract session data to the ADR-118 databases.
Quick Reference
Basic Operations
| Command | Description |
|---|---|
/cxq "term" | Search for term (FTS5) |
/cxq -h | Show help |
/cxq --examples | Show all examples |
/cxq --stats | Database statistics |
/cxq --knowledge-stats | Knowledge base statistics |
LLM Source Filtering (ADR-122)
| Command | Description |
|---|---|
/cxq "query" --llm claude | Filter to Claude sessions only |
/cxq "query" --llm codex | Filter to Codex sessions only |
/cxq "query" --llm gemini | Filter to Gemini sessions only |
/cxq --by-llm | Token/message breakdown by LLM source |
/cxq --llm-stats | LLM source distribution statistics |
/cxq --llm-models | Show model distribution per LLM |
Session Log Search (J.32)
| Command | Description |
|---|---|
/cxq --session-logs "query" | Full-text search session log entries |
/cxq --session-log-task ID | Find entries by task ID |
/cxq --session-log-date DATE | Filter by date |
/cxq --session-log-recent N | N most recent entries |
/cxq --session-log-stats | Indexing statistics |
Anti-Forgetting Features
| Command | Description |
|---|---|
/cxq --semantic "query" | Semantic similarity search (vector only, J.16.3.1) |
/cxq --hybrid "query" | Hybrid FTS5 + vector search with RRF fusion (J.16.3.1) |
/cxq --recall "topic" | RAG retrieval optimized for context injection (J.16.3.2) |
/cxq --semantic-help | Show semantic search help and status |
/cxq --decisions | List extracted decisions |
/cxq --patterns | List code patterns |
/cxq --errors | List error-solution pairs |
/cxq --extract | Run knowledge extraction |
/cxq --embeddings | Generate semantic embeddings |
Semantic Search Options (J.16.3)
| Command | Description |
|---|---|
/cxq --fts-weight W | FTS5 weight in hybrid search (default: 0.4) |
/cxq --vector-weight W | Vector weight in hybrid search (default: 0.6) |
/cxq --similarity-threshold T | Min similarity threshold (default: 0.3) |
Learning & Onboarding
| Command | Description |
|---|---|
/cxq --onboarding | Show onboarding progress + badges |
/cxq --learning-progress | Module completion status |
/cxq --learning-badges | Earned and available badges |
/cxq --learning-next | Recommend next module |
/cxq --learning-stats | Learning statistics |
Token Accounting (ADR-005)
| Command | Description |
|---|---|
/cxq --tokens | Token usage summary |
/cxq --cost | Cost analysis with model pricing |
/cxq --token-stats | Comprehensive token statistics |
/cxq --cache-efficiency | Prompt caching efficiency metrics |
/cxq --by-session | Token breakdown by session |
/cxq --by-project | Token breakdown by project |
/cxq --by-date | Token breakdown by date |
/cxq --by-model | Token breakdown by model |
/cxq --daily-cost-report | Comprehensive daily cost report with trends (J.6.4) |
/cxq --cost-date YYYY-MM-DD | Specify date for daily report (default: today) |
/cxq --cost-trend-days N | Days to include in trend analysis (default: 7) |
/cxq --optimize-costs | Generate cost optimization recommendations (J.6.5) |
/cxq --optimize-days N | Days to analyze for optimization (default: 30) |
/cxq --budget-alerts | Check spending against configurable budget limits (J.6.6) |
/cxq --daily-limit USD | Daily spending limit in USD (default: 50) |
/cxq --weekly-limit USD | Weekly spending limit in USD (default: 250) |
/cxq --monthly-limit USD | Monthly spending limit in USD (default: 800) |
/cxq --opus-limit PCT | Max Opus usage percentage threshold (default: 30) |
Enhanced Export Analytics (v4.0)
| Command | Description |
|---|---|
/cxq --diff-stats | Code change statistics (lines added/removed) |
/cxq --failed-tools | Failed/interrupted/truncated tool invocations |
/cxq --export-models | Messages grouped by Claude model from exports |
Reasoning Traces (J.5 - Agentic Metadata)
| Command | Description |
|---|---|
/cxq --traces | Show reasoning trace summary (success rates, confidence, latency) |
/cxq --trace-list | List recent reasoning traces with visualization |
/cxq --trace-id ID | Show specific trace by ID with all steps |
/cxq --trace-failures | Show failed traces grouped by error type |
/cxq --trace-low-confidence | Show traces with low confidence scores |
/cxq --trace-confidence-threshold N | Set confidence threshold (default: 0.5) |
/cxq --trace-tool TOOL | Filter traces by tool name (Read, Write, Edit, Bash) |
/cxq --trace-status STATUS | Filter traces by status (success, failed, interrupted, timeout) |
/cxq --failure-patterns | Detect recurring failure patterns with recommendations |
/cxq --pattern-min-occurrences N | Minimum occurrences for pattern detection (default: 2) |
Tool Analytics (J.7)
| Command | Description |
|---|---|
/cxq --tools | Show tool usage analytics summary |
/cxq --tools-by-category | Tool usage grouped by category |
/cxq --tool-errors | Tool errors and failure rates |
/cxq --tool-sequences | Detect common tool usage sequences (J.7.4) |
/cxq --sequence-length N | Number of tools in sequence (2-5, default: 3) |
/cxq --sequence-min N | Minimum occurrences for pattern (default: 3) |
/cxq --sequence-window MIN | Max minutes between tools in sequence (default: 5) |
Query Enhancement (ADR-149 Phase 1)
| Command | Description |
|---|---|
/cxq --tokens --where "EXPR" | Filter with SQL-like WHERE expressions |
/cxq --tokens --group-by FIELDS | Group results by fields (supports time functions) |
/cxq --tokens --sort FIELDS | Sort results (append _asc or _desc) |
/cxq --decisions --where "confidence > 0.8" | Filter decisions by confidence |
/cxq --tokens --group-by model_name,week | Group by model and week |
/cxq --tools --group-by tool_name --sort invocation_count_desc | Tool usage ranking |
Knowledge Graph Traversal (J.4.7.3)
| Command | Description |
|---|---|
/cxq --traversal bfs --start-node NODE | Breadth-first traversal from node |
/cxq --traversal dfs --start-node NODE | Depth-first traversal from node |
/cxq --traversal semantic --start-node NODE | Relevance-scored traversal |
/cxq --traversal policy_first --start-node NODE | Policy/ADR-prioritized traversal |
/cxq --traversal shortest --start-node A --end-node B | Find shortest path between nodes |
/cxq --traversal bfs --start-node NODE --traversal-depth 5 | Custom depth limit |
Traversal Strategies:
bfs- Breadth-first: explore all neighbors before going deeper (default for most uses)dfs- Depth-first: explore one path fully before backtrackingsemantic- Prioritize high-relevance nodes (degree, properties, type importance)policy_first- Start with policy/ADR nodes (for governance context)shortest- Find shortest path between two nodes (requires--end-node)
Session Log Queries (J.32)
| Command | Description |
|---|---|
/cxq --session-logs "query" | Full-text search across session log entries |
/cxq --session-log-task TASK_ID | Find entries by task ID (e.g., H.13.9) |
/cxq --session-log-date YYYY-MM-DD | Filter entries by specific date |
/cxq --session-log-range FROM TO | Filter entries by date range |
/cxq --session-log-recent N | Show N most recent session log entries |
/cxq --session-log-stats | Session log indexing statistics |
Session Log Query Examples:
# Search all session logs for ADR-173 mentions
/cxq --session-logs "ADR-173"
# Find all work done for task H.13.9
/cxq --session-log-task H.13.9
# Show all entries from a specific date
/cxq --session-log-date 2026-02-11
# Show entries from a date range
/cxq --session-log-range 2026-02-01 2026-02-12
# Show 5 most recent entries
/cxq --session-log-recent 5
# Combine with project filter
/cxq --session-logs "financial model" --filter-project PILOT
/cxq --session-log-stats --filter-project CUST-avivatec-fpa
# Indexing statistics
/cxq --session-log-stats
Note: Session logs are indexed by /cx automatically. Run /cx first to populate the database. Bare /cxq "query" also finds session log entries via messages cross-references.
Stored Context Graph Projections (J.25.6.15)
| Command | Description |
|---|---|
/cxq --context-graph | List all stored context graph projections |
/cxq --context-graph <ID> | Show details for a specific graph (nodes, usage) |
/cxq --context-graph <ID> --json | JSON output for programmatic access |
Context graphs are built with --graph "task" --graph-persist and stored in sessions.db. Use --context-graph to view previously built projections, inspect their seed/expanded nodes, and check usage history.
ADR-159 Project Scoping: Use --filter-project with --graph to build project-scoped context graphs:
/cxq --graph "deploy kubernetes" --filter-project CUST-avivatec-fpa
/cxq --context-graph --filter-project PILOT
Field-Specific Search (J.4.7.4)
| Command | Description |
|---|---|
/cxq --recent --field "role:assistant" | Filter by exact field value |
/cxq --tokens --field "model_name:*opus*" | Filter by pattern (contains) |
/cxq --decisions --field "decision_type:testing" | Filter decisions by type |
/cxq --errors --field "error_type:*Error,language:python" | Multiple field filters (AND) |
/cxq --tools --field "success:true" | Filter tools by success status |
/cxq --field-help | Show valid fields for each query type |
Field Syntax:
field:value- Exact match (case-insensitive)field:*value- Ends with value (LIKE '%value')field:value*- Starts with value (LIKE 'value%')field:*value*- Contains value (LIKE '%value%')field1:val1,field2:val2- Multiple constraints (AND logic)
Cross-Table Correlation (J.4.7.5)
| Command | Description |
|---|---|
/cxq --correlate "messages,token_economics" --by session_id | Correlate messages with costs |
/cxq --correlate "tool_analytics,token_economics" --by session_id | Tool performance with costs |
/cxq --correlate "decisions,messages" --by message_id | Decisions with source context |
/cxq --correlate cost-by-session | Shortcut: messages × token_economics |
/cxq --correlate tool-performance | Shortcut: tool_analytics × token_economics |
/cxq --correlate-help | Show valid tables and join keys |
Correlation Syntax:
--correlate "table1,table2[,table3]"- Comma-separated table names--by key1[,key2]- Join key(s) to correlate on- Shortcuts:
cost-by-session,tool-performance,decisions-context,skill-sessions
Valid Tables:
- sessions.db:
messages,token_economics,tool_analytics,message_component_invocations - org.db:
decisions,skill_learnings,error_solutions - messaging.db:
session_messages,session_registry,file_locks,task_claims
Inter-Session Message Bus Queries (ADR-173)
| Command | Description |
|---|---|
/cxq --bus-messages | List recent session messages from messaging.db |
/cxq --bus-messages "query" | Search session messages by payload content |
/cxq --bus-alerts | Show operator alerts (project/task/cwd/file conflicts) |
/cxq --bus-lifecycle | Show session lifecycle events (started/ended/resumed) |
/cxq --bus-unread | Show unread messages for the current session |
/cxq --bus-stats | Show messaging.db statistics (sessions, messages, locks, claims) |
/cxq --bus-sessions | List all sessions (active + historical) from session_registry |
/cxq --bus-messages --channel NAME | Filter messages by channel |
/cxq --bus-messages --priority N | Filter by minimum priority (0-3) |
/cxq --bus-messages --since "YYYY-MM-DD" | Filter messages since date |
/cxq --bus-feed | Chronological timeline of ALL session activity (lifecycle + alerts + broadcasts + directed) |
/cxq --bus-feed --limit N | Limit feed entries (default: 50) |
/cxq --bus-feed --since "YYYY-MM-DD" | Feed entries since date |
--bus-feed Implementation:
The session activity feed merges all message types into a single chronological timeline:
import os, sys
sys.path.insert(0, 'submodules/core/coditect-core')
from scripts.core.session_message_bus import get_session_message_bus
bus = get_session_message_bus()
# Collect all message types
lifecycle = bus.poll("session_lifecycle", since_id=0, limit=100)
alerts = bus.get_operator_alerts(unread_only=False, limit=100)
task_msgs = bus.poll("task_broadcast", since_id=0, limit=100)
coord_msgs = bus.poll("coordination", since_id=0, limit=100)
# Merge and sort by timestamp (newest first)
all_events = []
for msg in lifecycle:
all_events.append({"time": msg.created_at, "type": "lifecycle", "channel": "session_lifecycle", "data": msg})
for msg in alerts:
all_events.append({"time": msg.created_at, "type": "alert", "channel": "operator_alert", "data": msg})
for msg in task_msgs:
all_events.append({"time": msg.created_at, "type": "task", "channel": "task_broadcast", "data": msg})
for msg in coord_msgs:
all_events.append({"time": msg.created_at, "type": "coordination", "channel": "coordination", "data": msg})
all_events.sort(key=lambda e: e["time"], reverse=True)
Feed Output Format:
Session Activity Feed (last 50 events)
==================================================
2026-02-11T04:15:22Z [COORDINATION] claude-29583 → codex-41200: "please release lock"
2026-02-11T03:58:11Z [ALERT/CRITICAL] project_conflict: claude-29583 + codex-41200 on PILOT
2026-02-11T03:45:00Z [TASK] claude-29583 claimed H.13.8
2026-02-11T03:31:37Z [LIFECYCLE] claude-29583 started (PILOT)
2026-02-11T03:15:22Z [LIFECYCLE] codex-41200 started (PILOT)
2026-02-11T02:00:00Z [LIFECYCLE] claude-88200 ended (PILOT)
Total: 6 events (2 lifecycle, 1 alert, 1 task, 1 coordination, 1 directed)
Message Bus Query Implementation:
import sys, json
sys.path.insert(0, 'submodules/core/coditect-core')
from scripts.core.session_message_bus import get_session_message_bus
bus = get_session_message_bus()
# Get messages by channel
messages = bus.poll("operator_alert", since_id=0, limit=50)
# Get operator alerts
alerts = bus.get_operator_alerts(unread_only=False, limit=50)
# Get unread for current session
import os
unread = bus.get_unread(recipient_id=f"claude-{os.getpid()}")
# Get lifecycle events
lifecycle = bus.poll("session_lifecycle", since_id=0, limit=50)
# Get bus statistics
stats = bus.stats()
Message Channels:
session_lifecycle— started, ended, resumed eventsoperator_alert— project_conflict, task_conflict, cwd_overlap, file_conflicttask_broadcast— task claim/release/update notificationsstate— shared state updatescoordination— workflow coordination
Priority Levels: 0=routine, 1=normal, 2=high, 3=critical
Query Templates (ADR-154)
| Command | Description |
|---|---|
/cxq --queries | List all available query templates |
/cxq --template <name> / -Q <name> | Execute a named query template |
/cxq --query-agents <type> | List templates for a specific agent type |
/cxq --query-category <cat> | List templates by category |
/cxq --create-query | Create new template interactively (J.4.8.5) |
/cxq --create-query quick | Quick template creation with minimal prompts |
/cxq --create-query clone | Clone an existing template with new name |
Template Categories: agent-context, analytics, audit, search, workflow, debugging
Example Usage:
# List all templates
/cxq --queries
# Execute a template
/cxq --template architecture-context
/cxq -Q security-audit
# Find templates for an agent
/cxq --query-agents senior-architect
# Create new templates
/cxq --create-query # Full interactive wizard
/cxq --create-query quick # Minimal prompts
/cxq --create-query clone # Copy existing template
Boolean Search Operators (J.4.4.1)
| Command | Description |
|---|---|
/cxq "term1 AND term2" | Require both terms |
/cxq "term1 OR term2" | Match either term |
/cxq "term1 NOT term2" | Exclude second term |
/cxq '"exact phrase"' | Match exact phrase |
/cxq "prefix*" | Wildcard prefix match |
/cxq --boolean-help | Show full Boolean syntax help |
Operators:
AND- Both terms required (implicit between consecutive terms)OR- Either term matchesNOT- Exclude term"..."- Exact phrase match*- Wildcard (prefix or suffix)
Examples:
# Boolean AND (explicit)
/cxq "error AND authentication"
# Boolean OR
/cxq "deploy OR kubernetes"
# Boolean NOT
/cxq "security NOT test"
# Phrase search
/cxq '"database connection" AND timeout'
# Complex grouping
/cxq '(error OR warning) AND "stack trace"'
# Wildcards
/cxq "api* AND auth*"
Result Ranking (J.4.5)
| Command | Description |
|---|---|
/cxq "query" | Search with ranking enabled (default) |
/cxq "query" --no-rank | Disable ranking (chronological order) |
/cxq "query" --show-scores | Include score breakdown in output |
/cxq "query" --rank-weights 0.7,0.2,0.1 | Custom ranking weights |
/cxq --rank-help | Show ranking factors and options |
Ranking Factors:
- Relevance (50%) - BM25-style term frequency scoring
- Recency (30%) - Exponential decay (recent results boosted)
- Source Type (20%) - Decisions > skill_learnings > messages
Source Type Boosts:
| Source | Boost |
|---|---|
| decisions | 1.5x |
| skill_learnings | 1.4x |
| error_solutions | 1.3x |
| patterns | 1.2x |
| components | 1.1x |
| messages | 1.0x |
Examples:
# Default ranking (relevance + recency + source)
/cxq "authentication error"
# Show score breakdown
/cxq "auth" --show-scores
# Prioritize relevance over recency
/cxq "deploy" --rank-weights 0.7,0.2,0.1
# Disable ranking (raw chronological order)
/cxq "error" --no-rank
Aggregations (J.4.6)
| Command | Description |
|---|---|
/cxq "query" --by-day | Aggregate by day (J.4.6.1) |
/cxq "query" --by-week | Aggregate by ISO week |
/cxq "query" --by-month | Aggregate by month |
/cxq "query" --by-year | Aggregate by year |
/cxq "query" --topics | Cluster by topic keywords (J.4.6.2) |
/cxq --recent 500 --trending | Show trending topics (J.4.6.3) |
/cxq --aggregation-help | Show aggregation options |
Time Aggregations (J.4.6.1):
--by-hour- Group by hour (YYYY-MM-DD HH:00)--by-day- Group by day (YYYY-MM-DD)--by-week- Group by ISO week (YYYY-WNN)--by-month- Group by month (YYYY-MM)--by-year- Group by year (YYYY)
Topic Clustering (J.4.6.2):
--topics- Cluster messages by extracted keywords--min-cluster N- Minimum messages per cluster (default: 2)--max-clusters N- Maximum clusters to return (default: 20)
Trend Analysis (J.4.6.3):
--trending- Show rising/falling topics--window N- Days in comparison window (default: 7)--growth-threshold N- Min % change to be "rising" (default: 50)
Examples:
# Daily error frequency
/cxq "error" --by-day
# Weekly message volume
/cxq --recent 500 --by-week
# Find topic clusters in recent messages
/cxq --recent 200 --topics
# Show trending topics (last 7 days vs previous 7)
/cxq --recent 500 --trending
# 14-day trend comparison
/cxq --recent 1000 --trending --window 14
Multi-Database Search (ADR-103 Four-Database Architecture)
| Command | Description |
|---|---|
/cxq "query" --multi-db | Search ALL 4 databases with RRF merging |
/cxq "query" --scope-framework | Search framework only (platform.db + platform-index.db) |
/cxq "query" --scope-project UUID | Search specific project only (projects.db) |
/cxq "query" --scope-context | Search context only (org.db + sessions.db) - default |
Component Search (Self-Awareness) - Queries platform.db (ADR-080)
| Command | Description |
|---|---|
/cxq --components | List indexed components |
/cxq --components "query" | Search components by keyword (FTS5) |
/cxq --component-semantic "intent" | Semantic search by intent |
/cxq --component-type TYPE | Filter by type (agent, command, skill, script, hook, workflow) |
/cxq --show-component ID | Show detailed component info |
/cxq --component-stats | Component index statistics |
/cxq --component-embeddings | Generate semantic embeddings |
/cxq --component-embedding-stats | Embedding coverage statistics |
/cxq --component-threshold N | Similarity threshold (0-1, default: 0.3) |
Browse
| Command | Description |
|---|---|
/cxq --recent 20 | Last 20 messages |
/cxq --sessions | List sessions |
/cxq --longest 10 | 10 longest messages |
/cxq --code | Messages with code |
/cxq --today | Messages from today |
Database Views (Quick Insights)
| Command | Description |
|---|---|
/cxq --views | List all available database views (18 total) |
/cxq --view NAME | Query a specific view (e.g., --view knowledge_stats) |
/cxq --today-activity | Messages, decisions, patterns from last 24 hours |
/cxq --error-frequency | Most common errors with success counts |
/cxq --patterns-summary | Code patterns grouped by language |
/cxq --session-summary | Recent session activity and durations |
/cxq --component-overview | Components by type and status |
/cxq --docs-summary | Documentation by category |
Comprehensive Entries (All 6 Types) - ADR-025
| Command | Description |
|---|---|
/cxq --index-comprehensive | Index ALL 6 entry types from raw sessions |
/cxq --rebuild-comprehensive | Rebuild comprehensive index from scratch |
/cxq --comprehensive-stats | Show entry counts by type |
/cxq --search-entries "query" | FTS5 search across all entry types |
/cxq --entry-type TYPE | Filter by entry type (user, assistant, system, summary, queue-operation, file-history-snapshot) |
/cxq --threading | Show message threading relationships |
/cxq --thread-from UUID | Trace conversation thread from UUID |
/cxq --file-backups | List file backup entries |
Examples
Simple Search (FTS5)
/cxq "error" # Search for "error"
/cxq "git commit" # Search for phrase
/cxq "test OR spec" # Either word
/cxq "def*" # Prefix match
LLM Source Filtering (ADR-122)
# Filter searches by LLM source
/cxq "api" --llm claude # Search Claude sessions only
/cxq "model" --llm codex # Search Codex sessions only
/cxq "test" --llm gemini # Search Gemini sessions only
# LLM statistics and breakdown
/cxq --llm-stats # Show distribution by LLM source
/cxq --by-llm # Messages/tokens breakdown by LLM
/cxq --llm-models # Model usage per LLM
# Combine with other filters
/cxq "error" --llm claude --today # Claude errors from today
/cxq --decisions --llm codex # Decisions from Codex sessions
/cxq --patterns --llm gemini # Patterns from Gemini sessions
# Compare LLM usage
/cxq --cost --by-llm # Cost breakdown by LLM source
/cxq --tokens --by-llm # Token usage by LLM source
Multi-Database Search (ADR-103)
# Search all 4 databases with Reciprocal Rank Fusion merging
/cxq "authentication" --multi-db
# Search framework components only
/cxq "database" --scope-framework
# Search specific project
/cxq "api" --scope-project 550e8400-e29b-41d4-a716-446655440000
# Combine with semantic search
/cxq "how to implement caching" --multi-db --semantic
Semantic Search
/cxq --semantic "how to implement authentication"
/cxq --semantic "database connection pooling" --threshold 0.5
/cxq --semantic "error handling patterns" --role assistant
RAG Recall
/cxq --recall "API design" # Get messages + decisions + patterns + errors
/cxq --recall "testing" --json # JSON output for programmatic use
Knowledge Queries
# Decisions
/cxq --decisions # All decisions
/cxq --decisions --decision-type architecture # Architecture decisions only
/cxq "database" --decisions # Search decisions
# Code Patterns
/cxq --patterns # All patterns
/cxq --patterns --language python # Python patterns
/cxq --patterns --pattern-type async # Async patterns
/cxq --patterns --language rust --full # Full code
# Error Solutions
/cxq --errors # All error-solution pairs
/cxq --errors --error-type TypeError # TypeErrors
/cxq "import" --errors # Search errors
Session Linking
# Link two sessions
/cxq --link abc123 def456 continues # Session continues another
/cxq --link abc123 def456 fixes # Session fixes issues from another
# View linked sessions
/cxq --links abc123
Token Accounting (ADR-005)
# Token usage summary
/cxq --tokens # Overall token totals
# Cost analysis
/cxq --cost # Cost breakdown with model pricing
# Comprehensive statistics
/cxq --token-stats # Full statistics with percentages
# Cache efficiency (prompt caching)
/cxq --cache-efficiency # Cache hit rates and savings
# Breakdown views
/cxq --by-session # Tokens per session
/cxq --by-project # Tokens per project
/cxq --by-date # Tokens per day
/cxq --by-model # Tokens per model
Query Enhancement (ADR-149 Phase 1)
# WHERE expressions - SQL-like filtering (J.4.7.1)
/cxq --decisions --where "confidence > 0.8"
/cxq --decisions --where "decision_type = 'architecture' AND confidence >= 0.7"
/cxq --tokens --where "cost_total_usd > 0.01"
/cxq --tokens --where "model_name LIKE 'claude%'"
/cxq --errors --where "confidence > 0.5 OR error_type = 'TypeError'"
# GROUP BY - aggregate results (J.4.7.2)
/cxq --tokens --group-by model_name # Group by model
/cxq --tokens --group-by model_name,week # Group by model and week
/cxq --tokens --group-by session_id,day # Group by session and day
/cxq --tools --group-by tool_name # Group tool usage by name
/cxq --decisions --group-by decision_type # Group decisions by type
# Time functions for GROUP BY: day, week, month, year, hour
/cxq --tokens --group-by week # Group by week (uses created_at)
/cxq --tokens --group-by created_at.month # Explicit field.timefunction
# SORT - order results (J.4.7.2)
/cxq --tokens --sort cost_total_usd_desc # Sort by cost descending
/cxq --tokens --sort created_at_asc # Sort by date ascending
/cxq --tools --sort invocation_count_desc # Sort by invocation count
/cxq --decisions --sort confidence_desc # Sort by confidence
# Combined queries
/cxq --tokens --group-by model_name --sort cost_total_usd_desc
/cxq --tokens --group-by model_name,week --sort total_cost_desc
/cxq --tools --group-by tool_name --sort invocation_count_desc --limit 10
/cxq --decisions --where "confidence > 0.7" --sort created_at_desc
Enhanced Export Analytics (v4.0)
# Code change statistics
/cxq --diff-stats # Lines added/removed across all edits
/cxq --diff-stats --since 2026-01-01 # Diff stats since date
/cxq --diff-stats --json # JSON output for analysis
# Failed/interrupted tool invocations
/cxq --failed-tools # Show failed, interrupted, truncated tools
/cxq --failed-tools --week # From last 7 days
/cxq --failed-tools --json # JSON with full details
# Messages by Claude model (from export metadata)
/cxq --export-models # Group by model/version/tier
Learning & Onboarding
# Complete onboarding overview (progress + badges)
/cxq --onboarding
# Individual learning queries
/cxq --learning-progress # Show module completion status
/cxq --learning-badges # Show earned and available badges
/cxq --learning-modules # List all available modules
/cxq --learning-next # Recommend next module to learn
/cxq --learning-stats # Learning statistics
/cxq --learning-search "agents" # Search learning content
Filtered Search
/cxq "error" --role user # Only user messages
/cxq "async" --code # Only messages with code
/cxq "bug" --today # Only from today
/cxq "deploy" --week # From last 7 days
Browse
/cxq --recent 20 # Last 20 messages
/cxq --recent 10 --role user # Last 10 user messages
/cxq --today # All messages from today
/cxq --sessions # List all sessions
Analysis
/cxq --stats # Database statistics
/cxq --knowledge-stats # Knowledge base statistics
/cxq --longest 10 # 10 longest messages
/cxq --code --limit 20 # Messages with code
/cxq --count --role assistant # Count assistant messages
Database Views (Quick Insights)
# List all available views
/cxq --views
# Query specific views
/cxq --view knowledge_stats # Row counts for all knowledge tables
/cxq --view recent_decisions # High-confidence decisions (7 days)
/cxq --view error_frequency --limit 10 # Top 10 error types
# Shortcut commands (most useful)
/cxq --today-activity # What happened in last 24 hours
/cxq --patterns-summary # Code patterns by language
/cxq --session-summary # Recent session durations
/cxq --component-overview # Components by type/status
/cxq --docs-summary # Documentation by category
/cxq --error-frequency # Most common errors
# JSON output for any view
/cxq --view knowledge_stats --json
/cxq --patterns-summary --json
Comprehensive Entries (All 6 Types)
# View statistics (how many of each entry type)
/cxq --comprehensive-stats
# FTS5 search across ALL entry types
/cxq --search-entries "compaction"
/cxq --search-entries "error" --entry-type system
# Query specific entry types
/cxq --entry-type summary # All summaries
/cxq --entry-type system # System events (compaction, errors)
/cxq --entry-type queue-operation # Command queue history
/cxq --entry-type file-history-snapshot # File backup entries
# Message threading
/cxq --threading # Show all threading relationships
/cxq --thread-from 62a64845-97ca... # Trace thread from UUID
# File backups
/cxq --file-backups # List file backup entries
/cxq --file-backups --file-path "README.md" # Filter by file path
Output
/cxq "query" --full # Show full content
/cxq "query" --json # JSON output
/cxq --stats --json # Stats as JSON
Options
Index Operations
| Option | Description |
|---|---|
--index | Build/update search index from JSONL |
--rebuild | Rebuild index from scratch |
LLM Source Filtering (ADR-122)
| Option | Description |
|---|---|
--llm LLM | Filter by LLM source: claude, codex, gemini |
--by-llm | Show message/token breakdown by LLM source |
--llm-stats | Show LLM source distribution statistics |
--llm-models | Show model distribution per LLM source |
Multi-Database Search (ADR-103)
| Option | Description |
|---|---|
--multi-db | Search ALL 4 databases with RRF fusion |
--scope-framework | Search platform.db + platform-index.db only |
--scope-project UUID | Search specific project in projects.db |
--scope-context | Search org.db + sessions.db only (default behavior) |
Semantic & Knowledge (Anti-Forgetting)
| Option | Description |
|---|---|
--semantic QUERY | Semantic similarity search using embeddings |
--recall QUERY | RAG retrieval: messages + decisions + patterns + errors |
--decisions | List/search extracted decisions |
--decision-type TYPE | Filter: architecture, technology, api, database, testing, deployment, security |
--patterns | List/search code patterns |
--language LANG | Filter patterns by language (py, js, rust, etc.) |
--pattern-type TYPE | Filter: test, async, class, error_handling, database, api, imports |
--errors | List/search error-solution pairs |
--error-type TYPE | Filter errors by type |
--embeddings | Generate embeddings for semantic search |
--extract | Run knowledge extraction (decisions, patterns, errors) |
--knowledge-stats | Show knowledge base statistics |
--threshold N | Similarity threshold for semantic search (0-1, default: 0.3) |
Session Linking
| Option | Description |
|---|---|
--link A B REL | Link sessions (relations: continues, references, supersedes, fixes) |
--links SESSION | Show sessions linked to SESSION |
Learning & Onboarding
| Option | Description |
|---|---|
--onboarding | Show onboarding progress and badges (combined view) |
--learning-progress | Show learning module progress |
--learning-badges | Show earned and available badges |
--learning-modules | List available learning modules |
--learning-next | Recommend next learning module |
--learning-stats | Show learning statistics |
--learning-search QUERY | Search learning content |
Token Accounting (ADR-005)
| Option | Description |
|---|---|
--tokens | Token usage summary (totals from all sessions) |
--cost | Cost analysis with model-specific pricing |
--token-stats | Comprehensive statistics with percentages |
--cache-efficiency | Prompt caching efficiency (hit rate, savings) |
--by-session | Token breakdown by session |
--by-project | Token breakdown by project path |
--by-date | Token breakdown by date |
--by-model | Token breakdown by model |
Query Enhancement (ADR-149 Phase 1)
| Option | Description |
|---|---|
--where EXPR / -W EXPR | SQL-like WHERE expression for filtering (J.4.7.1) |
--group-by FIELDS / -G FIELDS | Group results by fields, comma-separated (J.4.7.2) |
--sort FIELDS / -S FIELDS | Sort results by fields with direction suffix (J.4.7.2) |
WHERE Expression Syntax (J.4.7.1):
- Comparison:
field = value,field > value,field >= value,field < value,field <= value,field != value - String matching:
field LIKE 'pattern%'(% = wildcard) - Boolean:
expr AND expr,expr OR expr - Parentheses:
(expr AND expr) OR expr - Examples:
confidence > 0.8,model_name LIKE 'claude%',cost_total_usd > 0.01 AND model_name = 'claude-opus-4-5'
GROUP BY Syntax (J.4.7.2):
- Fields: comma-separated field names (e.g.,
model_name,session_id) - Time functions:
day,week,month,year,hour(uses default date field) - Explicit time:
field.timefunction(e.g.,created_at.week) - Auto-aggregation: COUNT, SUM, AVG automatically added for numeric fields
SORT Syntax (J.4.7.2):
- Direction suffix:
_asc(ascending),_desc(descending) - Default: descending if no suffix
- Examples:
cost_total_usd_desc,created_at_asc,confidence_desc
Query Type Fields:
| Query Type | Valid Fields |
|---|---|
--tokens | model_name, model_tier, token_input, token_output, cost_total_usd, session_id, created_at |
--tools | tool_name, tool_category, invocation_count, success_count, failure_count, avg_latency_ms |
--decisions | decision_type, confidence, source, created_at |
--errors | error_type, confidence, created_at |
Enhanced Export Analytics (v4.0)
| Option | Description |
|---|---|
--diff-stats | Code change statistics (lines added/removed across edits) |
--failed-tools | Failed, interrupted, or truncated tool invocations |
--export-models | Messages grouped by Claude model from export metadata |
Browse
| Option | Description |
|---|---|
--recent N | Show N recent messages (default: 20) |
--sessions | List unique sessions |
--longest N | Show N longest messages |
--code | Show messages with code |
Database Views (Quick Insights)
| Option | Description |
|---|---|
--views | List all available database views |
--view NAME | Query a specific database view by name |
--today-activity | Show messages, decisions, patterns from last 24 hours |
--error-frequency | Show most common errors with occurrence and success counts |
--patterns-summary | Show code patterns grouped by language |
--session-summary | Show recent session activity with message counts and durations |
--component-overview | Show components grouped by type and status |
--docs-summary | Show documentation counts by category and type |
Comprehensive Entries (All 6 Types) - ADR-025
| Option | Description |
|---|---|
--index-comprehensive | Index ALL 6 entry types from raw sessions |
--rebuild-comprehensive | Rebuild comprehensive index from scratch |
--comprehensive-stats | Show entry counts by type |
--search-entries QUERY | FTS5 search across all comprehensive entries |
--entry-type TYPE | Filter by: user, assistant, system, summary, queue-operation, file-history-snapshot |
--threading | Show message threading relationships (uuid/parent_uuid) |
--thread-from UUID | Trace conversation thread from specific UUID |
--file-backups | List file backup entries |
--file-path PATH | Filter file backups by path |
Date Filters
| Option | Description |
|---|---|
--today | Messages from today |
--week | Messages from last 7 days |
--since DATE | Messages since DATE (YYYY-MM-DD) |
--until DATE | Messages until DATE |
--date DATE | Messages from specific date |
Content Filters
| Option | Description |
|---|---|
--role ROLE | Filter by: user, assistant, tool_use, tool_result |
--source TYPE | Filter by: jsonl, export |
--llm LLM | Filter by LLM source: claude, codex, gemini |
--model MODEL | Filter by specific model (e.g., claude-opus-4-5, o1-pro) |
--session ID | Filter by session ID (partial match) |
--min-length N | Minimum content length |
--max-length N | Maximum content length |
Output Options
| Option | Description |
|---|---|
--limit N | Result limit (default: 20) |
--full | Show full content (no truncation) |
--json | Output as JSON |
--count | Just show count |
Information
| Option | Description |
|---|---|
--stats | Database statistics |
--knowledge-stats | Knowledge base statistics |
--examples | Show detailed examples |
-h, --help | Show help message |
FTS5 Search Syntax
word1 word2 Both words (AND)
word1 OR word2 Either word
"exact phrase" Exact match
word* Prefix match
NEAR(a b, 5) Words within 5 tokens
-word Exclude word
Building the Knowledge Base
# Complete setup workflow:
/export # Export current session
/cx # Extract all + archive exports
/cxq --index # Build search index
/cxq --extract # Extract decisions, patterns, errors
/cxq --embeddings # Generate embeddings (optional, requires sentence-transformers)
Knowledge Base Contents
After running --extract, the database contains:
Decisions
- Types: architecture, technology, api, database, testing, deployment, security, general
- Fields: decision text, rationale, confidence score, timestamps
Code Patterns
- Languages: python, typescript, rust, javascript, bash, sql, etc.
- Types: test, async, class, error_handling, database, api, imports, general
- Fields: pattern name, code, description, usage count
Error Solutions
- Types: Error, TypeError, ValueError, ImportError, etc.
- Fields: error signature, solution, solution code, success count
Anti-Forgetting Workflow
# At session start:
/cxq --recall "current project topic" # Get relevant context
# During work:
/cxq --decisions --decision-type api # Check previous API decisions
/cxq --patterns --language python # Find reusable patterns
/cxq --errors "TypeError" # Find previous error solutions
# At session end:
/export && /cx && /cxq --extract # Preserve this session's knowledge
Related Skills
- token-cost-tracking - Manual logging for any LLM (GPT-4, Gemini, local models)
- Token Accounting (ADR-005) extracts automatically from Claude Code JSONL sessions
- Use
/cxq --tokensfor Claude sessions,token-cost-trackingskill for multi-provider tracking
Success Output
When query executes successfully:
✅ COMMAND COMPLETE: /cxq
Query: "<search-term>"
Results: N matches found
Databases: org.db (Tier 2), sessions.db (Tier 3)
Completion Checklist
Before marking complete:
- Query executed without errors
- Results displayed to user
- Relevant context surfaced
Failure Indicators
This command has FAILED if:
- ❌ Database not found (run
/cxfirst) - ❌ FTS5 index not built (run
/cxq --index) - ❌ Query syntax error
- ❌ No results when results expected
When NOT to Use
Do NOT use when:
- Database doesn't exist yet (use
/cxfirst) - Looking for files (use
Globinstead) - Need real-time data (database is snapshot)
Anti-Patterns (Avoid)
| Anti-Pattern | Problem | Solution |
|---|---|---|
| Query without indexing | Empty results | Run /cxq --index first |
| Too broad queries | Overwhelming results | Add filters like --role, --today |
| Ignoring --recall | Miss related context | Use --recall for comprehensive retrieval |
Principles
This command embodies:
- #1 Recycle, Extend, Re-Use - Leverages past session knowledge
- #9 Based on Facts - Queries actual session data
- #10 Research When in Doubt - Find answers in history
Full Standard: CODITECT-STANDARD-AUTOMATION.md
Required Tools
| Tool | Purpose | Required |
|---|---|---|
Bash | Execute context-query.py script | Yes |
Read | Read context database (for verification) | Optional |
External Requirements:
- Python 3.8+ with sqlite3
- Databases (ADR-118 Four-Tier):
~/PROJECTS/.coditect-data/context-storage/org.db(Tier 2: decisions, skill_learnings, error_solutions)~/PROJECTS/.coditect-data/context-storage/sessions.db(Tier 3: messages, tool_analytics, token_economics)
- Optional:
sentence-transformersfor semantic search
Output Validation
Before marking complete, verify output contains:
- Query executed without errors
- Result count reported
- Results displayed in readable format
- For --semantic/--recall: relevance scores shown
- For --stats: all statistics categories displayed
- For --tokens/--cost: token counts and cost breakdown
Script: scripts/context-query.py (ADR-118 compliant)
Databases (ADR-118 Four-Tier):
context-storage/org.db- TIER 2: Irreplaceable knowledge (decisions, skill_learnings, error_solutions)context-storage/sessions.db- TIER 3: Regenerable session data (messages, tool_analytics, token_economics)context-storage/platform.db- TIER 1: Component data (agents, skills, commands)
Message Schema Fields (ADR-122):
llm_source- LLM provider:claude,codex,geminillm_model- Specific model:claude-opus-4-5,o1-pro,gemini-2.0-flash
Version: 5.11.0 (+ Deprecated context-db.py fallback removed - J.16.5.2) Last Updated: 2026-02-11
Changelog (recent):
- v5.11.0 -
--bus-feed: chronological session activity timeline merging lifecycle + alerts + task + coordination events - v5.10.0 - ADR-173:
--bus-messages,--bus-alerts,--bus-lifecycle,--bus-unread,--bus-stats,--bus-sessionsfor messaging.db queries Related ADRs: ADR-020 (Context Extraction), ADR-021 (Context Query), ADR-025 (Comprehensive Entry Schema), ADR-118 (Four-Tier Database Architecture), ADR-122 (Unified LLM Architecture), ADR-149 (Query Language Evolution Strategy), ADR-154 (Context Graph Query DSL)