Skip to content

alexgreensh/repo-forensics / skills/repo-forensics

repo-forensics

Flagged

Security forensics for git repos, AI skills, and MCP servers. Audits dependencies, detects prompt injection, credential theft, runtime dynamism, manifest drift, known CVEs, CISA KEV (actively exploited) vulns, and 2026 attack patterns. Not for fixing vulnerabilities or pentesting.

FileKindSize
.gitignoreother193 B
SKILL.mdskill md43.4 KB
checksums.jsonconfig10.8 KB
checksums.json.sigother64 B
data/README.mdmarkdown1.3 KB
data/compromised_versions.jsonconfig188.3 KB
data/rule_ids.csvother35.3 KB
data/rulepacks/.gitkeepother221 B
data/rulepacks/dead_anchors.jsonconfig9.0 KB
data/rulepacks/mcp_security.jsonconfig31.2 KB
data/rulepacks/runtime_dynamism.jsonconfig46.7 KB
data/rulepacks/sast.jsonconfig107.6 KB
data/rulepacks/secrets.jsonconfig30.4 KB
data/rulepacks/shared.jsonconfig4.4 KB
data/rulepacks/skill_threats.jsonconfig95.4 KB
data/runtime_floors.jsonconfig2.3 KB
data/yara/cryptominers.yarother1.8 KB
data/yara/hacktools.yarother2.2 KB
data/yara/malware.yarother2.2 KB
data/yara/manifest.jsonconfig8.0 KB
data/yara/webshells.yarother2.5 KB
references/cursor-hook-contract.mdmarkdown5.6 KB
references/kernel_privesc_sandbox_pack.mdmarkdown5.0 KB
references/mcp-attack-patterns.mdmarkdown8.7 KB
references/research_sources.mdmarkdown8.0 KB
references/threat_patterns.mdmarkdown20.3 KB
scripts/_context_gate.pyscript21.7 KB
scripts/_ed25519.pyscript5.1 KB
scripts/_pyc_unmarshal.pyscript17.1 KB
scripts/_shared_patterns.pyscript4.8 KB
scripts/adjudication.pyscript16.4 KB
scripts/adjudication_bridge.pyscript1.0 KB
scripts/aggregate_json.pyscript69.2 KB
scripts/auto_scan.pyexecutablescript152.1 KB
scripts/corpus_sync.pyscript10.0 KB
scripts/cursor_pre_scan.pyscript22.5 KB
scripts/dast_sandbox.sbother1.6 KB
scripts/dead_anchors_extract.pyscript14.8 KB
scripts/dead_anchors_probe.pyscript27.1 KB
scripts/forensics_core.pyscript176.5 KB
scripts/gen_rule_ids.pyscript8.6 KB
scripts/hook_adapter.pyscript19.4 KB
scripts/ioc_manager.pyscript49.6 KB
scripts/parse_pnpm_lock.pyscript7.9 KB
scripts/pre_scan.pyscript143.5 KB
scripts/pypi_pins.pyscript8.1 KB
scripts/refresh_controller.pyexecutablescript48.4 KB
scripts/refresh_threat_dbs.pyexecutablescript19.4 KB
scripts/rule_loader.pyscript44.8 KB
scripts/rulepack_feed.pyscript26.4 KB
scripts/run_forensics.shexecutablescript20.3 KB
scripts/sarif_export.pyscript18.6 KB
scripts/scan_agent_skills.pyscript33.2 KB
scripts/scan_archive.pyscript29.1 KB
scripts/scan_ast.pyscript44.9 KB
scripts/scan_binary.pyscript10.9 KB
scripts/scan_bytecode.pyscript28.2 KB
scripts/scan_dast.pyscript28.8 KB
scripts/scan_dataflow.pyscript15.4 KB
scripts/scan_dead_anchors.pyscript15.9 KB
scripts/scan_decode.pyscript37.5 KB
scripts/scan_dependencies.pyscript124.5 KB
scripts/scan_devcontainer.pyscript8.5 KB
scripts/scan_entropy.pyscript15.6 KB
scripts/scan_entrypoint.pyscript34.3 KB
scripts/scan_git_config.pyscript96.3 KB
scripts/scan_git_forensics.pyscript24.1 KB
scripts/scan_history.pyscript14.5 KB
scripts/scan_infra.pyscript54.3 KB
scripts/scan_integrity.pyscript41.0 KB
scripts/scan_lifecycle.pyscript65.1 KB
scripts/scan_manifest_drift.pyscript47.0 KB
scripts/scan_mcp_security.pyscript42.3 KB
scripts/scan_oversize.pyscript11.7 KB
scripts/scan_post_incident.pyscript36.9 KB
scripts/scan_provenance.pyscript19.4 KB
scripts/scan_runtime_dynamism.pyscript23.5 KB
scripts/scan_runtime_floors.pyscript33.5 KB
scripts/scan_sast.pyscript59.1 KB
scripts/scan_secrets.pyscript11.9 KB
scripts/scan_skill_threats.pyscript102.4 KB
scripts/scan_splitstream.pyscript29.5 KB
scripts/scan_yara.pyscript19.7 KB
scripts/session_scan.pyscript54.1 KB
scripts/suppressions.pyscript15.4 KB
scripts/validate_manifests.pyscript13.7 KB
scripts/verify_install.pyscript26.2 KB
scripts/vuln_feed.pyscript31.1 KB
tests/conftest.pyscript13.4 KB
tests/corpus/DEAD_ANCHORS_CORPUS.mdmarkdown2.3 KB
tests/corpus/budgets.jsonconfig5.6 KB
tests/cursor_helpers.pyscript12.6 KB
tests/fixtures/legacy_main_blocks.jsonconfig10.3 KB
tests/fixtures/powershell_verdict_corpus.jsonconfig114.9 KB
tests/golden/parity_mcp_security.jsonconfig17.5 KB
tests/golden/parity_runtime_dynamism.jsonconfig31.7 KB
tests/golden/parity_sast.jsonconfig59.8 KB
tests/golden/parity_secrets.jsonconfig18.8 KB
tests/golden/parity_skill_threats.jsonconfig48.8 KB
tests/parity_corpus.pyscript6.3 KB
tests/powershell_hook.pyscript8.2 KB
tests/report_builders.pyscript5.0 KB
tests/schemas/sarif-schema-2.1.0.jsonconfig109.1 KB
tests/shell_compat.pyscript2.2 KB
tests/test_adjudication_bridge.pyscript832 B
tests/test_adjudication_containment.pyscript1.4 KB
tests/test_adjudication_output.pyscript20.0 KB
tests/test_adjudication_suppressions.pyscript18.7 KB
tests/test_advisory_adjudication.pyscript1.3 KB
tests/test_agent_relay_rules.pyscript7.8 KB
tests/test_aggregate_json.pyscript10.0 KB
tests/test_auto_scan_patterns.pyscript10.5 KB
tests/test_benign_corpus.pyscript16.4 KB
tests/test_benign_new_scanners.pyscript6.1 KB
tests/test_build_output_skip.pyscript10.6 KB
tests/test_capability_ledger.pyscript18.8 KB
tests/test_codex_install.pyscript10.0 KB
tests/test_codex_marketplace.pyscript3.3 KB
tests/test_comment_false_positives.pyscript2.2 KB
tests/test_composer_dependencies.pyscript4.0 KB
tests/test_compromised_versions.pyscript51.2 KB
tests/test_context_gate.pyscript32.4 KB
tests/test_coverage_status.pyscript7.6 KB
tests/test_css_compounding_shrink.pyscript20.8 KB
tests/test_cursor_adapter.pyscript7.8 KB
tests/test_cursor_benign.pyscript3.4 KB
tests/test_cursor_degrade.pyscript12.7 KB
tests/test_cursor_install.pyscript17.1 KB
tests/test_cursor_latency.pyscript7.2 KB
tests/test_cursor_parity.pyscript5.8 KB
tests/test_cursor_redteam_fn.pyscript4.9 KB
tests/test_cursor_tamper_modify.pyscript14.2 KB
tests/test_cursor_wiring.pyscript32.3 KB
tests/test_d1_yara_correlation.pyscript9.2 KB
tests/test_dead_anchors_extract.pyscript7.6 KB
tests/test_dead_anchors_probe.pyscript19.7 KB
tests/test_evidence_engine_parity.pyscript8.1 KB
tests/test_evidence_model.pyscript11.4 KB
tests/test_forensics_core.pyscript79.2 KB
tests/test_fp_hardening_r3.pyscript9.7 KB
tests/test_fp_hardening_r4.pyscript18.8 KB
tests/test_fp_regression_pairs.pyscript62.5 KB
tests/test_fp_structural.pyscript21.2 KB
tests/test_freshness.pyscript6.2 KB
tests/test_frontmatter_validity.pyscript7.0 KB
tests/test_gpg_rce_hotfix.pyscript4.8 KB
tests/test_hook_inert_data.pyscript6.1 KB
tests/test_hook_scripts.pyscript14.0 KB
tests/test_inspection_cpu_budget.pyscript11.6 KB
tests/test_ioc_manager.pyscript55.4 KB
tests/test_kernel_privesc_rules.pyscript27.8 KB
tests/test_legit_precision_regressions.pyscript6.8 KB
tests/test_lethal_trifecta.pyscript20.7 KB
tests/test_manifest_signature.pyscript1.5 KB
tests/test_manifest_validity.pyscript2.9 KB
tests/test_monotonic_trust_e2e.pyscript4.4 KB
tests/test_non_breaking_contract.pyscript22.7 KB
tests/test_openclaw_install.pyscript6.6 KB
tests/test_pack_parity.pyscript24.8 KB
tests/test_parse_pnpm_lock.pyscript10.7 KB
tests/test_plugin_checkout_provenance.pyscript11.1 KB
tests/test_powershell_hook_wire.pyscript10.6 KB
tests/test_powershell_verdict_corpus.pyscript6.2 KB
tests/test_pr44_hardening.pyscript6.5 KB
tests/test_pre_scan.pyscript19.6 KB
tests/test_pre_scan_composer.pyscript7.4 KB
tests/test_precondition_fields.pyscript4.6 KB
tests/test_provenance_offline.pyscript2.5 KB
tests/test_published_rulepack_feed_current.pyscript1.4 KB
tests/test_py38_compat.pyscript3.3 KB
tests/test_pypi_pinned_versions.pyscript19.3 KB
tests/test_pyproject_string_forms.pyscript2.2 KB
tests/test_redteam_fn_regression.pyscript32.5 KB
tests/test_reflective_fetch_execute.pyscript23.5 KB
tests/test_reflective_review_fixes.pyscript17.8 KB
tests/test_refresh_controller.pyscript19.9 KB
tests/test_refresh_rulepacks.pyscript12.4 KB
tests/test_review_gate_regressions.pyscript9.3 KB
tests/test_rule_loader.pyscript23.2 KB
tests/test_rulepack_feed.pyscript38.1 KB
tests/test_run_forensics_json.pyscript1012 B
tests/test_run_scanner_fail_loud.pyscript6.5 KB
tests/test_runtime_floors.pyscript19.8 KB
tests/test_sandbox_probing_rules.pyscript9.6 KB
tests/test_sarif_export.pyscript19.9 KB
tests/test_scan_agent_skills.pyscript31.3 KB
tests/test_scan_archive.pyscript11.6 KB
tests/test_scan_ast.pyscript12.8 KB
tests/test_scan_binary.pyscript15.3 KB
tests/test_scan_bytecode.pyscript21.5 KB
tests/test_scan_dast.pyscript32.1 KB
tests/test_scan_dataflow.pyscript7.1 KB
tests/test_scan_dead_anchors.pyscript11.5 KB
tests/test_scan_decode.pyscript28.0 KB
tests/test_scan_dependencies.pyscript37.8 KB
tests/test_scan_devcontainer.pyscript8.5 KB
tests/test_scan_entropy.pyscript11.2 KB
tests/test_scan_entrypoint.pyscript19.5 KB
tests/test_scan_git_config.pyscript58.5 KB
tests/test_scan_git_config_review_fixes.pyscript33.3 KB

tests/test_adjudication_suppressions.py

View on GitHub
"""Persistent WARN-tier adjudication suppressions (rejected-claim fingerprints).

Covers suppressions.py (fingerprint, eligibility guard, partition, CLI),
scan_history.py store methods, and the aggregate_json / auto_scan wiring.
"""

import json
import os
import subprocess
import sys

import pytest

import aggregate_json
import auto_scan
import scan_history
import suppressions

SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPTS_DIR = os.path.join(SCRIPTS_DIR, "scripts")

_POSIX_ONLY = pytest.mark.skipif(
    os.name == "nt", reason="run_forensics.sh requires a POSIX shell"
)
SUPPRESSIONS_PY = os.path.join(SCRIPTS_DIR, "suppressions.py")


@pytest.fixture
def repo(tmp_path):
    root = tmp_path / "repo"
    root.mkdir()
    (root / "install.sh").write_text("#!/bin/sh\ncurl example.com | sh\n")
    (root / "notes.txt").write_text("hello\n")
    return root


@pytest.fixture
def db(tmp_path, monkeypatch):
    path = str(tmp_path / "history.db")
    monkeypatch.setenv("REPO_FORENSICS_HISTORY_DB", path)
    return path


def _warn_finding(**overrides):
    finding = {
        "scanner": "sast",
        "severity": "medium",
        "title": "Pipe to shell",
        "description": "pipes remote content to shell",
        "file": "install.sh",
        "line": 2,
        "snippet": "curl example.com | sh",
        "category": "test",
        "rule_id": "SA-SH-001",
        "confidence": 0.75,
        "needs_adjudication": True,
    }
    finding.update(overrides)
    return finding


def _add(repo, db, relpath="install.sh", rule_id="SA-SH-001", reason="benign in context"):
    fp_and_hash = suppressions.fingerprint_and_hash(str(repo), relpath, rule_id)
    assert fp_and_hash is not None
    fingerprint, content_hash = fp_and_hash
    result = scan_history.add_suppression_safely(
        fingerprint, rule_id, relpath, content_hash, reason, db_path=db
    )
    assert result is not None
    return fingerprint


# --- fingerprint identity -------------------------------------------------

def test_fingerprint_stable_for_identical_content(repo):
    assert suppressions.fingerprint_for(str(repo), "install.sh", "SA-SH-001") == \
        suppressions.fingerprint_for(str(repo), "install.sh", "SA-SH-001")


def test_fingerprint_changes_on_any_content_edit(repo):
    before = suppressions.fingerprint_for(str(repo), "install.sh", "SA-SH-001")
    with open(repo / "install.sh", "a") as handle:
        handle.write("# one byte different\n")
    after = suppressions.fingerprint_for(str(repo), "install.sh", "SA-SH-001")
    assert before != after


def test_fingerprint_scoped_to_rule_and_file(repo):
    base = suppressions.fingerprint_for(str(repo), "install.sh", "SA-SH-001")
    assert base != suppressions.fingerprint_for(str(repo), "install.sh", "SA-SH-002")
    assert base != suppressions.fingerprint_for(str(repo), "notes.txt", "SA-SH-001")


def test_fingerprint_missing_file_returns_none(repo, tmp_path):
    assert suppressions.fingerprint_for(str(repo), "ghost.sh", "SA-SH-001") is None
    assert suppressions.fingerprint_for(str(tmp_path), "../repo/install.sh", "SA-SH-001") is None


def test_fingerprint_rejects_traversal_and_absolute(repo):
    assert suppressions.fingerprint_for(str(repo), "../../etc/passwd", "X") is None
    assert suppressions.fingerprint_for(str(repo), "/etc/passwd", "X") is None
    assert suppressions.fingerprint_for(str(repo), "", "X") is None
    assert suppressions.fingerprint_for(str(repo), "install.sh", "") is None


def test_fingerprint_symlink_escape_returns_none(repo, tmp_path):
    outside = tmp_path / "outside.sh"
    outside.write_text("x")
    os.symlink(str(outside), repo / "linked.sh")
    assert suppressions.fingerprint_for(str(repo), "linked.sh", "X") is None


# --- eligibility guard ----------------------------------------------------

def test_block_tier_never_eligible(repo, db):
    fingerprint = _add(repo, db)
    findings = [_warn_finding(confidence=0.95)]
    active, suppressed = suppressions.partition_suppressed(
        findings, str(repo), suppressions.load_active_records(db))
    assert len(active) == 1 and suppressed == []
    assert suppressions.load_active_records(db)[0]["fingerprint"] == fingerprint


def test_correlation_never_eligible(repo, db):
    _add(repo, db)
    findings = [_warn_finding(scanner="correlation")]
    active, suppressed = suppressions.partition_suppressed(
        findings, str(repo), suppressions.load_active_records(db))
    assert len(active) == 1 and suppressed == []


def test_missing_rule_id_or_file_never_eligible(repo, db):
    _add(repo, db)
    records = suppressions.load_active_records(db)
    for broken in (_warn_finding(rule_id=""), _warn_finding(file=""),
                   _warn_finding(confidence="not-a-number"),
                   _warn_finding(confidence=0.59), _warn_finding(confidence=0.92)):
        active, suppressed = suppressions.partition_suppressed([broken], str(repo), records)
        assert len(active) == 1 and suppressed == []


def test_exact_match_is_suppressed_and_annotated(repo, db):
    fingerprint = _add(repo, db, reason="example code, not executed")
    records = suppressions.load_active_records(db)
    active, suppressed = suppressions.partition_suppressed(
        [_warn_finding()], str(repo), records)
    assert active == []
    assert len(suppressed) == 1
    entry = suppressed[0]
    assert "needs_adjudication" not in entry
    assert entry["suppression_source"] == "adjudication"
    assert entry["suppression"]["fingerprint"] == fingerprint
    assert entry["suppression"]["reason"] == "example code, not executed"


def test_edited_content_re_fires(repo, db):
    _add(repo, db)
    with open(repo / "install.sh", "a") as handle:
        handle.write("echo changed\n")
    active, suppressed = suppressions.partition_suppressed(
        [_warn_finding()], str(repo), suppressions.load_active_records(db))
    assert len(active) == 1 and suppressed == []
    assert active[0].get("needs_adjudication") is True


# --- store behavior --------------------------------------------------------

def test_read_path_never_creates_db(tmp_path, monkeypatch):
    db = str(tmp_path / "subdir" / "history.db")
    monkeypatch.setenv("REPO_FORENSICS_HISTORY_DB", db)
    assert suppressions.load_active_records() == []
    assert not os.path.exists(db)
    assert not os.path.exists(os.path.dirname(db))


def test_corrupt_db_is_failure_safe(tmp_path, monkeypatch):
    db = tmp_path / "history.db"
    db.write_bytes(b"this is not sqlite")
    monkeypatch.setenv("REPO_FORENSICS_HISTORY_DB", str(db))
    assert suppressions.load_active_records() == []
    findings = [_warn_finding()]
    active, suppressed = suppressions.partition_suppressed(findings, "/repo", [])
    assert active == findings and suppressed == []


def test_revoke_by_unique_prefix_and_ambiguity(repo, db):
    _add(repo, db, relpath="install.sh", rule_id="SA-SH-001")
    _add(repo, db, relpath="notes.txt", rule_id="SA-SH-009")
    store = scan_history.HistoryStore(db)
    fps = [r["fingerprint"] for r in store.list_suppressions()]
    # An empty (or shared) prefix matches more than one record: refuse.
    with pytest.raises(ValueError):
        store.revoke_suppression("")
    # A unique prefix revokes exactly that record.
    prefix = fps[0][:12]
    if prefix != fps[1][:12]:
        assert store.revoke_suppression(prefix) == 1
    else:  # astronomically unlikely; fall back to exact match semantics
        assert store.revoke_suppression(fps[0]) == 1
    assert [r["fingerprint"] for r in store.list_suppressions()] == [fps[1]]
    # Exact fingerprint revokes; unknown prefix returns 0; clear empties.
    assert store.revoke_suppression(fps[1]) == 1
    assert store.revoke_suppression("deadbeef") == 0
    assert store.clear_suppressions() == 0


def test_add_refreshes_existing_record(repo, db):
    _add(repo, db, reason="first")
    _add(repo, db, reason="second")
    records = scan_history.HistoryStore(db).list_suppressions()
    assert len(records) == 1
    assert records[0]["reason"] == "second"


# --- aggregate_json wiring -------------------------------------------------

def _write_scanner_output(tmp_path, name, findings, exit_code="1"):
    (tmp_path / f"{name}.out").write_text(json.dumps(findings))
    (tmp_path / f"{name}.err").write_text("")
    (tmp_path / f"{name}.exit").write_text(exit_code)


def test_aggregate_report_applies_suppression(repo, db, tmp_path):
    _add(repo, db, reason="adjudicated benign")
    results = tmp_path / "results"
    results.mkdir()
    _write_scanner_output(results, "sast", [_warn_finding()])

    report = aggregate_json.build_report(str(results), str(repo), "false")

    assert report["summary"]["total"] == 0
    assert report["exit_code"] == 0
    assert not any(f.get("needs_adjudication") for f in report["findings"])
    assert len(report["suppressed"]) == 1
    assert report["suppressed"][0]["suppression_source"] == "adjudication"
    supp = report["adjudication_suppressions"]
    assert len(supp["applied"]) == 1
    assert supp["applied"][0]["rule_id"] == "SA-SH-001"
    assert len(supp["active"]) == 1


def test_aggregate_report_block_survives_suppression_record(repo, db, tmp_path):
    _add(repo, db)
    results = tmp_path / "results"
    results.mkdir()
    _write_scanner_output(results, "sast",
                          [_warn_finding(confidence=0.95, severity="critical")],
                          exit_code="2")

    report = aggregate_json.build_report(str(results), str(repo), "false")

    assert report["exit_code"] == 2
    assert report["summary"]["total"] == 1
    assert report["suppressed"] == []
    assert report["adjudication_suppressions"]["applied"] == []
    assert len(report["adjudication_suppressions"]["active"]) == 1


def test_aggregate_text_report_lists_suppressions(repo, db, tmp_path):
    _add(repo, db, reason="adjudicated benign")
    results = tmp_path / "results"
    results.mkdir()
    _write_scanner_output(results, "sast", [_warn_finding()])
    report = aggregate_json.build_report(str(results), str(repo), "false")

    text = aggregate_json.format_report_as_text(report)
    assert "ADJUDICATION SUPPRESSIONS: 1 active (1 applied this run)" in text
    assert "adjudicated benign" in text
    assert "revoke" in text and "--all" in text
    assert "ADJUDICATION REQUIRED" not in text


def test_clean_report_has_no_suppression_section(repo, db, tmp_path):
    results = tmp_path / "results"
    results.mkdir()
    _write_scanner_output(results, "sast", [], exit_code="0")
    report = aggregate_json.build_report(str(results), str(repo), "false")
    text = aggregate_json.format_report_as_text(report)
    assert "ADJUDICATION SUPPRESSIONS" not in text
    assert report["adjudication_suppressions"] == {"applied": [], "active": []}


# --- auto_scan wiring ------------------------------------------------------

def test_auto_scan_format_output_reports_suppressions(repo, db):
    _add(repo, db)
    kept, suppressed = auto_scan.apply_adjudication_suppressions(
        [_warn_finding()], str(repo))
    assert kept == [] and len(suppressed) == 1
    output = auto_scan.format_output(
        [], "git clone x", "git_clone", "repo", adjudication_suppressed=suppressed)
    assert "suppressed by prior adjudication" in output
    assert "ADJUDICATION REQUIRED" not in output


def test_auto_scan_filter_failure_safe(repo, monkeypatch):
    monkeypatch.setenv("REPO_FORENSICS_HISTORY_DB",
                       os.path.join(str(repo), "no-such-dir", "h.db"))
    findings = [_warn_finding()]
    kept, suppressed = auto_scan.apply_adjudication_suppressions(findings, str(repo))
    assert kept == findings and suppressed == []


def test_auto_scan_block_survives_suppression(repo, db):
    _add(repo, db)
    kept, suppressed = auto_scan.apply_adjudication_suppressions(
        [_warn_finding(confidence=0.95)], str(repo))
    assert len(kept) == 1 and suppressed == []


# --- CLI -------------------------------------------------------------------

def _run_cli(*argv, env_extra=None):
    env = dict(os.environ)
    if env_extra:
        env.update(env_extra)
    return subprocess.run(
        [sys.executable, SUPPRESSIONS_PY, *argv],
        capture_output=True, text=True, env=env, timeout=60,
    )


def test_cli_add_list_revoke_roundtrip(repo, db):
    env = {"REPO_FORENSICS_HISTORY_DB": db}
    result = _run_cli("add", "--repo", str(repo), "--file", "install.sh",
                      "--rule-id", "SA-SH-001", "--reason", "benign", env_extra=env)
    assert result.returncode == 0, result.stderr
    assert "suppressed" in result.stdout

    result = _run_cli("list", env_extra=env)
    assert result.returncode == 0
    assert "SA-SH-001" in result.stdout and "install.sh" in result.stdout
    assert "benign" in result.stdout

    result = _run_cli("list", "--json", env_extra=env)
    payload = json.loads(result.stdout)
    assert len(payload) == 1
    fingerprint = payload[0]["fingerprint"]

    result = _run_cli("revoke", "--fingerprint", fingerprint[:12], env_extra=env)
    assert result.returncode == 0, result.stderr
    result = _run_cli("list", env_extra=env)
    assert "no active" in result.stdout


def test_cli_add_requires_reason_and_real_file(repo, db):
    env = {"REPO_FORENSICS_HISTORY_DB": db}
    result = _run_cli("add", "--repo", str(repo), "--file", "install.sh",
                      "--rule-id", "SA-SH-001", "--reason", "  ", env_extra=env)
    assert result.returncode == 2
    result = _run_cli("add", "--repo", str(repo), "--file", "ghost.sh",
                      "--rule-id", "SA-SH-001", "--reason", "x", env_extra=env)
    assert result.returncode == 2
    result = _run_cli("add", "--repo", str(repo), "--file", "../../etc/passwd",
                      "--rule-id", "SA-SH-001", "--reason", "x", env_extra=env)
    assert result.returncode == 2
    assert not os.path.exists(db)  # refused adds never create the DB


def test_cli_reason_is_sanitized(repo, db):
    env = {"REPO_FORENSICS_HISTORY_DB": db}
    result = _run_cli("add", "--repo", str(repo), "--file", "install.sh",
                      "--rule-id", "SA-SH-001",
                      "--reason", "ok\x1b[31m\u202e hidden", env_extra=env)
    assert result.returncode == 0
    records = scan_history.HistoryStore(db).list_suppressions()
    assert "\x1b" not in records[0]["reason"]
    assert "\u202e" not in records[0]["reason"]


def test_cli_revoke_all_and_unknown(repo, db):
    env = {"REPO_FORENSICS_HISTORY_DB": db}
    _run_cli("add", "--repo", str(repo), "--file", "install.sh",
             "--rule-id", "SA-SH-001", "--reason", "x", env_extra=env)
    result = _run_cli("revoke", "--fingerprint", "deadbeef", env_extra=env)
    assert result.returncode == 2
    result = _run_cli("revoke", "--all", env_extra=env)
    assert result.returncode == 0
    assert "revoked 1" in result.stdout


def test_cli_revoke_on_missing_db(tmp_path):
    env = {"REPO_FORENSICS_HISTORY_DB": str(tmp_path / "none.db")}
    result = _run_cli("revoke", "--all", env_extra=env)
    assert result.returncode == 0
    assert "no active" in result.stdout


# --- focused-mode scanner count -------------------------------------------

@_POSIX_ONLY
def test_focused_mode_count_matches_launcher(repo):
    """The --skill-scan banner count must equal the number of scanners the
    launcher actually starts (the old hardcoded 18 drifted to 19 launches)."""
    import re as _re

    script = os.path.join(SCRIPTS_DIR, "run_forensics.sh")
    result = subprocess.run(
        ["bash", script, str(repo), "--skill-scan", "--format", "json", "--offline"],
        capture_output=True, text=True, timeout=300,
    )
    report = json.loads(result.stdout)
    scanner_names = [s["name"] for s in report["scanners"] if s["name"] != "correlation"]

    text = subprocess.run(
        ["bash", script, str(repo), "--skill-scan", "--format", "text", "--offline"],
        capture_output=True, text=True, timeout=300,
    ).stdout
    match = _re.search(r"Running focused skill scan \((\d+) scanners\)", text)
    assert match, f"banner missing; stdout head: {text[:400]}"
    assert int(match.group(1)) == len(scanner_names)


def test_critical_warn_band_finding_never_eligible(repo, db):
    # Many critical rules carry WARN-band confidence; the exit code follows
    # severity, so silencing one would turn a blocking scan into a clean one.
    finding = _warn_finding(severity="critical", confidence=0.85)
    _add(repo, db)
    active, suppressed = suppressions.partition_suppressed(
        [finding], str(repo), suppressions.load_active_records())
    assert suppressed == [] and active == [finding]


def test_prompt_injection_finding_never_eligible(repo, db):
    finding = _warn_finding(rule_id="ST-PI-001", severity="high", confidence=0.85)
    _add(repo, db, rule_id="ST-PI-001")
    active, suppressed = suppressions.partition_suppressed(
        [finding], str(repo), suppressions.load_active_records())
    assert suppressed == [] and active == [finding]
    assert suppressions.persist_command(finding) is None


def test_persist_command_quotes_repo_controlled_file_name():
    import shlex
    hostile = 'docs/$(touch PWNED)";touch p;\'x.md'
    cmd = suppressions.persist_command(_warn_finding(file=hostile))
    assert cmd is not None
    argv = shlex.split(cmd.replace("<scanned-repo>", "/r").replace("'<why>'", "why"))
    assert argv[argv.index("--file") + 1] == hostile
    assert suppressions.persist_command(_warn_finding(severity="critical")) is None
    assert suppressions.persist_command(_warn_finding(file="a\nb.md")) is None


def test_adjudication_block_prints_persist_line_only_when_allowed():
    import adjudication
    block = adjudication.build_adjudication_block([
        _warn_finding(),
        _warn_finding(rule_id="ST-PI-002", file="README.md", title="Injection"),
    ])
    persist_lines = [ln for ln in block.splitlines() if ln.strip().startswith("persist:")]
    assert len(persist_lines) == 1
    assert "--file install.sh" in persist_lines[0]


def test_revoke_rejects_non_hex_and_wildcards(repo, db):
    _add(repo, db)
    store = scan_history.HistoryStore(db)
    for bad in ("", "%", "_", "abc", "ABCD", "de%d", "zzzz"):
        with pytest.raises(ValueError):
            store.revoke_suppression(bad)
    assert len(store.list_suppressions()) == 1


def test_report_lists_only_suppressions_for_this_repo(repo, db, tmp_path):
    other = tmp_path / "other"
    other.mkdir()
    (other / "secret-plan.md").write_text("x\n")
    _add(other, db, relpath="secret-plan.md", rule_id="SA-SH-001", reason="other project")
    _add(repo, db, reason="this project")
    results = tmp_path / "results"
    results.mkdir()
    _write_scanner_output(results, "sast", [_warn_finding()])
    report = aggregate_json.build_report(str(results), str(repo), "false")
    files = [r["file"] for r in report["adjudication_suppressions"]["active"]]
    assert files == ["install.sh"]
    assert "other project" not in aggregate_json.format_report_as_text(report)
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 196kUpdated Claude CodeCodexVerifiedInstall