Pranjal Parashar commited on
Commit
f676764
·
unverified ·
0 Parent(s):

Initial FlowOS benchmark submission

Browse files
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ .uv-cache/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
6
+ .env
7
+ .DS_Store
8
+ *.egg-info/
Dockerfile ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
2
+ FROM ${BASE_IMAGE} AS builder
3
+
4
+ WORKDIR /app
5
+
6
+ RUN apt-get update && \
7
+ apt-get install -y --no-install-recommends git && \
8
+ rm -rf /var/lib/apt/lists/*
9
+
10
+ COPY . /app/env
11
+ WORKDIR /app/env
12
+
13
+ RUN if ! command -v uv >/dev/null 2>&1; then \
14
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
15
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
16
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
17
+ fi
18
+
19
+ RUN --mount=type=cache,target=/root/.cache/uv \
20
+ if [ -f uv.lock ]; then \
21
+ uv sync --frozen --no-editable; \
22
+ else \
23
+ uv sync --no-editable; \
24
+ fi
25
+
26
+ FROM ${BASE_IMAGE}
27
+
28
+ WORKDIR /app
29
+
30
+ COPY --from=builder /app/env/.venv /app/.venv
31
+ COPY --from=builder /app/env /app/env
32
+
33
+ ENV PATH="/app/.venv/bin:$PATH"
34
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
35
+
36
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
37
+ CMD curl -f http://localhost:7860/health || exit 1
38
+
39
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 7860"]
README.md ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: FlowOS
3
+ emoji: 🛠️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 7860
9
+ base_path: /web
10
+ tags:
11
+ - developer-tools
12
+ - pipeline-ops
13
+ - llm-evaluation
14
+ - workflow-generation
15
+ ---
16
+
17
+ # FlowOS
18
+
19
+ FlowOS is an end-to-end benchmark for AI agents that operate like real production teams. Instead of testing a narrow coding trick, it evaluates whether one agent can handle the full operating loop around modern software systems: diagnose failures, review risky AI-generated changes, and ship new production artifacts safely.
20
+
21
+ The benchmark runs inside a realistic repository with transforms, schemas, validators, lineage, deployment configs, policies, draft patches, and multi-file delivery tasks. That makes it useful for evaluating much more than “can the model write code?” It measures whether an agent can actually move work across the line.
22
+
23
+ FlowOS is designed around the work that burns the most money in real teams:
24
+
25
+ - failed pipelines, broken loads, and bad deploy drift that trigger retries, backfills, and missed refresh windows
26
+ - risky AI-generated patches that increase reviewer burden or create downstream incidents
27
+ - repetitive implementation work that bounces between developers, operators, analysts, and business owners before anything ships
28
+
29
+ One benchmark covers repair, review, and implementation in the same environment. Instead of training or evaluating separate agents for incident response, patch review, and artifact generation, FlowOS measures whether a single agent can operate across the entire workflow.
30
+
31
+ ## Why FlowOS
32
+
33
+ Most agent benchmarks stop at chat help, log triage, or a single-file patch. FlowOS models the broader operating loop that real teams care about:
34
+
35
+ - inspect the repo and supporting docs
36
+ - understand contracts, dependencies, and operational constraints
37
+ - decide whether an AI-generated fix is safe and correct
38
+ - create or edit multiple artifacts across code, config, checks, and delivery metadata
39
+ - validate before shipping
40
+
41
+ That makes FlowOS useful well beyond a single developer persona. It is relevant anywhere business logic and production systems meet:
42
+
43
+ - engineers repairing and shipping production changes
44
+ - operators and platform teams responding to failures
45
+ - analysts and data stakeholders who know the business logic but are not full-time software developers
46
+ - domain experts who can describe the desired outcome in natural language and rely on the agent to assemble the right technical artifacts
47
+
48
+ In other words, the benchmark measures whether an agent can turn intent into safe operational progress, not just whether it can autocomplete code.
49
+
50
+ ## Why this saves money
51
+
52
+ FlowOS is intentionally shaped around the highest-cost handoffs in production work:
53
+
54
+ - catching bad fixes before deployment reduces failed runs, emergency rollbacks, and compute-heavy recovery work
55
+ - repairing end-to-end loads and orchestration issues reduces backfill spend, on-call churn, and missed business reporting windows
56
+ - rejecting unsafe or incorrect AI patches reduces reviewer load and downstream incident cost
57
+ - generating production artifacts in the same environment reduces duplicated tooling across backend, platform, analytics, release, and operational workflows
58
+
59
+ The deeper value is leverage. When one agent can repair, review, and implement inside the same system, teams spend less money on repeated handoffs between people who understand the business problem and people who know how to encode it technically.
60
+
61
+ ## Benchmark design
62
+
63
+ The benchmark is organized around **6 public task entries** and **3 internal objective families**:
64
+
65
+ - public tasks are what evaluators select and score
66
+ - scenarios are deterministic variants inside those tasks
67
+ - internal grader families keep the implementation compact:
68
+ - `repair`
69
+ - `review`
70
+ - `workflow`
71
+
72
+ Difficulty is defined at the **task level**:
73
+
74
+ - Tasks `1-2` are easy
75
+ - Tasks `3-4` are medium
76
+ - Tasks `5-6` are hard
77
+
78
+ Variation is defined at the **scenario level**:
79
+
80
+ - each task contains one or more deterministic scenarios
81
+ - same `task_id + scenario_index + seed` always yields the same scenario
82
+ - selected scenarios also support light seeded literal variation in a few cases
83
+ - same action trajectory always yields the same rewards and score
84
+ - no randomness is used to create score spread
85
+
86
+ ## Tasks
87
+
88
+ | Task ID | Difficulty | Objective | Submission |
89
+ |---|---|---|---|
90
+ | `repair_data_transform` | Easy | Repair broken transform logic or dependency wiring while preserving downstream contracts | `submit_repair` |
91
+ | `repair_pipeline_execution` | Easy | Repair ingestion and orchestration failures caused by path, runner, or deploy drift | `submit_repair` |
92
+ | `review_ai_patch_safety` | Medium | Review AI-generated changes for privacy, governance, and operational safety risk | `submit_review` |
93
+ | `review_ai_patch_correctness` | Medium | Review AI-generated changes for semantic correctness and contract compatibility | `submit_review` |
94
+ | `synthesize_reporting_asset` | Hard | Create reporting-facing views, contracts, and alert/config assets | `submit_workspace` |
95
+ | `synthesize_data_product` | Hard | Create production-grade marts and feature workflows with validation and governance | `submit_workspace` |
96
+
97
+ ### Task coverage
98
+
99
+ - `repair_data_transform`: schema drift and stale downstream dependency repairs
100
+ - `repair_pipeline_execution`: ADLS path migration, Jenkins runner repair, deploy config drift, CSV/type mismatch loads, column-count mismatches, and primary-key-safe merge repair
101
+ - `review_ai_patch_safety`: PII leakage and unsafe operational advice
102
+ - `review_ai_patch_correctness`: incorrect joins and contract-breaking schema changes
103
+ - `synthesize_reporting_asset`: reporting view delivery and reporting view + alert config delivery
104
+ - `synthesize_data_product`: feature workflow and curated mart delivery
105
+
106
+ ### Current scenario set
107
+
108
+ - `repair_data_transform`
109
+ - `PR-001`: schema drift in a warehouse transform
110
+ - `PR-004`: stale downstream dependency on a deprecated upstream alias
111
+ - `repair_pipeline_execution`
112
+ - `PR-002`: ADLS path and partition migration
113
+ - `PR-003`: Jenkins runner-path breakage
114
+ - `PR-005`: deploy config env-var drift
115
+ - `PR-006`: CSV identifier type mismatch during warehouse load
116
+ - `PR-007`: 6-column extract into a 12-column archive target
117
+ - `PR-008`: primary-key violation from duplicate dimension rows
118
+ - `review_ai_patch_safety`
119
+ - `LR-001`: PII leakage in an analytics patch
120
+ - `LR-004`: unsafe warehouse recovery recommendation
121
+ - `review_ai_patch_correctness`
122
+ - `LR-002`: technically incorrect enrichment join
123
+ - `LR-003`: published-contract-breaking rename
124
+ - `synthesize_reporting_asset`
125
+ - `WS-002`: reporting view + schema contract
126
+ - `WS-004`: reporting view + alert config
127
+ - `synthesize_data_product`
128
+ - `WS-001`: feature workflow for downstream model scoring
129
+ - `WS-003`: curated finance mart / data product
130
+
131
+ ## Action space
132
+
133
+ ```json
134
+ {"action_type":"search_workspace","parameters":{"query":"orders_daily schema drift"}}
135
+ {"action_type":"read_file","parameters":{"path":"transforms/orders_daily.sql"}}
136
+ {"action_type":"inspect_schema","parameters":{"asset":"raw.orders_events"}}
137
+ {"action_type":"inspect_lineage","parameters":{"asset":"risk_model_scoring"}}
138
+ {"action_type":"inspect_llm_draft","parameters":{"draft_id":"primary"}}
139
+ {"action_type":"edit_file","parameters":{"path":"sql/merchant_risk_features.sql","content":"..."}}
140
+ {"action_type":"run_validator","parameters":{"validator":"governance_check"}}
141
+ {"action_type":"submit_repair","parameters":{"root_cause":"schema rename event_ts -> event_time","fix_path":"transforms/orders_daily.sql","summary":"..."}}
142
+ {"action_type":"submit_review","parameters":{"verdict":"reject","issue_type":"pii_exposure","summary":"..."}}
143
+ {"action_type":"submit_workspace","parameters":{"summary":"..."}}
144
+ ```
145
+
146
+ ## Observation space
147
+
148
+ The observation is typed in [models.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/models.py) and includes:
149
+
150
+ - `developer_request`
151
+ - `workspace_summary`
152
+ - `known_files`
153
+ - `editable_targets`
154
+ - `known_assets`
155
+ - `available_validators`
156
+ - `queried_data`
157
+ - `edited_files`
158
+ - `validator_status`
159
+ - `cumulative_reward`
160
+ - `feedback`
161
+ - `last_action_error`
162
+
163
+ The agent only sees operational context and its own interaction history. Hidden grader targets stay in the scenario fixtures and are not exposed directly in observations.
164
+
165
+ ## Reward shaping
166
+
167
+ Rewards are dense across the episode:
168
+
169
+ - small positive reward for first-time useful investigation actions
170
+ - negative reward for repeated, invalid, or no-op actions
171
+ - a progress delta from the deterministic grader after each step
172
+ - additional signal when validators are run and begin passing
173
+ - late-episode and max-step penalties for inefficient trajectories
174
+
175
+ This means the agent gets feedback for real progress, not just a binary terminal signal.
176
+
177
+ ## Deterministic graders
178
+
179
+ Each task has a deterministic grader implemented in [graders.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/graders.py):
180
+
181
+ - `repair`: investigation + correct file edit + validator passes + root-cause submission
182
+ - `review`: investigation + verdict + issue type + summary evidence
183
+ - `workflow`: reference inspection + artifact quality + governance + validator passes + summary
184
+
185
+ The public task list contains 6 tasks, but these 6 tasks intentionally map to 3 internal grader families because there are only 3 objective types. All task scores are constrained to `0.0–1.0`.
186
+
187
+ ## Anti-gaming and reproducibility
188
+
189
+ The environment is designed so that reward comes from useful work, not cheap action farming:
190
+
191
+ - repeated reads and repeated validators degrade in reward
192
+ - invalid or poorly grounded actions lose reward
193
+ - hard tasks intentionally require more investigation and broader validator coverage
194
+ - same task, scenario, and action trajectory always produce the same score
195
+
196
+ The repo now includes explicit tests for:
197
+
198
+ - repeated validator spam
199
+ - repeated file reads
200
+ - invalid early edits in the hybrid baseline
201
+ - reset-state cleanliness
202
+ - deterministic replay scoring
203
+ - solved versus unsolved hard-scenario separation
204
+
205
+ ### Score and success semantics
206
+
207
+ - `score` is a normalized quality signal in `0.0–1.0`
208
+ - `success` is not a simple threshold; it reflects whether the scenario’s core solve criteria were met
209
+ - this allows a scenario to score highly without being marked fully solved, especially in the hard tasks
210
+
211
+ ### Intended calibration
212
+
213
+ - easy tasks should cluster highest
214
+ - medium tasks should cluster below easy
215
+ - hard tasks should cluster lowest on average
216
+ - hard tasks intentionally mix solved and partial scenarios
217
+
218
+ Latest all-scenario baseline run:
219
+
220
+ | Public task | Typical band |
221
+ |---|---|
222
+ | `repair_data_transform` | `0.88-0.98` |
223
+ | `repair_pipeline_execution` | `0.90-0.97` |
224
+ | `review_ai_patch_safety` | `0.82-0.86` |
225
+ | `review_ai_patch_correctness` | `0.78-0.83` |
226
+ | `synthesize_reporting_asset` | `0.65-0.71` |
227
+ | `synthesize_data_product` | `0.61-0.70` |
228
+
229
+ Overall, the current calibrated profile is:
230
+
231
+ - easy tasks: about `0.93-0.95`
232
+ - medium tasks: about `0.82-0.84`
233
+ - hard tasks: about `0.65-0.68`
234
+
235
+ ## Baseline inference
236
+
237
+ The root [inference.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/inference.py) is the submission-facing entrypoint. It uses the OpenAI client with:
238
+
239
+ - `API_BASE_URL`
240
+ - `MODEL_NAME`
241
+ - `HF_TOKEN`
242
+
243
+ The benchmark-specific helper logic lives in [baseline.py](/Users/pranjalparashar/Desktop/hackz/cw-apr1/control-room/developer_control_room/baseline.py):
244
+
245
+ - prompt construction
246
+ - model response parsing
247
+ - deterministic fallback policy
248
+ - baseline artifact templates
249
+ - grader fetch helpers
250
+
251
+ By default, the baseline is a bounded hybrid policy: it allows `2` model-led steps, then switches to deterministic fallback behavior for the rest of the episode. You can change that budget with `DEVELOPER_CONTROL_ROOM_MAX_MODEL_STEPS` if you want a more or less model-led baseline for local experiments.
252
+
253
+ The baseline also supports two optional experimental knobs for local research:
254
+
255
+ - light seeded scenario variation through `DEVELOPER_CONTROL_ROOM_SCENARIO_SEED`
256
+ - cross-episode baseline memory through `DEVELOPER_CONTROL_ROOM_ENABLE_EPISODE_MEMORY=true`
257
+
258
+ That memory is policy-side only: it writes compact episode summaries to a temp JSON file and reuses them in later prompts, but it does not change environment state, reset behavior, or grading.
259
+
260
+ ### Inference behavior
261
+
262
+ - `python inference.py` runs all 6 public tasks by default
263
+ - `DEVELOPER_CONTROL_ROOM_TASK=<task_id> python inference.py` runs one task
264
+ - `DEVELOPER_CONTROL_ROOM_RUN_ALL_SCENARIOS=true python inference.py` runs every scenario inside every selected task
265
+ - `DEVELOPER_CONTROL_ROOM_SCENARIO_INDEX=<n>` selects a specific scenario index inside each selected task
266
+ - `DEVELOPER_CONTROL_ROOM_SCENARIO_SEED=<n>` selects scenarios deterministically by seed
267
+
268
+ Example:
269
+
270
+ ```bash
271
+ DEVELOPER_CONTROL_ROOM_RUN_ALL_SCENARIOS=true python inference.py
272
+ ```
273
+
274
+ ## Local usage
275
+
276
+ ```bash
277
+ uv sync
278
+ uv run server
279
+ ```
280
+
281
+ Or with Docker:
282
+
283
+ ```bash
284
+ docker build -t developer-control-room-env .
285
+ docker run -p 7860:7860 developer-control-room-env
286
+ ```
287
+
288
+ Example local container run:
289
+
290
+ ```bash
291
+ docker build -t developer_control_room:latest .
292
+ docker stop developer_control_room 2>/dev/null
293
+ docker rm developer_control_room 2>/dev/null
294
+ docker run -d --name developer_control_room -p 7860:7860 developer_control_room:latest
295
+ python inference.py
296
+ ```
297
+
298
+ ## Validation
299
+
300
+ The benchmark has also been validated against the submission-style checks:
301
+
302
+ - the deployed environment responds to `/reset`
303
+ - Docker build succeeds
304
+ - `inference.py` emits the required `[START]`, `[STEP]`, and `[END]` lines
305
+
306
+ ## Project structure
307
+
308
+ ```text
309
+ developer_control_room/
310
+ ├── Dockerfile
311
+ ├── README.md
312
+ ├── openenv.yaml
313
+ ├── pyproject.toml
314
+ ├── inference.py
315
+ ├── baseline.py
316
+ ├── tasks.py
317
+ ├── graders.py
318
+ ├── models.py
319
+ ├── client.py
320
+ └── server/
321
+ ├── app.py
322
+ └── developer_control_room_environment.py
323
+ ```
__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Developer Control Room OpenEnv benchmark."""
2
+
3
+ from .client import DeveloperControlRoomEnv
4
+ from .models import (
5
+ ActionParameters,
6
+ DeveloperControlRoomAction,
7
+ DeveloperControlRoomObservation,
8
+ DeveloperControlRoomState,
9
+ )
10
+
11
+ __all__ = [
12
+ "ActionParameters",
13
+ "DeveloperControlRoomAction",
14
+ "DeveloperControlRoomObservation",
15
+ "DeveloperControlRoomState",
16
+ "DeveloperControlRoomEnv",
17
+ ]
baseline.py ADDED
@@ -0,0 +1,961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Baseline policy helpers for the Developer Control Room benchmark."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import sys
9
+ import textwrap
10
+ from typing import Any, List, Optional
11
+
12
+ import requests
13
+ from openai import OpenAI
14
+
15
+ from client import DeveloperControlRoomEnv
16
+ from models import ActionParameters, DeveloperControlRoomAction
17
+ from tasks import get_task
18
+
19
+ SYSTEM_PROMPT = textwrap.dedent(
20
+ """
21
+ You are controlling a developer-assistant benchmark for data-platform workflows.
22
+ Reply with exactly one JSON object with keys `action_type` and `parameters`.
23
+ Do not include markdown, prose, or code fences.
24
+
25
+ Valid actions:
26
+ {"action_type":"search_workspace","parameters":{"query":"..."}}
27
+ {"action_type":"read_file","parameters":{"path":"..."}}
28
+ {"action_type":"inspect_schema","parameters":{"asset":"..."}}
29
+ {"action_type":"inspect_lineage","parameters":{"asset":"..."}}
30
+ {"action_type":"inspect_llm_draft","parameters":{"draft_id":"primary"}}
31
+ {"action_type":"edit_file","parameters":{"path":"...","content":"..."}}
32
+ {"action_type":"run_validator","parameters":{"validator":"..."}}
33
+ {"action_type":"submit_repair","parameters":{"root_cause":"...","fix_path":"...","summary":"..."}}
34
+ {"action_type":"submit_review","parameters":{"verdict":"approve|reject","issue_type":"...","summary":"..."}}
35
+ {"action_type":"submit_workspace","parameters":{"summary":"..."}}
36
+
37
+ Use exact file paths, assets, and validator names from the observation.
38
+ Prefer short, efficient trajectories and submit when enough evidence is gathered.
39
+ """
40
+ ).strip()
41
+
42
+ DEBUG_LOGGING = os.getenv("DEVELOPER_CONTROL_ROOM_DEBUG", "false").lower() == "true"
43
+
44
+
45
+ def debug_log(message: str) -> None:
46
+ if DEBUG_LOGGING:
47
+ print(message, file=sys.stderr, flush=True)
48
+
49
+
50
+ def compact_json(data: dict[str, Any]) -> str:
51
+ return json.dumps(data, separators=(",", ":"), ensure_ascii=True)
52
+
53
+
54
+ def parse_model_action(response_text: str) -> Optional[dict[str, Any]]:
55
+ text = response_text.strip()
56
+ if not text:
57
+ return None
58
+ if text.startswith("```"):
59
+ text = "\n".join(line for line in text.splitlines() if not line.startswith("```")).strip()
60
+ try:
61
+ return json.loads(text)
62
+ except json.JSONDecodeError:
63
+ start = text.find("{")
64
+ end = text.rfind("}") + 1
65
+ if start != -1 and end > start:
66
+ try:
67
+ return json.loads(text[start:end])
68
+ except json.JSONDecodeError:
69
+ return None
70
+ return None
71
+
72
+
73
+ def build_user_prompt(
74
+ step: int,
75
+ observation: Any,
76
+ history: List[str],
77
+ episode_memory: str = "",
78
+ ) -> str:
79
+ history_block = "\n".join(history[-4:]) if history else "None"
80
+ memory_block = episode_memory if episode_memory else "None"
81
+ return textwrap.dedent(
82
+ f"""
83
+ Step: {step}
84
+ Task: {observation.task_id}
85
+ Scenario: {observation.scenario_id}
86
+ Request: {observation.developer_request}
87
+ Workspace summary: {observation.workspace_summary}
88
+ Known files: {json.dumps(observation.known_files)}
89
+ Editable targets: {json.dumps(observation.editable_targets)}
90
+ Known assets: {json.dumps(observation.known_assets)}
91
+ Available validators: {json.dumps(observation.available_validators)}
92
+ Previous steps:
93
+ {history_block}
94
+ Recent episode memory:
95
+ {memory_block}
96
+ Gathered data: {json.dumps(observation.queried_data)}
97
+ Edited files: {json.dumps(list(observation.edited_files.keys()))}
98
+ Validator status: {json.dumps(observation.validator_status)}
99
+ Last feedback: {observation.feedback}
100
+ Last action error: {observation.last_action_error or "null"}
101
+ Return the next JSON action only.
102
+ """
103
+ ).strip()
104
+
105
+
106
+ def get_model_action(
107
+ client: OpenAI,
108
+ model_name: str,
109
+ temperature: float,
110
+ max_tokens: int,
111
+ timeout_seconds: float,
112
+ step: int,
113
+ observation: Any,
114
+ history: List[str],
115
+ episode_memory: str = "",
116
+ ) -> Optional[dict[str, Any]]:
117
+ user_prompt = build_user_prompt(step, observation, history, episode_memory)
118
+ try:
119
+ if os.getenv("DEVELOPER_CONTROL_ROOM_FORCE_MODEL_TIMEOUT", "false").lower() == "true":
120
+ raise TimeoutError("Forced model timeout for fallback-path validation.")
121
+ completion = client.chat.completions.create(
122
+ model=model_name,
123
+ messages=[
124
+ {"role": "system", "content": SYSTEM_PROMPT},
125
+ {"role": "user", "content": user_prompt},
126
+ ],
127
+ temperature=temperature,
128
+ max_tokens=max_tokens,
129
+ timeout=timeout_seconds,
130
+ stream=False,
131
+ )
132
+ text = (completion.choices[0].message.content or "").strip()
133
+ return parse_model_action(text)
134
+ except Exception as exc:
135
+ debug_log(f"[DEBUG] Model request failed: {exc}")
136
+ return None
137
+
138
+
139
+ def action_is_valid(action: Optional[dict[str, Any]], observation: Any) -> bool:
140
+ if not isinstance(action, dict):
141
+ return False
142
+ action_type = action.get("action_type")
143
+ if action_type not in observation.available_actions:
144
+ return False
145
+ params = action.get("parameters", {})
146
+ if not isinstance(params, dict):
147
+ return False
148
+ queried = observation.queried_data
149
+ read_paths = set(queried.get("read_file", {}))
150
+ inspected_assets = set(queried.get("inspect_schema", {})) | set(queried.get("inspect_lineage", {}))
151
+ has_edit = bool(observation.edited_files)
152
+
153
+ if action_type == "read_file":
154
+ path = (params.get("path") or "").strip()
155
+ return bool(path) and path in set(observation.known_files) | set(observation.editable_targets)
156
+
157
+ if action_type == "inspect_schema":
158
+ asset = (params.get("asset") or "").strip()
159
+ return bool(asset) and asset in set(observation.known_assets)
160
+
161
+ if action_type == "inspect_lineage":
162
+ asset = (params.get("asset") or "").strip()
163
+ return bool(asset) and asset in set(observation.known_assets)
164
+
165
+ if action_type == "inspect_llm_draft":
166
+ return (params.get("draft_id") or "primary").strip() == "primary"
167
+
168
+ if action_type == "run_validator":
169
+ validator = (params.get("validator") or "").strip()
170
+ if not validator or validator not in set(observation.available_validators):
171
+ return False
172
+ if observation.task_id.startswith("repair_") or observation.task_id.startswith("synthesize_"):
173
+ return has_edit
174
+ return True
175
+
176
+ if action_type == "edit_file":
177
+ path = (params.get("path") or "").strip()
178
+ content = (params.get("content") or "").strip()
179
+ if not path or not content or path not in set(observation.editable_targets):
180
+ return False
181
+ if observation.task_id.startswith("synthesize_"):
182
+ return bool(read_paths) and bool(inspected_assets)
183
+ if observation.task_id.startswith("repair_"):
184
+ return path in read_paths or bool(read_paths & set(observation.known_files))
185
+ return True
186
+
187
+ if action_type == "submit_repair":
188
+ return has_edit
189
+
190
+ if action_type == "submit_workspace":
191
+ return has_edit
192
+
193
+ if action_type == "submit_review":
194
+ return "primary" in queried.get("inspect_llm_draft", {})
195
+
196
+ return True
197
+
198
+
199
+ def build_action(action_dict: dict[str, Any]) -> DeveloperControlRoomAction:
200
+ return DeveloperControlRoomAction(
201
+ action_type=action_dict.get("action_type", ""),
202
+ parameters=ActionParameters(**action_dict.get("parameters", {})),
203
+ )
204
+
205
+
206
+ def get_http_base(env: DeveloperControlRoomEnv, env_url: Optional[str]) -> Optional[str]:
207
+ if env_url:
208
+ return env_url.rstrip("/")
209
+ ws_url = getattr(env, "_ws_url", "")
210
+ if not ws_url:
211
+ return None
212
+ base = ws_url[:-3] if ws_url.endswith("/ws") else ws_url
213
+ if base.startswith("ws://"):
214
+ return "http://" + base[len("ws://") :]
215
+ if base.startswith("wss://"):
216
+ return "https://" + base[len("wss://") :]
217
+ return base
218
+
219
+
220
+ def fetch_grader_result(env: DeveloperControlRoomEnv, env_url: Optional[str]) -> dict[str, Any]:
221
+ base = get_http_base(env, env_url)
222
+ if not base:
223
+ return {"total": 0.0, "solved": False}
224
+ try:
225
+ response = requests.get(f"{base}/grader", timeout=20)
226
+ response.raise_for_status()
227
+ payload = response.json()
228
+ return {
229
+ "total": float(payload.get("total", 0.0)),
230
+ "solved": bool(payload.get("solved", False)),
231
+ }
232
+ except Exception as exc:
233
+ debug_log(f"[DEBUG] grader fetch failed: {exc}")
234
+ return {"total": 0.0, "solved": False}
235
+
236
+
237
+ def repair_sql() -> str:
238
+ return """with base as (
239
+ select
240
+ o.order_id,
241
+ o.customer_id,
242
+ o.event_time as order_ts,
243
+ date(o.event_time) as order_date,
244
+ o.amount_cents / 100.0 as total_amount
245
+ from raw.orders_events o
246
+ where o.status = 'completed'
247
+ )
248
+ select * from base;
249
+ """
250
+
251
+
252
+ def repair_path_yaml() -> str:
253
+ return """name: customer_events_ingest
254
+ schedule: "0 * * * *"
255
+ owner: ingestion-platform
256
+ source_path: "abfss://bronze@datalake.dfs.core.windows.net/customer-events/v2/dt={{ ds }}/"
257
+ format: parquet
258
+ target: customer_events_raw
259
+ """
260
+
261
+
262
+ def repair_jenkins_job() -> str:
263
+ return """pipeline {
264
+ agent any
265
+ stages {
266
+ stage('Run') {
267
+ steps {
268
+ sh './scripts/run_orders_daily.sh'
269
+ }
270
+ }
271
+ }
272
+ }
273
+ """
274
+
275
+
276
+ def repair_dependency_yaml() -> str:
277
+ return """name: revenue_dashboard_refresh
278
+ schedule: "0 5 * * *"
279
+ owner: finance-analytics
280
+ sources:
281
+ - orders_daily
282
+ target: revenue_dashboard_refresh
283
+ """
284
+
285
+
286
+ def repair_release_yaml() -> str:
287
+ return repair_release_yaml_for("TARGET_WAREHOUSE_ROLE", "analytics_writer")
288
+
289
+
290
+ def repair_release_yaml_for(env_key: str, role: str) -> str:
291
+ return f"""job: reporting_release
292
+ runner_image: reporting-release:latest
293
+ script: ./scripts/release_reporting_asset.sh
294
+ env:
295
+ {env_key}: {role}
296
+ ALERT_ROUTE: finance-reporting
297
+ """
298
+
299
+
300
+ def repair_type_alignment_sql() -> str:
301
+ return repair_type_alignment_sql_for("customer_code")
302
+
303
+
304
+ def repair_type_alignment_sql_for(id_col: str) -> str:
305
+ return f"""insert into customer_profile_dim (
306
+ {id_col},
307
+ loyalty_tier,
308
+ state_code
309
+ )
310
+ select
311
+ s.{id_col},
312
+ s.loyalty_tier,
313
+ s.state_code
314
+ from customer_profile_stage s;
315
+ """
316
+
317
+
318
+ def repair_archive_load_yaml() -> str:
319
+ return """job: orders_archive_load
320
+ target_table: orders_archive
321
+ source_columns:
322
+ - order_id
323
+ - customer_id
324
+ - order_ts
325
+ - order_status
326
+ - gross_amount_usd
327
+ - currency_code
328
+ defaults:
329
+ ingest_source: csv_archive
330
+ ingest_batch_id: current_batch_id
331
+ created_at: current_timestamp
332
+ updated_at: current_timestamp
333
+ archive_status: active
334
+ notes: ''
335
+ """
336
+
337
+
338
+ def repair_pk_merge_sql() -> str:
339
+ return """with deduped as (
340
+ select
341
+ d.customer_id,
342
+ d.customer_name,
343
+ d.state_code,
344
+ d.updated_at,
345
+ row_number() over (
346
+ partition by customer_id
347
+ order by d.updated_at desc
348
+ ) as rn
349
+ from dim_customer_delta d
350
+ )
351
+ insert into dim_customer (
352
+ customer_id,
353
+ customer_name,
354
+ state_code,
355
+ updated_at
356
+ )
357
+ select
358
+ deduped.customer_id,
359
+ deduped.customer_name,
360
+ deduped.state_code,
361
+ deduped.updated_at
362
+ from deduped
363
+ where deduped.rn = 1;
364
+ """
365
+
366
+
367
+ def merchant_pipeline() -> str:
368
+ return """name: merchant_risk_features
369
+ schedule: "0 1 * * *"
370
+ owner: risk-platform
371
+ sources:
372
+ - transactions_silver
373
+ - chargebacks_silver
374
+ - merchant_dim
375
+ target: merchant_risk_features
376
+ checks_file: checks/merchant_risk_features.yaml
377
+ downstreams:
378
+ - risk_model_scoring
379
+ """
380
+
381
+
382
+ def merchant_sql() -> str:
383
+ return """with tx as (
384
+ select
385
+ t.merchant_id,
386
+ count(*) as txn_count_30d
387
+ from transactions_silver t
388
+ join merchant_dim m on t.merchant_id = m.merchant_id
389
+ where m.is_test = false
390
+ and t.processed_at >= current_date - interval '30 day'
391
+ group by 1
392
+ ),
393
+ cb as (
394
+ select
395
+ c.merchant_id,
396
+ count(*) as chargeback_count_30d
397
+ from chargebacks_silver c
398
+ where c.processed_at >= current_date - interval '30 day'
399
+ group by 1
400
+ )
401
+ select
402
+ tx.merchant_id,
403
+ tx.txn_count_30d,
404
+ coalesce(cb.chargeback_count_30d, 0) * 1.0 / nullif(tx.txn_count_30d, 0) as chargeback_rate_30d,
405
+ current_date as snapshot_date
406
+ from tx
407
+ left join cb on tx.merchant_id = cb.merchant_id;
408
+ """
409
+
410
+
411
+ def merchant_checks() -> str:
412
+ return """checks:
413
+ - type: freshness
414
+ column: snapshot_date
415
+ - type: not_null
416
+ column: merchant_id
417
+ - type: not_null
418
+ column: snapshot_date
419
+ """
420
+
421
+
422
+ def merchant_schema() -> str:
423
+ return """{
424
+ "name": "merchant_risk_features",
425
+ "columns": [
426
+ {"name": "merchant_id", "type": "string"},
427
+ {"name": "txn_count_30d", "type": "integer"},
428
+ {"name": "chargeback_rate_30d", "type": "float"},
429
+ {"name": "snapshot_date", "type": "date"}
430
+ ]
431
+ }
432
+ """
433
+
434
+
435
+ def weekly_view_sql() -> str:
436
+ return """with invoices as (
437
+ select
438
+ i.account_id,
439
+ date_trunc('week', i.invoice_ts) as revenue_week,
440
+ sum(i.net_revenue_usd) as invoice_revenue_usd
441
+ from invoice_line_items i
442
+ group by 1, 2
443
+ ),
444
+ credits as (
445
+ select
446
+ c.account_id,
447
+ date_trunc('week', c.credit_memo_date) as revenue_week,
448
+ sum(c.credit_amount_usd) as credit_amount_usd
449
+ from credit_memos_daily c
450
+ group by 1, 2
451
+ )
452
+ select
453
+ invoices.account_id,
454
+ invoices.revenue_week,
455
+ invoices.invoice_revenue_usd - coalesce(credits.credit_amount_usd, 0) as net_revenue_usd
456
+ from invoices
457
+ left join credits
458
+ on invoices.account_id = credits.account_id
459
+ and invoices.revenue_week = credits.revenue_week;
460
+ """
461
+
462
+
463
+ def weekly_view_schema() -> str:
464
+ return """{
465
+ "name": "finance_weekly_net_revenue",
466
+ "columns": [
467
+ {"name": "account_id", "type": "string"},
468
+ {"name": "revenue_week", "type": "timestamp"},
469
+ {"name": "net_revenue_usd", "type": "float"}
470
+ ]
471
+ }
472
+ """
473
+
474
+
475
+ def margin_watch_sql() -> str:
476
+ return margin_watch_sql_for("margin_delta_pct")
477
+
478
+
479
+ def margin_watch_sql_for(metric: str) -> str:
480
+ return f"""with invoices as (
481
+ select
482
+ i.account_id,
483
+ date(i.invoice_ts) as margin_date,
484
+ sum(i.net_revenue_usd) as net_revenue_usd,
485
+ sum(i.margin_usd) as margin_usd
486
+ from invoice_line_items i
487
+ group by 1, 2
488
+ ),
489
+ credits as (
490
+ select
491
+ c.account_id,
492
+ c.credit_memo_date as margin_date,
493
+ sum(c.credit_amount_usd) as credit_amount_usd
494
+ from credit_memos_daily c
495
+ group by 1, 2
496
+ )
497
+ select
498
+ invoices.account_id,
499
+ invoices.margin_date,
500
+ invoices.margin_usd - coalesce(credits.credit_amount_usd, 0) as margin_usd,
501
+ (
502
+ (invoices.margin_usd - coalesce(credits.credit_amount_usd, 0))
503
+ - lag(invoices.margin_usd - coalesce(credits.credit_amount_usd, 0))
504
+ over (partition by invoices.account_id order by invoices.margin_date)
505
+ ) / nullif(
506
+ lag(invoices.margin_usd - coalesce(credits.credit_amount_usd, 0))
507
+ over (partition by invoices.account_id order by invoices.margin_date),
508
+ 0
509
+ ) as {metric}
510
+ from invoices
511
+ left join credits
512
+ on invoices.account_id = credits.account_id
513
+ and invoices.margin_date = credits.margin_date;
514
+ """
515
+
516
+
517
+ def margin_watch_schema() -> str:
518
+ return margin_watch_schema_for("margin_delta_pct")
519
+
520
+
521
+ def margin_watch_schema_for(metric: str) -> str:
522
+ return f"""{{
523
+ "name": "finance_margin_watch",
524
+ "columns": [
525
+ {{"name": "account_id", "type": "string"}},
526
+ {{"name": "margin_date", "type": "date"}},
527
+ {{"name": "margin_usd", "type": "float"}},
528
+ {{"name": "{metric}", "type": "float"}}
529
+ ]
530
+ }}
531
+ """
532
+
533
+
534
+ def margin_watch_alert() -> str:
535
+ return margin_watch_alert_for("margin_delta_pct", "-0.10")
536
+
537
+
538
+ def margin_watch_alert_for(metric: str, threshold: str) -> str:
539
+ return f"""name: finance_margin_watch
540
+ dataset: finance_margin_watch
541
+ metric: {metric}
542
+ threshold: {threshold}
543
+ severity: medium
544
+ """
545
+
546
+
547
+ def _match_first(text: str, options: list[str], default: str) -> str:
548
+ lowered = text.lower()
549
+ for option in options:
550
+ if option.lower() in lowered:
551
+ return option
552
+ return default
553
+
554
+
555
+ def _detect_release_variant(observation: Any) -> tuple[str, str, str]:
556
+ text = f"{observation.developer_request} {observation.workspace_summary}"
557
+ env_key = _match_first(text, ["TARGET_REPORTING_ROLE", "TARGET_WAREHOUSE_ROLE"], "TARGET_WAREHOUSE_ROLE")
558
+ if env_key == "TARGET_REPORTING_ROLE":
559
+ return env_key, "reporting_writer", "REPORTING_ROLE"
560
+ return env_key, "analytics_writer", "WAREHOUSE_ROLE"
561
+
562
+
563
+ def _detect_id_column(observation: Any) -> str:
564
+ text = f"{observation.developer_request} {observation.workspace_summary}"
565
+ return _match_first(text, ["profile_code", "member_code", "customer_code"], "customer_code")
566
+
567
+
568
+ def _detect_contract_metric(observation: Any) -> tuple[str, str]:
569
+ text = f"{observation.developer_request} {observation.workspace_summary}"
570
+ metric = _match_first(text, ["net_revenue_usd", "arr_usd", "mrr_usd"], "mrr_usd")
571
+ replacements = {
572
+ "mrr_usd": "monthly_recurring_revenue_usd",
573
+ "arr_usd": "annual_recurring_revenue_usd",
574
+ "net_revenue_usd": "net_revenue_amount_usd",
575
+ }
576
+ return metric, replacements[metric]
577
+
578
+
579
+ def _detect_watch_variant(observation: Any) -> tuple[str, str]:
580
+ text = f"{observation.developer_request} {observation.workspace_summary}"
581
+ metric = _match_first(text, ["net_revenue_delta_pct", "margin_delta_pct"], "margin_delta_pct")
582
+ threshold_match = re.search(r"below `(-?\d+\.\d+)`", text)
583
+ threshold = threshold_match.group(1) if threshold_match else ("-0.12" if metric == "net_revenue_delta_pct" else "-0.10")
584
+ return metric, threshold
585
+
586
+
587
+ def margin_pipeline() -> str:
588
+ return """name: customer_margin_mart
589
+ schedule: "0 1 * * *"
590
+ owner: data-platform
591
+ sources:
592
+ - orders_silver
593
+ - refunds_silver
594
+ - customer_dim
595
+ target: customer_margin_mart
596
+ checks_file: checks/customer_margin_mart.yaml
597
+ """
598
+
599
+
600
+ def margin_sql() -> str:
601
+ return """with orders as (
602
+ select
603
+ o.customer_id,
604
+ sum(o.gross_amount_usd) as gross_revenue_usd
605
+ from orders_silver o
606
+ join customer_dim c on o.customer_id = c.customer_id
607
+ where c.is_test = false
608
+ group by 1
609
+ ),
610
+ refunds as (
611
+ select
612
+ r.customer_id,
613
+ sum(r.refund_amount_usd) as refund_amount_usd
614
+ from refunds_silver r
615
+ join customer_dim c on r.customer_id = c.customer_id
616
+ where c.is_test = false
617
+ group by 1
618
+ )
619
+ select
620
+ orders.customer_id,
621
+ orders.gross_revenue_usd,
622
+ coalesce(refunds.refund_amount_usd, 0) as refund_amount_usd,
623
+ orders.gross_revenue_usd - coalesce(refunds.refund_amount_usd, 0) as net_margin_usd,
624
+ current_date as snapshot_date
625
+ from orders
626
+ left join refunds on orders.customer_id = refunds.customer_id;
627
+ """
628
+
629
+
630
+ def margin_checks() -> str:
631
+ return """checks:
632
+ - type: freshness
633
+ column: snapshot_date
634
+ - type: not_null
635
+ column: customer_id
636
+ - type: not_null
637
+ column: snapshot_date
638
+ """
639
+
640
+
641
+ def margin_schema() -> str:
642
+ return """{
643
+ "name": "customer_margin_mart",
644
+ "columns": [
645
+ {"name": "customer_id", "type": "string"},
646
+ {"name": "gross_revenue_usd", "type": "float"},
647
+ {"name": "refund_amount_usd", "type": "float"},
648
+ {"name": "net_margin_usd", "type": "float"},
649
+ {"name": "snapshot_date", "type": "date"}
650
+ ]
651
+ }
652
+ """
653
+
654
+
655
+ def fallback_action(task_name: str, observation: Any) -> dict[str, Any]:
656
+ queried = observation.queried_data
657
+ validators = observation.validator_status
658
+ edited = observation.edited_files
659
+ scenario_id = observation.scenario_id
660
+ task_def = get_task(task_name)
661
+ grader_family = task_def["grader_family"]
662
+
663
+ if grader_family == "repair":
664
+ repair_specs = {
665
+ "PR-001": {
666
+ "read_paths": ["transforms/orders_daily.sql"],
667
+ "schema_assets": ["raw.orders_events"],
668
+ "edit_path": "transforms/orders_daily.sql",
669
+ "content": repair_sql(),
670
+ "validators": ["sql_compile", "contract_guard"],
671
+ "submission": {
672
+ "root_cause": "Schema rename changed event_ts to event_time in raw.orders_events.",
673
+ "fix_path": "transforms/orders_daily.sql",
674
+ "summary": "Updated the transform to read event_time while aliasing back to order_ts so the published contract stays stable.",
675
+ },
676
+ },
677
+ "PR-002": {
678
+ "read_paths": ["pipelines/customer_events_ingest.yaml", "docs/storage_layout.md"],
679
+ "schema_assets": [],
680
+ "edit_path": "pipelines/customer_events_ingest.yaml",
681
+ "content": repair_path_yaml(),
682
+ "validators": ["path_resolver", "target_guard"],
683
+ "submission": {
684
+ "root_cause": "The ADLS landing path still used the old date partition instead of the new dt folder layout.",
685
+ "fix_path": "pipelines/customer_events_ingest.yaml",
686
+ "summary": "Updated the ingest path to customer-events/v2 with dt partitions.",
687
+ },
688
+ },
689
+ "PR-003": {
690
+ "read_paths": ["ci/jenkins/orders_daily.groovy", "docs/ci_conventions.md"],
691
+ "schema_assets": [],
692
+ "edit_path": "ci/jenkins/orders_daily.groovy",
693
+ "content": repair_jenkins_job(),
694
+ "validators": ["jenkins_lint"],
695
+ "submission": {
696
+ "root_cause": "The Jenkins job called a hyphenated runner path that does not exist after the CI cleanup.",
697
+ "fix_path": "ci/jenkins/orders_daily.groovy",
698
+ "summary": "Restored the run_orders_daily.sh runner path in the Jenkins job definition.",
699
+ },
700
+ },
701
+ "PR-004": {
702
+ "read_paths": ["pipelines/revenue_dashboard_refresh.yaml", "docs/lineage_notes.md"],
703
+ "schema_assets": [],
704
+ "edit_path": "pipelines/revenue_dashboard_refresh.yaml",
705
+ "content": repair_dependency_yaml(),
706
+ "validators": ["dependency_guard"],
707
+ "submission": {
708
+ "root_cause": "The dashboard pipeline still depended on the deprecated orders_daily_v2 alias instead of the canonical upstream.",
709
+ "fix_path": "pipelines/revenue_dashboard_refresh.yaml",
710
+ "summary": "Repointed revenue_dashboard_refresh to orders_daily so the dashboard can refresh from the canonical dependency.",
711
+ },
712
+ },
713
+ "PR-005": {
714
+ "read_paths": ["deploy/reporting_release.yaml", "docs/deploy_runbook.md"],
715
+ "schema_assets": [],
716
+ "edit_path": "deploy/reporting_release.yaml",
717
+ "content": "",
718
+ "validators": ["deploy_lint", "role_guard"],
719
+ "submission": {},
720
+ },
721
+ "PR-006": {
722
+ "read_paths": [
723
+ "transforms/customer_profile_import.sql",
724
+ "samples/customer_profile_import.csv",
725
+ "docs/load_contracts.md",
726
+ ],
727
+ "schema_assets": [],
728
+ "edit_path": "transforms/customer_profile_import.sql",
729
+ "content": "",
730
+ "validators": ["type_alignment_guard", "load_contract_guard"],
731
+ "submission": {},
732
+ },
733
+ "PR-007": {
734
+ "read_paths": [
735
+ "pipelines/orders_archive_load.yaml",
736
+ "schemas/orders_archive.json",
737
+ "docs/archive_load_guide.md",
738
+ ],
739
+ "schema_assets": [],
740
+ "edit_path": "pipelines/orders_archive_load.yaml",
741
+ "content": repair_archive_load_yaml(),
742
+ "validators": ["column_mapping_guard", "archive_defaults_guard"],
743
+ "submission": {
744
+ "root_cause": "The extract only supplies 6 source columns, but the archive table now expects 12 columns with deterministic warehouse defaults.",
745
+ "fix_path": "pipelines/orders_archive_load.yaml",
746
+ "summary": "Added the required archive default mappings so the 6-column extract can load into the 12-column target table.",
747
+ },
748
+ },
749
+ "PR-008": {
750
+ "read_paths": [
751
+ "transforms/dim_customer_merge.sql",
752
+ "samples/dim_customer_delta.csv",
753
+ "docs/merge_strategy.md",
754
+ ],
755
+ "schema_assets": [],
756
+ "edit_path": "transforms/dim_customer_merge.sql",
757
+ "content": repair_pk_merge_sql(),
758
+ "validators": ["pk_uniqueness_guard", "merge_strategy_guard"],
759
+ "submission": {
760
+ "root_cause": "Duplicate customer_id rows in the delta batch caused a primary key violation because the load inserted the full batch without deduplicating.",
761
+ "fix_path": "transforms/dim_customer_merge.sql",
762
+ "summary": "Updated the merge SQL to deduplicate by customer_id with row_number and keep the latest row before loading.",
763
+ },
764
+ },
765
+ }
766
+ spec = repair_specs.get(scenario_id, repair_specs["PR-001"])
767
+ if scenario_id == "PR-005":
768
+ env_key, role, stale_key = _detect_release_variant(observation)
769
+ spec = {
770
+ **spec,
771
+ "content": repair_release_yaml_for(env_key, role),
772
+ "submission": {
773
+ "root_cause": f"The release config still used {stale_key} instead of {env_key} after the deploy cleanup.",
774
+ "fix_path": "deploy/reporting_release.yaml",
775
+ "summary": f"Updated the reporting release config to pass {env_key} with the {role} role.",
776
+ },
777
+ }
778
+ if scenario_id == "PR-006":
779
+ id_col = _detect_id_column(observation)
780
+ spec = {
781
+ **spec,
782
+ "content": repair_type_alignment_sql_for(id_col),
783
+ "submission": {
784
+ "root_cause": f"The load cast {id_col} to integer even though the warehouse contract keeps it as a string with leading zeroes.",
785
+ "fix_path": "transforms/customer_profile_import.sql",
786
+ "summary": f"Updated the load mapping to preserve {id_col} as a string instead of casting it to integer.",
787
+ },
788
+ }
789
+ for path in spec["read_paths"]:
790
+ if path not in queried.get("read_file", {}):
791
+ return {"action_type": "read_file", "parameters": {"path": path}}
792
+ for asset in spec["schema_assets"]:
793
+ if asset not in queried.get("inspect_schema", {}):
794
+ return {"action_type": "inspect_schema", "parameters": {"asset": asset}}
795
+ if spec["edit_path"] not in edited:
796
+ return {
797
+ "action_type": "edit_file",
798
+ "parameters": {"path": spec["edit_path"], "content": spec["content"]},
799
+ }
800
+ for validator in spec["validators"]:
801
+ if validator not in validators:
802
+ return {"action_type": "run_validator", "parameters": {"validator": validator}}
803
+ return {"action_type": "submit_repair", "parameters": spec["submission"]}
804
+
805
+ if grader_family == "review":
806
+ review_specs = {
807
+ "LR-001": {
808
+ "read_paths": ["policies/data_governance.md"],
809
+ "validators": ["privacy_guard"],
810
+ "submission": {
811
+ "verdict": "reject",
812
+ "issue_type": "pii_exposure",
813
+ "summary": "Reject the patch because it adds customer_email to a shared analytics dataset and violates policy.",
814
+ },
815
+ },
816
+ "LR-002": {
817
+ "read_paths": ["docs/settlement_conventions.md"],
818
+ "validators": ["logic_guard"],
819
+ "submission": {
820
+ "verdict": "reject",
821
+ "issue_type": "technical_incorrectness",
822
+ "summary": "Reject the patch because the join key is wrong and the enrichment logic is incorrect.",
823
+ },
824
+ },
825
+ "LR-003": {
826
+ "read_paths": ["policies/published_contracts.md"],
827
+ "validators": ["contract_guard"],
828
+ "submission": {
829
+ "verdict": "reject",
830
+ "issue_type": "contract_breakage",
831
+ "summary": "",
832
+ },
833
+ },
834
+ "LR-004": {
835
+ "read_paths": ["policies/recovery_playbook.md"],
836
+ "validators": ["safety_guard"],
837
+ "submission": {
838
+ "verdict": "reject",
839
+ "issue_type": "unsafe_operation",
840
+ "summary": "Reject the recommendation because it suggests dropping a production mart and disabling checks.",
841
+ },
842
+ },
843
+ }
844
+ spec = review_specs.get(scenario_id, review_specs["LR-001"])
845
+ if scenario_id == "LR-003":
846
+ metric, replacement = _detect_contract_metric(observation)
847
+ spec = {
848
+ **spec,
849
+ "submission": {
850
+ "verdict": "reject",
851
+ "issue_type": "contract_breakage",
852
+ "summary": f"Reject the patch because it renames {metric} to {replacement} in a published contract.",
853
+ },
854
+ }
855
+ if "primary" not in queried.get("inspect_llm_draft", {}):
856
+ return {"action_type": "inspect_llm_draft", "parameters": {"draft_id": "primary"}}
857
+ for path in spec["read_paths"]:
858
+ if path not in queried.get("read_file", {}):
859
+ return {"action_type": "read_file", "parameters": {"path": path}}
860
+ for validator in spec["validators"]:
861
+ if validator not in validators:
862
+ return {"action_type": "run_validator", "parameters": {"validator": validator}}
863
+ return {"action_type": "submit_review", "parameters": spec["submission"]}
864
+
865
+ if grader_family == "workflow":
866
+ workflow_specs = {
867
+ "WS-001": {
868
+ "read_paths": ["templates/pipeline_template.yaml"],
869
+ "schema_assets": ["transactions_silver"],
870
+ "lineage_assets": [],
871
+ "edits": [
872
+ ("pipelines/merchant_risk_features.yaml", merchant_pipeline()),
873
+ ("sql/merchant_risk_features.sql", merchant_sql()),
874
+ ("checks/merchant_risk_features.yaml", merchant_checks()),
875
+ ("schemas/merchant_risk_features.json", merchant_schema()),
876
+ ],
877
+ "validators": ["workflow_lint", "governance_check"],
878
+ "summary": "Created merchant_risk_features with the required workflow artifacts and governance-safe SQL.",
879
+ },
880
+ "WS-002": {
881
+ "read_paths": [
882
+ "sql/views/finance_daily_revenue.sql",
883
+ "docs/reporting_view_standards.md",
884
+ "schemas/views/finance_daily_revenue.json",
885
+ ],
886
+ "schema_assets": ["invoice_line_items", "credit_memos_daily"],
887
+ "lineage_assets": [],
888
+ "edits": [
889
+ ("sql/views/finance_weekly_net_revenue.sql", weekly_view_sql()),
890
+ ("schemas/views/finance_weekly_net_revenue.json", weekly_view_schema()),
891
+ ],
892
+ "validators": ["view_sql_check", "view_contract_check"],
893
+ "summary": "Created the finance_weekly_net_revenue reporting view with weekly grain and a matching schema contract.",
894
+ },
895
+ "WS-003": {
896
+ "read_paths": [
897
+ "templates/pipeline_template.yaml",
898
+ "docs/platform_standards.md",
899
+ "checks/order_features.yaml",
900
+ ],
901
+ "schema_assets": ["orders_silver", "customer_dim"],
902
+ "lineage_assets": [],
903
+ "edits": [
904
+ ("pipelines/customer_margin_mart.yaml", margin_pipeline()),
905
+ ("sql/customer_margin_mart.sql", margin_sql()),
906
+ ("checks/customer_margin_mart.yaml", margin_checks()),
907
+ ("schemas/customer_margin_mart.json", margin_schema()),
908
+ ],
909
+ "validators": ["mart_lint", "mart_governance"],
910
+ "summary": "Created customer_margin_mart with daily pipeline metadata and a contract-safe schema.",
911
+ },
912
+ "WS-004": {
913
+ "read_paths": [
914
+ "sql/views/finance_daily_revenue.sql",
915
+ "docs/reporting_view_standards.md",
916
+ "docs/alerting_playbook.md",
917
+ ],
918
+ "schema_assets": ["invoice_line_items"],
919
+ "lineage_assets": [],
920
+ "edits": [
921
+ ("sql/views/finance_margin_watch.sql", ""),
922
+ ("schemas/views/finance_margin_watch.json", ""),
923
+ ("alerts/finance_margin_watch.yaml", ""),
924
+ ],
925
+ "validators": ["view_sql_check", "alert_config_check"],
926
+ "summary": "",
927
+ },
928
+ }
929
+ spec = workflow_specs.get(scenario_id, workflow_specs["WS-001"])
930
+ if scenario_id == "WS-004":
931
+ metric, threshold = _detect_watch_variant(observation)
932
+ spec = {
933
+ **spec,
934
+ "edits": [
935
+ ("sql/views/finance_margin_watch.sql", margin_watch_sql_for(metric)),
936
+ ("schemas/views/finance_margin_watch.json", margin_watch_schema_for(metric)),
937
+ ("alerts/finance_margin_watch.yaml", margin_watch_alert_for(metric, threshold)),
938
+ ],
939
+ "summary": f"Created the finance_margin_watch reporting view and alert config for {metric} monitoring.",
940
+ }
941
+ for path in spec["read_paths"]:
942
+ if path not in queried.get("read_file", {}):
943
+ return {"action_type": "read_file", "parameters": {"path": path}}
944
+ for asset in spec["schema_assets"]:
945
+ if asset not in queried.get("inspect_schema", {}):
946
+ return {"action_type": "inspect_schema", "parameters": {"asset": asset}}
947
+ for asset in spec["lineage_assets"]:
948
+ if asset not in queried.get("inspect_lineage", {}):
949
+ return {"action_type": "inspect_lineage", "parameters": {"asset": asset}}
950
+ for path, content in spec["edits"]:
951
+ if path not in edited:
952
+ return {
953
+ "action_type": "edit_file",
954
+ "parameters": {"path": path, "content": content},
955
+ }
956
+ for validator in spec["validators"]:
957
+ if validator not in validators:
958
+ return {"action_type": "run_validator", "parameters": {"validator": validator}}
959
+ return {"action_type": "submit_workspace", "parameters": {"summary": spec["summary"]}}
960
+
961
+ return {"action_type": "search_workspace", "parameters": {"query": observation.developer_request}}
client.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Client wrapper for the Developer Control Room benchmark."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from openenv.core import EnvClient
8
+ from openenv.core.client_types import StepResult
9
+
10
+ try:
11
+ from .models import (
12
+ DeveloperControlRoomAction,
13
+ DeveloperControlRoomObservation,
14
+ DeveloperControlRoomState,
15
+ )
16
+ except ImportError:
17
+ from models import (
18
+ DeveloperControlRoomAction,
19
+ DeveloperControlRoomObservation,
20
+ DeveloperControlRoomState,
21
+ )
22
+
23
+
24
+ class DeveloperControlRoomEnv(
25
+ EnvClient[
26
+ DeveloperControlRoomAction,
27
+ DeveloperControlRoomObservation,
28
+ DeveloperControlRoomState,
29
+ ]
30
+ ):
31
+ """Convenience client for the Developer Control Room environment."""
32
+
33
+ def _step_payload(self, action: DeveloperControlRoomAction) -> dict[str, Any]:
34
+ return action.model_dump(exclude_none=True)
35
+
36
+ def _parse_result(
37
+ self,
38
+ payload: dict[str, Any],
39
+ ) -> StepResult[DeveloperControlRoomObservation]:
40
+ obs = payload.get("observation", {})
41
+ observation = DeveloperControlRoomObservation(
42
+ episode_id=obs.get("episode_id", ""),
43
+ task_id=obs.get("task_id", ""),
44
+ scenario_id=obs.get("scenario_id", ""),
45
+ step_count=obs.get("step_count", 0),
46
+ max_steps=obs.get("max_steps", 0),
47
+ developer_request=obs.get("developer_request", ""),
48
+ workspace_summary=obs.get("workspace_summary", ""),
49
+ available_actions=obs.get("available_actions", []),
50
+ known_files=obs.get("known_files", []),
51
+ editable_targets=obs.get("editable_targets", []),
52
+ known_assets=obs.get("known_assets", []),
53
+ available_validators=obs.get("available_validators", []),
54
+ queried_data=obs.get("queried_data", {}),
55
+ edited_files=obs.get("edited_files", {}),
56
+ validator_status=obs.get("validator_status", {}),
57
+ cumulative_reward=obs.get("cumulative_reward", 0.0),
58
+ feedback=obs.get("feedback", ""),
59
+ last_action_error=obs.get("last_action_error"),
60
+ reward=payload.get("reward"),
61
+ done=payload.get("done", False),
62
+ )
63
+ return StepResult(
64
+ observation=observation,
65
+ reward=payload.get("reward"),
66
+ done=payload.get("done", False),
67
+ )
68
+
69
+ def _parse_state(self, payload: dict[str, Any]) -> DeveloperControlRoomState:
70
+ return DeveloperControlRoomState(**payload)
graders.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic graders and validator helpers for Developer Control Room."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ try:
8
+ from .tasks import get_grader_family
9
+ except ImportError:
10
+ from tasks import get_grader_family
11
+
12
+
13
+ def _norm(text: str) -> str:
14
+ return text.lower().strip()
15
+
16
+
17
+ def _workspace_files(state: dict, scenario: dict) -> dict[str, str]:
18
+ files = dict(scenario.get("files", {}))
19
+ files.update(state.get("edited_files", {}))
20
+ return files
21
+
22
+
23
+ def _token_score(text: str, groups: list[list[str]]) -> tuple[float, int, int]:
24
+ if not groups:
25
+ return 1.0, 0, 0
26
+ lowered = _norm(text)
27
+ matched = 0
28
+ for group in groups:
29
+ if any(_norm(option) in lowered for option in group):
30
+ matched += 1
31
+ return matched / len(groups), matched, len(groups)
32
+
33
+
34
+ def _contains_any(text: str, snippets: list[str]) -> bool:
35
+ lowered = _norm(text)
36
+ return any(_norm(snippet) in lowered for snippet in snippets)
37
+
38
+
39
+ def _source_text(source: dict, state: dict, scenario: dict) -> str:
40
+ source_type = source.get("type")
41
+ if source_type == "file":
42
+ return _workspace_files(state, scenario).get(source.get("path", ""), "")
43
+ if source_type == "draft":
44
+ return scenario.get("llm_draft", {}).get(source.get("draft_id", "primary"), "")
45
+ if source_type == "schema":
46
+ return scenario.get("schema_registry", {}).get(source.get("asset", ""), "")
47
+ return ""
48
+
49
+
50
+ def _investigation_score(state: dict, targets: set[tuple[str, str]]) -> float:
51
+ history = state.get("action_history", [])
52
+ seen: set[tuple[str, str]] = set()
53
+ for item in history:
54
+ action_type = item.get("action_type", "")
55
+ params = item.get("parameters", {})
56
+ key = (
57
+ action_type,
58
+ _norm(
59
+ params.get("path")
60
+ or params.get("asset")
61
+ or params.get("validator")
62
+ or params.get("draft_id")
63
+ or params.get("query")
64
+ or ""
65
+ ),
66
+ )
67
+ if key in targets:
68
+ seen.add(key)
69
+ if not targets:
70
+ return 0.0
71
+ return min(1.0, len(seen) / len(targets))
72
+
73
+
74
+ def _groups_score(text: str, groups: list[list[str]], forbidden_terms: list[str] | None = None) -> float:
75
+ score, _, _ = _token_score(text, groups)
76
+ if forbidden_terms and _contains_any(text, forbidden_terms):
77
+ return 0.0
78
+ return score
79
+
80
+
81
+ def _summary_score(text: str, groups: list[list[str]]) -> float:
82
+ return _groups_score(text, groups)
83
+
84
+
85
+ def _validator_usage_score(state: dict, validator_targets: list[str]) -> float:
86
+ if not validator_targets:
87
+ return 0.0
88
+ seen = state.get("validator_status", {})
89
+ matched = sum(1 for name in validator_targets if name in seen)
90
+ return matched / len(validator_targets)
91
+
92
+
93
+ def evaluate_validator(
94
+ task_id: str,
95
+ validator_name: str,
96
+ state: dict,
97
+ scenario: dict,
98
+ ) -> dict[str, Any]:
99
+ del task_id
100
+ validators = scenario.get("validators", {})
101
+ spec = validators.get(validator_name)
102
+ if spec is None:
103
+ return {"passed": False, "message": f"Unknown validator '{validator_name}'"}
104
+
105
+ kind = spec.get("kind")
106
+
107
+ if kind == "file_groups":
108
+ text = _source_text({"type": "file", "path": spec.get("path", "")}, state, scenario)
109
+ score, matched, total = _token_score(text, spec.get("required_groups", []))
110
+ has_forbidden = _contains_any(text, spec.get("forbidden_terms", []))
111
+ ok = score == 1.0 and not has_forbidden
112
+ return {
113
+ "passed": ok,
114
+ "message": (
115
+ f"PASS: {validator_name} satisfied."
116
+ if ok
117
+ else f"FAIL: matched {matched}/{total} groups; forbidden={has_forbidden}."
118
+ ),
119
+ }
120
+
121
+ if kind == "draft_groups":
122
+ text = _source_text({"type": "draft", "draft_id": spec.get("draft_id", "primary")}, state, scenario)
123
+ score, matched, total = _token_score(text, spec.get("required_groups", []))
124
+ has_forbidden = _contains_any(text, spec.get("forbidden_terms", []))
125
+ ok = score == 1.0 and not has_forbidden
126
+ return {
127
+ "passed": ok,
128
+ "message": (
129
+ f"PASS: {validator_name} satisfied."
130
+ if ok
131
+ else f"FAIL: matched {matched}/{total} groups; forbidden={has_forbidden}."
132
+ ),
133
+ }
134
+
135
+ if kind == "workflow_artifact":
136
+ target = scenario.get("workflow_target", {})
137
+ artifact_key = spec.get("artifact", "")
138
+ artifact = target.get("artifacts", {}).get(artifact_key, {})
139
+ text = _source_text({"type": "file", "path": artifact.get("path", "")}, state, scenario)
140
+ score, matched, total = _token_score(text, artifact.get("required_groups", []))
141
+ has_forbidden = _contains_any(text, artifact.get("forbidden_terms", []))
142
+ ok = score == 1.0 and not has_forbidden
143
+ return {
144
+ "passed": ok,
145
+ "message": (
146
+ f"PASS: {artifact_key} artifact satisfied validator."
147
+ if ok
148
+ else f"FAIL: matched {matched}/{total} groups; forbidden={has_forbidden}."
149
+ ),
150
+ }
151
+
152
+ return {"passed": False, "message": f"Unhandled validator kind '{kind}'"}
153
+
154
+
155
+ def _grade_pipeline_repair(state: dict, scenario: dict) -> dict[str, Any]:
156
+ files = _workspace_files(state, scenario)
157
+ target = scenario["repair_target"]
158
+ path = target["path"]
159
+ text = files.get(path, "")
160
+
161
+ investigation = 0.15 * _investigation_score(
162
+ state,
163
+ {(action_type, _norm(name)) for action_type, name in target.get("investigation_targets", [])},
164
+ )
165
+
166
+ edit_raw = _groups_score(text, target.get("required_groups", []), target.get("forbidden_terms", []))
167
+ edit_score = 0.45 * edit_raw
168
+
169
+ validator_status = state.get("validator_status", {})
170
+ validator_targets = scenario.get("available_validators", [])
171
+ validator_hits = sum(1 for name in validator_targets if validator_status.get(name, {}).get("passed"))
172
+ validator_score = 0.2 * (validator_hits / len(validator_targets) if validator_targets else 0.0)
173
+
174
+ submission = state.get("submission", {})
175
+ root_cause_score = _summary_score(submission.get("root_cause", ""), target.get("root_cause_groups", []))
176
+ summary_score_raw = _summary_score(submission.get("summary", ""), target.get("summary_groups", []))
177
+ fix_path_ok = 1.0 if submission.get("fix_path", "") == target.get("fix_path", "") else 0.0
178
+ submission_score = 0.2 * ((root_cause_score + summary_score_raw + fix_path_ok) / 3.0)
179
+ solved = (
180
+ state.get("submitted", False)
181
+ and edit_raw == 1.0
182
+ and validator_hits >= max(1, len(validator_targets) - 1)
183
+ and root_cause_score >= (2 / 3)
184
+ and fix_path_ok == 1.0
185
+ )
186
+
187
+ total = round(min(1.0, investigation + edit_score + validator_score + submission_score), 4)
188
+ return {
189
+ "total": total,
190
+ "solved": solved,
191
+ "breakdown": {
192
+ "investigation": round(investigation, 4),
193
+ "edit_score": round(edit_score, 4),
194
+ "validator_score": round(validator_score, 4),
195
+ "submission_score": round(submission_score, 4),
196
+ },
197
+ "feedback": (
198
+ f"investigation={investigation:.2f} "
199
+ f"edit={edit_score:.2f} validators={validator_score:.2f} "
200
+ f"submission={submission_score:.2f}"
201
+ ),
202
+ }
203
+
204
+
205
+ def _grade_llm_patch_review(state: dict, scenario: dict) -> dict[str, Any]:
206
+ target = scenario["review_target"]
207
+ submission = state.get("submission", {})
208
+
209
+ investigation = 0.15 * _investigation_score(
210
+ state,
211
+ {(action_type, _norm(name)) for action_type, name in target.get("investigation_targets", [])},
212
+ )
213
+
214
+ verdict_score = 0.3 if _norm(submission.get("verdict", "")) == target.get("correct_verdict", "") else 0.0
215
+ issue_score = 0.25 if _norm(submission.get("issue_type", "")) == target.get("correct_issue_type", "") else 0.0
216
+ summary_raw = _summary_score(submission.get("summary", ""), target.get("summary_groups", []))
217
+ summary_score = 0.12 * summary_raw
218
+ validator_score = 0.08 * _validator_usage_score(state, target.get("validator_targets", []))
219
+ solved = (
220
+ state.get("submitted", False)
221
+ and verdict_score > 0.0
222
+ and issue_score > 0.0
223
+ and summary_raw >= (2 / 3)
224
+ and _investigation_score(
225
+ state,
226
+ {(action_type, _norm(name)) for action_type, name in target.get("investigation_targets", [])},
227
+ )
228
+ >= (2 / 3)
229
+ )
230
+
231
+ total = round(min(1.0, investigation + verdict_score + issue_score + summary_score + validator_score), 4)
232
+ return {
233
+ "total": total,
234
+ "solved": solved,
235
+ "breakdown": {
236
+ "investigation": round(investigation, 4),
237
+ "verdict_score": round(verdict_score, 4),
238
+ "issue_score": round(issue_score, 4),
239
+ "summary_score": round(summary_score, 4),
240
+ "validator_score": round(validator_score, 4),
241
+ },
242
+ "feedback": (
243
+ f"investigation={investigation:.2f} verdict={verdict_score:.2f} "
244
+ f"issue={issue_score:.2f} summary={summary_score:.2f}"
245
+ ),
246
+ }
247
+
248
+
249
+ def _artifact_score(files: dict[str, str], target: dict) -> float:
250
+ required_artifacts = target.get("required_artifacts", [])
251
+ artifacts = target.get("artifacts", {})
252
+ if not required_artifacts:
253
+ return 0.0
254
+
255
+ total_weight = sum(artifacts[name].get("weight", 1.0) for name in required_artifacts)
256
+ if total_weight <= 0:
257
+ return 0.0
258
+
259
+ weighted_score = 0.0
260
+ for name in required_artifacts:
261
+ artifact = artifacts.get(name, {})
262
+ path = artifact.get("path", "")
263
+ text = files.get(path, "")
264
+ raw = _groups_score(text, artifact.get("required_groups", []), artifact.get("forbidden_terms", []))
265
+ weighted_score += artifact.get("weight", 1.0) * raw
266
+ return weighted_score / total_weight
267
+
268
+
269
+ def _governance_score(files: dict[str, str], target: dict) -> float:
270
+ forbidden_terms = target.get("forbidden_terms", [])
271
+ required_artifacts = target.get("required_artifacts", [])
272
+ artifacts = target.get("artifacts", {})
273
+ if not forbidden_terms:
274
+ return 1.0
275
+
276
+ for name in required_artifacts:
277
+ artifact = artifacts.get(name, {})
278
+ text = files.get(artifact.get("path", ""), "")
279
+ artifact_forbidden = list(forbidden_terms) + artifact.get("forbidden_terms", [])
280
+ if _contains_any(text, artifact_forbidden):
281
+ return 0.0
282
+ return 1.0
283
+
284
+
285
+ def _grade_workflow_shipping(state: dict, scenario: dict) -> dict[str, Any]:
286
+ files = _workspace_files(state, scenario)
287
+ target = scenario["workflow_target"]
288
+
289
+ investigation_raw = _investigation_score(
290
+ state,
291
+ {(action_type, _norm(name)) for action_type, name in target.get("investigation_targets", [])},
292
+ )
293
+ investigation = 0.2 * investigation_raw
294
+
295
+ artifact_raw = _artifact_score(files, target)
296
+ artifact_score = 0.3 * artifact_raw
297
+
298
+ validator_targets = target.get("validator_targets", [])
299
+ solve_validator_targets = target.get("solve_validator_targets", validator_targets)
300
+ validator_status = state.get("validator_status", {})
301
+ validator_hits = sum(1 for name in validator_targets if validator_status.get(name, {}).get("passed"))
302
+ solve_validator_hits = sum(1 for name in solve_validator_targets if validator_status.get(name, {}).get("passed"))
303
+ validator_score = 0.3 * (validator_hits / len(validator_targets) if validator_targets else 0.0)
304
+
305
+ governance_raw = _governance_score(files, target)
306
+ governance_score = 0.1 * governance_raw
307
+
308
+ summary = state.get("submission", {}).get("summary", "")
309
+ summary_raw = _summary_score(summary, target.get("summary_groups", []))
310
+ summary_score = 0.1 * summary_raw
311
+ solved = (
312
+ state.get("submitted", False)
313
+ and investigation_raw >= (2 / 3)
314
+ and artifact_raw == 1.0
315
+ and (solve_validator_hits == len(solve_validator_targets) if solve_validator_targets else True)
316
+ and governance_raw == 1.0
317
+ and summary_raw == 1.0
318
+ )
319
+
320
+ total = round(
321
+ min(1.0, investigation + artifact_score + validator_score + governance_score + summary_score),
322
+ 4,
323
+ )
324
+ return {
325
+ "total": total,
326
+ "solved": solved,
327
+ "breakdown": {
328
+ "investigation": round(investigation, 4),
329
+ "artifact_score": round(artifact_score, 4),
330
+ "validator_score": round(validator_score, 4),
331
+ "governance_score": round(governance_score, 4),
332
+ "summary_score": round(summary_score, 4),
333
+ },
334
+ "feedback": (
335
+ f"investigation={investigation:.2f} artifact={artifact_score:.2f} "
336
+ f"validators={validator_score:.2f} governance={governance_score:.2f}"
337
+ ),
338
+ }
339
+
340
+
341
+ def grade(task_id: str, state: dict, scenario: dict) -> dict[str, Any]:
342
+ graders = {
343
+ "repair": _grade_pipeline_repair,
344
+ "review": _grade_llm_patch_review,
345
+ "workflow": _grade_workflow_shipping,
346
+ }
347
+ try:
348
+ grader_family = get_grader_family(task_id)
349
+ except ValueError:
350
+ grader_family = task_id
351
+ fn = graders.get(grader_family)
352
+ if fn is None:
353
+ return {
354
+ "total": 0.0,
355
+ "solved": False,
356
+ "breakdown": {},
357
+ "feedback": f"Unknown task or grader family '{task_id}'",
358
+ }
359
+ return fn(state, scenario)
inference.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference Script Example
3
+ ===================================
4
+ MANDATORY
5
+ - Before submitting, ensure the following variables are defined in your environment configuration:
6
+ API_BASE_URL The API endpoint for the LLM.
7
+ MODEL_NAME The model identifier to use for inference.
8
+ HF_TOKEN Your Hugging Face / API key.
9
+ LOCAL_IMAGE_NAME The name of the local image to use for the environment if you are using from_docker_image()
10
+ method
11
+
12
+ - Defaults are set only for API_BASE_URL and MODEL_NAME
13
+ (and should reflect your active inference setup):
14
+ API_BASE_URL = os.getenv("API_BASE_URL", "<your-active-endpoint>")
15
+ MODEL_NAME = os.getenv("MODEL_NAME", "<your-active-model>")
16
+
17
+ - The inference script must be named `inference.py` and placed in the root directory of the project
18
+ - Participants must use OpenAI Client for all LLM calls using above variables
19
+
20
+ STDOUT FORMAT
21
+ - The script must emit exactly three line types to stdout, in this order:
22
+
23
+ [START] task=<task_name> env=<benchmark> model=<model_name>
24
+ [STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>
25
+ [END] success=<true|false> steps=<n> score=<score> rewards=<r1,r2,...,rn>
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import asyncio
31
+ import json
32
+ import os
33
+ import sys
34
+ import tempfile
35
+ from typing import Any, List, Optional
36
+
37
+ from openai import OpenAI
38
+
39
+ from baseline import action_is_valid, build_action, fallback_action, fetch_grader_result, get_model_action
40
+ from client import DeveloperControlRoomEnv
41
+ from tasks import list_tasks
42
+
43
+
44
+ def load_env_file(path: str = ".env") -> None:
45
+ if not os.path.exists(path):
46
+ return
47
+
48
+ try:
49
+ from dotenv import load_dotenv # type: ignore
50
+
51
+ load_dotenv(path)
52
+ return
53
+ except Exception:
54
+ pass
55
+
56
+ with open(path, "r", encoding="utf-8") as handle:
57
+ for raw_line in handle:
58
+ line = raw_line.strip()
59
+ if not line or line.startswith("#") or "=" not in line:
60
+ continue
61
+ key, value = line.split("=", 1)
62
+ key = key.strip()
63
+ value = value.strip().strip('"').strip("'")
64
+ if key and key not in os.environ:
65
+ os.environ[key] = value
66
+
67
+
68
+ load_env_file()
69
+
70
+ LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME") or os.getenv("IMAGE_NAME")
71
+ ENV_URL = os.getenv("ENV_URL")
72
+ API_KEY = os.getenv("HF_TOKEN") or os.getenv("OPENAI_API_KEY") or os.getenv("API_KEY")
73
+
74
+ API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
75
+ MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
76
+ TASK_NAME = os.getenv("DEVELOPER_CONTROL_ROOM_TASK")
77
+ BENCHMARK = os.getenv("DEVELOPER_CONTROL_ROOM_BENCHMARK", "developer_control_room")
78
+ MAX_STEPS = int(os.getenv("DEVELOPER_CONTROL_ROOM_MAX_STEPS", "14"))
79
+ DEFAULT_MODEL_STEPS = 2
80
+ MAX_MODEL_STEPS = int(
81
+ os.getenv("DEVELOPER_CONTROL_ROOM_MAX_MODEL_STEPS", str(DEFAULT_MODEL_STEPS))
82
+ )
83
+ RUN_ALL_SCENARIOS = os.getenv("DEVELOPER_CONTROL_ROOM_RUN_ALL_SCENARIOS", "false").lower() == "true"
84
+ SCENARIO_INDEX_RAW = os.getenv("DEVELOPER_CONTROL_ROOM_SCENARIO_INDEX")
85
+ SCENARIO_SEED_RAW = os.getenv("DEVELOPER_CONTROL_ROOM_SCENARIO_SEED")
86
+ SCENARIO_INDEX = int(SCENARIO_INDEX_RAW) if SCENARIO_INDEX_RAW not in (None, "") else None
87
+ SCENARIO_SEED = int(SCENARIO_SEED_RAW) if SCENARIO_SEED_RAW not in (None, "") else None
88
+ TEMPERATURE = 0.2
89
+ MAX_TOKENS = 250
90
+ MODEL_TIMEOUT_SECONDS = float(os.getenv("DEVELOPER_CONTROL_ROOM_MODEL_TIMEOUT_SECONDS", "20"))
91
+ ENABLE_EPISODE_MEMORY = os.getenv("DEVELOPER_CONTROL_ROOM_ENABLE_EPISODE_MEMORY", "false").lower() == "true"
92
+ DEBUG_LOGGING = os.getenv("DEVELOPER_CONTROL_ROOM_DEBUG", "false").lower() == "true"
93
+ EPISODE_MEMORY_PATH = os.getenv(
94
+ "DEVELOPER_CONTROL_ROOM_EPISODE_MEMORY_PATH",
95
+ os.path.join(tempfile.gettempdir(), "developer_control_room_episode_memory.json"),
96
+ )
97
+ EPISODE_MEMORY_LIMIT = int(os.getenv("DEVELOPER_CONTROL_ROOM_EPISODE_MEMORY_LIMIT", "6"))
98
+
99
+
100
+ def log_start(task: str, env: str, model: str) -> None:
101
+ print(f"[START] task={task} env={env} model={model}", flush=True)
102
+
103
+
104
+ def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
105
+ error_val = _single_line(error) if error else "null"
106
+ done_val = str(done).lower()
107
+ print(
108
+ f"[STEP] step={step} action={_single_line(action)} reward={reward:.2f} done={done_val} error={error_val}",
109
+ flush=True,
110
+ )
111
+
112
+
113
+ def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
114
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards)
115
+ print(
116
+ f"[END] success={str(success).lower()} steps={steps} score={max(0.0, min(score, 1.0)):.2f} rewards={rewards_str}",
117
+ flush=True,
118
+ )
119
+
120
+
121
+ def _single_line(value: str | None) -> str:
122
+ return (value or "").replace("\n", "\\n").replace("\r", "\\r")
123
+
124
+
125
+ def debug_log(message: str) -> None:
126
+ if DEBUG_LOGGING:
127
+ print(message, file=sys.stderr, flush=True)
128
+
129
+
130
+ def format_action_str(action_dict: Optional[dict[str, Any]]) -> str:
131
+ if not isinstance(action_dict, dict):
132
+ return "null"
133
+ action_type = str(action_dict.get("action_type") or "").strip() or "unknown"
134
+ params = action_dict.get("parameters", {})
135
+ if not isinstance(params, dict) or not params:
136
+ return f"{action_type}()"
137
+
138
+ parts: list[str] = []
139
+ for key in sorted(params):
140
+ value = params[key]
141
+ if value is None:
142
+ rendered = "null"
143
+ elif isinstance(value, bool):
144
+ rendered = str(value).lower()
145
+ elif isinstance(value, (int, float)):
146
+ rendered = str(value)
147
+ else:
148
+ text = str(value).replace("\\", "\\\\").replace("'", "\\'")
149
+ text = text.replace("\n", "\\n").replace("\r", "\\r")
150
+ rendered = f"'{text}'"
151
+ parts.append(f"{key}={rendered}")
152
+ return f"{action_type}({','.join(parts)})"
153
+
154
+
155
+ def load_episode_memory() -> list[dict[str, Any]]:
156
+ if not ENABLE_EPISODE_MEMORY or not os.path.exists(EPISODE_MEMORY_PATH):
157
+ return []
158
+ try:
159
+ with open(EPISODE_MEMORY_PATH, "r", encoding="utf-8") as handle:
160
+ payload = json.load(handle)
161
+ if isinstance(payload, list):
162
+ return [item for item in payload if isinstance(item, dict)]
163
+ except Exception as exc:
164
+ debug_log(f"[DEBUG] episode memory load failed: {exc}")
165
+ return []
166
+
167
+
168
+ def save_episode_memory(entries: list[dict[str, Any]]) -> None:
169
+ if not ENABLE_EPISODE_MEMORY:
170
+ return
171
+ try:
172
+ with open(EPISODE_MEMORY_PATH, "w", encoding="utf-8") as handle:
173
+ json.dump(entries[-EPISODE_MEMORY_LIMIT:], handle, ensure_ascii=True, indent=2)
174
+ except Exception as exc:
175
+ debug_log(f"[DEBUG] episode memory save failed: {exc}")
176
+
177
+
178
+ def summarize_episode_memory(entries: list[dict[str, Any]]) -> str:
179
+ if not ENABLE_EPISODE_MEMORY or not entries:
180
+ return ""
181
+ recent = entries[-min(3, len(entries)) :]
182
+ lines: list[str] = []
183
+ for item in recent:
184
+ lines.append(
185
+ f"- task={item.get('task_id')} scenario={item.get('scenario_id')} "
186
+ f"solved={str(bool(item.get('solved', False))).lower()} "
187
+ f"score={float(item.get('score', 0.0)):.2f} takeaway={item.get('takeaway', '')}"
188
+ )
189
+ return "\n".join(lines)
190
+
191
+
192
+ def record_episode_memory(
193
+ entries: list[dict[str, Any]],
194
+ task_name: str,
195
+ scenario_id: str | None,
196
+ solved: bool,
197
+ score: float,
198
+ history: list[str],
199
+ ) -> list[dict[str, Any]]:
200
+ if not ENABLE_EPISODE_MEMORY:
201
+ return entries
202
+ takeaway = ""
203
+ if solved:
204
+ takeaway = "Pattern solved successfully; repeat similar investigation and validation ordering."
205
+ elif history:
206
+ takeaway = "Recent attempt stayed partial; gather grounding evidence earlier and validate before submitting."
207
+ entry = {
208
+ "task_id": task_name,
209
+ "scenario_id": scenario_id or "unknown",
210
+ "solved": bool(solved),
211
+ "score": max(0.0, min(score, 1.0)),
212
+ "takeaway": takeaway,
213
+ "actions": history[-4:],
214
+ }
215
+ updated = entries + [entry]
216
+ return updated[-EPISODE_MEMORY_LIMIT:]
217
+
218
+
219
+ async def create_env() -> DeveloperControlRoomEnv:
220
+ if ENV_URL:
221
+ env = DeveloperControlRoomEnv(base_url=ENV_URL)
222
+ await env.connect()
223
+ return env
224
+ if not LOCAL_IMAGE_NAME:
225
+ raise ValueError("Set ENV_URL or LOCAL_IMAGE_NAME/IMAGE_NAME before running inference.py")
226
+ return await DeveloperControlRoomEnv.from_docker_image(LOCAL_IMAGE_NAME)
227
+
228
+
229
+ async def run_task(
230
+ client: OpenAI,
231
+ task_name: str,
232
+ memory_entries: list[dict[str, Any]],
233
+ scenario_index: int | None = None,
234
+ scenario_seed: int | None = None,
235
+ ) -> list[dict[str, Any]]:
236
+ env: DeveloperControlRoomEnv | None = None
237
+ history: List[str] = []
238
+ rewards: List[float] = []
239
+ steps_taken = 0
240
+ success = False
241
+ score = 0.0
242
+ scenario_id: str | None = None
243
+
244
+ log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
245
+
246
+ try:
247
+ env = await create_env()
248
+ reset_kwargs: dict[str, Any] = {"task_id": task_name}
249
+ if scenario_index is not None:
250
+ reset_kwargs["scenario_index"] = scenario_index
251
+ elif scenario_seed is not None:
252
+ reset_kwargs["seed"] = scenario_seed
253
+ result = await env.reset(**reset_kwargs)
254
+ observation = result.observation
255
+ scenario_id = observation.scenario_id
256
+ episode_memory = summarize_episode_memory(memory_entries)
257
+
258
+ for step in range(1, MAX_STEPS + 1):
259
+ if result.done:
260
+ break
261
+
262
+ action_dict: Optional[dict[str, Any]] = None
263
+ if step <= MAX_MODEL_STEPS:
264
+ action_dict = get_model_action(
265
+ client,
266
+ MODEL_NAME,
267
+ TEMPERATURE,
268
+ MAX_TOKENS,
269
+ MODEL_TIMEOUT_SECONDS,
270
+ step,
271
+ observation,
272
+ history,
273
+ episode_memory,
274
+ )
275
+ if not action_is_valid(action_dict, observation):
276
+ action_dict = fallback_action(task_name, observation)
277
+
278
+ action = build_action(action_dict)
279
+ result = await env.step(action)
280
+ observation = result.observation
281
+
282
+ reward = result.reward or 0.0
283
+ done = result.done
284
+ error = observation.last_action_error
285
+
286
+ rewards.append(reward)
287
+ steps_taken = step
288
+
289
+ log_step(
290
+ step=step,
291
+ action=format_action_str(action_dict),
292
+ reward=reward,
293
+ done=done,
294
+ error=error,
295
+ )
296
+
297
+ history.append(f"Step {step}: {format_action_str(action_dict)} -> reward {reward:+.2f}")
298
+
299
+ if done:
300
+ break
301
+
302
+ grader_result = fetch_grader_result(env, ENV_URL)
303
+ score = grader_result["total"]
304
+ success = grader_result["solved"]
305
+ except Exception as exc:
306
+ debug_log(f"[DEBUG] task run failed: {exc}")
307
+ success = False
308
+ score = 0.0
309
+
310
+ finally:
311
+ try:
312
+ if env is not None:
313
+ await env.close()
314
+ except Exception as exc:
315
+ debug_log(f"[DEBUG] env.close() error (container cleanup): {exc}")
316
+ log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
317
+ return record_episode_memory(memory_entries, task_name, scenario_id, success, score, history)
318
+
319
+
320
+ async def main() -> None:
321
+ client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
322
+ memory_entries = load_episode_memory()
323
+ tasks = list_tasks()
324
+ selected_tasks = [task for task in tasks if task["id"] == TASK_NAME] if TASK_NAME else tasks
325
+
326
+ for task_offset, task in enumerate(selected_tasks):
327
+ task_name = task["id"]
328
+ if RUN_ALL_SCENARIOS:
329
+ for scenario_index in range(task["scenarios"]):
330
+ scenario_seed = None if SCENARIO_SEED is None else SCENARIO_SEED + scenario_index + task_offset
331
+ memory_entries = await run_task(
332
+ client,
333
+ task_name,
334
+ memory_entries,
335
+ scenario_index=scenario_index,
336
+ scenario_seed=scenario_seed,
337
+ )
338
+ save_episode_memory(memory_entries)
339
+ continue
340
+
341
+ scenario_seed = None
342
+ if SCENARIO_INDEX is None and SCENARIO_SEED is not None:
343
+ scenario_seed = SCENARIO_SEED + task_offset
344
+
345
+ memory_entries = await run_task(
346
+ client,
347
+ task_name,
348
+ memory_entries,
349
+ scenario_index=SCENARIO_INDEX,
350
+ scenario_seed=scenario_seed,
351
+ )
352
+ save_episode_memory(memory_entries)
353
+
354
+
355
+ if __name__ == "__main__":
356
+ try:
357
+ asyncio.run(main())
358
+ except Exception as exc:
359
+ debug_log(f"[DEBUG] inference failed: {exc}")
360
+ raise SystemExit(1)
models.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed models for the Developer Control Room OpenEnv environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from openenv.core.env_server.types import Action, Observation, State
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ class ActionParameters(BaseModel):
12
+ """Flexible bag of action-specific parameters."""
13
+
14
+ query: str | None = None
15
+ path: str | None = None
16
+ asset: str | None = None
17
+ validator: str | None = None
18
+ content: str | None = None
19
+ root_cause: str | None = None
20
+ fix_path: str | None = None
21
+ verdict: str | None = None
22
+ issue_type: str | None = None
23
+ summary: str | None = None
24
+ draft_id: str | None = None
25
+
26
+ model_config = {"extra": "allow"}
27
+
28
+
29
+ class DeveloperControlRoomAction(Action):
30
+ """Action accepted by the environment."""
31
+
32
+ action_type: str = Field(..., description="Type of action to execute")
33
+ parameters: ActionParameters = Field(
34
+ default_factory=ActionParameters,
35
+ description="Action-specific parameters",
36
+ )
37
+
38
+
39
+ class DeveloperControlRoomObservation(Observation):
40
+ """Observation returned after reset and step."""
41
+
42
+ episode_id: str = Field(..., description="Unique episode identifier")
43
+ task_id: str = Field(..., description="Active task identifier")
44
+ scenario_id: str = Field(..., description="Scenario identifier")
45
+ step_count: int = Field(..., ge=0, description="Steps used in the episode")
46
+ max_steps: int = Field(..., ge=1, description="Maximum steps allowed")
47
+ developer_request: str = Field(..., description="Natural-language request")
48
+ workspace_summary: str = Field(..., description="High-level workspace context")
49
+ available_actions: list[str] = Field(
50
+ default_factory=list,
51
+ description="Valid actions for the current task",
52
+ )
53
+ known_files: list[str] = Field(
54
+ default_factory=list,
55
+ description="Readable workspace files",
56
+ )
57
+ editable_targets: list[str] = Field(
58
+ default_factory=list,
59
+ description="Files the agent may create or modify",
60
+ )
61
+ known_assets: list[str] = Field(
62
+ default_factory=list,
63
+ description="Schemas or logical assets visible to the agent",
64
+ )
65
+ available_validators: list[str] = Field(
66
+ default_factory=list,
67
+ description="Validators available for the current scenario",
68
+ )
69
+ queried_data: dict[str, Any] = Field(
70
+ default_factory=dict,
71
+ description="All tool responses gathered so far",
72
+ )
73
+ edited_files: dict[str, str] = Field(
74
+ default_factory=dict,
75
+ description="Current edited file contents",
76
+ )
77
+ validator_status: dict[str, dict[str, Any]] = Field(
78
+ default_factory=dict,
79
+ description="Validator pass/fail status accumulated so far",
80
+ )
81
+ cumulative_reward: float = Field(
82
+ default=0.0,
83
+ description="Running reward across the episode",
84
+ )
85
+ feedback: str = Field(default="", description="Per-step feedback")
86
+ last_action_error: str | None = Field(
87
+ default=None,
88
+ description="Error from the previous action, if any",
89
+ )
90
+
91
+
92
+ class DeveloperControlRoomState(State):
93
+ """Internal state returned by GET /state."""
94
+
95
+ task_id: str | None = Field(default=None, description="Current task identifier")
96
+ scenario_id: str | None = Field(
97
+ default=None,
98
+ description="Current scenario identifier",
99
+ )
100
+ max_steps: int = Field(default=0, ge=0, description="Maximum allowed steps")
101
+ developer_request: str = Field(default="", description="Request under evaluation")
102
+ available_actions: list[str] = Field(default_factory=list)
103
+ action_history: list[dict[str, Any]] = Field(default_factory=list)
104
+ queried_data: dict[str, Any] = Field(default_factory=dict)
105
+ edited_files: dict[str, str] = Field(default_factory=dict)
106
+ validator_status: dict[str, dict[str, Any]] = Field(default_factory=dict)
107
+ submission: dict[str, Any] = Field(default_factory=dict)
108
+ submitted: bool = Field(default=False)
109
+ cumulative_reward: float = Field(default=0.0)
110
+ done: bool = Field(default=False)
111
+ feedback: str = Field(default="")
112
+ last_action_error: str | None = Field(default=None)
my_env_v4.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Compatibility aliases for the provided inference template name."""
2
+
3
+ from client import DeveloperControlRoomEnv as MyEnvV4Env
4
+ from models import DeveloperControlRoomAction as MyEnvV4Action
5
+
6
+ __all__ = ["MyEnvV4Action", "MyEnvV4Env"]
openenv.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: developer_control_room
3
+ type: space
4
+ runtime: fastapi
5
+ app: server.app:app
6
+ port: 7860
7
+ description: >
8
+ OpenEnv benchmark for AI developer assistants operating in a simulated
9
+ data-platform workspace. Agents repair broken pipelines, review unsafe
10
+ LLM-generated patches, and synthesize reporting or data-product assets
11
+ from natural-language requests while respecting schema, governance, and
12
+ downstream contracts.
13
+ authors:
14
+ - name: Pranjal Parashar
15
+ license: MIT
16
+ tags:
17
+ - openenv
18
+ - developer-tools
19
+ - data-platform
20
+ - pipeline-ops
21
+ - llm-evaluation
22
+ - workflow-generation
23
+ tasks:
24
+ - id: repair_data_transform
25
+ name: "Task 1: Repair Data Transform"
26
+ difficulty: easy
27
+ max_steps: 8
28
+ score_range: [0.0, 1.0]
29
+ description: >
30
+ Repair a broken transform or dependency reference while keeping
31
+ downstream warehouse contracts stable.
32
+ - id: repair_pipeline_execution
33
+ name: "Task 2: Repair Pipeline Execution"
34
+ difficulty: easy
35
+ max_steps: 8
36
+ score_range: [0.0, 1.0]
37
+ description: >
38
+ Recover ingestion or orchestration failures caused by storage,
39
+ runner, or deploy-configuration drift.
40
+ - id: review_ai_patch_safety
41
+ name: "Task 3: Review AI Patch Safety"
42
+ difficulty: medium
43
+ max_steps: 8
44
+ score_range: [0.0, 1.0]
45
+ description: >
46
+ Review an AI-generated patch for privacy, governance, and operational
47
+ safety risks before it can be merged.
48
+ - id: review_ai_patch_correctness
49
+ name: "Task 4: Review AI Patch Correctness"
50
+ difficulty: medium
51
+ max_steps: 8
52
+ score_range: [0.0, 1.0]
53
+ description: >
54
+ Review an AI-generated patch for semantic correctness and compatibility
55
+ with published contracts.
56
+ - id: synthesize_reporting_asset
57
+ name: "Task 5: Synthesize Reporting Asset"
58
+ difficulty: hard
59
+ max_steps: 12
60
+ score_range: [0.0, 1.0]
61
+ description: >
62
+ Create reporting-facing views, contracts, and alerting artifacts that
63
+ are safe to operate in production.
64
+ - id: synthesize_data_product
65
+ name: "Task 6: Synthesize Data Product"
66
+ difficulty: hard
67
+ max_steps: 14
68
+ score_range: [0.0, 1.0]
69
+ description: >
70
+ Ship a production-grade workflow or mart by creating multiple artifacts,
71
+ validating them, and submitting a production-safe summary.
pyproject.toml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=45", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "openenv-developer_control_room"
7
+ version = "0.1.0"
8
+ description = "Developer Control Room benchmark for OpenEnv"
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ "openenv-core[core]>=0.2.2",
12
+ "openai>=1.52.0",
13
+ "requests>=2.32.0",
14
+ "python-dotenv>=1.0.1",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ dev = [
19
+ "pytest>=8.0.0",
20
+ "pytest-cov>=4.0.0",
21
+ ]
22
+
23
+ [project.scripts]
24
+ server = "developer_control_room.server.app:main"
25
+
26
+ [tool.setuptools]
27
+ include-package-data = true
28
+ packages = ["developer_control_room", "developer_control_room.server"]
29
+ package-dir = { "developer_control_room" = ".", "developer_control_room.server" = "server" }
server/Dockerfile ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Multi-stage build using openenv-base
8
+ # This Dockerfile is flexible and works for both:
9
+ # - In-repo environments (with local OpenEnv sources)
10
+ # - Standalone environments (with openenv from PyPI/Git)
11
+ # The build script (openenv build) handles context detection and sets appropriate build args.
12
+
13
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
14
+ FROM ${BASE_IMAGE} AS builder
15
+
16
+ WORKDIR /app
17
+
18
+ # Ensure git is available (required for installing dependencies from VCS)
19
+ RUN apt-get update && \
20
+ apt-get install -y --no-install-recommends git && \
21
+ rm -rf /var/lib/apt/lists/*
22
+
23
+ # Build argument to control whether we're building standalone or in-repo
24
+ ARG BUILD_MODE=in-repo
25
+ ARG ENV_NAME=developer_control_room
26
+
27
+ # Copy environment code (always at root of build context)
28
+ COPY . /app/env
29
+
30
+ # For in-repo builds, openenv is already vendored in the build context
31
+ # For standalone builds, openenv will be installed via pyproject.toml
32
+ WORKDIR /app/env
33
+
34
+ # Ensure uv is available (for local builds where base image lacks it)
35
+ RUN if ! command -v uv >/dev/null 2>&1; then \
36
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
37
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
38
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
39
+ fi
40
+
41
+ # Install dependencies using uv sync
42
+ # If uv.lock exists, use it; otherwise resolve on the fly
43
+ RUN --mount=type=cache,target=/root/.cache/uv \
44
+ if [ -f uv.lock ]; then \
45
+ uv sync --frozen --no-install-project --no-editable; \
46
+ else \
47
+ uv sync --no-install-project --no-editable; \
48
+ fi
49
+
50
+ RUN --mount=type=cache,target=/root/.cache/uv \
51
+ if [ -f uv.lock ]; then \
52
+ uv sync --frozen --no-editable; \
53
+ else \
54
+ uv sync --no-editable; \
55
+ fi
56
+
57
+ # Final runtime stage
58
+ FROM ${BASE_IMAGE}
59
+
60
+ WORKDIR /app
61
+
62
+ # Copy the virtual environment from builder
63
+ COPY --from=builder /app/env/.venv /app/.venv
64
+
65
+ # Copy the environment code
66
+ COPY --from=builder /app/env /app/env
67
+
68
+ # Set PATH to use the virtual environment
69
+ ENV PATH="/app/.venv/bin:$PATH"
70
+
71
+ # Set PYTHONPATH so imports work correctly
72
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
+
74
+ # Health check
75
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
76
+ CMD curl -f http://localhost:7860/health || exit 1
77
+
78
+ # Run the FastAPI server
79
+ # The module path is constructed to work with the /app/env structure
80
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 7860"]
server/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Developer Control Room environment server components."""
8
+
9
+ from .developer_control_room_environment import DeveloperControlRoomEnvironment
10
+
11
+ __all__ = ["DeveloperControlRoomEnvironment"]
server/app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI app for the Developer Control Room benchmark."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from fastapi import HTTPException
12
+
13
+ from openenv.core.env_server.web_interface import create_web_interface_app
14
+
15
+ try:
16
+ from ..graders import grade
17
+ from ..models import DeveloperControlRoomAction, DeveloperControlRoomObservation
18
+ from ..tasks import ALL_TASKS, list_tasks
19
+ from .developer_control_room_environment import DeveloperControlRoomEnvironment
20
+ from .ui import build_developer_control_room_ui
21
+ except ImportError:
22
+ from graders import grade
23
+ from models import DeveloperControlRoomAction, DeveloperControlRoomObservation
24
+ from tasks import ALL_TASKS, list_tasks
25
+ from server.developer_control_room_environment import DeveloperControlRoomEnvironment
26
+ from server.ui import build_developer_control_room_ui
27
+
28
+ ROOT = Path(__file__).resolve().parents[1]
29
+ ENV = DeveloperControlRoomEnvironment()
30
+
31
+
32
+ def _get_env() -> DeveloperControlRoomEnvironment:
33
+ return ENV
34
+
35
+
36
+ app = create_web_interface_app(
37
+ _get_env,
38
+ DeveloperControlRoomAction,
39
+ DeveloperControlRoomObservation,
40
+ env_name="developer_control_room",
41
+ max_concurrent_envs=1,
42
+ gradio_builder=build_developer_control_room_ui,
43
+ )
44
+
45
+
46
+ @app.get("/tasks")
47
+ def tasks() -> dict:
48
+ return {
49
+ "tasks": list_tasks(),
50
+ "total": len(ALL_TASKS),
51
+ "action_schema": {
52
+ "search_workspace": {"query": "string"},
53
+ "read_file": {"path": "string"},
54
+ "inspect_schema": {"asset": "string"},
55
+ "inspect_lineage": {"asset": "string"},
56
+ "inspect_llm_draft": {"draft_id": "string"},
57
+ "edit_file": {"path": "string", "content": "string"},
58
+ "run_validator": {"validator": "string"},
59
+ "submit_repair": {
60
+ "root_cause": "string",
61
+ "fix_path": "string",
62
+ "summary": "string",
63
+ },
64
+ "submit_review": {
65
+ "verdict": "approve|reject",
66
+ "issue_type": "string",
67
+ "summary": "string",
68
+ },
69
+ "submit_workspace": {"summary": "string"},
70
+ },
71
+ }
72
+
73
+
74
+ @app.get("/grader")
75
+ def grader() -> dict:
76
+ state = ENV.state.model_dump()
77
+ if not state.get("task_id"):
78
+ raise HTTPException(status_code=400, detail="No active episode. Call /reset first.")
79
+ result = grade(state["task_id"], state, ENV._scenario)
80
+ return {
81
+ "task_id": state["task_id"],
82
+ "scenario_id": state.get("scenario_id"),
83
+ "steps_used": state.get("step_count", 0),
84
+ "done": state.get("done", False),
85
+ "total": result["total"],
86
+ "solved": result.get("solved", False),
87
+ "breakdown": result["breakdown"],
88
+ "feedback": result["feedback"],
89
+ }
90
+
91
+
92
+ @app.post("/baseline")
93
+ def baseline() -> dict:
94
+ script = ROOT / "inference.py"
95
+ if not script.exists():
96
+ raise HTTPException(status_code=500, detail="inference.py not found")
97
+ env = {
98
+ **os.environ,
99
+ "ENV_URL": os.environ.get("ENV_URL", "http://localhost:7860"),
100
+ }
101
+ try:
102
+ result = subprocess.run(
103
+ [sys.executable, str(script)],
104
+ cwd=ROOT,
105
+ capture_output=True,
106
+ text=True,
107
+ timeout=1200,
108
+ env=env,
109
+ check=False,
110
+ )
111
+ except subprocess.TimeoutExpired as exc:
112
+ raise HTTPException(status_code=500, detail=f"inference.py timed out: {exc}") from exc
113
+
114
+ if result.returncode != 0:
115
+ raise HTTPException(
116
+ status_code=500,
117
+ detail={
118
+ "returncode": result.returncode,
119
+ "stdout_tail": result.stdout.splitlines()[-20:],
120
+ "stderr_tail": result.stderr.splitlines()[-20:],
121
+ },
122
+ )
123
+
124
+ return {
125
+ "status": "completed",
126
+ "stdout_tail": result.stdout.splitlines()[-20:],
127
+ "stderr_tail": result.stderr.splitlines()[-20:],
128
+ }
129
+
130
+
131
+ @app.get("/api/info")
132
+ def api_info() -> dict:
133
+ return {
134
+ "name": "developer_control_room",
135
+ "version": "0.1.0",
136
+ "description": "Developer workspace benchmark for OpenEnv",
137
+ "tasks": [task["id"] for task in list_tasks()],
138
+ "docs": "/docs",
139
+ }
140
+
141
+
142
+ def main(host: str = "0.0.0.0", port: int = 7860) -> None:
143
+ import uvicorn
144
+
145
+ uvicorn.run(app, host=host, port=port)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
server/developer_control_room_environment.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core environment implementation for Developer Control Room."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from uuid import uuid4
6
+
7
+ from openenv.core.env_server.interfaces import Environment
8
+ from openenv.core.env_server.types import EnvironmentMetadata
9
+
10
+ try:
11
+ from ..graders import evaluate_validator, grade
12
+ from ..models import (
13
+ DeveloperControlRoomAction,
14
+ DeveloperControlRoomObservation,
15
+ DeveloperControlRoomState,
16
+ )
17
+ from ..tasks import get_scenario, get_task, scenario_count
18
+ except ImportError:
19
+ from graders import evaluate_validator, grade
20
+ from models import (
21
+ DeveloperControlRoomAction,
22
+ DeveloperControlRoomObservation,
23
+ DeveloperControlRoomState,
24
+ )
25
+ from tasks import get_scenario, get_task, scenario_count
26
+
27
+
28
+ class DeveloperControlRoomEnvironment(
29
+ Environment[
30
+ DeveloperControlRoomAction,
31
+ DeveloperControlRoomObservation,
32
+ DeveloperControlRoomState,
33
+ ]
34
+ ):
35
+ """Singleton-friendly environment simulating a developer workspace."""
36
+
37
+ SUPPORTS_CONCURRENT_SESSIONS = False
38
+
39
+ def __init__(self) -> None:
40
+ self._task_def: dict = {}
41
+ self._scenario: dict = {}
42
+ self._state = DeveloperControlRoomState(
43
+ episode_id=str(uuid4()),
44
+ step_count=0,
45
+ task_id=None,
46
+ scenario_id=None,
47
+ )
48
+ self._ready = False
49
+
50
+ def reset(
51
+ self,
52
+ seed: int | None = None,
53
+ episode_id: str | None = None,
54
+ task_id: str = "repair_data_transform",
55
+ scenario_index: int | None = None,
56
+ **_: object,
57
+ ) -> DeveloperControlRoomObservation:
58
+ self._task_def = get_task(task_id)
59
+ if scenario_index is None:
60
+ scenario_index = (seed or 0) % scenario_count(task_id)
61
+ self._scenario = get_scenario(task_id, scenario_index, seed=seed)
62
+ self._state = DeveloperControlRoomState(
63
+ episode_id=episode_id or str(uuid4()),
64
+ step_count=0,
65
+ task_id=task_id,
66
+ scenario_id=self._scenario["scenario_id"],
67
+ max_steps=self._task_def["max_steps"],
68
+ developer_request=self._scenario["developer_request"],
69
+ available_actions=list(self._task_def["available_actions"]),
70
+ action_history=[],
71
+ queried_data={},
72
+ edited_files={},
73
+ validator_status={},
74
+ submission={},
75
+ submitted=False,
76
+ cumulative_reward=0.0,
77
+ done=False,
78
+ feedback="Episode started.",
79
+ last_action_error=None,
80
+ )
81
+ self._ready = True
82
+ return self._build_observation(reward=0.0, done=False)
83
+
84
+ def step(
85
+ self,
86
+ action: DeveloperControlRoomAction,
87
+ timeout_s: float | None = None,
88
+ **_: object,
89
+ ) -> DeveloperControlRoomObservation:
90
+ del timeout_s
91
+ if not self._ready:
92
+ raise RuntimeError("Call reset() before step().")
93
+
94
+ if self._state.done:
95
+ return self._build_observation(
96
+ reward=0.0,
97
+ done=True,
98
+ feedback="Episode already completed.",
99
+ )
100
+
101
+ before = grade(self._state.task_id or "", self._state.model_dump(), self._scenario)["total"]
102
+
103
+ self._state.step_count += 1
104
+ self._state.last_action_error = None
105
+ params = action.parameters
106
+ payload = params.model_dump(exclude_none=True)
107
+ self._state.action_history.append(
108
+ {
109
+ "step": self._state.step_count,
110
+ "action_type": action.action_type,
111
+ "parameters": payload,
112
+ }
113
+ )
114
+
115
+ reward = 0.0
116
+ feedback: list[str] = []
117
+ available = set(self._task_def.get("available_actions", []))
118
+ if action.action_type not in available:
119
+ reward -= 0.08
120
+ self._state.last_action_error = f"Action `{action.action_type}` is not available in this task."
121
+ feedback.append("invalid action")
122
+ else:
123
+ reward_delta, step_feedback = self._handle_action(action)
124
+ reward += reward_delta
125
+ if step_feedback:
126
+ feedback.append(step_feedback)
127
+
128
+ half = max(1, self._state.max_steps // 2)
129
+ if self._state.step_count > half and not self._state.submitted:
130
+ reward -= 0.01
131
+ feedback.append("late in episode")
132
+
133
+ if self._state.step_count >= self._state.max_steps and not self._state.done:
134
+ self._state.done = True
135
+ reward -= 0.1
136
+ feedback.append("max steps reached")
137
+
138
+ after_result = grade(self._state.task_id or "", self._state.model_dump(), self._scenario)
139
+ progress_delta = after_result["total"] - before
140
+ reward += progress_delta
141
+ self._state.cumulative_reward = round(self._state.cumulative_reward + reward, 4)
142
+ self._state.feedback = " | ".join(part for part in feedback if part) or after_result["feedback"]
143
+
144
+ return self._build_observation(
145
+ reward=round(reward, 4),
146
+ done=self._state.done,
147
+ feedback=self._state.feedback,
148
+ )
149
+
150
+ def _handle_action(self, action: DeveloperControlRoomAction) -> tuple[float, str]:
151
+ params = action.parameters
152
+ action_type = action.action_type
153
+ queried = self._state.queried_data
154
+
155
+ if action_type == "search_workspace":
156
+ query = (params.query or "").strip()
157
+ if not query:
158
+ self._state.last_action_error = "search_workspace requires `query`."
159
+ return -0.05, "missing query"
160
+ results = self._search_workspace(query)
161
+ query_map = queried.setdefault("search_workspace", {})
162
+ first_time = query not in query_map
163
+ query_map[query] = results
164
+ return (0.02 if first_time else -0.01), f"search returned {len(results)} results"
165
+
166
+ if action_type == "read_file":
167
+ path = (params.path or "").strip()
168
+ if not path:
169
+ self._state.last_action_error = "read_file requires `path`."
170
+ return -0.05, "missing path"
171
+ content = self._get_file(path)
172
+ if content is None:
173
+ self._state.last_action_error = f"Unknown file: {path}"
174
+ return -0.05, "unknown file"
175
+ file_map = queried.setdefault("read_file", {})
176
+ first_time = path not in file_map
177
+ file_map[path] = content
178
+ return (0.02 if first_time else -0.01), f"read {path}"
179
+
180
+ if action_type == "inspect_schema":
181
+ asset = (params.asset or "").strip()
182
+ schema = self._scenario.get("schema_registry", {}).get(asset)
183
+ if not asset or schema is None:
184
+ self._state.last_action_error = f"Unknown asset for inspect_schema: {asset or '<empty>'}"
185
+ return -0.05, "unknown asset"
186
+ schema_map = queried.setdefault("inspect_schema", {})
187
+ first_time = asset not in schema_map
188
+ schema_map[asset] = schema
189
+ return (0.03 if first_time else -0.01), f"inspected schema {asset}"
190
+
191
+ if action_type == "inspect_lineage":
192
+ asset = (params.asset or "").strip()
193
+ lineage = self._scenario.get("lineage", {}).get(asset)
194
+ if not asset or lineage is None:
195
+ self._state.last_action_error = f"Unknown asset for inspect_lineage: {asset or '<empty>'}"
196
+ return -0.05, "unknown lineage target"
197
+ lineage_map = queried.setdefault("inspect_lineage", {})
198
+ first_time = asset not in lineage_map
199
+ lineage_map[asset] = lineage
200
+ return (0.03 if first_time else -0.01), f"inspected lineage {asset}"
201
+
202
+ if action_type == "inspect_llm_draft":
203
+ draft_id = (params.draft_id or "primary").strip()
204
+ draft = self._scenario.get("llm_draft", {}).get(draft_id)
205
+ if draft is None:
206
+ self._state.last_action_error = f"Unknown draft id: {draft_id}"
207
+ return -0.05, "unknown draft"
208
+ draft_map = queried.setdefault("inspect_llm_draft", {})
209
+ first_time = draft_id not in draft_map
210
+ draft_map[draft_id] = draft
211
+ return (0.03 if first_time else -0.01), f"inspected draft {draft_id}"
212
+
213
+ if action_type == "edit_file":
214
+ path = (params.path or "").strip()
215
+ content = params.content or ""
216
+ if not path or not content.strip():
217
+ self._state.last_action_error = "edit_file requires `path` and non-empty `content`."
218
+ return -0.06, "invalid edit"
219
+ allowed = set(self._scenario.get("editable_targets", []))
220
+ if path not in allowed:
221
+ self._state.last_action_error = f"Editing `{path}` is not allowed in this scenario."
222
+ return -0.08, "forbidden edit target"
223
+ current = self._get_file(path) or ""
224
+ if current.strip() == content.strip():
225
+ return -0.03, f"no-op edit on {path}"
226
+ self._state.edited_files[path] = content
227
+ queried.setdefault("edit_file", {})[path] = {
228
+ "preview": content[:200],
229
+ "length": len(content),
230
+ }
231
+ return -0.01, f"edited {path}"
232
+
233
+ if action_type == "run_validator":
234
+ validator = (params.validator or "").strip()
235
+ if not validator:
236
+ self._state.last_action_error = "run_validator requires `validator`."
237
+ return -0.05, "missing validator"
238
+ result = evaluate_validator(self._state.task_id or "", validator, self._state.model_dump(), self._scenario)
239
+ first_time = validator not in self._state.validator_status
240
+ self._state.validator_status[validator] = result
241
+ queried.setdefault("run_validator", {})[validator] = result
242
+ bonus = 0.02 if first_time else -0.01
243
+ if result["passed"]:
244
+ bonus += 0.01
245
+ return bonus, f"{validator}: {'pass' if result['passed'] else 'fail'}"
246
+
247
+ if action_type == "submit_repair":
248
+ return self._submit(
249
+ action_type,
250
+ {
251
+ "root_cause": params.root_cause or "",
252
+ "fix_path": params.fix_path or "",
253
+ "summary": params.summary or "",
254
+ },
255
+ )
256
+
257
+ if action_type == "submit_review":
258
+ return self._submit(
259
+ action_type,
260
+ {
261
+ "verdict": params.verdict or "",
262
+ "issue_type": params.issue_type or "",
263
+ "summary": params.summary or "",
264
+ },
265
+ )
266
+
267
+ if action_type == "submit_workspace":
268
+ return self._submit(action_type, {"summary": params.summary or ""})
269
+
270
+ self._state.last_action_error = f"Unhandled action `{action_type}`"
271
+ return -0.08, "unhandled action"
272
+
273
+ def _submit(self, action_type: str, submission: dict[str, str]) -> tuple[float, str]:
274
+ expected = self._task_def.get("submission_action")
275
+ if action_type != expected:
276
+ self._state.last_action_error = f"Wrong submission action. Expected `{expected}`."
277
+ return -0.08, "wrong submission action"
278
+ self._state.submission = submission
279
+ self._state.submitted = True
280
+ self._state.done = True
281
+ return 0.02, f"submitted via {action_type}"
282
+
283
+ def _search_workspace(self, query: str) -> list[dict[str, str]]:
284
+ tokens = [_token for _token in query.lower().split() if _token]
285
+ matches: list[dict[str, str]] = []
286
+ files = {**self._scenario.get("files", {}), **self._state.edited_files}
287
+ for path, content in files.items():
288
+ haystack = f"{path}\n{content}".lower()
289
+ if all(token in haystack for token in tokens):
290
+ snippet = " ".join(content.strip().split())[:180]
291
+ matches.append({"path": path, "snippet": snippet})
292
+ for asset, content in self._scenario.get("schema_registry", {}).items():
293
+ haystack = f"{asset}\n{content}".lower()
294
+ if all(token in haystack for token in tokens):
295
+ snippet = " ".join(content.strip().split())[:180]
296
+ matches.append({"path": f"schema::{asset}", "snippet": snippet})
297
+ return matches[:5]
298
+
299
+ def _get_file(self, path: str) -> str | None:
300
+ if path in self._state.edited_files:
301
+ return self._state.edited_files[path]
302
+ if path in self._scenario.get("files", {}):
303
+ return self._scenario["files"][path]
304
+ if path in self._scenario.get("editable_targets", []):
305
+ return "File does not exist yet. Create it with edit_file."
306
+ return None
307
+
308
+ def _build_observation(
309
+ self,
310
+ reward: float,
311
+ done: bool,
312
+ feedback: str | None = None,
313
+ ) -> DeveloperControlRoomObservation:
314
+ return DeveloperControlRoomObservation(
315
+ episode_id=self._state.episode_id or "",
316
+ task_id=self._state.task_id or "",
317
+ scenario_id=self._state.scenario_id or "",
318
+ step_count=self._state.step_count,
319
+ max_steps=self._state.max_steps,
320
+ developer_request=self._scenario.get("developer_request", ""),
321
+ workspace_summary=self._scenario.get("workspace_summary", ""),
322
+ available_actions=list(self._task_def.get("available_actions", [])),
323
+ known_files=list(self._scenario.get("known_files", [])),
324
+ editable_targets=list(self._scenario.get("editable_targets", [])),
325
+ known_assets=list(self._scenario.get("known_assets", [])),
326
+ available_validators=list(self._scenario.get("available_validators", [])),
327
+ queried_data=self._state.queried_data,
328
+ edited_files=self._state.edited_files,
329
+ validator_status=self._state.validator_status,
330
+ cumulative_reward=self._state.cumulative_reward,
331
+ feedback=feedback or self._state.feedback,
332
+ last_action_error=self._state.last_action_error,
333
+ reward=reward,
334
+ done=done,
335
+ )
336
+
337
+ @property
338
+ def state(self) -> DeveloperControlRoomState:
339
+ if not self._ready:
340
+ return self._state
341
+ return self._state
342
+
343
+ def get_metadata(self) -> EnvironmentMetadata:
344
+ return EnvironmentMetadata(
345
+ name="developer_control_room",
346
+ description=(
347
+ "OpenEnv benchmark for AI developer assistants working on "
348
+ "pipeline repair, LLM patch review, and workflow shipping."
349
+ ),
350
+ version="0.1.0",
351
+ author="Codex",
352
+ )
353
+
354
+ def close(self) -> None:
355
+ """No-op because the app uses a singleton environment instance."""
server/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openenv-core[core]>=0.2.2
2
+ fastapi>=0.115.0
3
+ uvicorn>=0.24.0
4
+ openai>=1.52.0
5
+ requests>=2.32.0
6
+ python-dotenv>=1.0.1
server/ui.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom Gradio UI for the Developer Control Room Space."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ import gradio as gr
9
+
10
+
11
+ def _pretty_json(payload: Dict[str, Any]) -> str:
12
+ return json.dumps(payload, indent=2, ensure_ascii=False)
13
+
14
+
15
+ def _safe_json(text: str) -> Dict[str, Any]:
16
+ text = (text or "").strip()
17
+ if not text:
18
+ return {}
19
+ return json.loads(text)
20
+
21
+
22
+ def build_developer_control_room_ui(
23
+ web_manager: Any,
24
+ action_fields: List[Dict[str, Any]],
25
+ metadata: Optional[Any],
26
+ is_chat_env: bool,
27
+ title: str = "Developer Control Room",
28
+ quick_start_md: Optional[str] = None,
29
+ ) -> gr.Blocks:
30
+ del action_fields, is_chat_env
31
+
32
+ display_title = metadata.name if metadata and getattr(metadata, "name", None) else title
33
+
34
+ css = """
35
+ :root {
36
+ --bg: #09111f;
37
+ --bg-2: #0f1728;
38
+ --surface: rgba(14, 23, 39, 0.62);
39
+ --surface-strong: rgba(17, 24, 39, 0.88);
40
+ --line: rgba(148, 163, 184, 0.18);
41
+ --text: #eef4ff;
42
+ --muted: #9db0c7;
43
+ --cyan: #6ee7f9;
44
+ --blue: #60a5fa;
45
+ --coral: #fb7185;
46
+ --glow: rgba(110, 231, 249, 0.18);
47
+ }
48
+ body, .gradio-container {
49
+ background:
50
+ radial-gradient(circle at 15% 20%, rgba(96, 165, 250, 0.18), transparent 28%),
51
+ radial-gradient(circle at 85% 12%, rgba(251, 113, 133, 0.16), transparent 24%),
52
+ linear-gradient(180deg, var(--bg), var(--bg-2)) !important;
53
+ color: var(--text);
54
+ }
55
+ .gradio-container { max-width: 1400px !important; padding-top: 18px !important; }
56
+ .dcr-hero {
57
+ padding: 28px 30px 18px 30px;
58
+ border: 1px solid var(--line);
59
+ border-radius: 28px;
60
+ background: linear-gradient(135deg, rgba(15, 23, 40, 0.92), rgba(12, 18, 31, 0.72));
61
+ box-shadow: 0 20px 80px rgba(0, 0, 0, 0.28);
62
+ backdrop-filter: blur(14px);
63
+ margin-bottom: 18px;
64
+ }
65
+ .dcr-kicker {
66
+ display: inline-flex;
67
+ gap: 10px;
68
+ align-items: center;
69
+ color: var(--cyan);
70
+ font-size: 12px;
71
+ letter-spacing: 0.22em;
72
+ text-transform: uppercase;
73
+ margin-bottom: 12px;
74
+ }
75
+ .dcr-title {
76
+ font-size: 42px;
77
+ line-height: 1.02;
78
+ font-weight: 760;
79
+ letter-spacing: -0.03em;
80
+ margin: 0;
81
+ }
82
+ .dcr-subtitle {
83
+ max-width: 760px;
84
+ color: var(--muted);
85
+ margin-top: 12px;
86
+ font-size: 16px;
87
+ line-height: 1.65;
88
+ }
89
+ .dcr-panel {
90
+ background: var(--surface);
91
+ border: 1px solid var(--line);
92
+ border-radius: 24px;
93
+ padding: 18px 18px 10px 18px;
94
+ backdrop-filter: blur(10px);
95
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.03);
96
+ }
97
+ .dcr-panel-title {
98
+ font-size: 13px;
99
+ text-transform: uppercase;
100
+ letter-spacing: 0.16em;
101
+ color: var(--cyan);
102
+ margin-bottom: 8px;
103
+ }
104
+ .dcr-side-note {
105
+ color: var(--muted);
106
+ font-size: 13px;
107
+ line-height: 1.6;
108
+ margin-top: 4px;
109
+ margin-bottom: 10px;
110
+ }
111
+ .dcr-status {
112
+ padding: 14px 16px;
113
+ border-radius: 18px;
114
+ background: rgba(96, 165, 250, 0.09);
115
+ border: 1px solid rgba(96, 165, 250, 0.16);
116
+ }
117
+ .dcr-chip-row {
118
+ display: flex;
119
+ flex-wrap: wrap;
120
+ gap: 10px;
121
+ justify-content: flex-end;
122
+ }
123
+ .dcr-chip {
124
+ display: inline-block;
125
+ padding: 6px 12px;
126
+ border-radius: 999px;
127
+ border: 1px solid var(--line);
128
+ background: rgba(255, 255, 255, 0.04);
129
+ color: var(--text);
130
+ font-size: 12px;
131
+ }
132
+ .dcr-chip strong { color: var(--cyan); font-weight: 600; }
133
+ .dcr-btn-primary button {
134
+ background: linear-gradient(135deg, var(--cyan), var(--blue));
135
+ border: none !important;
136
+ color: #06111f !important;
137
+ font-weight: 700;
138
+ box-shadow: 0 10px 30px var(--glow);
139
+ }
140
+ .dcr-btn-secondary button {
141
+ background: rgba(255, 255, 255, 0.03) !important;
142
+ border: 1px solid var(--line) !important;
143
+ color: var(--text) !important;
144
+ }
145
+ .dcr-btn-secondary button:hover,
146
+ .dcr-btn-primary button:hover {
147
+ filter: brightness(1.05);
148
+ }
149
+ .dcr-json, .dcr-json textarea, .dcr-json pre {
150
+ font-size: 12px !important;
151
+ }
152
+ .block, .gr-group, .gr-box, .gr-panel {
153
+ border-radius: 20px !important;
154
+ }
155
+ """
156
+
157
+ async def reset_env(task_id: str, scenario_index: int):
158
+ try:
159
+ data = await web_manager.reset_environment(
160
+ {"task_id": task_id, "scenario_index": scenario_index}
161
+ )
162
+ return (
163
+ _pretty_json(data.get("observation", {})),
164
+ _pretty_json(data),
165
+ "Reset complete.",
166
+ )
167
+ except Exception as exc:
168
+ return ("", "", f"Reset error: {exc}")
169
+
170
+ async def step_env(action_type: str, params_json: str):
171
+ try:
172
+ parameters = _safe_json(params_json)
173
+ except Exception as exc:
174
+ return ("", "", f"Invalid JSON: {exc}")
175
+
176
+ payload = {"action_type": action_type, "parameters": parameters}
177
+ try:
178
+ data = await web_manager.step_environment(payload)
179
+ return (
180
+ _pretty_json(data.get("observation", {})),
181
+ _pretty_json(data),
182
+ "Step complete.",
183
+ )
184
+ except Exception as exc:
185
+ return ("", "", f"Step error: {exc}")
186
+
187
+ def get_state_sync():
188
+ try:
189
+ return _pretty_json(web_manager.get_state())
190
+ except Exception as exc:
191
+ return f"State error: {exc}"
192
+
193
+ with gr.Blocks(title=display_title) as demo:
194
+ gr.HTML(f"<style>{css}</style>")
195
+ gr.HTML(
196
+ f"""
197
+ <section class="dcr-hero">
198
+ <div class="dcr-kicker">Control Room / OpenEnv / Interactive Workspace</div>
199
+ <div class="dcr-title">{display_title}</div>
200
+ <div class="dcr-subtitle">
201
+ Explore pipeline repair, LLM patch review, and workflow shipping in one live environment.
202
+ Same page, cleaner flow, better atmosphere.
203
+ </div>
204
+ </section>
205
+ """
206
+ )
207
+
208
+ with gr.Row():
209
+ with gr.Column(scale=3):
210
+ gr.HTML("<div class='dcr-chip-row'><span class='dcr-chip'><strong>Port</strong> 7860</span><span class='dcr-chip'><strong>Mode</strong> Single-page UI</span></div>")
211
+ with gr.Group(elem_classes="dcr-panel"):
212
+ gr.HTML("<div class='dcr-panel-title'>Scenario Control</div>")
213
+ gr.HTML("<div class='dcr-side-note'>Pick a task, reset the episode, then drive the env with direct JSON actions.</div>")
214
+ task_id = gr.Dropdown(
215
+ choices=["pipeline_repair", "llm_patch_review", "workflow_shipping"],
216
+ value="pipeline_repair",
217
+ label="Task",
218
+ )
219
+ scenario_index = gr.Number(value=0, label="Scenario Index", precision=0)
220
+ reset_btn = gr.Button("Reset Episode", elem_classes="dcr-btn-secondary")
221
+
222
+ with gr.Group(elem_classes="dcr-panel"):
223
+ gr.HTML("<div class='dcr-panel-title'>Action Composer</div>")
224
+ gr.HTML("<div class='dcr-side-note'>Use exact action names and JSON params. This is intentionally close to the raw benchmark surface.</div>")
225
+ action_type = gr.Dropdown(
226
+ choices=[
227
+ "search_workspace",
228
+ "read_file",
229
+ "inspect_schema",
230
+ "inspect_lineage",
231
+ "inspect_llm_draft",
232
+ "edit_file",
233
+ "run_validator",
234
+ "submit_repair",
235
+ "submit_review",
236
+ "submit_workspace",
237
+ ],
238
+ value="read_file",
239
+ label="Action Type",
240
+ )
241
+ params_json = gr.Code(
242
+ value='{"path":"transforms/orders_daily.sql"}',
243
+ label="Action Parameters (JSON)",
244
+ language="json",
245
+ elem_classes="dcr-json",
246
+ )
247
+ with gr.Row():
248
+ step_btn = gr.Button("Send Action", elem_classes="dcr-btn-primary")
249
+ state_btn = gr.Button("Get State", elem_classes="dcr-btn-secondary")
250
+
251
+ with gr.Group(elem_classes="dcr-status"):
252
+ status = gr.Textbox(label="Status", interactive=False, container=False)
253
+
254
+ with gr.Column(scale=4):
255
+ with gr.Group(elem_classes="dcr-panel"):
256
+ gr.HTML("<div class='dcr-panel-title'>Observation</div>")
257
+ obs_display = gr.Code(label="Observation", language="json", value="")
258
+ with gr.Group(elem_classes="dcr-panel"):
259
+ gr.HTML("<div class='dcr-panel-title'>Raw JSON</div>")
260
+ raw_json = gr.Code(label="Raw Response", language="json", value="")
261
+ if quick_start_md:
262
+ with gr.Group(elem_classes="dcr-panel"):
263
+ gr.HTML("<div class='dcr-panel-title'>Quick Start</div>")
264
+ gr.Markdown(quick_start_md)
265
+
266
+ reset_btn.click(
267
+ fn=reset_env,
268
+ inputs=[task_id, scenario_index],
269
+ outputs=[obs_display, raw_json, status],
270
+ )
271
+ step_btn.click(
272
+ fn=step_env,
273
+ inputs=[action_type, params_json],
274
+ outputs=[obs_display, raw_json, status],
275
+ )
276
+ state_btn.click(
277
+ fn=get_state_sync,
278
+ outputs=[raw_json],
279
+ )
280
+
281
+ return demo
tasks.py ADDED
@@ -0,0 +1,2494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task and scenario definitions for the Developer Control Room benchmark."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+
7
+
8
+ def repair_validator(
9
+ description: str,
10
+ path: str,
11
+ required_groups: list[list[str]] | None = None,
12
+ forbidden_terms: list[str] | None = None,
13
+ ) -> dict:
14
+ return {
15
+ "description": description,
16
+ "kind": "file_groups",
17
+ "path": path,
18
+ "required_groups": required_groups or [],
19
+ "forbidden_terms": forbidden_terms or [],
20
+ }
21
+
22
+
23
+ def review_validator(
24
+ description: str,
25
+ draft_id: str,
26
+ required_groups: list[list[str]] | None = None,
27
+ forbidden_terms: list[str] | None = None,
28
+ ) -> dict:
29
+ return {
30
+ "description": description,
31
+ "kind": "draft_groups",
32
+ "draft_id": draft_id,
33
+ "required_groups": required_groups or [],
34
+ "forbidden_terms": forbidden_terms or [],
35
+ }
36
+
37
+
38
+ def workflow_validator(
39
+ description: str,
40
+ artifact: str,
41
+ ) -> dict:
42
+ return {
43
+ "description": description,
44
+ "kind": "workflow_artifact",
45
+ "artifact": artifact,
46
+ }
47
+
48
+
49
+ def repair_scenario(
50
+ scenario_id: str,
51
+ developer_request: str,
52
+ workspace_summary: str,
53
+ known_files: list[str],
54
+ editable_targets: list[str],
55
+ known_assets: list[str],
56
+ available_validators: list[str],
57
+ files: dict[str, str],
58
+ schema_registry: dict[str, str],
59
+ repair_target: dict,
60
+ validators: dict[str, dict],
61
+ lineage: dict[str, str] | None = None,
62
+ ) -> dict:
63
+ return {
64
+ "scenario_id": scenario_id,
65
+ "developer_request": developer_request,
66
+ "workspace_summary": workspace_summary,
67
+ "known_files": known_files,
68
+ "editable_targets": editable_targets,
69
+ "known_assets": known_assets,
70
+ "available_validators": available_validators,
71
+ "files": files,
72
+ "schema_registry": schema_registry,
73
+ "lineage": lineage or {},
74
+ "llm_draft": {},
75
+ "repair_target": repair_target,
76
+ "validators": validators,
77
+ }
78
+
79
+
80
+ def review_scenario(
81
+ scenario_id: str,
82
+ developer_request: str,
83
+ workspace_summary: str,
84
+ known_files: list[str],
85
+ known_assets: list[str],
86
+ available_validators: list[str],
87
+ files: dict[str, str],
88
+ schema_registry: dict[str, str],
89
+ llm_draft: dict[str, str],
90
+ review_target: dict,
91
+ validators: dict[str, dict],
92
+ ) -> dict:
93
+ return {
94
+ "scenario_id": scenario_id,
95
+ "developer_request": developer_request,
96
+ "workspace_summary": workspace_summary,
97
+ "known_files": known_files,
98
+ "editable_targets": [],
99
+ "known_assets": known_assets,
100
+ "available_validators": available_validators,
101
+ "files": files,
102
+ "schema_registry": schema_registry,
103
+ "lineage": {},
104
+ "llm_draft": llm_draft,
105
+ "review_target": review_target,
106
+ "validators": validators,
107
+ }
108
+
109
+
110
+ def workflow_artifact(
111
+ path: str,
112
+ required_groups: list[list[str]],
113
+ weight: float,
114
+ forbidden_terms: list[str] | None = None,
115
+ ) -> dict:
116
+ return {
117
+ "path": path,
118
+ "required_groups": required_groups,
119
+ "forbidden_terms": forbidden_terms or [],
120
+ "weight": weight,
121
+ }
122
+
123
+
124
+ def workflow_scenario(
125
+ scenario_id: str,
126
+ developer_request: str,
127
+ workspace_summary: str,
128
+ known_files: list[str],
129
+ editable_targets: list[str],
130
+ known_assets: list[str],
131
+ available_validators: list[str],
132
+ files: dict[str, str],
133
+ schema_registry: dict[str, str],
134
+ workflow_target: dict,
135
+ validators: dict[str, dict],
136
+ lineage: dict[str, str] | None = None,
137
+ llm_draft: dict[str, str] | None = None,
138
+ ) -> dict:
139
+ return {
140
+ "scenario_id": scenario_id,
141
+ "developer_request": developer_request,
142
+ "workspace_summary": workspace_summary,
143
+ "known_files": known_files,
144
+ "editable_targets": editable_targets,
145
+ "known_assets": known_assets,
146
+ "available_validators": available_validators,
147
+ "files": files,
148
+ "schema_registry": schema_registry,
149
+ "lineage": lineage or {},
150
+ "llm_draft": llm_draft or {},
151
+ "workflow_target": workflow_target,
152
+ "validators": validators,
153
+ }
154
+
155
+
156
+ TASK_DEFINITIONS: dict[str, dict] = {
157
+ "repair_data_transform": {
158
+ "id": "repair_data_transform",
159
+ "name": "Task 1: Repair Data Transform",
160
+ "difficulty": "easy",
161
+ "max_steps": 8,
162
+ "score_range": [0.0, 1.0],
163
+ "description": (
164
+ "Repair transform logic or dependency wiring while keeping downstream "
165
+ "warehouse contracts stable."
166
+ ),
167
+ "available_actions": [
168
+ "search_workspace",
169
+ "read_file",
170
+ "inspect_schema",
171
+ "run_validator",
172
+ "edit_file",
173
+ "submit_repair",
174
+ ],
175
+ "submission_action": "submit_repair",
176
+ "grader_family": "repair",
177
+ "scenario_ids": ["PR-001", "PR-004"],
178
+ },
179
+ "repair_pipeline_execution": {
180
+ "id": "repair_pipeline_execution",
181
+ "name": "Task 2: Repair Pipeline Execution",
182
+ "difficulty": "easy",
183
+ "max_steps": 8,
184
+ "score_range": [0.0, 1.0],
185
+ "description": (
186
+ "Recover ingestion or orchestration failures caused by storage layout, "
187
+ "runner, or deploy-configuration drift."
188
+ ),
189
+ "available_actions": [
190
+ "search_workspace",
191
+ "read_file",
192
+ "inspect_schema",
193
+ "run_validator",
194
+ "edit_file",
195
+ "submit_repair",
196
+ ],
197
+ "submission_action": "submit_repair",
198
+ "grader_family": "repair",
199
+ "scenario_ids": ["PR-002", "PR-003", "PR-005", "PR-006", "PR-007", "PR-008"],
200
+ },
201
+ "review_ai_patch_safety": {
202
+ "id": "review_ai_patch_safety",
203
+ "name": "Task 3: Review AI Patch Safety",
204
+ "difficulty": "medium",
205
+ "max_steps": 8,
206
+ "score_range": [0.0, 1.0],
207
+ "description": (
208
+ "Review AI-generated changes for governance, privacy, and operational "
209
+ "safety risks before they reach production."
210
+ ),
211
+ "available_actions": [
212
+ "search_workspace",
213
+ "read_file",
214
+ "inspect_schema",
215
+ "inspect_llm_draft",
216
+ "run_validator",
217
+ "submit_review",
218
+ ],
219
+ "submission_action": "submit_review",
220
+ "grader_family": "review",
221
+ "scenario_ids": ["LR-001", "LR-004"],
222
+ },
223
+ "review_ai_patch_correctness": {
224
+ "id": "review_ai_patch_correctness",
225
+ "name": "Task 4: Review AI Patch Correctness",
226
+ "difficulty": "medium",
227
+ "max_steps": 8,
228
+ "score_range": [0.0, 1.0],
229
+ "description": (
230
+ "Review AI-generated changes for semantic correctness and compatibility "
231
+ "with published warehouse contracts."
232
+ ),
233
+ "available_actions": [
234
+ "search_workspace",
235
+ "read_file",
236
+ "inspect_schema",
237
+ "inspect_llm_draft",
238
+ "run_validator",
239
+ "submit_review",
240
+ ],
241
+ "submission_action": "submit_review",
242
+ "grader_family": "review",
243
+ "scenario_ids": ["LR-002", "LR-003"],
244
+ },
245
+ "synthesize_reporting_asset": {
246
+ "id": "synthesize_reporting_asset",
247
+ "name": "Task 5: Synthesize Reporting Asset",
248
+ "difficulty": "hard",
249
+ "max_steps": 12,
250
+ "score_range": [0.0, 1.0],
251
+ "description": (
252
+ "Create reporting-facing assets such as views, contracts, and alerts "
253
+ "that are ready for production use."
254
+ ),
255
+ "available_actions": [
256
+ "search_workspace",
257
+ "read_file",
258
+ "inspect_schema",
259
+ "inspect_lineage",
260
+ "inspect_llm_draft",
261
+ "edit_file",
262
+ "run_validator",
263
+ "submit_workspace",
264
+ ],
265
+ "submission_action": "submit_workspace",
266
+ "grader_family": "workflow",
267
+ "scenario_ids": ["WS-002", "WS-004"],
268
+ },
269
+ "synthesize_data_product": {
270
+ "id": "synthesize_data_product",
271
+ "name": "Task 6: Synthesize Data Product",
272
+ "difficulty": "hard",
273
+ "max_steps": 14,
274
+ "score_range": [0.0, 1.0],
275
+ "description": (
276
+ "Create production-grade data products with pipeline metadata, SQL, "
277
+ "checks, contracts, and governance-safe outputs."
278
+ ),
279
+ "available_actions": [
280
+ "search_workspace",
281
+ "read_file",
282
+ "inspect_schema",
283
+ "inspect_lineage",
284
+ "inspect_llm_draft",
285
+ "edit_file",
286
+ "run_validator",
287
+ "submit_workspace",
288
+ ],
289
+ "submission_action": "submit_workspace",
290
+ "grader_family": "workflow",
291
+ "scenario_ids": ["WS-001", "WS-003"],
292
+ },
293
+ }
294
+
295
+ ALL_TASKS = TASK_DEFINITIONS
296
+
297
+
298
+ SCENARIOS: dict[str, list[dict]] = {
299
+ "pipeline_repair": [
300
+ repair_scenario(
301
+ scenario_id="PR-001",
302
+ developer_request=(
303
+ "The nightly `orders_daily` build started failing after an upstream "
304
+ "change. Repair the workspace so the job compiles again, but keep "
305
+ "the published contract stable for downstream dashboards."
306
+ ),
307
+ workspace_summary=(
308
+ "This repo keeps transform logic in `transforms/`, job configs in "
309
+ "`pipelines/`, and published contracts in `schemas/`. Validators "
310
+ "`sql_compile` and `contract_guard` are available."
311
+ ),
312
+ known_files=[
313
+ "pipelines/orders_daily.yaml",
314
+ "transforms/orders_daily.sql",
315
+ "schemas/orders_daily.json",
316
+ "docs/pipeline_conventions.md",
317
+ ],
318
+ editable_targets=["transforms/orders_daily.sql"],
319
+ known_assets=["raw.orders_events", "dim.customers", "orders_daily"],
320
+ available_validators=["sql_compile", "contract_guard"],
321
+ files={
322
+ "pipelines/orders_daily.yaml": """name: orders_daily
323
+ schedule: "0 2 * * *"
324
+ owner: analytics-platform
325
+ sources:
326
+ - raw.orders_events
327
+ - dim.customers
328
+ target: orders_daily
329
+ contract: schemas/orders_daily.json
330
+ """,
331
+ "transforms/orders_daily.sql": """with base as (
332
+ select
333
+ o.order_id,
334
+ o.customer_id,
335
+ o.event_ts as order_ts,
336
+ date(o.event_ts) as order_date,
337
+ o.amount_cents / 100.0 as total_amount
338
+ from raw.orders_events o
339
+ where o.status = 'completed'
340
+ )
341
+ select * from base;
342
+ """,
343
+ "schemas/orders_daily.json": """{
344
+ "name": "orders_daily",
345
+ "columns": [
346
+ {"name": "order_id", "type": "string"},
347
+ {"name": "customer_id", "type": "string"},
348
+ {"name": "order_ts", "type": "timestamp"},
349
+ {"name": "order_date", "type": "date"},
350
+ {"name": "total_amount", "type": "float"}
351
+ ]
352
+ }
353
+ """,
354
+ "docs/pipeline_conventions.md": """# Pipeline conventions
355
+
356
+ - Keep published column names stable when upstream systems rename fields.
357
+ - Prefer aliasing upstream renames inside SQL rather than changing the contract.
358
+ - `sql_compile` fails on unresolved columns.
359
+ """,
360
+ },
361
+ schema_registry={
362
+ "raw.orders_events": """asset: raw.orders_events
363
+ columns:
364
+ - order_id: string
365
+ - customer_id: string
366
+ - event_time: timestamp
367
+ - amount_cents: bigint
368
+ - status: string
369
+ notes:
370
+ - Column `event_ts` was renamed to `event_time` in the latest ingestion deploy.
371
+ """,
372
+ "dim.customers": """asset: dim.customers
373
+ columns:
374
+ - customer_id: string
375
+ - segment: string
376
+ """,
377
+ "orders_daily": """asset: orders_daily
378
+ published_columns:
379
+ - order_id
380
+ - customer_id
381
+ - order_ts
382
+ - order_date
383
+ - total_amount
384
+ """,
385
+ },
386
+ repair_target={
387
+ "path": "transforms/orders_daily.sql",
388
+ "required_groups": [["event_time"], ["as order_ts"], ["order_date"]],
389
+ "forbidden_terms": ["event_ts"],
390
+ "root_cause_groups": [["schema", "column"], ["event_ts"], ["event_time", "rename"]],
391
+ "summary_groups": [["order_ts", "contract"], ["event_time"], ["orders_daily"]],
392
+ "fix_path": "transforms/orders_daily.sql",
393
+ "investigation_targets": [
394
+ ("read_file", "transforms/orders_daily.sql"),
395
+ ("inspect_schema", "raw.orders_events"),
396
+ ("run_validator", "sql_compile"),
397
+ ],
398
+ },
399
+ validators={
400
+ "sql_compile": repair_validator(
401
+ "Checks unresolved columns in the SQL transform.",
402
+ "transforms/orders_daily.sql",
403
+ required_groups=[["event_time"], ["as order_ts"]],
404
+ forbidden_terms=["event_ts"],
405
+ ),
406
+ "contract_guard": repair_validator(
407
+ "Confirms the output contract still publishes `order_ts`.",
408
+ "transforms/orders_daily.sql",
409
+ required_groups=[["as order_ts"], ["order_date"]],
410
+ ),
411
+ },
412
+ ),
413
+ repair_scenario(
414
+ scenario_id="PR-002",
415
+ developer_request=(
416
+ "The `customer_events_ingest` job started failing after the data lake "
417
+ "team changed the ADLS folder convention. Repair the config without "
418
+ "renaming the target dataset."
419
+ ),
420
+ workspace_summary=(
421
+ "Landing-zone jobs read from ADLS paths declared in `pipelines/`. "
422
+ "Validators `path_resolver` and `target_guard` are available."
423
+ ),
424
+ known_files=[
425
+ "pipelines/customer_events_ingest.yaml",
426
+ "schemas/customer_events_raw.json",
427
+ "docs/storage_layout.md",
428
+ ],
429
+ editable_targets=["pipelines/customer_events_ingest.yaml"],
430
+ known_assets=["landing.customer_events", "customer_events_raw"],
431
+ available_validators=["path_resolver", "target_guard"],
432
+ files={
433
+ "pipelines/customer_events_ingest.yaml": """name: customer_events_ingest
434
+ schedule: "0 * * * *"
435
+ owner: ingestion-platform
436
+ source_path: "abfss://bronze@datalake.dfs.core.windows.net/customer-events/date={{ ds }}/"
437
+ format: parquet
438
+ target: customer_events_raw
439
+ """,
440
+ "schemas/customer_events_raw.json": """{
441
+ "name": "customer_events_raw",
442
+ "columns": [
443
+ {"name": "event_id", "type": "string"},
444
+ {"name": "customer_id", "type": "string"},
445
+ {"name": "event_type", "type": "string"},
446
+ {"name": "event_ts", "type": "timestamp"}
447
+ ]
448
+ }
449
+ """,
450
+ "docs/storage_layout.md": """# Storage layout
451
+
452
+ - Customer events now land under `customer-events/v2/`.
453
+ - Daily partitions use `dt={{ ds }}` instead of `date={{ ds }}`.
454
+ - Downstream dataset names must stay unchanged across ingestion path migrations.
455
+ """,
456
+ },
457
+ schema_registry={
458
+ "landing.customer_events": """asset: landing.customer_events
459
+ location:
460
+ abfss://bronze@datalake.dfs.core.windows.net/customer-events/v2/dt={{ ds }}/
461
+ format: parquet
462
+ """,
463
+ "customer_events_raw": """asset: customer_events_raw
464
+ published_columns:
465
+ - event_id
466
+ - customer_id
467
+ - event_type
468
+ - event_ts
469
+ """,
470
+ },
471
+ repair_target={
472
+ "path": "pipelines/customer_events_ingest.yaml",
473
+ "required_groups": [["customer-events/v2"], ["dt={{ ds }}", "dt={ds}"], ["target: customer_events_raw"]],
474
+ "forbidden_terms": ["date={{ ds }}"],
475
+ "root_cause_groups": [["path", "folder", "partition"], ["date"], ["dt"]],
476
+ "summary_groups": [["customer-events/v2"], ["customer_events_raw"]],
477
+ "fix_path": "pipelines/customer_events_ingest.yaml",
478
+ "investigation_targets": [
479
+ ("read_file", "pipelines/customer_events_ingest.yaml"),
480
+ ("read_file", "docs/storage_layout.md"),
481
+ ("run_validator", "path_resolver"),
482
+ ],
483
+ },
484
+ validators={
485
+ "path_resolver": repair_validator(
486
+ "Checks that the ADLS path uses the new folder and partition layout.",
487
+ "pipelines/customer_events_ingest.yaml",
488
+ required_groups=[["customer-events/v2"], ["dt={{ ds }}", "dt={ds}"]],
489
+ forbidden_terms=["date={{ ds }}"],
490
+ ),
491
+ "target_guard": repair_validator(
492
+ "Confirms the target dataset stays stable during the repair.",
493
+ "pipelines/customer_events_ingest.yaml",
494
+ required_groups=[["target: customer_events_raw"]],
495
+ ),
496
+ },
497
+ ),
498
+ repair_scenario(
499
+ scenario_id="PR-003",
500
+ developer_request=(
501
+ "The Jenkins release job for `orders_daily` started failing after a CI "
502
+ "cleanup. Fix the job definition so it invokes the packaged runner again."
503
+ ),
504
+ workspace_summary=(
505
+ "CI jobs are declared in `ci/jenkins/`. Validators `jenkins_lint` and "
506
+ "`runner_guard` are available."
507
+ ),
508
+ known_files=[
509
+ "ci/jenkins/orders_daily.groovy",
510
+ "docs/ci_conventions.md",
511
+ "scripts/run_orders_daily.sh",
512
+ ],
513
+ editable_targets=["ci/jenkins/orders_daily.groovy"],
514
+ known_assets=["ci.orders_daily", "artifact.orders_daily"],
515
+ available_validators=["jenkins_lint", "runner_guard"],
516
+ files={
517
+ "ci/jenkins/orders_daily.groovy": """pipeline {
518
+ agent any
519
+ stages {
520
+ stage('Run') {
521
+ steps {
522
+ sh './scripts/run-orders-daily.sh'
523
+ }
524
+ }
525
+ }
526
+ }
527
+ """,
528
+ "docs/ci_conventions.md": """# CI conventions
529
+
530
+ - Release jobs call the packaged runner script under `./scripts/`.
531
+ - Script names use underscores, not hyphens.
532
+ - Jobs should execute `./scripts/run_orders_daily.sh` for the orders_daily release.
533
+ """,
534
+ "scripts/run_orders_daily.sh": """#!/usr/bin/env bash
535
+ set -euo pipefail
536
+ echo "running orders daily"
537
+ """,
538
+ },
539
+ schema_registry={
540
+ "ci.orders_daily": """asset: ci.orders_daily
541
+ expected_runner:
542
+ ./scripts/run_orders_daily.sh
543
+ """,
544
+ "artifact.orders_daily": """asset: artifact.orders_daily
545
+ package:
546
+ orders_daily.tar.gz
547
+ """,
548
+ },
549
+ repair_target={
550
+ "path": "ci/jenkins/orders_daily.groovy",
551
+ "required_groups": [["./scripts/run_orders_daily.sh"]],
552
+ "forbidden_terms": ["run-orders-daily.sh"],
553
+ "root_cause_groups": [["jenkins", "ci"], ["script", "runner"], ["hyphen", "path", "name"]],
554
+ "summary_groups": [["run_orders_daily.sh"], ["jenkins", "runner"]],
555
+ "fix_path": "ci/jenkins/orders_daily.groovy",
556
+ "investigation_targets": [
557
+ ("read_file", "ci/jenkins/orders_daily.groovy"),
558
+ ("read_file", "docs/ci_conventions.md"),
559
+ ("run_validator", "jenkins_lint"),
560
+ ],
561
+ },
562
+ validators={
563
+ "jenkins_lint": repair_validator(
564
+ "Checks that the Jenkins job points at an existing runner script.",
565
+ "ci/jenkins/orders_daily.groovy",
566
+ required_groups=[["./scripts/run_orders_daily.sh"]],
567
+ forbidden_terms=["run-orders-daily.sh"],
568
+ ),
569
+ "runner_guard": repair_validator(
570
+ "Confirms the repair still uses the packaged runner convention.",
571
+ "ci/jenkins/orders_daily.groovy",
572
+ required_groups=[["sh"], ["./scripts/run_orders_daily.sh"]],
573
+ ),
574
+ },
575
+ ),
576
+ repair_scenario(
577
+ scenario_id="PR-004",
578
+ developer_request=(
579
+ "The `revenue_dashboard_refresh` job is stale because its upstream "
580
+ "dependency was renamed incorrectly during a rollout. Repair the "
581
+ "dependency wiring so the dashboard refreshes again."
582
+ ),
583
+ workspace_summary=(
584
+ "Downstream jobs declare upstreams in pipeline YAML. Validators "
585
+ "`dependency_guard` and `freshness_guard` are available."
586
+ ),
587
+ known_files=[
588
+ "pipelines/revenue_dashboard_refresh.yaml",
589
+ "pipelines/orders_daily.yaml",
590
+ "docs/lineage_notes.md",
591
+ ],
592
+ editable_targets=["pipelines/revenue_dashboard_refresh.yaml"],
593
+ known_assets=["orders_daily", "orders_daily_v2", "revenue_dashboard_refresh"],
594
+ available_validators=["dependency_guard", "freshness_guard"],
595
+ files={
596
+ "pipelines/revenue_dashboard_refresh.yaml": """name: revenue_dashboard_refresh
597
+ schedule: "0 5 * * *"
598
+ owner: finance-analytics
599
+ sources:
600
+ - orders_daily_v2
601
+ target: revenue_dashboard_refresh
602
+ """,
603
+ "pipelines/orders_daily.yaml": """name: orders_daily
604
+ schedule: "0 2 * * *"
605
+ target: orders_daily
606
+ """,
607
+ "docs/lineage_notes.md": """# Lineage notes
608
+
609
+ - The rollout created a temporary `orders_daily_v2` alias, but the canonical
610
+ upstream for production dashboards remains `orders_daily`.
611
+ - Downstream jobs should depend on canonical dataset names after the rollback.
612
+ """,
613
+ },
614
+ schema_registry={
615
+ "orders_daily": """asset: orders_daily
616
+ freshness_sla: 3h
617
+ status: healthy
618
+ """,
619
+ "orders_daily_v2": """asset: orders_daily_v2
620
+ status: deprecated_alias
621
+ """,
622
+ "revenue_dashboard_refresh": """asset: revenue_dashboard_refresh
623
+ depends_on:
624
+ - orders_daily
625
+ """,
626
+ },
627
+ repair_target={
628
+ "path": "pipelines/revenue_dashboard_refresh.yaml",
629
+ "required_groups": [["orders_daily"], ["target: revenue_dashboard_refresh"]],
630
+ "forbidden_terms": ["orders_daily_v2"],
631
+ "root_cause_groups": [["upstream", "dependency", "stale"], ["orders_daily_v2"], ["orders_daily", "canonical"]],
632
+ "summary_groups": [["orders_daily"], ["revenue_dashboard_refresh"], ["deprecated", "alias"]],
633
+ "fix_path": "pipelines/revenue_dashboard_refresh.yaml",
634
+ "investigation_targets": [
635
+ ("read_file", "pipelines/revenue_dashboard_refresh.yaml"),
636
+ ("read_file", "docs/lineage_notes.md"),
637
+ ("run_validator", "dependency_guard"),
638
+ ],
639
+ },
640
+ validators={
641
+ "dependency_guard": repair_validator(
642
+ "Checks that the pipeline points at the canonical upstream dataset.",
643
+ "pipelines/revenue_dashboard_refresh.yaml",
644
+ required_groups=[["orders_daily"]],
645
+ forbidden_terms=["orders_daily_v2"],
646
+ ),
647
+ "freshness_guard": repair_validator(
648
+ "Confirms the dashboard target remains unchanged after the dependency fix.",
649
+ "pipelines/revenue_dashboard_refresh.yaml",
650
+ required_groups=[["target: revenue_dashboard_refresh"]],
651
+ ),
652
+ },
653
+ ),
654
+ repair_scenario(
655
+ scenario_id="PR-005",
656
+ developer_request=(
657
+ "The reporting release deploy started failing after a config cleanup. "
658
+ "Repair the deploy definition so it passes the expected warehouse "
659
+ "role to the packaged release runner again."
660
+ ),
661
+ workspace_summary=(
662
+ "Release definitions live under `deploy/`. Validators `deploy_lint` "
663
+ "and `role_guard` are available."
664
+ ),
665
+ known_files=[
666
+ "deploy/reporting_release.yaml",
667
+ "docs/deploy_runbook.md",
668
+ "scripts/release_reporting_asset.sh",
669
+ ],
670
+ editable_targets=["deploy/reporting_release.yaml"],
671
+ known_assets=["deploy.reporting_release", "warehouse.reporting_release"],
672
+ available_validators=["deploy_lint", "role_guard"],
673
+ files={
674
+ "deploy/reporting_release.yaml": """job: reporting_release
675
+ runner_image: reporting-release:latest
676
+ script: ./scripts/release_reporting_asset.sh
677
+ env:
678
+ WAREHOUSE_ROLE: analytics_writer
679
+ ALERT_ROUTE: finance-reporting
680
+ """,
681
+ "docs/deploy_runbook.md": """# Reporting release runbook
682
+
683
+ - Reporting releases execute `./scripts/release_reporting_asset.sh`.
684
+ - Production deploys must pass `TARGET_WAREHOUSE_ROLE`.
685
+ - The reporting release role remains `analytics_writer`.
686
+ """,
687
+ "scripts/release_reporting_asset.sh": """#!/usr/bin/env bash
688
+ set -euo pipefail
689
+ echo "releasing reporting asset"
690
+ """,
691
+ },
692
+ schema_registry={
693
+ "deploy.reporting_release": """asset: deploy.reporting_release
694
+ expected_script:
695
+ ./scripts/release_reporting_asset.sh
696
+ required_env:
697
+ TARGET_WAREHOUSE_ROLE
698
+ """,
699
+ "warehouse.reporting_release": """asset: warehouse.reporting_release
700
+ role: analytics_writer
701
+ """,
702
+ },
703
+ repair_target={
704
+ "path": "deploy/reporting_release.yaml",
705
+ "required_groups": [
706
+ ["TARGET_WAREHOUSE_ROLE"],
707
+ ["analytics_writer"],
708
+ ["./scripts/release_reporting_asset.sh"],
709
+ ],
710
+ "forbidden_terms": ["\nenv:\n WAREHOUSE_ROLE:"],
711
+ "root_cause_groups": [
712
+ ["deploy", "release"],
713
+ ["env", "environment", "variable"],
714
+ ["target_warehouse_role", "warehouse_role"],
715
+ ],
716
+ "summary_groups": [["TARGET_WAREHOUSE_ROLE"], ["analytics_writer"], ["release"]],
717
+ "fix_path": "deploy/reporting_release.yaml",
718
+ "investigation_targets": [
719
+ ("read_file", "deploy/reporting_release.yaml"),
720
+ ("read_file", "docs/deploy_runbook.md"),
721
+ ("read_file", "scripts/release_reporting_asset.sh"),
722
+ ("run_validator", "deploy_lint"),
723
+ ],
724
+ },
725
+ validators={
726
+ "deploy_lint": repair_validator(
727
+ "Checks that the release job uses the correct release script and env key.",
728
+ "deploy/reporting_release.yaml",
729
+ required_groups=[["./scripts/release_reporting_asset.sh"], ["TARGET_WAREHOUSE_ROLE"]],
730
+ forbidden_terms=["\nenv:\n WAREHOUSE_ROLE:"],
731
+ ),
732
+ "role_guard": repair_validator(
733
+ "Confirms the release config still deploys with the analytics_writer role.",
734
+ "deploy/reporting_release.yaml",
735
+ required_groups=[["TARGET_WAREHOUSE_ROLE"], ["analytics_writer"]],
736
+ ),
737
+ },
738
+ ),
739
+ repair_scenario(
740
+ scenario_id="PR-006",
741
+ developer_request=(
742
+ "The `customer_profile_import` batch started failing during load. The "
743
+ "CSV still lands successfully, but the warehouse insert now errors "
744
+ "because the incoming identifier shape no longer matches the target "
745
+ "table contract. Repair the load mapping."
746
+ ),
747
+ workspace_summary=(
748
+ "Batch loads stage CSVs in `samples/` and warehouse load SQL lives in "
749
+ "`transforms/`. Validators `type_alignment_guard` and "
750
+ "`load_contract_guard` are available."
751
+ ),
752
+ known_files=[
753
+ "transforms/customer_profile_import.sql",
754
+ "samples/customer_profile_import.csv",
755
+ "schemas/customer_profile_dim.json",
756
+ "docs/load_contracts.md",
757
+ ],
758
+ editable_targets=["transforms/customer_profile_import.sql"],
759
+ known_assets=["customer_profile_stage", "customer_profile_dim"],
760
+ available_validators=["type_alignment_guard", "load_contract_guard"],
761
+ files={
762
+ "transforms/customer_profile_import.sql": """insert into customer_profile_dim (
763
+ customer_code,
764
+ loyalty_tier,
765
+ state_code
766
+ )
767
+ select
768
+ cast(s.customer_code as integer) as customer_code,
769
+ s.loyalty_tier,
770
+ s.state_code
771
+ from customer_profile_stage s;
772
+ """,
773
+ "samples/customer_profile_import.csv": """customer_code,loyalty_tier,state_code
774
+ 000123,GOLD,CA
775
+ 000124,SILVER,WA
776
+ """,
777
+ "schemas/customer_profile_dim.json": """{
778
+ "name": "customer_profile_dim",
779
+ "columns": [
780
+ {"name": "customer_code", "type": "string"},
781
+ {"name": "loyalty_tier", "type": "string"},
782
+ {"name": "state_code", "type": "string"}
783
+ ]
784
+ }
785
+ """,
786
+ "docs/load_contracts.md": """# Load contracts
787
+
788
+ - `customer_code` remains a string identifier because leading zeroes are significant.
789
+ - Batch imports may receive numeric-looking identifiers in CSV files, but warehouse
790
+ inserts must preserve the original string representation.
791
+ """,
792
+ },
793
+ schema_registry={
794
+ "customer_profile_stage": """asset: customer_profile_stage
795
+ columns:
796
+ - customer_code: string
797
+ - loyalty_tier: string
798
+ - state_code: string
799
+ """,
800
+ "customer_profile_dim": """asset: customer_profile_dim
801
+ published_columns:
802
+ - customer_code:string
803
+ - loyalty_tier:string
804
+ - state_code:string
805
+ """,
806
+ },
807
+ repair_target={
808
+ "path": "transforms/customer_profile_import.sql",
809
+ "required_groups": [
810
+ ["insert into customer_profile_dim"],
811
+ ["customer_code"],
812
+ ["s.customer_code"],
813
+ ],
814
+ "forbidden_terms": ["cast(s.customer_code as integer)", "::integer", "as integer) as customer_code"],
815
+ "root_cause_groups": [
816
+ ["customer_code"],
817
+ ["string", "varchar", "text"],
818
+ ["cast", "integer", "type mismatch"],
819
+ ],
820
+ "summary_groups": [["customer_code"], ["string", "leading zero"], ["load", "mapping"]],
821
+ "fix_path": "transforms/customer_profile_import.sql",
822
+ "investigation_targets": [
823
+ ("read_file", "transforms/customer_profile_import.sql"),
824
+ ("read_file", "samples/customer_profile_import.csv"),
825
+ ("read_file", "docs/load_contracts.md"),
826
+ ("read_file", "schemas/customer_profile_dim.json"),
827
+ ],
828
+ },
829
+ validators={
830
+ "type_alignment_guard": repair_validator(
831
+ "Checks that the load no longer casts customer_code to integer.",
832
+ "transforms/customer_profile_import.sql",
833
+ required_groups=[["s.customer_code"]],
834
+ forbidden_terms=["cast(s.customer_code as integer)", "::integer"],
835
+ ),
836
+ "load_contract_guard": repair_validator(
837
+ "Checks that the warehouse insert still targets the published string contract.",
838
+ "transforms/customer_profile_import.sql",
839
+ required_groups=[["customer_profile_dim"], ["customer_code"], ["loyalty_tier"], ["state_code"]],
840
+ ),
841
+ },
842
+ ),
843
+ repair_scenario(
844
+ scenario_id="PR-007",
845
+ developer_request=(
846
+ "The `orders_archive_load` job is failing because the new CSV extract "
847
+ "only ships 6 columns, while the archive table now has 12 columns. "
848
+ "Repair the load configuration so the archive ingest succeeds again."
849
+ ),
850
+ workspace_summary=(
851
+ "Archive loads map source columns in YAML and rely on default values "
852
+ "for warehouse-only metadata fields. Validators `column_mapping_guard` "
853
+ "and `archive_defaults_guard` are available."
854
+ ),
855
+ known_files=[
856
+ "pipelines/orders_archive_load.yaml",
857
+ "samples/orders_archive_extract.csv",
858
+ "schemas/orders_archive.json",
859
+ "docs/archive_load_guide.md",
860
+ ],
861
+ editable_targets=["pipelines/orders_archive_load.yaml"],
862
+ known_assets=["orders_archive_stage", "orders_archive"],
863
+ available_validators=["column_mapping_guard", "archive_defaults_guard"],
864
+ files={
865
+ "pipelines/orders_archive_load.yaml": """job: orders_archive_load
866
+ target_table: orders_archive
867
+ source_columns:
868
+ - order_id
869
+ - customer_id
870
+ - order_ts
871
+ - order_status
872
+ - gross_amount_usd
873
+ - currency_code
874
+ defaults: {}
875
+ """,
876
+ "samples/orders_archive_extract.csv": """order_id,customer_id,order_ts,order_status,gross_amount_usd,currency_code
877
+ o-1001,c-11,2026-04-01T02:00:00Z,completed,129.0,USD
878
+ """,
879
+ "schemas/orders_archive.json": """{
880
+ "name": "orders_archive",
881
+ "columns": [
882
+ {"name": "order_id", "type": "string"},
883
+ {"name": "customer_id", "type": "string"},
884
+ {"name": "order_ts", "type": "timestamp"},
885
+ {"name": "order_status", "type": "string"},
886
+ {"name": "gross_amount_usd", "type": "float"},
887
+ {"name": "currency_code", "type": "string"},
888
+ {"name": "ingest_source", "type": "string"},
889
+ {"name": "ingest_batch_id", "type": "string"},
890
+ {"name": "created_at", "type": "timestamp"},
891
+ {"name": "updated_at", "type": "timestamp"},
892
+ {"name": "archive_status", "type": "string"},
893
+ {"name": "notes", "type": "string"}
894
+ ]
895
+ }
896
+ """,
897
+ "docs/archive_load_guide.md": """# Archive load guide
898
+
899
+ - The extract only supplies 6 business columns.
900
+ - Warehouse-only fields must be populated through deterministic defaults:
901
+ - ingest_source: csv_archive
902
+ - ingest_batch_id: current_batch_id
903
+ - created_at: current_timestamp
904
+ - updated_at: current_timestamp
905
+ - archive_status: active
906
+ - notes: ''
907
+ """,
908
+ },
909
+ schema_registry={
910
+ "orders_archive_stage": """asset: orders_archive_stage
911
+ extract_columns:
912
+ - order_id
913
+ - customer_id
914
+ - order_ts
915
+ - order_status
916
+ - gross_amount_usd
917
+ - currency_code
918
+ """,
919
+ "orders_archive": """asset: orders_archive
920
+ required_columns: 12
921
+ warehouse_default_columns:
922
+ - ingest_source
923
+ - ingest_batch_id
924
+ - created_at
925
+ - updated_at
926
+ - archive_status
927
+ - notes
928
+ """,
929
+ },
930
+ repair_target={
931
+ "path": "pipelines/orders_archive_load.yaml",
932
+ "required_groups": [
933
+ ["order_id"],
934
+ ["customer_id"],
935
+ ["order_ts"],
936
+ ["order_status"],
937
+ ["gross_amount_usd"],
938
+ ["currency_code"],
939
+ ["ingest_source: csv_archive"],
940
+ ["ingest_batch_id: current_batch_id"],
941
+ ["created_at: current_timestamp"],
942
+ ["updated_at: current_timestamp"],
943
+ ["archive_status: active"],
944
+ ["notes: ''", "notes: \"\""],
945
+ ],
946
+ "forbidden_terms": ["defaults: {}"],
947
+ "root_cause_groups": [
948
+ ["6", "six"],
949
+ ["12", "twelve"],
950
+ ["columns", "mapping"],
951
+ ],
952
+ "summary_groups": [["defaults"], ["12", "columns"], ["archive"], ["metadata"]],
953
+ "fix_path": "pipelines/orders_archive_load.yaml",
954
+ "investigation_targets": [
955
+ ("read_file", "pipelines/orders_archive_load.yaml"),
956
+ ("read_file", "schemas/orders_archive.json"),
957
+ ("read_file", "docs/archive_load_guide.md"),
958
+ ("read_file", "samples/orders_archive_extract.csv"),
959
+ ],
960
+ },
961
+ validators={
962
+ "column_mapping_guard": repair_validator(
963
+ "Checks that the archive load maps the 6 source columns and 6 deterministic defaults.",
964
+ "pipelines/orders_archive_load.yaml",
965
+ required_groups=[
966
+ ["order_id"],
967
+ ["customer_id"],
968
+ ["order_ts"],
969
+ ["order_status"],
970
+ ["gross_amount_usd"],
971
+ ["currency_code"],
972
+ ["ingest_source: csv_archive"],
973
+ ["ingest_batch_id: current_batch_id"],
974
+ ],
975
+ forbidden_terms=["defaults: {}"],
976
+ ),
977
+ "archive_defaults_guard": repair_validator(
978
+ "Checks that archive-only metadata fields are populated with stable defaults.",
979
+ "pipelines/orders_archive_load.yaml",
980
+ required_groups=[
981
+ ["created_at: current_timestamp"],
982
+ ["updated_at: current_timestamp"],
983
+ ["archive_status: active"],
984
+ ["notes: ''", "notes: \"\""],
985
+ ],
986
+ ),
987
+ },
988
+ ),
989
+ repair_scenario(
990
+ scenario_id="PR-008",
991
+ developer_request=(
992
+ "The `dim_customer_merge` load started failing with a primary key "
993
+ "violation after duplicate rows appeared in the incoming batch. "
994
+ "Repair the merge strategy so the load is safe again."
995
+ ),
996
+ workspace_summary=(
997
+ "Dimension merges are implemented in SQL and should deduplicate the "
998
+ "incoming batch before writing to the warehouse table. Validators "
999
+ "`pk_uniqueness_guard` and `merge_strategy_guard` are available."
1000
+ ),
1001
+ known_files=[
1002
+ "transforms/dim_customer_merge.sql",
1003
+ "samples/dim_customer_delta.csv",
1004
+ "schemas/dim_customer.json",
1005
+ "docs/merge_strategy.md",
1006
+ ],
1007
+ editable_targets=["transforms/dim_customer_merge.sql"],
1008
+ known_assets=["dim_customer_delta", "dim_customer"],
1009
+ available_validators=["pk_uniqueness_guard", "merge_strategy_guard"],
1010
+ files={
1011
+ "transforms/dim_customer_merge.sql": """insert into dim_customer (
1012
+ customer_id,
1013
+ customer_name,
1014
+ state_code,
1015
+ updated_at
1016
+ )
1017
+ select
1018
+ d.customer_id,
1019
+ d.customer_name,
1020
+ d.state_code,
1021
+ d.updated_at
1022
+ from dim_customer_delta d;
1023
+ """,
1024
+ "samples/dim_customer_delta.csv": """customer_id,customer_name,state_code,updated_at
1025
+ c-1,Ada Smith,CA,2026-04-01T10:00:00Z
1026
+ c-1,Ada Smith,CA,2026-04-01T10:05:00Z
1027
+ """,
1028
+ "schemas/dim_customer.json": """{
1029
+ "name": "dim_customer",
1030
+ "primary_key": ["customer_id"],
1031
+ "columns": [
1032
+ {"name": "customer_id", "type": "string"},
1033
+ {"name": "customer_name", "type": "string"},
1034
+ {"name": "state_code", "type": "string"},
1035
+ {"name": "updated_at", "type": "timestamp"}
1036
+ ]
1037
+ }
1038
+ """,
1039
+ "docs/merge_strategy.md": """# Merge strategy
1040
+
1041
+ - Incoming dimension batches may contain duplicate customer_id rows.
1042
+ - Deduplicate the stage with `row_number()` and keep the latest `updated_at`.
1043
+ - Use `merge` or `insert ... where not exists` semantics; never blindly insert the full batch.
1044
+ """,
1045
+ },
1046
+ schema_registry={
1047
+ "dim_customer_delta": """asset: dim_customer_delta
1048
+ possible_duplicates:
1049
+ primary_key: customer_id
1050
+ """,
1051
+ "dim_customer": """asset: dim_customer
1052
+ primary_key:
1053
+ - customer_id
1054
+ """,
1055
+ },
1056
+ repair_target={
1057
+ "path": "transforms/dim_customer_merge.sql",
1058
+ "required_groups": [
1059
+ ["row_number()"],
1060
+ ["partition by customer_id"],
1061
+ ["order by d.updated_at desc", "order by updated_at desc"],
1062
+ ["where rn = 1", "where deduped.rn = 1"],
1063
+ ],
1064
+ "forbidden_terms": [],
1065
+ "root_cause_groups": [
1066
+ ["primary key", "pk"],
1067
+ ["duplicate", "duplicates"],
1068
+ ["deduplicate", "row_number", "merge"],
1069
+ ],
1070
+ "summary_groups": [["primary key"], ["deduplicate", "latest"], ["merge", "load"]],
1071
+ "fix_path": "transforms/dim_customer_merge.sql",
1072
+ "investigation_targets": [
1073
+ ("read_file", "transforms/dim_customer_merge.sql"),
1074
+ ("read_file", "samples/dim_customer_delta.csv"),
1075
+ ("read_file", "schemas/dim_customer.json"),
1076
+ ("read_file", "docs/merge_strategy.md"),
1077
+ ],
1078
+ },
1079
+ validators={
1080
+ "pk_uniqueness_guard": repair_validator(
1081
+ "Checks that the merge SQL deduplicates customer_id rows before writing.",
1082
+ "transforms/dim_customer_merge.sql",
1083
+ required_groups=[
1084
+ ["row_number()"],
1085
+ ["partition by customer_id"],
1086
+ ["where rn = 1", "where deduped.rn = 1"],
1087
+ ],
1088
+ ),
1089
+ "merge_strategy_guard": repair_validator(
1090
+ "Checks that the merge keeps the latest updated_at row instead of blindly inserting duplicates.",
1091
+ "transforms/dim_customer_merge.sql",
1092
+ required_groups=[
1093
+ ["order by d.updated_at desc", "order by updated_at desc"],
1094
+ ["insert into dim_customer", "merge into dim_customer"],
1095
+ ],
1096
+ ),
1097
+ },
1098
+ ),
1099
+ ],
1100
+ "llm_patch_review": [
1101
+ review_scenario(
1102
+ scenario_id="LR-001",
1103
+ developer_request=(
1104
+ "Review the AI-generated patch for `payments_enriched` and decide if "
1105
+ "it is safe to merge into production analytics."
1106
+ ),
1107
+ workspace_summary=(
1108
+ "Company policy forbids exposing direct identifiers in analytics "
1109
+ "outputs. The patch file in `drafts/` contains the assistant's "
1110
+ "proposed change."
1111
+ ),
1112
+ known_files=[
1113
+ "transforms/payments_enriched.sql",
1114
+ "schemas/payments_enriched.json",
1115
+ "policies/data_governance.md",
1116
+ "drafts/payments_enriched.patch",
1117
+ ],
1118
+ known_assets=["payments_raw", "customer_dim", "payments_enriched"],
1119
+ available_validators=["privacy_guard", "contract_guard"],
1120
+ files={
1121
+ "transforms/payments_enriched.sql": """select
1122
+ p.payment_id,
1123
+ p.customer_id,
1124
+ p.amount_usd,
1125
+ p.payment_status,
1126
+ p.processed_at
1127
+ from payments_raw p;
1128
+ """,
1129
+ "schemas/payments_enriched.json": """{
1130
+ "name": "payments_enriched",
1131
+ "columns": [
1132
+ {"name": "payment_id", "type": "string"},
1133
+ {"name": "customer_id", "type": "string"},
1134
+ {"name": "amount_usd", "type": "float"},
1135
+ {"name": "payment_status", "type": "string"},
1136
+ {"name": "processed_at", "type": "timestamp"}
1137
+ ]
1138
+ }
1139
+ """,
1140
+ "policies/data_governance.md": """# Data governance
1141
+
1142
+ - Analytics outputs must not expose `customer_email`, `phone`, or `full_name`.
1143
+ - Direct identifiers are only allowed in operational systems, not shared marts.
1144
+ - Schema changes to published datasets require explicit approval.
1145
+ """,
1146
+ "drafts/payments_enriched.patch": """diff --git a/transforms/payments_enriched.sql b/transforms/payments_enriched.sql
1147
+ @@
1148
+ select
1149
+ p.payment_id,
1150
+ p.customer_id,
1151
+ + c.customer_email,
1152
+ p.amount_usd,
1153
+ p.payment_status,
1154
+ p.processed_at
1155
+ from payments_raw p
1156
+ +left join customer_dim c on p.customer_id = c.customer_id;
1157
+
1158
+ diff --git a/schemas/payments_enriched.json b/schemas/payments_enriched.json
1159
+ @@
1160
+ {"name": "customer_id", "type": "string"},
1161
+ + {"name": "customer_email", "type": "string"},
1162
+ {"name": "amount_usd", "type": "float"},
1163
+ """,
1164
+ },
1165
+ schema_registry={
1166
+ "payments_raw": """asset: payments_raw
1167
+ columns:
1168
+ - payment_id: string
1169
+ - customer_id: string
1170
+ - amount_usd: float
1171
+ - payment_status: string
1172
+ - processed_at: timestamp
1173
+ """,
1174
+ "customer_dim": """asset: customer_dim
1175
+ columns:
1176
+ - customer_id: string
1177
+ - customer_email: string
1178
+ - phone: string
1179
+ """,
1180
+ "payments_enriched": """asset: payments_enriched
1181
+ published_columns:
1182
+ - payment_id
1183
+ - customer_id
1184
+ - amount_usd
1185
+ - payment_status
1186
+ - processed_at
1187
+ """,
1188
+ },
1189
+ llm_draft={
1190
+ "primary": """AI draft summary:
1191
+ - Adds `customer_email` to the SELECT list.
1192
+ - Joins `customer_dim`.
1193
+ - Extends the published schema with `customer_email`.
1194
+ """,
1195
+ },
1196
+ review_target={
1197
+ "correct_verdict": "reject",
1198
+ "correct_issue_type": "pii_exposure",
1199
+ "summary_groups": [["customer_email"], ["policy", "direct identifier"], ["schema", "contract"]],
1200
+ "investigation_targets": [
1201
+ ("inspect_llm_draft", "primary"),
1202
+ ("read_file", "policies/data_governance.md"),
1203
+ ("run_validator", "privacy_guard"),
1204
+ ],
1205
+ "validator_targets": ["privacy_guard"],
1206
+ },
1207
+ validators={
1208
+ "privacy_guard": review_validator(
1209
+ "Checks whether the proposed patch leaks direct identifiers.",
1210
+ "primary",
1211
+ forbidden_terms=["customer_email", "phone", "full_name"],
1212
+ ),
1213
+ "contract_guard": review_validator(
1214
+ "Checks whether the patch changes the published contract.",
1215
+ "primary",
1216
+ forbidden_terms=["published schema", "customer_email"],
1217
+ ),
1218
+ },
1219
+ ),
1220
+ review_scenario(
1221
+ scenario_id="LR-002",
1222
+ developer_request=(
1223
+ "Review the assistant patch for `merchant_settlement_rollup`. The SQL "
1224
+ "looks plausible, but finance thinks the join is wrong."
1225
+ ),
1226
+ workspace_summary=(
1227
+ "The AI patch sits in `drafts/` and the correct join key is documented "
1228
+ "in the settlement conventions file."
1229
+ ),
1230
+ known_files=[
1231
+ "transforms/merchant_settlement_rollup.sql",
1232
+ "docs/settlement_conventions.md",
1233
+ "drafts/merchant_settlement_rollup.patch",
1234
+ ],
1235
+ known_assets=["settlements_raw", "merchant_dim", "merchant_settlement_rollup"],
1236
+ available_validators=["logic_guard", "join_key_guard"],
1237
+ files={
1238
+ "transforms/merchant_settlement_rollup.sql": """select
1239
+ s.settlement_id,
1240
+ s.merchant_id,
1241
+ s.net_amount_usd,
1242
+ s.settlement_date
1243
+ from settlements_raw s;
1244
+ """,
1245
+ "docs/settlement_conventions.md": """# Settlement conventions
1246
+
1247
+ - Merchant enrichment joins on `merchant_id`.
1248
+ - Never join merchant dimensions using settlement or payment identifiers.
1249
+ - Published rollups must stay at one row per settlement_id.
1250
+ """,
1251
+ "drafts/merchant_settlement_rollup.patch": """diff --git a/transforms/merchant_settlement_rollup.sql b/transforms/merchant_settlement_rollup.sql
1252
+ @@
1253
+ select
1254
+ s.settlement_id,
1255
+ s.merchant_id,
1256
+ m.region as merchant_region,
1257
+ s.net_amount_usd,
1258
+ s.settlement_date
1259
+ from settlements_raw s
1260
+ +left join merchant_dim m on s.settlement_id = m.merchant_id;
1261
+ """,
1262
+ },
1263
+ schema_registry={
1264
+ "settlements_raw": """asset: settlements_raw
1265
+ columns:
1266
+ - settlement_id: string
1267
+ - merchant_id: string
1268
+ - net_amount_usd: float
1269
+ - settlement_date: date
1270
+ """,
1271
+ "merchant_dim": """asset: merchant_dim
1272
+ columns:
1273
+ - merchant_id: string
1274
+ - region: string
1275
+ """,
1276
+ "merchant_settlement_rollup": """asset: merchant_settlement_rollup
1277
+ grain:
1278
+ one_row_per: settlement_id
1279
+ """,
1280
+ },
1281
+ llm_draft={
1282
+ "primary": """AI draft summary:
1283
+ - Enriches settlements with merchant region.
1284
+ - Joins `merchant_dim` using `settlement_id = merchant_id`.
1285
+ - Does not change the published grain intentionally.
1286
+ """,
1287
+ },
1288
+ review_target={
1289
+ "correct_verdict": "reject",
1290
+ "correct_issue_type": "technical_incorrectness",
1291
+ "summary_groups": [["join"], ["settlement_id", "merchant_id"], ["wrong", "incorrect"]],
1292
+ "investigation_targets": [
1293
+ ("inspect_llm_draft", "primary"),
1294
+ ("read_file", "drafts/merchant_settlement_rollup.patch"),
1295
+ ("read_file", "docs/settlement_conventions.md"),
1296
+ ("run_validator", "logic_guard"),
1297
+ ],
1298
+ "validator_targets": ["logic_guard", "join_key_guard"],
1299
+ },
1300
+ validators={
1301
+ "logic_guard": review_validator(
1302
+ "Checks that the draft avoids the incorrect settlement-to-merchant join.",
1303
+ "primary",
1304
+ forbidden_terms=["settlement_id = merchant_id"],
1305
+ ),
1306
+ "join_key_guard": review_validator(
1307
+ "Checks that the draft references the documented merchant join key.",
1308
+ "primary",
1309
+ required_groups=[["merchant_id"]],
1310
+ forbidden_terms=["settlement_id = merchant_id"],
1311
+ ),
1312
+ },
1313
+ ),
1314
+ review_scenario(
1315
+ scenario_id="LR-003",
1316
+ developer_request=(
1317
+ "Review the patch for `subscription_mrr_daily`. The assistant claims it "
1318
+ "fixes a reporting bug, but product analytics is worried about contract "
1319
+ "compatibility."
1320
+ ),
1321
+ workspace_summary=(
1322
+ "Published contracts for finance datasets are strict. Review the patch "
1323
+ "and decide if the proposed schema change is acceptable."
1324
+ ),
1325
+ known_files=[
1326
+ "schemas/subscription_mrr_daily.json",
1327
+ "policies/published_contracts.md",
1328
+ "drafts/subscription_mrr_daily.patch",
1329
+ ],
1330
+ known_assets=["subscription_mrr_daily"],
1331
+ available_validators=["contract_guard", "consumer_guard"],
1332
+ files={
1333
+ "schemas/subscription_mrr_daily.json": """{
1334
+ "name": "subscription_mrr_daily",
1335
+ "columns": [
1336
+ {"name": "account_id", "type": "string"},
1337
+ {"name": "snapshot_date", "type": "date"},
1338
+ {"name": "mrr_usd", "type": "float"}
1339
+ ]
1340
+ }
1341
+ """,
1342
+ "policies/published_contracts.md": """# Published contracts
1343
+
1344
+ - Finance marts require approval before adding or renaming published columns.
1345
+ - Backward-incompatible contract changes must not be merged through assistant patches.
1346
+ """,
1347
+ "drafts/subscription_mrr_daily.patch": """diff --git a/schemas/subscription_mrr_daily.json b/schemas/subscription_mrr_daily.json
1348
+ @@
1349
+ {"name": "account_id", "type": "string"},
1350
+ {"name": "snapshot_date", "type": "date"},
1351
+ - {"name": "mrr_usd", "type": "float"}
1352
+ + {"name": "monthly_recurring_revenue_usd", "type": "float"}
1353
+ """,
1354
+ },
1355
+ schema_registry={
1356
+ "subscription_mrr_daily": """asset: subscription_mrr_daily
1357
+ published_columns:
1358
+ - account_id
1359
+ - snapshot_date
1360
+ - mrr_usd
1361
+ """,
1362
+ },
1363
+ llm_draft={
1364
+ "primary": """AI draft summary:
1365
+ - Renames `mrr_usd` to `monthly_recurring_revenue_usd` for clarity.
1366
+ - Describes the change as non-breaking because the meaning is unchanged.
1367
+ """,
1368
+ },
1369
+ review_target={
1370
+ "correct_verdict": "reject",
1371
+ "correct_issue_type": "contract_breakage",
1372
+ "summary_groups": [["published", "contract"], ["mrr_usd"], ["rename", "breaking"], ["consumer", "downstream"]],
1373
+ "investigation_targets": [
1374
+ ("inspect_llm_draft", "primary"),
1375
+ ("read_file", "policies/published_contracts.md"),
1376
+ ("run_validator", "contract_guard"),
1377
+ ],
1378
+ "validator_targets": ["contract_guard", "consumer_guard"],
1379
+ },
1380
+ validators={
1381
+ "contract_guard": review_validator(
1382
+ "Checks that the draft keeps the published finance contract stable.",
1383
+ "primary",
1384
+ forbidden_terms=["monthly_recurring_revenue_usd", "rename"],
1385
+ ),
1386
+ "consumer_guard": review_validator(
1387
+ "Checks that downstream consumers still receive `mrr_usd`.",
1388
+ "primary",
1389
+ forbidden_terms=["monthly_recurring_revenue_usd"],
1390
+ ),
1391
+ },
1392
+ ),
1393
+ review_scenario(
1394
+ scenario_id="LR-004",
1395
+ developer_request=(
1396
+ "Review the assistant response for warehouse recovery. Decide whether "
1397
+ "the recommendation is safe to execute in production."
1398
+ ),
1399
+ workspace_summary=(
1400
+ "The assistant produced an ops recommendation instead of a code patch. "
1401
+ "Use the platform recovery policy as the source of truth."
1402
+ ),
1403
+ known_files=[
1404
+ "policies/recovery_playbook.md",
1405
+ "drafts/warehouse_recovery_response.md",
1406
+ ],
1407
+ known_assets=["warehouse.recovery"],
1408
+ available_validators=["safety_guard", "playbook_guard"],
1409
+ files={
1410
+ "policies/recovery_playbook.md": """# Recovery playbook
1411
+
1412
+ - Never drop production marts as a first response to pipeline incidents.
1413
+ - Do not disable contract or governance checks to speed up recovery.
1414
+ - Preferred order: identify failing upstream, patch safely, re-run validators, then backfill.
1415
+ """,
1416
+ "drafts/warehouse_recovery_response.md": """The quickest fix is to drop and recreate `finance.daily_margin_mart`,
1417
+ disable contract checks temporarily, and backfill after the model retrains.
1418
+ This avoids waiting on upstream teams and gets dashboards green faster.
1419
+ """,
1420
+ },
1421
+ schema_registry={
1422
+ "warehouse.recovery": """asset: warehouse.recovery
1423
+ policy_owner: platform-sre
1424
+ """,
1425
+ },
1426
+ llm_draft={
1427
+ "primary": """AI response summary:
1428
+ - Recommends dropping a production mart.
1429
+ - Suggests disabling contract checks temporarily.
1430
+ - Prioritizes speed over safe rollback and validation.
1431
+ """,
1432
+ },
1433
+ review_target={
1434
+ "correct_verdict": "reject",
1435
+ "correct_issue_type": "unsafe_operation",
1436
+ "summary_groups": [["drop", "recreate"], ["disable", "checks"], ["unsafe", "policy"]],
1437
+ "investigation_targets": [
1438
+ ("inspect_llm_draft", "primary"),
1439
+ ("read_file", "policies/recovery_playbook.md"),
1440
+ ("run_validator", "safety_guard"),
1441
+ ],
1442
+ "validator_targets": ["safety_guard", "playbook_guard"],
1443
+ },
1444
+ validators={
1445
+ "safety_guard": review_validator(
1446
+ "Checks that the recommendation avoids destructive recovery advice.",
1447
+ "primary",
1448
+ forbidden_terms=["drop", "disable contract checks"],
1449
+ ),
1450
+ "playbook_guard": review_validator(
1451
+ "Checks alignment with the platform recovery playbook.",
1452
+ "primary",
1453
+ forbidden_terms=["drop", "disable"],
1454
+ ),
1455
+ },
1456
+ ),
1457
+ ],
1458
+ "workflow_shipping": [
1459
+ workflow_scenario(
1460
+ scenario_id="WS-001",
1461
+ developer_request=(
1462
+ "Add a daily `merchant_risk_features` workflow for the risk-model "
1463
+ "team. Use `transactions_silver`, `chargebacks_silver`, and "
1464
+ "`merchant_dim`; compute a 30-day lookback; exclude test merchants; "
1465
+ "do not expose PII; add freshness and not-null checks; and preserve "
1466
+ "the downstream `risk_model_scoring` contract."
1467
+ ),
1468
+ workspace_summary=(
1469
+ "This repo contains examples for feature pipelines plus a draft from "
1470
+ "an internal coding assistant. The target workflow does not exist yet. "
1471
+ "Use the templates and downstream contract as the source of truth."
1472
+ ),
1473
+ known_files=[
1474
+ "templates/pipeline_template.yaml",
1475
+ "templates/feature_template.sql",
1476
+ "templates/checks_template.yaml",
1477
+ "pipelines/order_features.yaml",
1478
+ "sql/order_features.sql",
1479
+ "checks/order_features.yaml",
1480
+ "schemas/order_features.json",
1481
+ "pipelines/risk_model_scoring.yaml",
1482
+ "schemas/risk_model_scoring.json",
1483
+ "docs/platform_standards.md",
1484
+ "drafts/merchant_risk_features.stub",
1485
+ ],
1486
+ editable_targets=[
1487
+ "pipelines/merchant_risk_features.yaml",
1488
+ "sql/merchant_risk_features.sql",
1489
+ "checks/merchant_risk_features.yaml",
1490
+ "schemas/merchant_risk_features.json",
1491
+ ],
1492
+ known_assets=[
1493
+ "transactions_silver",
1494
+ "chargebacks_silver",
1495
+ "merchant_dim",
1496
+ "merchant_risk_features",
1497
+ "risk_model_scoring",
1498
+ ],
1499
+ available_validators=[
1500
+ "workflow_lint",
1501
+ "quality_checks",
1502
+ "contract_check",
1503
+ "governance_check",
1504
+ ],
1505
+ files={
1506
+ "templates/pipeline_template.yaml": """name: <pipeline_name>
1507
+ schedule: "0 1 * * *"
1508
+ owner: risk-platform
1509
+ sources:
1510
+ - <source_asset>
1511
+ target: <target_asset>
1512
+ checks_file: checks/<pipeline_name>.yaml
1513
+ downstreams:
1514
+ - <consumer>
1515
+ """,
1516
+ "templates/feature_template.sql": """with source as (
1517
+ select *
1518
+ from <source_asset>
1519
+ )
1520
+ select *
1521
+ from source;
1522
+ """,
1523
+ "templates/checks_template.yaml": """checks:
1524
+ - type: freshness
1525
+ column: snapshot_date
1526
+ - type: not_null
1527
+ column: id
1528
+ """,
1529
+ "pipelines/order_features.yaml": """name: order_features
1530
+ schedule: "0 1 * * *"
1531
+ owner: risk-platform
1532
+ sources:
1533
+ - orders_silver
1534
+ - merchant_dim
1535
+ target: order_features
1536
+ checks_file: checks/order_features.yaml
1537
+ downstreams:
1538
+ - risk_model_scoring
1539
+ """,
1540
+ "sql/order_features.sql": """with recent_orders as (
1541
+ select
1542
+ o.merchant_id,
1543
+ count(*) as order_count_30d,
1544
+ current_date as snapshot_date
1545
+ from orders_silver o
1546
+ join merchant_dim m on o.merchant_id = m.merchant_id
1547
+ where m.is_test = false
1548
+ and o.created_at >= current_date - interval '30 day'
1549
+ group by 1, 3
1550
+ )
1551
+ select *
1552
+ from recent_orders;
1553
+ """,
1554
+ "checks/order_features.yaml": """checks:
1555
+ - type: freshness
1556
+ column: snapshot_date
1557
+ - type: not_null
1558
+ column: merchant_id
1559
+ """,
1560
+ "schemas/order_features.json": """{
1561
+ "name": "order_features",
1562
+ "columns": [
1563
+ {"name": "merchant_id", "type": "string"},
1564
+ {"name": "order_count_30d", "type": "integer"},
1565
+ {"name": "snapshot_date", "type": "date"}
1566
+ ]
1567
+ }
1568
+ """,
1569
+ "pipelines/risk_model_scoring.yaml": """name: risk_model_scoring
1570
+ sources:
1571
+ - merchant_risk_features
1572
+ target: risk_model_scoring
1573
+ """,
1574
+ "schemas/risk_model_scoring.json": """{
1575
+ "name": "risk_model_scoring",
1576
+ "required_inputs": [
1577
+ "merchant_id",
1578
+ "txn_count_30d",
1579
+ "chargeback_rate_30d",
1580
+ "snapshot_date"
1581
+ ]
1582
+ }
1583
+ """,
1584
+ "docs/platform_standards.md": """# Platform standards
1585
+
1586
+ - New feature pipelines run daily at `0 1 * * *`.
1587
+ - Exclude test merchants using `merchant_dim.is_test = false`.
1588
+ - Never select direct identifiers such as `email`, `phone`, or `full_name`.
1589
+ - Every feature pipeline must ship freshness and not_null checks.
1590
+ - Declare downstream consumers in the pipeline YAML.
1591
+ """,
1592
+ "drafts/merchant_risk_features.stub": """# AI assistant stub
1593
+ -- WARNING: draft may be unsafe
1594
+ select
1595
+ t.merchant_id,
1596
+ m.email as merchant_email,
1597
+ count(*) as txn_count_30d,
1598
+ current_date as snapshot_date
1599
+ from transactions_silver t
1600
+ join merchant_dim m on t.merchant_id = m.merchant_id
1601
+ group by 1, 2, 4;
1602
+ """,
1603
+ },
1604
+ schema_registry={
1605
+ "transactions_silver": """asset: transactions_silver
1606
+ columns:
1607
+ - merchant_id: string
1608
+ - transaction_id: string
1609
+ - amount_usd: float
1610
+ - processed_at: timestamp
1611
+ """,
1612
+ "chargebacks_silver": """asset: chargebacks_silver
1613
+ columns:
1614
+ - merchant_id: string
1615
+ - chargeback_id: string
1616
+ - processed_at: timestamp
1617
+ """,
1618
+ "merchant_dim": """asset: merchant_dim
1619
+ columns:
1620
+ - merchant_id: string
1621
+ - is_test: boolean
1622
+ - email: string
1623
+ - owner_name: string
1624
+ """,
1625
+ "merchant_risk_features": """asset: merchant_risk_features
1626
+ required_columns:
1627
+ - merchant_id
1628
+ - txn_count_30d
1629
+ - chargeback_rate_30d
1630
+ - snapshot_date
1631
+ """,
1632
+ "risk_model_scoring": """asset: risk_model_scoring
1633
+ requires:
1634
+ - merchant_id
1635
+ - txn_count_30d
1636
+ - chargeback_rate_30d
1637
+ - snapshot_date
1638
+ """,
1639
+ },
1640
+ workflow_target={
1641
+ "required_artifacts": ["pipeline", "sql", "checks", "schema"],
1642
+ "artifacts": {
1643
+ "pipeline": workflow_artifact(
1644
+ "pipelines/merchant_risk_features.yaml",
1645
+ [
1646
+ ["merchant_risk_features"],
1647
+ ["0 1 * * *", "daily"],
1648
+ ["transactions_silver"],
1649
+ ["chargebacks_silver"],
1650
+ ["merchant_dim"],
1651
+ ["risk_model_scoring"],
1652
+ ],
1653
+ 0.25,
1654
+ ),
1655
+ "sql": workflow_artifact(
1656
+ "sql/merchant_risk_features.sql",
1657
+ [
1658
+ ["transactions_silver"],
1659
+ ["chargebacks_silver"],
1660
+ ["merchant_dim"],
1661
+ ["30 day", "30-day", "interval '30 day'"],
1662
+ ["is_test = false", "is_test=false"],
1663
+ ["txn_count_30d"],
1664
+ ["chargeback_rate_30d"],
1665
+ ["snapshot_date"],
1666
+ ],
1667
+ 0.4,
1668
+ forbidden_terms=["email", "phone", "full_name"],
1669
+ ),
1670
+ "checks": workflow_artifact(
1671
+ "checks/merchant_risk_features.yaml",
1672
+ [["freshness"], ["not_null"], ["merchant_id"], ["snapshot_date"]],
1673
+ 0.15,
1674
+ ),
1675
+ "schema": workflow_artifact(
1676
+ "schemas/merchant_risk_features.json",
1677
+ [["merchant_id"], ["txn_count_30d"], ["chargeback_rate_30d"], ["snapshot_date"]],
1678
+ 0.2,
1679
+ forbidden_terms=["email", "phone", "full_name"],
1680
+ ),
1681
+ },
1682
+ "investigation_targets": [
1683
+ ("read_file", "templates/pipeline_template.yaml"),
1684
+ ("read_file", "sql/order_features.sql"),
1685
+ ("inspect_schema", "transactions_silver"),
1686
+ ("inspect_lineage", "risk_model_scoring"),
1687
+ ],
1688
+ "summary_groups": [["merchant_risk_features"], ["risk_model_scoring"], ["checks", "validators"]],
1689
+ "solve_validator_targets": ["workflow_lint", "governance_check"],
1690
+ "validator_targets": [
1691
+ "workflow_lint",
1692
+ "quality_checks",
1693
+ "contract_check",
1694
+ "governance_check",
1695
+ "workflow_sources_check",
1696
+ "workflow_schema_shape_check",
1697
+ "workflow_checks_shape_check",
1698
+ "workflow_delivery_check",
1699
+ ],
1700
+ "forbidden_terms": ["email", "phone", "full_name"],
1701
+ },
1702
+ validators={
1703
+ "workflow_lint": workflow_validator(
1704
+ "Checks pipeline metadata and lineage wiring.",
1705
+ "pipeline",
1706
+ ),
1707
+ "quality_checks": workflow_validator(
1708
+ "Checks freshness and not-null coverage.",
1709
+ "checks",
1710
+ ),
1711
+ "contract_check": workflow_validator(
1712
+ "Checks the schema contract expected by downstream scoring.",
1713
+ "schema",
1714
+ ),
1715
+ "governance_check": workflow_validator(
1716
+ "Checks for PII leakage and missing test-merchant filters.",
1717
+ "sql",
1718
+ ),
1719
+ "workflow_sources_check": workflow_validator(
1720
+ "Checks that the workflow covers the intended upstream source set.",
1721
+ "pipeline",
1722
+ ),
1723
+ "workflow_schema_shape_check": workflow_validator(
1724
+ "Checks that the feature schema stays aligned with downstream scoring expectations.",
1725
+ "schema",
1726
+ ),
1727
+ "workflow_checks_shape_check": workflow_validator(
1728
+ "Checks that the workflow publishes the expected validation checks.",
1729
+ "checks",
1730
+ ),
1731
+ "workflow_delivery_check": workflow_validator(
1732
+ "Checks that the workflow artifact bundle is ready for downstream delivery.",
1733
+ "pipeline",
1734
+ ),
1735
+ },
1736
+ lineage={
1737
+ "risk_model_scoring": """risk_model_scoring
1738
+ <- merchant_risk_features
1739
+ <- transactions_silver
1740
+ <- chargebacks_silver
1741
+ <- merchant_dim
1742
+ """,
1743
+ },
1744
+ llm_draft={
1745
+ "primary": """AI draft summary:
1746
+ - Mentions `merchant_email`, which violates governance.
1747
+ - Omits chargeback rate.
1748
+ - Does not exclude test merchants.
1749
+ - Does not define checks or pipeline metadata.
1750
+ """,
1751
+ },
1752
+ ),
1753
+ workflow_scenario(
1754
+ scenario_id="WS-002",
1755
+ developer_request=(
1756
+ "Create a reporting view called `finance_weekly_net_revenue` for the "
1757
+ "finance analysts. Base it on `invoice_line_items` and "
1758
+ "`credit_memos_daily`, publish a weekly grain by account, and define "
1759
+ "the view contract. This task only needs the SQL and schema artifacts."
1760
+ ),
1761
+ workspace_summary=(
1762
+ "Reporting views live under `sql/views/` and publish contracts under "
1763
+ "`schemas/views/`. There is no pipeline YAML for analyst-facing views."
1764
+ ),
1765
+ known_files=[
1766
+ "sql/views/finance_daily_revenue.sql",
1767
+ "schemas/views/finance_daily_revenue.json",
1768
+ "docs/reporting_view_standards.md",
1769
+ "docs/finance_reporting_glossary.md",
1770
+ ],
1771
+ editable_targets=[
1772
+ "sql/views/finance_weekly_net_revenue.sql",
1773
+ "schemas/views/finance_weekly_net_revenue.json",
1774
+ ],
1775
+ known_assets=[
1776
+ "invoice_line_items",
1777
+ "credit_memos_daily",
1778
+ "finance_weekly_net_revenue",
1779
+ ],
1780
+ available_validators=[
1781
+ "view_sql_check",
1782
+ "view_contract_check",
1783
+ "view_usage_check",
1784
+ "view_reference_check",
1785
+ "view_schema_naming_check",
1786
+ "view_rollup_check",
1787
+ "view_source_shape_check",
1788
+ "view_semantics_check",
1789
+ "view_contract_shape_check",
1790
+ ],
1791
+ files={
1792
+ "sql/views/finance_daily_revenue.sql": """select
1793
+ i.account_id,
1794
+ date(i.invoice_ts) as revenue_date,
1795
+ sum(i.net_revenue_usd) as net_revenue_usd
1796
+ from invoice_line_items i
1797
+ group by 1, 2;
1798
+ """,
1799
+ "schemas/views/finance_daily_revenue.json": """{
1800
+ "name": "finance_daily_revenue",
1801
+ "columns": [
1802
+ {"name": "account_id", "type": "string"},
1803
+ {"name": "revenue_date", "type": "date"},
1804
+ {"name": "net_revenue_usd", "type": "float"}
1805
+ ]
1806
+ }
1807
+ """,
1808
+ "docs/reporting_view_standards.md": """# Reporting view standards
1809
+
1810
+ - Analyst-facing views do not need pipeline YAML.
1811
+ - Weekly finance views should group by `date_trunc('week', ...)`.
1812
+ - Publish one schema contract per view.
1813
+ - Keep direct identifiers out of finance reporting views.
1814
+ """,
1815
+ "docs/finance_reporting_glossary.md": """# Finance reporting glossary
1816
+
1817
+ - Weekly reporting views should preserve a stable account-level rollup.
1818
+ - Reporting contracts should stay aligned with finance naming conventions.
1819
+ """,
1820
+ },
1821
+ schema_registry={
1822
+ "invoice_line_items": """asset: invoice_line_items
1823
+ columns:
1824
+ - account_id: string
1825
+ - invoice_ts: timestamp
1826
+ - net_revenue_usd: float
1827
+ """,
1828
+ "credit_memos_daily": """asset: credit_memos_daily
1829
+ columns:
1830
+ - account_id: string
1831
+ - credit_memo_date: date
1832
+ - credit_amount_usd: float
1833
+ """,
1834
+ "finance_weekly_net_revenue": """asset: finance_weekly_net_revenue
1835
+ required_columns:
1836
+ - account_id
1837
+ - revenue_week
1838
+ - net_revenue_usd
1839
+ """,
1840
+ },
1841
+ workflow_target={
1842
+ "required_artifacts": ["sql", "schema"],
1843
+ "artifacts": {
1844
+ "sql": workflow_artifact(
1845
+ "sql/views/finance_weekly_net_revenue.sql",
1846
+ [
1847
+ ["invoice_line_items"],
1848
+ ["credit_memos_daily"],
1849
+ ["date_trunc('week'", "date_trunc(\"week\""],
1850
+ ["account_id"],
1851
+ ["net_revenue_usd"],
1852
+ ],
1853
+ 0.7,
1854
+ forbidden_terms=["email", "phone", "full_name"],
1855
+ ),
1856
+ "schema": workflow_artifact(
1857
+ "schemas/views/finance_weekly_net_revenue.json",
1858
+ [["account_id"], ["revenue_week"], ["net_revenue_usd"]],
1859
+ 0.3,
1860
+ forbidden_terms=["email", "phone", "full_name"],
1861
+ ),
1862
+ },
1863
+ "investigation_targets": [
1864
+ ("read_file", "sql/views/finance_daily_revenue.sql"),
1865
+ ("read_file", "schemas/views/finance_daily_revenue.json"),
1866
+ ("read_file", "docs/reporting_view_standards.md"),
1867
+ ("read_file", "docs/finance_reporting_glossary.md"),
1868
+ ("inspect_schema", "invoice_line_items"),
1869
+ ("inspect_schema", "credit_memos_daily"),
1870
+ ("inspect_schema", "finance_weekly_net_revenue"),
1871
+ ],
1872
+ "summary_groups": [["finance_weekly_net_revenue"], ["weekly"], ["schema"]],
1873
+ "solve_validator_targets": ["view_sql_check", "view_contract_check"],
1874
+ "validator_targets": [
1875
+ "view_sql_check",
1876
+ "view_contract_check",
1877
+ "view_usage_check",
1878
+ "view_reference_check",
1879
+ "view_schema_naming_check",
1880
+ "view_rollup_check",
1881
+ "view_source_shape_check",
1882
+ "view_semantics_check",
1883
+ "view_contract_shape_check",
1884
+ ],
1885
+ "forbidden_terms": ["email", "phone", "full_name"],
1886
+ },
1887
+ validators={
1888
+ "view_sql_check": workflow_validator(
1889
+ "Checks that the weekly reporting view SQL joins the expected inputs and weekly grain.",
1890
+ "sql",
1891
+ ),
1892
+ "view_contract_check": workflow_validator(
1893
+ "Checks that the reporting view contract publishes the required columns.",
1894
+ "schema",
1895
+ ),
1896
+ "view_usage_check": workflow_validator(
1897
+ "Checks that the reporting SQL publishes a stable account-level view shape.",
1898
+ "sql",
1899
+ ),
1900
+ "view_reference_check": workflow_validator(
1901
+ "Checks that the weekly view references the expected finance source tables.",
1902
+ "sql",
1903
+ ),
1904
+ "view_schema_naming_check": workflow_validator(
1905
+ "Checks that the published reporting schema uses the expected view name and column contract.",
1906
+ "schema",
1907
+ ),
1908
+ "view_rollup_check": workflow_validator(
1909
+ "Checks that the weekly reporting SQL preserves the intended rollup output shape.",
1910
+ "sql",
1911
+ ),
1912
+ "view_source_shape_check": workflow_validator(
1913
+ "Checks that the weekly reporting view contract stays aligned with the finance source shape.",
1914
+ "schema",
1915
+ ),
1916
+ "view_semantics_check": workflow_validator(
1917
+ "Checks that the weekly reporting SQL preserves the intended finance semantics.",
1918
+ "sql",
1919
+ ),
1920
+ "view_contract_shape_check": workflow_validator(
1921
+ "Checks that the weekly reporting contract stays aligned with downstream reporting expectations.",
1922
+ "schema",
1923
+ ),
1924
+ },
1925
+ ),
1926
+ workflow_scenario(
1927
+ scenario_id="WS-003",
1928
+ developer_request=(
1929
+ "Create a new `customer_margin_mart` workflow for finance. It should "
1930
+ "combine `orders_silver`, `refunds_silver`, and `customer_dim`, ship "
1931
+ "daily, exclude internal test accounts, write checks, and publish a "
1932
+ "contract for downstream BI dashboards."
1933
+ ),
1934
+ workspace_summary=(
1935
+ "Finance marts follow the same pipeline structure as other curated "
1936
+ "warehouse tables. Use the existing mart example and governance rules."
1937
+ ),
1938
+ known_files=[
1939
+ "templates/pipeline_template.yaml",
1940
+ "sql/order_features.sql",
1941
+ "checks/order_features.yaml",
1942
+ "schemas/order_features.json",
1943
+ "docs/platform_standards.md",
1944
+ ],
1945
+ editable_targets=[
1946
+ "pipelines/customer_margin_mart.yaml",
1947
+ "sql/customer_margin_mart.sql",
1948
+ "checks/customer_margin_mart.yaml",
1949
+ "schemas/customer_margin_mart.json",
1950
+ ],
1951
+ known_assets=[
1952
+ "orders_silver",
1953
+ "refunds_silver",
1954
+ "customer_dim",
1955
+ "customer_margin_mart",
1956
+ ],
1957
+ available_validators=[
1958
+ "mart_lint",
1959
+ "mart_checks",
1960
+ "mart_contract",
1961
+ "mart_governance",
1962
+ "mart_source_check",
1963
+ "mart_schema_shape_check",
1964
+ "mart_pipeline_metadata_check",
1965
+ "mart_publish_contract_check",
1966
+ "mart_consumer_shape_check",
1967
+ ],
1968
+ files={
1969
+ "templates/pipeline_template.yaml": """name: <pipeline_name>
1970
+ schedule: "0 1 * * *"
1971
+ owner: data-platform
1972
+ sources:
1973
+ - <source_asset>
1974
+ target: <target_asset>
1975
+ checks_file: checks/<pipeline_name>.yaml
1976
+ """,
1977
+ "sql/order_features.sql": """with recent_orders as (
1978
+ select
1979
+ o.merchant_id,
1980
+ count(*) as order_count_30d,
1981
+ current_date as snapshot_date
1982
+ from orders_silver o
1983
+ join merchant_dim m on o.merchant_id = m.merchant_id
1984
+ where m.is_test = false
1985
+ and o.created_at >= current_date - interval '30 day'
1986
+ group by 1, 3
1987
+ )
1988
+ select *
1989
+ from recent_orders;
1990
+ """,
1991
+ "checks/order_features.yaml": """checks:
1992
+ - type: freshness
1993
+ column: snapshot_date
1994
+ - type: not_null
1995
+ column: merchant_id
1996
+ """,
1997
+ "schemas/order_features.json": """{
1998
+ "name": "order_features",
1999
+ "columns": [
2000
+ {"name": "merchant_id", "type": "string"},
2001
+ {"name": "order_count_30d", "type": "integer"},
2002
+ {"name": "snapshot_date", "type": "date"}
2003
+ ]
2004
+ }
2005
+ """,
2006
+ "docs/platform_standards.md": """# Platform standards
2007
+
2008
+ - Curated marts run daily at `0 1 * * *`.
2009
+ - Exclude test or internal entities using the dimension table filter.
2010
+ - Publish freshness and not_null checks for curated marts.
2011
+ - Avoid direct identifiers such as `email`, `phone`, and `full_name`.
2012
+ """,
2013
+ },
2014
+ schema_registry={
2015
+ "orders_silver": """asset: orders_silver
2016
+ columns:
2017
+ - customer_id: string
2018
+ - order_id: string
2019
+ - created_at: timestamp
2020
+ - gross_amount_usd: float
2021
+ """,
2022
+ "refunds_silver": """asset: refunds_silver
2023
+ columns:
2024
+ - customer_id: string
2025
+ - refund_id: string
2026
+ - processed_at: timestamp
2027
+ - refund_amount_usd: float
2028
+ """,
2029
+ "customer_dim": """asset: customer_dim
2030
+ columns:
2031
+ - customer_id: string
2032
+ - is_test: boolean
2033
+ - email: string
2034
+ """,
2035
+ "customer_margin_mart": """asset: customer_margin_mart
2036
+ required_columns:
2037
+ - customer_id
2038
+ - gross_revenue_usd
2039
+ - refund_amount_usd
2040
+ - net_margin_usd
2041
+ - snapshot_date
2042
+ """,
2043
+ },
2044
+ workflow_target={
2045
+ "required_artifacts": ["pipeline", "sql", "checks", "schema"],
2046
+ "artifacts": {
2047
+ "pipeline": workflow_artifact(
2048
+ "pipelines/customer_margin_mart.yaml",
2049
+ [
2050
+ ["customer_margin_mart"],
2051
+ ["0 1 * * *", "daily"],
2052
+ ["orders_silver"],
2053
+ ["refunds_silver"],
2054
+ ["customer_dim"],
2055
+ ],
2056
+ 0.2,
2057
+ ),
2058
+ "sql": workflow_artifact(
2059
+ "sql/customer_margin_mart.sql",
2060
+ [
2061
+ ["orders_silver"],
2062
+ ["refunds_silver"],
2063
+ ["customer_dim"],
2064
+ ["is_test = false", "is_test=false"],
2065
+ ["gross_revenue_usd"],
2066
+ ["refund_amount_usd"],
2067
+ ["net_margin_usd"],
2068
+ ["snapshot_date"],
2069
+ ],
2070
+ 0.45,
2071
+ forbidden_terms=["email", "phone", "full_name"],
2072
+ ),
2073
+ "checks": workflow_artifact(
2074
+ "checks/customer_margin_mart.yaml",
2075
+ [["freshness"], ["not_null"], ["customer_id"], ["snapshot_date"]],
2076
+ 0.15,
2077
+ ),
2078
+ "schema": workflow_artifact(
2079
+ "schemas/customer_margin_mart.json",
2080
+ [
2081
+ ["customer_id"],
2082
+ ["gross_revenue_usd"],
2083
+ ["refund_amount_usd"],
2084
+ ["net_margin_usd"],
2085
+ ["snapshot_date"],
2086
+ ],
2087
+ 0.2,
2088
+ forbidden_terms=["email", "phone", "full_name"],
2089
+ ),
2090
+ },
2091
+ "investigation_targets": [
2092
+ ("read_file", "templates/pipeline_template.yaml"),
2093
+ ("read_file", "checks/order_features.yaml"),
2094
+ ("read_file", "docs/platform_standards.md"),
2095
+ ("read_file", "schemas/order_features.json"),
2096
+ ("inspect_schema", "orders_silver"),
2097
+ ("inspect_schema", "refunds_silver"),
2098
+ ("inspect_schema", "customer_dim"),
2099
+ ],
2100
+ "summary_groups": [["customer_margin_mart"], ["daily"], ["checks", "contract"]],
2101
+ "solve_validator_targets": ["mart_lint", "mart_governance"],
2102
+ "validator_targets": [
2103
+ "mart_lint",
2104
+ "mart_checks",
2105
+ "mart_contract",
2106
+ "mart_governance",
2107
+ "mart_source_check",
2108
+ "mart_schema_shape_check",
2109
+ "mart_pipeline_metadata_check",
2110
+ "mart_publish_contract_check",
2111
+ "mart_consumer_shape_check",
2112
+ "mart_schedule_check",
2113
+ "mart_delivery_shape_check",
2114
+ ],
2115
+ "forbidden_terms": ["email", "phone", "full_name"],
2116
+ },
2117
+ validators={
2118
+ "mart_lint": workflow_validator(
2119
+ "Checks mart pipeline metadata and sources.",
2120
+ "pipeline",
2121
+ ),
2122
+ "mart_checks": workflow_validator(
2123
+ "Checks mart freshness and not-null coverage.",
2124
+ "checks",
2125
+ ),
2126
+ "mart_contract": workflow_validator(
2127
+ "Checks mart contract columns.",
2128
+ "schema",
2129
+ ),
2130
+ "mart_governance": workflow_validator(
2131
+ "Checks that mart SQL excludes direct identifiers and test accounts.",
2132
+ "sql",
2133
+ ),
2134
+ "mart_source_check": workflow_validator(
2135
+ "Checks that the mart pipeline and SQL cover the required upstream sources.",
2136
+ "pipeline",
2137
+ ),
2138
+ "mart_schema_shape_check": workflow_validator(
2139
+ "Checks that the mart schema publishes the expected finance BI columns.",
2140
+ "schema",
2141
+ ),
2142
+ "mart_pipeline_metadata_check": workflow_validator(
2143
+ "Checks that the mart pipeline metadata is production-ready for finance scheduling.",
2144
+ "pipeline",
2145
+ ),
2146
+ "mart_publish_contract_check": workflow_validator(
2147
+ "Checks that the mart contract remains publishable for downstream BI consumers.",
2148
+ "schema",
2149
+ ),
2150
+ "mart_consumer_shape_check": workflow_validator(
2151
+ "Checks that the mart output shape is suitable for downstream dashboard consumption.",
2152
+ "schema",
2153
+ ),
2154
+ "mart_schedule_check": workflow_validator(
2155
+ "Checks that the mart pipeline metadata stays aligned with the daily finance schedule.",
2156
+ "pipeline",
2157
+ ),
2158
+ "mart_delivery_shape_check": workflow_validator(
2159
+ "Checks that the mart contract shape is ready for downstream finance delivery.",
2160
+ "schema",
2161
+ ),
2162
+ },
2163
+ ),
2164
+ workflow_scenario(
2165
+ scenario_id="WS-004",
2166
+ developer_request=(
2167
+ "Create a new `finance_margin_watch` reporting asset for the control "
2168
+ "room. It should publish a daily SQL view, a schema contract, and an "
2169
+ "alert config that fires when margin drops sharply."
2170
+ ),
2171
+ workspace_summary=(
2172
+ "Control-room reporting assets pair warehouse views with lightweight "
2173
+ "alert configs so finance on-call can react to anomalies."
2174
+ ),
2175
+ known_files=[
2176
+ "sql/views/finance_daily_revenue.sql",
2177
+ "docs/reporting_view_standards.md",
2178
+ "docs/alerting_playbook.md",
2179
+ "alerts/examples/revenue_watch.yaml",
2180
+ ],
2181
+ editable_targets=[
2182
+ "sql/views/finance_margin_watch.sql",
2183
+ "schemas/views/finance_margin_watch.json",
2184
+ "alerts/finance_margin_watch.yaml",
2185
+ ],
2186
+ known_assets=[
2187
+ "invoice_line_items",
2188
+ "credit_memos_daily",
2189
+ "finance_margin_watch",
2190
+ ],
2191
+ available_validators=[
2192
+ "view_sql_check",
2193
+ "view_contract_check",
2194
+ "alert_config_check",
2195
+ "alert_severity_check",
2196
+ "view_monitoring_shape_check",
2197
+ "alert_dataset_check",
2198
+ ],
2199
+ files={
2200
+ "sql/views/finance_daily_revenue.sql": """select
2201
+ account_id,
2202
+ date(invoice_ts) as revenue_date,
2203
+ sum(net_revenue_usd) as net_revenue_usd
2204
+ from invoice_line_items
2205
+ group by 1, 2;
2206
+ """,
2207
+ "docs/reporting_view_standards.md": """# Reporting view standards
2208
+
2209
+ - Reporting views must publish stable business columns.
2210
+ - Views for control-room monitoring should expose a single daily grain.
2211
+ - Schema contracts should list the published fields in order.
2212
+ """,
2213
+ "docs/alerting_playbook.md": """# Alerting playbook
2214
+
2215
+ - Alert configs declare `name`, `dataset`, `metric`, `threshold`, and `severity`.
2216
+ - Margin watch alerts should trigger when `margin_delta_pct` falls below `-0.15`.
2217
+ - Finance alerts use severity `high`.
2218
+ """,
2219
+ "alerts/examples/revenue_watch.yaml": """name: finance_revenue_watch
2220
+ dataset: finance_daily_revenue
2221
+ metric: net_revenue_usd
2222
+ threshold: -0.1
2223
+ severity: medium
2224
+ """,
2225
+ },
2226
+ schema_registry={
2227
+ "invoice_line_items": """asset: invoice_line_items
2228
+ columns:
2229
+ - account_id: string
2230
+ - invoice_ts: timestamp
2231
+ - net_revenue_usd: float
2232
+ - margin_usd: float
2233
+ """,
2234
+ "credit_memos_daily": """asset: credit_memos_daily
2235
+ columns:
2236
+ - account_id: string
2237
+ - credit_memo_date: date
2238
+ - credit_amount_usd: float
2239
+ """,
2240
+ "finance_margin_watch": """asset: finance_margin_watch
2241
+ required_columns:
2242
+ - account_id
2243
+ - margin_date
2244
+ - margin_usd
2245
+ - margin_delta_pct
2246
+ """,
2247
+ },
2248
+ workflow_target={
2249
+ "required_artifacts": ["sql", "schema", "alert_config"],
2250
+ "artifacts": {
2251
+ "sql": workflow_artifact(
2252
+ "sql/views/finance_margin_watch.sql",
2253
+ [
2254
+ ["invoice_line_items"],
2255
+ ["credit_memos_daily"],
2256
+ ["margin_date"],
2257
+ ["margin_usd"],
2258
+ ["margin_delta_pct"],
2259
+ ],
2260
+ 0.45,
2261
+ forbidden_terms=["email", "phone", "full_name"],
2262
+ ),
2263
+ "schema": workflow_artifact(
2264
+ "schemas/views/finance_margin_watch.json",
2265
+ [["account_id"], ["margin_date"], ["margin_usd"], ["margin_delta_pct"]],
2266
+ 0.2,
2267
+ forbidden_terms=["email", "phone", "full_name"],
2268
+ ),
2269
+ "alert_config": workflow_artifact(
2270
+ "alerts/finance_margin_watch.yaml",
2271
+ [
2272
+ ["finance_margin_watch"],
2273
+ ["margin_delta_pct"],
2274
+ ["-0.15"],
2275
+ ["high"],
2276
+ ],
2277
+ 0.35,
2278
+ ),
2279
+ },
2280
+ "investigation_targets": [
2281
+ ("read_file", "sql/views/finance_daily_revenue.sql"),
2282
+ ("read_file", "docs/reporting_view_standards.md"),
2283
+ ("read_file", "docs/alerting_playbook.md"),
2284
+ ("read_file", "alerts/examples/revenue_watch.yaml"),
2285
+ ("inspect_schema", "invoice_line_items"),
2286
+ ],
2287
+ "summary_groups": [["finance_margin_watch"], ["alert"], ["margin_delta_pct"]],
2288
+ "solve_validator_targets": ["view_sql_check", "view_contract_check"],
2289
+ "validator_targets": [
2290
+ "view_sql_check",
2291
+ "view_contract_check",
2292
+ "alert_config_check",
2293
+ "alert_severity_check",
2294
+ "view_monitoring_shape_check",
2295
+ "alert_dataset_check",
2296
+ "alert_threshold_shape_check",
2297
+ "view_alert_contract_check",
2298
+ ],
2299
+ "forbidden_terms": ["email", "phone", "full_name"],
2300
+ },
2301
+ validators={
2302
+ "view_sql_check": workflow_validator(
2303
+ "Checks that the margin watch SQL publishes the expected daily fields.",
2304
+ "sql",
2305
+ ),
2306
+ "view_contract_check": workflow_validator(
2307
+ "Checks that the margin watch contract publishes the expected columns.",
2308
+ "schema",
2309
+ ),
2310
+ "alert_config_check": workflow_validator(
2311
+ "Checks that the alert config targets the correct dataset, metric, and threshold.",
2312
+ "alert_config",
2313
+ ),
2314
+ "alert_severity_check": workflow_validator(
2315
+ "Checks that the alert config preserves the intended severity and threshold semantics.",
2316
+ "alert_config",
2317
+ ),
2318
+ "view_monitoring_shape_check": workflow_validator(
2319
+ "Checks that the monitoring schema exposes the expected daily margin-watch columns.",
2320
+ "schema",
2321
+ ),
2322
+ "alert_dataset_check": workflow_validator(
2323
+ "Checks that the alert config stays aligned with the intended monitoring dataset shape.",
2324
+ "alert_config",
2325
+ ),
2326
+ "alert_threshold_shape_check": workflow_validator(
2327
+ "Checks that the alert threshold configuration preserves the intended monitoring shape.",
2328
+ "alert_config",
2329
+ ),
2330
+ "view_alert_contract_check": workflow_validator(
2331
+ "Checks that the reporting schema and alert contract remain aligned for monitoring delivery.",
2332
+ "schema",
2333
+ ),
2334
+ },
2335
+ ),
2336
+ ],
2337
+ }
2338
+
2339
+ SCENARIO_REGISTRY: dict[str, dict] = {
2340
+ scenario["scenario_id"]: scenario
2341
+ for scenario_group in SCENARIOS.values()
2342
+ for scenario in scenario_group
2343
+ }
2344
+
2345
+
2346
+ def _replace_text(value: str, mapping: dict[str, str]) -> str:
2347
+ rendered = value
2348
+ for old, new in mapping.items():
2349
+ rendered = rendered.replace(old, new)
2350
+ return rendered
2351
+
2352
+
2353
+ def _replace_groups(groups: list[list[str]], mapping: dict[str, str]) -> list[list[str]]:
2354
+ return [[_replace_text(option, mapping) for option in group] for group in groups]
2355
+
2356
+
2357
+ def _apply_variant_mapping(value: object, mapping: dict[str, str]) -> object:
2358
+ if isinstance(value, str):
2359
+ return _replace_text(value, mapping)
2360
+ if isinstance(value, list):
2361
+ return [_apply_variant_mapping(item, mapping) for item in value]
2362
+ if isinstance(value, dict):
2363
+ return {key: _apply_variant_mapping(item, mapping) for key, item in value.items()}
2364
+ return value
2365
+
2366
+
2367
+ def _seed_variant_index(seed: int, count: int, salt: int) -> int:
2368
+ if count <= 0:
2369
+ return 0
2370
+ return abs(seed + salt) % count
2371
+
2372
+
2373
+ def _apply_seeded_variant(scenario: dict, seed: int | None) -> dict:
2374
+ if seed is None:
2375
+ return scenario
2376
+
2377
+ scenario_id = scenario.get("scenario_id", "")
2378
+
2379
+ if scenario_id == "PR-005":
2380
+ variants = [
2381
+ {
2382
+ "env_key": "TARGET_WAREHOUSE_ROLE",
2383
+ "stale_key": "WAREHOUSE_ROLE",
2384
+ "role": "analytics_writer",
2385
+ },
2386
+ {
2387
+ "env_key": "TARGET_REPORTING_ROLE",
2388
+ "stale_key": "REPORTING_ROLE",
2389
+ "role": "reporting_writer",
2390
+ },
2391
+ ]
2392
+ variant = variants[_seed_variant_index(seed, len(variants), 5)]
2393
+ mapping = {
2394
+ "TARGET_WAREHOUSE_ROLE": variant["env_key"],
2395
+ "WAREHOUSE_ROLE": variant["stale_key"],
2396
+ "analytics_writer": variant["role"],
2397
+ }
2398
+ scenario = _apply_variant_mapping(scenario, mapping)
2399
+ scenario["developer_request"] = (
2400
+ f"{scenario['developer_request']} The packaged runner now expects `{variant['env_key']}` "
2401
+ f"with the `{variant['role']}` role."
2402
+ )
2403
+ return scenario
2404
+
2405
+ if scenario_id == "PR-006":
2406
+ variants = [
2407
+ {"id_col": "customer_code"},
2408
+ {"id_col": "member_code"},
2409
+ {"id_col": "profile_code"},
2410
+ ]
2411
+ variant = variants[_seed_variant_index(seed, len(variants), 6)]
2412
+ mapping = {"customer_code": variant["id_col"]}
2413
+ scenario = _apply_variant_mapping(scenario, mapping)
2414
+ scenario["developer_request"] = (
2415
+ f"{scenario['developer_request']} The failing identifier column is `{variant['id_col']}`."
2416
+ )
2417
+ return scenario
2418
+
2419
+ if scenario_id == "LR-003":
2420
+ variants = [
2421
+ {"metric": "mrr_usd", "replacement": "monthly_recurring_revenue_usd"},
2422
+ {"metric": "arr_usd", "replacement": "annual_recurring_revenue_usd"},
2423
+ {"metric": "net_revenue_usd", "replacement": "net_revenue_amount_usd"},
2424
+ ]
2425
+ variant = variants[_seed_variant_index(seed, len(variants), 3)]
2426
+ mapping = {
2427
+ "mrr_usd": variant["metric"],
2428
+ "monthly_recurring_revenue_usd": variant["replacement"],
2429
+ }
2430
+ scenario = _apply_variant_mapping(scenario, mapping)
2431
+ scenario["developer_request"] = (
2432
+ f"{scenario['developer_request']} The published metric under review is `{variant['metric']}`."
2433
+ )
2434
+ return scenario
2435
+
2436
+ if scenario_id == "WS-004":
2437
+ variants = [
2438
+ {"metric": "margin_delta_pct", "threshold": "-0.15"},
2439
+ {"metric": "net_revenue_delta_pct", "threshold": "-0.12"},
2440
+ ]
2441
+ variant = variants[_seed_variant_index(seed, len(variants), 4)]
2442
+ mapping = {
2443
+ "margin_delta_pct": variant["metric"],
2444
+ "-0.15": variant["threshold"],
2445
+ }
2446
+ scenario = _apply_variant_mapping(scenario, mapping)
2447
+ scenario["developer_request"] = (
2448
+ f"{scenario['developer_request']} The alert should monitor `{variant['metric']}` "
2449
+ f"and fire below `{variant['threshold']}`."
2450
+ )
2451
+ return scenario
2452
+
2453
+ return scenario
2454
+
2455
+
2456
+ def scenario_count(task_id: str) -> int:
2457
+ task = TASK_DEFINITIONS.get(task_id)
2458
+ if not task:
2459
+ raise ValueError(f"Unknown task_id '{task_id}'")
2460
+ return len(task.get("scenario_ids", []))
2461
+
2462
+
2463
+ def get_task(task_id: str) -> dict:
2464
+ if task_id not in TASK_DEFINITIONS:
2465
+ raise ValueError(f"Unknown task_id '{task_id}'")
2466
+ task = deepcopy(TASK_DEFINITIONS[task_id])
2467
+ task["scenarios"] = scenario_count(task_id)
2468
+ return task
2469
+
2470
+
2471
+ def get_scenario(task_id: str, index: int = 0, seed: int | None = None) -> dict:
2472
+ task = TASK_DEFINITIONS.get(task_id)
2473
+ if not task:
2474
+ raise ValueError(f"Unknown task_id '{task_id}'")
2475
+ scenario_ids = task.get("scenario_ids", [])
2476
+ if index < 0 or index >= len(scenario_ids):
2477
+ raise ValueError(
2478
+ f"Scenario index {index} out of range for task '{task_id}' "
2479
+ f"(available: 0-{len(scenario_ids) - 1})"
2480
+ )
2481
+ scenario_id = scenario_ids[index]
2482
+ scenario = deepcopy(SCENARIO_REGISTRY[scenario_id])
2483
+ return _apply_seeded_variant(scenario, seed)
2484
+
2485
+
2486
+ def get_grader_family(task_id: str) -> str:
2487
+ task = TASK_DEFINITIONS.get(task_id)
2488
+ if task is None:
2489
+ raise ValueError(f"Unknown task_id '{task_id}'")
2490
+ return str(task.get("grader_family", ""))
2491
+
2492
+
2493
+ def list_tasks() -> list[dict]:
2494
+ return [get_task(task_id) for task_id in TASK_DEFINITIONS]
tests/test_calibration.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+ from pathlib import Path
5
+ import sys
6
+
7
+ ROOT = Path(__file__).resolve().parents[1]
8
+ if str(ROOT) not in sys.path:
9
+ sys.path.insert(0, str(ROOT))
10
+
11
+ from baseline import build_action, fallback_action
12
+ from graders import grade
13
+ from server.developer_control_room_environment import DeveloperControlRoomEnvironment
14
+ from tasks import TASK_DEFINITIONS, get_task
15
+
16
+
17
+ def collect_scores() -> dict[str, list[float]]:
18
+ env = DeveloperControlRoomEnvironment()
19
+ scores: dict[str, list[float]] = defaultdict(list)
20
+ for task_id in TASK_DEFINITIONS:
21
+ task = get_task(task_id)
22
+ for idx in range(task["scenarios"]):
23
+ observation = env.reset(task_id=task_id, scenario_index=idx)
24
+ while not env._state.done:
25
+ action_dict = fallback_action(task_id, observation)
26
+ observation = env.step(build_action(action_dict))
27
+ scores[task_id].append(grade(task_id, env._state.model_dump(), env._scenario)["total"])
28
+ return scores
29
+
30
+
31
+ def test_scores_stay_in_range() -> None:
32
+ for task_scores in collect_scores().values():
33
+ for score in task_scores:
34
+ assert 0.0 <= score <= 1.0
35
+
36
+
37
+ def test_easy_medium_hard_ordering() -> None:
38
+ scores = collect_scores()
39
+ easy = scores["repair_data_transform"] + scores["repair_pipeline_execution"]
40
+ medium = scores["review_ai_patch_safety"] + scores["review_ai_patch_correctness"]
41
+ hard = scores["synthesize_reporting_asset"] + scores["synthesize_data_product"]
42
+
43
+ easy_avg = sum(easy) / len(easy)
44
+ medium_avg = sum(medium) / len(medium)
45
+ hard_avg = sum(hard) / len(hard)
46
+
47
+ assert easy_avg > medium_avg > hard_avg
48
+
49
+
50
+ def test_unsolved_hard_scenarios_score_lower() -> None:
51
+ scores = collect_scores()
52
+ solved_hard = [
53
+ max(scores["synthesize_reporting_asset"]),
54
+ max(scores["synthesize_data_product"]),
55
+ ]
56
+ unsolved_hard = [
57
+ min(scores["synthesize_reporting_asset"]),
58
+ min(scores["synthesize_data_product"]),
59
+ ]
60
+
61
+ assert max(unsolved_hard) < min(solved_hard)
tests/test_environment_behaviors.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ ROOT = Path(__file__).resolve().parents[1]
7
+ if str(ROOT) not in sys.path:
8
+ sys.path.insert(0, str(ROOT))
9
+
10
+ from baseline import action_is_valid, build_action, fallback_action, get_model_action
11
+ from graders import grade
12
+ from server.developer_control_room_environment import DeveloperControlRoomEnvironment
13
+ from tasks import get_scenario
14
+
15
+
16
+ def run_episode_with_fallback(task_id: str, scenario_index: int) -> dict:
17
+ env = DeveloperControlRoomEnvironment()
18
+ observation = env.reset(task_id=task_id, scenario_index=scenario_index)
19
+ while not env._state.done:
20
+ action_dict = fallback_action(task_id, observation)
21
+ observation = env.step(build_action(action_dict))
22
+ return {
23
+ "state": env._state.model_dump(),
24
+ "scenario": env._scenario,
25
+ "grade": grade(task_id, env._state.model_dump(), env._scenario),
26
+ }
27
+
28
+
29
+ def test_repeated_file_reads_are_penalized() -> None:
30
+ env = DeveloperControlRoomEnvironment()
31
+ env.reset(task_id="repair_pipeline_execution", scenario_index=0)
32
+
33
+ first = env.step(
34
+ build_action(
35
+ {
36
+ "action_type": "read_file",
37
+ "parameters": {"path": "pipelines/customer_events_ingest.yaml"},
38
+ }
39
+ )
40
+ )
41
+ second = env.step(
42
+ build_action(
43
+ {
44
+ "action_type": "read_file",
45
+ "parameters": {"path": "pipelines/customer_events_ingest.yaml"},
46
+ }
47
+ )
48
+ )
49
+
50
+ assert first.reward > 0
51
+ assert second.reward < first.reward
52
+
53
+
54
+ def test_repeated_validator_spam_gets_worse() -> None:
55
+ env = DeveloperControlRoomEnvironment()
56
+ env.reset(task_id="repair_pipeline_execution", scenario_index=1)
57
+
58
+ env.step(
59
+ build_action(
60
+ {
61
+ "action_type": "read_file",
62
+ "parameters": {"path": "ci/jenkins/orders_daily.groovy"},
63
+ }
64
+ )
65
+ )
66
+ env.step(
67
+ build_action(
68
+ {
69
+ "action_type": "edit_file",
70
+ "parameters": {
71
+ "path": "ci/jenkins/orders_daily.groovy",
72
+ "content": """pipeline {
73
+ agent any
74
+ stages {
75
+ stage('Run') {
76
+ steps {
77
+ sh './scripts/run_orders_daily.sh'
78
+ }
79
+ }
80
+ }
81
+ }
82
+ """,
83
+ },
84
+ }
85
+ )
86
+ )
87
+
88
+ first = env.step(
89
+ build_action(
90
+ {
91
+ "action_type": "run_validator",
92
+ "parameters": {"validator": "jenkins_lint"},
93
+ }
94
+ )
95
+ )
96
+ second = env.step(
97
+ build_action(
98
+ {
99
+ "action_type": "run_validator",
100
+ "parameters": {"validator": "jenkins_lint"},
101
+ }
102
+ )
103
+ )
104
+
105
+ assert first.reward > 0
106
+ assert second.reward <= 0
107
+ assert second.reward < first.reward
108
+
109
+
110
+ def test_invalid_early_edits_and_validators_are_blocked_by_hybrid_guardrails() -> None:
111
+ env = DeveloperControlRoomEnvironment()
112
+
113
+ reporting_obs = env.reset(task_id="synthesize_data_product", scenario_index=1)
114
+ assert not action_is_valid(
115
+ {
116
+ "action_type": "edit_file",
117
+ "parameters": {"path": "pipelines/customer_margin_mart.yaml", "content": "x"},
118
+ },
119
+ reporting_obs,
120
+ )
121
+
122
+ repair_obs = env.reset(task_id="repair_pipeline_execution", scenario_index=4)
123
+ assert not action_is_valid(
124
+ {
125
+ "action_type": "run_validator",
126
+ "parameters": {"validator": "column_mapping_guard"},
127
+ },
128
+ repair_obs,
129
+ )
130
+
131
+
132
+ def test_same_trajectory_gives_same_score() -> None:
133
+ first = run_episode_with_fallback("repair_pipeline_execution", 0)
134
+ second = run_episode_with_fallback("repair_pipeline_execution", 0)
135
+
136
+ assert first["state"]["action_history"] == second["state"]["action_history"]
137
+ assert first["state"]["cumulative_reward"] == second["state"]["cumulative_reward"]
138
+ assert first["grade"]["total"] == second["grade"]["total"]
139
+ assert first["grade"]["solved"] == second["grade"]["solved"]
140
+
141
+
142
+ def test_hard_tasks_mix_solved_and_unsolved_scenarios() -> None:
143
+ solved_reporting = run_episode_with_fallback("synthesize_reporting_asset", 0)["grade"]
144
+ unsolved_reporting = run_episode_with_fallback("synthesize_reporting_asset", 1)["grade"]
145
+ unsolved_product = run_episode_with_fallback("synthesize_data_product", 0)["grade"]
146
+ solved_product = run_episode_with_fallback("synthesize_data_product", 1)["grade"]
147
+
148
+ assert solved_reporting["solved"] is True
149
+ assert unsolved_reporting["solved"] is False
150
+ assert unsolved_product["solved"] is False
151
+ assert solved_product["solved"] is True
152
+ assert solved_reporting["total"] > unsolved_reporting["total"]
153
+ assert solved_product["total"] > unsolved_product["total"]
154
+
155
+
156
+ def test_reset_produces_clean_state() -> None:
157
+ env = DeveloperControlRoomEnvironment()
158
+ env.reset(task_id="repair_data_transform", scenario_index=0)
159
+ env.step(
160
+ build_action(
161
+ {
162
+ "action_type": "read_file",
163
+ "parameters": {"path": "transforms/orders_daily.sql"},
164
+ }
165
+ )
166
+ )
167
+ env.step(
168
+ build_action(
169
+ {
170
+ "action_type": "inspect_schema",
171
+ "parameters": {"asset": "raw.orders_events"},
172
+ }
173
+ )
174
+ )
175
+
176
+ fresh = env.reset(task_id="review_ai_patch_safety", scenario_index=0)
177
+
178
+ assert fresh.step_count == 0
179
+ assert fresh.cumulative_reward == 0.0
180
+ assert fresh.queried_data == {}
181
+ assert fresh.edited_files == {}
182
+ assert fresh.validator_status == {}
183
+ assert fresh.last_action_error is None
184
+
185
+
186
+ def test_forced_model_timeout_returns_none(monkeypatch) -> None:
187
+ env = DeveloperControlRoomEnvironment()
188
+ observation = env.reset(task_id="repair_data_transform", scenario_index=0)
189
+
190
+ monkeypatch.setenv("DEVELOPER_CONTROL_ROOM_FORCE_MODEL_TIMEOUT", "true")
191
+ result = get_model_action(
192
+ client=None, # type: ignore[arg-type]
193
+ model_name="demo-model",
194
+ temperature=0.2,
195
+ max_tokens=32,
196
+ timeout_seconds=0.01,
197
+ step=1,
198
+ observation=observation,
199
+ history=[],
200
+ )
201
+
202
+ assert result is None
203
+
204
+
205
+ def test_seeded_variants_are_deterministic_and_change_literals() -> None:
206
+ first = get_scenario("review_ai_patch_correctness", 1, seed=1)
207
+ second = get_scenario("review_ai_patch_correctness", 1, seed=1)
208
+ third = get_scenario("review_ai_patch_correctness", 1, seed=2)
209
+
210
+ assert first["developer_request"] == second["developer_request"]
211
+ assert first["files"]["schemas/subscription_mrr_daily.json"] == second["files"]["schemas/subscription_mrr_daily.json"]
212
+ assert first["developer_request"] != third["developer_request"]
uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
validate-submission.sh ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ #
3
+ # validate-submission.sh — OpenEnv Submission Validator
4
+ #
5
+ # Checks that your HF Space is live, Docker image builds, and openenv validate passes.
6
+ #
7
+ # Prerequisites:
8
+ # - Docker: https://docs.docker.com/get-docker/
9
+ # - openenv-core: pip install openenv-core
10
+ # - curl (usually pre-installed)
11
+ #
12
+ # Run:
13
+ # curl -fsSL https://raw.githubusercontent.com/<owner>/<repo>/main/scripts/validate-submission.sh | bash -s -- <ping_url> [repo_dir]
14
+ #
15
+ # Or download and run locally:
16
+ # chmod +x validate-submission.sh
17
+ # ./validate-submission.sh <ping_url> [repo_dir]
18
+ #
19
+ # Arguments:
20
+ # ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)
21
+ # repo_dir Path to your repo (default: current directory)
22
+ #
23
+ # Examples:
24
+ # ./validate-submission.sh https://my-team.hf.space
25
+ # ./validate-submission.sh https://my-team.hf.space ./my-repo
26
+ #
27
+
28
+ set -uo pipefail
29
+
30
+ DOCKER_BUILD_TIMEOUT=600
31
+ if [ -t 1 ]; then
32
+ RED='\033[0;31m'
33
+ GREEN='\033[0;32m'
34
+ YELLOW='\033[1;33m'
35
+ BOLD='\033[1m'
36
+ NC='\033[0m'
37
+ else
38
+ RED='' GREEN='' YELLOW='' BOLD='' NC=''
39
+ fi
40
+
41
+ run_with_timeout() {
42
+ local secs="$1"; shift
43
+ if command -v timeout &>/dev/null; then
44
+ timeout "$secs" "$@"
45
+ elif command -v gtimeout &>/dev/null; then
46
+ gtimeout "$secs" "$@"
47
+ else
48
+ "$@" &
49
+ local pid=$!
50
+ ( sleep "$secs" && kill "$pid" 2>/dev/null ) &
51
+ local watcher=$!
52
+ wait "$pid" 2>/dev/null
53
+ local rc=$?
54
+ kill "$watcher" 2>/dev/null
55
+ wait "$watcher" 2>/dev/null
56
+ return $rc
57
+ fi
58
+ }
59
+
60
+ portable_mktemp() {
61
+ local prefix="${1:-validate}"
62
+ mktemp "${TMPDIR:-/tmp}/${prefix}-XXXXXX" 2>/dev/null || mktemp
63
+ }
64
+
65
+ CLEANUP_FILES=()
66
+ cleanup() { rm -f "${CLEANUP_FILES[@]+"${CLEANUP_FILES[@]}"}"; }
67
+ trap cleanup EXIT
68
+
69
+ PING_URL="${1:-}"
70
+ REPO_DIR="${2:-.}"
71
+
72
+ if [ -z "$PING_URL" ]; then
73
+ printf "Usage: %s <ping_url> [repo_dir]\n" "$0"
74
+ printf "\n"
75
+ printf " ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)\n"
76
+ printf " repo_dir Path to your repo (default: current directory)\n"
77
+ exit 1
78
+ fi
79
+
80
+ if ! REPO_DIR="$(cd "$REPO_DIR" 2>/dev/null && pwd)"; then
81
+ printf "Error: directory '%s' not found\n" "${2:-.}"
82
+ exit 1
83
+ fi
84
+ PING_URL="${PING_URL%/}"
85
+ export PING_URL
86
+ PASS=0
87
+
88
+ log() { printf "[%s] %b\n" "$(date -u +%H:%M:%S)" "$*"; }
89
+ pass() { log "${GREEN}PASSED${NC} -- $1"; PASS=$((PASS + 1)); }
90
+ fail() { log "${RED}FAILED${NC} -- $1"; }
91
+ hint() { printf " ${YELLOW}Hint:${NC} %b\n" "$1"; }
92
+ stop_at() {
93
+ printf "\n"
94
+ printf "${RED}${BOLD}Validation stopped at %s.${NC} Fix the above before continuing.\n" "$1"
95
+ exit 1
96
+ }
97
+
98
+ printf "\n"
99
+ printf "${BOLD}========================================${NC}\n"
100
+ printf "${BOLD} OpenEnv Submission Validator${NC}\n"
101
+ printf "${BOLD}========================================${NC}\n"
102
+ log "Repo: $REPO_DIR"
103
+ log "Ping URL: $PING_URL"
104
+ printf "\n"
105
+
106
+ log "${BOLD}Step 1/3: Pinging HF Space${NC} ($PING_URL/reset) ..."
107
+
108
+ CURL_OUTPUT=$(portable_mktemp "validate-curl")
109
+ CLEANUP_FILES+=("$CURL_OUTPUT")
110
+ HTTP_CODE=$(curl -s -o "$CURL_OUTPUT" -w "%{http_code}" -X POST \
111
+ -H "Content-Type: application/json" -d '{}' \
112
+ "$PING_URL/reset" --max-time 30 2>"$CURL_OUTPUT" || printf "000")
113
+
114
+ if [ "$HTTP_CODE" = "200" ]; then
115
+ pass "HF Space is live and responds to /reset"
116
+ elif [ "$HTTP_CODE" = "000" ]; then
117
+ fail "HF Space not reachable (connection failed or timed out)"
118
+ hint "Check your network connection and that the Space is running."
119
+ hint "Try: curl -s -o /dev/null -w '%%{http_code}' -X POST $PING_URL/reset"
120
+ stop_at "Step 1"
121
+ else
122
+ fail "HF Space /reset returned HTTP $HTTP_CODE (expected 200)"
123
+ hint "Make sure your Space is running and the URL is correct."
124
+ hint "Try opening $PING_URL in your browser first."
125
+ stop_at "Step 1"
126
+ fi
127
+
128
+ log "${BOLD}Step 2/3: Running docker build${NC} ..."
129
+
130
+ if ! command -v docker &>/dev/null; then
131
+ fail "docker command not found"
132
+ hint "Install Docker: https://docs.docker.com/get-docker/"
133
+ stop_at "Step 2"
134
+ fi
135
+
136
+ if [ -f "$REPO_DIR/Dockerfile" ]; then
137
+ DOCKER_CONTEXT="$REPO_DIR"
138
+ elif [ -f "$REPO_DIR/server/Dockerfile" ]; then
139
+ DOCKER_CONTEXT="$REPO_DIR/server"
140
+ else
141
+ fail "No Dockerfile found in repo root or server/ directory"
142
+ stop_at "Step 2"
143
+ fi
144
+
145
+ log " Found Dockerfile in $DOCKER_CONTEXT"
146
+
147
+ BUILD_OK=false
148
+ BUILD_OUTPUT=$(run_with_timeout "$DOCKER_BUILD_TIMEOUT" docker build "$DOCKER_CONTEXT" 2>&1) && BUILD_OK=true
149
+
150
+ if [ "$BUILD_OK" = true ]; then
151
+ pass "Docker build succeeded"
152
+ else
153
+ fail "Docker build failed (timeout=${DOCKER_BUILD_TIMEOUT}s)"
154
+ printf "%s\n" "$BUILD_OUTPUT" | tail -20
155
+ stop_at "Step 2"
156
+ fi
157
+
158
+ log "${BOLD}Step 3/3: Running openenv validate${NC} ..."
159
+
160
+ if ! command -v openenv &>/dev/null; then
161
+ fail "openenv command not found"
162
+ hint "Install it: pip install openenv-core"
163
+ stop_at "Step 3"
164
+ fi
165
+
166
+ VALIDATE_OK=false
167
+ VALIDATE_OUTPUT=$(cd "$REPO_DIR" && openenv validate 2>&1) && VALIDATE_OK=true
168
+
169
+ if [ "$VALIDATE_OK" = true ]; then
170
+ pass "openenv validate passed"
171
+ [ -n "$VALIDATE_OUTPUT" ] && log " $VALIDATE_OUTPUT"
172
+ else
173
+ fail "openenv validate failed"
174
+ printf "%s\n" "$VALIDATE_OUTPUT"
175
+ stop_at "Step 3"
176
+ fi
177
+
178
+ printf "\n"
179
+ printf "${BOLD}========================================${NC}\n"
180
+ printf "${GREEN}${BOLD} All 3/3 checks passed!${NC}\n"
181
+ printf "${GREEN}${BOLD} Your submission is ready to submit.${NC}\n"
182
+ printf "${BOLD}========================================${NC}\n"
183
+ printf "\n"
184
+
185
+ exit 0