Generated banner for Codeql
Generated logo for Codeql

Codeql

GitHubOfficialFirst committed by VeVarunSharmaDistributed by GitHub

  • Skill
  • Tool integration
  • Security
  • MIT
  • No issues found

From the author

Comprehensive guide for setting up and configuring CodeQL code scanning via GitHub Actions workflows and the CodeQL CLI. This skill should be used when users need help with code scanning configuration, CodeQL workflow files, CodeQL CLI commands, SARIF output, security analysis setup, or troubleshooting CodeQL analysis.
— the description by VeVarunSharma

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides procedural instructions for setting up CodeQL to perform automated code scanning. It covers both the GitHub Actions workflow integration for automated CI/CD pipelines and the standalone CodeQL CLI for local analysis. The documentation includes details on language support, build modes, query suite selection, SARIF output management, and troubleshooting common analysis issues.

What it does

  • Configures CodeQL code scanning within GitHub Actions workflows.
  • Provides commands for local database creation and analysis using the CodeQL CLI.
  • Explains how to manage and interpret SARIF output files.
  • Details how to configure language matrices, build modes, and custom query packs.
  • Offers guidance on alert triage, severity levels, and GitHub Copilot Autofix integration.
  • Provides troubleshooting steps for common analysis failures and environment requirements.

When to use it

  • When setting up automated security scanning in a GitHub repository.
  • When you need to run CodeQL analysis locally on a development machine.
  • When customizing CodeQL workflows for monorepos or specific build requirements.
  • When troubleshooting failed CodeQL analysis or build mode configurations.
  • When managing or dismissing security alerts generated by CodeQL.

Advantages

  • Supports a wide range of programming languages.
  • Integrates directly into GitHub Actions for automated security checks.
  • Allows for granular control over analysis via custom query packs and configuration files.
  • Provides clear paths for both default and advanced setup scenarios.
  • Facilitates local analysis and debugging through the CodeQL CLI.

Usage examples

“How do I set up a basic CodeQL workflow in GitHub Actions?”
The agent will provide a template for a .github/workflows/codeql.yml file, explaining the necessary steps for initialization, language matrix configuration, and analysis.
“How can I run CodeQL locally on my machine?”
The agent will guide you through downloading the CodeQL bundle, creating a database with the CLI, and running the analysis command to generate a SARIF file.
“What should I do if my CodeQL autobuild fails?”
The agent will suggest switching to manual build mode and provide instructions on how to insert custom build commands into your workflow.
“How do I interpret the severity of a CodeQL alert?”
The agent will explain the difference between standard severity and security severity, including how CVSS scores influence the reported alert level.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/github/codeql/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip codeql.zip -d .agents/skills

Documentation by VeVarunSharma

CodeQL Code Scanning

This skill provides procedural guidance for configuring and running CodeQL code scanning — both through GitHub Actions workflows and the standalone CodeQL CLI.

When to Use This Skill

Use this skill when the request involves:

  • Creating or customizing a codeql.yml GitHub Actions workflow

  • Choosing between default setup and advanced setup for code scanning

  • Configuring CodeQL language matrix, build modes, or query suites

  • Running CodeQL CLI locally (codeql database create, database analyze, github upload-results)

  • Understanding or interpreting SARIF output from CodeQL

  • Troubleshooting CodeQL analysis failures (build modes, compiled languages, runner requirements)

  • Setting up CodeQL for monorepos with per-component scanning

  • Configuring dependency caching, custom query packs, or model packs

Supported Languages

CodeQL supports the following language identifiers:

LanguageIdentifierAlternatives
C/C++c-cppc, cpp
C#csharp—
Gogo—
Java/Kotlinjava-kotlinjava, kotlin
JavaScript/TypeScriptjavascript-typescriptjavascript, typescript
Pythonpython—
Rubyruby—
Rustrust—
Swiftswift—
GitHub Actionsactions—

Alternative identifiers are equivalent to the standard identifier (e.g., javascript does not exclude TypeScript analysis).

Core Workflow — GitHub Actions

Step 1: Choose Setup Type
  • Default setup — Enable from repository Settings → Advanced Security → CodeQL analysis. Best for getting started quickly. Uses none build mode for most languages.

  • Advanced setup — Create a .github/workflows/codeql.yml file for full control over triggers, build modes, query suites, and matrix strategies.

To switch from default to advanced: disable default setup first, then commit the workflow file.

Step 2: Configure Workflow Triggers

Define when scanning runs:

on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
  schedule:
    - cron: '30 6 * * 1'  # Weekly Monday 6:30 UTC
  • push — scans on every push to specified branches; results appear in Security tab

  • pull_request — scans PR merge commits; results appear as PR check annotations

  • schedule — periodic scans of the default branch (cron must exist on default branch)

  • merge_group — add if repository uses merge queues

To skip scans for documentation-only PRs:

on:
  pull_request:
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'

paths-ignore controls whether the workflow runs, not which files are analyzed.

Step 3: Configure Permissions

Set least-privilege permissions:

permissions:
  security-events: write   # Required to upload SARIF results
  contents: read            # Required to checkout code
  actions: read             # Required for private repos using codeql-action
Step 4: Configure Language Matrix

Use a matrix strategy to analyze each language in parallel:

jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - language: javascript-typescript
            build-mode: none
          - language: python
            build-mode: none

For compiled languages, set the appropriate build-mode:

  • none — no build required (supported for C/C++, C#, Java, Rust)

  • autobuild — automatic build detection

  • manual — custom build commands (advanced setup only)

For detailed per-language autobuild behavior and runner requirements, search references/compiled-languages.md.

Step 5: Configure CodeQL Init and Analysis
steps:
  - name: Checkout repository
    uses: actions/checkout@v4

  - name: Initialize CodeQL
    uses: github/codeql-action/init@v4
    with:
      languages: ${{ matrix.language }}
      build-mode: ${{ matrix.build-mode }}
      queries: security-extended
      dependency-caching: true

  - name: Perform CodeQL Analysis
    uses: github/codeql-action/analyze@v4
    with:
      category: "/language:${{ matrix.language }}"

Query suite options:

  • security-extended — default security queries plus additional coverage

  • security-and-quality — security plus code quality queries

  • Custom query packs via packs: input (e.g., codeql/javascript-queries:AlertSuppression.ql)

Dependency caching: Set dependency-caching: true on the init action to cache restored dependencies across runs.

Analysis category: Use category to distinguish SARIF results in monorepos (e.g., per-language, per-component).

Step 6: Monorepo Configuration

For monorepos with multiple components, use the category parameter to separate SARIF results:

category: "/language:${{ matrix.language }}/component:frontend"

To restrict analysis to specific directories, use a CodeQL configuration file (.github/codeql/codeql-config.yml):

paths:
  - apps/
  - services/
paths-ignore:
  - node_modules/
  - '**/test/**'

Reference it in the workflow:

- uses: github/codeql-action/init@v4
  with:
    config-file: .github/codeql/codeql-config.yml
Step 7: Manual Build Steps (Compiled Languages)

If autobuild fails or custom build commands are needed:

- language: c-cpp
  build-mode: manual

Then add explicit build steps between init and analyze:

- if: matrix.build-mode == 'manual'
  name: Build
  run: |
    make bootstrap
    make release

Core Workflow — CodeQL CLI

Step 1: Install the CodeQL CLI

Download the CodeQL bundle (includes CLI + precompiled queries):

# Download from https://github.com/github/codeql-action/releases
# Extract and add to PATH
export PATH="$HOME/codeql:$PATH"

# Verify installation
codeql resolve packs
codeql resolve languages

Always use the CodeQL bundle, not a standalone CLI download. The bundle ensures query compatibility and provides precompiled queries for better performance.

Step 2: Create a CodeQL Database
# Single language
codeql database create codeql-db \
  --language=javascript-typescript \
  --source-root=src

# Multiple languages (cluster mode)
codeql database create codeql-dbs \
  --db-cluster \
  --language=java,python \
  --command=./build.sh \
  --source-root=src

For compiled languages, provide the build command via --command.

Step 3: Analyze the Database
codeql database analyze codeql-db \
  javascript-code-scanning.qls \
  --format=sarif-latest \
  --sarif-category=javascript \
  --output=results.sarif

Common query suites: <language>-code-scanning.qls, <language>-security-extended.qls, <language>-security-and-quality.qls.

Step 4: Upload Results to GitHub
codeql github upload-results \
  --repository=owner/repo \
  --ref=refs/heads/main \
  --commit=<commit-sha> \
  --sarif=results.sarif

Requires GITHUB_TOKEN environment variable with security-events: write permission.

CLI Server Mode

To avoid repeated JVM initialization when running multiple commands:

codeql execute cli-server

For detailed CLI command reference, search references/cli-commands.md.

Alert Management

Severity Levels

Alerts have two severity dimensions:

  • Standard severity: Error, Warning, Note

  • Security severity: Critical, High, Medium, Low (derived from CVSS scores; takes display precedence)

Copilot Autofix

GitHub Copilot Autofix generates fix suggestions for CodeQL alerts in pull requests automatically — no Copilot subscription required. Review suggestions carefully before committing.

Alert Triage in PRs
  • Alerts appear as check annotations on changed lines

  • Check fails by default for error/critical/high severity alerts

  • Configure merge protection rulesets to customize the threshold

  • Dismiss false positives with a documented reason for audit trail

For detailed alert management guidance, search references/alert-management.md.

Custom Queries and Packs

Using Custom Query Packs
- uses: github/codeql-action/init@v4
  with:
    packs: |
      my-org/[email protected]
      codeql/javascript-queries:AlertSuppression.ql
Creating Custom Query Packs

Use the CodeQL CLI to create and publish packs:

# Initialize a new pack
codeql pack init my-org/my-queries

# Install dependencies
codeql pack install

# Publish to GitHub Container Registry
codeql pack publish
CodeQL Configuration File

For advanced query and path configuration, create .github/codeql/codeql-config.yml:

paths:
  - apps/
  - services/
paths-ignore:
  - '**/test/**'
  - node_modules/
queries:
  - uses: security-extended
packs:
  javascript-typescript:
    - my-org/my-custom-queries

Code Scanning Logs

Summary Metrics

Workflow logs include key metrics:

  • Lines of code in codebase — baseline before extraction

  • Lines extracted — including external libraries and auto-generated files

  • Extraction errors/warnings — files that failed or produced warnings during extraction

Debug Logging

To enable detailed diagnostics:

  • GitHub Actions: re-run the workflow with "Enable debug logging" checked

  • CodeQL CLI: use --verbosity=progress++ and --logdir=codeql-logs

Troubleshooting

Common Issues
ProblemSolution
Workflow not triggeringVerify on: triggers match event; check paths/branches filters; ensure workflow exists on target branch
Resource not accessible errorAdd security-events: write and contents: read permissions
Autobuild failureSwitch to build-mode: manual and add explicit build commands
No source code seenVerify --source-root, build command, and language identifier
C# compiler failureCheck for /p:EmitCompilerGeneratedFiles=true conflicts with .sqlproj or legacy projects
Fewer lines scanned than expectedSwitch from none to autobuild/manual; verify build compiles all source
Kotlin in no-build modeDisable and re-enable default setup to switch to autobuild
Cache miss every runVerify dependency-caching: true on init action
Out of disk/memoryUse larger runners; reduce analysis scope via paths config; use build-mode: none
SARIF upload failsEnsure token has security-events: write; check 10 MB file size limit
SARIF results exceed limitsSplit across multiple uploads with different --sarif-category; reduce query scope
Two CodeQL workflowsDisable default setup if using advanced setup, or remove old workflow file
Slow analysisEnable dependency caching; use --threads=0; reduce query suite scope

For comprehensive troubleshooting with detailed solutions, search references/troubleshooting.md.

Hardware Requirements (Self-Hosted Runners)
Codebase SizeRAMCPU
Small (<100K LOC)8 GB+2 cores
Medium (100K–1M LOC)16 GB+4–8 cores
Large (>1M LOC)64 GB+8 cores

All sizes: SSD with ≥14 GB free disk space.

Action Versioning

Pin CodeQL actions to a specific major version:

uses: github/codeql-action/init@v4      # Recommended
uses: github/codeql-action/autobuild@v4
uses: github/codeql-action/analyze@v4

For maximum security, pin to a full commit SHA instead of a version tag.

Reference Files

For detailed documentation, load the following reference files as needed:

  • references/workflow-configuration.md — Full workflow trigger, runner, and configuration options

    • Search patterns: trigger, schedule, paths-ignore, db-location, model packs, alert severity, merge protection, concurrency, config file

  • references/cli-commands.md — Complete CodeQL CLI command reference

    • Search patterns: database create, database analyze, upload-results, resolve packs, cli-server, installation, CI integration

  • references/sarif-output.md — SARIF v2.1.0 object model, upload limits, and third-party support

    • Search patterns: sarifLog, result, location, region, codeFlow, fingerprint, suppression, upload limits, third-party, precision, security-severity

  • references/compiled-languages.md — Build modes and autobuild behavior per language

    • Search patterns: C/C++, C#, Java, Go, Rust, Swift, autobuild, build-mode, hardware, dependency caching

  • references/troubleshooting.md — Comprehensive error diagnosis and resolution

    • Search patterns: no source code, out of disk, out of memory, 403, C# compiler, analysis too long, fewer lines, Kotlin, extraction errors, debug logging, SARIF upload, SARIF limits

  • references/alert-management.md — Alert severity, triage, Copilot Autofix, and dismissal

    • Search patterns: severity, security severity, CVSS, Copilot Autofix, dismiss, triage, PR alerts, data flow, merge protection, REST API

Files

references/troubleshooting.md

CodeQL Troubleshooting Reference

Comprehensive guide for diagnosing and resolving CodeQL analysis errors, SARIF upload issues, and common configuration problems.

Build and Analysis Errors

"No source code was seen during the build"

Cause: CodeQL extractor did not find any source files during database creation.

Solutions:

  • Verify the --source-root points to the correct directory

  • For compiled languages, ensure the build command actually compiles source files

  • Check that autobuild is detecting the correct build system

  • Switch from autobuild to manual build mode with explicit build commands

  • Verify the language specified matches the actual source code language

Automatic Build Failed

Cause: autobuild could not detect or run the project's build system.

Solutions:

  • Switch to build-mode: manual and provide explicit build commands

  • Ensure all build dependencies are installed on the runner

  • For C/C++: verify gcc, make, cmake, or msbuild are available

  • For C#: verify .NET SDK or MSBuild is installed

  • For Java: verify gradle or maven is installed

  • Check the autobuild logs for the specific detection step that failed

C# Compiler Unexpectedly Failing

Cause: The CodeQL tracer injects compiler flags that may conflict with project configuration.

Details: CodeQL injects /p:EmitCompilerGeneratedFiles=true which can cause issues with:

  • Legacy .NET Framework projects

  • Projects using .sqlproj files

Solutions:

  • Add <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles> to problematic project files

  • Use build-mode: none for C# if build accuracy is acceptable

  • Exclude problematic projects from the CodeQL analysis

Analysis Takes Too Long

Cause: Large codebase, complex queries, or insufficient resources.

Solutions:

  • Use build-mode: none where accuracy is acceptable (significantly faster)

  • Enable dependency caching: dependency-caching: true

  • Set timeout-minutes on the job to prevent hung workflows

  • Use --threads=0 (CLI) to use all available CPU cores

  • Reduce query scope: use default suite instead of security-and-quality

  • For self-hosted runners, ensure hardware meets recommendations:

    • Small (<100K LOC): 8 GB RAM, 2 cores

    • Medium (100K–1M LOC): 16 GB RAM, 4–8 cores

    • Large (>1M LOC): 64 GB RAM, 8 cores

  • Configure larger GitHub-hosted runners if available

  • Use paths in config file to limit analyzed directories

CodeQL Scanned Fewer Lines Than Expected

Cause: Build command didn't compile all source files, or build-mode: none missed generated code.

Solutions:

  • Switch from none to autobuild or manual build mode

  • Ensure the build command compiles the full codebase (not just a subset)

  • Check the code scanning logs for extraction metrics:

    • Lines of code in codebase (baseline)

    • Lines of code extracted

    • Lines excluding auto-generated files

  • Verify language detection includes all expected languages

Kotlin Detected in No-Build Mode

Cause: Repository uses build-mode: none (Java only) but also contains Kotlin code.

Solutions:

  • Disable default setup and re-enable it (switches to autobuild)

  • Or switch to advanced setup with build-mode: autobuild for java-kotlin

  • Kotlin requires a build to be analyzed; none mode only works for Java

Permission and Access Errors

Error: 403 "Resource not accessible by integration"

Cause: GITHUB_TOKEN lacks required permissions.

Solutions:

  • Add explicit permissions to the workflow:

    permissions:
      security-events: write
      contents: read
      actions: read
  • For Dependabot PRs, use pull_request_target instead of pull_request

  • Verify the repository has GitHub Code Security enabled (for private repos)

Cannot Enable CodeQL in a Private Repository

Cause: GitHub Code Security is not enabled.

Solution: Enable GitHub Code Security in repository Settings → Advanced Security.

Error: "GitHub Code Security or Advanced Security must be enabled"

Cause: Attempting to use code scanning on a private repo without the required license.

Solutions:

  • Enable GitHub Code Security for the repository

  • Contact organization admin to enable Advanced Security

Configuration Errors

Two CodeQL Workflows Running

Cause: Both default setup and a pre-existing codeql.yml workflow are active.

Solutions:

  • Disable default setup if using advanced setup, or

  • Delete the old workflow file if using default setup

  • Check repository Settings → Advanced Security for active configurations

Some Languages Not Analyzed

Cause: Matrix configuration doesn't include all languages.

Solutions:

  • Add missing languages to the matrix.include array

  • Verify language identifiers are correct (e.g., javascript-typescript not just javascript)

  • Check that each language has an appropriate build-mode

Unclear What Triggered a Workflow Run

Solutions:

  • Check the tool status page in repository Settings → Advanced Security

  • Review workflow run logs for trigger event details

  • Look at the on: triggers in the workflow file

Error: "is not a .ql file, .qls file, a directory, or a query pack specification"

Cause: Invalid query or pack reference in the workflow.

Solutions:

  • Verify query pack names and versions exist

  • Use correct format: owner/pack-name@version or owner/pack-name:path/to/query.ql

  • Run codeql resolve packs to verify available packs

Resource Errors

"Out of disk" or "Out of memory"

Cause: Runner lacks sufficient resources for the analysis.

Solutions:

  • Use larger GitHub-hosted runners (if available)

  • For self-hosted runners, increase RAM and disk (SSD with ≥14 GB)

  • Reduce analysis scope with paths configuration

  • Analyze fewer languages per job

  • Use build-mode: none to reduce resource usage

Extraction Errors in Database

Cause: Some source files couldn't be processed by the CodeQL extractor.

Solutions:

  • Check extraction metrics in workflow logs for error counts

  • Enable debug logging for detailed extraction diagnostics

  • Verify source files are syntactically valid

  • Ensure all build dependencies are available

Logging and Debugging

Enable Debug Logging

To get more detailed diagnostic information:

GitHub Actions:

  1. Re-run the workflow with debug logging enabled

  2. In the workflow run, click "Re-run jobs" → "Enable debug logging"

CodeQL CLI:

codeql database create my-db \
  --language=javascript-typescript \
  --verbosity=progress++ \
  --logdir=codeql-logs

Verbosity levels: errors, warnings, progress, progress+, progress++, progress+++

Code Scanning Log Metrics

Workflow logs include summary metrics:

  • Lines of code in codebase — baseline before extraction

  • Lines of code in CodeQL database — extracted including external libraries

  • Lines excluding auto-generated files — net analyzed code

  • Extraction success/error/warning counts — per-file extraction results

Private Registry Diagnostics

For build-mode: none with private package registries:

  • Check the "Setup proxy for registries" step in workflow logs

  • Look for Credentials loaded for the following registries: message

  • Verify organization-level private registry configuration

  • Ensure internet access is available for dependency resolution

SARIF Upload Errors

SARIF File Too Large

Limit: 10 MB maximum (gzip-compressed).

Solutions:

  • Focus on the most important query suites (use default instead of security-and-quality)

  • Reduce the number of queries via configuration

  • Split analysis into multiple jobs with separate SARIF uploads

  • Remove --sarif-add-file-contents flag

SARIF Results Exceed Limits

GitHub enforces limits on SARIF data objects:

ObjectMaximum
Runs per file20
Results per run25,000
Rules per run25,000
Tool extensions per run100
Thread flow locations per result10,000
Location per result1,000
Tags per rule20

Solutions:

  • Reduce query scope to focus on high-impact rules

  • Split analysis across multiple SARIF uploads with different --sarif-category

  • Disable noisy queries that produce many results

SARIF File Invalid

Solutions:

  • Validate against the Microsoft SARIF validator

  • Ensure version is "2.1.0" and $schema points to the correct schema

  • Verify required properties (runs, tool.driver, results) are present

Upload Rejected: Default Setup Enabled

Cause: Cannot upload CodeQL-generated SARIF when default setup is active.

Solutions:

  • Disable default setup before uploading via CLI/API

  • Or switch to using default setup exclusively (no manual uploads)

Missing Authentication Token

Solutions:

  • Set GITHUB_TOKEN environment variable with security-events: write scope

  • Or use --github-auth-stdin to pipe the token

  • For GitHub Actions: the token is automatically available via ${{ secrets.GITHUB_TOKEN }}

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of VeVarunSharmaVeVarunSharma
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/codeql · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
VeVarunSharma

AutoGineer is not affiliated with or endorsed by VeVarunSharma or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download codeql.zip