File size: 61,079 Bytes
49b5084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert the pinned MiMo-V2.6-RL-oss Code rows to Harbor tasks and archive the Cyber rows.

    python data/mimo/patch.py --source SOURCE_DIR --output NEW_DIR

SOURCE_DIR holds the pinned code.parquet, cyber.parquet and image-mapping.jsonl
and is only read. NEW_DIR receives tasks.parquet (2,600 Code tasks whose image tag still exists and
without reward-hack residue), tasks.archive.parquet (1,000 Cyber rows, 96 Code rows with
removed images and 2 with residue, original payloads),
tasks.manifest.json and the patcher snapshot.

Code semantics follow OpenSourceCodeEnvironment (opensource_code.py and
datasets/base.py, MiMo-Agent commit 467f0a19016f0ac4d63b8d17a1f0da9ba07f232c):
capture the base ref before the agent starts, reset every path the test patch
touches to that ref, git apply the test patch, run test_command in cwd, reward 1
if and only if it exits 0, then reset the touched paths again.
"""

# Support both direct execution and python -m data.<source>.patch.
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))


import argparse
import hashlib
import io
import json
import re
import shlex
import tarfile

import pyarrow.parquet as pq

from data.utils.full_source.harbor_parquet import pack_task, write_tasks
from data.utils.patch_reporting import write_conversion_report


DATASET = "XiaomiMiMo/MiMo-V2.6-RL-oss"
REVISION = "639865fd3374018d6cb29b9fb82dd531406fcf5f"
MIMO_AGENT_REVISION = "467f0a19016f0ac4d63b8d17a1f0da9ba07f232c"
SUBSETS = {"code": ("code.parquet", 2698), "cyber": ("cyber.parquet", 1000)}
SHA256 = {
    "code.parquet": "e15733cf2451cfbc5492a4120f7f8cfddbad818aa9f0b324c79888dd1fece161",
    "cyber.parquet": "9e6e69034f4f3e6cfb5c901de642dddc7f4bacf35ab886b0e8eb53eb03084ba1",
    "image-mapping.jsonl": "704ad2716d746430a805b9b1ac7c6725aea2117fd8e4823ebe9d339d0313ad58",
}
REQUIRED_KEYS = {
    # _REQUIRED_FIELDS of opensource_code.py plus dataset_type; the rows have exactly these keys.
    "code": {"cwd", "dataset_type", "docker_image", "instance_id", "problem_statement",
             "test_command", "test_patch", "verifier_timeout_sec"},
    "cyber": {"cwd", "dataset_type", "description", "docker_image", "instance_id", "problem_statement"},
}
TASK_ID = re.compile(r"[A-Za-z0-9._-]+")
WORKDIR = re.compile(r"/[A-Za-z0-9._/-]+")

# agent_loop.py default trajectory_timeout at the pinned MiMo-Agent commit.
AGENT_TIMEOUT_SEC = 1800
# Kept outside the repository so the agent's own commits cannot move it.
BASE_REF_FILE = "/var/lib/mimo/base_ref"

CONVERSION_LABEL = "converted-to-harbor"
CONVERSION_REASON = (
    "The Code subset is published as rows of a training Parquet (problem statement, prebuilt "
    "image, hidden test patch and test command) and is graded by the MiMo-Agent environment "
    "OpenSourceCodeEnvironment, not as Harbor tasks. Each row becomes one Harbor task with its "
    "original instance ID. The instruction is the problem statement, unchanged. The environment is "
    "the published image with WORKDIR set to the row's cwd, so the repository and its dependencies "
    "are exactly the upstream ones and there is one image per task. The only addition is tmux, which "
    "the agent harness needs for its terminal: one image build step installs it from the image's own "
    "package manager when the published image has none, and does nothing otherwise. On Debian and "
    "Ubuntu that step registers root ownership for the utempter helper of libutempter0 first, "
    "because the single-user build namespace cannot assign the utmp group and the package would stay "
    "half installed (stage 3, job 997001: format-code-task-002953 could not start for that reason). "
    "The upstream reward "
    "steps are split between two verifier scripts: tests/setup.sh resets every path the test patch "
    "touches to the base commit and applies the test patch with git apply, and tests/test.sh runs "
    "the published test command in cwd, gives reward 1 if and only if it exits 0, and resets the "
    "touched paths again. A patch that cannot be reset or applied gives reward 0, as upstream. "
    "The verifier timeout is the row's verifier_timeout_sec (1800 s) and the agent timeout is the "
    "upstream default trajectory timeout (1800 s). The source has no resource or network fields, so "
    "4 CPUs, 4096 MiB and internet access are adapter defaults. Upstream records the base commit "
    "before the agent starts. Here an environment healthcheck does that before the agent runs. If "
    "that record is missing, the verifier uses the current HEAD, which differs from upstream only "
    "when an agent commits changes to files the test patch modifies. The rows contain no reference "
    "solution, so the tasks have none."
)

# Pinned image digests of the 2026-10-16 re-upload (see image-digests.json). Every Code task's
# Dockerfile uses FROM <repository>@<digest>, so a later re-push cannot change a validated task.
IMAGE_DIGESTS = json.loads((Path(__file__).parent / "image-digests.json").read_text())
REMOVED_CATEGORY = "upstream-image-removed"
REMOVED_REASON = (
    "The published image tag was deleted when xiaomimimo/mimo-v2.6-rl-oss re-pushed all tags on "
    "2026-10-16 (the registry and Docker Hub return 404), so the task environment can no longer be "
    "built. Not a task-quality finding; the original payload is preserved."
)


def pinned(image):
    """(FROM reference pinned by digest, digest), or (None, None) when the tag was removed."""
    repository, _, tag = image.rpartition(":")
    if repository != IMAGE_DIGESTS["repository"]:
        raise ValueError(f"unexpected image repository: {image}")
    if tag in IMAGE_DIGESTS["removed_tags"]:
        return None, None
    digest = IMAGE_DIGESTS["digests"].get(tag)
    if not digest:
        raise ValueError(f"no pinned digest for {image}")
    return f"{repository}@{digest}", digest


# Installed copies in the 2026-10-16 images that still differ from the repository (checked
# 2026-10-17, job 1039963, ~/autonomous-20261017/mimo-residue/probe-1039963.out: every differing
# file's blob was looked up in the repository's history with git log --all --find-object).
# Kept after the same check: format-code-task-000407 (all 3 differing airflow files are older
# repository versions), format-code-task-002070 (node_modules/nopt 7.2.1 differs only in
# package.json and the bin/ tester; lib/ equals the repository), format-code-task-002517 (no
# /testbed; the Go module cache holds the go-streams v0.12.0 release the test module requires;
# the requested S3 connector, NewS3Source, exists nowhere outside the repository).
RESIDUE_CATEGORY = "reward-hack-residue"
RESIDUE = {
    "format-code-task-000092": (
        "The image installs the repository's tests package in /usr/local/lib/python3.10/site-packages/tests; "
        "3 of its 99 files differ from the repository and none of the 3 blobs is in the repository's history "
        "(post-base content). They contain the test cases of the requested feature: test_checker.py adds "
        "var_rank_multi_1..5 and var_rank_multi_broadcast, test_parser.py and test_specs.py add specs with "
        "several variable-rank dimensions ([ds1..., ds2...]), the behaviour the hidden test "
        "tests/gpflow/experimental/check_shapes/test_multi_varrank.py checks. An agent can read the expected "
        "behaviour from the image."),
    "format-code-task-001397": (
        "The image's virtual environment /testbed/.venv/lib/python3.12/site-packages/grai_schemas has "
        "v1/metadata/edges.py with TableToTableMetadata typed by TableToTableAttributes and included in the "
        "Metadata union; the repository copy has the defect (TableToColumnAttributes, union without "
        "TableToTableMetadata) and the installed blob is not in the repository's history (post-base content). "
        "grai_client/schemas/__init__.py likewise imports an edge module the repository lacks. The installed "
        "copy is the fix for the relationship-metadata contract the hidden test checks."),
}

# Images whose package installation upstream never finished (validation 2026-10-17, final run
# array 1047484, image build logs). Stage 1 refuses an image with unconfigured packages, and
# 001314 cannot even install tmux (apt stops on the interrupted dpkg). Reproduced from the image
# digest alone, so the image as published is incomplete; not a task-content or runtime finding.
INCOMPLETE_PACKAGES_CATEGORY = "upstream-image-incomplete-packages"
INCOMPLETE_PACKAGES = {
    "format-code-task-001302": (
        "dpkg in the published image lists mysql-server as unpacked but not configured and "
        "mysql-server-8.0 as half configured (shard 0032, image build log 5911a2363542)."),
    "format-code-task-000809": (
        "dpkg in the published image lists libevent-dev as unpacked but not configured "
        "(shard 0017, image build log 3dea9d582103)."),
    "format-code-task-001314": (
        "dpkg in the published image was interrupted: apt-get stops with \"dpkg was interrupted, you "
        "must manually run 'dpkg --configure -a'\", so no package (tmux) can be installed "
        "(shard 0041, image build log 4d5d8b7feef4)."),
    "format-code-task-002899": (
        "dpkg in the published image lists typesense-server as half configured; tmux was already "
        "present, so the build installed nothing (shard 0074, image build log da84e0f3c6d8)."),
}
# No-op stage review of the final run (array 1047484, 2026-10-18, user-approved): tasks whose
# reward-0 run did not come from the missing feature. runtime-user-emulation / runtime-incompatible:
# our single-uid Apptainer runtime (services as their own users, root browsers, host network or
# CPU count); upstream-environment-broken: the image cannot run the tests at all; upstream-task-defect:
# the repository lacks files or a base commit the task needs; nop-unverifiable: no output shows that a
# test ran. Per-task evidence: verdict files of the review (scratch nop/verdicts-*.jsonl).
NOP_REVIEW = {
    'format-code-task-000348': ('upstream-environment-broken', 'Memory measurement on CLAIX (2026-10-18, 16 GiB limit): needs more than 16 GiB (peak 15,674 MiB at the 16 GiB limit; no tests ran)'),
    'format-code-task-000707': ('upstream-environment-broken', 'Memory measurement on CLAIX (2026-10-18, 16 GiB limit): its JavaScript test runs out of Node\'s own heap at about 4 GB ("JavaScript heap out of memory"), which the test command does not raise; more container memory does not help'),
    'format-code-task-001633': ('upstream-environment-broken', 'Memory measurement on CLAIX (2026-10-18, 16 GiB limit): its JavaScript test runs out of Node\'s own heap ("Reached heap limit"), which the test command does not raise; more container memory does not help'),
    'format-code-task-002280': ('upstream-environment-broken', 'Memory measurement on CLAIX (2026-10-18, 16 GiB limit): needs more than 16 GiB (peak reached the 16 GiB limit)'),
    'format-code-task-000252': ('upstream-environment-broken', 'No-op rerun on CLAIX (job 5117303, 2026-10-18, direct internet): the StarRocks fe-core Maven build ran 19 minutes and then exceeded the task memory limit; too slow and too large for validation (user rule: Maven tasks over 20 minutes are archived).'),
    'format-code-task-001107': ('upstream-environment-broken', 'No-op rerun on CLAIX (job 5117303, 2026-10-18, direct internet): Gradle cannot resolve the com.gradle.enterprise 3.16.2 settings plugin from any plugin repository, so the build fails before any test.'),
    'format-code-task-002916': ('upstream-environment-broken', 'No-op rerun on CLAIX (job 5117303, 2026-10-18, direct internet): pnpm install --frozen-lockfile hangs without output until the 1800 s verifier timeout, so no test runs.'),
    'format-code-task-000020': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): Julia segfaults in Pkg.instantiate before any test runs.'),
    'format-code-task-000111': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Firefox never connected to karma under xvfb, so no spec ran; the likely cause is Firefox under single-uid fakeroot root without user namespaces for its sandbox (not proven by the log).'),
    'format-code-task-000130': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): Julia segfaults before any test runs (same image setup as 000020).'),
    'format-code-task-000177': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres not running; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-000178': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): pg_ctlcluster start failed silently (2>/dev/null); Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-000179': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): pg_ctlcluster start failed (hidden); Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-000181': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres did not start and sudo -u postgres used; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-000182': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Script writes /etc/hosts, which Apptainer binds read-only.'),
    'format-code-task-000209': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): pg_ctlcluster start fails under the single-uid runtime (root-owned PGDATA, cf. 001272); the first selected base test errors in DB setup.'),
    'format-code-task-000277': ('nop-unverifiable', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): forge test -q prints only compile lines; no test result is visible.'),
    'format-code-task-000279': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): pg_ctlcluster start failed silently (output sent to /dev/null) and the tests never ran; this is the same root-owned datadir/single-uid issue as the other postgres tasks (inferred).'),
    'format-code-task-000394': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): usecase.sh stops at its precondition "FAIL: molecule CLI is not runnable": the project CLI does not start in the image.'),
    'format-code-task-000474': ('upstream-task-defect', 'The repository has no commit (all files only staged, the base commit exists only as an unreferenced object), so the base ref the task reset needs cannot be recorded; the environment healthcheck fails (CLAIX rerun 5116864, 2026-10-18).'),
    'format-code-task-000528': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): MySQL cannot open its datadir because under the single-uid Apptainer runtime the mysql user cannot own or access /var/lib/mysql, so the tests never ran.'),
    'format-code-task-000622': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): HOME/GOMODCACHE belong to the image's testuser; under the single-uid runtime the directory is not accessible, so go cannot start."),
    'format-code-task-000723': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): MariaDB did not come up (mysql client errors hidden, script exits under -e); inferred same single-uid ownership problem as 001983.'),
    'format-code-task-000945': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres not running (pg_ctlcluster start fails silently, same root-owned PGDATA problem as 001272); additionally our ot_pytest_execution plugin crashes on pytest 3.0.2 (no _pytest.outcomes).'),
    'format-code-task-000965': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Offline Maven repo lacks parent POM; no test compiled.'),
    'format-code-task-001030': ('upstream-task-defect', "No-op stage (final run array 1047484, reviewed 2026-10-18): Upstream 'task base' commit deleted 64 files (incl. internal/apischema/openai/openai.go, 60 of them mention LLM vendors) that the instruction calls the existing extension; the package cannot build regardless of the feature (task defective)."),
    'format-code-task-001050': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Repo has go.mod requiring testify but no go.sum at all (checked in image); `go test ./lib/lru` cannot load the module graph independent of the feature (new test imports only reflect/testing).'),
    'format-code-task-001059': ('upstream-task-defect', "No-op stage (final run array 1047484, reviewed 2026-10-18): Upstream 'task base' deleted common/openai/{chat,exports,msg}.go (all mention OpenAI), so yakgrpc no longer compiles; unrelated to the YaklangInspectInformation feature (task defective)."),
    'format-code-task-001069': ('upstream-task-defect', "No-op stage (final run array 1047484, reviewed 2026-10-18): Upstream 'task base' deleted 76 files incl. src/any_agent/config.py and tracing/agent_trace.py; the package cannot be imported at all although the instruction only asks to extend spans_to_messages (task defective)."),
    'format-code-task-001077': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): a jar the test classpath needs (commons-lang 2.6) is missing from the offline Maven repository in the image.'),
    'format-code-task-001098': ('upstream-task-defect', 'No-op stage (final run array 1047484, reviewed 2026-10-18): The prerequisite lib-sourcify build fails on a missing ipfsHash module in existing code, which is unrelated to the custom-API feature, so the tests never run (the repo snapshot may be missing a file, which would make the task defective).'),
    'format-code-task-001137': ('upstream-task-defect', "No-op stage (final run array 1047484, reviewed 2026-10-18): Upstream 'task base' deleted doc_comments_ai/app.py, llm.py, utils.py (and an existing test response_parser_test.py also fails); the instruction presumes the CLI exists (task defective)."),
    'format-code-task-001168': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): conftest import fails because mlflow imports as a namespace package (mlflow.__file__ is None), unrelated to log_table modes; environment/repo state broken.'),
    'format-code-task-001172': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Maven offline cache lacks junit-bom; build cannot even load the POM.'),
    'format-code-task-001183': ('upstream-task-defect', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Same griptape repo state as 001406: conftest imports an existing driver module that is missing; unrelated to retrieval fusion (likely defective task).'),
    'format-code-task-001188': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): the test command starts mysqld as the mysql user, which our single-user runtime cannot provide.'),
    'format-code-task-001193': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Flow server crashes in select(); most likely too many worker fds because flow sizes workers from the 384 host CPUs (select fd limit 1024). Not task-related.'),
    'format-code-task-001203': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit at first service start: pg_ctlcluster ... 2>/dev/null fails under -e; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-001207': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit: service postgresql start / sudo -u postgres psql 2>/dev/null fail under -e; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-001212': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Bench dir owned by frappe uid is unreadable for root under the single-uid fakeroot runtime.'),
    'format-code-task-001272': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres refuses to start because under the single-uid Apptainer runtime PGDATA appears root-owned; base tests error in setup before any feature test runs.'),
    'format-code-task-001273': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): PostgreSQL refuses to start because under fakeroot/single-uid the datadir appears owned by root; the tests never ran.'),
    'format-code-task-001406': ('upstream-task-defect', 'No-op stage (final run array 1047484, reviewed 2026-10-18): conftest import chain fails on an existing griptape driver module unrelated to the RAG-provenance feature; repo snapshot appears to be missing that file (task likely defective).'),
    'format-code-task-001438': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): pg_ctlcluster start failed (errors hidden); Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-001561': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Existing repository code imports dict2schema, which the installed webargs version no longer has, so the import precheck fails before pytest runs (a dependency version mismatch, not the feature).'),
    'format-code-task-001574': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): pg_ctlcluster start failed silently (output sent to /dev/null), so ALTER ROLE failed and no tests ran; this matches the postgres datadir-owned-by-root failure under fakeroot/single-uid (inferred).'),
    'format-code-task-001756': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Composer resolved latest deps (no lock) that need PHP 8 while PHP 7.4 runs; errors come from vendor code.'),
    'format-code-task-001757': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): PHP 8.0 parse error from a typed class constant in an installed dependency (needs PHP 8.3); unrelated to onSuccess/onFailure. Other 3 tests pass.'),
    'format-code-task-001866': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): PostgreSQL never became ready, so no go test ran; this matches the root-owned datadir/single-uid problem of the other postgres tasks (inferred, the start output is suppressed).'),
    'format-code-task-001969': ('nop-unverifiable', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): npm aborts with exit code 243 after the install step with its output hidden; no test runs visibly.'),
    'format-code-task-001975': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): RabbitMQ cannot read its cookie (owned by rabbitmq uid) under the single-uid runtime; tests never ran.'),
    'format-code-task-001980': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres cannot run as root and the single-uid runtime has no postgres user to switch to.'),
    'format-code-task-001982': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): MariaDB did not start, mysql error hidden by 2>/dev/null; inferred single-uid ownership problem as in 001983.'),
    'format-code-task-001983': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): mysqld_safe cannot manage its pid file: uid mapping / overlay under fakeroot.'),
    'format-code-task-002001': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): su to a non-root user cannot use its home under single-uid runtime.'),
    'format-code-task-002022': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit at 'pg_ctlcluster 16 main start 2>/dev/null' under -e; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e."),
    'format-code-task-002023': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit at 'pg_ctlcluster 16 main start 2>/dev/null' under -e; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e."),
    'format-code-task-002024': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres not running; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-002035': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit at 'pg_ctlcluster 16 main start 2>/dev/null' under -e; Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e."),
    'format-code-task-002036': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): postgres never comes up (the start command's stderr is sent to /dev/null); same class as the known DB-ownership failures under our single-uid fakeroot runtime. Per user decision archive as runtime-user-emulation only after confirming the ownership error (start it once by hand without 2>/dev/null)."),
    'format-code-task-002037': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): postgres never comes up (the start command's stderr is sent to /dev/null); same class as the known DB-ownership failures under our single-uid fakeroot runtime. Per user decision archive as runtime-user-emulation only after confirming the ownership error (start it once by hand without 2>/dev/null)."),
    'format-code-task-002038': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): postgres never comes up (the start command's stderr is sent to /dev/null); same class as the known DB-ownership failures under our single-uid fakeroot runtime. Per user decision archive as runtime-user-emulation only after confirming the ownership error (start it once by hand without 2>/dev/null). Django aborts while creating the test DB, so the runner never reports results."),
    'format-code-task-002092': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): postgres never comes up (the start command's stderr is sent to /dev/null); same class as the known DB-ownership failures under our single-uid fakeroot runtime. Per user decision archive as runtime-user-emulation only after confirming the ownership error (start it once by hand without 2>/dev/null)."),
    'format-code-task-002144': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): the junit 3.8.1 jar the test command needs is missing from the offline Maven repository in the image.'),
    'format-code-task-002148': ('upstream-task-defect', "No-op stage (final run array 1047484, reviewed 2026-10-18): Upstream 'task base' deleted api/api.gen.go (plus clients/openapi specs), so package api cannot compile; unrelated to the subscription phase-patch feature (task defective)."),
    'format-code-task-002169': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Neo4j cannot write its log file (owned by the neo4j uid, not writable under single-uid fakeroot), so the database never starts and pytest never runs.'),
    'format-code-task-002180': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres refuses to start because the single-uid fakeroot runtime makes its data dir root-owned; go tests never ran.'),
    'format-code-task-002293': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Old pnpm on newer Node fails every registry fetch (ERR_INVALID_THIS); dependencies never installed.'),
    'format-code-task-002294': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit in postgres setup (pg_ctlcluster ... || true, then sudo -u postgres psql with errors hidden); Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-002309': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Karma never ran a spec because Chrome refuses to start as uid 0 without --no-sandbox; under fakeroot the verifier is root (Chrome would also need --no-sandbox in a root Docker container, so the task config is fragile too).'),
    'format-code-task-002338': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): postgres never comes up (the start command's stderr is sent to /dev/null); same class as the known DB-ownership failures under our single-uid fakeroot runtime. Per user decision archive as runtime-user-emulation only after confirming the ownership error (start it once by hand without 2>/dev/null). Also uses su - postgres, which cannot switch uid with empty subuid."),
    'format-code-task-002396': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): The setup cannot read the postgres-owned pg_hba.conf because single-uid fakeroot "root" lacks access to files owned by another image uid, so the tests never ran.'),
    'format-code-task-002557': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Silent exit in postgres setup (su - postgres psql 2>/dev/null under -e); Postgres data dir owned by root under single-uid fakeroot (seen explicitly in 002180/002732); start errors hidden by 2>/dev/null, script exits under -e.'),
    'format-code-task-002558': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): test_command.sh runs `pg_ctlcluster 16 main start 2>/dev/null || true`; Postgres cannot start under the single-uid runtime (cf. 001272).'),
    'format-code-task-002559': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): postgresql init script fails on chmod under fakeroot/overlay uid mapping.'),
    'format-code-task-002613': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): The pinned old PHPUnit cannot run on the installed PHP 8.1+, so it dies on startup before any test executes (unrelated to the feature).'),
    'format-code-task-002620': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): The new sent_time test fails genuinely, but read_routes6 also fails because the Apptainer container shares the host network namespace (host ens13f0np0/ibs5 routes), so even a correct solution would score 0 here.'),
    'format-code-task-002629': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): MariaDB cannot be reached because of a permission error (errno 13) on the socket or datadir; under single-uid fakeroot the mysql user cannot use root-owned dirs, so the tests never ran.'),
    'format-code-task-002689': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): The setup step chmods a symlink into the read-only image tree (/opt/node-22/...), and under Apptainer fakeroot this gives EINVAL, so the script exits before jest.'),
    'format-code-task-002693': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): The test_command.sh runs under bash -e and starts postgres with stderr sent to /dev/null; a failed pg_ctlcluster start ends the script silently before go test, which matches the postgres-under-fakeroot failures (inferred from the script, as the output is empty).'),
    'format-code-task-002732': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Postgres refuses root-owned data dir under single-uid fakeroot.'),
    'format-code-task-002740': ('runtime-incompatible', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Taskpools sizes from host CPU count (384 visible) and aborts in the regression test before the new test; our node exposes all host cores.'),
    'format-code-task-002850': ('runtime-user-emulation', 'No-op stage (final run array 1047484, reviewed 2026-10-18, traced with bash -x): pip install -e . fails with "Permission denied: /usr/local/bin/sqlmesh" under our single-user runtime, so no test runs.'),
    'format-code-task-003020': ('upstream-task-defect', 'No-op stage (final run array 1047484, reviewed 2026-10-18): Base app/reducers/links.js imports react-addons-update, which is not installed; bundle fails before tests. Dependency missing in image (possible task defect).'),
    'format-code-task-003039': ('upstream-environment-broken', 'No-op stage (final run array 1047484, reviewed 2026-10-18): mongod failed to start (log not captured, possibly runtime-related); tests never ran.'),
    'format-code-task-003053': ('runtime-user-emulation', "No-op stage (final run array 1047484, reviewed 2026-10-18): postgres never comes up (the start command's stderr is sent to /dev/null); same class as the known DB-ownership failures under our single-uid fakeroot runtime. Per user decision archive as runtime-user-emulation only after confirming the ownership error (start it once by hand without 2>/dev/null)."),
}
# Leftover from the residue audit that is still in the re-uploaded image (checked 2026-10-18): the
# new API names of the hidden tests exist only in that leftover. Six other leftovers of the audit
# (000046, 000283, 000556, 000699, 000114, 001372) contain none of them and stay.
RESIDUE_UNTESTED = {
    'format-code-task-000253': ("The image's .build_env/venv installs a pipeline package whose "
        "pipeline/contrib/node_timeout (handlers.py and its bytecode) already defines deal_with_timeout_node, "
        "parse_node_timeout_configs, forced_fail_and_skip and node_timeout_handler, the API the hidden tests check "
        "and the repository lacks (residue audit CharlieFRuan/rl-env-cleaner@836c6061, checked 2026-10-18)."),
}
# Every Code task archived by name: (category, reason).
EXCLUDED = {**{task: (RESIDUE_CATEGORY, reason) for task, reason in RESIDUE.items()},
            **{task: (RESIDUE_CATEGORY, reason) for task, reason in RESIDUE_UNTESTED.items()},
            **{task: (INCOMPLETE_PACKAGES_CATEGORY, reason) for task, reason in INCOMPLETE_PACKAGES.items()},
            **NOP_REVIEW}

ARCHIVE_CATEGORY = "unsupported-user-isolation"
ARCHIVE_REASON = (
    "Archived for compatibility with the current Helma Apptainer runtime: upstream Cyber grading "
    "requires separate agent, verify and root identities. The tested Helma account configuration "
    "has no subordinate UID/GID mappings, and switching to the required users fails. The current "
    "runtime cannot preserve the upstream grading permissions. This is a runtime compatibility "
    "exclusion, not a task-quality or reward-hacking finding; the original payload is preserved "
    "for future re-enablement. No claim is made that cluster policy prohibits these mappings."
)

# _setup_dataset_specific: safe.directory (result ignored, as upstream), _ensure_work_tree,
# then _capture_base_ref (without overwriting an earlier capture). A base ref file that
# cannot be written is not fatal; the verifier then resolves HEAD itself.
CAPTURE_BASE_REF = (
    "git config --global --add safe.directory {cwd}; cd {cwd} && "
    "{{ git rev-parse --git-dir >/dev/null 2>&1 || "
    "{{ git init -q && git add -A && git commit -q -m baseline --allow-empty; }}; }} && "
    "ref=$(git rev-parse --verify HEAD) && [ ${{#ref}} -eq 40 ] && "
    "{{ [ -s {file} ] || {{ mkdir -p {directory} && printf '%s\\n' \"$ref\" > {file}; }} || true; }}"
)

# The harness terminal needs tmux. The shared builder adds it in most builds, but not when it has
# to import the published image as is (job 997001, format-code-task-002953: Debian 11), and an
# installation at task start cannot give libutempter0's helper its root:utmp ownership in a
# single-UID namespace. Without the helper's privileged utmp accounting tmux works the same.
UTEMPTER = "/usr/lib/x86_64-linux-gnu/utempter/utempter"
INSTALL_TMUX = (
    "if ! command -v tmux >/dev/null 2>&1; then "
    "if command -v apt-get >/dev/null 2>&1; then "
    f"{{ dpkg-statoverride --list {UTEMPTER} >/dev/null 2>&1 || "
    f"dpkg-statoverride --add root root 0755 {UTEMPTER}; }} && "
    "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tmux; "
    "elif command -v apk >/dev/null 2>&1; then apk add --no-cache tmux; "
    "elif command -v dnf >/dev/null 2>&1; then dnf install -y -q tmux; "
    "elif command -v yum >/dev/null 2>&1; then yum install -y -q tmux; "
    # An explicit exit: errexit does not stop a build script for a failure inside the if.
    "fi; fi; tmux -V || exit 1"
)

RESET_SH = r"""#!/bin/bash
# Upstream reset_test_files_to_base: give every path the test patch touches a
# clean starting point at the base commit. Sourced by setup.sh and test.sh.
mimo_base_ref() {
  local ref=""
  if [ -s __BASE_REF_FILE__ ]; then
    ref=$(head -n 1 __BASE_REF_FILE__)
    if [ ${#ref} -eq 40 ] && git cat-file -e "$ref^{commit}" 2>/dev/null; then
      echo "base ref $ref (recorded before the agent started)" >&2
      printf '%s\n' "$ref"
      return 0
    fi
  fi
  # No usable record (the healthcheck did not run): same steps as upstream setup.
  if ! git rev-parse --git-dir >/dev/null 2>&1; then
    git init -q && git add -A && git commit -q -m baseline --allow-empty || return 1
  fi
  ref=$(git rev-parse --verify HEAD) || return 1
  [ ${#ref} -eq 40 ] || return 1
  echo "base ref $ref (current HEAD, no usable record at __BASE_REF_FILE__)" >&2
  printf '%s\n' "$ref"
}

mimo_reset_test_files() {
  local base tf
  cd __CWD__ || return 1
  base=$(mimo_base_ref) || return 1
  while IFS= read -r tf; do
    [ -z "$tf" ] && continue
    if git cat-file -e "$base":"$tf" 2>/dev/null; then
      git checkout "$base" -- "$tf" 2>/dev/null || true
    else
      git rm -f --cached "$tf" >/dev/null 2>&1 || true
      rm -f "$tf"
    fi
  done < /tests/touched_paths.txt
}
"""

SETUP_SH = r"""#!/bin/bash
# Verifier preparation, upstream reward steps 1 and 2: reset the paths the test
# patch touches to the base commit, then apply the test patch.
fail() {
  echo "$1" >&2
  # Upstream scores a testbed that cannot be reset or patched as reward 0.
  mkdir -p /logs/verifier
  rm -f /logs/verifier/reward.json
  echo 0 > /logs/verifier/reward.txt
  exit 1
}
git config --global --add safe.directory __CWD__
. /tests/reset_test_files.sh
mimo_reset_test_files || fail "reset_tests_failed"
cd __CWD__ || fail "reset_tests_failed"
git apply --verbose /tests/test.patch || fail "apply_test_patch_failed"
"""

TEST_SH = r"""#!/bin/bash
# Upstream reward step 3: reward 1 if and only if the published test command exits 0.
mkdir -p /logs/verifier
if cd __CWD__; then
  bash -lc __TEST_COMMAND__
  status=$?
else
  status=1
fi
if [ "$status" -eq 0 ]; then
  printf '{"reward": 1.0}\n' > /logs/verifier/reward.json
else
  printf '{"reward": 0.0}\n' > /logs/verifier/reward.json
fi
# Upstream leaves the test files as they were found.
. /tests/reset_test_files.sh
mimo_reset_test_files
exit 0
"""


def get_patch_touched_files(patch):
    """Upstream DatasetEnvironment.get_patch_touched_files, unchanged."""
    files = []
    for line in patch.split("\n"):
        m = re.match(r"^diff --git a/(.+?) b/(.+)$", line)
        if m:
            for fp in (m.group(1), m.group(2)):
                if fp not in files:
                    files.append(fp)
    return files


def sha256(path):
    with Path(path).open("rb") as stream:
        return hashlib.file_digest(stream, "sha256").hexdigest()


def check_source(source):
    """Pinned hashes are constants; the loop's input manifest must agree with them."""
    manifest = source.parent / "input-manifest.json"
    recorded = json.loads(manifest.read_text()) if manifest.is_file() else None
    if recorded is not None:
        if recorded.get("dataset") != DATASET or recorded.get("revision") != REVISION:
            raise ValueError(f"{manifest}: not {DATASET} at {REVISION}")
        if recorded.get("domains") != {name: count for name, (_, count) in SUBSETS.items()}:
            raise ValueError(f"{manifest}: unexpected subset counts {recorded.get('domains')}")
    for name, expected in SHA256.items():
        path = source / name
        if not path.is_file():
            raise FileNotFoundError(f"missing pinned MiMo source file: {path}")
        actual = sha256(path)
        if actual != expected:
            raise ValueError(f"{path}: sha256 {actual} differs from the pinned {expected}")
        if recorded is not None and recorded.get("sha256", {}).get(name) != expected:
            raise ValueError(f"{manifest}: sha256 of {name} differs from the pinned {expected}")


def read_mapping(path):
    mapping = {}
    for line in path.read_text().splitlines():
        entry = json.loads(line)
        if mapping.setdefault(entry["dataset_image"], entry["dockerhub_image"]) != entry["dockerhub_image"]:
            raise ValueError(f"conflicting image mapping: {entry['dataset_image']}")
    return mapping


def read_subset(source, subset, mapping):
    """Yield (row index, source row, decoded instance, published image) for every row."""
    filename, expected = SUBSETS[subset]
    rows = pq.read_table(source / filename).to_pylist()
    if len(rows) != expected:
        raise ValueError(f"{filename}: expected {expected} rows, found {len(rows)}")
    for index, row in enumerate(rows):
        instance = json.loads(row["extra_info"]["instance_json"])
        where = f"{filename} row {index}"
        if set(instance) != REQUIRED_KEYS[subset]:
            raise ValueError(f"{where}: unexpected instance keys {sorted(instance)}")
        empty = [key for key in sorted(instance) if not instance[key] or not isinstance(
            instance[key], (str, int) if key == "verifier_timeout_sec" else str)]
        if empty:
            raise ValueError(f"{where}: empty or mistyped field(s) {empty}")
        task_id = instance["instance_id"]
        if row["extra_info"]["instance_id"] != task_id:
            raise ValueError(f"{where}: instance ID mismatch {row['extra_info']['instance_id']!r} != {task_id!r}")
        if not TASK_ID.fullmatch(task_id):
            raise ValueError(f"{where}: unsafe instance ID {task_id!r}")
        if instance["docker_image"] not in mapping:
            raise ValueError(f"{where}: unmapped image {instance['docker_image']!r}")
        yield index, row, instance, mapping[instance["docker_image"]]


# Tasks that exceed the 4096 MiB default. Measured 2026-10-17 with a 16 GiB limit (job 1046057,
# cgroup peak of the no-op run, ~/OT_next_data validation of stages 1,3,4): jest starts worker
# processes and MiMo's /etc/profile.d/zz-autoinstall-oom.sh gives every node a 4 GiB heap, so
# 4096 MiB stopped the verifier ("Task memory limit exceeded"). Peak plus about 35 % headroom.
# Tasks that exceed the 4096 MiB default. Measured 2026-10-18 with a 16 GiB limit (CLAIX jobs
# 5117335, 5120667, 5120669; peak = sacct MaxRSS of the trial step). Limit = peak + 35 %, rounded up
# to the next size Terminal-Bench's check-resource-sizes.sh allows (8192 or 16384 MiB): all of them failed at
# 4096 MiB, where the limit also counts page cache.
MEMORY_MB = {
    "format-code-task-000035": 8192,  # peak 1,907 MiB
    "format-code-task-000036": 8192,  # 2026-10-17 jest profile
    "format-code-task-000037": 8192,  # peak 2,278 MiB
    "format-code-task-000197": 8192,  # peak 2,949 MiB
    "format-code-task-000268": 8192,  # peak 5,261 MiB
    "format-code-task-000283": 16384,  # peak 10,921 MiB
    "format-code-task-000319": 8192,  # peak 2,197 MiB
    "format-code-task-000475": 8192,  # peak 1,842 MiB
    "format-code-task-000479": 8192,  # peak 2,201 MiB
    "format-code-task-000576": 8192,  # peak 3,304 MiB
    "format-code-task-000583": 16384,  # peak 6,245 MiB
    "format-code-task-000604": 8192,  # peak 3,330 MiB
    "format-code-task-000609": 16384,  # peak 10,688 MiB
    "format-code-task-000632": 8192,  # peak 2,120 MiB
    "format-code-task-000656": 8192,  # peak 2,914 MiB
    "format-code-task-000756": 8192,  # peak 3,327 MiB
    "format-code-task-000772": 8192,  # peak 5,851 MiB
    "format-code-task-000776": 8192,  # peak 3,063 MiB
    "format-code-task-000867": 8192,  # peak 2,992 MiB
    "format-code-task-000890": 8192,  # peak 2,675 MiB
    "format-code-task-000891": 8192,  # peak 1,607 MiB
    "format-code-task-000928": 8192,  # peak 4,173 MiB
    "format-code-task-000943": 8192,  # peak 2,211 MiB
    "format-code-task-001085": 8192,  # peak 5,885 MiB
    "format-code-task-001239": 8192,  # peak 4,485 MiB
    "format-code-task-001379": 8192,  # peak 2,369 MiB
    "format-code-task-001388": 16384,  # peak 6,689 MiB
    "format-code-task-001403": 8192,  # peak 1,994 MiB
    "format-code-task-001408": 8192,  # peak 2,517 MiB
    "format-code-task-001409": 8192,  # peak 2,673 MiB
    "format-code-task-001549": 8192,  # peak 2,617 MiB
    "format-code-task-001572": 8192,  # peak 2,790 MiB
    "format-code-task-001625": 8192,  # peak 3.9 GiB
    "format-code-task-001632": 8192,  # peak 4,517 MiB
    "format-code-task-001656": 8192,  # peak 2,122 MiB
    "format-code-task-001698": 8192,  # peak 2,526 MiB
    "format-code-task-001856": 16384,  # peak 6,821 MiB
    "format-code-task-001883": 8192,  # peak 1,652 MiB
    "format-code-task-001890": 8192,  # peak 2,300 MiB
    "format-code-task-001907": 16384,  # peak 6,363 MiB
    "format-code-task-001954": 8192,  # peak 954 MiB
    "format-code-task-001955": 8192,  # peak 1,696 MiB
    "format-code-task-002057": 16384,  # peak 6,519 MiB
    "format-code-task-002080": 8192,  # peak 1,699 MiB
    "format-code-task-002141": 8192,  # peak 2,642 MiB
    "format-code-task-002242": 8192,  # peak 1,916 MiB
    "format-code-task-002317": 8192,  # peak 1,744 MiB
    "format-code-task-002318": 8192,  # peak 3,028 MiB
    "format-code-task-002319": 8192,  # peak 2,697 MiB
    "format-code-task-002320": 8192,  # peak 1,800 MiB
    "format-code-task-002322": 8192,  # peak 1,785 MiB
    "format-code-task-002323": 8192,  # peak 1,996 MiB
    "format-code-task-002324": 8192,  # 2026-10-17 jest profile
    "format-code-task-002325": 8192,  # peak 1,969 MiB
    "format-code-task-002326": 8192,  # peak 2,034 MiB
    "format-code-task-002327": 8192,  # peak 1,995 MiB
    "format-code-task-002328": 8192,  # peak 3,419 MiB
    "format-code-task-002329": 8192,  # peak 2,297 MiB
    "format-code-task-002330": 8192,  # peak 2,796 MiB
    "format-code-task-002331": 8192,  # peak 2,620 MiB
    "format-code-task-002332": 8192,  # peak 1,718 MiB
    "format-code-task-002414": 8192,  # peak 5,542 MiB
    "format-code-task-002432": 8192,  # peak 4,233 MiB
    "format-code-task-002433": 8192,  # peak 4,367 MiB
    "format-code-task-002435": 8192,  # peak 4,652 MiB
    "format-code-task-002436": 8192,  # peak 4,639 MiB
    "format-code-task-002437": 8192,  # peak 4,705 MiB
    "format-code-task-002438": 8192,  # peak 3,726 MiB
    "format-code-task-002439": 8192,  # peak 4,900 MiB
    "format-code-task-002440": 8192,  # peak 4,933 MiB
    "format-code-task-002441": 8192,  # peak 5,005 MiB
    "format-code-task-002491": 8192,  # peak 1,638 MiB
    "format-code-task-002492": 8192,  # peak 2,799 MiB
    "format-code-task-002711": 8192,  # peak 5,542 MiB
    "format-code-task-002728": 8192,  # peak 2,589 MiB
    "format-code-task-002730": 8192,  # peak 2,095 MiB
    "format-code-task-002741": 8192,  # peak 1,736 MiB
    "format-code-task-002751": 8192,  # peak 2,152 MiB
    "format-code-task-002752": 16384,  # peak 7,120 MiB
    "format-code-task-002753": 8192,  # peak 5,186 MiB
    "format-code-task-002764": 8192,  # peak 1,730 MiB
    "format-code-task-002766": 8192,  # peak 2,211 MiB
    "format-code-task-002767": 8192,  # peak 2,085 MiB
    "format-code-task-002768": 8192,  # peak 1,931 MiB
    "format-code-task-002777": 8192,  # peak 5,629 MiB
    "format-code-task-002797": 8192,  # peak 2,084 MiB
    "format-code-task-002820": 8192,  # peak 1,940 MiB
    "format-code-task-002821": 8192,  # peak 1,883 MiB
    "format-code-task-002896": 8192,  # peak 1,773 MiB
    "format-code-task-002905": 8192,  # peak 3,517 MiB
    "format-code-task-002911": 8192,  # peak 3.9 GiB
    "format-code-task-002945": 8192,  # peak 3,846 MiB
    "format-code-task-002967": 8192,  # peak 2,331 MiB
    "format-code-task-002988": 8192,  # peak 1,823 MiB
}


def code_files(row, instance, image):
    task_id, cwd = instance["instance_id"], instance["cwd"]
    reference, digest = pinned(image)
    if not WORKDIR.fullmatch(cwd):
        raise ValueError(f"{task_id}: unsupported cwd {cwd!r}")
    if [message["content"] for message in row["prompt"]] != [instance["problem_statement"]]:
        raise ValueError(f"{task_id}: prompt differs from problem_statement")
    touched = get_patch_touched_files(instance["test_patch"])
    if not touched or any(not path or path != path.strip() or "\r" in path for path in touched):
        raise ValueError(f"{task_id}: test patch paths cannot be listed one per line: {touched!r}")
    quoted = shlex.quote(cwd)
    health = CAPTURE_BASE_REF.format(cwd=quoted, file=BASE_REF_FILE, directory=str(Path(BASE_REF_FILE).parent))
    fill = lambda text: text.replace("__CWD__", quoted).replace("__BASE_REF_FILE__", BASE_REF_FILE)
    task_toml = (
        'version = "1.0"\n'
        f'[agent]\ntimeout_sec = {AGENT_TIMEOUT_SEC}\n'
        f'[verifier]\ntimeout_sec = {int(instance["verifier_timeout_sec"])}\n'
        f'[environment]\ncpus = 4\nmemory_mb = {MEMORY_MB.get(task_id, 4096)}\nallow_internet = true\n'
        '[environment.healthcheck]\n'
        f'command = {json.dumps(health)}\n'
        'timeout_sec = 300\nretries = 1\n'
        '[metadata]\n'
        f'source = {json.dumps(DATASET)}\n'
        'subset = "code"\n'
        f'source_revision = {json.dumps(REVISION)}\n'
        f'dataset_image = {json.dumps(instance["docker_image"])}\n'
        f'dockerhub_image = {json.dumps(image)}\n'
        f'image_digest = {json.dumps(digest)}\n'
    )
    return {
        "instruction.md": instance["problem_statement"].encode(),
        "environment/Dockerfile": f"FROM {reference}\nWORKDIR {cwd}\nRUN {INSTALL_TMUX}\n",
        "task.toml": task_toml,
        # Bytes as published: CRLF content and Git binary hunks must survive.
        "tests/test.patch": instance["test_patch"].encode(),
        "tests/touched_paths.txt": "".join(path + "\n" for path in touched),
        "tests/reset_test_files.sh": fill(RESET_SH),
        "tests/setup.sh": (fill(SETUP_SH), 0o755),
        "tests/test.sh": (fill(TEST_SH).replace("__TEST_COMMAND__", shlex.quote(instance["test_command"])), 0o755),
    }


def original_payload(filename, index, row, instance, image):
    """The complete source row, sufficient to rebuild it without the upstream Parquet."""
    dump = lambda value: json.dumps(value, sort_keys=True, ensure_ascii=False, indent=1) + "\n"
    return {
        "original/row.json": dump(row),
        "original/instance.json": dump(instance),
        "original/image.json": dump({
            "dataset": DATASET, "revision": REVISION, "source_file": filename, "row_index": index,
            "dataset_image": instance["docker_image"], "dockerhub_image": image}),
    }


def convert(source, output):
    check_source(source)
    mapping = read_mapping(source / "image-mapping.jsonl")
    records, code, archived = {}, {}, []

    known = set()
    for subset in SUBSETS:
        for index, row, instance, image in read_subset(source, subset, mapping):
            task_id = instance["instance_id"]
            if task_id.lower() in known:
                raise ValueError(f"duplicate instance ID: {task_id}")
            known.add(task_id.lower())
            records[task_id] = {"project": subset, "bug_id": task_id,
                                "dataset_image": instance["docker_image"], "dockerhub_image": image}
            if subset == "code" and task_id in EXCLUDED and pinned(image)[0] is not None:
                category, reason = EXCLUDED[task_id]
                archived.append({
                    "path": task_id,
                    "task_binary": pack_task(original_payload(SUBSETS[subset][0], index, row, instance, image)),
                    "archive_category": category,
                    "archive_reason": f"{category}: Code task {task_id} (published image {image}). " + reason})
            elif subset == "code" and pinned(image)[0] is None:
                archived.append({
                    "path": task_id,
                    "task_binary": pack_task(original_payload(SUBSETS[subset][0], index, row, instance, image)),
                    "archive_category": REMOVED_CATEGORY,
                    "archive_reason": f"{REMOVED_CATEGORY}: Code task {task_id} (published image {image}). "
                                      + REMOVED_REASON})
            elif subset == "code":
                code[task_id] = code_files(row, instance, image)
            else:
                archived.append({
                    "path": task_id,
                    "task_binary": pack_task(original_payload(SUBSETS[subset][0], index, row, instance, image)),
                    "archive_category": ARCHIVE_CATEGORY,
                    "archive_reason": f"{ARCHIVE_CATEGORY}: Cyber task {task_id} (published image {image}). "
                                      + ARCHIVE_REASON})
    archived.sort(key=lambda entry: entry["path"])
    output.mkdir(parents=True, exist_ok=True)
    write_tasks(sorted(code.items()), output / "tasks.parquet", expected_count=SUBSETS["code"][1] - len(removed_code(source, mapping)) - len(EXCLUDED))
    rows = [{"path": task_id, "task_binary": pack_task(files)} for task_id, files in sorted(code.items())]
    write_conversion_report(
        output, rows, archived, patcher=__file__, records=records,
        source={"dataset": DATASET, "url": f"https://huggingface.co/datasets/{DATASET}/tree/{REVISION}",
                "revision": REVISION, "task_count": len(records),
                "subsets": {name: count for name, (_, count) in SUBSETS.items()},
                "mimo_agent_revision": MIMO_AGENT_REVISION},
        # One label covers the whole adapter; the explanation appears once per PR table.
        change_labels={row["path"]: [CONVERSION_LABEL] for row in rows},
        change_reasons={row["path"]: CONVERSION_REASON for row in rows})


def removed_code(source, mapping):
    """Code task IDs whose published image tag was removed upstream."""
    return {instance["instance_id"] for _, _, instance, image in read_subset(source, "code", mapping)
            if pinned(image)[0] is None}


def self_check(source, output):
    """Re-read the written files and account for every source row."""
    mapping = read_mapping(source / "image-mapping.jsonl")
    expected = {subset: {instance["instance_id"]: (row, instance)
                         for _, row, instance, _ in read_subset(source, subset, mapping)}
                for subset in SUBSETS}
    kept = pq.read_table(output / "tasks.parquet", columns=["path"]).column("path").to_pylist()
    archive = pq.read_table(output / "tasks.archive.parquet").to_pylist()
    dropped = [row["path"] for row in archive]
    problems = []
    removed = removed_code(source, mapping)
    residue = set(EXCLUDED)
    if not residue <= set(expected["code"]) - removed:
        problems.append("archive by name names a task that is not a pinned Code task")
    if sorted(kept) != sorted(set(expected["code"]) - removed - residue) or len(set(kept)) != len(kept):
        problems.append("kept tasks differ from the Code source IDs with a pinned image and no residue")
    if sorted(dropped) != sorted(set(expected["cyber"]) | removed | residue) or len(set(dropped)) != len(dropped):
        problems.append("archived tasks differ from the Cyber source IDs plus removed-image and residue Code IDs")
    if set(kept) & set(dropped):
        problems.append("kept and archived IDs overlap")
    for row in archive:
        task_id = row["path"]
        category, subset, reason = ((REMOVED_CATEGORY, "Code", REMOVED_REASON) if task_id in removed
                                    else (EXCLUDED[task_id][0], "Code", EXCLUDED[task_id][1]) if task_id in residue
                                    else (ARCHIVE_CATEGORY, "Cyber", ARCHIVE_REASON))
        prefix = f"{category}: {subset} task {task_id} "
        if row["archive_category"] != category or not row["archive_reason"].startswith(prefix) \
                or not row["archive_reason"].endswith(reason):
            problems.append(f"{task_id}: unexpected archive category or reason")
        with tarfile.open(fileobj=io.BytesIO(row["task_binary"])) as payload:
            original = {name: json.load(payload.extractfile(name)) for name in payload.getnames()}
        source_row = expected["cyber"].get(task_id) or expected["code"].get(task_id)
        if (original.get("original/row.json"), original.get("original/instance.json")) != source_row:
            problems.append(f"{task_id}: archived payload differs from the source row")
    manifest = json.loads((output / "tasks.manifest.json").read_text())
    actions = {}
    for task in manifest["tasks"]:
        actions[task["action"]] = actions.get(task["action"], 0) + 1
    if manifest.get("complete") is not True or actions != {
            "changed": len(expected["code"]) - len(removed) - len(residue),
            "dropped": len(expected["cyber"]) + len(removed) + len(residue)}:
        problems.append(f"manifest is incomplete or has unexpected actions: {actions}")
    if any(not task.get("reason") for task in manifest["tasks"]):
        problems.append("manifest task without a reason")
    if problems:
        raise SystemExit("MiMo conversion self-check failed:\n" + "\n".join(problems[:20]))
    total = len(expected["code"]) + len(expected["cyber"])
    print(f"source rows read: {total} (code {len(expected['code'])}, cyber {len(expected['cyber'])})")
    print(f"tasks.parquet: {len(kept)} converted Code tasks pinned by image digest, label {CONVERSION_LABEL}")
    print(f"tasks.archive.parquet: {len(dropped)} archived rows ({len(expected['cyber'])} Cyber, category "
          f"{ARCHIVE_CATEGORY}; {len(removed)} Code, category {REMOVED_CATEGORY}; {len(RESIDUE) + len(RESIDUE_UNTESTED)} Code, category "
          f"{RESIDUE_CATEGORY}; {len(INCOMPLETE_PACKAGES)} Code, category {INCOMPLETE_PACKAGES_CATEGORY}; "
          f"{len(NOP_REVIEW)} Code, no-op review), "
          "original payloads equal the source rows")
    print(f"ID accounting: {len(set(kept) | set(dropped))} of {total} source IDs, no overlap")
    print(f"tasks.manifest.json: complete, {actions['changed']} changed, {actions['dropped']} dropped")


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("--source", type=Path, required=True,
                        help="directory with the pinned code.parquet, cyber.parquet and image-mapping.jsonl")
    parser.add_argument("--output", type=Path, required=True, help="new output directory")
    args = parser.parse_args()
    if not args.source.is_dir():
        raise ValueError(f"missing pinned MiMo source directory: {args.source}")
    convert(args.source, args.output)
    self_check(args.source, args.output)


if __name__ == "__main__":
    main()