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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
"""Opt-in, bounded local execution of feedback repairs (stdlib only).

``execute_repairs(config_path, output, *, execute=False)`` returns a JSON dict
and retains result.json, history, per-round chain results, logs and all outputs.
Without both execute=True and repair_execution.enabled=True there is one chain
call and no retry. Enabled settings require max_attempts in [1, 10] (including
the initial generation) and finite positive total_timeout_s. An existing
attempt_index consumes that same budget; neither attempts nor seeds reset.

Controller integration contract: run_chain must expose generated_manifest and
output_manifest_sha256 even for diagnosed outputs, native_contract_passed before
measured diagnostics, inputs_unchanged, implementation_sha256 and input_sha256.
It writes validated diagnostics to attempt_01/output_review.json and calls
feedback.plan_repair with the ACTUAL output and verified effective request.
If eligibility changes the request, attempt_01/effective_request_review.json
provides passed=True and the sealed effective_request path and fingerprint.
generation.diagnostics_output is interpreted ONLY by run_chain; arbitrary error
strings, preflight plans, config diagnostics and external receipts cannot retry.

The plan source fingerprint is canonical JSON, whereas controller output hashes
bind exact file bytes. Next-round manifest and preservation_plan refer to that
actual prior output and its controller plan; next_request is used verbatim.
Each round is run in a subprocess under the one monotonic deadline, including
preflight. process_control adds at most its bounded TERM/KILL grace (1.5s), plus
OS/snapshot overhead, to a deadline; this is not a hard realtime sandbox.
Rounds are never reused. Original config, implementation, controller-bound inputs
and completed round files are checked across rounds. No evidence hash, task,
prior, native source, asset domain or seed is silently replaced. Each generated
scene with task/prior requirements needs fresh, scene-bound measured evidence.
The controller accepts a configured measurement hook and only propagates its
validated evidence. Native reports establish search enforcement; independent
verify_preservation comparisons establish output preservation.
physical_qualified and whole_task_acceptance remain false in every result.
"""
from __future__ import annotations

import copy
import hashlib
import json
import math
from pathlib import Path
import sys
import time

if __package__:
    from .feedback import verify_preservation, geometry_scope_supported
    from .process_control import execute_command
    from .run_chain import BASE, contained, digest, load, save
else:
    from feedback import verify_preservation, geometry_scope_supported
    from process_control import execute_command
    from run_chain import BASE, contained, digest, load, save


__all__ = ['execute_repairs']

# Deliberately closed: unknown, missing-evidence, source and contract errors stop.
_REPAIRABLE_CODES = frozenset((
    'collision', 'entity_collision', 'layout_collision', 'overlap',
    'out_of_bounds', 'access_blocked', 'clearance_violation',
    'support_footprint_outside_region', 'support_height_out_of_range',
    'approach_width_below_minimum', 'reservation_out_of_bounds',
    'reservation_overlap', 'reservation_footprint_overlap',
    'support_contact_invalid',
))
_OUTPUT_STATUSES = frozenset((
    'output_contract_failed', 'generation_completed_pending_native_validation',
    'generation_completed_pending_measured_review',
    'generation_completed_pending_geometry_review', 'generation_completed_geometry_verified',
))


class _IntegrityError(ValueError):
    pass


def _fingerprint(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'),
                                     allow_nan=False).encode('utf-8')).hexdigest()


def _positive(value, label):
    if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
        raise ValueError(label + ' must be finite and positive')
    return value


def _integer(value, label):
    if type(value) is not int or not 1 <= value <= 10:
        raise ValueError(label + ' must be an integer in [1, 10]')
    return value


def _implementation_hashes():
    return {str(p.relative_to(BASE)): digest(p)
            for p in [*BASE.glob('*.py'), BASE / 'source/scripts/run_frontier_generation.py']}


def _absolute_config(config, parent):
    config = copy.deepcopy(config)

    def absolute(value):
        if not isinstance(value, str) or not value:
            raise ValueError('Require a nonempty config file path')
        return str((parent / value).resolve())

    for key in ('manifest', 'request', 'preservation_plan'):
        if key in config:
            config[key] = absolute(config[key])
    if 'prepared_pools' in config:
        if not isinstance(config['prepared_pools'], list):
            raise ValueError('prepared_pools must be a list')
        config['prepared_pools'] = [absolute(value) for value in config['prepared_pools']]
    generation = config.get('generation', {})
    if not isinstance(generation, dict):
        raise ValueError('generation must be an object')
    for key in ('runtime_template', 'cwd'):
        if generation.get(key):
            generation[key] = absolute(generation[key])
    return config


def _check_pins(pins):
    for name, expected in pins.items():
        try:
            valid = Path(name).is_file() and digest(name) == expected
        except OSError:
            valid = False
        if not valid:
            raise _IntegrityError('Previously bound file changed: ' + name)


def _pin(pins, name, expected=None):
    name = str(Path(name).resolve())
    actual = digest(name)
    if expected is not None and expected != actual or name in pins and pins[name] != actual:
        raise _IntegrityError('File differs from its bound SHA256: ' + name)
    pins[name] = actual


def _actual_output(round_path, config, native, pins):
    attempt = round_path / 'attempt_01'
    expected = contained(attempt, config['generation']['manifest_output'])
    # A result path is evidence only inside this fresh, exact attempt.
    actual = Path(native['generated_manifest'])
    if not actual.is_absolute() or actual.resolve() != expected:
        raise ValueError('Controller generated_manifest does not name this round output')
    _pin(pins, actual, native['output_manifest_sha256'])
    return expected, load(expected)


def _bound_plan(round_path, config, native, actual, pins, index, maximum):
    review_path = round_path / 'attempt_01/output_review.json'
    plan_path = round_path / 'repair_plan.json'
    review, plan = load(review_path), load(plan_path)
    _pin(pins, review_path)
    _pin(pins, plan_path)
    if __package__:
        from .search_bridge import compile_search_request
    else:
        from search_bridge import compile_search_request
    effective = compile_search_request(load(config['request']), config, load(config['manifest']))
    audit_path = round_path / 'attempt_01/effective_request_review.json'
    if audit_path.exists():
        audit = load(audit_path)
        path = Path(audit['effective_request'])
        attempt = (round_path / 'attempt_01').resolve()
        if (audit.get('passed') is not True or not path.is_absolute()
                or attempt not in path.resolve().parents):
            raise ValueError('Effective request must be sealed inside this actual attempt')
        hashes = native['input_sha256']
        if str(path.resolve()) not in hashes:
            raise ValueError('Effective request was not bound by the controller')
        _pin(pins, path, hashes[str(path.resolve())])
        effective = load(path)
        if _fingerprint(effective) != audit.get('effective_request_sha256'):
            raise ValueError('Effective request fingerprint changed')
        _pin(pins, audit_path)
    if (plan.get('attempt_index') != index or plan.get('max_attempts') != maximum
            or plan.get('source_request_sha256') != _fingerprint(effective)
            or plan.get('diagnostics') != review.get('diagnostics')
            or not verify_preservation(actual, actual, plan)['passed']):
        raise ValueError('Controller repair plan does not bind this actual output/request/budget')
    diagnostics = review['diagnostics']
    expected_passed = not diagnostics and (not native.get('geometry_requested')
                                           or native.get('geometry_passed') is True)
    if not isinstance(diagnostics, list) or review.get('passed') is not expected_passed:
        raise ValueError('Invalid validated output review')
    return plan_path, plan, diagnostics


def execute_repairs(config_path, output, *, execute=False):
    """Execute one chain call or opt-in local repairs; see module contract."""
    started = time.monotonic()
    config_path, output = Path(config_path).resolve(), Path(output).resolve()
    if output == BASE or output == BASE / 'source' or BASE / 'source' in output.parents:
        raise ValueError('Repair outputs must be outside the saved source tree')
    output.mkdir(parents=True, exist_ok=False)
    result = dict(schema='rhg.frontier.repair-execution-result.v1',
        status='configuration_failed', history=[], count=0, total_elapsed_s=0.,
        generation_executed=False, output_contract_passed=False, native_contract_passed=False,
        preservation_requested=False, preservation_enforced=False,
        preservation_verified=False, physical_execution='not_run',
        geometry_requested=False, geometry_current=False, geometry_passed=False,
        geometry_provenance_current=False, geometry_complete=False,
        physical_qualified=False, whole_task_acceptance=False,
        automatic_seed_replacement=False, automatic_retry=False, inputs_unchanged=True)
    pins, sealed_rounds = {}, {}
    deadline = None
    try:
        _pin(pins, config_path)
        config = _absolute_config(load(config_path), config_path.parent)
        if config.get('schema') != 'rhg.frontier-chain-config.v1':
            raise ValueError('Unsupported frontier chain config schema')
        settings = config.get('repair_execution', {})
        if not isinstance(settings, dict) or type(settings.get('enabled', False)) is not bool:
            raise ValueError('repair_execution must be an object with boolean enabled')
        enabled = settings.get('enabled', False)
        if enabled and not {'max_attempts', 'total_timeout_s'} <= settings.keys():
            raise ValueError('Enabled repairs require max_attempts and total_timeout_s')
        maximum = _integer(settings.get('max_attempts', config.get('max_attempts', 1)), 'max_attempts')
        index = _integer(config.get('attempt_index', 1), 'attempt_index')
        timeout = _positive(settings.get('total_timeout_s',
            _positive(config.get('generation', {}).get('timeout_s', 7200), 'timeout_s') + 30),
            'total_timeout_s')
        deadline = started + timeout
        result.update(max_attempts=maximum, total_timeout_s=timeout)
        implementations = _implementation_hashes()
        result['implementation_sha256'] = implementations
        for name, sha in implementations.items():
            _pin(pins, BASE / name, sha)
        _pin(pins, BASE / 'BASE_SHA256SUMS')
        for key in ('manifest', 'request', 'preservation_plan'):
            if config.get(key):
                _pin(pins, config[key])
        generation = config.get('generation', {})
        if generation.get('runtime_template'):
            _pin(pins, generation['runtime_template'])
        for name in config.get('prepared_pools', []):
            _pin(pins, name)
        pending_plan = load(config['preservation_plan']) if config.get('preservation_plan') else None
        if load(config['request']).get('repair') is not None and pending_plan is None:
            raise ValueError('Continuing a repair requires its bound preservation_plan; attempts cannot reset')
        if pending_plan:
            index = _integer(config.get('attempt_index', pending_plan['next_attempt_index']), 'attempt_index')
            if pending_plan.get('max_attempts') != maximum:
                raise ValueError('Existing preservation plan and global attempt budget disagree')
        if index > maximum:
            result['status'] = 'budget_exhausted'
            return result
        controls = output / 'control'
        controls.mkdir()
        while index <= maximum:
            _check_pins(pins)
            if _implementation_hashes() != implementations:
                raise _IntegrityError('Original implementation inventory changed')
            for directory, names in sealed_rounds.items():
                if {str(p) for p in Path(directory).rglob('*') if p.is_file()} != names:
                    raise _IntegrityError('Completed round inventory changed: ' + directory)
            if time.monotonic() >= deadline:
                result['status'] = 'total_timeout'
                break
            number = len(result['history']) + 1
            round_path = output / ('round_%02d' % number)
            round_config = copy.deepcopy(config)
            round_config.update(attempt_index=index, max_attempts=maximum)
            # The controller never retries; only this loop owns the global count.
            round_config['repair_execution'] = dict(enabled=False)
            round_config_path = controls / ('round_%02d.config.json' % number)
            save(round_config_path, round_config)
            _pin(pins, round_config_path)
            entry = dict(attempt_index=index, output=str(round_path),
                config_path=str(round_config_path), preservation_requested=pending_plan is not None,
                preservation_enforced=False, preservation_verified=False)
            result['history'].append(entry)
            result['count'] = len(result['history'])
            result['automatic_retry'] = number > 1
            result['preservation_requested'] = pending_plan is not None
            result['preservation_verified'] = False
            result['native_contract_passed'] = False
            for key in ('geometry_requested', 'geometry_current', 'geometry_passed',
                        'geometry_provenance_current', 'geometry_complete'):
                result[key] = False
            result.pop('geometry_validation', None)
            command = [sys.executable, str(BASE / 'run_chain.py'),
                       '--config', str(round_config_path), '--output', str(round_path)]
            if execute:
                command.append('--execute')
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                result['status'] = 'total_timeout'
                break
            entry['command'] = execute_command(command, BASE,
                controls / ('round_%02d.log' % number), remaining)
            save(controls / ('round_%02d.command.json' % number), entry['command'])
            native_path = round_path / 'result.json'
            native = load(native_path) if native_path.is_file() else {}
            entry['result'] = native
            if native.get('candidate_admission_failure'):
                result['candidate_admission_failure'] = native['candidate_admission_failure']
            for key in ('geometry_requested', 'geometry_current', 'geometry_passed',
                        'geometry_provenance_current', 'geometry_complete'):
                result[key] = native.get(key) is True
            if isinstance(native.get('geometry_validation'), dict):
                result['geometry_validation'] = native['geometry_validation']
            geometry = native.get('geometry_validation') or {}
            entry['failure_record'] = dict(
                geometry_label=('failure' if native.get('geometry_provenance_current')
                    and geometry.get('diagnostics') else 'pass' if native.get('geometry_passed')
                    else 'unknown'),
                measurement_label='failure' if geometry.get('status') == 'failed' else (
                    'measured' if native.get('geometry_provenance_current') else 'unknown'),
                geometry_complete=native.get('geometry_complete') is True,
                pending_fields=geometry.get('pending_fields', []),
                diagnostics=geometry.get('diagnostics', []),
                result_status=native.get('status', 'unknown'),
                accepted_training_positive=False)
            entry['repair_record'] = dict(action='not_executed', outcome='unknown',
                                         accepted_training_positive=False)
            result['generation_executed'] |= native.get('generation_executed', False)
            result['output_contract_passed'] = native.get('output_contract_passed', False)
            _check_pins(pins)
            if entry['command']['timed_out'] or time.monotonic() >= deadline:
                result.update(status='total_timeout', output_contract_passed=False)
                break
            if not entry['command']['cleanup_passed']:
                result.update(status='cleanup_failed', output_contract_passed=False)
                break
            result['status'] = native.get('status', 'chain_failed')
            if not native:
                break
            if native.get('implementation_sha256') != implementations:
                raise _IntegrityError('Controller implementation differs from the original snapshot')
            if native.get('inputs_unchanged') is not True:
                raise _IntegrityError('Controller input integrity check failed')
            for name, sha in native['input_sha256'].items():
                _pin(pins, name, sha)
            result['native_contract_passed'] = native.get('native_contract_passed') is True
            result['preservation_enforced'] = native.get('preservation_enforced') is True
            entry['preservation_enforced'] = result['preservation_enforced']
            if native.get('error_type') or native['status'] not in _OUTPUT_STATUSES:
                break
            inner_command = native.get('command', {})
            if (not native.get('generation_executed') or inner_command.get('exit_code') != 0
                    or inner_command.get('timed_out') or not inner_command.get('cleanup', {}).get('complete')):
                break
            actual_path, actual = _actual_output(round_path, round_config, native, pins)
            result.update(generated_manifest=str(actual_path),
                          output_manifest_sha256=native['output_manifest_sha256'])
            if (native.get('geometry_requested') and not native.get('geometry_current')
                    and not native.get('geometry_provenance_current')):
                result['status'] = ('generation_completed_pending_geometry_review'
                    if (native.get('geometry_validation') or {}).get('status') == 'pending'
                    else 'manual_review_required')
                break
            if pending_plan is not None:
                receipt = verify_preservation(load(round_config['manifest']), actual, pending_plan,
                    geometry_evidence=native.get('geometry_validation') if native.get('geometry_requested') else None)
                save(round_path / 'preservation_verification.json', receipt)
                entry['preservation_verified'] = receipt['preservation_verified']
                result['preservation_verified'] = receipt['preservation_verified']
                entry['repair_record'].update(action='executed', outcome=(
                    'preservation_verified' if receipt['preservation_verified'] else 'failure'),
                    changed_entity_ids=receipt['changed_entity_ids'])
                if not receipt['passed']:
                    result.update(status='preservation_failed', output_contract_passed=False)
                    break
            if native.get('native_contract_passed') is not True:
                break
            if (native.get('measurement_refresh') or {}).get('status') == 'failed':
                result['status'] = 'manual_review_required'
                break
            # The pinned controller accepts only measurements bound to this output.
            if native.get('refreshed_evidence_config'):
                updates = native['refreshed_evidence_config']
                if updates.get('evidence_manifest_sha256') != native['output_manifest_sha256']:
                    raise ValueError('Refreshed evidence is stale')
                config.update(updates)
            if ((config.get('task') or config.get('priors'))
                    and (not native.get('measurement_current')
                         or native['output_manifest_sha256'] != config.get('evidence_manifest_sha256'))):
                result['status'] = 'generation_completed_pending_measured_review'
                break
            if not execute or not enabled:
                break
            plan_path, plan, diagnostics = _bound_plan(
                round_path, round_config, native, actual, pins, index, maximum)
            entry['repair_plan'] = str(plan_path)
            entry['diagnostics'] = diagnostics
            entry['failure_record']['diagnostics'] = diagnostics
            entry['repair_record']['plan_status'] = plan['status']
            if not diagnostics:
                break
            if any(not d.get('entity_ids') or d.get('code') not in _REPAIRABLE_CODES for d in diagnostics):
                result['status'] = 'manual_review_required'
                break
            if plan['status'] != 'repair_planned':
                result['status'] = plan['status']
                break
            if (native.get('geometry_requested') and not native.get('geometry_current')
                    and not geometry_scope_supported(actual, native.get('geometry_validation'),
                        plan['resample_entity_ids'], diagnostics=diagnostics)):
                entry['repair_record'].update(action='blocked', outcome='unknown',
                    reason='Current measured evidence does not cover the repair dependency closure')
                result['status'] = 'manual_review_required'
                break
            entry['repair_record'].update(action='planned', outcome='unknown',
                resample_entity_ids=plan['resample_entity_ids'],
                preserved_entity_ids=plan['preserved_entity_ids'])
            if (plan.get('next_attempt_index') != index + 1 or index >= maximum
                    or not isinstance(plan.get('next_request'), dict)):
                raise ValueError('Invalid next repair attempt or exhausted global budget')
            next_request_path = round_path / 'next_request.json'
            if load(next_request_path) != plan['next_request']:
                raise ValueError('Stored next_request differs from controller feedback plan')
            config.update(manifest=str(actual_path), request=str(next_request_path),
                          preservation_plan=str(plan_path))
            pending_plan = plan
            for path in round_path.rglob('*'):
                if path.is_file():
                    _pin(pins, path)
            sealed_rounds[str(round_path)] = {str(p) for p in round_path.rglob('*') if p.is_file()}
            index = plan['next_attempt_index']
    except _IntegrityError as error:
        result.update(status='input_integrity_failed', inputs_unchanged=False,
                      output_contract_passed=False, error_type=type(error).__name__, error=str(error))
    except Exception as error:
        result.update(status='configuration_failed' if not result['history'] else 'manual_review_required',
                      output_contract_passed=False, error_type=type(error).__name__, error=str(error))
    finally:
        try:
            _check_pins(pins)
            if ('implementation_sha256' in result
                    and _implementation_hashes() != result['implementation_sha256']):
                raise _IntegrityError('Original implementation inventory changed')
        except _IntegrityError as error:
            result.update(status='input_integrity_failed', inputs_unchanged=False,
                          output_contract_passed=False, error=str(error))
        result['input_sha256'] = pins
        result['total_elapsed_s'] = time.monotonic() - started
        if deadline is not None and time.monotonic() >= deadline and result['inputs_unchanged']:
            result.update(status='total_timeout', output_contract_passed=False)
        if result['status'] in ('input_integrity_failed', 'source_integrity_failed',
                                'preservation_failed', 'total_timeout', 'cleanup_failed'):
            result['native_contract_passed'] = False
            result['preservation_verified'] = False
            result['geometry_current'] = False
            result['geometry_passed'] = False
            result['geometry_provenance_current'] = False
        save(output / 'result.json', result)
    return result