
Qodo Get Rules
- 2.2k installs
- 44 repo stars
- Updated August 2, 2026
- qodo-ai/qodo-skills
qodo-get-rules retrieves ranked Qodo coding rules via semantic search for the current coding task.
About
Qodo Get Rules loads the most relevant coding rules for the current task by generating structured semantic search queries and calling POST /rules/search. Skip when Qodo Rules Loaded already appears in context. Workflow verifies a git repository, derives optional repository scope from origin URL and modules path, reads API key and environment from ~/.qodo/config.json, then issues two structured queries: a topic query on the primary concern and a cross-cutting quality query. Each query uses Name, Category, and Content lines matching the rule embedding format, not keyword lists. Results merge with deduplication by rule ID, topic results prioritized, then print with severity labels. ERROR rules are mandatory, WARNING should comply, and RECOMMENDATION is optional. Apply rules during code generation and report which were followed or skipped with reasons.
- Skips when Qodo Rules Loaded already appears in conversation context.
- Derives optional repo scope from git remote and modules path for narrower search.
- Uses two structured Name Category Content queries, not flat keyword lists.
- Merges parallel search results deduplicating by rule ID with topic priority.
- Enforces ERROR WARNING RECOMMENDATION severity during code application.
Qodo Get Rules by the numbers
- 2,210 all-time installs (skills.sh)
- +17 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #71 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
qodo-get-rules capabilities & compatibility
- Capabilities
- git repo and scope detection · structured dual query semantic search · rule merge and deduplication · severity based enforcement reporting · graceful missing config handling
- Works with
- github · gitlab · bitbucket
- Use cases
- code review · refactoring · api development
- Runs
- Hosted SaaS
- Pricing
- Freemium
npx skills add https://github.com/qodo-ai/qodo-skills --skill qodo-get-rulesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.2k |
|---|---|
| repo stars | ★ 44 |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | qodo-ai/qodo-skills ↗ |
What Qodo coding rules apply before I implement or refactor this change?
Fetch semantically relevant Qodo coding rules for the current task via structured POST /rules/search queries.
Who is it for?
Teams with Qodo configured who want relevant standards before coding.
Skip if: Skip when rules are already loaded or Qodo API key is missing.
When should I use this skill?
User starts coding, refactoring, or explicitly asks to load Qodo rules.
What you get
Ranked rules printed with severity labels and applied during code generation.
- Ranked rules list
- Severity-tagged standards block
By the numbers
- Rules use 3 severity levels: ERROR, WARNING, RECOMMENDATION
Files
Get Qodo Rules Skill
Description
Fetches the most relevant Qodo coding rules for the current coding task. Generates a focused semantic search query from the coding assignment and calls POST /rules/search to retrieve only the rules most relevant to the task at hand, ranked by relevance.
Skip if "Qodo Rules Loaded" already appears in conversation context.
---
Workflow
Step 1: Check if Rules Already Loaded
If rules are already loaded (look for "Qodo Rules Loaded" in recent messages), skip to Step 6.
Step 2: Verify Working in a Git Repository and Detect Repository Scope
Check that the current directory is inside a git repository. If not, inform the user that a git repository is required and exit gracefully.
After confirming a git repository exists, extract the repository scope to pass to the search API. Scope narrows results to rules relevant to this specific repository.
# 1. Confirm inside a git repository
git rev-parse --is-inside-work-tree
# 2. Get the remote URL
REMOTE_URL=$(git remote get-url origin 2>/dev/null)
# 3. Parse the URL into a scope path
if [ -n "$REMOTE_URL" ]; then
# Strip .git suffix if present
REMOTE_URL="${REMOTE_URL%.git}"
# Handle SSH format: git@github.com:org/repo
if echo "$REMOTE_URL" | grep -q "^git@"; then
REPO_PATH=$(echo "$REMOTE_URL" | sed 's/^git@[^:]*://')
# Handle HTTPS format: https://github.com/org/repo
elif echo "$REMOTE_URL" | grep -q "^https\?://"; then
REPO_PATH=$(echo "$REMOTE_URL" | sed 's|^https\?://[^/]*/||')
else
REPO_PATH=""
fi
if [ -n "$REPO_PATH" ]; then
# 4. Detect module-level scope: check if cwd is inside modules/<name>/
REPO_ROOT=$(git rev-parse --show-toplevel)
REL_PATH=$(realpath --relative-to="$REPO_ROOT" "$(pwd)" 2>/dev/null || python3 -c "import os; print(os.path.relpath('$(pwd)', '$REPO_ROOT'))")
MODULE=$(echo "$REL_PATH" | sed -n 's|^modules/\([^/]*\).*|\1|p')
if [ -n "$MODULE" ]; then
SCOPE="/${REPO_PATH}/modules/${MODULE}/"
else
SCOPE="/${REPO_PATH}/"
fi
fi
fi
# If SCOPE is empty (no remote, unparseable URL), proceed without scope — graceful degradationPass SCOPE in the search request body if set (see Step 5). If SCOPE is empty or unset, omit the scopes field entirely and proceed — org-wide search still returns relevant results.
See repository scope detection for URL format details and degradation behavior.
Step 3: Verify Qodo Configuration
Check that the required Qodo configuration is present. The default location is ~/.qodo/config.json.
- API key: Read from
~/.qodo/config.json(API_KEYfield). Environment variableQODO_API_KEYtakes precedence. If not found, inform the user that an API key is required and provide setup instructions, then exit gracefully. - Environment name: Read from
~/.qodo/config.json(ENVIRONMENT_NAMEfield), withQODO_ENVIRONMENT_NAMEenvironment variable taking precedence. If not found or empty, use production. - API URL override (optional): Read from
~/.qodo/config.json(QODO_API_URLfield). If present, use{QODO_API_URL}/rules/v1as the API base URL. If absent, theENVIRONMENT_NAME-based URL is used. - Request ID: Generate a UUID (e.g.
python3 -c "import uuid; print(uuid.uuid4())") to use asrequest-idfor all API calls in this invocation.
Example config parsing:
API_KEY=$(python3 -c "import json,os; c=json.load(open(os.path.expanduser('~/.qodo/config.json'))); print(c['API_KEY'])")
ENV_NAME=$(python3 -c "import json,os; c=json.load(open(os.path.expanduser('~/.qodo/config.json'))); print(c.get('ENVIRONMENT_NAME',''))")
QODO_API_URL=$(python3 -c "import json,os; c=json.load(open(os.path.expanduser('~/.qodo/config.json'))); print(c.get('QODO_API_URL',''))")
REQUEST_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
# Determine API_URL: QODO_API_URL takes precedence over ENVIRONMENT_NAME
if [ -n "$QODO_API_URL" ]; then
API_URL="${QODO_API_URL}/rules/v1"
elif [ -z "$ENV_NAME" ]; then
API_URL="https://qodo-platform.qodo.ai/rules/v1"
else
API_URL="https://qodo-platform.${ENV_NAME}.qodo.ai/rules/v1"
fiStep 4: Generate Structured Search Queries from Coding Assignment
Generate two structured search queries that mirror the rule embedding format. Query quality directly determines retrieval quality.
Each query must use this exact three-line structure:
Name: {concise 5-10 word title of the rule this task would trigger}
Category: {one of: Security, Correctness, Quality, Reliability, Performance, Testability, Compliance, Accessibility, Observability, Architecture}
Content: {1-2 sentences describing what should be checked or enforced}Query 1 (Topic query): Focused on the coding assignment's primary concern. Pick the most relevant Category and describe the specific check in Content. When the repository's tech stack is known, mention it in the Content field.
Query 2 (Cross-cutting query): Targets recurring quality and standards patterns that apply to most code changes. Choose Category based on the org's rule emphasis (Security, Compliance, Observability, or Architecture as default). Include concerns like module structure, type annotations, structured logging, and repository patterns in Content.
Do not write keyword lists or flat sentences — they perform poorly with the embedding model.
See query generation guidelines for the full strategy, category selection rules, and examples.
Step 5: Call POST /rules/search
Call the search endpoint once per query (topic query and cross-cutting query), each with the configured TOP_K value (default: 20 — see search endpoint for tuning guidance). When parallel execution is available, run both calls in parallel. Merge results, deduplicating by rule ID. Topic query results take priority.
Include scopes in the request body if SCOPE was detected in Step 2. If SCOPE is empty, omit the field entirely — do not send "scopes": null or "scopes": [].
See search endpoint for the full request/response contract, URL construction, scopes field usage, and error handling.
Step 6: Format and Output Rules
Print the "📋 Qodo Rules Loaded" header and list rules in relevance order with severity as a label per rule.
See output format for the exact format.
Step 7: Apply Rules by Severity
Apply all returned rules to the coding task. Rules are ranked by relevance — apply all returned rules based on their severity:
| Severity | Enforcement | When Skipped |
|---|---|---|
| ERROR | Must comply, non-negotiable. Add a comment documenting compliance (e.g., # Following Qodo rule: No Hardcoded Credentials) | Explain to user and ask for guidance |
| WARNING | Should comply by default | Briefly explain why in response |
| RECOMMENDATION | Consider when appropriate | No action needed |
Step 8: Report
After code generation, inform the user about rule application:
- Rules applied: List which rules were followed and their severity
- WARNING rules skipped: Explain why
- No applicable rules: Inform: "No Qodo rules were applicable to this code change"
- RECOMMENDATION rules: Mention only if they influenced a design decision
---
Configuration
See README.md for full configuration instructions, including API key setup and environment variable options.
---
Common Mistakes
- Re-running when rules are loaded - Check for "Qodo Rules Loaded" in context first
- Wrong query format - Write queries using the structured Name/Category/Content format, not keyword lists or flat sentences
- Single query only - Always generate both a topic query and a cross-cutting query; a single topic query misses cross-cutting rules
- Vague query - The query must capture the nature of the task; generic Name or Content returns irrelevant rules
- Crashing on empty results - An empty rules list is valid; proceed without rule constraints
- Not in git repo - Inform the user that a git repository is required and exit gracefully
- No API key - Inform the user with setup instructions; set
QODO_API_KEYor create~/.qodo/config.json - Missing compliance comments on ERROR rules - ERROR rules require a comment documenting compliance
Formatting and Outputting Rules
Output Structure
Print the following header:
# 📋 Qodo Rules Loaded
Search queries: `{TOPIC_QUERY_NAME}` + `{CROSS_CUTTING_QUERY_NAME}`
Rules loaded: **{TOTAL_RULES}** (ranked by relevance to your task)
These rules must be applied during code generation based on severity:Rules List
List rules in the order returned (ranked by relevance — most relevant first). Each rule uses this format:
- **{name}** [{SEVERITY}]: {content}Where {SEVERITY} is one of: ERROR, WARNING, or RECOMMENDATION.
Example:
- **No Hardcoded Credentials** [ERROR]: Credentials, API keys, and tokens must not appear in source code; use environment variables or a secrets manager instead.
- **Structured Logging Required** [WARNING]: All log statements must use structured logging with key-value pairs; avoid string interpolation in log messages.
- **Repository Pattern** [RECOMMENDATION]: Service layer should delegate data access to a dedicated repository class rather than calling the ORM directly.Empty Result
If no rules were returned, output:
# 📋 Qodo Rules Loaded
No relevant rules found for this task. Proceeding without rule constraints.
---Do not crash or error — an empty result is valid.
Closing Separator
End all output (rules found or not) with ---.
Query Generation Guidelines
The search query is the most important input to the /rules/search endpoint. A well-formed query retrieves rules that are genuinely applicable to the task; a generic query returns irrelevant or noisy rules.
Strategy
The search uses embedding-based retrieval where every rule is indexed as a vector of:
Name: {rule name}
Category: {rule category}
Content: {rule content}To maximize semantic alignment between the query and the stored rule vectors, the search query must mirror this exact structure. A structured query aligns on all three dimensions (name, category, content) rather than collapsing the signal into a single sentence.
Field guidelines
- Name: Think of it as "what rule would apply here?" Write a concise 5-10 word title describing the rule this coding assignment would trigger.
- Category: Choose the single most relevant category from the available values:
Security— authentication, authorization, injection, secrets, encryption, token validation, access control, privilege escalation, CSRF, XSSCorrectness— logic errors, null handling, off-by-one, type safety, incorrect computation, wrong conditional, missing guard, data corruptionQuality— code style, naming, readability, maintainability, dead code, code duplication, comment quality, magic numbers, overly complex logic, formattingReliability— error handling, retries, graceful degradation, timeouts, circuit breakers, fault tolerance, service availability, idempotency, recoveryPerformance— latency, caching, memory, query optimization, batching, N+1 queries, connection pooling, unnecessary computation, scalabilityTestability— test coverage, mocking, test structure, assertions, test isolation, test data, parameterized tests, fixture managementCompliance— licensing, regulatory, data retention, audit trails, GDPR, PII handling, data classification, policy enforcementAccessibility— WCAG, ARIA, screen readers, keyboard navigation, color contrast, focus management, semantic HTMLObservability— logging, metrics, tracing, alerting, monitoring, instrumentation, dashboards, distributed tracing, log levels, error reportingArchitecture— layering, coupling, module boundaries, API design, dependency direction, separation of concerns, package structure, interface design, service decomposition, domain modeling
Tie-breaking: When an assignment spans multiple categories, prefer Security if security is one of the candidates (security rules have the highest impact if missed). Otherwise prefer the category that describes the primary purpose of the change, not a secondary effect. For example, "add rate limiting" is primarily Reliability (protecting availability), not Security, even though it has security benefits. The cross-cutting query will cover the other dimensions.
Avoiding over-use of Correctness: The heuristic classifier defaults to Correctness for a disproportionate share of tasks. Before selecting Correctness, consider whether a more specific category better describes the primary purpose:
- Structural changes (new modules, refactors, layer reorganization) → prefer
Architecture - Code style, naming, or readability improvements → prefer
Quality - Availability, fault tolerance, or error recovery work → prefer
Reliability - Instrumentation, logging, or monitoring additions → prefer
Observability - Speed or resource efficiency improvements → prefer
Performance
Use Correctness when the task is genuinely about fixing a logic error, ensuring type safety, or preventing incorrect computation — not as a generic catch-all. If LLM-based classification is available, prefer it over keyword heuristics for ambiguous cases.
- Content: 1-2 sentences (aim for at least 15 words) describing what specifically should be checked or enforced for this coding assignment. When the coding assignment is in a known repository with established patterns, mention the relevant tech stack in the Content field — this helps the embedding model align with rules that reference specific technologies. Even for ambiguous assignments, expand the Content with general concerns (e.g., error handling, input validation) to provide enough semantic signal.
Broadening Content for weak domains: Some domains have sparser rule coverage in a given organization's rule set. When a topic query returns fewer than 3 rules, or when the assignment involves a domain that the organization's rules may not address directly, expand the Content field with semantically adjacent concepts to improve retrieval.
To identify adjacent concepts, ask: What broader category does this task touch? What common patterns or concerns appear in code that does this kind of work?
Examples by domain (for illustration — your org's sparse domains may differ):
| Domain | Adjacent concepts to include in Content |
|---|---|
| Auth / JWT / OAuth | token validation, credential handling, session management, authorization headers, access control |
| Async / concurrency | event loop, task management, concurrent execution, thread safety, resource cleanup |
| Rate limiting / throttling | request quotas, backpressure, abuse prevention, middleware, circuit breaking |
| Data migration | schema changes, rollback safety, backward compatibility, data integrity |
| Frontend form validation | input sanitization, client-side validation, accessibility requirements, error state handling |
| Database access patterns | query optimization, connection management, transaction handling, ORM conventions |
The goal is to give the embedding model a richer surface to align against — not to make the query generic, but to ensure that closely related rules surface even when the exact terminology differs. Adjust based on your organization's actual rule coverage.
Query Format
Write the query as a structured three-line block matching the rule embedding format:
Name: {concise title of the rule this coding assignment would trigger}
Category: {most relevant RuleCategory value}
Content: {what specifically should be checked or enforced for this assignment}Do not write keyword-style queries (e.g., authentication login JWT token Python).
Do not write flat natural language sentences. The embedding model aligns better when the query mirrors the indexed structure.
Do not include filler words like "please", "I need to", or other padding that dilutes the semantic signal.
Multi-Query Strategy
Generate two queries per coding assignment for best coverage:
1. Topic query -- a structured query focused on the assignment's primary concern (the standard approach described above). 2. Cross-cutting query -- a supplementary query targeting recurring quality and standards rules that apply to most code changes regardless of topic.
Why two queries? Evaluation data shows that cross-cutting rules (module structure, structured logging, type annotations, repository pattern) account for 60%+ of rules flagged in real code reviews. A single topic-focused query systematically misses these because they are semantically distant from the PR's specific subject.
Cross-cutting query — Category selection:
Choose the Category for the cross-cutting query based on the organization's rule set emphasis when that is known:
- If the org's rules are primarily about code structure, layering, or module design → use
Architecture - If the org's rules are primarily about security requirements applied everywhere → use
Security - If the org's rules include mandatory compliance or audit requirements → use
Compliance - If the org's rules focus on observability standards applied to all code → use
Observability - If the org's rule emphasis is unknown → default to
Architecture(a reasonable fallback for most backend codebases)
The goal is to retrieve the category of rules that the org applies broadly, not just rules that are topically aligned with the PR.
Cross-cutting query — Content:
When the organization's rule set emphasis is known, tailor the cross-cutting Content to reflect the categories of rules the organization enforces broadly:
- A security-focused org: include secure coding baseline (input validation, safe dependencies, secret handling)
- A compliance-focused org: include audit trail, data classification, policy enforcement
- A quality-focused org: include naming, dead code, test coverage, documentation
- A performance-focused org: include query efficiency, caching, resource management
If the org's emphasis is unknown, use the generic default template. The goal is for the cross-cutting query to retrieve the rules that apply to all of the org's code changes, regardless of PR topic.
Cross-cutting query default template:
Name: Code Quality and Standards Compliance
Category: Architecture
Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventionsAdjust the Content field to reflect the repository's tech stack and the organization's rule emphasis when known.
Call the search endpoint once per query (each with the configured TOP_K value) and merge the results, deduplicating by rule ID.
Low-return fallback: If the topic query returns fewer than 3 rules, do not silently accept the sparse result. Re-generate the topic query with a broader Content field by including adjacent concepts for the domain (see the "Broadening Content for weak domains" table above). Then call the endpoint again with the broadened query before merging with cross-cutting results. Note: the threshold is count-based — use it as a trigger, not a hard guarantee of quality. Apply judgment on the semantic fit of returned rules; a sparse but highly relevant set may be preferable to a broader query that surfaces loosely related rules.
Cross-cutting false positives: The cross-cutting query intentionally casts a wide net. Some rules will surface frequently across many different code changes — these are typically your organization's broadest quality or standards rules that the org considers universally applicable. This is expected. Use cross-cutting results as supplementary context; rely on the topic query for task-specific guidance. When the merged result set feels too noisy for a particular assignment, deprioritize cross-cutting results that are semantically distant from the coding task.
Examples
| Coding Assignment | Topic Query | Cross-Cutting Query |
|---|---|---|
| Add a login endpoint that accepts username and password, validates credentials, and returns a JWT token | Name: JWT Authentication Endpoint Validation<br>Category: Security<br>Content: Implementing a login endpoint that validates user credentials against the database and issues JWT tokens securely | Name: Code Quality and Security Standards<br>Category: Security<br>Content: Token validation, credential handling, secure session management, input sanitization, and access control requirements applied broadly across all endpoints |
| Refactor the user service to use async/await instead of callbacks | Name: Async Await Migration Pattern<br>Category: Quality<br>Content: Refactoring a service layer from callback-based concurrency to async/await, ensuring correct error propagation and resource cleanup | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Fix a SQL injection vulnerability in the search query builder | Name: SQL Injection Prevention<br>Category: Security<br>Content: Sanitizing user input in the database query builder to prevent SQL injection attacks through parameterized queries | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Add unit tests for the payment processing module | Name: Payment Processing Test Coverage<br>Category: Testability<br>Content: Adding unit tests for the payment processing module with mocked external payment gateway services | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Implement a rate limiter middleware for the API | Name: Rate Limiting Enforcement<br>Category: Reliability<br>Content: Implementing rate limiting middleware to throttle HTTP API requests and protect against abuse | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Add error handling to the file upload handler | Name: File Upload Error Handling<br>Category: Reliability<br>Content: Adding structured error handling and exception management to the file upload handler for graceful failure recovery | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Optimize the dashboard query that takes 5 seconds to load | Name: Database Query Performance Optimization<br>Category: Performance<br>Content: Optimizing slow database queries for the dashboard view through indexing, query restructuring, or caching | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Add ARIA labels to the navigation menu _(TypeScript React)_ | Name: Navigation Accessibility Labels<br>Category: Accessibility<br>Content: Adding ARIA attributes and roles to the navigation menu to ensure screen reader compatibility and keyboard navigation | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: React component structure, TypeScript strict type checking, consistent naming conventions, proper prop typing, and component test coverage |
| Add a new user management module with CRUD endpoints | Name: Module Structure and Layer Boundaries<br>Category: Architecture<br>Content: Creating a new module with proper directory structure, service layer, repository pattern, and dependency injection | Name: Code Quality and Standards Compliance<br>Category: Architecture<br>Content: Module directory structure, type annotations or type safety, structured logging, repository or service layer patterns, dependency injection, and naming conventions |
| Add logging to the payment processing pipeline _(Go microservice)_ | Name: Structured Logging Implementation<br>Category: Observability<br>Content: Adding structured logging with contextual fields and appropriate log levels to the payment processing pipeline | Name: Code Quality and Architecture Standards<br>Category: Architecture<br>Content: Go package structure, interface-based dependency injection, structured logging with contextual fields, error wrapping conventions, and consistent handler patterns |
| Add a GDPR data deletion endpoint _(Java Spring)_ | Name: GDPR Data Deletion Compliance<br>Category: Compliance<br>Content: Implementing a data deletion endpoint that enforces data retention policies, logs audit trails, and handles PII according to GDPR requirements | Name: Code Quality and Compliance Standards<br>Category: Compliance<br>Content: Data retention policy enforcement, audit trail logging, PII handling requirements, Spring service layer conventions, and exception handling standards |
| Add JWT authentication to the API _(Node.js Express)_ | Name: JWT Authentication Middleware<br>Category: Security<br>Content: Implementing JWT token validation and authentication middleware in an Express API with secure credential handling | Name: Code Quality and Security Standards<br>Category: Security<br>Content: Token validation, credential handling, secure session management, Express middleware conventions, and input sanitization requirements |
Approach: Start from the Coding Assignment
1. Read the coding assignment and identify the core concern -- what rule would a reviewer look for? 2. Write that as a concise Name (5-10 words) 3. Pick the single best Category from the list above 4. Write 1-2 sentences for Content describing what should be checked or enforced; include tech stack details when the repository context is known 5. Assemble the three-line structured topic query 6. Generate the cross-cutting query: choose the Category based on the org's rule emphasis (or default to Architecture), and tailor the Content to reflect what the org enforces broadly 7. Call the search endpoint with both queries (top_k=20 each), merge and deduplicate results
Fallback
If the coding assignment is very short or ambiguous (e.g., "fix the bug"), use the assignment text as the Name field, pick the closest Category (default to Correctness when truly ambiguous -- the cross-cutting query already covers Architecture, so using a different category for the topic query maximizes category diversity), and write a brief Content line restating the assignment with at least 15 words. Still generate the cross-cutting query alongside it. A short structured query is better than an invented one.
Repository Scope Detection
The skill detects the repository scope from the git origin remote URL and passes it to the search API as the scopes field. This narrows results to rules that are relevant to the specific repository, improving retrieval precision.
Git Repository Check
# Must be inside a git repository
git rev-parse --is-inside-work-treeExit code is non-zero (128) if not in a git repository. If not in a git repo, inform the user and exit gracefully.
Scope Extraction
After confirming a git repository, extract the scope from the origin remote:
REMOTE_URL=$(git remote get-url origin 2>/dev/null)URL Format Handling
| Remote format | Example | Parsed REPO_PATH |
|---|---|---|
| HTTPS | https://github.com/org/repo.git | org/repo |
| SSH | git@github.com:org/repo.git | org/repo |
The .git suffix is stripped before parsing. The resulting scope path is /org/repo/.
Module-Level Scope
If the current working directory is inside a modules/<name>/ subdirectory of the repository root, the scope is narrowed to that module:
/org/repo/modules/<name>/Otherwise the repository-wide scope /org/repo/ is used.
Detection:
REPO_ROOT=$(git rev-parse --show-toplevel)
REL_PATH=$(realpath --relative-to="$REPO_ROOT" "$(pwd)" 2>/dev/null \
|| python3 -c "import os; print(os.path.relpath('$(pwd)', '$REPO_ROOT'))")
MODULE=$(echo "$REL_PATH" | sed -n 's|^modules/\([^/]*\).*|\1|p')
if [ -n "$MODULE" ]; then
SCOPE="/${REPO_PATH}/modules/${MODULE}/"
else
SCOPE="/${REPO_PATH}/"
fiGraceful Degradation
Scope is optional. If scope cannot be determined for any reason, the skill proceeds without it — org-wide semantic search still returns relevant results.
Skip scope and proceed without error when:
- No
originremote is configured - Remote URL cannot be parsed into an org/repo path
- Any other unexpected failure during extraction
Do not send "scopes": null or "scopes": [] — omit the scopes field entirely from the request body.
POST /rules/search Endpoint
Request
POST {API_URL}/rules/search
Content-Type: application/json
Authorization: Bearer {API_KEY}
request-id: {REQUEST_ID}
qodo-client-type: skill-qodo-get-rulesBody:
{
"query": "<generated search query>",
"top_k": 20,
"scopes": ["/org/repo/"]
}scopes is optional. It is omitted when the repository scope cannot be determined (no git remote, unparseable URL). When omitted, the search falls back to org-wide matching. Do not send "scopes": null or "scopes": [] — omit the field entirely.
`TOP_K` (tunable constant): The number of results to request per query. Default: 20. The skill generates two queries (topic + cross-cutting) and calls this endpoint once per query, each with top_k=TOP_K. Results are merged and deduplicated by rule ID — the final count depends on overlap between the two result sets.
Increase TOP_K if retrieval quality data shows relevant rules are being missed. No pagination is needed regardless of the value — the search endpoint returns up to top_k results in a single response.
Merge strategy: When merging topic and cross-cutting results: 1. Start with topic query results (in order of relevance). 2. Append cross-cutting results not already present, in order of relevance.
Topic results always take priority, ensuring task-specific rules are never pushed out by cross-cutting results.
Response
{
"rules": [
{ "id": "...", "name": "...", "content": "...", "severity": "..." },
...
]
}Rules are returned ranked by relevance (most relevant first). The list may be empty if no matching rules exist — this is a valid response; do not treat it as an error.
API URL Construction
Construct {API_URL} using the following priority:
1. `QODO_API_URL` in config (highest priority): If QODO_API_URL is present in ~/.qodo/config.json, use {QODO_API_URL}/rules/v1 as the full API URL. The /rules/v1 path is always appended internally — do not include it in the config value.
2. `ENVIRONMENT_NAME`-based construction (fallback): If QODO_API_URL is not set, construct from ENVIRONMENT_NAME (read from ~/.qodo/config.json, overridable via QODO_ENVIRONMENT_NAME env var):
ENVIRONMENT_NAME | {API_URL} |
|---|---|
| not set / empty | https://qodo-platform.qodo.ai/rules/v1 |
staging | https://qodo-platform.staging.qodo.ai/rules/v1 |
qodost.st | https://qodo-platform.qodost.st.qodo.ai/rules/v1 |
The ENVIRONMENT_NAME value is substituted verbatim as a subdomain segment.
URL resolution priority: QODO_API_URL → ENVIRONMENT_NAME → production default
Attribution Headers
All requests must include attribution headers per the usage tracking guidelines:
| Header | Value |
|---|---|
Authorization | Bearer {API_KEY} |
request-id | UUID generated once per invocation |
qodo-client-type | skill-qodo-get-rules |
trace_id (optional) | Value of TRACE_ID env var if set |
Example (curl)
# Build body — include scopes only when SCOPE is set
if [ -n "${SCOPE:-}" ]; then
BODY="{\"query\": \"${SEARCH_QUERY}\", \"top_k\": 20, \"scopes\": [\"${SCOPE}\"]}"
else
BODY="{\"query\": \"${SEARCH_QUERY}\", \"top_k\": 20}"
fi
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${API_KEY}" \
-H "request-id: ${REQUEST_ID}" \
-H "qodo-client-type: skill-qodo-get-rules" \
-d "${BODY}" \
"${API_URL}/rules/search"With optional trace header:
TRACE_HEADER=""
if [ -n "${TRACE_ID:-}" ]; then
TRACE_HEADER="-H trace_id:${TRACE_ID}"
fi
if [ -n "${SCOPE:-}" ]; then
BODY="{\"query\": \"${SEARCH_QUERY}\", \"top_k\": 20, \"scopes\": [\"${SCOPE}\"]}"
else
BODY="{\"query\": \"${SEARCH_QUERY}\", \"top_k\": 20}"
fi
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${API_KEY}" \
-H "request-id: ${REQUEST_ID}" \
-H "qodo-client-type: skill-qodo-get-rules" \
${TRACE_HEADER} \
-d "${BODY}" \
"${API_URL}/rules/search"Example (Python)
import json
import os
from urllib.request import urlopen, Request
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"request-id": request_id,
"qodo-client-type": "skill-qodo-get-rules",
}
if trace_id := os.environ.get("TRACE_ID"):
headers["trace_id"] = trace_id
payload = {"query": search_query, "top_k": 20}
if scope: # omit field entirely when scope is not available
payload["scopes"] = [scope]
body = json.dumps(payload).encode()
req = Request(f"{api_url}/rules/search", data=body, headers=headers, method="POST")
with urlopen(req, timeout=30) as resp:
data = json.loads(resp.read())
rules = data.get("rules", [])Error Handling
| Status | Meaning | Action |
|---|---|---|
| 200 | Success | Parse rules array; empty list is valid |
| 401 | Invalid or expired API key | Inform user, exit gracefully |
| 403 | Access forbidden | Inform user, exit gracefully |
| 404 | Endpoint not found | Inform user to check QODO_ENVIRONMENT_NAME, exit gracefully |
| 429 | Rate limit exceeded | Inform user, exit gracefully |
| 5xx | API temporarily unavailable | Inform user, exit gracefully |
| Connection error | Network issue | Inform user to check internet connection, exit gracefully |
Never crash on an empty `rules` list. An empty result means no relevant rules exist — proceed with the coding task without constraints.
Related skills
How it compares
Use qodo-get-rules for org-specific ranked standards; use generic linter skills when no Qodo rule corpus is configured.
FAQ
What query format works best?
Use Name, Category, and Content lines mirroring rule embeddings, not keyword lists.
How is repository scope determined?
Parse git origin into org/repo path and optionally narrow to modules/name when cwd is inside modules.
What if no API key is configured?
Inform the user, provide setup instructions, and exit gracefully without calling the API.
Is Qodo Get Rules safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.