File size: 32,270 Bytes
ad6248e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
"""
All 10 agent tools β€” implemented as plain Python functions wrapped in ToolDispatcher.

Each tool returns (reward_delta: float, done: bool, output: Any).
The EpisodeManager calls ToolDispatcher.dispatch(tool, params).
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any, Dict, Tuple

if TYPE_CHECKING:
    from app.engine.manager import EpisodeManager


# ---------------------------------------------------------------------------
# Schema exposed to the LLM (OpenEnv tool_spec format)
# ---------------------------------------------------------------------------

TOOL_SPECS = [
    {
        "name": "view_file",
        "description": (
            "Read the contents of a file in a service codebase. "
            "Use this BEFORE editing to understand the code."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "service":  {"type": "string", "enum": ["ad_ranking", "capi_pipeline", "whatsapp_sync"]},
                "filename": {"type": "string", "description": "e.g. ranker.py"},
            },
            "required": ["service", "filename"],
        },
    },
    {
        "name": "edit_line",
        "description": (
            "Replace a single line in a file. SURGICAL edits only β€” "
            "do NOT rewrite whole functions. One line at a time."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "service":     {"type": "string"},
                "filename":    {"type": "string"},
                "line_number": {"type": "integer", "description": "1-based line number"},
                "new_code":    {"type": "string", "description": "Replacement line (preserve indentation)"},
            },
            "required": ["service", "filename", "line_number", "new_code"],
        },
    },
    {
        "name": "run_tests",
        "description": (
            "Execute a test suite for a service. "
            "suite options: 'unit' (fast, 1 step), "
            "'integration' (2 steps), 'load' (3 steps), 'security' (2 steps)."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "service": {"type": "string"},
                "suite":   {"type": "string", "enum": ["unit", "integration", "load", "security"],
                            "default": "unit"},
            },
            "required": ["service"],
        },
    },
    {
        "name": "check_dependency",
        "description": "Show the data-flow relationship between two services.",
        "parameters": {
            "type": "object",
            "properties": {
                "service_a": {"type": "string"},
                "service_b": {"type": "string"},
            },
            "required": ["service_a", "service_b"],
        },
    },
    {
        "name": "read_logs",
        "description": "Pull recent logs for a service filtered by log level.",
        "parameters": {
            "type": "object",
            "properties": {
                "service":      {"type": "string"},
                "log_level":    {"type": "string", "enum": ["ERROR", "WARN", "INFO", "DEBUG"],
                                 "default": "ERROR"},
                "last_n_lines": {"type": "integer", "default": 20},
            },
            "required": ["service"],
        },
    },
    {
        "name": "git_blame",
        "description": "Find who/what last changed a specific line β€” reveals AI-generated code.",
        "parameters": {
            "type": "object",
            "properties": {
                "service":     {"type": "string"},
                "filename":    {"type": "string"},
                "line_number": {"type": "integer"},
            },
            "required": ["service", "filename", "line_number"],
        },
    },
    {
        "name": "rollback",
        "description": (
            "Roll back a service's database migration by version string. "
            "HIGH COST β€” use only when a bad migration is the root cause."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "service": {"type": "string"},
                "version": {"type": "string", "description": "Migration version, e.g. '003'"},
            },
            "required": ["service", "version"],
        },
    },
    {
        "name": "query_metrics_history",
        "description": "Show how a metric changed over time β€” reveals when the problem started.",
        "parameters": {
            "type": "object",
            "properties": {
                "service":    {"type": "string"},
                "metric":     {"type": "string",
                               "enum": ["cpu_percent", "memory_mb", "error_rate",
                                        "p99_latency_ms", "request_queue"]},
                "hours_back": {"type": "integer", "default": 6},
            },
            "required": ["service", "metric"],
        },
    },
    {
        "name": "ask_senior_sre",
        "description": (
            "Ask the on-call Senior SRE for a hint. "
            "Costs 2 reward steps. Use when genuinely stuck."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "question": {"type": "string"},
            },
            "required": ["question"],
        },
    },
    {
        "name": "write_incident_report",
        "description": (
            "Close the incident by submitting a post-mortem report. "
            "MUST be called after fixing the bug to end the episode."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "root_cause":             {"type": "string"},
                "fix_applied":            {"type": "string"},
                "services_affected":      {"type": "array", "items": {"type": "string"}},
                "severity_classification": {"type": "string", "enum": ["P0", "P1", "P2"]},
            },
            "required": ["root_cause", "fix_applied", "services_affected", "severity_classification"],
        },
    },
]


# ---------------------------------------------------------------------------
# Per-task contextual log data
# ---------------------------------------------------------------------------

_TASK_LOGS: Dict[int, Dict[str, Dict[str, str]]] = {
    1: {
        "ad_ranking": {
            "ERROR": (
                "[2026-04-24 03:14:21] ERROR ad_ranking.ranker: "
                "AttributeError: 'dict' object has no attribute 'get_clicks'\n"
                "  File ranker.py, line 22, in score_ads\n"
                "  click_rate = ad.get_clicks() / max(ad.get('impressions', 1), 1)\n"
                "[2026-04-24 03:14:22] ERROR ad_ranking.ranker: same error (x487 in last 60s)"
            ),
            "DEBUG": (
                "[2026-04-24 03:14:20] DEBUG ad_ranking.ranker: fetch_candidate_ads returned 12 ads\n"
                "[2026-04-24 03:14:21] DEBUG ad_ranking.ranker: entering score_ads with 12 ads\n"
                "[2026-04-24 03:14:21] DEBUG ad_ranking.ranker: processing ad_id=ad_001 β€” CRASH"
            ),
        },
    },
    2: {
        "capi_pipeline": {
            "WARN": (
                "[2026-04-24 03:00:05] WARN capi_pipeline.transformer: "
                "event_time 1700000000 converted to 1700000 β€” check threshold\n"
                "[2026-04-24 03:00:05] WARN capi_pipeline.transformer: "
                "event_time 1745392000 converted to 1745392 β€” data from 1970-01-20"
            ),
            "DEBUG": (
                "[2026-04-24 02:14:03] DEBUG capi_pipeline.transformer: "
                "_normalize_timestamp called with ts=1700000000\n"
                "[2026-04-24 02:14:03] DEBUG capi_pipeline.transformer: "
                "ts > 1_000_000_000 β†’ True, returning ts // 1000 = 1700000\n"
                "[2026-04-24 02:14:03] DEBUG capi_pipeline.transformer: "
                "EXPECTED: ts > 1_000_000_000_000 for millisecond timestamps"
            ),
            "ERROR": "[2026-04-24 03:00:00] INFO capi_pipeline: No errors β€” pipeline healthy",
        },
        "ad_ranking": {
            "WARN": (
                "[2026-04-24 03:01:00] WARN ad_ranking.ranker: "
                "ROAS attribution window: events from 1970-01-20 (expected: 2023+)\n"
                "[2026-04-24 03:01:01] WARN ad_ranking.attribution: "
                "Conversion events all timestamped <86400 (one day in 1970)"
            ),
        },
    },
    3: {
        "whatsapp_sync": {
            "ERROR": (
                "[2026-04-24 03:10:00] ERROR whatsapp_sync.handler: "
                "asyncpg.exceptions.TooManyConnectionsError: pool exhausted\n"
                "[2026-04-24 03:10:02] ERROR whatsapp_sync.handler: "
                "sync_user_messages acquire() blocked for user_id=8841923\n"
                "[2026-04-24 03:10:05] ERROR whatsapp_sync.handler: "
                "490/500 connections allocated β€” 0 available"
            ),
            "DEBUG": (
                "[2026-04-24 03:09:00] DEBUG whatsapp_sync.handler: "
                "sync_user_messages β€” db_pool.acquire() called\n"
                "[2026-04-24 03:09:00] DEBUG whatsapp_sync.handler: "
                "sync_user_messages β€” conn acquired, fetching messages\n"
                "[2026-04-24 03:09:00] DEBUG whatsapp_sync.handler: "
                "sync_user_messages β€” messages fetched, returning\n"
                "NOTE: No 'release' log line β€” connection never returned to pool"
            ),
        },
    },
    4: {
        "whatsapp_sync": {
            "ERROR": (
                "[2026-04-24 02:14:31] ERROR whatsapp_sync.db: "
                "asyncpg.ForeignKeyViolationError: "
                "insert into user_preferences violates FK constraint\n"
                "[2026-04-24 02:14:31] ERROR whatsapp_sync.db: "
                "migration 003 failed β€” circular FK: messages ↔ message_threads\n"
                "[2026-04-24 02:14:31] ERROR whatsapp_sync.db: "
                "ALTER TABLE messages failed β€” message_threads.id referenced before table commit"
            ),
        },
        "ad_ranking": {
            "ERROR": (
                "[2026-04-24 02:15:00] ERROR ad_ranking: "
                "DB pool returning FK violation errors from upstream\n"
                "[2026-04-24 02:15:01] WARN ad_ranking: "
                "This is a SYMPTOM β€” root cause is in whatsapp_sync migration"
            ),
        },
        "capi_pipeline": {
            "WARN": (
                "[2026-04-24 02:15:00] WARN capi_pipeline: "
                "Event association latency +340ms β€” DB pool contention\n"
                "[2026-04-24 02:15:00] WARN capi_pipeline: "
                "This is a SYMPTOM β€” root cause is in whatsapp_sync migration"
            ),
        },
    },
    5: {
        "capi_pipeline": {
            "DEBUG": (
                "[2026-04-24 02:00:00] DEBUG capi_pipeline.ingestor: "
                "DEBUG_MODE=True β€” including raw payload in response\n"
                "[2026-04-24 02:00:00] DEBUG capi_pipeline.ingestor: "
                "Response size: 14,382 bytes (expected ~48 bytes)\n"
                "[2026-04-24 02:00:01] DEBUG capi_pipeline.ingestor: "
                "debug_data.user_emails contains plaintext email fields"
            ),
            "ERROR": "[2026-04-24 02:00:00] INFO capi_pipeline: No errors β€” unit tests all pass",
        },
    },
}

_METRICS_HISTORY: Dict[str, Dict[str, list]] = {
    "ad_ranking:error_rate": [
        (0, 0.0), (1, 0.0), (2, 0.0), (3, 12.3), (4, 12.1), (5, 11.9),
    ],
    "capi_pipeline:error_rate": [
        (0, 0.0), (1, 0.0), (2, 0.0), (3, 0.0), (4, 0.0), (5, 0.0),
    ],
    "whatsapp_sync:memory_mb": [
        (0, 200), (1, 250), (2, 350), (3, 500), (4, 800), (5, 1200),
    ],
    "whatsapp_sync:request_queue": [
        (0, 5), (1, 45), (2, 130), (3, 280), (4, 420), (5, 490),
    ],
    "capi_pipeline:p99_latency_ms": [
        (0, 20), (1, 20), (2, 21), (3, 1100), (4, 1080), (5, 1090),
    ],
}


# ---------------------------------------------------------------------------
# Senior SRE hints β€” contextually aware
# ---------------------------------------------------------------------------

def _senior_sre_hint(task_id: int, question: str, sre_memory: list, step: int) -> str:
    question_lower = question.lower()
    memory_text = " ".join(sre_memory).lower()

    if task_id == 1:
        if "get_clicks" in memory_text or "attributeerror" in question_lower:
            return (
                "Senior SRE: The AttributeError is very specific β€” 'dict' has no method "
                "'get_clicks'. The ad objects coming from the API are plain Python dicts. "
                "You need dict accessor syntax, not method call syntax. "
                "Check line 22 of ranker.py."
            )
        return (
            "Senior SRE: Look at the stack trace carefully. "
            "The error is on the line that computes click_rate. "
            "How are you accessing the 'clicks' field on the ad object?"
        )

    if task_id == 2:
        if "timestamp" in memory_text or "1970" in question_lower or "normalize" in question_lower:
            return (
                "Senior SRE: The timestamp normalisation logic has an off-by-three-orders-of-magnitude "
                "bug. A Unix second timestamp is ~10 digits. A Unix millisecond timestamp is ~13 digits. "
                "The condition in _normalize_timestamp() uses the wrong threshold. "
                "What number has 13 digits?"
            )
        if "capi" in memory_text or "capi" in question_lower:
            return (
                "Senior SRE: You're on the right track β€” CAPI is the data source for ad attribution. "
                "Check the transformer.py file. The event_time values being emitted are wrong β€” "
                "they look like they're in 1970. Where does event_time get processed?"
            )
        return (
            "Senior SRE: The ad ranking ROAS drop is NOT a ranking algorithm bug. "
            "The ranking model is working correctly β€” it just has bad input data. "
            "Follow the data upstream. Where do conversion events come from?"
        )

    if task_id == 3:
        if "finally" in memory_text or "release" in question_lower or "pool" in question_lower:
            return (
                "Senior SRE: Yes β€” the connection pool is exhausted because connections are "
                "acquired but never released. In Python async code, you MUST release connections "
                "in a 'finally' block, otherwise an exception will skip the release call entirely. "
                "Add: finally: await self.db_pool.release(conn)"
            )
        return (
            "Senior SRE: The load test shows pool exhaustion. "
            "Under normal load each sync call is short so you don't notice. "
            "Under high load, the missing resource cleanup compounds. "
            "Look at how sync_user_messages() handles its DB connection lifecycle."
        )

    if task_id == 4:
        if step > 3 and "migration" not in memory_text:
            return (
                "Senior SRE (impatient): Stop chasing symptoms! All three services degraded "
                "simultaneously at 02:14 UTC β€” that's when the last deploy landed. "
                "Check the DB migration logs. The whatsapp_sync service ran a new migration "
                "at that exact time. Look at db.py migration 003."
            )
        if "migration" in memory_text or "003" in question_lower:
            return (
                "Senior SRE: Good, you found migration 003. Look at what it does: "
                "it adds a column 'thread_id' to messages that references message_threads. "
                "But message_threads also references messages. "
                "That's a circular FK β€” PostgreSQL can't resolve the constraint. "
                "Remove the ALTER TABLE statement from migration 003."
            )
        return (
            "Senior SRE: Three services failing simultaneously at 02:14 UTC is not a coincidence. "
            "Check the deploy logs and DB migration history for that exact timestamp."
        )

    if task_id == 5:
        if "debug" in memory_text or "pii" in question_lower or "response" in question_lower:
            return (
                "Senior SRE: DEBUG_MODE = True should never reach production. "
                "Find that flag in the ingestor and disable it. "
                "The security test will verify the response body no longer contains 'debug_data'."
            )
        if step > 2:
            return (
                "Senior SRE: The unit tests pass β€” that's the trap. This is a security bug "
                "invisible to unit tests. Run the security test suite instead: "
                "run_tests('capi_pipeline', 'security'). "
                "Read the DEBUG logs for the ingestor β€” you'll see the response sizes."
            )
        return (
            "Senior SRE: Something is leaking data in the CAPI ingestor. "
            "Response sizes are 70x larger than expected. "
            "What conditions cause a larger response body?"
        )

    return "Senior SRE: Check the logs and follow the data flow upstream."


# ---------------------------------------------------------------------------
# Tool Dispatcher
# ---------------------------------------------------------------------------

class ToolDispatcher:

    def __init__(self, episode: "EpisodeManager"):
        self.ep = episode

    def dispatch(self, tool: str, params: Dict[str, Any]) -> Tuple[float, bool, Any]:
        """Route to the correct tool. Returns (reward_delta, done, output)."""
        handlers = {
            "view_file":             self._view_file,
            "edit_line":             self._edit_line,
            "run_tests":             self._run_tests,
            "check_dependency":      self._check_dependency,
            "read_logs":             self._read_logs,
            "git_blame":             self._git_blame,
            "rollback":              self._rollback,
            "query_metrics_history": self._query_metrics_history,
            "ask_senior_sre":        self._ask_senior_sre,
            "write_incident_report": self._write_incident_report,
        }
        fn = handlers.get(tool)
        if fn is None:
            r = self.ep.reward.step_reward(tool)
            return r, False, f"Unknown tool: {tool}"
        return fn(params)

    # ------------------------------------------------------------------
    # 1. view_file
    # ------------------------------------------------------------------
    def _view_file(self, p: Dict) -> Tuple[float, bool, Any]:
        service  = p.get("service", "")
        filename = p.get("filename", "")
        found, content = self.ep.vfs.read_file(service, filename)

        if not found:
            r = self.ep.reward.step_reward("view_file")
            return r, False, {"error": content}

        lines = content.splitlines()
        numbered = "\n".join(f"{i+1:4d}  {line}" for i, line in enumerate(lines))

        # Intermediate reward: opening the right file
        task_def = {
            1: ("ad_ranking", "ranker.py"),
            2: ("capi_pipeline", "transformer.py"),
            3: ("whatsapp_sync", "handler.py"),
            4: ("whatsapp_sync", "db.py"),
            5: ("capi_pipeline", "ingestor.py"),
        }.get(self.ep._task_id)

        r = self.ep.reward.step_reward("view_file")
        if task_def and (service, filename) == task_def:
            bonus = self.ep.reward.progress_reward("file_found")
            r += bonus
            self.ep.add_memory(f"opened root-cause file {service}/{filename}")

        return r, False, {
            "service":      service,
            "filename":     filename,
            "total_lines":  len(lines),
            "content":      numbered,
        }

    # ------------------------------------------------------------------
    # 2. edit_line
    # ------------------------------------------------------------------
    def _edit_line(self, p: Dict) -> Tuple[float, bool, Any]:
        service     = p.get("service", "")
        filename    = p.get("filename", "")
        line_number = int(p.get("line_number", 0))
        new_code    = p.get("new_code", "")

        # Anti-cheat: SREs cannot modify test suites during an incident.
        # Prevents reward hacking (e.g. deleting asserts to make tests pass).
        PROTECTED = ("tests/", "test_", "_test.py", "conftest.py")
        if any(guard in filename for guard in PROTECTED):
            r = self.ep.reward.step_reward("edit_line", syntax_error=True)
            return r, False, {
                "error": (
                    "Error: SREs cannot modify test suites during an incident. "
                    "Fix the source code, not the tests."
                )
            }

        success, msg = self.ep.vfs.edit_line(
            service, filename, line_number, new_code, self.ep._step
        )
        if not success:
            r = self.ep.reward.step_reward("edit_line")
            return r, False, {"error": msg}

        # Syntax check: look for obvious Python syntax errors in the new line
        syntax_error = _has_syntax_error(new_code)
        r = self.ep.reward.step_reward("edit_line", syntax_error=syntax_error)

        self.ep.add_memory(
            f"edited {service}/{filename} line {line_number}: "
            f"{new_code[:60]!r}"
        )

        msg_out = f"Line {line_number} updated."
        if syntax_error:
            msg_out += " WARNING: possible syntax error detected in replacement line."

        return r, False, {"result": msg_out, "syntax_warning": syntax_error}

    # ------------------------------------------------------------------
    # 3. run_tests
    # ------------------------------------------------------------------
    def _run_tests(self, p: Dict) -> Tuple[float, bool, Any]:
        service = p.get("service", "")
        suite   = p.get("suite", "unit")

        # Suite cost (extra step penalties)
        suite_cost = {"unit": 0, "integration": -0.1, "load": -0.2, "security": -0.1}
        extra_cost = suite_cost.get(suite, 0)

        passed, output, partial = self.ep.grader.run(self.ep._task_id, suite)
        r = self.ep.reward.step_reward("run_tests") + extra_cost

        self.ep._last_terminal = output
        self.ep.add_memory(f"ran {suite} tests for {service}: {'PASS' if passed else 'FAIL'}")

        if passed:
            self.ep.metrics.mark_fixed(service)
            r += self.ep.reward.progress_reward("error_drop")

        return r, False, {"passed": passed, "suite": suite, "output": output}

    # ------------------------------------------------------------------
    # 4. check_dependency
    # ------------------------------------------------------------------
    def _check_dependency(self, p: Dict) -> Tuple[float, bool, Any]:
        from app.engine.manager import DEPENDENCY_GRAPH
        a = p.get("service_a", "")
        b = p.get("service_b", "")
        deps_a = DEPENDENCY_GRAPH.get(a, [])
        deps_b = DEPENDENCY_GRAPH.get(b, [])

        r = self.ep.reward.step_reward("check_dependency")

        relationship = "no direct dependency"
        if b in deps_a:
            relationship = f"{a} depends on {b} (data flows: {b} β†’ {a})"
            self.ep.add_memory(f"confirmed: {a} depends on {b}")
            r += self.ep.reward.progress_reward("service_id")
        elif a in deps_b:
            relationship = f"{b} depends on {a} (data flows: {a} β†’ {b})"
        return r, False, {
            "service_a":      a,
            "service_b":      b,
            "relationship":   relationship,
            f"{a}_depends_on": deps_a,
            f"{b}_depends_on": deps_b,
        }

    # ------------------------------------------------------------------
    # 5. read_logs
    # ------------------------------------------------------------------
    def _read_logs(self, p: Dict) -> Tuple[float, bool, Any]:
        service   = p.get("service", "")
        log_level = p.get("log_level", "ERROR")
        n         = int(p.get("last_n_lines", 20))

        task_logs = _TASK_LOGS.get(self.ep._task_id, {})
        svc_logs  = task_logs.get(service, {})
        log_text  = svc_logs.get(log_level, f"[{log_level}] No {log_level} logs for {service}")

        r = self.ep.reward.step_reward("read_logs")
        self.ep.add_memory(f"read {log_level} logs for {service}")

        # Partial reward for reading the right service's debug/error logs
        right_service = {
            1: "ad_ranking", 2: "capi_pipeline", 3: "whatsapp_sync",
            4: "whatsapp_sync", 5: "capi_pipeline",
        }.get(self.ep._task_id)
        if service == right_service and log_level in ("DEBUG", "ERROR"):
            r += self.ep.reward.progress_reward("service_id")

        return r, False, {"service": service, "log_level": log_level, "logs": log_text}

    # ------------------------------------------------------------------
    # 6. git_blame
    # ------------------------------------------------------------------
    def _git_blame(self, p: Dict) -> Tuple[float, bool, Any]:
        service     = p.get("service", "")
        filename    = p.get("filename", "")
        line_number = int(p.get("line_number", 1))

        blame = self.ep.vfs.git_blame(service, filename, line_number)
        r = self.ep.reward.step_reward("git_blame")
        self.ep.add_memory(f"git blame {service}/{filename}:{line_number}")
        return r, False, {"blame": blame}

    # ------------------------------------------------------------------
    # 7. rollback
    # ------------------------------------------------------------------
    def _rollback(self, p: Dict) -> Tuple[float, bool, Any]:
        service = p.get("service", "")
        version = p.get("version", "")

        # Only valid for Task 4 and correct service/version
        is_correct = (
            self.ep._task_id == 4 and
            service == "whatsapp_sync" and
            version == "003"
        )

        if is_correct:
            # Remove the circular FK from the VFS (simulate rollback)
            _, content = self.ep.vfs.read_file("whatsapp_sync", "db.py")
            # Strip migration 003 block
            lines = content.splitlines()
            new_lines = []
            skip = False
            for line in lines:
                if '"version": "003"' in line or "'version': '003'" in line:
                    skip = True
                if skip and line.strip().startswith("}"):
                    skip = False
                    continue
                if not skip:
                    new_lines.append(line)
            self.ep.vfs._files["whatsapp_sync"]["db.py"] = "\n".join(new_lines)
            self.ep.metrics.mark_fixed("whatsapp_sync")
            self.ep.metrics.mark_fixed("ad_ranking")
            self.ep.metrics.mark_fixed("capi_pipeline")
            self.ep.add_memory("rolled back migration 003 β€” circular FK removed")
            r = self.ep.reward.step_reward("rollback")
            r += self.ep.reward.progress_reward("error_drop")
            return r, False, {
                "result": "Migration 003 rolled back successfully. All three services recovering."
            }

        # Wrong rollback β€” penalise
        r = self.ep.reward.step_reward("rollback", syntax_error=False)
        r += self.ep.reward.ROLLBACK_PENALTY  # extra penalty via RewardManager field
        return r, False, {
            "error": (
                f"Rollback of {service} v{version} either unnecessary or incorrect. "
                "Verify the root cause before rolling back."
            )
        }

    # ------------------------------------------------------------------
    # 8. query_metrics_history
    # ------------------------------------------------------------------
    def _query_metrics_history(self, p: Dict) -> Tuple[float, bool, Any]:
        service    = p.get("service", "")
        metric     = p.get("metric", "")
        hours_back = int(p.get("hours_back", 6))

        key = f"{service}:{metric}"
        history = _METRICS_HISTORY.get(key, [])

        r = self.ep.reward.step_reward("query_metrics_history")
        self.ep.add_memory(f"queried {metric} history for {service}")

        if history:
            table = "\n".join(
                f"  T-{hours_back - i}h: {val}" for i, (_, val) in enumerate(history)
            )
            return r, False, {
                "service": service,
                "metric":  metric,
                "history": table,
                "note":    f"Spike visible at T-{hours_back - 3}h (correlates with 02:14 UTC deploy)",
            }
        return r, False, {
            "service": service,
            "metric":  metric,
            "history": "No historical data for this metric combination.",
        }

    # ------------------------------------------------------------------
    # 9. ask_senior_sre
    # ------------------------------------------------------------------
    def _ask_senior_sre(self, p: Dict) -> Tuple[float, bool, Any]:
        question = p.get("question", "")

        hint = _senior_sre_hint(
            self.ep._task_id,
            question,
            self.ep._sre_memory,
            self.ep._step,
        )

        # 2-step penalty
        r = self.ep.reward.step_reward("ask_senior_sre") * 2
        self.ep.add_memory(f"asked senior SRE: {question[:60]}")
        return r, False, {"hint": hint}

    # ------------------------------------------------------------------
    # 10. write_incident_report
    # ------------------------------------------------------------------
    def _write_incident_report(self, p: Dict) -> Tuple[float, bool, Any]:
        from app.models import IncidentReport

        report = IncidentReport(
            root_cause=p.get("root_cause", ""),
            fix_applied=p.get("fix_applied", ""),
            services_affected=p.get("services_affected", []),
            severity_classification=p.get("severity_classification", "P1"),
        )
        self.ep._incident_report = report

        report_accuracy = self.ep.grader.grade_incident_report(self.ep._task_id, report)
        task_def = {1: 15, 2: 20, 3: 20, 4: 25, 5: 20}
        sla = task_def.get(self.ep._task_id, 20)
        within_sla = self.ep._step <= sla

        # Check if tests actually passed
        passed, _, _ = self.ep.grader.run(self.ep._task_id)
        no_regressions = passed

        r = self.ep.reward.step_reward("write_incident_report")
        r += self.ep.reward.terminal_reward(
            tests_passed=passed,
            report_accuracy=report_accuracy,
            fixed_within_sla=within_sla,
            no_regressions=no_regressions,
            task_id=self.ep._task_id,
        )

        summary = (
            f"Incident {self.ep._incident_id} closed.\n"
            f"Report accuracy:  {report_accuracy:.0%}\n"
            f"Tests passed:     {passed}\n"
            f"Within SLA:       {within_sla}\n"
            f"Normalized score: {self.ep.reward.normalized_score():.3f}"
        )

        # Update difficulty controller
        self.ep.dc.update(self.ep._task_id, self.ep.reward.normalized_score())

        return r, True, {"summary": summary, "report_accuracy": report_accuracy}


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _has_syntax_error(line: str) -> bool:
    """Quick heuristic check for obvious Python syntax mistakes in a single line."""
    stripped = line.strip()
    # Unmatched brackets
    for open_, close_ in [("(", ")"), ("[", "]"), ("{", "}")]:
        if stripped.count(open_) != stripped.count(close_):
            return True
    # Ends with lone colon inside dict/call (not a block statement)
    # Detect obvious incomplete assignments
    if re.search(r"=\s*$", stripped):
        return True
    return False