The world's first agentic reverse engineer.
test deobfuscator
Amruth01855333217d
diff --git a/tests/test_agent_analyzer.py b/tests/test_agent_analyzer.pyindex 5443c31..a26b38b 100644--- a/tests/test_agent_analyzer.py+++ b/tests/test_agent_analyzer.py@@ -122,6 +122,28 @@ class TestAnalyzerAnalyze:assert result.name == "bad_name!@#"+ def test_signature_applied_tracks_success(self):+ response = LLMResponse(name="f", signature="void f(int x)")+ llm = _mock_llm(response)+ client = _mock_client()++ analyzer = Analyzer(client, llm)+ result = analyzer.analyze(_item(), _binary_info(), {}, [])++ assert result.signature_applied is True++ def test_signature_applied_tracks_failure(self):+ response = LLMResponse(name="f", signature="void f(cJSON *item)")+ llm = _mock_llm(response)+ client = _mock_client()+ client.set_function_signature.side_effect = Exception("Can't resolve datatype")++ analyzer = Analyzer(client, llm)+ result = analyzer.analyze(_item(), _binary_info(), {}, [])++ assert result.signature_applied is False+ assert result.signature == "void f(cJSON *item)"+class TestAnalyzerContext:def test_includes_decompilation(self):diff --git a/tests/test_deobfuscator.py b/tests/test_deobfuscator.pynew file mode 100644index 0000000..186061b--- /dev/null+++ b/tests/test_deobfuscator.py@@ -0,0 +1,338 @@+"""Tests for kong.agent.deobfuscator — classification heuristics, pattern loading,+and the Deobfuscator orchestrator.+"""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from kong.agent.analyzer import AnalysisContext, LLMResponse+from kong.agent.deobfuscator import (+ Deobfuscator,+ ObfuscationType,+ classify_obfuscation,+ load_patterns,+)+from kong.agent.models import FunctionResult+from kong.ghidra.types import BinaryInfo, FunctionInfo+++# ---------------------------------------------------------------------------+# Classification heuristic tests+# ---------------------------------------------------------------------------++_CFF_CODE = """\+void FUN_004015a0(int *data, int len) {+ int state = 0x3a2b;+ while (1) {+ switch (state) {+ case 0x3a2b:+ if (len <= 0) { state = 0x9e22; }+ else { state = 0x7f01; }+ break;+ case 0x7f01:+ data[0] ^= 0x55;+ state = 0x1c44;+ break;+ case 0x1c44:+ data++;+ len--;+ state = 0x3a2b;+ break;+ case 0x9e22:+ return;+ }+ }+}+"""++_BOGUS_CF_CODE = """\+int FUN_00401000(int a, int b) {+ int result;+ if ((a * (a + 1)) % 2 == 0) {+ result = a + b;+ } else {+ result = a ^ b ^ 0xDEAD;+ }+ if ((b & ~b) != 0) {+ result ^= 0xBEEF;+ }+ if ((a | ~a) == -1) {+ result += 1;+ }+ return result;+}+"""++_INSTRUCTION_SUB_CODE = """\+int FUN_00403000(int a, int b) {+ int t1 = (~a & b) | (a & ~b);+ int t2 = (a ^ b) + 2 * (a & b);+ return ~t1 + 1;+}+"""++_STRING_ENCRYPT_CODE = """\+void FUN_00404000(void) {+ char buf[14] = { 0x2a, 0x27, 0x2e, 0x2e, 0x29, 0x4e, 0x42, 0x3f, 0x29, 0x36, 0x2e, 0x26, 0x43, 0x42 };+ for (int i = 0; i < 14; i++) {+ buf[i] ^= 0x42;+ }+ puts(buf);+}+"""++_CLEAN_CODE = """\+int add(int a, int b) {+ return a + b;+}+"""+++class TestClassifyObfuscation:+ def test_detects_cff(self):+ techniques = classify_obfuscation(_CFF_CODE)+ assert ObfuscationType.CONTROL_FLOW_FLATTENING in techniques++ def test_detects_bogus_cf(self):+ techniques = classify_obfuscation(_BOGUS_CF_CODE)+ assert ObfuscationType.BOGUS_CONTROL_FLOW in techniques++ def test_detects_instruction_sub(self):+ techniques = classify_obfuscation(_INSTRUCTION_SUB_CODE)+ assert ObfuscationType.INSTRUCTION_SUBSTITUTION in techniques++ def test_detects_string_encrypt(self):+ techniques = classify_obfuscation(_STRING_ENCRYPT_CODE)+ assert ObfuscationType.STRING_ENCRYPTION in techniques++ def test_clean_code_no_obfuscation(self):+ techniques = classify_obfuscation(_CLEAN_CODE)+ assert techniques == []++ def test_combined_cff_and_bogus(self):+ combined = _CFF_CODE + "\n" + _BOGUS_CF_CODE+ techniques = classify_obfuscation(combined)+ assert ObfuscationType.CONTROL_FLOW_FLATTENING in techniques+ assert ObfuscationType.BOGUS_CONTROL_FLOW in techniques++ def test_empty_code(self):+ assert classify_obfuscation("") == []++ def test_vmprotect_needs_many_cases(self):+ code = "void dispatch(void) {\n"+ code += "while (1) {\n"+ code += " unsigned char opcode = *vip++;\n"+ code += " switch (opcode) {\n"+ for i in range(25):+ code += f" case {i}: vstack[vsp++] = reg[{i % 8}]; break;\n"+ code += " }\n}\n}\n"+ padding_lines = 210 - code.count("\n")+ code += "\n".join(f"// padding line {i}" for i in range(padding_lines))+ techniques = classify_obfuscation(code)+ assert ObfuscationType.VM_PROTECTION in techniques+++# ---------------------------------------------------------------------------+# Pattern library tests+# ---------------------------------------------------------------------------++class TestPatternLibrary:+ def test_load_cff_pattern(self):+ content = load_patterns([ObfuscationType.CONTROL_FLOW_FLATTENING])+ assert "Control Flow Flattening" in content+ assert "while(1)" in content or "while (1)" in content++ def test_load_bogus_cf_pattern(self):+ content = load_patterns([ObfuscationType.BOGUS_CONTROL_FLOW])+ assert "Bogus Control Flow" in content++ def test_load_multiple_patterns(self):+ content = load_patterns([+ ObfuscationType.CONTROL_FLOW_FLATTENING,+ ObfuscationType.BOGUS_CONTROL_FLOW,+ ])+ assert "Control Flow Flattening" in content+ assert "Bogus Control Flow" in content+ assert "---" in content++ def test_load_all_patterns(self):+ all_types = list(ObfuscationType)+ content = load_patterns(all_types)+ assert "Control Flow Flattening" in content+ assert "Instruction Substitution" in content+ assert "VM-Based Protection" in content++ def test_empty_techniques(self):+ content = load_patterns([])+ assert content == ""+++# ---------------------------------------------------------------------------+# Deobfuscator orchestrator tests+# ---------------------------------------------------------------------------++def _make_context(decompilation: str = "void foo() {}") -> AnalysisContext:+ return AnalysisContext(+ function=FunctionInfo(address=0x401000, name="FUN_00401000", size=200),+ decompilation=decompilation,+ binary_info=BinaryInfo(+ arch="x86", format="ELF", endianness="little",+ word_size=8, compiler="gcc",+ ),+ )+++class TestDeobfuscator:+ @pytest.fixture+ def mock_ghidra(self):+ return MagicMock()++ @pytest.fixture+ def mock_llm(self):+ llm = MagicMock()+ llm.analyze_with_tools.return_value = LLMResponse(+ name="deobfuscated_func",+ signature="int deobfuscated_func(int x)",+ confidence=75,+ classification="crypto",+ comments="Deobfuscated CFF function",+ reasoning="Used state machine tracer",+ )+ return llm++ def test_deobfuscate_returns_response(self, mock_ghidra, mock_llm):+ deob = Deobfuscator(mock_ghidra, mock_llm)+ context = _make_context(_CFF_CODE)+ response, tool_calls = deob.deobfuscate(+ context,+ [ObfuscationType.CONTROL_FLOW_FLATTENING],+ )+ assert response.name == "deobfuscated_func"+ assert response.confidence == 75+ mock_llm.analyze_with_tools.assert_called_once()++ def test_prompt_includes_pattern_context(self, mock_ghidra, mock_llm):+ deob = Deobfuscator(mock_ghidra, mock_llm)+ context = _make_context(_CFF_CODE)+ deob.deobfuscate(context, [ObfuscationType.CONTROL_FLOW_FLATTENING])+ call_kwargs = mock_llm.analyze_with_tools.call_args+ prompt = call_kwargs.kwargs.get("prompt") or call_kwargs[1].get("prompt") or call_kwargs[0][0]+ assert "Control Flow Flattening" in prompt or "cff" in prompt.lower()++ def test_prompt_includes_technique_list(self, mock_ghidra, mock_llm):+ deob = Deobfuscator(mock_ghidra, mock_llm)+ context = _make_context(_CFF_CODE)+ deob.deobfuscate(+ context,+ [ObfuscationType.CONTROL_FLOW_FLATTENING, ObfuscationType.BOGUS_CONTROL_FLOW],+ )+ call_kwargs = mock_llm.analyze_with_tools.call_args+ prompt = call_kwargs.kwargs.get("prompt") or call_kwargs[1].get("prompt") or call_kwargs[0][0]+ assert "cff" in prompt+ assert "bogus_cf" in prompt++ def test_passes_deobfuscation_system_prompt(self, mock_ghidra, mock_llm):+ from kong.agent.prompts import DEOBFUSCATION_SYSTEM_PROMPT++ deob = Deobfuscator(mock_ghidra, mock_llm)+ context = _make_context()+ deob.deobfuscate(context, [ObfuscationType.BOGUS_CONTROL_FLOW])+ call_kwargs = mock_llm.analyze_with_tools.call_args+ system = call_kwargs.kwargs.get("system") or call_kwargs[1].get("system") or call_kwargs[0][1]+ assert system == DEOBFUSCATION_SYSTEM_PROMPT++ def test_passes_tools(self, mock_ghidra, mock_llm):+ from kong.llm.tools import DEOBFUSCATION_TOOLS++ deob = Deobfuscator(mock_ghidra, mock_llm)+ context = _make_context()+ deob.deobfuscate(context, [ObfuscationType.INSTRUCTION_SUBSTITUTION])+ call_kwargs = mock_llm.analyze_with_tools.call_args+ tools = call_kwargs.kwargs.get("tools") or call_kwargs[1].get("tools") or call_kwargs[0][2]+ assert tools == DEOBFUSCATION_TOOLS+++# ---------------------------------------------------------------------------+# Integration: Analyzer delegates to Deobfuscator+# ---------------------------------------------------------------------------++class TestAnalyzerDeobfuscationIntegration:+ def test_obfuscated_function_delegates(self):+ from kong.agent.analyzer import Analyzer+ from kong.agent.queue import WorkItem++ mock_ghidra = MagicMock()+ mock_ghidra.get_decompilation.return_value = _CFF_CODE+ mock_ghidra.get_xrefs_from.return_value = []++ mock_llm = MagicMock()+ mock_llm.analyze_with_tools.return_value = LLMResponse(+ name="xor_decrypt",+ confidence=80,+ classification="crypto",+ )++ from kong.agent.deobfuscator import Deobfuscator+ deob = Deobfuscator(mock_ghidra, mock_llm)++ analyzer = Analyzer(mock_ghidra, mock_llm, deobfuscator=deob)+ item = WorkItem(+ function=FunctionInfo(address=0x401000, name="FUN_00401000", size=200),+ callers=[],+ callees=[],+ )+ result = analyzer.analyze(+ item,+ binary_info=BinaryInfo(+ arch="x86", format="ELF", endianness="little",+ word_size=8, compiler="gcc",+ ),+ known_results={},+ strings=[],+ )+ assert result.name == "xor_decrypt"+ assert "cff" in result.obfuscation_techniques+ mock_llm.analyze_with_tools.assert_called_once()++ def test_clean_function_uses_normal_path(self):+ from kong.agent.analyzer import Analyzer+ from kong.agent.queue import WorkItem++ mock_ghidra = MagicMock()+ mock_ghidra.get_decompilation.return_value = _CLEAN_CODE+ mock_ghidra.get_xrefs_from.return_value = []++ mock_llm = MagicMock()+ mock_llm.analyze_function.return_value = LLMResponse(+ name="add",+ confidence=95,+ classification="math",+ )++ from kong.agent.deobfuscator import Deobfuscator+ deob = Deobfuscator(mock_ghidra, mock_llm)++ analyzer = Analyzer(mock_ghidra, mock_llm, deobfuscator=deob)+ item = WorkItem(+ function=FunctionInfo(address=0x402000, name="FUN_00402000", size=20),+ callers=[],+ callees=[],+ )+ result = analyzer.analyze(+ item,+ binary_info=BinaryInfo(+ arch="x86", format="ELF", endianness="little",+ word_size=8, compiler="gcc",+ ),+ known_results={},+ strings=[],+ )+ assert result.name == "add"+ assert result.obfuscation_techniques == []+ mock_llm.analyze_function.assert_called_once()+ mock_llm.analyze_with_tools.assert_not_called()diff --git a/tests/test_llm_tools.py b/tests/test_llm_tools.pynew file mode 100644index 0000000..1b174c2--- /dev/null+++ b/tests/test_llm_tools.py@@ -0,0 +1,245 @@+"""Tests for kong.llm.tools — tool schemas, executor, and tool use loop."""++from __future__ import annotations++import json+from unittest.mock import MagicMock, patch++import pytest++from kong.llm.tools import (+ DEOBFUSCATION_TOOLS,+ ToolCallRecord,+ ToolExecutor,+)+++# ---------------------------------------------------------------------------+# Tool schema tests+# ---------------------------------------------------------------------------++class TestToolSchemas:+ def test_all_tools_have_required_fields(self):+ for tool in DEOBFUSCATION_TOOLS:+ assert "name" in tool+ assert "description" in tool+ assert "input_schema" in tool+ assert tool["input_schema"]["type"] == "object"+ assert "properties" in tool["input_schema"]+ assert "required" in tool["input_schema"]++ def test_tool_names_unique(self):+ names = [t["name"] for t in DEOBFUSCATION_TOOLS]+ assert len(names) == len(set(names))++ def test_expected_tools_present(self):+ names = {t["name"] for t in DEOBFUSCATION_TOOLS}+ assert "simplify_expression" in names+ assert "eliminate_dead_code" in names+ assert "trace_state_machine" in names+ assert "identify_crypto_constants" in names+ assert "get_decompilation" in names+ assert "get_basic_blocks" in names+++# ---------------------------------------------------------------------------+# ToolExecutor tests+# ---------------------------------------------------------------------------++class TestToolExecutor:+ @pytest.fixture+ def mock_ghidra(self):+ return MagicMock()++ @pytest.fixture+ def executor(self, mock_ghidra):+ return ToolExecutor(mock_ghidra)++ def test_simplify_expression(self, executor):+ result = executor.execute("simplify_expression", {+ "expression": "(x ^ x) == 0",+ })+ data = json.loads(result)+ assert data["is_opaque_predicate"] is True+ assert data["predicate_kind"] == "always_true"++ def test_simplify_expression_with_bit_width(self, executor):+ result = executor.execute("simplify_expression", {+ "expression": "3 + 5",+ "bit_width": 64,+ })+ data = json.loads(result)+ assert data["simplified"] == "8"++ def test_eliminate_dead_code(self, executor):+ result = executor.execute("eliminate_dead_code", {+ "decompiled_code": "if (x ^ x) { dead(); } live();",+ "resolved_predicates": [+ {"expression": "x ^ x", "resolution": "always_false"},+ ],+ })+ assert "dead" not in result+ assert "live" in result++ def test_get_decompilation(self, executor, mock_ghidra):+ mock_ghidra.get_decompilation.return_value = "void main() {}"+ result = executor.execute("get_decompilation", {+ "function_address": 0x401000,+ })+ assert "void main" in result+ mock_ghidra.get_decompilation.assert_called_once_with(0x401000)++ def test_identify_crypto_constants(self, executor, mock_ghidra):+ mock_ghidra.get_decompilation.return_value = (+ "int sbox[] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5 };"+ )+ result = executor.execute("identify_crypto_constants", {+ "function_address": 0x401000,+ })+ data = json.loads(result)+ assert len(data["matches"]) > 0+ assert any("AES" in m["algorithm"] for m in data["matches"])++ def test_identify_crypto_constants_no_match(self, executor, mock_ghidra):+ mock_ghidra.get_decompilation.return_value = "void foo() { return; }"+ result = executor.execute("identify_crypto_constants", {+ "function_address": 0x401000,+ })+ data = json.loads(result)+ assert data["matches"] == []++ def test_unknown_tool(self, executor):+ result = executor.execute("nonexistent_tool", {})+ assert "Unknown tool" in result++ def test_call_log(self, executor):+ executor.execute("simplify_expression", {"expression": "1 + 2"})+ executor.execute("simplify_expression", {"expression": "3 + 4"})+ assert executor.call_count == 2+ assert executor.call_log[0].tool_name == "simplify_expression"+ assert executor.call_log[1].tool_input["expression"] == "3 + 4"++ def test_handles_execution_error(self, executor, mock_ghidra):+ mock_ghidra.get_decompilation.side_effect = Exception("Ghidra crashed")+ result = executor.execute("get_decompilation", {+ "function_address": 0xDEAD,+ })+ assert "Error" in result+ assert executor.call_count == 1+++# ---------------------------------------------------------------------------+# Tool use loop tests (mocked Anthropic)+# ---------------------------------------------------------------------------++class TestToolUseLoop:+ def _mock_text_message(self, text, input_tokens=100, output_tokens=50):+ msg = MagicMock()+ block = MagicMock()+ block.type = "text"+ block.text = text+ msg.content = [block]+ msg.stop_reason = "end_turn"+ msg.usage.input_tokens = input_tokens+ msg.usage.output_tokens = output_tokens+ return msg++ def _mock_tool_use_message(self, tool_name, tool_input, tool_id="tool_1"):+ msg = MagicMock()+ tool_block = MagicMock()+ tool_block.type = "tool_use"+ tool_block.name = tool_name+ tool_block.input = tool_input+ tool_block.id = tool_id+ msg.content = [tool_block]+ msg.stop_reason = "tool_use"+ msg.usage.input_tokens = 200+ msg.usage.output_tokens = 100+ return msg++ def test_no_tool_calls(self):+ from kong.llm.client import AnthropicClient++ json_response = json.dumps({+ "name": "simple_func",+ "signature": "void simple_func(void)",+ "confidence": 85,+ "classification": "utility",+ "comments": "A simple function",+ "reasoning": "No obfuscation",+ })++ with patch("kong.llm.client.anthropic") as mock_anthropic:+ mock_client = MagicMock()+ mock_anthropic.Anthropic.return_value = mock_client+ mock_client.messages.create.return_value = self._mock_text_message(json_response)++ client = AnthropicClient(api_key="test")+ executor = ToolExecutor(MagicMock())+ response = client.analyze_with_tools(+ prompt="test",+ system="test system",+ tools=DEOBFUSCATION_TOOLS,+ tool_executor=executor,+ )+ assert response.name == "simple_func"+ assert response.confidence == 85++ def test_single_tool_call(self):+ from kong.llm.client import AnthropicClient++ json_response = json.dumps({+ "name": "deobfuscated_func",+ "signature": "int deobfuscated_func(int x)",+ "confidence": 72,+ "classification": "crypto",+ "comments": "Deobfuscated",+ "reasoning": "Used simplifier",+ })++ tool_msg = self._mock_tool_use_message(+ "simplify_expression",+ {"expression": "(x ^ x) == 0"},+ )+ final_msg = self._mock_text_message(json_response)++ with patch("kong.llm.client.anthropic") as mock_anthropic:+ mock_client = MagicMock()+ mock_anthropic.Anthropic.return_value = mock_client+ mock_client.messages.create.side_effect = [tool_msg, final_msg]++ client = AnthropicClient(api_key="test")+ executor = ToolExecutor(MagicMock())+ response = client.analyze_with_tools(+ prompt="test",+ system="test system",+ tools=DEOBFUSCATION_TOOLS,+ tool_executor=executor,+ )+ assert response.name == "deobfuscated_func"+ assert executor.call_count == 1+ assert mock_client.messages.create.call_count == 2++ def test_max_rounds_limit(self):+ from kong.llm.client import AnthropicClient++ tool_msg = self._mock_tool_use_message(+ "simplify_expression",+ {"expression": "x + 1"},+ )++ with patch("kong.llm.client.anthropic") as mock_anthropic:+ mock_client = MagicMock()+ mock_anthropic.Anthropic.return_value = mock_client+ mock_client.messages.create.return_value = tool_msg++ client = AnthropicClient(api_key="test")+ executor = ToolExecutor(MagicMock())+ response = client.analyze_with_tools(+ prompt="test",+ system="test system",+ tools=DEOBFUSCATION_TOOLS,+ tool_executor=executor,+ max_rounds=3,+ )+ assert mock_client.messages.create.call_count == 3diff --git a/tests/test_type_recovery.py b/tests/test_type_recovery.pyindex e826ebe..99464c7 100644--- a/tests/test_type_recovery.py+++ b/tests/test_type_recovery.py@@ -28,11 +28,6 @@ from kong.ghidra.types import (StructField,)-from kong.agent.queue import WorkItem-from kong.agent.events import EventType, Phase-from kong.agent.supervisor import Supervisor-from kong.config import KongConfig, OutputConfig-def _field(name: str, dtype: str, offset: int, size: int) -> StructFieldProposal:return StructFieldProposal(name=name, data_type=dtype, offset=offset, size=size)@@ -91,7 +86,7 @@ class TestStructAccumulator:assert unified[0].definition.size == 24assert len(unified[0].definition.fields) == 2- def test_same_size_overlapping_offsets_merge(self):+ def test_same_name_merges_fields(self):acc = StructAccumulator()acc.add_proposals(0x1000, [_proposal("conn_t", 32, [@@ -100,7 +95,7 @@ class TestStructAccumulator:]),])acc.add_proposals(0x2000, [- _proposal("connection", 32, [+ _proposal("conn_t", 32, [_field("socket_fd", "int", 0, 4),_field("port", "uint16_t", 8, 2),]),@@ -110,38 +105,52 @@ class TestStructAccumulator:assert unified[0].definition.size == 32assert len(unified[0].definition.fields) == 3- def test_same_size_no_overlap_stays_separate(self):+ def test_same_name_different_sizes_merge_to_max(self):+ """The cJSON scenario: same struct seen partially by different functions."""acc = StructAccumulator()acc.add_proposals(0x1000, [- _proposal("type_a", 16, [_field("x", "int", 0, 4)]),+ _proposal("cJSON", 24, [+ _field("type", "int", 0, 4),+ _field("valueint", "int", 8, 4),+ ]),])acc.add_proposals(0x2000, [- _proposal("type_b", 16, [_field("y", "int", 8, 4)]),+ _proposal("cJSON", 64, [+ _field("type", "int", 0, 4),+ _field("valueint", "int", 8, 4),+ _field("valuedouble", "double", 16, 8),+ _field("string", "char *", 24, 8),+ _field("child", "void *", 40, 8),+ _field("next", "void *", 48, 8),+ ]),])unified = acc.unify()- assert len(unified) == 2+ assert len(unified) == 1+ assert unified[0].definition.name == "cJSON"+ assert unified[0].definition.size == 64+ assert len(unified[0].definition.fields) == 6- def test_different_sizes_stay_separate(self):+ def test_different_names_stay_separate(self):acc = StructAccumulator()acc.add_proposals(0x1000, [- _proposal("small_t", 8, [_field("a", "int", 0, 4)]),+ _proposal("type_a", 16, [_field("x", "int", 0, 4)]),])acc.add_proposals(0x2000, [- _proposal("big_t", 64, [_field("b", "int", 0, 4)]),+ _proposal("type_b", 16, [_field("y", "int", 8, 4)]),])unified = acc.unify()assert len(unified) == 2- def test_winning_name_by_majority(self):+ def test_name_used_directly(self):acc = StructAccumulator()- for _ in range(3):- acc.add_proposals(0x1000, [- _proposal("config_t", 16, [_field("a", "int", 0, 4)]),- ])+ acc.add_proposals(0x1000, [+ _proposal("config_t", 16, [_field("a", "int", 0, 4)]),+ ])acc.add_proposals(0x2000, [- _proposal("cfg", 16, [_field("a", "int", 0, 4)]),+ _proposal("config_t", 32, [_field("a", "int", 0, 4), _field("b", "int", 8, 4)]),])unified = acc.unify()+ assert len(unified) == 1assert unified[0].definition.name == "config_t"def test_applications_tracked(self):@@ -367,6 +376,7 @@ class TestAnalyzerContextTypes:)client.get_xrefs_from.return_value = []+ from kong.agent.queue import WorkItemitem = WorkItem(function=FunctionInfo(address=0x1000, name="FUN_00001000", size=100,@@ -409,6 +419,7 @@ class TestAnalyzerContextTypes:)client.get_xrefs_from.return_value = []+ from kong.agent.queue import WorkItemitem = WorkItem(function=FunctionInfo(address=0x1000, name="f", size=100,@@ -456,7 +467,7 @@ class TestAnalyzerStructProposalPassthrough:)client.get_xrefs_from.return_value = []-+ from kong.agent.queue import WorkItemitem = WorkItem(function=FunctionInfo(address=0x1000, name="f", size=100,@@ -514,6 +525,9 @@ class TestStructDefinition:class TestSupervisorCleanupIntegration:def test_cleanup_with_struct_proposals(self, tmp_path):+ from kong.agent.events import EventType, Phase+ from kong.agent.supervisor import Supervisor+ from kong.config import KongConfig, OutputConfigfuncs = [FunctionInfo(@@ -564,6 +578,10 @@ class TestSupervisorCleanupIntegration:assert EventType.CLEANUP_TYPE_CREATED in event_typesdef test_cleanup_without_struct_proposals(self, tmp_path):+ from kong.agent.events import EventType+ from kong.agent.supervisor import Supervisor+ from kong.config import KongConfig, OutputConfig+funcs = [FunctionInfo(address=0x1000, name="f", size=100,@@ -596,6 +614,10 @@ class TestSupervisorCleanupIntegration:assert EventType.CLEANUP_TYPES_UNIFIED not in event_typesdef test_cleanup_reanalyzes_low_confidence(self, tmp_path):+ from kong.agent.events import EventType, Phase+ from kong.agent.supervisor import Supervisor+ from kong.config import KongConfig, OutputConfig+funcs = [FunctionInfo(address=0x1000, name="FUN_00001000", size=100,@@ -643,3 +665,77 @@ class TestSupervisorCleanupIntegration:if e.type == EventType.FUNCTION_COMPLETE and e.phase == Phase.CLEANUP]assert len(cleanup_completes) == 1++ def test_cleanup_retries_failed_signatures(self, tmp_path):+ """Signatures that fail during Phase 2 (type not yet created) get+ retried after struct creation in cleanup."""+ from kong.agent.events import EventType+ from kong.agent.supervisor import Supervisor+ from kong.config import KongConfig, OutputConfig++ funcs = [+ FunctionInfo(+ address=0x1000, name="cJSON_IsTrue", size=100,+ classification=FunctionClassification.MEDIUM,+ ),+ ]+ client = MagicMock()+ client.get_binary_info.return_value = BinaryInfo(+ arch="x86-64", format="ELF", endianness="little",+ word_size=8, compiler="GCC", name="cjson_test",+ )+ client.list_functions.return_value = funcs+ client.get_strings.return_value = []+ client.get_callers.return_value = []+ client.get_callees.return_value = []+ client.get_decompilation.return_value = "int f(void *p) { return *(int *)(p + 4); }"+ client.get_function_info.return_value = funcs[0]+ client.get_xrefs_from.return_value = []+ client.list_custom_types.return_value = []++ sig_call_count = 0++ def set_sig_side_effect(addr, sig):+ nonlocal sig_call_count+ sig_call_count += 1+ if sig_call_count == 1:+ raise Exception("Can't resolve datatype: cJSON *")++ client.set_function_signature.side_effect = set_sig_side_effect++ response = LLMResponse(+ name="cJSON_IsTrue",+ signature="int cJSON_IsTrue(cJSON *item)",+ confidence=95,+ struct_proposals=[+ StructProposal(+ name="cJSON",+ total_size=64,+ fields=[+ _field("type", "int", 0, 4),+ _field("valueint", "int", 4, 4),+ ],+ used_by_param="param_1",+ ),+ ],+ )+ llm = MagicMock()+ llm.analyze_function.return_value = response++ config = KongConfig(output=OutputConfig(directory=tmp_path / "out"))+ sup = Supervisor(client, config, llm_client=llm)++ events = []+ sup.on_event(events.append)+ sup.run()++ assert sup.results[0x1000].signature == "int cJSON_IsTrue(cJSON *item)"+ assert sup.results[0x1000].signature_applied is True++ event_types = [e.type for e in events]+ assert EventType.CLEANUP_SIGNATURES_RETRIED in event_types++ retry_event = next(+ e for e in events if e.type == EventType.CLEANUP_SIGNATURES_RETRIED+ )+ assert retry_event.data["succeeded"] == 1