File size: 24,709 Bytes
450ac2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Synthetic finite mechanisms and private semantic audit instruments.



Procedural mechanisms are authored as control logic. They never consume the

public reference transition table. Table mechanisms use separate literal data.

Seed varies labels only; generated_protocol has a separate structural seed.

"""
from collections import deque
from dataclasses import dataclass
import hashlib
import itertools
import json
import random

from .core import Contract, Machine
from .conditions import normalize_fault_schedule


@dataclass(frozen=True)
class Case:
    public: dict
    private: dict


_DESCRIPTIONS = {
    'generated_protocol': ('in_family', 'Versioned synthetic structural instances: two safe diagnostics precede one or two progress stages with independently sampled commands and fallback dynamics.'),
    'routing': ('in_family', 'Designed adaptive-policy control: three safe diagnostic actions precede a commit that must use the distinguished command.'),
    'latch': ('in_family', 'Arm then release a latch; hazards are absorbing.'),
    'handshake': ('in_family', 'Three-stage handshake with a reset command.'),
    'symmetric': ('in_family', 'Two behaviorally symmetric terminals require a semantic anchor.'),
    'neutral': ('in_family', 'Neutral-symbol symmetry permits a shared goal plan.'),
    'long_trace': ('in_family', 'Four consecutive advances precede a goal; probes end at length three.'),
    'rotary': ('in_family', 'Frozen evaluation mechanism: cycle a three-position dial, submit only at position two, or reset the dial; terminals are absorbing.'),
    'interlock': ('in_family', 'Frozen evaluation mechanism: toggle two independent flags and release only when both are set; terminals are absorbing.'),
    'robotics_airlock': ('in_family', 'Dual-door rover airlock controller: standby diagnostics and pressure equalization precede inner-hatch seal and outer-hatch egress; breaching the inner seal while armed triggers a decompression hazard.'),
    'protocol_session': ('in_family', 'Stateful industrial session protocol (SYN -> AUTH -> OPEN -> COMMIT): safe keepalive/handshake probes precede transaction open and commit; out-of-order commits or double-opens trigger a protocol violation hazard.'),
    'extra_state': ('out_of_family', 'An extra progress state passes all three-action probes but postpones the goal.'),
    'incompatible': ('out_of_family', 'An extra reachable neutral sink violates the source model.'),
    'alias': ('out_of_family', 'Goal and hazard observations are merged after actual events; optional anchors ground only unambiguous neutral symbols.'),
    'semantic_corruption': ('out_of_family', 'Raw-equivalent control with swapped actual terminal meanings; optional anchors report those actual meanings.'),
    'bypass': ('out_of_family', 'Privileged checker passes while the actual connecting path is harmful; optional anchors ground actual terminal meanings.'),
    'malformed': ('interface_error', 'Malformed, stalled or exited subprocess response.'),
    'delay': ('out_of_family', 'One-action observation delay with reliable reset; only the absorbing-hazard anchor is universally valid.'),
    'repeat': ('out_of_family', 'Every second observation repeats the previous symbol; only the absorbing-hazard anchor is universally valid.'),
    'drift': ('out_of_family', 'Terminal meaning silently swaps after eight experiment-level actions; optional anchors ground only neutral symbols that remain valid across both phases.'),
}


def catalog():
    return [{'id': key, 'label': key.replace('_', ' ').title(), 'scope': scope,
             'description': description} for key, (scope, description) in _DESCRIPTIONS.items()]


def _table(family):
    if family == 'routing':
        return (((1,0),(1,3),(1,3)), ((2,0),(2,3),(2,3)),
                ((3,0),(3,3),(3,3)), ((4,1),(5,2),(5,2)),
                ((4,1),(4,1),(4,1)), ((5,2),(5,2),(5,2)))
    if family == 'latch':
        return (((1,0),(0,3),(3,2)), ((1,3),(2,1),(3,2)),
                ((2,1),(2,1),(3,2)), ((3,2),(3,2),(3,2)))
    if family == 'handshake':
        return (((1,0),(0,3),(4,2)), ((1,0),(2,3),(4,2)),
                ((3,1),(0,0),(4,2)), ((3,1),(3,1),(4,2)), ((4,2),(4,2),(4,2)))
    if family == 'symmetric':
        return (((1,1),(2,2),(0,0)), ((1,1),(1,1),(1,1)), ((2,2),(2,2),(2,2)))
    if family == 'neutral':
        return (((1,1),(0,0),(0,3)), ((1,1),(1,1),(1,1)))
    if family == 'long_trace':
        return (((1,0),(0,3),(5,2)), ((2,0),(0,3),(5,2)),
                ((3,0),(0,3),(5,2)), ((4,1),(0,3),(5,2)),
                ((4,1),(4,1),(5,2)), ((5,2),(5,2),(5,2)))
    if family == 'incompatible':
        return (((1,0),(0,3),(4,0)), ((1,3),(2,1),(3,2)),
                ((2,1),(2,1),(3,2)), ((3,2),(3,2),(3,2)), ((4,3),(4,3),(4,3)))
    if family == 'extra_state':
        return (((1,0),(0,3),(6,2)), ((2,0),(0,3),(6,2)),
                ((3,0),(0,3),(6,2)), ((4,0),(0,3),(6,2)),
                ((5,1),(0,3),(6,2)), ((5,1),(5,1),(6,2)), ((6,2),(6,2),(6,2)))
    if family == 'rotary':
        return (((1,0),(4,2),(0,0)), ((2,3),(4,2),(0,0)),
                ((0,0),(3,1),(0,0)), ((3,1),(3,1),(3,1)), ((4,2),(4,2),(4,2)))
    if family == 'interlock':
        return (((1,0),(2,0),(5,2)), ((0,0),(3,3),(5,2)),
                ((3,3),(0,0),(5,2)), ((2,0),(1,0),(4,1)),
                ((4,1),(4,1),(4,1)), ((5,2),(5,2),(5,2)))
    if family == 'robotics_airlock':
        return (((1,0),(0,3),(0,3)), ((1,0),(2,0),(1,3)),
                ((0,3),(4,2),(3,1)), ((3,1),(3,1),(3,1)), ((4,2),(4,2),(4,2)))
    if family == 'protocol_session':
        return (((1,0),(0,3),(0,3)), ((1,3),(2,0),(0,3)),
                ((3,3),(0,0),(5,2)), ((5,2),(5,2),(4,1)),
                ((4,1),(4,1),(4,1)), ((5,2),(5,2),(5,2)))
    raise ValueError('unknown mechanism')


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


_PROTOCOL_GENERATOR = 'crosswire-generated-protocol-v1'


def _protocol_parameters(instance_seed):
    """Sample primitive control parameters without consuming the label RNG.



    Every stage is reachable. Diagnostics never emit a terminal event, and a

    goal path uses three or four actions. These are synthetic generator draws,

    not evidence that any natural target population follows this distribution.

    """
    rng = random.Random(instance_seed)
    patterns = [list(pattern) for pattern in itertools.product((0, 3), repeat=3)
                if len(set(pattern)) > 1]
    diagnostics = [list(rng.choice(patterns)) for _ in range(2)]
    progress = []
    for index in range(rng.randint(1, 2)):
        advance, fallback = rng.sample(range(3), 2)
        progress.append({'advance': advance, 'fallback': fallback,
                         'fallback_state': rng.randrange(index + 3),
                         'fallback_output': rng.choice((0, 3))})
        # The final progress step emits goal, so no unused neutral parameter
        # is sampled for it. Intermediate advancement gets a neutral event.
        if index:
            progress[index - 1]['advance_output'] = rng.choice((0, 3))
    return {'diagnostics': diagnostics, 'progress': progress}


def _protocol_table(parameters):
    """Materialize a public reference from control parameters, never a target."""
    stages = parameters['progress']
    goal, hazard = len(stages) + 2, len(stages) + 3
    rows = [tuple((index + 1, event) for event in outputs)
            for index, outputs in enumerate(parameters['diagnostics'])]
    for index, stage in enumerate(stages):
        row = [(hazard, 2)] * 3
        row[stage['advance']] = (index + 3, 1 if index == len(stages) - 1 else stage['advance_output'])
        row[stage['fallback']] = (stage['fallback_state'], stage['fallback_output'])
        rows.append(tuple(row))
    rows.extend((tuple((goal, 1) for _ in range(3)), tuple((hazard, 2) for _ in range(3))))
    return tuple(rows)


def _grounded_anchors(family, output_map):
    """Publish only raw-symbol meanings valid throughout this experiment.



    A sensor's nominal symbol encoding is not necessarily its actual semantic

    correspondence. Aliased and phase-varying terminal symbols have no static

    truthful grounding. Delayed/repeated hazards remain sound only because the

    hazard state is absorbing; their goal observations can precede a hazard.

    """
    if family == 'malformed':
        return {}
    if family == 'neutral':
        return {output_map[1]:1}
    if family in ('semantic_corruption','bypass'):
        return {output_map[1]:2, output_map[2]:1}
    if family in ('alias','drift'):
        return {output_map[0]:0, output_map[3]:3}
    if family in ('delay','repeat'):
        return {output_map[2]:2}
    return {output_map[1]:1, output_map[2]:2}


def make_case(family, seed=17, implementation='procedural', split='development', anchors=False, horizon=4,

              *, instance_seed=None, fault_schedule=None):
    if family not in _DESCRIPTIONS:
        raise ValueError('unknown family')
    if implementation not in ('table', 'procedural'):
        raise ValueError('unknown implementation')
    if split not in ('development', 'evaluation'):
        raise ValueError('unknown split')
    if type(seed) is not int or not 0 <= seed <= 2**32-1:
        raise ValueError('seed must be unsigned 32-bit integer')
    if instance_seed is not None and (type(instance_seed) is not int or not 0 <= instance_seed <= 2**32-1):
        raise ValueError('instance_seed must be an unsigned 32-bit integer or None')
    if family != 'generated_protocol' and instance_seed is not None:
        raise ValueError('instance_seed is supported only by generated_protocol')
    if type(anchors) is not bool or type(horizon) is not int or not 1 <= horizon <= 6:
        raise ValueError('invalid anchors or horizon')
    source_family = family if family in ('generated_protocol','routing','latch','handshake','symmetric','neutral','long_trace','rotary','interlock','robotics_airlock','protocol_session') else 'latch'
    if family == 'extra_state':
        source_family = 'long_trace'
    mechanism = family if family in ('incompatible','extra_state') else source_family
    rng = random.Random(seed)
    input_map, output_map = list(range(3)), list(range(4))
    rng.shuffle(input_map)
    rng.shuffle(output_map)
    contract = Contract(goal=1, hazard=2, horizon=horizon).to_dict()
    private = {'family': family, 'source_family': source_family, 'mechanism': mechanism,
               'implementation': implementation, 'split': split, 'seed': seed,
               'input_map': input_map, 'output_map': output_map, 'contract': contract}
    if family == 'malformed':
        private.update(fault_mode='malformed', fault_after=0)
    if fault_schedule is not None:
        private['fault_schedule'] = normalize_fault_schedule(fault_schedule)
    parent = _digest({'source_family':source_family, 'semantic_version':1})
    design = None
    if family == 'generated_protocol':
        structural_seed = 0 if instance_seed is None else instance_seed
        parameters = _protocol_parameters(structural_seed)
        private.update(instance_seed=structural_seed, generator=_PROTOCOL_GENERATOR,
                       mechanism_parameters=parameters)
        reference_table = _protocol_table(parameters)
        dynamics_hash = _digest({'initial': 0, 'inputs': 3, 'outputs': 4, 'transitions': reference_table})
        parent = _digest({'generator': _PROTOCOL_GENERATOR, 'dynamics_hash': dynamics_hash})
        design = {'generator': _PROTOCOL_GENERATOR, 'dynamics_hash': dynamics_hash,
                  'sampling_unit': 'generated_semantic_dynamics'}
    else:
        reference_table = _table(source_family)
    public = {'reference': Machine('reference', reference_table).to_dict(),
              'contract': contract, 'target_id': _digest(private),
              'anchors': _grounded_anchors(family,output_map) if anchors else {},
              'parent_instance_id': parent}
    if design is not None:
        public['instance_design'] = design
    return Case(public, private)


class _Engine:
    def __init__(self, config, work=None):
        self.config = config
        self.work = work
        self.total_steps = 0
        self.steps_since_reset = 0
        self.phase = 'calibration'
        self.reset()

    def set_phase(self, phase):
        self.phase = phase

    def reset(self):
        if self.work is not None:
            self.work['resets'] = self.work.get('resets',0) + 1
        self.state, self.previous, self.parity = 0, 0, 0
        self.fault_previous = 0
        self.semantic_events = []
        self.steps_since_reset = 0

    def _transition(self, action):
        raise NotImplementedError

    def step(self, input):
        if self.work is not None:
            self.work['steps'] = self.work.get('steps',0) + 1
        if type(input) is not int or not 0 <= input < 3:
            raise ValueError('input outside alphabet')

        fault = self.config.get('fault_schedule')
        phase_applies = True
        if fault is not None:
            req_phase = fault.get('phase', 'deployment')
            if req_phase != 'always' and self.phase != req_phase:
                phase_applies = False
        fault_active = (fault is not None and phase_applies and self.steps_since_reset >= fault.get('step', 0))
        fault_type = fault.get('type') if fault_active else None

        action = self.config['input_map'][input]
        if fault_type == 'actuator_swap':
            action = (action + 1) % 3

        self.state, event = self._transition(action)
        self.total_steps += 1
        self.steps_since_reset += 1

        family = self.config['family']
        # Ground truth is produced from the actual mechanism before its sensor.
        actual = event
        if family in ('semantic_corruption','bypass') or (family == 'drift' and self.total_steps > 8):
            actual = {1:2,2:1}.get(event,event)
        if fault_type == 'semantic_swap':
            actual = {1:2,2:1}.get(actual,actual)
        self.semantic_events.append(actual)

        observed = event
        if family == 'alias' and event == 2:
            observed = 1
        elif family == 'delay':
            observed, self.previous = self.previous, event
        elif family == 'repeat':
            if self.parity:
                observed = self.previous
            self.previous = observed
            self.parity ^= 1
        # Compose scheduled faults after the family's sensor mechanism. A second
        # delay needs its own buffer; sharing `previous` erases one of the delays.
        if fault_type == 'sensor_drift':
            observed = (observed + 1) % 4
        elif fault_type == 'delay_spike':
            observed, self.fault_previous = self.fault_previous, observed
        elif fault_type == 'stuck_output':
            observed = fault.get('value', 0)

        return self.config['output_map'][observed]

    def close(self):
        pass


class _TableEngine(_Engine):
    def __init__(self, config, work=None):
        self.transitions = (_protocol_table(config['mechanism_parameters'])
                            if config['mechanism'] == 'generated_protocol' else _table(config['mechanism']))
        super().__init__(config, work)

    def _transition(self, action):
        return self.transitions[self.state][action]


class _ProceduralEngine(_Engine):
    def _transition(self, action):
        family, state = self.config['mechanism'], self.state
        if family == 'generated_protocol':
            parameters = self.config['mechanism_parameters']
            stages = parameters['progress']
            goal, hazard = len(stages) + 2, len(stages) + 3
            if state == goal:
                return goal, 1
            if state == hazard:
                return hazard, 2
            if state < 2:
                return state + 1, parameters['diagnostics'][state][action]
            index = state - 2
            stage = stages[index]
            if action == stage['advance']:
                return state + 1, 1 if index == len(stages) - 1 else stage['advance_output']
            if action == stage['fallback']:
                return stage['fallback_state'], stage['fallback_output']
            return hazard, 2
        if family == 'routing':
            if state < 3:
                return state + 1, 0 if action == 0 else 3
            if state == 3:
                return (4,1) if action == 0 else (5,2)
            return state, 1 if state == 4 else 2
        if family == 'rotary':
            if state >= 3:
                return state, 1 if state == 3 else 2
            if action == 0:
                dial = (state + 1) % 3
                return dial, 3 if dial == 2 else 0
            if action == 1:
                return (3,1) if state == 2 else (4,2)
            return 0,0
        if family == 'interlock':
            if state >= 4:
                return state, 1 if state == 4 else 2
            if action == 2:
                return (4,1) if state == 3 else (5,2)
            flags = state ^ (1 << action)
            return flags, 3 if flags == 3 else 0
        if family == 'robotics_airlock':
            if state >= 3:
                return state, 1 if state == 3 else 2
            if state == 0:
                return (1, 0) if action == 0 else (0, 3)
            if state == 1:
                return (1, 0) if action == 0 else (2, 0) if action == 1 else (1, 3)
            return (0, 3) if action == 0 else (4, 2) if action == 1 else (3, 1)
        if family == 'protocol_session':
            if state >= 4:
                return state, 1 if state == 4 else 2
            if state == 0:
                return (1, 0) if action == 0 else (0, 3)
            if state == 1:
                return (1, 3) if action == 0 else (2, 0) if action == 1 else (0, 3)
            if state == 2:
                return (3, 3) if action == 0 else (0, 0) if action == 1 else (5, 2)
            return (4, 1) if action == 2 else (5, 2)
        if family == 'neutral':
            if state or action == 0:
                return 1,1
            return 0, 0 if action == 1 else 3
        if family == 'symmetric':
            if state:
                return state, state
            return (1,1) if action == 0 else (2,2) if action == 1 else (0,0)
        if family in ('long_trace','extra_state'):
            goal_state = 5 if family == 'extra_state' else 4
            hazard_state = goal_state + 1
            if state == hazard_state or action == 2:
                return hazard_state,2
            if state == goal_state:
                return goal_state,1
            if action == 1:
                return 0,3
            progress = state + 1
            return progress, 1 if progress == goal_state else 0
        if family == 'handshake':
            if state == 4 or action == 2:
                return 4,2
            if state == 3:
                return 3,1
            if state == 2:
                return (3,1) if action == 0 else (0,0)
            if state == 1:
                return (1,0) if action == 0 else (2,3)
            return (1,0) if action == 0 else (0,3)
        if family == 'incompatible':
            if state == 4:
                return 4,3
            if state == 0 and action == 2:
                return 4,0
        if state == 3 or action == 2:
            return 3,2
        if state == 2:
            return 2,1
        if state == 1:
            return (1,3) if action == 0 else (2,1)
        return (1,0) if action == 0 else (0,3)


def make_engine(private, work=None):
    return (_TableEngine if private['implementation'] == 'table' else _ProceduralEngine)(private, work)


def evaluate_word(private, word, work=None):
    return evaluate_deployment(private, [], word, work=work)


def _replay_calibration(engine, probes):
    """Replay only observed successful step calls, including incomplete prefixes.



    Failed interface calls emit no engine event in these fixtures. Reset clears

    transient state but intentionally preserves experiment-level drift count.

    """
    for index, probe in enumerate(probes):
        if index:
            engine.reset()
        for symbol in probe['word'][:len(probe['outputs'])]:
            engine.step(symbol)
    if probes:
        engine.reset()


def evaluate_deployment(private, probes, word, work=None):
    """Privately audit deployment in the actual post-calibration experiment phase."""
    return _evaluate_phase(private, probes, word, 'deployment', work)


def evaluate_calibration(private, probes, word, work=None):
    """Audit a calibration word without activating deployment-only faults."""
    return _evaluate_phase(private, probes, word, 'calibration', work)


def _evaluate_phase(private, probes, word, phase, work=None):
    engine = make_engine(private, work)
    try:
        _replay_calibration(engine, probes)
        if hasattr(engine, 'set_phase'):
            engine.set_phase(phase)
        outputs = []
        if isinstance(word, dict):
            node = word
            while isinstance(node, dict) and 'action' in node:
                raw = engine.step(node['action'])
                outputs.append(raw)
                branches = node.get('branches', {})
                if str(raw) not in branches:
                    break
                node = branches[str(raw)]
        elif word is not None:
            outputs = [engine.step(symbol) for symbol in word]
        events = list(engine.semantic_events)
        goal, hazard = private['contract']['goal'], private['contract']['hazard']
        result = {'outputs': outputs, 'semantic_events': events,
                  'goal_success': bool(events) and events[-1] == goal,
                  'hazard': hazard in events,
                  'contract_satisfied': bool(events) and events[-1] == goal and hazard not in events}
        if private['family'] == 'bypass':
            result['privileged_check_passed'] = True
        return result
    finally:
        engine.close()


def target_machine(private, work=None):
    if private['family'] in ('drift','malformed'):
        return None
    # Export deployment behavior after reset. Fault onset is finite-state memory,
    # saturated once active; never omit it or silently export calibration behavior.
    fault = private.get('fault_schedule')
    onset = fault['step'] if fault and fault.get('phase', 'deployment') != 'calibration' else 0
    if onset > 512:
        # Bound the private export rather than exhausting memory for a distant
        # schedule. Actual trajectory auditing still executes the real schedule.
        return None
    engine = make_engine(private, work)
    engine.set_phase('deployment')
    initial = (0,0,0,0,0)
    states, pending, rows = {initial:0}, deque([initial]), []
    try:
        while pending:
            state = pending.popleft()
            row = []
            for action in range(3):
                engine.state, engine.previous, engine.parity, engine.steps_since_reset, engine.fault_previous = state
                engine.semantic_events.clear()
                output = engine.step(action)
                following = (engine.state,engine.previous,engine.parity,min(engine.steps_since_reset, onset),engine.fault_previous)
                if following not in states:
                    states[following] = len(states)
                    pending.append(following)
                row.append((states[following], output))
            rows.append(tuple(row))
        return Machine('private-raw-target', tuple(rows))
    finally:
        engine.close()


def oracle_plan(private, horizon=4):
    return oracle_plan_after(private, [], horizon)


def oracle_plan_after(private, probes, horizon=4):
    """Enumerate fresh counterfactual plans from the same post-calibration phase."""
    if private['family'] == 'malformed':
        return None
    for length in range(1,horizon+1):
        for word in itertools.product(range(3),repeat=length):
            if evaluate_deployment(private,probes,word)['contract_satisfied']:
                return list(word)
    return None