Skip to main content

/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:

  1. IMMEDIATELY execute - no questions, no explanations first
  2. ALWAYS show full output from script/tool execution
  3. 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: true in 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

CommandDescription
/cxq "term"Search for term (FTS5)
/cxq -hShow help
/cxq --examplesShow all examples
/cxq --statsDatabase statistics
/cxq --knowledge-statsKnowledge base statistics

LLM Source Filtering (ADR-122)

CommandDescription
/cxq "query" --llm claudeFilter to Claude sessions only
/cxq "query" --llm codexFilter to Codex sessions only
/cxq "query" --llm geminiFilter to Gemini sessions only
/cxq --by-llmToken/message breakdown by LLM source
/cxq --llm-statsLLM source distribution statistics
/cxq --llm-modelsShow model distribution per LLM

Session Log Search (J.32)

CommandDescription
/cxq --session-logs "query"Full-text search session log entries
/cxq --session-log-task IDFind entries by task ID
/cxq --session-log-date DATEFilter by date
/cxq --session-log-recent NN most recent entries
/cxq --session-log-statsIndexing statistics

Anti-Forgetting Features

CommandDescription
/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-helpShow semantic search help and status
/cxq --decisionsList extracted decisions
/cxq --patternsList code patterns
/cxq --errorsList error-solution pairs
/cxq --extractRun knowledge extraction
/cxq --embeddingsGenerate semantic embeddings

Semantic Search Options (J.16.3)

CommandDescription
/cxq --fts-weight WFTS5 weight in hybrid search (default: 0.4)
/cxq --vector-weight WVector weight in hybrid search (default: 0.6)
/cxq --similarity-threshold TMin similarity threshold (default: 0.3)

Learning & Onboarding

CommandDescription
/cxq --onboardingShow onboarding progress + badges
/cxq --learning-progressModule completion status
/cxq --learning-badgesEarned and available badges
/cxq --learning-nextRecommend next module
/cxq --learning-statsLearning statistics

Token Accounting (ADR-005)

CommandDescription
/cxq --tokensToken usage summary
/cxq --costCost analysis with model pricing
/cxq --token-statsComprehensive token statistics
/cxq --cache-efficiencyPrompt caching efficiency metrics
/cxq --by-sessionToken breakdown by session
/cxq --by-projectToken breakdown by project
/cxq --by-dateToken breakdown by date
/cxq --by-modelToken breakdown by model
/cxq --daily-cost-reportComprehensive daily cost report with trends (J.6.4)
/cxq --cost-date YYYY-MM-DDSpecify date for daily report (default: today)
/cxq --cost-trend-days NDays to include in trend analysis (default: 7)
/cxq --optimize-costsGenerate cost optimization recommendations (J.6.5)
/cxq --optimize-days NDays to analyze for optimization (default: 30)
/cxq --budget-alertsCheck spending against configurable budget limits (J.6.6)
/cxq --daily-limit USDDaily spending limit in USD (default: 50)
/cxq --weekly-limit USDWeekly spending limit in USD (default: 250)
/cxq --monthly-limit USDMonthly spending limit in USD (default: 800)
/cxq --opus-limit PCTMax Opus usage percentage threshold (default: 30)

Enhanced Export Analytics (v4.0)

CommandDescription
/cxq --diff-statsCode change statistics (lines added/removed)
/cxq --failed-toolsFailed/interrupted/truncated tool invocations
/cxq --export-modelsMessages grouped by Claude model from exports

Reasoning Traces (J.5 - Agentic Metadata)

CommandDescription
/cxq --tracesShow reasoning trace summary (success rates, confidence, latency)
/cxq --trace-listList recent reasoning traces with visualization
/cxq --trace-id IDShow specific trace by ID with all steps
/cxq --trace-failuresShow failed traces grouped by error type
/cxq --trace-low-confidenceShow traces with low confidence scores
/cxq --trace-confidence-threshold NSet confidence threshold (default: 0.5)
/cxq --trace-tool TOOLFilter traces by tool name (Read, Write, Edit, Bash)
/cxq --trace-status STATUSFilter traces by status (success, failed, interrupted, timeout)
/cxq --failure-patternsDetect recurring failure patterns with recommendations
/cxq --pattern-min-occurrences NMinimum occurrences for pattern detection (default: 2)

Tool Analytics (J.7)

CommandDescription
/cxq --toolsShow tool usage analytics summary
/cxq --tools-by-categoryTool usage grouped by category
/cxq --tool-errorsTool errors and failure rates
/cxq --tool-sequencesDetect common tool usage sequences (J.7.4)
/cxq --sequence-length NNumber of tools in sequence (2-5, default: 3)
/cxq --sequence-min NMinimum occurrences for pattern (default: 3)
/cxq --sequence-window MINMax minutes between tools in sequence (default: 5)

Query Enhancement (ADR-149 Phase 1)

CommandDescription
/cxq --tokens --where "EXPR"Filter with SQL-like WHERE expressions
/cxq --tokens --group-by FIELDSGroup results by fields (supports time functions)
/cxq --tokens --sort FIELDSSort results (append _asc or _desc)
/cxq --decisions --where "confidence > 0.8"Filter decisions by confidence
/cxq --tokens --group-by model_name,weekGroup by model and week
/cxq --tools --group-by tool_name --sort invocation_count_descTool usage ranking

Knowledge Graph Traversal (J.4.7.3)

CommandDescription
/cxq --traversal bfs --start-node NODEBreadth-first traversal from node
/cxq --traversal dfs --start-node NODEDepth-first traversal from node
/cxq --traversal semantic --start-node NODERelevance-scored traversal
/cxq --traversal policy_first --start-node NODEPolicy/ADR-prioritized traversal
/cxq --traversal shortest --start-node A --end-node BFind shortest path between nodes
/cxq --traversal bfs --start-node NODE --traversal-depth 5Custom 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 backtracking
  • semantic - 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)

CommandDescription
/cxq --session-logs "query"Full-text search across session log entries
/cxq --session-log-task TASK_IDFind entries by task ID (e.g., H.13.9)
/cxq --session-log-date YYYY-MM-DDFilter entries by specific date
/cxq --session-log-range FROM TOFilter entries by date range
/cxq --session-log-recent NShow N most recent session log entries
/cxq --session-log-statsSession 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)

CommandDescription
/cxq --context-graphList all stored context graph projections
/cxq --context-graph <ID>Show details for a specific graph (nodes, usage)
/cxq --context-graph <ID> --jsonJSON 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)

CommandDescription
/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-helpShow 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)

CommandDescription
/cxq --correlate "messages,token_economics" --by session_idCorrelate messages with costs
/cxq --correlate "tool_analytics,token_economics" --by session_idTool performance with costs
/cxq --correlate "decisions,messages" --by message_idDecisions with source context
/cxq --correlate cost-by-sessionShortcut: messages × token_economics
/cxq --correlate tool-performanceShortcut: tool_analytics × token_economics
/cxq --correlate-helpShow 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)

CommandDescription
/cxq --bus-messagesList recent session messages from messaging.db
/cxq --bus-messages "query"Search session messages by payload content
/cxq --bus-alertsShow operator alerts (project/task/cwd/file conflicts)
/cxq --bus-lifecycleShow session lifecycle events (started/ended/resumed)
/cxq --bus-unreadShow unread messages for the current session
/cxq --bus-statsShow messaging.db statistics (sessions, messages, locks, claims)
/cxq --bus-sessionsList all sessions (active + historical) from session_registry
/cxq --bus-messages --channel NAMEFilter messages by channel
/cxq --bus-messages --priority NFilter by minimum priority (0-3)
/cxq --bus-messages --since "YYYY-MM-DD"Filter messages since date
/cxq --bus-feedChronological timeline of ALL session activity (lifecycle + alerts + broadcasts + directed)
/cxq --bus-feed --limit NLimit 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 events
  • operator_alert — project_conflict, task_conflict, cwd_overlap, file_conflict
  • task_broadcast — task claim/release/update notifications
  • state — shared state updates
  • coordination — workflow coordination

Priority Levels: 0=routine, 1=normal, 2=high, 3=critical

Query Templates (ADR-154)

CommandDescription
/cxq --queriesList 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-queryCreate new template interactively (J.4.8.5)
/cxq --create-query quickQuick template creation with minimal prompts
/cxq --create-query cloneClone 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)

CommandDescription
/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-helpShow full Boolean syntax help

Operators:

  • AND - Both terms required (implicit between consecutive terms)
  • OR - Either term matches
  • NOT - 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)

CommandDescription
/cxq "query"Search with ranking enabled (default)
/cxq "query" --no-rankDisable ranking (chronological order)
/cxq "query" --show-scoresInclude score breakdown in output
/cxq "query" --rank-weights 0.7,0.2,0.1Custom ranking weights
/cxq --rank-helpShow 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:

SourceBoost
decisions1.5x
skill_learnings1.4x
error_solutions1.3x
patterns1.2x
components1.1x
messages1.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)

CommandDescription
/cxq "query" --by-dayAggregate by day (J.4.6.1)
/cxq "query" --by-weekAggregate by ISO week
/cxq "query" --by-monthAggregate by month
/cxq "query" --by-yearAggregate by year
/cxq "query" --topicsCluster by topic keywords (J.4.6.2)
/cxq --recent 500 --trendingShow trending topics (J.4.6.3)
/cxq --aggregation-helpShow 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)

CommandDescription
/cxq "query" --multi-dbSearch ALL 4 databases with RRF merging
/cxq "query" --scope-frameworkSearch framework only (platform.db + platform-index.db)
/cxq "query" --scope-project UUIDSearch specific project only (projects.db)
/cxq "query" --scope-contextSearch context only (org.db + sessions.db) - default

Component Search (Self-Awareness) - Queries platform.db (ADR-080)

CommandDescription
/cxq --componentsList indexed components
/cxq --components "query"Search components by keyword (FTS5)
/cxq --component-semantic "intent"Semantic search by intent
/cxq --component-type TYPEFilter by type (agent, command, skill, script, hook, workflow)
/cxq --show-component IDShow detailed component info
/cxq --component-statsComponent index statistics
/cxq --component-embeddingsGenerate semantic embeddings
/cxq --component-embedding-statsEmbedding coverage statistics
/cxq --component-threshold NSimilarity threshold (0-1, default: 0.3)

Browse

CommandDescription
/cxq --recent 20Last 20 messages
/cxq --sessionsList sessions
/cxq --longest 1010 longest messages
/cxq --codeMessages with code
/cxq --todayMessages from today

Database Views (Quick Insights)

CommandDescription
/cxq --viewsList all available database views (18 total)
/cxq --view NAMEQuery a specific view (e.g., --view knowledge_stats)
/cxq --today-activityMessages, decisions, patterns from last 24 hours
/cxq --error-frequencyMost common errors with success counts
/cxq --patterns-summaryCode patterns grouped by language
/cxq --session-summaryRecent session activity and durations
/cxq --component-overviewComponents by type and status
/cxq --docs-summaryDocumentation by category

Comprehensive Entries (All 6 Types) - ADR-025

CommandDescription
/cxq --index-comprehensiveIndex ALL 6 entry types from raw sessions
/cxq --rebuild-comprehensiveRebuild comprehensive index from scratch
/cxq --comprehensive-statsShow entry counts by type
/cxq --search-entries "query"FTS5 search across all entry types
/cxq --entry-type TYPEFilter by entry type (user, assistant, system, summary, queue-operation, file-history-snapshot)
/cxq --threadingShow message threading relationships
/cxq --thread-from UUIDTrace conversation thread from UUID
/cxq --file-backupsList 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
/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
/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

OptionDescription
--indexBuild/update search index from JSONL
--rebuildRebuild index from scratch

LLM Source Filtering (ADR-122)

OptionDescription
--llm LLMFilter by LLM source: claude, codex, gemini
--by-llmShow message/token breakdown by LLM source
--llm-statsShow LLM source distribution statistics
--llm-modelsShow model distribution per LLM source

Multi-Database Search (ADR-103)

OptionDescription
--multi-dbSearch ALL 4 databases with RRF fusion
--scope-frameworkSearch platform.db + platform-index.db only
--scope-project UUIDSearch specific project in projects.db
--scope-contextSearch org.db + sessions.db only (default behavior)

Semantic & Knowledge (Anti-Forgetting)

OptionDescription
--semantic QUERYSemantic similarity search using embeddings
--recall QUERYRAG retrieval: messages + decisions + patterns + errors
--decisionsList/search extracted decisions
--decision-type TYPEFilter: architecture, technology, api, database, testing, deployment, security
--patternsList/search code patterns
--language LANGFilter patterns by language (py, js, rust, etc.)
--pattern-type TYPEFilter: test, async, class, error_handling, database, api, imports
--errorsList/search error-solution pairs
--error-type TYPEFilter errors by type
--embeddingsGenerate embeddings for semantic search
--extractRun knowledge extraction (decisions, patterns, errors)
--knowledge-statsShow knowledge base statistics
--threshold NSimilarity threshold for semantic search (0-1, default: 0.3)

Session Linking

OptionDescription
--link A B RELLink sessions (relations: continues, references, supersedes, fixes)
--links SESSIONShow sessions linked to SESSION

Learning & Onboarding

OptionDescription
--onboardingShow onboarding progress and badges (combined view)
--learning-progressShow learning module progress
--learning-badgesShow earned and available badges
--learning-modulesList available learning modules
--learning-nextRecommend next learning module
--learning-statsShow learning statistics
--learning-search QUERYSearch learning content

Token Accounting (ADR-005)

OptionDescription
--tokensToken usage summary (totals from all sessions)
--costCost analysis with model-specific pricing
--token-statsComprehensive statistics with percentages
--cache-efficiencyPrompt caching efficiency (hit rate, savings)
--by-sessionToken breakdown by session
--by-projectToken breakdown by project path
--by-dateToken breakdown by date
--by-modelToken breakdown by model

Query Enhancement (ADR-149 Phase 1)

OptionDescription
--where EXPR / -W EXPRSQL-like WHERE expression for filtering (J.4.7.1)
--group-by FIELDS / -G FIELDSGroup results by fields, comma-separated (J.4.7.2)
--sort FIELDS / -S FIELDSSort 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 TypeValid Fields
--tokensmodel_name, model_tier, token_input, token_output, cost_total_usd, session_id, created_at
--toolstool_name, tool_category, invocation_count, success_count, failure_count, avg_latency_ms
--decisionsdecision_type, confidence, source, created_at
--errorserror_type, confidence, created_at

Enhanced Export Analytics (v4.0)

OptionDescription
--diff-statsCode change statistics (lines added/removed across edits)
--failed-toolsFailed, interrupted, or truncated tool invocations
--export-modelsMessages grouped by Claude model from export metadata

Browse

OptionDescription
--recent NShow N recent messages (default: 20)
--sessionsList unique sessions
--longest NShow N longest messages
--codeShow messages with code

Database Views (Quick Insights)

OptionDescription
--viewsList all available database views
--view NAMEQuery a specific database view by name
--today-activityShow messages, decisions, patterns from last 24 hours
--error-frequencyShow most common errors with occurrence and success counts
--patterns-summaryShow code patterns grouped by language
--session-summaryShow recent session activity with message counts and durations
--component-overviewShow components grouped by type and status
--docs-summaryShow documentation counts by category and type

Comprehensive Entries (All 6 Types) - ADR-025

OptionDescription
--index-comprehensiveIndex ALL 6 entry types from raw sessions
--rebuild-comprehensiveRebuild comprehensive index from scratch
--comprehensive-statsShow entry counts by type
--search-entries QUERYFTS5 search across all comprehensive entries
--entry-type TYPEFilter by: user, assistant, system, summary, queue-operation, file-history-snapshot
--threadingShow message threading relationships (uuid/parent_uuid)
--thread-from UUIDTrace conversation thread from specific UUID
--file-backupsList file backup entries
--file-path PATHFilter file backups by path

Date Filters

OptionDescription
--todayMessages from today
--weekMessages from last 7 days
--since DATEMessages since DATE (YYYY-MM-DD)
--until DATEMessages until DATE
--date DATEMessages from specific date

Content Filters

OptionDescription
--role ROLEFilter by: user, assistant, tool_use, tool_result
--source TYPEFilter by: jsonl, export
--llm LLMFilter by LLM source: claude, codex, gemini
--model MODELFilter by specific model (e.g., claude-opus-4-5, o1-pro)
--session IDFilter by session ID (partial match)
--min-length NMinimum content length
--max-length NMaximum content length

Output Options

OptionDescription
--limit NResult limit (default: 20)
--fullShow full content (no truncation)
--jsonOutput as JSON
--countJust show count

Information

OptionDescription
--statsDatabase statistics
--knowledge-statsKnowledge base statistics
--examplesShow detailed examples
-h, --helpShow 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

  • 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 --tokens for Claude sessions, token-cost-tracking skill 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 /cx first)
  • ❌ 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 /cx first)
  • Looking for files (use Glob instead)
  • Need real-time data (database is snapshot)

Anti-Patterns (Avoid)

Anti-PatternProblemSolution
Query without indexingEmpty resultsRun /cxq --index first
Too broad queriesOverwhelming resultsAdd filters like --role, --today
Ignoring --recallMiss related contextUse --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

ToolPurposeRequired
BashExecute context-query.py scriptYes
ReadRead 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-transformers for 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, gemini
  • llm_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-sessions for 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)