File size: 24,599 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Editable development packages and immutable experiment input revisions.

Only explicitly selected videos or complete sessions and ordinary files cross this boundary.
Evaluator cases and repository source are never added implicitly.
"""
from __future__ import annotations

import functools
import hashlib
import json
import os
import shutil
import subprocess
import tempfile
import threading
import uuid
from pathlib import Path, PurePosixPath

from bench_builder.util.digest import sha256_file

_LOCK = threading.RLock()


def _write(path: Path, value) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + '.tmp')
    temporary.write_text(json.dumps(value, indent=2), encoding='utf-8')
    temporary.replace(path)


def _id(value: str) -> str:
    import re
    if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,159}', value):
        raise ValueError('Invalid development input identifier')
    return value


def file_path(root: Path, name: str) -> Path:
    relative = PurePosixPath(name)
    if not name or '\\' in name or relative.is_absolute() or any(p in {'.', '..'} for p in relative.parts):
        raise ValueError('Use a relative file path inside the development package')
    path = root.joinpath(*relative.parts)
    if not path.resolve().is_relative_to(root.resolve()):
        raise ValueError('Development file escapes its package')
    if any(p.is_symlink() for p in (path, *path.parents) if p != root.parent):
        raise ValueError('Development files must not be symlinks')
    return path


def _files(root: Path):
    for path in sorted(root.rglob('*')):
        if path.is_symlink():
            raise ValueError('Development inputs must not contain symlinks')
        if path.is_file():
            yield path


def inventory(root: Path) -> dict[str, str]:
    return {path.relative_to(root).as_posix(): sha256_file(path) for path in _files(root)}


def recordings(task):
    from bench_builder.program_bench import discover_reference_recordings
    return {item.session_id: item for item in discover_reference_recordings(task) if item.playable}


def draft_root(task, draft='default') -> Path:
    return task.package_dir / 'development' / 'drafts' / _id(draft)


def ensure_default(task) -> Path:
    root = draft_root(task)
    with _LOCK:
        if (root / 'selection.json').is_file():
            return root
        from bench_builder.program_bench import public_design_prompt_text, _prepare_workspace_assets
        files = root / 'files'
        files.mkdir(parents=True, exist_ok=True)
        (files / 'instruction.md').write_text(public_design_prompt_text(task) or task.instruction, encoding='utf-8')
        # Initial assets are ordinary editable files. No recording is selected
        # implicitly; the author chooses the information condition explicitly.
        (files / 'assets').mkdir(exist_ok=True)
        _prepare_workspace_assets(task, files / 'assets')
        _write(root / 'selection.json', {'recording_ids': []})
    return root


def draft_files(task, draft='default') -> dict[str, Path]:
    """Resolve shared inputs and this draft's local edits without copying bytes."""
    root = draft_root(task, draft)
    selection = json.loads((root / 'selection.json').read_text())
    shared = selection.get('shared_files', {})
    if not isinstance(shared, dict):
        raise ValueError('Invalid shared development files')
    files = {path.relative_to(root / 'files').as_posix(): path for path in _files(root / 'files')}
    for name, source in shared.items():
        file_path(root / 'files', name)
        if not isinstance(source, str):
            raise ValueError('Invalid shared development file path')
        parts = PurePosixPath(source).parts
        if (len(parts) < 5 or parts[0] != 'development'
                or parts[1] not in {'drafts', 'revisions'} or parts[3] != 'files'):
            raise ValueError('Shared files must reference development inputs in this task')
        _id(parts[2])
        path = file_path(task.package_dir, source)
        if name in files:
            continue
        if not path.is_file():
            raise ValueError(f'Shared development file is unavailable: {name}')
        files[name] = path
    return dict(sorted(files.items()))


def resolve_draft_file(task, draft, name) -> Path:
    file_path(draft_root(task, draft) / 'files', name)
    path = draft_files(task, draft).get(name)
    if path is None:
        raise ValueError('Development file was not found')
    return path


def read_state(task, draft='default') -> dict:
    if draft == 'default':
        ensure_default(task)
    root = draft_root(task, draft)
    selection = json.loads((root / 'selection.json').read_text())
    files = draft_files(task, draft)
    return {
        'draftId': draft, 'recordingIds': selection['recording_ids'],
        'name': selection.get('name', ''),
        'buildOptions': selection.get('build_options', {}),
        'recordingMode': selection.get('recording_mode', 'video'),
        'instruction': files['instruction.md'].read_text(encoding='utf-8') if 'instruction.md' in files else '',
        'files': [{'path': name, 'bytes': path.stat().st_size} for name, path in files.items()],
        'recordings': [{'sessionId': sid, 'label': f'{item.track_id} · {sid}',
                        'videoUrl': f'/api/tasks/{task.task_id}/reference-studio/recordings/{sid}/video'}
                       for sid, item in recordings(task).items()],
    }


def remove_recording_selection(task, session_id: str) -> None:
    """Unselect a deleted recording in editable drafts; preserve frozen revisions."""
    with _LOCK:
        for path in (task.package_dir / 'development' / 'drafts').glob('*/selection.json'):
            selection = json.loads(path.read_text())
            ids = selection.get('recording_ids', [])
            if session_id in ids:
                selection['recording_ids'] = [item for item in ids if item != session_id]
                _write(path, selection)


def save(task, draft, instruction, recording_ids, recording_mode='video'):
    if recording_mode not in {'video', 'session'}:
        raise ValueError('Recording mode must be video or session')
    with _LOCK:
        root = draft_root(task, draft)
        if not (root / 'selection.json').is_file():
            raise ValueError('Development draft was not found')
        available = recordings(task)
        if any(sid not in available for sid in recording_ids):
            raise ValueError('A selected recording is unavailable')
        selection = json.loads((root / 'selection.json').read_text())
        (root / 'files').mkdir(exist_ok=True)
        (root / 'files' / 'instruction.md').write_text(instruction, encoding='utf-8')
        selection.get('shared_files', {}).pop('instruction.md', None)
        selection.update(recording_ids=list(dict.fromkeys(recording_ids)), recording_mode=recording_mode)
        _write(root / 'selection.json', selection)
    return read_state(task, draft)


def write_file(task, draft, name, content: bytes | None):
    with _LOCK:
        root = draft_root(task, draft)
        if not (root / 'selection.json').exists():
            raise ValueError('Development draft was not found')
        path = file_path(root / 'files', name)
        selection = json.loads((root / 'selection.json').read_text())
        if content is None:
            path.unlink(missing_ok=True)
        else:
            if any(other != name and (other.startswith(name + '/') or name.startswith(other + '/'))
                   for other in draft_files(task, draft)):
                raise ValueError('Development file conflicts with an existing file or directory')
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(content)
        selection.get('shared_files', {}).pop(name, None)
        _write(root / 'selection.json', selection)
    return read_state(task, draft)


def named_drafts(task) -> list[dict]:
    """List saved build tasks without reading or hashing their shared media."""
    result = []
    for path in sorted((task.package_dir / 'development/drafts').glob('*/selection.json')):
        selection = json.loads(path.read_text())
        if selection.get('name'):
            result.append({'draftId': path.parent.name, 'name': selection['name']})
    return result


def duplicate(task, *, source='default', revision=None, name=None, build_options=None):
    if name is not None and (not name.strip() or len(name) > 200 or any(ord(c) < 32 for c in name)):
        raise ValueError('Build task name must contain 1 to 200 printable characters')
    with _LOCK:
        ensure_default(task)
        draft = uuid.uuid4().hex
        target = draft_root(task, draft)
        if revision:
            original = task.package_dir / 'development' / 'revisions' / _id(revision)
            verify(original)
            files = {path.relative_to(original / 'files').as_posix(): path for path in _files(original / 'files')}
            selection = {'recording_ids': []}
        else:
            original = draft_root(task, source)
            files = draft_files(task, source)
            selection = json.loads((original / 'selection.json').read_text())
        # Instructions and recording selection belong to the new experiment.
        # Large reference files stay at their existing paths; edits create local overrides.
        (target / 'files').mkdir(parents=True)
        if 'instruction.md' in files:
            (target / 'files/instruction.md').write_text(files['instruction.md'].read_text(encoding='utf-8'), encoding='utf-8')
        selection['shared_files'] = {
            name: path.relative_to(task.package_dir).as_posix()
            for name, path in files.items() if name != 'instruction.md'
        }
        if name is not None:
            selection['name'] = name.strip()
        else:
            selection.pop('name', None)
        if build_options is not None:
            selection['build_options'] = build_options
        _write(target / 'selection.json', selection)
    return read_state(task, draft)


def unreferenced_drafts(task, delete=()) -> list[dict]:
    """Report unnamed drafts that no other draft shares files from; delete only the ids given.

    Nothing calls this automatically. ``default`` and named drafts are never listed.
    ``bytes`` is what deleting a draft frees: the files it holds itself, not the shared
    files it points to. A listed draft can still be in use (the Build page keeps its
    current draft unnamed), so read the report first and pass back the ids to delete.
    A draft that only a listed draft references is listed once that one is gone.
    """
    with _LOCK:
        drafts = task.package_dir / 'development' / 'drafts'
        selections = {path.parent.name: json.loads(path.read_text())
                      for path in sorted(drafts.glob('*/selection.json'))}
        referenced = set()
        for draft, selection in selections.items():
            shared = selection.get('shared_files', {})
            if not isinstance(shared, dict):
                raise ValueError(f'Invalid shared development files in draft {draft}')
            for source in shared.values():
                parts = PurePosixPath(str(source)).parts
                # Compared without case: on Windows both spellings are one directory.
                if (parts[:2] == ('development', 'drafts') and len(parts) > 2
                        and parts[2].casefold() != draft.casefold()):
                    referenced.add(parts[2].casefold())
        report = [
            {'draftId': draft, 'bytes': sum(
                path.lstat().st_size for path in (drafts / draft).rglob('*')
                if path.is_file() and not path.is_symlink())}
            for draft, selection in selections.items()
            if draft.casefold() != 'default' and not selection.get('name')
            and draft.casefold() not in referenced
        ]
        delete = set(delete)
        unlisted = delete - {row['draftId'] for row in report}
        if unlisted:
            raise ValueError(f'Not an unnamed, unreferenced draft: {", ".join(sorted(unlisted))}')
        for row in report:
            row['deleted'] = row['draftId'] in delete
            if row['deleted']:
                shutil.rmtree(drafts / row['draftId'])  # A directory name listed above.
    return report


def _frozen_files(revisions: Path) -> dict[str, list[tuple[Path, str]]]:
    """Index the files that existing revisions record, by sha256, without hashing them."""
    held: dict[str, list[tuple[Path, str]]] = {}
    for manifest in revisions.glob('*/inputs.json'):
        if manifest.parent.name.startswith('.'):
            continue  # A staging directory, not a revision.
        try:
            for name, digest in json.loads(manifest.read_text())['files'].items():
                held.setdefault(digest, []).append((manifest.parent / 'files', name))
        except (OSError, ValueError, LookupError, AttributeError, TypeError):
            continue  # An unreadable revision only loses its chance to share bytes.
    return held


def _keep(source, destination, *, held: dict[str, list[tuple[Path, str]]]) -> None:
    """Freeze one file, hard-linking bytes that a frozen file already holds.

    Links are only made between frozen files. The source is never linked: it may be
    a draft file, and ``write_file`` edits drafts in place.
    """
    source, destination = Path(source), Path(destination)
    digest = sha256_file(source)
    for root, name in held.get(digest, ()):
        try:
            os.link(file_path(root, name), destination)
        except (OSError, ValueError):
            continue  # Missing, or this file system cannot link it.
        if sha256_file(destination) == digest:
            return
        destination.unlink()  # That frozen file changed; do not spread it.
    shutil.copy2(source, destination)
    held.setdefault(digest, []).append((destination.parent, destination.name))


def _link_or_copy(source, destination) -> None:
    try:
        os.link(source, destination)
    except OSError:
        shutil.copy2(source, destination)


def freeze(task, draft='default') -> Path:
    """Snapshot a draft as a revision whose files share storage with earlier revisions.

    A revision is still a complete ``files/`` tree. A file whose bytes another revision
    of this task already holds is a hard link to them instead of another copy, and falls
    back to a copy where hard links are unavailable.
    """
    with _LOCK:
        if draft == 'default':
            ensure_default(task)
        root = draft_root(task, draft)
        selection = json.loads((root / 'selection.json').read_text())
        selected = selection['recording_ids']
        revisions = task.package_dir / 'development' / 'revisions'
        revisions.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=revisions, prefix='.preparing-') as temporary:
            staged = Path(temporary)
            keep = functools.partial(_keep, held=_frozen_files(revisions))
            files = draft_files(task, draft)
            shared_revisions = {
                task.package_dir / 'development/revisions' / path.relative_to(task.package_dir).parts[2]
                for path in files.values()
                if path.relative_to(task.package_dir).parts[:2] == ('development', 'revisions')
            }
            for shared in shared_revisions:
                verify(shared)
            (staged / 'files').mkdir()
            for name, source in files.items():
                destination = file_path(staged / 'files', name)
                destination.parent.mkdir(parents=True, exist_ok=True)
                keep(source, destination)
            sources = []
            available = recordings(task)
            for sid in selected:
                if sid not in available:
                    raise ValueError(f'Selected recording is unavailable: {sid}')
                item = available[sid]
                if selection.get('recording_mode') == 'session':
                    target = file_path(staged / 'files', f'recordings/{_id(sid)}')
                    if item.session_dir.is_symlink():
                        raise ValueError('Recording sessions must not be symlinks')
                    list(_files(item.session_dir))  # Reject links before copying any session files.
                    shutil.copytree(item.session_dir, target, copy_function=keep)
                    sources.append({'recording_id': sid, 'mode': 'session', 'path': f'recordings/{sid}'})
                    continue
                from bench_builder.recording_media import browser_video
                video = browser_video(item.effective_video_path)
                target = file_path(staged / 'files', f'recordings/{_id(sid)}{video.suffix.lower()}')
                if target.exists():
                    raise ValueError(f'Recording filename already exists: {target.name}')
                target.parent.mkdir(parents=True, exist_ok=True)
                keep(video, target)
                sources.append({'recording_id': sid, 'video_sha256': sha256_file(target)})
            from . import checkpoints
            entrances = checkpoints.read(task)
            associations = {sid: key for sid, key in entrances['recordings'].items() if sid in selected}
            if entrances['checkpoints'] and (selected or not (staged / 'files/checkpoints.json').exists()):
                _write(staged / 'files' / 'checkpoints.json', {
                    'checkpoints': entrances['checkpoints'],
                    'recordings': associations,
                })
            manifest = {'files': inventory(staged / 'files'), 'recordings': sources}
            revision = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()
            manifest['revision'] = revision
            _write(staged / 'inputs.json', manifest)
            destination = revisions / revision
            if not destination.exists():
                shutil.copytree(staged, destination, copy_function=_link_or_copy)
            verify(destination)
            return destination


def verify(root: Path) -> dict:
    metadata = json.loads((root / 'inputs.json').read_text())
    if inventory(root / 'files') != metadata['files']:
        raise ValueError('Frozen development inputs changed')
    expected = hashlib.sha256(json.dumps({k: v for k, v in metadata.items() if k != 'revision'}, sort_keys=True).encode()).hexdigest()
    if expected != metadata['revision']:
        raise ValueError('Development input revision changed')
    return metadata


def extract_screenshots(task, draft, recording_id, count=12):
    """Materialize screenshots and remove this video's selection explicitly."""
    import imageio_ffmpeg
    if not 1 <= count <= 120:
        raise ValueError('Choose between 1 and 120 screenshots')
    with _LOCK:
        item = recordings(task).get(recording_id)
        if item is None:
            raise ValueError('Recording was not found')
        root = draft_root(task, draft)
        selection = json.loads((root / 'selection.json').read_text())
        _, duration = imageio_ffmpeg.count_frames_and_secs(str(item.effective_video_path))
        if duration <= 0:
            raise ValueError('Recording duration is unavailable')
        with tempfile.TemporaryDirectory(prefix='gbb-development-frames-') as temporary:
            try:
                subprocess.run(
                    [imageio_ffmpeg.get_ffmpeg_exe(), '-v', 'error', '-i', str(item.effective_video_path),
                     '-vf', f'fps={count / duration}', '-frames:v', str(count),
                     str(Path(temporary) / 'frame-%04d.png')],
                    check=True, timeout=180, capture_output=True,
                )
            except subprocess.SubprocessError as exc:
                raise ValueError('Could not extract screenshots from this recording') from exc
            target = file_path(root / 'files', f'screenshots/{_id(recording_id)}-{uuid.uuid4().hex[:8]}')
            shutil.copytree(temporary, target)
        selection['recording_ids'] = [sid for sid in selection['recording_ids'] if sid != recording_id]
        _write(root / 'selection.json', selection)
    return read_state(task, draft)


def import_task_assets(task, draft):
    """Copy the current saved asset selection without requiring publication approval."""
    from bench_builder.program_bench import load_public_pack_review, _inside, _reject_links
    with _LOCK:
        root = draft_root(task, draft)
        if not (root / 'selection.json').exists():
            raise ValueError('Development draft was not found')
        review = load_public_pack_review(task)
        if review is None:
            raise ValueError('Save an asset selection on the task first')
        existing_files = draft_files(task, draft)
        with tempfile.TemporaryDirectory(prefix='.assets-', dir=root) as temporary:
            staged = []
            for item in review.assets:
                if not item.included:
                    continue
                if item.blocked_reason:
                    raise ValueError(f'Asset is not eligible: {item.source_path}')
                source = _inside(task.reference_dir, item.source_path)
                _reject_links(source, label='selected development asset')
                snapshot = Path(temporary) / str(len(staged))
                shutil.copyfile(source, snapshot)
                if sha256_file(snapshot) != item.sha256:
                    raise ValueError('Selected asset changed; refresh the task asset selection')
                relative = item.destination_path.removeprefix('public/assets/').removeprefix('public/')
                name = 'assets/' + relative
                destination = file_path(root / 'files', name)
                existing = existing_files.get(name)
                if existing is not None and sha256_file(existing) != item.sha256:
                    raise ValueError(f'Asset would replace an edited development file: {relative}')
                staged.append((destination, snapshot))
            for destination, snapshot in staged:
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(snapshot, destination)
    return read_state(task, draft)


def prepare_progress_contract(run_dir: Path) -> None:
    """Provide a fixed fallback without replacing any supplied or retained contract."""
    candidate = run_dir / 'candidate'
    paths = (
        run_dir / 'public-inputs/video_agent/analysis/game_design.json',
        run_dir / 'progress-contract.json',
        candidate / 'game_design.json',
    )
    existing = next((path for path in paths if path.is_file()), None)
    if existing is not None:
        if not (candidate / 'game_design.json').exists():
            shutil.copy2(existing, candidate / 'game_design.json')
        return
    if (run_dir / 'agent/progress/snapshots.jsonl').is_file():
        return
    ledger = candidate / 'builder_checks.json'
    if ledger.is_file():
        checks = json.loads(ledger.read_text()).get('requirement_checks')
        if not isinstance(checks, list) or not checks:
            raise ValueError('Existing checklist has no requirements; cannot replace it with a fallback')
        rows = [{'id': row.get('requirement_id', row.get('id')),
                 'acceptance': row.get('acceptance') or row.get('description') or row.get('reason') or row.get('requirement_id') or row.get('id')}
                for row in checks]
        ids = [row['id'] for row in rows]
        if any(not isinstance(key, str) or not key.strip() for key in ids) or len(ids) != len(set(ids)):
            raise ValueError('Existing checklist must have unique nonempty requirement IDs')
        contract = {'observable_requirements': rows, 'source': 'retained_legacy_checklist'}
        _write(run_dir / 'progress-contract.json', contract)
        _write(candidate / 'game_design.json', contract)
        return
    supplied = run_dir / 'public-inputs/game_design.json'
    contract = json.loads(supplied.read_text(encoding='utf-8')) if supplied.is_file() else {
        'observable_requirements': [{
            'id': 'recreate-game',
            'acceptance': 'Recreate the game according to the supplied development instructions and files.',
        }],
        'generated_fallback': True,
    }
    _write(run_dir / 'progress-contract.json', contract)
    _write(candidate / 'game_design.json', contract)