mitudrudutta commited on
Commit
c8ebaee
·
1 Parent(s): 8b70d95

refactor: build grading on OpenEnv Rubric system

Browse files

Each of the seven scoring dimensions is now an openenv.core.rubrics.Rubric
subclass in evaluation/rubrics.py, composed via WeightedSum inside a per-case
CaseRubric and an episode-level ChargebackOpsEpisodeRubric that is wired into
ChargebackOpsEnvironment.rubric. The legacy evaluation/grading.py functions
remain as thin adapters so every call site (env step, episode store, API,
audit tooling, tests) keeps its current contract and outputs are bit-for-bit
identical to the previous implementation.

Wins: env.rubric.named_rubrics() exposes the full grader tree, every
dimension gets register_forward_hook / last_score / state_dict for free,
and swapping a dimension (e.g. LLMJudge for the note rubric) is a one-line
change. Docs (README, AGENT.md, OPENENV.md) and the grader test are updated
to reflect the rubric integration.

AGENT.md CHANGED
@@ -380,7 +380,7 @@ When the agent submits a contest, it generates a representment note. The grader
380
 
381
  ## The Grading System
382
 
383
- After all cases are resolved (or the step budget is exhausted), the deterministic grader in `grading.py` scores each case across 7 dimensions:
384
 
385
  ### Strategy Correctness (25%)
386
 
@@ -566,7 +566,8 @@ Nightmare tasks push the step budget to its limit: 5-6 cases with ~2.4 steps per
566
  |---|---|---|
567
  | `runners/baseline_runner.py` | The agent: decision pipeline, candidate generation, LLM integration, representment notes | ~1100 |
568
  | `server/chargeback_ops_environment.py` | The environment: step/reset/state, action execution, reward computation | ~500 |
569
- | `evaluation/grading.py` | Deterministic 7-dimension scoring, representment note grading | ~200 |
 
570
  | `scenarios/simulation.py` | Task definitions, case progress tracking, evidence metadata | ~600 |
571
  | `core/models.py` | Pydantic models for actions, observations, state, grading | ~600 |
572
  | `runners/inference.py` | OpenEnv-compatible inference entry point with provider fallback | ~200 |
 
380
 
381
  ## The Grading System
382
 
383
+ After all cases are resolved (or the step budget is exhausted), the grader scores each case across 7 dimensions. Each dimension is an OpenEnv `Rubric` subclass defined in `evaluation/rubrics.py`; they compose into a per-case `WeightedSum` and an episode-level `ChargebackOpsEpisodeRubric` that is wired into `env.rubric`. `evaluation/grading.py` keeps the legacy `score_case` / `grade_episode` API as a thin adapter over the rubric tree.
384
 
385
  ### Strategy Correctness (25%)
386
 
 
566
  |---|---|---|
567
  | `runners/baseline_runner.py` | The agent: decision pipeline, candidate generation, LLM integration, representment notes | ~1100 |
568
  | `server/chargeback_ops_environment.py` | The environment: step/reset/state, action execution, reward computation | ~500 |
569
+ | `evaluation/rubrics.py` | OpenEnv `Rubric` subclasses for all 7 scoring dimensions, composed via `WeightedSum` | ~300 |
570
+ | `evaluation/grading.py` | Legacy `score_case` / `grade_episode` adapter that delegates to the rubric tree | ~120 |
571
  | `scenarios/simulation.py` | Task definitions, case progress tracking, evidence metadata | ~600 |
572
  | `core/models.py` | Pydantic models for actions, observations, state, grading | ~600 |
573
  | `runners/inference.py` | OpenEnv-compatible inference entry point with provider fallback | ~200 |
OPENENV.md CHANGED
@@ -47,4 +47,4 @@ The OpenEnv hackathon asks participants to build an environment, not an agent. T
47
 
48
  Round 1 evaluates environments on real-world utility (30%), task and grader quality (25%), environment design (20%), code quality (15%), and creativity (10%). Round 2 runs a standard agent against all qualifying environments to measure how well each environment discriminates between good and bad agent behaviour.
49
 
50
- ChargebackOps is built to perform well on both rounds: the 7-dimension deterministic grader produces a clear difficulty curve (easy 0.96 → nightmare 0.47), and the typed action space with dense reward shaping gives any standard agent enough signal to learn the environment within a single episode.
 
47
 
48
  Round 1 evaluates environments on real-world utility (30%), task and grader quality (25%), environment design (20%), code quality (15%), and creativity (10%). Round 2 runs a standard agent against all qualifying environments to measure how well each environment discriminates between good and bad agent behaviour.
49
 
50
+ ChargebackOps is built to perform well on both rounds: the 7-dimension grader is implemented on top of OpenEnv's `Rubric` system (each dimension is a `Rubric` subclass composed via `WeightedSum` and wired into `env.rubric`, so the whole grader is introspectable, hookable, and checkpointable), it produces a clear difficulty curve (easy 0.96 → nightmare 0.47), and the typed action space with dense reward shaping gives any standard agent enough signal to learn the environment within a single episode.
README.md CHANGED
@@ -30,7 +30,7 @@ graph TB
30
  subgraph Core["Environment Core"]
31
  ENV["ChargebackOpsEnvironment\nstep() / reset() / state()"]
32
  SIM["Simulation Engine\nscenarios/simulation.py"]
33
- GRD["Deterministic Grader\nevaluation/grading.py"]
34
  end
35
 
36
  subgraph Tasks["Task Sources"]
@@ -52,6 +52,8 @@ graph TB
52
 
53
  ## Grading
54
 
 
 
55
  7-dimension deterministic grader, weighted per case by financial impact:
56
 
57
  ```mermaid
@@ -112,6 +114,19 @@ openenv validate .
112
  python -m runners.inference
113
  ```
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  ```bash
116
  # Docker
117
  docker build -t chargebackops .
@@ -157,7 +172,7 @@ Entry point: [`inference.py`](inference.py). Fallback chain: primary provider ->
157
  ├── inference.py # Submission entry point
158
  ├── openenv.yaml # OpenEnv spec
159
  ├── core/ # Models, client, episode store
160
- ├── evaluation/ # 7-dimension grader, audit suite
161
  ├── runners/ # Baseline agent, inference logic
162
  ├── scenarios/ # Tasks, generator, ISO adapter
163
  ├── server/ # FastAPI app, environment, Gradio demo
 
30
  subgraph Core["Environment Core"]
31
  ENV["ChargebackOpsEnvironment\nstep() / reset() / state()"]
32
  SIM["Simulation Engine\nscenarios/simulation.py"]
33
+ GRD["OpenEnv Rubric Grader\nevaluation/rubrics.py"]
34
  end
35
 
36
  subgraph Tasks["Task Sources"]
 
52
 
53
  ## Grading
54
 
55
+ Each scoring dimension is a standalone `openenv.core.rubrics.Rubric` subclass. They compose into a per-case `WeightedSum` and an episode-level `ChargebackOpsEpisodeRubric` that the environment wires into `self.rubric`, so the whole grader is introspectable via `env.rubric.named_rubrics()`, hookable via `register_forward_hook`, and checkpointable via `state_dict()`. Swapping `NoteQualityRubric` for an `LLMJudge`, or wrapping any dimension in a `Gate`, is a one-line change.
56
+
57
  7-dimension deterministic grader, weighted per case by financial impact:
58
 
59
  ```mermaid
 
114
  python -m runners.inference
115
  ```
116
 
117
+ Inspect the rubric tree on a live environment:
118
+
119
+ ```python
120
+ from server.chargeback_ops_environment import ChargebackOpsEnvironment
121
+ env = ChargebackOpsEnvironment()
122
+ for name, r in env.rubric.named_rubrics():
123
+ print(f"{name}: {type(r).__name__}")
124
+ # case_rubric: CaseRubric
125
+ # case_rubric.aggregator: WeightedSum
126
+ # case_rubric.aggregator.rubric_0: StrategyCorrectnessRubric
127
+ # ... (all 7 dimensions)
128
+ ```
129
+
130
  ```bash
131
  # Docker
132
  docker build -t chargebackops .
 
172
  ├── inference.py # Submission entry point
173
  ├── openenv.yaml # OpenEnv spec
174
  ├── core/ # Models, client, episode store
175
+ ├── evaluation/ # OpenEnv Rubric subclasses + legacy grader adapters
176
  ├── runners/ # Baseline agent, inference logic
177
  ├── scenarios/ # Tasks, generator, ISO adapter
178
  ├── server/ # FastAPI app, environment, Gradio demo
evaluation/__init__.py CHANGED
@@ -1 +1,19 @@
1
  """Grading and audit modules for ChargebackOps."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """Grading and audit modules for ChargebackOps."""
2
+
3
+ from .grading import grade_episode, grade_representment_note, score_case
4
+ from .rubrics import (
5
+ CaseRubric,
6
+ ChargebackOpsEpisodeRubric,
7
+ EpisodeGradingContext,
8
+ GradingContext,
9
+ )
10
+
11
+ __all__ = [
12
+ "grade_episode",
13
+ "grade_representment_note",
14
+ "score_case",
15
+ "CaseRubric",
16
+ "ChargebackOpsEpisodeRubric",
17
+ "EpisodeGradingContext",
18
+ "GradingContext",
19
+ ]
evaluation/grading.py CHANGED
@@ -1,192 +1,50 @@
1
- """Deterministic grading logic for ChargebackOps."""
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
  try:
6
  from ..core.models import CaseScoreBreakdown, GraderReport
7
  from ..scenarios.simulation import CaseProgress, InternalCase, TaskScenario
 
 
 
 
 
 
 
8
  except ImportError: # pragma: no cover
9
  from core.models import CaseScoreBreakdown, GraderReport
10
  from scenarios.simulation import CaseProgress, InternalCase, TaskScenario
 
 
 
 
 
 
 
11
 
12
 
13
- def _ratio(numerator: int, denominator: int) -> float:
14
- if denominator <= 0:
15
- return 1.0
16
- return max(0.0, min(1.0, numerator / denominator))
17
-
18
-
19
- def grade_representment_note(
20
- note: str | None,
21
- case: "InternalCase",
22
- attached_ids: set[str],
23
- ) -> float:
24
- """Score a representment note from 0.0 to 1.0.
25
-
26
- Evaluates whether the note:
27
- - References required claims from the policy requirements
28
- - Avoids mentioning harmful evidence
29
- - Has sufficient substance (length and specificity)
30
- """
31
- if not note or not note.strip():
32
- return 0.0
33
-
34
- text = note.lower()
35
- score = 0.0
36
-
37
- # Substance: minimum length for a coherent note
38
- word_count = len(text.split())
39
- if word_count >= 5:
40
- score += 0.2
41
- elif word_count >= 2:
42
- score += 0.1
43
-
44
- # Required claims coverage: does the note mention policy requirements?
45
- if case.policy_requirements:
46
- claims_hit = 0
47
- for req in case.policy_requirements:
48
- req_keywords = req.lower().split()
49
- if any(kw in text for kw in req_keywords if len(kw) > 3):
50
- claims_hit += 1
51
- score += 0.5 * _ratio(claims_hit, len(case.policy_requirements))
52
- else:
53
- score += 0.3 # No requirements to check
54
-
55
- # Evidence coherence: does the note reference attached evidence?
56
- evidence_refs = sum(1 for eid in attached_ids if eid.lower() in text or any(
57
- part in text for part in eid.lower().replace("-", " ").split() if len(part) > 3
58
- ))
59
- if evidence_refs > 0:
60
- score += 0.15
61
-
62
- # Harmful mention penalty: derived from the case's actual harmful evidence.
63
- # Each case defines its own harmful artifacts, so the penalty adapts to
64
- # the specific dispute rather than matching a static keyword list.
65
- harmful_terms: set[str] = set()
66
- for items in case.evidence_by_system.values():
67
- for item in items:
68
- if item.harmful:
69
- for word in (item.title + " " + item.summary).lower().split():
70
- clean = word.strip(".,;:()")
71
- if len(clean) > 3:
72
- harmful_terms.add(clean)
73
- # Remove generic words that would cause false positives
74
- harmful_terms -= {"was", "the", "and", "for", "that", "with", "from", "time", "detail"}
75
- harmful_hits = sum(1 for term in harmful_terms if term in text)
76
- if harmful_hits > 0:
77
- score -= 0.12 * min(harmful_hits, 3)
78
-
79
- return max(0.0, min(1.0, score))
80
 
81
 
82
- def score_case(
83
- case: InternalCase,
84
- progress: CaseProgress,
85
- step_count: int,
86
- ) -> CaseScoreBreakdown:
87
- """Score one case deterministically."""
88
 
 
89
  final_resolution = progress.final_resolution or "unresolved"
90
  attached_set = set(progress.attached_evidence_ids)
91
- required_attached = len(attached_set.intersection(case.required_evidence_ids))
92
- helpful_attached = len(attached_set.intersection(case.helpful_evidence_ids))
93
  harmful_attached = len(attached_set.intersection(case.harmful_evidence_ids))
94
 
95
- if final_resolution == case.optimal_strategy:
96
- strategy_correctness = 1.0
97
- elif final_resolution in case.acceptable_strategies:
98
- strategy_correctness = 0.35
99
- else:
100
- strategy_correctness = 0.0
101
-
102
- if final_resolution == "contest":
103
- if case.optimal_strategy != "contest" and "contest" not in case.acceptable_strategies:
104
- # Contesting a case that should not be contested — evidence is irrelevant
105
- evidence_quality = 0.0
106
- packet_validity = 0.0
107
- else:
108
- base_evidence_quality = 0.7 * _ratio(required_attached, len(case.required_evidence_ids))
109
- bonus = 0.3 * _ratio(helpful_attached, max(1, len(case.helpful_evidence_ids)))
110
- penalty = 0.25 * harmful_attached
111
- evidence_quality = max(0.0, min(1.0, base_evidence_quality + bonus - penalty))
112
- packet_validity = (
113
- 1.0
114
- if required_attached == len(case.required_evidence_ids) and harmful_attached == 0
115
- else 0.0
116
- )
117
- else:
118
- if final_resolution in {"accept_chargeback", "issue_refund"}:
119
- if case.optimal_strategy == "contest":
120
- # Conceded a contestable case — evidence gathering was abandoned
121
- evidence_quality = 0.15
122
- packet_validity = 0.0
123
- else:
124
- evidence_quality = 1.0 if helpful_attached == 0 and harmful_attached == 0 else 0.7
125
- packet_validity = 1.0
126
- else:
127
- evidence_quality = 0.0
128
- packet_validity = 0.0
129
-
130
- resolution_step = progress.resolved_at_step if progress.resolved_at_step is not None else step_count
131
- deadline_compliance = 1.0
132
- if final_resolution == "unresolved":
133
- deadline_compliance = 0.0
134
- elif resolution_step > case.deadline_step:
135
- deadline_compliance = 0.0
136
-
137
- # --- Efficiency: penalise shallow operational behaviour ---
138
- wasted_actions = progress.duplicate_queries + progress.invalid_actions
139
- efficiency = max(0.0, 1.0 - min(0.9, wasted_actions * 0.1 + progress.submit_attempts * 0.05))
140
-
141
- # Penalty: over-querying a concedable case wastes steps
142
- if final_resolution in {"accept_chargeback", "issue_refund"} and case.optimal_strategy != "contest":
143
- systems_queried = len(progress.revealed_systems)
144
- if systems_queried > 2:
145
- efficiency -= 0.15 * (systems_queried - 2)
146
-
147
- # Penalty: retrieving policy too late to change the outcome
148
- if progress.policy_retrieved and resolution_step is not None:
149
- # The case was already being resolved, policy retrieval was wasted
150
- if final_resolution in {"accept_chargeback", "issue_refund"} and case.optimal_strategy in {
151
- "accept_chargeback", "issue_refund"
152
- }:
153
- # Correct concession but wasted a step on policy retrieval
154
- efficiency -= 0.08
155
-
156
- # Reward: early correct concession on a clearly bad case (≤3 steps used)
157
- if (
158
- final_resolution in {"accept_chargeback", "issue_refund"}
159
- and case.optimal_strategy in {"accept_chargeback", "issue_refund"}
160
- and resolution_step is not None
161
- and resolution_step <= 3
162
- ):
163
- efficiency = min(1.0, efficiency + 0.1)
164
-
165
- efficiency = max(0.0, min(1.0, efficiency))
166
-
167
- if final_resolution == case.optimal_strategy:
168
- outcome_quality = 1.0
169
- elif final_resolution in case.acceptable_strategies:
170
- outcome_quality = 0.4
171
- else:
172
- outcome_quality = 0.0
173
-
174
- # Representment note quality (only relevant for contested cases)
175
- if final_resolution == "contest" and progress.representment_note:
176
- note_quality = grade_representment_note(progress.representment_note, case, attached_set)
177
- else:
178
- note_quality = 0.0
179
-
180
- weighted_score = (
181
- 0.25 * strategy_correctness
182
- + 0.20 * evidence_quality
183
- + 0.15 * packet_validity
184
- + 0.15 * deadline_compliance
185
- + 0.10 * efficiency
186
- + 0.10 * outcome_quality
187
- + 0.05 * note_quality
188
- )
189
-
190
  note_parts = [case.resolution_summary]
191
  if harmful_attached:
192
  note_parts.append("Harmful evidence weakened the case.")
@@ -194,19 +52,32 @@ def score_case(
194
  note_parts.append("Case was never resolved.")
195
  elif step_count > case.deadline_step:
196
  note_parts.append("Resolution happened after the deadline.")
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
  return CaseScoreBreakdown(
199
  case_id=case.case_id,
200
- strategy_correctness=round(strategy_correctness, 4),
201
- evidence_quality=round(evidence_quality, 4),
202
- packet_validity=round(packet_validity, 4),
203
- deadline_compliance=round(deadline_compliance, 4),
204
- efficiency=round(efficiency, 4),
205
- outcome_quality=round(outcome_quality, 4),
206
- note_quality=round(note_quality, 4),
207
- weighted_score=round(weighted_score * case.weight, 4),
208
- final_resolution=final_resolution,
209
- notes=" ".join(note_parts),
210
  )
211
 
212
 
@@ -217,7 +88,7 @@ def grade_episode(
217
  episode_id: str,
218
  completed: bool,
219
  ) -> GraderReport:
220
- """Grade a full episode."""
221
 
222
  case_reports = [
223
  score_case(case, progress_by_case[case.case_id], step_count)
@@ -225,7 +96,14 @@ def grade_episode(
225
  ]
226
  total_weight = sum(case.weight for case in task.cases)
227
  total_score = sum(report.weighted_score for report in case_reports)
228
- normalized = 0.0 if total_weight == 0 else min(1.0, total_score / total_weight)
 
 
 
 
 
 
 
229
  summary = (
230
  f"Resolved {sum(1 for report in case_reports if report.final_resolution != 'unresolved')}/"
231
  f"{len(case_reports)} cases with normalized score {normalized:.3f}."
 
1
+ """Deterministic grading adapters that delegate to OpenEnv Rubric subclasses.
2
+
3
+ The real scoring lives in :mod:`evaluation.rubrics`. This module keeps the
4
+ legacy call sites (``score_case`` / ``grade_episode`` / ``grade_representment_note``)
5
+ stable so the environment, tests, and audit tooling do not need to change.
6
+ """
7
 
8
  from __future__ import annotations
9
 
10
  try:
11
  from ..core.models import CaseScoreBreakdown, GraderReport
12
  from ..scenarios.simulation import CaseProgress, InternalCase, TaskScenario
13
+ from .rubrics import (
14
+ CaseRubric,
15
+ ChargebackOpsEpisodeRubric,
16
+ EpisodeGradingContext,
17
+ GradingContext,
18
+ grade_representment_note,
19
+ )
20
  except ImportError: # pragma: no cover
21
  from core.models import CaseScoreBreakdown, GraderReport
22
  from scenarios.simulation import CaseProgress, InternalCase, TaskScenario
23
+ from evaluation.rubrics import (
24
+ CaseRubric,
25
+ ChargebackOpsEpisodeRubric,
26
+ EpisodeGradingContext,
27
+ GradingContext,
28
+ grade_representment_note,
29
+ )
30
 
31
 
32
+ __all__ = [
33
+ "grade_representment_note",
34
+ "score_case",
35
+ "grade_episode",
36
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
 
39
+ _CASE_RUBRIC = CaseRubric()
40
+ _EPISODE_RUBRIC = ChargebackOpsEpisodeRubric()
41
+
 
 
 
42
 
43
+ def _build_case_notes(case: InternalCase, progress: CaseProgress, step_count: int) -> str:
44
  final_resolution = progress.final_resolution or "unresolved"
45
  attached_set = set(progress.attached_evidence_ids)
 
 
46
  harmful_attached = len(attached_set.intersection(case.harmful_evidence_ids))
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  note_parts = [case.resolution_summary]
49
  if harmful_attached:
50
  note_parts.append("Harmful evidence weakened the case.")
 
52
  note_parts.append("Case was never resolved.")
53
  elif step_count > case.deadline_step:
54
  note_parts.append("Resolution happened after the deadline.")
55
+ return " ".join(note_parts)
56
+
57
+
58
+ def score_case(
59
+ case: InternalCase,
60
+ progress: CaseProgress,
61
+ step_count: int,
62
+ ) -> CaseScoreBreakdown:
63
+ """Score one case deterministically via the case rubric."""
64
+
65
+ ctx = GradingContext(case=case, progress=progress, step_count=step_count)
66
+ weighted = _CASE_RUBRIC(ctx, None)
67
+ dims = _CASE_RUBRIC.dimension_scores()
68
 
69
  return CaseScoreBreakdown(
70
  case_id=case.case_id,
71
+ strategy_correctness=round(dims["strategy_correctness"], 4),
72
+ evidence_quality=round(dims["evidence_quality"], 4),
73
+ packet_validity=round(dims["packet_validity"], 4),
74
+ deadline_compliance=round(dims["deadline_compliance"], 4),
75
+ efficiency=round(dims["efficiency"], 4),
76
+ outcome_quality=round(dims["outcome_quality"], 4),
77
+ note_quality=round(dims["note_quality"], 4),
78
+ weighted_score=round(weighted * case.weight, 4),
79
+ final_resolution=progress.final_resolution or "unresolved",
80
+ notes=_build_case_notes(case, progress, step_count),
81
  )
82
 
83
 
 
88
  episode_id: str,
89
  completed: bool,
90
  ) -> GraderReport:
91
+ """Grade a full episode via the episode-level rubric."""
92
 
93
  case_reports = [
94
  score_case(case, progress_by_case[case.case_id], step_count)
 
96
  ]
97
  total_weight = sum(case.weight for case in task.cases)
98
  total_score = sum(report.weighted_score for report in case_reports)
99
+
100
+ ctx = EpisodeGradingContext(
101
+ task=task,
102
+ progress_by_case=progress_by_case,
103
+ step_count=step_count,
104
+ )
105
+ normalized = float(_EPISODE_RUBRIC(ctx, None))
106
+
107
  summary = (
108
  f"Resolved {sum(1 for report in case_reports if report.final_resolution != 'unresolved')}/"
109
  f"{len(case_reports)} cases with normalized score {normalized:.3f}."
evaluation/rubrics.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv Rubric subclasses that power ChargebackOps grading.
2
+
3
+ Every scoring dimension is a standalone :class:`openenv.core.rubrics.Rubric`
4
+ so the whole grader can be introspected via ``named_rubrics``, captured via
5
+ ``state_dict``, and swapped piecewise (e.g. replace :class:`NoteQualityRubric`
6
+ with an ``LLMJudge``). The per-case composite uses :class:`WeightedSum` with
7
+ weights that must sum to 1.0.
8
+
9
+ The rubrics take their inputs via a :class:`GradingContext` dataclass passed
10
+ as the ``action`` argument of :meth:`Rubric.forward`. The ``observation``
11
+ argument is ignored — ChargebackOps grading operates over deterministic
12
+ episode progress, not on the last observation payload. This keeps the rubrics
13
+ pure and unit-testable without an environment instance.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Any
20
+
21
+ from openenv.core.rubrics import Rubric, WeightedSum
22
+
23
+ try:
24
+ from ..scenarios.simulation import CaseProgress, InternalCase, TaskScenario
25
+ except ImportError: # pragma: no cover
26
+ from scenarios.simulation import CaseProgress, InternalCase, TaskScenario
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class GradingContext:
31
+ """Inputs one per-case rubric evaluation needs."""
32
+
33
+ case: InternalCase
34
+ progress: CaseProgress
35
+ step_count: int
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class EpisodeGradingContext:
40
+ """Inputs the episode-level rubric needs."""
41
+
42
+ task: TaskScenario
43
+ progress_by_case: dict[str, CaseProgress]
44
+ step_count: int
45
+
46
+
47
+ def _ratio(numerator: int, denominator: int) -> float:
48
+ if denominator <= 0:
49
+ return 1.0
50
+ return max(0.0, min(1.0, numerator / denominator))
51
+
52
+
53
+ def _final_resolution(progress: CaseProgress) -> str:
54
+ return progress.final_resolution or "unresolved"
55
+
56
+
57
+ def _contest_is_valid(case: InternalCase) -> bool:
58
+ return case.optimal_strategy == "contest" or "contest" in case.acceptable_strategies
59
+
60
+
61
+ class StrategyCorrectnessRubric(Rubric):
62
+ """Score final strategy: optimal=1.0, acceptable=0.35, else 0.0."""
63
+
64
+ def forward(self, action: Any, observation: Any) -> float:
65
+ ctx: GradingContext = action
66
+ final = _final_resolution(ctx.progress)
67
+ if final == ctx.case.optimal_strategy:
68
+ return 1.0
69
+ if final in ctx.case.acceptable_strategies:
70
+ return 0.35
71
+ return 0.0
72
+
73
+
74
+ class EvidenceQualityRubric(Rubric):
75
+ """Score the evidence packet attached to the case.
76
+
77
+ Zeroes out (vacuous-truth fix) when the agent contests a case that was
78
+ never contestable — no evidence quality can rescue a wrong strategy.
79
+ """
80
+
81
+ def forward(self, action: Any, observation: Any) -> float:
82
+ ctx: GradingContext = action
83
+ case = ctx.case
84
+ progress = ctx.progress
85
+ final = _final_resolution(progress)
86
+
87
+ attached_set = set(progress.attached_evidence_ids)
88
+ required_attached = len(attached_set.intersection(case.required_evidence_ids))
89
+ helpful_attached = len(attached_set.intersection(case.helpful_evidence_ids))
90
+ harmful_attached = len(attached_set.intersection(case.harmful_evidence_ids))
91
+
92
+ if final == "contest":
93
+ if not _contest_is_valid(case):
94
+ return 0.0
95
+ base = 0.7 * _ratio(required_attached, len(case.required_evidence_ids))
96
+ bonus = 0.3 * _ratio(helpful_attached, max(1, len(case.helpful_evidence_ids)))
97
+ penalty = 0.25 * harmful_attached
98
+ return max(0.0, min(1.0, base + bonus - penalty))
99
+
100
+ if final in {"accept_chargeback", "issue_refund"}:
101
+ if case.optimal_strategy == "contest":
102
+ return 0.15
103
+ return 1.0 if helpful_attached == 0 and harmful_attached == 0 else 0.7
104
+
105
+ return 0.0
106
+
107
+
108
+ class PacketValidityRubric(Rubric):
109
+ """All-or-nothing: required evidence complete AND no harmful attached."""
110
+
111
+ def forward(self, action: Any, observation: Any) -> float:
112
+ ctx: GradingContext = action
113
+ case = ctx.case
114
+ progress = ctx.progress
115
+ final = _final_resolution(progress)
116
+
117
+ attached_set = set(progress.attached_evidence_ids)
118
+ required_attached = len(attached_set.intersection(case.required_evidence_ids))
119
+ harmful_attached = len(attached_set.intersection(case.harmful_evidence_ids))
120
+
121
+ if final == "contest":
122
+ if not _contest_is_valid(case):
123
+ return 0.0
124
+ if (
125
+ required_attached == len(case.required_evidence_ids)
126
+ and harmful_attached == 0
127
+ ):
128
+ return 1.0
129
+ return 0.0
130
+
131
+ if final in {"accept_chargeback", "issue_refund"}:
132
+ if case.optimal_strategy == "contest":
133
+ return 0.0
134
+ return 1.0
135
+
136
+ return 0.0
137
+
138
+
139
+ class DeadlineComplianceRubric(Rubric):
140
+ """1.0 if resolved on time, else 0.0."""
141
+
142
+ def forward(self, action: Any, observation: Any) -> float:
143
+ ctx: GradingContext = action
144
+ case = ctx.case
145
+ progress = ctx.progress
146
+ final = _final_resolution(progress)
147
+
148
+ if final == "unresolved":
149
+ return 0.0
150
+ resolution_step = (
151
+ progress.resolved_at_step
152
+ if progress.resolved_at_step is not None
153
+ else ctx.step_count
154
+ )
155
+ if resolution_step > case.deadline_step:
156
+ return 0.0
157
+ return 1.0
158
+
159
+
160
+ class EfficiencyRubric(Rubric):
161
+ """Penalise wasted / redundant actions, reward early correct concessions."""
162
+
163
+ def forward(self, action: Any, observation: Any) -> float:
164
+ ctx: GradingContext = action
165
+ case = ctx.case
166
+ progress = ctx.progress
167
+ final = _final_resolution(progress)
168
+
169
+ wasted_actions = progress.duplicate_queries + progress.invalid_actions
170
+ efficiency = max(
171
+ 0.0,
172
+ 1.0 - min(0.9, wasted_actions * 0.1 + progress.submit_attempts * 0.05),
173
+ )
174
+
175
+ # Over-querying a concedable case is wasted exploration.
176
+ if final in {"accept_chargeback", "issue_refund"} and case.optimal_strategy != "contest":
177
+ systems_queried = len(progress.revealed_systems)
178
+ if systems_queried > 2:
179
+ efficiency -= 0.15 * (systems_queried - 2)
180
+
181
+ # Retrieving policy after the decision was already made is wasted.
182
+ if progress.policy_retrieved and progress.resolved_at_step is not None:
183
+ if final in {"accept_chargeback", "issue_refund"} and case.optimal_strategy in {
184
+ "accept_chargeback",
185
+ "issue_refund",
186
+ }:
187
+ efficiency -= 0.08
188
+
189
+ # Early correct concession bonus.
190
+ if (
191
+ final in {"accept_chargeback", "issue_refund"}
192
+ and case.optimal_strategy in {"accept_chargeback", "issue_refund"}
193
+ and progress.resolved_at_step is not None
194
+ and progress.resolved_at_step <= 3
195
+ ):
196
+ efficiency = min(1.0, efficiency + 0.1)
197
+
198
+ return max(0.0, min(1.0, efficiency))
199
+
200
+
201
+ class OutcomeQualityRubric(Rubric):
202
+ """Discrete outcome quality: optimal=1.0, acceptable=0.4, else 0.0."""
203
+
204
+ def forward(self, action: Any, observation: Any) -> float:
205
+ ctx: GradingContext = action
206
+ final = _final_resolution(ctx.progress)
207
+ if final == ctx.case.optimal_strategy:
208
+ return 1.0
209
+ if final in ctx.case.acceptable_strategies:
210
+ return 0.4
211
+ return 0.0
212
+
213
+
214
+ class NoteQualityRubric(Rubric):
215
+ """Text-based representment note scorer (contest-only)."""
216
+
217
+ def forward(self, action: Any, observation: Any) -> float:
218
+ ctx: GradingContext = action
219
+ progress = ctx.progress
220
+ if _final_resolution(progress) != "contest" or not progress.representment_note:
221
+ return 0.0
222
+ return grade_representment_note(
223
+ progress.representment_note,
224
+ ctx.case,
225
+ set(progress.attached_evidence_ids),
226
+ )
227
+
228
+
229
+ def grade_representment_note(
230
+ note: str | None,
231
+ case: InternalCase,
232
+ attached_ids: set[str],
233
+ ) -> float:
234
+ """Score a representment note from 0.0 to 1.0.
235
+
236
+ Evaluates whether the note references required policy claims, mentions
237
+ attached evidence, has sufficient substance, and avoids harmful mentions.
238
+ """
239
+
240
+ if not note or not note.strip():
241
+ return 0.0
242
+
243
+ text = note.lower()
244
+ score = 0.0
245
+
246
+ # Substance: minimum length for a coherent note.
247
+ word_count = len(text.split())
248
+ if word_count >= 5:
249
+ score += 0.2
250
+ elif word_count >= 2:
251
+ score += 0.1
252
+
253
+ # Required claims coverage: does the note mention policy requirements?
254
+ if case.policy_requirements:
255
+ claims_hit = 0
256
+ for req in case.policy_requirements:
257
+ req_keywords = req.lower().split()
258
+ if any(kw in text for kw in req_keywords if len(kw) > 3):
259
+ claims_hit += 1
260
+ score += 0.5 * _ratio(claims_hit, len(case.policy_requirements))
261
+ else:
262
+ score += 0.3
263
+
264
+ # Evidence coherence: does the note reference attached evidence?
265
+ evidence_refs = sum(
266
+ 1
267
+ for eid in attached_ids
268
+ if eid.lower() in text
269
+ or any(part in text for part in eid.lower().replace("-", " ").split() if len(part) > 3)
270
+ )
271
+ if evidence_refs > 0:
272
+ score += 0.15
273
+
274
+ # Harmful mention penalty derived from each case's harmful evidence blobs.
275
+ harmful_terms: set[str] = set()
276
+ for items in case.evidence_by_system.values():
277
+ for item in items:
278
+ if item.harmful:
279
+ for word in (item.title + " " + item.summary).lower().split():
280
+ clean = word.strip(".,;:()")
281
+ if len(clean) > 3:
282
+ harmful_terms.add(clean)
283
+ harmful_terms -= {"was", "the", "and", "for", "that", "with", "from", "time", "detail"}
284
+ harmful_hits = sum(1 for term in harmful_terms if term in text)
285
+ if harmful_hits > 0:
286
+ score -= 0.12 * min(harmful_hits, 3)
287
+
288
+ return max(0.0, min(1.0, score))
289
+
290
+
291
+ # Weights must match the order of rubrics handed to WeightedSum and sum to 1.0.
292
+ CASE_DIMENSION_WEIGHTS: tuple[float, ...] = (0.25, 0.20, 0.15, 0.15, 0.10, 0.10, 0.05)
293
+ CASE_DIMENSION_NAMES: tuple[str, ...] = (
294
+ "strategy_correctness",
295
+ "evidence_quality",
296
+ "packet_validity",
297
+ "deadline_compliance",
298
+ "efficiency",
299
+ "outcome_quality",
300
+ "note_quality",
301
+ )
302
+
303
+
304
+ class CaseRubric(Rubric):
305
+ """Per-case composite — weighted sum of the seven scoring dimensions."""
306
+
307
+ def __init__(self) -> None:
308
+ super().__init__()
309
+ self.aggregator = WeightedSum(
310
+ rubrics=[
311
+ StrategyCorrectnessRubric(),
312
+ EvidenceQualityRubric(),
313
+ PacketValidityRubric(),
314
+ DeadlineComplianceRubric(),
315
+ EfficiencyRubric(),
316
+ OutcomeQualityRubric(),
317
+ NoteQualityRubric(),
318
+ ],
319
+ weights=list(CASE_DIMENSION_WEIGHTS),
320
+ )
321
+
322
+ def forward(self, action: Any, observation: Any) -> float:
323
+ return self.aggregator(action, observation)
324
+
325
+ def dimension_scores(self) -> dict[str, float]:
326
+ """Return per-dimension scores from the most recent forward pass."""
327
+
328
+ scores: dict[str, float] = {}
329
+ for name, child in zip(CASE_DIMENSION_NAMES, self.aggregator._rubric_list):
330
+ scores[name] = float(child.last_score) if child.last_score is not None else 0.0
331
+ return scores
332
+
333
+
334
+ class ChargebackOpsEpisodeRubric(Rubric):
335
+ """Episode-level rubric: aggregate per-case scores weighted by case.weight."""
336
+
337
+ def __init__(self) -> None:
338
+ super().__init__()
339
+ self.case_rubric = CaseRubric()
340
+
341
+ def forward(self, action: Any, observation: Any) -> float:
342
+ ctx: EpisodeGradingContext = action
343
+ total = 0.0
344
+ total_weight = 0.0
345
+ for case in ctx.task.cases:
346
+ case_ctx = GradingContext(
347
+ case=case,
348
+ progress=ctx.progress_by_case[case.case_id],
349
+ step_count=ctx.step_count,
350
+ )
351
+ case_score = self.case_rubric(case_ctx, observation)
352
+ total += case_score * case.weight
353
+ total_weight += case.weight
354
+ if total_weight == 0:
355
+ return 0.0
356
+ return min(1.0, total / total_weight)
server/chargeback_ops_environment.py CHANGED
@@ -11,6 +11,7 @@ from openenv.core.env_server.interfaces import Environment
11
  try:
12
  from ..core.episode_store import record_report
13
  from ..evaluation.grading import grade_episode
 
14
  from ..core.models import (
15
  ActionTraceItem,
16
  CaseQueueItem,
@@ -26,6 +27,7 @@ try:
26
  except ImportError: # pragma: no cover
27
  from core.episode_store import record_report
28
  from evaluation.grading import grade_episode
 
29
  from core.models import (
30
  ActionTraceItem,
31
  CaseQueueItem,
@@ -48,7 +50,7 @@ class ChargebackOpsEnvironment(
48
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
49
 
50
  def __init__(self):
51
- super().__init__()
52
  self._task = get_task("goods_not_received_easy")
53
  self._selected_case_id: str | None = None
54
  self._last_action_result = "Environment initialized."
@@ -114,6 +116,7 @@ class ChargebackOpsEnvironment(
114
  objective=self._task.objective,
115
  )
116
  self._reset_task_state()
 
117
  return self._build_observation(reward=0.0, done=False)
118
 
119
  def step(
 
11
  try:
12
  from ..core.episode_store import record_report
13
  from ..evaluation.grading import grade_episode
14
+ from ..evaluation.rubrics import ChargebackOpsEpisodeRubric
15
  from ..core.models import (
16
  ActionTraceItem,
17
  CaseQueueItem,
 
27
  except ImportError: # pragma: no cover
28
  from core.episode_store import record_report
29
  from evaluation.grading import grade_episode
30
+ from evaluation.rubrics import ChargebackOpsEpisodeRubric
31
  from core.models import (
32
  ActionTraceItem,
33
  CaseQueueItem,
 
50
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
51
 
52
  def __init__(self):
53
+ super().__init__(rubric=ChargebackOpsEpisodeRubric())
54
  self._task = get_task("goods_not_received_easy")
55
  self._selected_case_id: str | None = None
56
  self._last_action_result = "Environment initialized."
 
116
  objective=self._task.objective,
117
  )
118
  self._reset_task_state()
119
+ self._reset_rubric()
120
  return self._build_observation(reward=0.0, done=False)
121
 
122
  def step(
tests/test_grader.py CHANGED
@@ -1,4 +1,8 @@
1
  from evaluation.grading import grade_episode
 
 
 
 
2
  from server.chargeback_ops_environment import ChargebackOpsEnvironment
3
  from scenarios.simulation import get_task
4
 
@@ -14,3 +18,23 @@ def test_grade_episode_bounds():
14
  completed=False,
15
  )
16
  assert 0.0 <= report.normalized_score <= 1.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from evaluation.grading import grade_episode
2
+ from evaluation.rubrics import (
3
+ CASE_DIMENSION_WEIGHTS,
4
+ ChargebackOpsEpisodeRubric,
5
+ )
6
  from server.chargeback_ops_environment import ChargebackOpsEnvironment
7
  from scenarios.simulation import get_task
8
 
 
18
  completed=False,
19
  )
20
  assert 0.0 <= report.normalized_score <= 1.0
21
+
22
+
23
+ def test_environment_exposes_rubric_tree():
24
+ """The env must wire an OpenEnv Rubric that exposes all 7 scoring dimensions."""
25
+
26
+ env = ChargebackOpsEnvironment()
27
+ assert isinstance(env.rubric, ChargebackOpsEpisodeRubric)
28
+
29
+ names = {name for name, _ in env.rubric.named_rubrics()}
30
+ expected = {
31
+ "case_rubric",
32
+ "case_rubric.aggregator",
33
+ *(f"case_rubric.aggregator.rubric_{i}" for i in range(7)),
34
+ }
35
+ assert expected.issubset(names)
36
+
37
+ # Weights must sum to 1.0 (WeightedSum enforces this at construction but
38
+ # we lock the constant here so weight changes stay intentional).
39
+ assert abs(sum(CASE_DIMENSION_WEIGHTS) - 1.0) < 1e-6
40
+ assert len(CASE_DIMENSION_WEIGHTS) == 7