File size: 33,494 Bytes
fe4e0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""shared_handle_abandoned_operations on the coding-template.

Reads like a scoreboard:

- GRADERS is the single list of ALL criteria: (name, weight, blocker, kind,
  timeout); every entry maps to a function in grader/run_grading.sh and to one
  cell of the execution harness (grader/cells, a held-out Rust crate compiled
  against the candidate's own tree through its published surface and driven
  against a real PostgreSQL server in this container). Grading is entirely
  execution-based: every observation is either a count the server itself
  reports, a statement the server accepts or refuses, or an answer the
  candidate's own client gave a concurrent reader. No LLM judge anywhere in the
  loop, no grep for an identifier, nothing that reads the agent's source. The
  subscore you see in the trace viewer is the name you grep for in the grader.
- The task template runs them sequentially over the coding-template's hermetic
  repo lifecycle (vault -> capture diff -> reset -> re-apply). They have to run
  sequentially: they share one workspace, one candidate build and one harness
  run.
- A criterion has three outcomes, not two. PASS and FAIL are verdicts about the
  change; GRADER FAULT is the grader admitting it could not judge (the
  toolchain would not run, the database would not start, the report is
  missing). A fault is never scored as a failed criterion — it cannot cap the
  run — and it is never scored as a met one either, because "break the fixture
  and collect the weight" is otherwise the cheapest way past a hard criterion
  (see `_absolve_faults`). A run with a fault in it comes back with isError set
  and has to be re-run: a number that was not measured is not a measurement.
- LAW G-5: THE GATE IS A CELL, AND IT IS NOT WEIGHTLESS.
  `gate_repo_suite_green_and_tests_untouched` is the last row of GRADERS, it is
  a BLOCKER, and it carries GATE_WEIGHT = 0.0200 — inside the 0.01-0.05 band the
  law allows. A tree that rewrote the repository's own tests, or that left the
  suite red, loses that weight AND takes the flat blocker cap; what it no longer
  does is disappear into a 0.000 produced by a veto that itself carries nothing.
  The ladder reads: gold 1.000, an untouched checkout 0.020 — a number that says
  "the gate ran and passed and nothing else was met", where a bare 0.000 could
  equally mean "the gate never ran at all".

- LAW W-1: THE TICKET HAS TWO PARTS, AND THE SECOND ONE IS ON THE BOARD.
  Part one is the twenty-one cells of the core — the separate cases the change
  has to cover. Part two is the rule the ticket states in plain words, and
  `rule_existing_teardown_kept` is that rule as a criterion: a blocker worth
  0.2500, decided by the bytes of the two teardown paths the ticket names,
  green on the reference solution and green on an independent correct fix.
- LAW G-5" : a criterion that an untouched checkout passes by construction —
  the gate and the rule both — is paid only NEXT TO a green cell of the core.
  The ladder therefore reads gold 1.0000, base 0.0000, noop 0.0000, and no tree
  that met at least one cell changes by a thousandth.

``validate_mode="golden"`` grades the baked /hud/gold.diff instead of the
agent's edits (maintainer-only gold validation).
"""

from __future__ import annotations

from decimal import Decimal
from pathlib import Path

from hud.graders import BashGrader, EvaluationResult, SubScore, combine

from coding import repo as repo_lib
from env import LOGS_DIR, REPO_DIR, VAULT_DIR, WORKSPACE_NOTE, env, _setup

PROMPT = (Path(__file__).parent / "task" / "prompt.md").read_text()
GRADER = "/hud/grader/run_grading.sh"
GOLD_DIFF = Path("/hud/gold.diff")

# On blocker failure the reward is capped FLAT: a shared connection handle that
# keeps growing a pile of server-side objects every time one of its users gives
# up is not shippable however polished the rest is. Any number of failed
# blockers sets the same ceiling — the cap never drops below 0.60, which is the
# rule, and staged subtraction that would push it lower is deliberately not done
# here. The gradient below the cap is preserved, so what separates two wrong
# answers is which criteria they actually met.
BLOCKER_CAP = 0.60

# GATES names every gate criterion. Law G-5: each one is on the board, each one
# is a blocker, and each one carries GATE_WEIGHT — not zero: 0.0200, inside the
# 0.01-0.05 band. The gate still decides whether the board's total is a
# measurement of a fix at all (G3), but it decides it the way every other
# must-be-right criterion does — it blocks (flat cap 0.60) and it earns its
# 0.0200 when the repository's own suite is green and its tests are untouched.
GATE = "gate_repo_suite_green_and_tests_untouched"
GATES = frozenset({GATE})
GATE_WEIGHT = Decimal("0.0200")
GATE_TIMEOUT = 900

# ─── LAW W-1: THE RULE OF THE TICKET IS A WEIGHTED BLOCKER ────────────────
# The ticket has two parts. Part one is the many separate cases the change has
# to cover — the twenty-one cells below. Part two is the rule it may not break,
# written in the ticket in plain words: "keep the existing design: what a
# prepared query or a cursor already does today when it is dropped comes out
# byte for byte unchanged; add the new cleanup beside that path rather than
# reworking it into a shared helper".
#
# That rule is a criterion like any other: it is on the board, it is a blocker,
# it carries 0.2500 (inside the 0.15-0.30 band W-1 allows and under the 0.30
# ceiling of §1.A/B-1), and it is decided by bytes — the text of the two
# teardown paths the ticket names, compared against the pristine checkout. It
# is not a measure of how big the diff is: a tree may add as many lines as it
# likes anywhere, including right beside those paths. It fails only where the
# ticket said it would, when the existing teardown was rewritten or moved.
#
# It is honest by measurement, not by intent: it is GREEN on the reference
# solution and GREEN on an independent correct fix (ctl/alt-w1, 1.0000 twice
# under board v3), so it does not punish a second right answer.
RULE = "rule_existing_teardown_kept"
RULES = frozenset({RULE})
RULE_WEIGHT = Decimal("0.2500")
RULE_TIMEOUT = 120

# G-5-prime, extended to the rule (G-5", ratified 11.09): a criterion that is
# green on an untouched checkout — the gate and the rule both are, by
# construction — earns its weight only NEXT TO a green cell of the core. A tree
# that met nothing collects nothing for having broken nothing, so the ladder
# reads base 0.0000 and noop 0.0000, and no tree that met at least one cell
# moves at all.
CONDITIONAL = GATES | RULES

# ─── ALL graders: name, weight, blocker?, kind, timeout ───────────────────
# Every grader: name == function in run_grading.sh == cell of the harness.
#
# Every criterion is red on an untouched checkout, ONE BY ONE, and that is
# measured rather than asserted: the image refuses to build unless the whole
# board is green on the reference solution and red on the released tree,
# criterion by criterion (Dockerfile.hud, step 10).
#
# WHERE THE WEIGHT IS, AND WHY
#
# The board asks one question at twenty-one sites, and the weights say how much of
# the contract each site is:
#
#   what the server was left holding on          the leaks
#   behalf of an operation nobody is waiting
#   for any more
#
#   whether the other tasks on that same         the conjunctive cells
#   handle can tell it happened
#
# THE WEIGHTS WERE WRITTEN DOWN BEFORE THE NUMBERS. The order they were fixed
# in was: which axis (the ordinary request path, the streaming paths, the
# binding path, the rollback-point path), then each cell's share inside its
# axis. What the reference solution, the obvious one-site fix and the two blind
# shadow solutions then scored under this table is recorded in FREEZE.md §1; no
# weight was moved afterwards, because a table fitted to its own gate measures
# the fitting and not the tree.
#
# BOARD v2. The axis the board is about is the rollback point: eight cells,
# 0.7820 of the mass, each of them measured red on the untouched checkout,
# green on the reference solution, red on both blind shadows and on the obvious
# one-site fix, and red on three of the five live solvers, three runs each,
# BEFORE a weight was written beside it (CELLS.md v2 §1, PREREG.md §2). The
# thirteen cells of the ordinary request path, the streaming paths and the
# binding path are what every one of those five trees already took: they stay
# on the board, because a board that drops what a field agrees on cannot tell a
# tree that met the whole contract from one that met the hard half, but they
# carry 0.1980 between them rather than 0.7800.
#
# The five conjunctive cells (nothing_left_and_concurrent_readers_correct,
# four_abandoning_tasks_and_two_hundred_controls,
# same_with_the_outer_transaction_intact,
# inner_point_gone_with_the_enclosing_one_kept,
# the_name_is_free_for_the_next_nested_transaction) each measure ONE property with the
# other half of the contract held: "nothing was left behind AND the tasks still
# using the handle got right answers". That is one criterion, not two merged: a
# tree that empties the handle by resetting the session takes the first half and
# loses the second, which is exactly the wrong answer they are here to catch.
#
# THE ORDER IS THE EXECUTION ORDER, and it is part of the budget. The blocker
# comes first, so the one candidate build and the one harness run are paid for
# by the criterion that matters most and cached for the rest.
#
# The arithmetic below is enforced at import (see the assertions) and again at
# image build time by test_weights_and_faults.py: the weights sum to 1.0000
# exactly, in Decimal, because a float sum of twenty-two literals is not 1.0 and
# the platform normalises a table that does not sum to one without saying so.
WEIGHTS = {
    # the blocker of the axis, then the rule of the ticket (law W-1),
    # then the rest of the axis, the light legs, and the gate last.
    "abandoned_rollback_point_not_left_set":               Decimal("0.1342"),
    "rule_existing_teardown_kept":                         Decimal("0.2500"),
    "same_with_the_outer_transaction_intact":              Decimal("0.0670"),
    "same_one_level_down":                                 Decimal("0.0596"),
    "automatic_name_at_depth_not_left_set":                Decimal("0.0670"),
    "inner_point_gone_with_the_enclosing_one_kept":        Decimal("0.0819"),
    "the_name_is_free_for_the_next_nested_transaction":    Decimal("0.0745"),
    "a_neighbours_work_survives_the_cleanup":              Decimal("0.0670"),
    "same_when_the_point_carried_a_name":                  Decimal("0.0313"),
    "abandoned_prepare_leaves_no_server_object":           Decimal("0.0223"),
    "same_under_implicit_preparation":                     Decimal("0.0164"),
    "same_under_typed_preparation":                        Decimal("0.0112"),
    "same_under_direct_execution":                         Decimal("0.0089"),
    "abandonment_at_the_first_suspension_point":           Decimal("0.0127"),
    "eight_tasks_on_one_handle":                           Decimal("0.0127"),
    "nothing_left_and_concurrent_readers_correct":         Decimal("0.0164"),
    "four_abandoning_tasks_and_two_hundred_controls":      Decimal("0.0112"),
    "same_text_prepared_again_afterwards":                 Decimal("0.0060"),
    "micro_timeout_boundary":                              Decimal("0.0060"),
    "streaming_upload_path":                               Decimal("0.0074"),
    "streaming_download_path":                             Decimal("0.0074"),
    "abandoned_binding_leaves_no_portal":                  Decimal("0.0089"),
    # Written out as a literal, not as `GATE:`, because calibrate.py,
    # mutprobe.py and test_weights_and_faults.py read these tables with
    # ast.literal_eval — a name they cannot resolve would blind all three.
    "gate_repo_suite_green_and_tests_untouched":           Decimal("0.0200"),
}
# THE BLOCKER, AND WHY IT MOVED IN BOARD v2.
#
# In v1 the blocker was `abandoned_prepare_leaves_no_server_object`. Measured
# under the live five, both blind shadows and the obvious one-site fix, every
# one of those eight trees took it (CELLS.md v2 §4): a criterion nothing fails
# is a criterion that caps nothing, which is to say it was a blocker in name
# only. The blocker is now the plainest statement of the axis that actually
# divides the field — a task gives up on setting a rollback point, and the
# server must not be left holding it. It is worth 0.1800, under the 0.30
# ceiling a blocker may carry: it is
# ONE observation, not a summary of the board,
# and a tree that misses it is capped at 0.60 rather than
# zeroed; the gradient below the cap is what separates two wrong answers.
BLOCKERS = frozenset({
    "abandoned_rollback_point_not_left_set",
    # Law W-1: the rule the ticket states in plain words blocks like any other
    # must-be-right criterion. Two failed blockers do not stack below the cap —
    # the cap is flat — but a tree that broke the rule AND missed the axis is
    # separated from one that only missed the axis by the gradient underneath.
    "rule_existing_teardown_kept",
    "gate_repo_suite_green_and_tests_untouched",
})

# The literal table the platform and every offline tool read. It is written out
# in full rather than generated from WEIGHTS above, because calibrate.py,
# mutprobe.py and test_weights_and_faults.py read it out of this file by AST —
# tasks.py is the one and only place the scoreboard is written down, and a
# computed table would be invisible to all three. The assertions below are what
# keep the two copies from ever drifting apart.
#
# The timeouts: the first criterion pays for the candidate build and for the one
# harness run (the candidate's library, the held-out crate linked against it,
# and twenty-one timing-sensitive cells against a live server), so it gets 900 s;
# every criterion after it reads its cell out of a report that already exists
# and is given 600 s of head-room it never needs.
GRADERS = [
    ("abandoned_rollback_point_not_left_set",               0.1342, True, "bash", 900),
    ("rule_existing_teardown_kept",                         0.2500, True, "bash", 120),
    ("same_with_the_outer_transaction_intact",              0.0670, False, "bash", 600),
    ("same_one_level_down",                                 0.0596, False, "bash", 600),
    ("automatic_name_at_depth_not_left_set",                0.0670, False, "bash", 600),
    ("inner_point_gone_with_the_enclosing_one_kept",        0.0819, False, "bash", 600),
    ("the_name_is_free_for_the_next_nested_transaction",    0.0745, False, "bash", 600),
    ("a_neighbours_work_survives_the_cleanup",              0.0670, False, "bash", 600),
    ("same_when_the_point_carried_a_name",                  0.0313, False, "bash", 600),
    ("abandoned_prepare_leaves_no_server_object",           0.0223, False, "bash", 600),
    ("same_under_implicit_preparation",                     0.0164, False, "bash", 600),
    ("same_under_typed_preparation",                        0.0112, False, "bash", 600),
    ("same_under_direct_execution",                         0.0089, False, "bash", 600),
    ("abandonment_at_the_first_suspension_point",           0.0127, False, "bash", 600),
    ("eight_tasks_on_one_handle",                           0.0127, False, "bash", 600),
    ("nothing_left_and_concurrent_readers_correct",         0.0164, False, "bash", 600),
    ("four_abandoning_tasks_and_two_hundred_controls",      0.0112, False, "bash", 600),
    ("same_text_prepared_again_afterwards",                 0.0060, False, "bash", 600),
    ("micro_timeout_boundary",                              0.0060, False, "bash", 600),
    ("streaming_upload_path",                               0.0074, False, "bash", 600),
    ("streaming_download_path",                             0.0074, False, "bash", 600),
    ("abandoned_binding_leaves_no_portal",                  0.0089, False, "bash", 600),
    ("gate_repo_suite_green_and_tests_untouched",           0.0200, True, "bash", 900),
]

# ─── the scoreboard's arithmetic, checked where it is written ──────────────
# Every one of these has been got wrong in prose while looking right, so they
# are executed on import: a tasks.py that breaks one of them cannot even be
# loaded, let alone deployed.
assert [n for n, _w, _b, _k, _t in GRADERS] == list(WEIGHTS), \
    "GRADERS and WEIGHTS list different criteria, or list them in a different order"
assert all(Decimal(str(w)) == WEIGHTS[n] for n, w, _b, _k, _t in GRADERS), \
    "a weight in GRADERS disagrees with the Decimal table above it"
assert all(b == (n in BLOCKERS) for n, _w, b, _k, _t in GRADERS), \
    "a blocker flag in GRADERS disagrees with BLOCKERS"
assert sum(WEIGHTS.values()) == Decimal("1.0000"), \
    f"the weights sum to {sum(WEIGHTS.values())}, not 1.0000"
assert all(w > 0 for w in WEIGHTS.values()), "a criterion carries no weight"
assert len(WEIGHTS) >= 6, "fewer than six criteria"
# §1.A + B-1: at least one blocker; no single blocker over 0.30; the blocking
# mass at or under 0.75; and what a tree that fails the WORST blocker still
# lands on — min(1.00 - w, cap) — at or above 0.60, so the flat cap is a
# ceiling that board can actually reach rather than a number hiding a lower one.
assert BLOCKERS, "no blocker: a board with nothing that must be right is not a board"
assert all(WEIGHTS[n] <= Decimal("0.30") for n in BLOCKERS), "a blocker is worth more than 0.30"
assert sum(WEIGHTS[n] for n in BLOCKERS) <= Decimal("0.75"), "the blocking mass is over 0.75"
assert min(Decimal("1.00") - max(WEIGHTS[n] for n in BLOCKERS),
           Decimal(str(BLOCKER_CAP))) >= Decimal("0.60"), \
    "a tree that fails one blocker would land below 0.60"
assert BLOCKER_CAP >= 0.60, "the blocker cap is below the floor"
# Law G-5, asserted where it is written: every gate is ON the board, is a
# blocker, and carries a weight in [0.01, 0.05]. The old rule — `assert GATE not
# in WEIGHTS` — is deliberately inverted here.
assert GATES, "no gate: a board with nothing that can void it is not a board"
assert all(g in WEIGHTS for g in GATES), "G-5: a gate is not on the board"
assert all(g in BLOCKERS for g in GATES), "G-5: a gate is not a blocker"
assert all(Decimal("0.01") <= WEIGHTS[g] <= Decimal("0.05") for g in GATES), \
    "G-5: a gate's weight is outside the 0.01-0.05 band"
assert WEIGHTS[GATE] == GATE_WEIGHT, "the gate weight is written twice and they disagree"
assert GRADERS[-1][0] == GATE, "the gate is not the last criterion to run"
# Law W-1, asserted where it is written: the rule of the ticket is ON the board,
# is a blocker, and carries a weight in [0.15, 0.30] — heavy enough to be a rule
# and not a note, light enough that a tree which broke only it still lands on
# the 0.60 floor.
assert RULES, "W-1: a part-two rule was declared and is not on the board"
assert all(r in WEIGHTS for r in RULES), "W-1: a rule is not on the board"
assert all(r in BLOCKERS for r in RULES), "W-1: a rule is not a blocker"
assert all(Decimal("0.15") <= WEIGHTS[r] <= Decimal("0.30") for r in RULES), \
    "W-1: a rule's weight is outside the 0.15-0.30 band"
assert WEIGHTS[RULE] == RULE_WEIGHT, "the rule weight is written twice and they disagree"
assert GRADERS[1][0] == RULE, "the rule is not the second criterion to run"
assert not (GATES & RULES), "a criterion is both a gate and a rule"
# What the ladder must read, stated as arithmetic rather than as prose: an
# untouched checkout earns exactly the gates' weight, because the gates are the
# only criteria it can meet.
GATE_MASS = sum(WEIGHTS[g] for g in GATES)
assert GATE_MASS == Decimal("0.0200"), "the gate mass moved without the ladder moving with it"
# ... and under G-5" the same is true of the rule: green on an untouched
# checkout, paid only next to a green cell of the core, so base is 0.0000 and
# not GATE_MASS + RULE_MASS.
RULE_MASS = sum(WEIGHTS[r] for r in RULES)
assert RULE_MASS == Decimal("0.2500"), "the rule mass moved without the ladder moving with it"
CORE = [n for n, _w, _b, _k, _t in GRADERS if n not in CONDITIONAL]
assert len(CORE) == 21, f"the core of the board is {len(CORE)} cells, not 21"
assert sum(WEIGHTS[n] for n in CORE) == Decimal("0.7300"), "the core mass moved"


# ─── grading machinery ─────────────────────────────────────────────────────


# run_grading.sh exits 3 when the grader could not judge — a toolchain that
# would not run, a database that would not start, a missing report, its own
# budget running out. It is not a verdict about the change.
GRADER_FAULT_EXIT = 3


def _absolve_faults(subscores) -> dict[str, str]:
    """Take every criterion the grader could not judge off the agent's bill.

    A fault used to reach the platform as an ordinary non-zero exit, which is to
    say as a failed criterion, which is to say — for the blocking ones — as a
    capped reward. That is a verdict about the grader's machine reported as a
    verdict about the tree.

    So a faulted criterion is STRUCK FROM THE BLOCKER SET — the grader broke, so
    it cannot cap anything — and the whole result is returned with isError set,
    because a run with a fault in it has not been measured and a number that was
    not measured must not be read as one. Re-run it.

    What it is NOT is scored 1.0. "Break the grader's fixture and collect the
    weight" is a strictly better strategy than meeting the criterion whenever
    the criterion is hard, and isError does not close it: the platform publishes
    the reward with isError already set. Here the fixture is a crate compiled
    against the library the agent edits, driven against a server in the same
    container, so the channel is real: a tree that removed the published surface
    the cells drive, or that wedged the database, would make every criterion
    unjudgeable if a fault paid.

    So: a faulted criterion is scored 0.0 and its weight is simply not earned.
    The normalised figure §5.3 asks for — what the run scored over the weight
    that WAS measured — is computed and reported in the info block, because it
    is the number a human re-reading the trace wants; it is deliberately not the
    reward, because renormalising also pays for a broken fixture.
    """
    faults: dict[str, str] = {}
    for score in subscores:
        info = score.info or {}
        if info.get("timed_out"):
            why = f"the criterion did not finish inside {info.get('timeout')}s"
        elif info.get("exit_code") == GRADER_FAULT_EXIT:
            why = _fault_reason(info.get("stdout") or "")
        else:
            continue
        faults[score.name] = why
        score.value = 0.0
        # The subscore now reads red, so it has to say why in the one place a
        # reader of the trace will look next: it is not a failed criterion.
        score.info = {**info, "grader_fault": why,
                      "note": "NOT MEASURED, not failed: the grader could not judge "
                              "this criterion. It cannot cap the run (it is struck "
                              "from the blocker set) and it earns nothing. The run "
                              "is flagged isError and has to be re-run."}
    return faults


def _measured_scale(subscores, faults) -> tuple[float, float]:
    """(weight that was measured, reward expressed over that weight).

    Reported, never returned as the reward — see `_absolve_faults`.
    """
    weights = {name: weight for name, weight, _b, _k, _t in GRADERS}
    measured = sum(w for n, w in weights.items() if n not in faults)
    if measured <= 0:
        return 0.0, 0.0
    earned = sum(
        weights[s.name] * s.value for s in subscores
        if s.name in weights and s.name not in faults
    )
    return measured, earned / measured


def _fault_reason(stdout: str) -> str:
    for line in reversed(stdout.splitlines()):
        stripped = line.strip().lstrip("| ").strip()
        if stripped.startswith("GRADER FAULT"):
            return stripped[:300]
    return "the grader reported a fault with no reason in its tail"


def _slim_metadata(subscores) -> None:
    """Bound subscore metadata so the grade frame stays small."""
    for score in subscores:
        meta = getattr(score, "metadata", None)
        if not meta:
            continue
        params = meta.get("_parameters")
        if isinstance(params, dict):
            for key in ("answer", "question"):
                if key in params and isinstance(params[key], str) and len(params[key]) > 300:
                    params[key] = f"({key} elided; {len(params[key])} chars)"
        for key in ("stdout", "stderr"):
            value = meta.get(key)
            if isinstance(value, str) and len(value) > 2500:
                meta[key] = "…" + value[-2500:]


async def _grade(validate_mode: str | None) -> EvaluationResult:
    setup_commit = await repo_lib.restore_history(REPO_DIR, VAULT_DIR)
    if validate_mode == "golden":
        diff = GOLD_DIFF.read_text()
    else:
        diff = await repo_lib.capture_agent_diff(REPO_DIR, setup_commit)

    await repo_lib.reset_worktree(REPO_DIR, setup_commit)
    apply_error = await repo_lib.apply_diff(REPO_DIR, diff, LOGS_DIR / "patch.diff")
    if apply_error is not None:
        return EvaluationResult(
            reward=0.0, content="patch failed to apply", info={"git_apply": apply_error}
        )

    subscores: list[SubScore] = []
    for name, weight, _blocker, _kind, timeout in GRADERS:
        subscores.append(
            await BashGrader.grade(
                weight,
                name=name,
                # The criterion's timeout is passed to the grader, which fits
                # every subprocess inside the hidden checks into it. One number,
                # read from one table, so the grader's budget and the timeout
                # the platform enforces cannot drift apart.
                command=f"bash {GRADER} {name} {timeout}",
                cwd=str(REPO_DIR),
                timeout_seconds=timeout,
            )
        )

    # Law G-5: there is no separate gate run. The gate is the last row of
    # GRADERS, it was graded in the loop above off the same build, and it is
    # combined with everything else.
    faults = _absolve_faults(subscores)

    # G-5-prime: гейт зелен только рядом с зелёной клеткой. Гейт, который
    # проходит на нетронутом checkout, иначе платит за пустой diff, и лестница
    # читает base/noop как массу гейта вместо 0.000. Ни одной измеренной
    # не-гейтовой клетки в зелёном => гейт зарабатывает ноль (и, как блокер,
    # кладёт итог на кап, который на пустом дереве и без того ноль).
    # G-5" (11.09): the same arithmetic now covers the rule of the ticket. Both
    # the gate and the rule are GREEN on an untouched checkout by construction —
    # a tree that changed nothing broke no test and rewrote no teardown — so
    # either would otherwise pay 0.2700 for doing nothing at all.
    _G5P_CONDITIONAL = ("gate_repo_suite_green_and_tests_untouched",
                        "rule_existing_teardown_kept")
    _g5p_cells = [s for s in subscores
                  if s.name not in _G5P_CONDITIONAL and s.name not in faults]
    if _g5p_cells and not any(s.value > 0.0 for s in _g5p_cells):
        for _g5p in subscores:
            if _g5p.name in _G5P_CONDITIONAL and _g5p.value > 0.0:
                _g5p.value = 0.0
                _key = "rule_vacuous" if _g5p.name.startswith("rule_") else "g5_prime"
                _g5p.info = {**(_g5p.info or {}), _key:
                             "this criterion earns nothing on a tree that met no "
                             "cell of the core: a green gate, or a rule nothing "
                             "broke, on an empty change is weight for doing "
                             "nothing"}
    _slim_metadata(subscores)
    result = await combine(*subscores)

    failed = sorted(
        (name, weight)
        for name, weight, blocker, _kind, _t in GRADERS
        if blocker
        and name not in faults
        and next(s.value for s in subscores if s.name == name) < 1.0
    )
    unproven = sorted(n for n, _w, blocker, _k, _t in GRADERS if blocker and n in faults)

    if faults:
        measured_weight, over_measured = _measured_scale(subscores, faults)
        all_faults = dict(faults)
        capped = bool(failed) or bool(unproven)
        return EvaluationResult(
            reward=result.reward if not capped
            else max(0.0, min(result.reward, BLOCKER_CAP)),
            subscores=result.subscores,
            isError=True,
            info={
                **result.info,
                "grader_faults": all_faults,
                "failed_blockers": [n for n, _w in failed],
                "unproven_blockers": unproven,
                "unproven_gates": [g for g in sorted(GATES) if g in faults],
                "measured_weight": round(measured_weight, 4),
                "reward_over_measured_weight": round(over_measured, 4),
            },
            content=(
                "GRADER FAULT: this run was not graded. "
                + "; ".join(f"{name}: {why}" for name, why in all_faults.items())
                + ". A fault is the grader failing to judge, not the change failing "
                "a criterion: nothing here is reported as a failed criterion. It is "
                "not reported as a met one either — a criterion that was not measured "
                "earns nothing, and a blocker or a gate that was not measured keeps "
                f"the {BLOCKER_CAP:.2f} ceiling on"
                + (f" ({', '.join(unproven)} was not proven)" if unproven else "")
                + f". {measured_weight:.2f} of the 1.00 was measured, and over that "
                f"weight the run scored {over_measured:.3f}. This run has to be "
                "re-run; do not read the reward as a measurement."
            ),
        )

    if failed:
        reward = max(0.0, min(result.reward, BLOCKER_CAP))
        names = [name for name, _weight in failed]
        gates_failed = [n for n in names if n in GATES]
        return EvaluationResult(
            reward=reward,
            subscores=result.subscores,
            info={
                **result.info,
                "uncapped_reward": result.reward,
                "failed_blockers": names,
                "blocker_cap": BLOCKER_CAP,
                "failed_gates": gates_failed,
            },
            content=(
                f"Blocker criteria failed ({', '.join(names)}); "
                f"cap {BLOCKER_CAP:.2f}, reward {reward:.3f} "
                f"(uncapped {result.reward:.3f})."
                + (
                    f" Among them a GATE ({', '.join(gates_failed)}): the "
                    "repository's own tests were rewritten or left red, so the "
                    "board's total is not a measurement of a fix."
                    if gates_failed else ""
                )
            ),
        )
    return result


@env.template(
    id="shared_handle_abandoned_operations",
    description=(
        "One connection handle is shared by many concurrent tasks. When a task "
        "gives up on an operation part-way through, whatever the server had set "
        "up for it has to be taken back, and the tasks still using the handle "
        "must not be able to tell it happened."
    ),
)
async def shared_handle_abandoned_operations(
    validate_mode: str | None = None,
    revision: str | None = None,  # V-2: inert provenance argument.
):
    # `revision` is never read. It exists so that the board label travels in the
    # scenario's ARGS: HUD cuts a new task version for a change of args or system
    # prompt, and `columns` alone would not (measured 5.09, law I13). tasks_sync.py
    # fills it from .hud/board.json; the image manifest validates args against this
    # signature, so the parameter has to be in the deployed image.
    _ = revision
    if validate_mode not in (None, "golden"):
        raise ValueError(f"unknown validate_mode: {validate_mode!r}")
    await _setup()
    if validate_mode == "golden":
        _ = yield "Golden-validation run: no work is expected of you. Finish immediately."
    else:
        # E-4: the ticket travels inside the coding-task scenario's own framing,
        # never bare. The framing is what a rollout reads as an ordinary
        # engineering request; the same words handed over without it have been
        # measured to change how a run starts.
        _ = yield (
            f"You are working in a coding repository located at {REPO_DIR}. "
            f"{WORKSPACE_NOTE}\n\n"
            "Use the tools provided to complete the following task. Hidden tests "
            "grade your work when you finish; do not modify existing tests.\n\n"
            f"{PROMPT}"
        )
    yield await _grade(validate_mode)


tasks = [shared_handle_abandoned_operations()]