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_refresh_controller.py

View on GitHub
import json
import hashlib
import importlib.util
import os
import sys
import time
from pathlib import Path
from types import SimpleNamespace

import refresh_controller as controller


def _redirect_state(monkeypatch, tmp_path):
    home = tmp_path / "home with spaces"
    cache = home / ".cache" / "repo-forensics"
    data = home / ".local" / "share" / "repo-forensics"
    values = {
        "HOME": home,
        "CACHE_DIR": cache,
        "DATA_DIR": data,
        "VERSIONS_DIR": data / "versions",
        "ACTIVE_STATE": data / "active.json",
        "REFRESH_STATE": cache / "refresh-state.json",
        "SUCCESS_MARKER": cache / ".last-refresh",
        "ATTEMPT_MARKER": cache / ".last-refresh-attempt",
        "DISABLED_MARKER": cache / "refresh.disabled",
        "CONTROLLER_LOCK": cache / "controller.lock",
        "BOOTSTRAP_LOG": cache / "scheduler.log",
        "REFRESH_STDIO_LOG": cache / "refresh-stdio.log",
    }
    for name, value in values.items():
        monkeypatch.setattr(controller, name, value)
    return home, cache, data


def _signed_candidate(monkeypatch, tmp_path):
    skill = tmp_path / "signed-skill"
    for rel in controller.REQUIRED_PAYLOAD_FILES:
        path = skill / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(f"# {rel}\n")
    files = {
        rel: hashlib.sha256((skill / rel).read_bytes()).hexdigest()
        for rel in sorted(controller.REQUIRED_PAYLOAD_FILES)
    }
    manifest = json.dumps({
        "version": "2", "file_count": len(files), "files": files,
    }, indent=2).encode() + b"\n"
    (skill / "checksums.json").write_bytes(manifest)
    signer_path = Path(__file__).resolve().parents[3] / "scripts" / "_ed25519_sign.py"
    spec = importlib.util.spec_from_file_location("test_release_signer", signer_path)
    signer = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(signer)
    seed = bytes(range(32))
    _private, public = signer.keypair(seed)
    (skill / "checksums.json.sig").write_bytes(signer.sign(manifest, seed, public))
    monkeypatch.setattr(controller, "CHECKSUMS_PUBKEY_HEX", public.hex())
    return skill


def test_future_attempt_and_success_markers_are_due(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    controller.SUCCESS_MARKER.parent.mkdir(parents=True)
    controller.SUCCESS_MARKER.write_text("future")
    future = time.time() + 86400
    os.utime(controller.SUCCESS_MARKER, (future, future))

    assert controller._timestamp_is_due(controller.SUCCESS_MARKER, 86400)


def test_signed_complete_manifest_rejects_tamper_and_unexpected_files(monkeypatch, tmp_path):
    skill = _signed_candidate(monkeypatch, tmp_path)
    assert controller._verify_skill(skill) == (True, "verified")

    extra = skill / "scripts" / "unmanifested.py"
    extra.write_text("print('unexpected')\n")
    ok, detail = controller._verify_skill(skill)
    assert ok is False and "unexpected files" in detail
    extra.unlink()

    target = skill / "scripts" / "ioc_manager.py"
    target.write_text("# tampered\n")
    ok, detail = controller._verify_skill(skill)
    assert ok is False and "integrity mismatch" in detail


def test_signed_manifest_rejects_wrong_signature(monkeypatch, tmp_path):
    skill = _signed_candidate(monkeypatch, tmp_path)
    (skill / "checksums.json.sig").write_bytes(b"x" * 64)

    ok, detail = controller._verify_skill(skill)

    assert ok is False
    assert "signature invalid" in detail


def test_verify_ignores_payload_supplied_verifier(monkeypatch, tmp_path):
    # Trust-model regression: the candidate payload is required to carry its own
    # scripts/_ed25519.py. A hostile payload could ship a permissive verifier
    # that approves any signature. _verify_skill must use the controller's own
    # trusted verifier and never the candidate's, so a bad signature is still
    # rejected even when the payload's verifier would have accepted it.
    skill = _signed_candidate(monkeypatch, tmp_path)
    (skill / "checksums.json.sig").write_bytes(b"x" * 64)
    (skill / "scripts" / "_ed25519.py").write_text(
        "def verify(signature, message, public_key):\n    return True\n"
    )

    ok, detail = controller._verify_skill(skill)

    assert ok is False
    assert "signature invalid" in detail
    # The trusted verifier (this repo's own _ed25519) must own the cache slot.
    assert sys.modules["_ed25519"].__file__ == str(
        controller._TRUSTED_SCRIPTS_DIR / "_ed25519.py"
    )


def test_promotion_never_downgrades_active_cross_agent_payload(monkeypatch, tmp_path):
    _home, _cache, data = _redirect_state(monkeypatch, tmp_path)
    active_skill = data / "versions" / "3.0.0"
    scripts = active_skill / "scripts"
    scripts.mkdir(parents=True)
    (active_skill / "VERSION").write_text("3.0.0\n")
    refresh = scripts / "refresh_threat_dbs.py"
    refresh.write_text("# active\n")
    (scripts / "refresh_controller.py").write_text("# active controller\n")
    active = {"version": "3.0.0", "refresh_script": str(refresh),
              "controller": str(scripts / "refresh_controller.py")}
    controller.ACTIVE_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.ACTIVE_STATE.write_text(json.dumps(active))
    candidate = tmp_path / "older" / "skills" / "repo-forensics"
    candidate.mkdir(parents=True)
    (candidate / "checksums.json").write_text("{}\n")
    monkeypatch.setattr(controller, "_candidate", lambda: (candidate, "2.11.5"))
    monkeypatch.setattr(controller, "_verify_skill", lambda _path: (True, "verified"))

    selected = controller.promote_payload()

    assert selected["version"] == "3.0.0"
    assert not (controller.VERSIONS_DIR / "2.11.5").exists()


def test_promotion_copies_verified_payload_to_stable_version(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    candidate = tmp_path / "plugin" / "skills" / "repo-forensics"
    scripts = candidate / "scripts"
    scripts.mkdir(parents=True)
    (scripts / "refresh_threat_dbs.py").write_text("# refresh\n")
    (scripts / "refresh_controller.py").write_text("# controller\n")
    (candidate / "checksums.json").write_text("{}\n")
    monkeypatch.setattr(controller, "_candidate", lambda: (candidate, "2.11.5"))
    monkeypatch.setattr(controller, "_verify_skill", lambda _path: (True, "verified"))
    monkeypatch.setattr(controller.subprocess, "run", lambda *a, **k: SimpleNamespace(
        returncode=0, stdout="", stderr=""))

    active = controller.promote_payload()

    assert active["version"] == "2.11.5"
    assert Path(active["refresh_script"]).is_file()
    assert Path(active["controller"]).is_file()
    assert Path(active["refresh_script"]).parents[1].joinpath("VERSION").read_text().strip() == "2.11.5"


def test_scheduler_targets_stable_controller_not_refresh_script(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    active = {"controller": "/stable/controller.py", "refresh_script": "/stable/refresh.py"}

    plist = controller._mac_plist(active)
    service = controller._systemd_quote("/stable/controller.py")
    windows = controller._windows_task_command(active)

    assert plist["ProgramArguments"][-2:] == ["/stable/controller.py", "run"]
    assert service in f"ExecStart={service} run"
    assert "/stable/controller.py" in windows and windows.endswith(" run")
    assert controller.LABEL.endswith("-v2")
    assert controller.LABEL != controller.LEGACY_LABEL


def test_status_is_machine_readable_per_feed(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    skill = controller.VERSIONS_DIR / "2.11.5"
    scripts = skill / "scripts"
    scripts.mkdir(parents=True)
    (skill / "VERSION").write_text("2.11.5\n")
    refresh = scripts / "refresh_threat_dbs.py"
    refresh.write_text("# refresh\n")
    controller.ACTIVE_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.ACTIVE_STATE.write_text(json.dumps({
        "version": "2.11.5", "refresh_script": str(refresh),
        "controller": str(scripts / "refresh_controller.py")}))
    controller.REFRESH_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.REFRESH_STATE.write_text(json.dumps({
        "status": "degraded", "last_attempt": 10,
        "feeds": {"ioc": {"ok": True}, "kev": {"ok": False}}}))

    result = controller.status()

    assert result["status"] == "degraded"
    assert result["feeds"]["kev"]["ok"] is False
    assert result["active_version"] == "2.11.5"


def test_existing_stable_controller_authenticates_future_candidate(monkeypatch, tmp_path):
    _home, _cache, data = _redirect_state(monkeypatch, tmp_path)
    stable = data / "versions" / "2.11.4" / "scripts" / "refresh_controller.py"
    stable.parent.mkdir(parents=True)
    stable.write_text("# stable\n")
    candidate = tmp_path / "marketplace" / "skills" / "repo-forensics"
    candidate.mkdir(parents=True)
    controller.ACTIVE_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.ACTIVE_STATE.write_text(json.dumps({
        "version": "2.11.4", "controller": str(stable),
        "refresh_script": str(stable.with_name("refresh_threat_dbs.py")),
    }))
    monkeypatch.setattr(controller, "_active_is_usable", lambda _active: True)
    seen = {}

    def fake_run(args, **_kwargs):
        seen["args"] = args
        return SimpleNamespace(returncode=0, stdout='{"ok": true, "status": "ready"}\n', stderr="")

    monkeypatch.setattr(controller.subprocess, "run", fake_run)
    result = controller._delegate_to_stable(candidate)

    assert result["ok"] is True
    assert result["delegated_to_stable"] is True
    assert seen["args"][1:] == [str(stable.resolve()), "adopt", "--candidate",
                                str(candidate), "--json"]


def test_stable_controller_delegation_failure_is_fail_closed(monkeypatch, tmp_path):
    _home, _cache, data = _redirect_state(monkeypatch, tmp_path)
    stable = data / "versions" / "2.11.4" / "scripts" / "refresh_controller.py"
    stable.parent.mkdir(parents=True)
    stable.write_text("# stable\n")
    controller.ACTIVE_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.ACTIVE_STATE.write_text(json.dumps({
        "version": "2.11.4", "controller": str(stable), "refresh_script": str(stable),
    }))
    monkeypatch.setattr(controller, "_active_is_usable", lambda _active: True)
    monkeypatch.setattr(controller.subprocess, "run", lambda *_a, **_k: SimpleNamespace(
        returncode=1, stdout="not-json\n", stderr="boom"))

    result = controller._delegate_to_stable(tmp_path / "candidate")

    assert result["ok"] is False
    assert result["delegated_to_stable"] is True
    assert "delegation failed" in result["error"]


def test_failed_candidate_self_check_preserves_active_pointer(monkeypatch, tmp_path):
    _home, _cache, data = _redirect_state(monkeypatch, tmp_path)
    old = {"version": "2.11.4", "controller": "/old/controller.py",
           "refresh_script": "/old/refresh.py"}
    controller.ACTIVE_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.ACTIVE_STATE.write_text(json.dumps(old))
    candidate = tmp_path / "candidate"
    (candidate / "scripts").mkdir(parents=True)
    (candidate / "scripts" / "refresh_controller.py").write_text("# controller\n")
    (candidate / "scripts" / "refresh_threat_dbs.py").write_text("# refresh\n")
    (candidate / "checksums.json").write_text("{}\n")
    monkeypatch.setattr(controller, "_candidate", lambda *_a: (candidate, "2.11.5"))
    monkeypatch.setattr(controller, "_verify_skill", lambda _path: (True, "verified"))
    monkeypatch.setattr(controller, "_active_is_usable", lambda _active: False)
    monkeypatch.setattr(controller.subprocess, "run", lambda *_a, **_k: SimpleNamespace(
        returncode=1, stdout="", stderr="self-check failed"))

    try:
        controller.promote_payload(candidate)
    except RuntimeError as exc:
        assert "self-check failed" in str(exc)
    else:
        raise AssertionError("promotion unexpectedly succeeded")

    assert json.loads(controller.ACTIVE_STATE.read_text()) == old


def test_attempt_throttle_has_one_atomic_source(monkeypatch, tmp_path):
    _home, cache, _data = _redirect_state(monkeypatch, tmp_path)
    controller._mark_attempt()

    state = json.loads(controller.REFRESH_STATE.read_text())
    assert isinstance(state["last_attempt"], float)
    assert state["trigger_status"] == "requested"
    assert not controller.ATTEMPT_MARKER.exists()
    assert controller._attempt_due() is False


def test_status_rejects_future_success_marker(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    controller.SUCCESS_MARKER.parent.mkdir(parents=True)
    controller.SUCCESS_MARKER.write_text("future")
    future = time.time() + 3600
    os.utime(controller.SUCCESS_MARKER, (future, future))
    controller.REFRESH_STATE.write_text(json.dumps({
        "status": "healthy", "feeds": {"ioc": {"ok": True}},
    }))
    monkeypatch.setattr(controller, "_active_is_usable", lambda _active: True)
    monkeypatch.setattr(controller, "_scheduler_status", lambda _active: (True, "healthy"))

    result = controller.status()

    assert result["ok"] is False
    assert result["clock_skew"] is True
    assert result["refresh_healthy"] is False


def test_run_reports_worker_degradation_despite_zero_exit(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    controller.ACTIVE_STATE.parent.mkdir(parents=True, exist_ok=True)
    controller.ACTIVE_STATE.write_text(json.dumps({
        "version": "2.11.5", "controller": "/stable/controller.py",
        "refresh_script": "/stable/refresh.py",
    }))
    monkeypatch.setattr(controller, "_active_is_usable", lambda _active: True)

    def fake_popen(_args, **kwargs):
        run_id = kwargs["env"]["REPO_FORENSICS_RUN_ID"]
        controller.REFRESH_STATE.write_text(json.dumps({
            "run_id": run_id, "status": "degraded",
            "feeds": {"ioc": {"ok": False}},
        }))
        # 2.14.7: run_active spawns the worker with Popen in its own process
        # group so a timeout can reap the scanners it fans out into, rather
        # than orphaning them. wait() stands in for the old run() returncode.
        return SimpleNamespace(returncode=0, pid=-1,
                               wait=lambda timeout=None: 0, poll=lambda: 0)

    monkeypatch.setattr(controller.subprocess, "Popen", fake_popen)
    result = controller.run_active()

    assert result["operation_ok"] is True
    assert result["ok"] is False
    assert result["refresh_healthy"] is False
    assert result["status"] == "degraded"


def test_disable_exit_code_tracks_scheduler_removal_not_health(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    monkeypatch.setattr(controller, "_remove_all_schedulers", lambda: (True, "removed"))

    assert controller.main(["disable", "--json"]) == 0
    assert controller.DISABLED_MARKER.is_file()


def test_enable_when_never_disabled_does_not_crash(monkeypatch, tmp_path):
    # Regression: `enable` with no pre-existing disable marker used to leave
    # `result` unbound (FileNotFoundError silenced, else-branch skipped) and
    # crash with NameError — the exact command the boot warning tells users to
    # run to re-enable refresh.
    _redirect_state(monkeypatch, tmp_path)
    monkeypatch.setattr(controller, "ensure",
                        lambda *a, **k: {"ok": True, "operation_ok": True, "status": "ready"})
    assert not controller.DISABLED_MARKER.exists()

    assert controller.main(["enable", "--json"]) == 0


def test_enable_removes_existing_marker(monkeypatch, tmp_path):
    _redirect_state(monkeypatch, tmp_path)
    controller.DISABLED_MARKER.parent.mkdir(parents=True, exist_ok=True)
    controller.DISABLED_MARKER.write_text("disabled by user\n")
    monkeypatch.setattr(controller, "ensure",
                        lambda *a, **k: {"ok": True, "operation_ok": True, "status": "ready"})

    assert controller.main(["enable", "--json"]) == 0
    assert not controller.DISABLED_MARKER.exists()


def test_version_tuple_handles_non_string():
    # Regression: a JSON-null version field reached _version_tuple as None and
    # raised AttributeError (not caught by the TypeError/ValueError guard).
    assert controller._version_tuple(None) == ()
    assert controller._version_tuple(123) == ()
    assert controller._version_tuple("") == ()
    assert controller._version_tuple("2.11.5") == (2, 11, 5)


def test_controller_lock_excludes_same_process_reentry(monkeypatch, tmp_path):
    # POSIX flock is per-process, so two threads could both pass the file lock.
    # The in-process mutex must reject a second concurrent acquisition.
    _redirect_state(monkeypatch, tmp_path)
    controller.CACHE_DIR.mkdir(parents=True, exist_ok=True)
    with controller._ControllerLock():
        try:
            with controller._ControllerLock():
                raised = False
        except BlockingIOError:
            raised = True
    assert raised, "second same-process lock acquisition should raise BlockingIOError"
    # Lock is fully released afterwards: a fresh acquisition now succeeds.
    with controller._ControllerLock():
        pass


def test_ensure_selfheals_stale_uninstall_disable(monkeypatch, tmp_path):
    # A "disabled by uninstall" marker must NOT survive a reinstall: ensure()
    # runs only because the hook is installed, so it clears the stale marker and
    # proceeds to (re)enable. This is the self-heal path for users who hit the
    # refresh bug after an uninstall/reinstall cycle.
    _redirect_state(monkeypatch, tmp_path)
    controller.DISABLED_MARKER.parent.mkdir(parents=True, exist_ok=True)
    controller.DISABLED_MARKER.write_text("disabled by uninstall\n")
    monkeypatch.setattr(controller, "promote_payload",
                        lambda *a, **k: {"version": "2.11.5", "refresh_script": "/x",
                                         "controller": "/x"})
    monkeypatch.setattr(controller, "_retire_legacy_scheduler", lambda: None)
    monkeypatch.setattr(controller, "_ensure_scheduler", lambda a: (True, "macos", "ok"))
    monkeypatch.setattr(controller, "_timestamp_is_due", lambda *a: False)
    monkeypatch.setattr(controller, "_active_is_usable", lambda a: True)

    result = controller.ensure()

    assert result["status"] != "disabled"
    assert not controller.DISABLED_MARKER.exists(), "stale uninstall marker must be cleared"


def test_ensure_respects_explicit_user_disable(monkeypatch, tmp_path):
    # An explicit `disable` is deliberate intent and MUST stay sticky across
    # ensure() calls / updates — only an uninstall marker self-heals.
    _redirect_state(monkeypatch, tmp_path)
    controller.DISABLED_MARKER.parent.mkdir(parents=True, exist_ok=True)
    controller.DISABLED_MARKER.write_text("disabled by user\n")
    monkeypatch.setattr(controller, "_remove_all_schedulers", lambda: (True, "removed"))

    result = controller.ensure()

    assert result["status"] == "disabled"
    assert controller.DISABLED_MARKER.exists(), "explicit user disable must persist"


def test_ensure_selfheal_requires_exact_uninstall_sentinel(monkeypatch, tmp_path):
    # A user-disable marker whose free text merely contains the word "uninstall"
    # must NOT be self-healed — only the exact "disabled by uninstall" sentinel.
    _redirect_state(monkeypatch, tmp_path)
    controller.DISABLED_MARKER.parent.mkdir(parents=True, exist_ok=True)
    controller.DISABLED_MARKER.write_text("no uninstall needed; user disabled\n")
    monkeypatch.setattr(controller, "_remove_all_schedulers", lambda: (True, "removed"))

    result = controller.ensure()

    assert result["status"] == "disabled"
    assert controller.DISABLED_MARKER.exists()


def test_controller_lock_releases_process_lock_on_mkdir_failure(monkeypatch, tmp_path):
    # Regression: mkdir/chmod raising inside __enter__ must not leak _PROCESS_LOCK.
    _redirect_state(monkeypatch, tmp_path)

    def boom(*a, **k):
        raise OSError("cannot mkdir")
    monkeypatch.setattr(controller.CACHE_DIR.__class__, "mkdir", boom)

    try:
        with controller._ControllerLock():
            pass
    except OSError:
        pass
    # The process lock must be free again — a subsequent acquire succeeds.
    assert controller._PROCESS_LOCK.acquire(blocking=False)
    controller._PROCESS_LOCK.release()
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: 194kUpdated Claude CodeCodexVerifiedInstall