Skip to content

add capa-diff for comparing capability deltas between result docs#2959

Open
akshat4703 wants to merge 2 commits intomandiant:masterfrom
akshat4703:akshat/capa-diff
Open

add capa-diff for comparing capability deltas between result docs#2959
akshat4703 wants to merge 2 commits intomandiant:masterfrom
akshat4703:akshat/capa-diff

Conversation

@akshat4703
Copy link
Copy Markdown

This PR adds a standalone helper script, scripts/capa-diff.py, to compare two capa JSON result documents and report added/removed capabilities. It defaults to text output and also supports --format json; it can optionally include subscope-only matches via --include-subscope-rules.

Also added a script smoke test entry in tests/test_scripts.py to ensure the helper runs in CI script coverage.

Copy link
Copy Markdown

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add bug fixes, new features, breaking changes and anything else you think is worthwhile mentioning to the master (unreleased) section of CHANGELOG.md. If no CHANGELOG update is needed add the following to the PR description: [x] No CHANGELOG update needed

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the capa tool's analytical capabilities by introducing a new utility script, capa-diff.py. This script allows users to efficiently compare two capa analysis output files, highlighting changes in detected capabilities. This feature is crucial for tracking modifications in malware behavior or software functionality over time, providing a clear delta view of capabilities.

Highlights

  • New capa-diff.py script: Introduced a new standalone helper script, capa-diff.py, designed to compare two capa JSON result documents.
  • Capability Delta Reporting: The new script identifies and reports added or removed capabilities between the two compared documents.
  • Flexible Output Formats: The capa-diff.py script supports both human-readable text output (default) and machine-parseable JSON output via the --format json option.
  • Subscope Rule Inclusion: An optional flag, --include-subscope-rules, allows users to include rules that only matched as subrule references in the comparison.
  • CI Integration: A smoke test for capa-diff.py has been added to tests/test_scripts.py to ensure its functionality is covered in continuous integration.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions github-actions bot dismissed their stale review March 21, 2026 14:28

CHANGELOG updated or no update needed, thanks! 😄

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new script, capa-diff.py, for comparing capabilities between two capa JSON result documents. The script is well-structured and includes support for both text and JSON output formats. A smoke test has also been added to ensure the script's basic functionality is covered in CI. My review includes a suggestion to improve type safety and readability in the new script by using a TypedDict.

Comment on lines +33 to +86
from __future__ import annotations

import json
import sys
import argparse
from pathlib import Path

import capa.render.utils as rutils
import capa.render.default as rdefault
import capa.render.result_document as rd


def _parse_args(argv: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Compare capabilities in two capa JSON result documents.")
parser.add_argument("old", type=Path, help="path to older/baseline capa JSON result document")
parser.add_argument("new", type=Path, help="path to newer/target capa JSON result document")
parser.add_argument(
"--format",
dest="output_format",
choices=("text", "json"),
default="text",
help="render output as text or json (default: text)",
)
parser.add_argument(
"--include-subscope-rules",
action="store_true",
help="include rules that only matched as subrule references",
)
return parser.parse_args(argv)


def _load_result_document(path: Path) -> rd.ResultDocument:
return rd.ResultDocument.model_validate_json(path.read_text(encoding="utf-8"))


def _collect_capabilities(doc: rd.ResultDocument, include_subscope_rules: bool = False) -> dict[str, dict[str, object]]:
hidden = set()
if not include_subscope_rules:
hidden = rdefault.find_subrule_matches(doc)

capabilities: dict[str, dict[str, object]] = {}
for rule in rutils.capability_rules(doc):
if rule.meta.name in hidden:
continue

capabilities[rule.meta.name] = {
"name": rule.meta.name,
"namespace": rule.meta.namespace,
"match_count": len(rule.matches),
}
return capabilities


def _render_text(added: list[dict[str, object]], removed: list[dict[str, object]]) -> str:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For better type safety and code clarity, consider using a TypedDict for the structure of a capability. This makes the code easier to understand and maintain, as it explicitly defines the shape of the dictionary. This also allows for more precise type hints in function signatures.

from __future__ import annotations

import json
import sys
import argparse
from pathlib import Path
from typing import TypedDict

import capa.render.utils as rutils
import capa.render.default as rdefault
import capa.render.result_document as rd


class CapabilityInfo(TypedDict):
    name: str
    namespace: str | None
    match_count: int


def _parse_args(argv: list[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Compare capabilities in two capa JSON result documents.")
    parser.add_argument("old", type=Path, help="path to older/baseline capa JSON result document")
    parser.add_argument("new", type=Path, help="path to newer/target capa JSON result document")
    parser.add_argument(
        "--format",
        dest="output_format",
        choices=("text", "json"),
        default="text",
        help="render output as text or json (default: text)",
    )
    parser.add_argument(
        "--include-subscope-rules",
        action="store_true",
        help="include rules that only matched as subrule references",
    )
    return parser.parse_args(argv)


def _load_result_document(path: Path) -> rd.ResultDocument:
    return rd.ResultDocument.model_validate_json(path.read_text(encoding="utf-8"))


def _collect_capabilities(doc: rd.ResultDocument, include_subscope_rules: bool = False) -> dict[str, CapabilityInfo]:
    hidden = set()
    if not include_subscope_rules:
        hidden = rdefault.find_subrule_matches(doc)

    capabilities: dict[str, CapabilityInfo] = {}
    for rule in rutils.capability_rules(doc):
        if rule.meta.name in hidden:
            continue

        capabilities[rule.meta.name] = {
            "name": rule.meta.name,
            "namespace": rule.meta.namespace,
            "match_count": len(rule.matches),
        }
    return capabilities


def _render_text(added: list[CapabilityInfo], removed: list[CapabilityInfo]) -> str:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant