Skip to main content

Scenario 19: Standards check

Import coding rules, check selected source files, and save a violations report to review findings and prepare corrections.

User Guides

Check selected source files against your project’s coding rules. Scenario 19 finds matches for imported rules and shows their source locations. Use the report to decide which corrections are needed.

Check a complete example

Prepare the project Python environment using the CLI guide. Work in PowerShell from the CodeGraph repository root. This example checks Python source against one explicit regular-expression rule in a single process.

Save the following rule document as standards.yaml:

metadata:
  name: Example logging rules
  version: "1.0"
  language: python
rules:
  - id: LOG-001
    title: Use the configured logger
    description: Find print calls for review.
    category: best_practice
    severity: warning
    language: python
    pattern: '\bprint\s*\('

Save this source as example.py:

def greet(name):
    message = f"Hello, {name}"
    print(message)

Save the checker as check_standards_example.py:

import json
from pathlib import Path
from src.standards import StandardsParser, RuleDatabase, StandardsAnalyzer

parser = StandardsParser()
document = parser.parse_file("standards.yaml")
errors = parser.validate_document(document)
if errors:
    raise ValueError("; ".join(errors))
database = RuleDatabase()
database.add_document(document)
rules = database.list_rules(language="python")
if not rules:
    raise ValueError("The document contains no Python rules")
violations = StandardsAnalyzer().analyze_file("example.py", rules)
report = [violation.to_dict() for violation in violations]
Path("violations.json").write_text(
    json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
)
print(json.dumps({"rules": len(rules), "violations": len(report)}))

Run the checker and inspect its report:

python check_standards_example.py
Get-Content violations.json -Raw | ConvertFrom-Json | ForEach-Object { $_ | Select-Object rule_id, severity, line_number }

The checker prints {"rules": 1, "violations": 1}. The report contains rule_id="LOG-001", severity="warning", and line_number=3: the print call matches the rule. The analyzer reads the source; the script writes violations.json.

Replace example.py with this version and run the same two commands again:

import logging

def greet(name):
    logging.getLogger(__name__).info("Hello, %s", name)

The second run prints {"rules": 1, "violations": 0} and writes [] to violations.json. This rule identifies calls for review; use your project’s logging configuration and requirements when accepting the correction.

StandardsParser reads the YAML, RuleDatabase holds the document and rules in the current process, and StandardsAnalyzer returns matches with source locations. This example uses a regex rule, so it requires the Python environment and source files. CPG-query rules additionally require a configured CPG service.

CLI availability

The CLI registers commands for importing standards and listing documents and rules, but these commands do not currently provide a usable way to load a rule set. To load YAML and check a file, use the programmatic example above. It performs both steps in one process.

CLI check status

The registered check accepts a source path and an output filename:

python -m src.cli standards check "<source-path>" --output "<violations.json>"

The command also accepts --document, --category, --severity, and --fail-on. It currently stops before analysis and does not create the report. Use the programmatic example above to check the file and save the JSON results.

Run the typed reviewer scenario

from src.digital_employees.runtime.scenarios import (
    RoleBoundScenarioInvocationRequest,
    invoke_role_bound_scenario_request,
)

request = RoleBoundScenarioInvocationRequest(
    query="Check the bounded component against the accepted coding standards.",
    employee_id="codegraph_reviewer",
    scenario_id="scenario_19",
    event_type="review_start",
    context={
        "project_key": "codegraph",
        "namespace": "default",
        "task_id": "<task-id>",
        "source_refs": ["<revision-ref>", "<standards-document-ref>"],
        "file_paths": ["<bounded-source-path>"],
    },
)
result = invoke_role_bound_scenario_request(request)
if result.get("error"):
    raise RuntimeError(result["error"])
if not result.get("scenario_id") or not result.get("answer"):
    raise RuntimeError("Scenario returned no scenario identity or answer")
print(result["answer"])

The request scopes analysis by project, source revision, standards document and file paths. Read the result in result["answer"]. To save findings as JSON, run the programmatic checker above.

Other standards interfaces

python -m src.cli standards report is registered, but it does not generate a report. Save the JSON artifact from the programmatic checker above.

The current REST API has no standards endpoint. Use the programmatic example above to run this check.

Review the findings

For each match, open the referenced line and read the rule. Check whether the rule applies to that file and compare the finding with agreed exceptions. After a correction, repeat the analysis over the same scope. Retain the revision, rule set, report, and decision for each finding.

Failure and recovery

  • No rules found: check the rules list and language value in standards.yaml. Load the document and run the check in the same script execution.

  • Invalid YAML: correct standards.yaml using the parser message and run check_standards_example.py again.

  • Unexpected zero violations: verify the source path, the rules and language values, and whether the rule matches the source syntax.

  • Report command fails: save violations.json from the programmatic example above.