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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""Reward computation for CyberSecurity_OWASP."""

from __future__ import annotations

try:
    from .models import CyberSecurityOWASPAction, CyberSecurityOWASPState
    from .reward_config import RewardSettings, load_reward_settings
except ImportError:  # pragma: no cover
    from models import CyberSecurityOWASPAction, CyberSecurityOWASPState
    from reward_config import RewardSettings, load_reward_settings


REWARD_KEYS = (
    "discovery",
    "security",
    "regression",
    "public_routes",
    "patch_quality",
    "visible_tests",
    "safety",
    "anti_cheat",
    "terminal_total",
    "progressive",
    "step_penalty",
    "speed_bonus",
    "token_penalty",
    "behavior_penalty",
    "train_total",
    "total",
)


def empty_reward() -> dict[str, float]:
    return {key: 0.0 for key in REWARD_KEYS}


def compute_reward(
    state: CyberSecurityOWASPState,
    action: CyberSecurityOWASPAction,
    verifier_result: dict,
) -> dict[str, float]:
    settings = load_reward_settings()
    reward = empty_reward()
    if action.tool_name == "submit_diagnosis":
        diagnosis = verifier_result.get("diagnosis", verifier_result.get("finding", {}))
        reward["discovery"] = _diagnosis_score(diagnosis)
    elif action.tool_name == "run_visible_tests":
        visible = verifier_result.get("visible", {})
        reward["visible_tests"] = 1.0 if visible.get("passed") else 0.0
    elif action.tool_name == "submit_fix":
        _add_terminal_submit_fix_reward(state, verifier_result, reward, settings)

    _add_current_anti_cheat_penalties(verifier_result, reward, settings)

    if verifier_result.get("invalid_action"):
        reward["behavior_penalty"] += settings.value("invalid_action", -0.2)
    if verifier_result.get("repeated_action"):
        reward["behavior_penalty"] += (
            settings.value("repeated_invalid_action", -0.3)
            if verifier_result.get("invalid_action")
            else settings.value("repeated_low_value_action", -0.1)
        )

    reward["progressive"] = _compute_progressive_reward(
        state,
        action,
        verifier_result,
        settings,
    )
    reward["step_penalty"] = _compute_step_penalty(state, settings)
    reward["speed_bonus"] = _compute_speed_bonus(state, action, verifier_result, settings)
    reward["behavior_penalty"] += _compute_behavior_penalty(
        state,
        action,
        verifier_result,
        settings,
        reward["progressive"],
    )

    terminal_total = (
        _component_total(reward)
        if action.tool_name == "submit_fix"
        else reward["safety"] + reward["anti_cheat"]
    )
    reward["terminal_total"] = _cap_terminal(terminal_total, settings)
    reward["train_total"] = _cap_train(
        reward["terminal_total"]
        + settings.shaping_weight * reward["progressive"]
        + reward["step_penalty"]
        + reward["speed_bonus"]
        + reward["token_penalty"]
        + reward["behavior_penalty"],
        settings,
        state,
    )
    reward["total"] = reward["train_total"] if settings.dense_train else reward["terminal_total"]
    return reward


def _followed_repair_phase_order(state: CyberSecurityOWASPState) -> bool:
    tools = [item.get("tool_name") for item in state.action_history]
    required = ["submit_diagnosis", "patch_file", "run_visible_tests", "submit_fix"]
    cursor = 0
    for tool in tools:
        if cursor < len(required) and tool == required[cursor]:
            cursor += 1
    return cursor == len(required)


def should_terminate_for_flags(flags: list[str], settings: RewardSettings | None = None) -> bool:
    settings = settings or load_reward_settings()
    mapping = {
        "external_network_attempt": "external_url_attempt",
        "blocked_file_probe": "hidden_file_probe",
        "host_path_escape": "host_path_escape",
        "test_file_edit_attempt": "test_file_edit",
    }
    return any(settings.terminate(mapping[flag]) for flag in flags if flag in mapping)


def _diagnosis_score(diagnosis: dict) -> float:
    return sum(
        0.25
        for key in (
            "correct_route",
            "correct_bug_class",
            "correct_policy_rule",
            "valid_local_evidence",
        )
        if diagnosis.get(key)
    )


def _add_terminal_submit_fix_reward(
    state: CyberSecurityOWASPState,
    verifier_result: dict,
    reward: dict[str, float],
    settings: RewardSettings,
) -> None:
    security = verifier_result.get("security", {})
    oracle = verifier_result.get("oracle_matrix", {})
    regression = verifier_result.get("regression", {})
    public_routes = verifier_result.get("public_routes", {})
    quality = verifier_result.get("patch_quality", {})
    visible = verifier_result.get("visible", {})
    security_passed = bool(security.get("passed") and oracle.get("passed", True))
    reward["security"] = 5.0 if security_passed else -6.0
    reward["regression"] = 3.0 if regression.get("passed") else -5.0
    reward["public_routes"] = 1.0 if public_routes.get("passed") else -3.0
    reward["patch_quality"] = 2.0 if quality.get("passed") else 0.0
    if quality.get("passed") and _followed_repair_phase_order(state):
        reward["patch_quality"] += 0.5
    reward["visible_tests"] = 1.0 if visible.get("passed") else -6.0
    if quality.get("hardcoded"):
        reward["anti_cheat"] += settings.value("hardcoded_identifier", -2.0)
    if quality.get("deny_all"):
        reward["safety"] += settings.value("deny_all_patch", -3.0)


def _add_current_anti_cheat_penalties(
    verifier_result: dict,
    reward: dict[str, float],
    settings: RewardSettings,
) -> None:
    flags = set(verifier_result.get("anti_cheat_flags", []) or [])
    if "external_network_attempt" in flags:
        reward["safety"] += settings.value("external_url_attempt", -5.0)
    if "blocked_file_probe" in flags:
        reward["anti_cheat"] += settings.value("hidden_file_probe", -5.0)
    if "host_path_escape" in flags:
        reward["anti_cheat"] += settings.value("host_path_escape", -4.0)
    if "test_file_edit_attempt" in flags:
        reward["anti_cheat"] += settings.value("test_file_edit", -5.0)
    if "hardcoded_hidden_identifier" in flags:
        reward["anti_cheat"] += settings.value("hardcoded_identifier", -2.0)


def _compute_progressive_reward(
    state: CyberSecurityOWASPState,
    action: CyberSecurityOWASPAction,
    verifier_result: dict,
    settings: RewardSettings,
) -> float:
    if not settings.dense_train:
        return 0.0
    delta = 0.0
    if action.tool_name == "inspect_policy_graph":
        delta += _award_progress_once(state, "policy_seen", "policy_inspected", settings)
    if action.tool_name in {"list_routes", "read_openapi"}:
        delta += _award_progress_once(state, "route_map_seen", "route_map_inspected", settings)
    if action.tool_name in {"read_file", "search_code"} and _is_relevant_code_action(action):
        delta += _award_progress_once(
            state,
            "relevant_file_seen",
            "relevant_file_inspected",
            settings,
        )
    if action.tool_name in {"send_local_request", "compare_identities"} and any(
        trace.get("unauthorized_success") for trace in state.request_trace
    ):
        delta += _award_progress_once(
            state,
            "local_evidence_found",
            "local_evidence_found",
            settings,
        )
    if action.tool_name == "submit_diagnosis":
        diagnosis = verifier_result.get("diagnosis", verifier_result.get("finding", {}))
        if all(
            diagnosis.get(key)
            for key in (
                "correct_route",
                "correct_bug_class",
                "correct_policy_rule",
                "valid_local_evidence",
            )
        ):
            delta += _award_progress_once(
                state,
                "diagnosis_correct",
                "diagnosis_correct",
                settings,
            )
    if action.tool_name == "patch_file" and not verifier_result.get("invalid_action"):
        delta += _award_progress_once(state, "patch_applies", "patch_applies", settings)
    if action.tool_name == "run_visible_tests":
        visible = verifier_result.get("visible", {})
        checks = visible.get("checks", {}) if isinstance(visible, dict) else {}
        if visible.get("passed"):
            delta += _award_progress_once(
                state,
                "app_boots",
                "app_boots_after_patch",
                settings,
            )
            delta += _award_progress_once(
                state,
                "visible_tests_improved",
                "visible_tests_improved",
                settings,
            )
        if checks.get("health_public"):
            delta += _award_progress_once(
                state,
                "public_routes_visible_pass",
                "public_routes_visible_pass",
                settings,
            )
    return delta


def _award_progress_once(
    state: CyberSecurityOWASPState,
    flag_name: str,
    config_name: str,
    settings: RewardSettings,
) -> float:
    if state.progress_flags.get(flag_name):
        return 0.0
    cap = settings.value("progressive_cap", 5.0)
    remaining = max(0.0, cap - float(state.progress_reward_total or 0.0))
    if remaining <= 0.0:
        return 0.0
    state.progress_flags[flag_name] = True
    value = min(settings.value(config_name, 0.0), remaining)
    state.progress_reward_total += value
    return value


def _is_relevant_code_action(action: CyberSecurityOWASPAction) -> bool:
    args = action.arguments or {}
    text = f"{args.get('path', '')} {args.get('query', '')}".lower()
    return any(
        term in text
        for term in ("auth", "tenant", "owner", "role", "invoice", "route", "guard", "policy")
    )


def _compute_step_penalty(
    state: CyberSecurityOWASPState,
    settings: RewardSettings,
) -> float:
    if not settings.dense_train:
        return 0.0
    rate = settings.value("step_penalty", 0.0)
    if rate >= 0.0:
        return 0.0
    current = float(state.metrics.get("step_penalty_total", 0.0))
    cap = settings.cap("step_penalty", -0.6)
    delta = max(rate, float(cap) - current) if cap is not None else rate
    state.metrics["step_penalty_total"] = current + delta
    return delta


def _compute_speed_bonus(
    state: CyberSecurityOWASPState,
    action: CyberSecurityOWASPAction,
    verifier_result: dict,
    settings: RewardSettings,
) -> float:
    if not settings.dense_train or action.tool_name != "submit_fix":
        return 0.0
    success = all(
        bool((verifier_result.get(key) or {}).get("passed", False))
        for key in ("security", "oracle_matrix", "regression", "public_routes", "patch_quality")
    )
    if not success:
        return 0.0
    max_steps = max(1, int(state.max_steps or 1))
    bonus = settings.value("speed_bonus", 1.0) * (1.0 - min(state.step_count, max_steps) / max_steps)
    return max(0.0, bonus)


def _compute_behavior_penalty(
    state: CyberSecurityOWASPState,
    action: CyberSecurityOWASPAction,
    verifier_result: dict,
    settings: RewardSettings,
    progressive_delta: float,
) -> float:
    if not settings.dense_train:
        return 0.0
    penalty = 0.0
    tools = [item.get("tool_name") for item in state.action_history]
    if action.tool_name == "noop":
        penalty += settings.value("noop_action", -0.02)
    if action.tool_name == "read_file":
        path = str((action.arguments or {}).get("path", ""))
        reads = [
            item
            for item in state.action_history
            if item.get("tool_name") == "read_file"
            and str((item.get("arguments") or {}).get("path", "")) == path
        ]
        if len(reads) > 1:
            penalty += settings.value("repeated_file_read", -0.05)
    if action.tool_name == "send_local_request":
        args = action.arguments or {}
        current = (
            str(args.get("method", "GET")).upper(),
            str(args.get("path", "")),
            str(args.get("user_id", "")),
        )
        matches = [
            item
            for item in state.action_history
            if item.get("tool_name") == "send_local_request"
            and (
                str((item.get("arguments") or {}).get("method", "GET")).upper(),
                str((item.get("arguments") or {}).get("path", "")),
                str((item.get("arguments") or {}).get("user_id", "")),
            )
            == current
        ]
        if len(matches) > 1:
            penalty += settings.value("repeated_local_request", -0.05)
    if action.tool_name == "run_visible_tests" and state.visible_test_count > 1:
        penalty += settings.value("repeated_visible_tests", -0.1)
    if action.tool_name == "patch_file" and not state.progress_flags.get("policy_seen"):
        penalty += settings.value("patch_before_policy", -0.3)
    if action.tool_name == "submit_fix":
        if "patch_file" not in tools:
            penalty += settings.value("submit_without_patch", -0.5)
        if state.patch_attempt_count > 0 and state.visible_test_count == 0:
            penalty += settings.value("submit_without_visible_tests", -0.3)
    if action.tool_name == "patch_file" and state.patch_attempt_count > 3:
        penalty += settings.value("excessive_patch_attempt", -0.2)
    files_touched = state.metrics.get("files_touched", [])
    if isinstance(files_touched, list) and len(files_touched) > 5:
        penalty += settings.value("too_many_files_changed", -0.5)
    if action.tool_name == "patch_file":
        penalty += _oversized_patch_penalty(state, settings)
    if (
        progressive_delta <= 0.0
        and not verifier_result.get("invalid_action")
        and action.tool_name
        in {
            "inspect_policy_graph",
            "list_routes",
            "read_openapi",
            "noop",
            "run_visible_tests",
            "send_local_request",
            "compare_identities",
        }
    ):
        penalty += settings.value("no_progress_action", -0.05)
    return penalty


def _oversized_patch_penalty(
    state: CyberSecurityOWASPState,
    settings: RewardSettings,
) -> float:
    diff_lines = [
        line
        for line in str(state.patch_diff or "").splitlines()
        if (line.startswith("+") or line.startswith("-"))
        and not line.startswith("+++")
        and not line.startswith("---")
    ]
    entry = settings.entry("oversized_patch")
    threshold = int(entry.get("threshold_lines", 80))
    severe_threshold = int(entry.get("severe_threshold_lines", 180))
    if len(diff_lines) >= severe_threshold:
        return float(entry.get("severe_value", -1.0))
    if len(diff_lines) >= threshold:
        return settings.value("oversized_patch", -0.25)
    return 0.0


def _component_total(reward: dict[str, float]) -> float:
    excluded = {
        "total",
        "terminal_total",
        "progressive",
        "step_penalty",
        "speed_bonus",
        "token_penalty",
        "behavior_penalty",
        "train_total",
    }
    return sum(value for key, value in reward.items() if key not in excluded)


def _cap_terminal(total: float, settings: RewardSettings) -> float:
    cap = settings.value("terminal_cap", 15.0)
    return min(cap, total) if total > 0 else total


def _cap_train(
    total: float,
    settings: RewardSettings,
    state: CyberSecurityOWASPState,
) -> float:
    floor = settings.value("penalty_floor", -6.0)
    capped = max(floor, total)
    cap = settings.value("train_cap", 21.0)
    if capped > 0.0:
        remaining = max(0.0, cap - float(state.accumulated_reward or 0.0))
        return min(capped, remaining)
    return capped