File size: 55,802 Bytes
0364757
 
 
 
 
 
 
 
 
2719bf4
 
 
0364757
 
 
2719bf4
0364757
2719bf4
 
0364757
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
2719bf4
0364757
 
 
 
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0364757
2719bf4
0364757
 
 
2719bf4
 
0364757
 
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
0364757
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
0364757
 
 
 
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
2719bf4
0364757
2719bf4
0364757
 
 
 
 
 
2719bf4
 
 
 
 
0364757
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0364757
 
2719bf4
 
 
 
 
0364757
2719bf4
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0364757
2719bf4
 
 
 
 
 
 
 
 
 
 
0364757
 
 
 
 
 
2719bf4
0364757
 
 
2719bf4
0364757
 
 
 
2719bf4
0364757
 
 
 
2719bf4
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0364757
2719bf4
 
0364757
 
2719bf4
 
0364757
 
 
 
 
 
 
 
 
 
2719bf4
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
2719bf4
0364757
2719bf4
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
0364757
2719bf4
 
0364757
 
2719bf4
 
 
 
 
 
 
0364757
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0364757
 
 
2719bf4
 
0364757
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
 
 
 
2719bf4
 
0364757
2719bf4
 
0364757
 
 
2719bf4
 
0364757
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
2719bf4
 
 
0364757
 
2719bf4
0364757
2719bf4
0364757
2719bf4
0364757
2719bf4
0364757
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
0364757
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0364757
 
2719bf4
0364757
 
 
 
 
 
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
747
748
749
750
751
from __future__ import annotations

from copy import deepcopy
from dataclasses import asdict
from itertools import combinations
import json
import hashlib
from pathlib import Path
from .domain import (Action, ActionError, Observation, Transition, Phase, CampaignState, RuleState, MazeState, ArchiveState, OsmosisState, WitnessState, BlackoutState, ExitState, canonical)
from .plant import (sensor_reading, phase_reading, delivery_lane, delivery_ready,
                    permit_decision, corridor_open, circuit_bus, circuit_ready, exit_decision, opponent_lane,
                    shutter_open, bridge_fatigue, compensated_bus)

SCHEMAS = {
 'set_latch': {'value': ('int',0,3)}, 'pulse': {'fixture': ('enum','sensor','gate','relay')}, 'observe_sensor': {}, 'lock_chamber': {},
 'select_channel': {'channel': ('str',)},
 'scan': {}, 'walk': {'direction': ('enum','north','south','east','west')}, 'turn_rotor': {'rotor_id': ('enum','hub')}, 'collect': {}, 'leave_maze': {}, 'wait': {},
 'open_scroll': {'slot': ('int',0,63)}, 'advance_page': {}, 'compare_seal': {'left_id': ('str',), 'right_id': ('str',)}, 'bind_docket': {'record_ids': ('ids',)}, 'file_record': {'record_id': ('str',)},
 'audit_service': {'service': ('str',)}, 'repair_exit': {}, 'uninstall': {'socket': ('enum','coupler','power')},
 'deploy': {'actor': ('str',),'neighbor': ('enum','home','west','relay','east','enemy')}, 'challenge': {'actor': ('str',),'target': ('str',)}, 'support': {'actor': ('str',),'ally': ('str',)}, 'feint': {'actor': ('str',),'lane': ('enum','west','east')}, 'bank': {'actor': ('str',)}, 'transfer': {'from_actor': ('str',),'to_actor': ('str',)}, 'rest': {'actor': ('str',)}, 'end_osmosis': {},
 'visit': {'cell': ('int',0,4)}, 'interview': {'witness': ('str',)}, 'cross_check': {'claim_id': ('str',),'record_id': ('str',)}, 'test_checkpoint': {'seal_id': ('enum','amber','cobalt','silver')}, 'escort': {'witness': ('str',),'neighbor': ('int',0,4)},
 'connect': {'circuit': ('str',),'bus': ('enum','west','east')}, 'energize': {'circuit': ('str',)}, 'isolate': {'circuit': ('str',)}, 'restore': {},
 'install': {'item': ('str',),'socket': ('enum','coupler','power')}, 'align_track': {'position': ('int',0,2)}, 'board': {'actor': ('str',)}, 'arm_exit': {'seal_id': ('enum','amber','cobalt','silver')}, 'open_valve': {'side': ('enum','west','east')}, 'launch': {}}
PHASE_TAGS = [set(), {'set_latch','pulse','observe_sensor','lock_chamber'}, {'scan','walk','turn_rotor','collect','leave_maze','wait'}, {'open_scroll','advance_page','compare_seal','bind_docket'}, {'deploy','challenge','support','feint','bank','transfer','rest','end_osmosis'}, {'visit','interview','cross_check','test_checkpoint','escort'}, {'connect','energize','isolate','restore'}, {'install','align_track','board','arm_exit','open_valve','launch'}]
COST = {'pulse':2,'scan':2,'turn_rotor':2,'compare_seal':2,'bind_docket':2,'challenge':2,'support':2,'cross_check':2,'test_checkpoint':2,'escort':2,'connect':2,'energize':2,'open_valve':4,'audit_service':6,'repair_exit':6,'uninstall':2}
CAUSAL_RULES = {
1: ('Select either named calibration channel. A sensor pulse and costed observation read latch low bit XOR its wiring bit. A relay pulse exposes (latch + phase offset) mod 4. Set latch zero to measure each independently.', 'Prime the relay at latch 2 or 3. Gate opens at latch 2 plus the FIRST channel wiring bit. Every action costs charge.'),
2: ('The nine-cell grid retains timed shutters and physical equipment. Scan at cell 4 reads the freight transit plate. Local scan clocks and schedules are public.', 'Bridge rig adds west/enemy travel in Osmosis. A relay cell shortens relay cooldown and discounts one circuit. Collection fatigues its carrier. The plate gives freight lane, delivery residue, corridor closure residue and bridge rating.'),
3: ('Each scroll is one consequential service with a baseline and two authenticated conditional amendments. A bit condition names a measured channel. Apply the matching amendment, regardless of issue order.', 'Compare its baseline and amendment, then file the chosen record for that service. Bind the filed records. Wrong bindings cost charge and can be repaired. Every circuit service has real bus and predecessor consumers.'),
4: ('Keep a defender home, score four points, then end the contest before 48 orders. Support, challenges, transfers, rest, bridge travel and flag deliveries have physical effects.', 'Delivery lane is freight XOR named channel wiring XOR clause lane, west=0 and east=1. Bank only when (turn + channel phase) mod 4 equals plate delivery residue. Wrong lane deliveries pay 3 customs charge. Wrong timing keeps the flag. All attempts cost charge.', 'Opponent may track a weighted window of 2 or 3 orders with lag 1 or 2, deny loaded delivery threats, or ambush after 2 or 3 loaded crossings. Parameters and law are hidden. Realized guard positions are public. Guard challenges suppress it for this reaction and the next order, never permanently. Each engagement spends up to 2 support. The guard recovers full strength. A Denier guards the enemy base against unladen bridge approaches. Entering an occupied base resolves combat before capture. Audits cost 6.', 'Home joins west/east, lanes join relay, relay joins enemy. Bridge rig adds west/enemy. Relay flags bank for 2. An enemy base capture grants 3 once and returns to the approach with bridge-rating fatigue from west, otherwise 1. Base entry fights guard then keeper. Attack strength is power + support - exhaustion - flag burden. Ties repel the attacker to the approach with 1 fatigue and no capture. Victory clears that defender and takes its flag. Every engagement spends up to 2 support. Support adds 2 to a colocated ally. Transfer moves all support and a flag to a colocated ally. An active guard intercepts its occupied lane after each order. Losing returns the runner home, restores its flag to origin and grants the enemy 1 point. A defender stays home to prevent the telegraphed Ambusher raid. Three enemy points lose the contest. Relay cell renews a banked flag immediately, otherwise cooldown is six orders.'),
5: ('Permit witness index is clause witness plus freight lane modulo 3. Seal index is clause seal plus named channel phase modulo 3. Indices use Iris/Juno/Kade and amber/cobalt/silver.', 'Travel, interview, verify against the filed permit, test the checkpoint and physically escort. Final corridors close when (clock + permit channel phase) mod 4 equals plate closure residue. Wait or rest to recover. Two available teammates below exhaustion 3 and the relay core are required. Audits cost 6.'),
6: ('Each circuit bus is channel wiring XOR freight lane XOR clause bus shift. Energize only after its clause predecessors are live. Wrong attempts trip the circuit and fatigue Ada; isolate and reconnect to recover.', 'All circuits must be live and the relay core present to restore exit power. Audits expose applicable service, named calibration and transit evidence for 6 charge. Rest recovers fatigue. Relay cell discounts one energize.'),
7: ('Install coupler and exit power in their sockets, board at least two available teammates, arm the authorized seal, set track and open the valve before launching.', 'Track is (freight lane index + egress channel phase + clause track delta) mod 3. Valve is channel wiring XOR freight lane XOR clause valve shift. Wrong launch gives charged diagnostic feedback. Repair costs 6 and resets pressure and valve. Audits cost 6.', 'Failed campaigns score 0. Escape scores 1 + boarded/(N+1) + remaining_charge/((N+1)*(B+1)), where N is the initial team size 3 and B is the profile initial charge. Any escape beats failure. Boarding one more available teammate outweighs every charge saving. Completion is reported separately. Repeated terminal calls score 0.')}
RULES = {
1: ('Every command costs charge. Sensor reads (latch low bit XOR hidden wiring bit). Set, pulse sensor, then read. Changing a fixture erases the reading.', 'The relay primes at latch 2 or 3. Gate opens at latch 2 plus the wiring bit, after relay priming. Lock only after opening gate. The same bit later selects west=0 or east=1 bus and exit valve.'),
2: ('Nine cells use row-major coordinates. Start 0, exit 8. Supply at 2 is bridge rig, at 4 relay cell. Collecting equipment costs charge.', 'Scan exposes local shutter schedules. Edges are indexed in cell order, east then south. A shutter is open unless (clock + rotation + edge index + rotor offset) mod 4 is zero. Walk, collect, scan, rotor and wait each advance clock. Perimeter edges except 1/2 are permanent. Timed routes reach equipment sooner than the permanent detour.'),
3: ('Six scrolls each have three revision packets. Open and advance each cost 1. Only the current packet remains visible.', 'Keep the highest authenticated civic issue for each series and subject. Compare the exposed current predecessor endpoints, then bind the three authoritative IDs. Newer exposures invalidate old comparison proofs. Bind costs 2 even when invalid.'),
4: ('Keep one defender at home. Win at least four points before turn 18 and end the contest. All orders cost at least 1; challenge/support cost 2.', 'Home joins west/east, lanes join relay, relay joins enemy. Bridge rig adds west/enemy. Enter relay to take a flag, carry home and bank for 2. Capture enemy base once per contest for 3 and return to the entry node with one exhaustion. Challenge the keeper from an adjacent node and carry its flag home for another 2.', 'Guard doctrine defends the most committed lane; raid doctrine defends the least committed lane while home is occupied; ties alternate. After every order the guard shifts and challenges collocated runners. Flag burden subtracts 1 from strength. Challenges use power + support - exhaustion; ties favor defense. A defeated runner returns home, loses its flag and gains exhaustion; enemy earns 1. Surviving interception also exhausts the runner. Support and transfer require co-location. Relay cell instantly renews a banked relay flag; without it recharge takes six turns. A raider telegraphs when home is empty, then raids next turn.'),
5: ('Cells 0,1,2,3 connect to court 4; all witness alcoves connect to lobby 0. Witness at 1 Iris, 2 Juno, 3 Kade.', 'Read a claim, cross-check the bound authorization record, test its seal at the checkpoint and escort the verified witness to court. At countdown zero, corridor 0/3 closes. Escort costs 2 and moves both. Escort needs two available members below exhaustion 3; each escort exhausts Cy. At exhaustion 4 a member becomes unavailable for boarding.'),
6: ('Fresh context boundary. Historical records and experiments are unavailable here. Use retained notebook facts.', 'Connect each circuit to the stable bus inferred in Rule chamber, then energize in the Archive revision order. Wrong bus/order trips the circuit and exhausts engineer. Isolate permits repair. Relay cell discounts one energize from 2 to 1. Restore consumes relay core and grants exit power.'),
7: ('Install coupler and exit power, align revised track, board at least two available members, arm with verified witness seal, choose irreversible valve then launch.', 'Every operation costs 1 except valve costs 4. Wrong valve vents pressure permanently. Launch checks all physical prerequisites. Charge may reach exactly zero on successful launch.')}


def terminal_objective(outcome, boarded, remaining_charge, initial_teammates, initial_charge):
    if outcome != 'escaped':
        return 0.0
    return 1 + boarded / (initial_teammates + 1) + remaining_charge / ((initial_teammates + 1) * (initial_charge + 1))


def parse_action(raw,generation_version=2):
    if isinstance(raw, Action):
        raw = {'tag': raw.tag, 'arguments': raw.arguments}
    if type(raw) is not dict or set(raw) != {'tag','arguments'} or type(raw['tag']) is not str or type(raw['arguments']) is not dict:
        return None, ActionError('malformed','Expected exactly tag and arguments objects.')
    try:
        if len(json.dumps(raw,allow_nan=False).encode()) > 8192:
            return None, ActionError('malformed','Action is too large.')
    except (ValueError, TypeError, RecursionError):
        return None, ActionError('malformed','Action must contain finite JSON values.')
    tag, args = raw['tag'], raw['arguments']
    if tag not in SCHEMAS or (generation_version==2 and tag in {'select_channel','file_record','audit_service','repair_exit','uninstall'}):
        return None, ActionError('unknown_action','Unknown action tag.')
    if set(args) != set(SCHEMAS[tag]):
        return None, ActionError('malformed','Arguments have missing or extra keys.')
    for key, spec in SCHEMAS[tag].items():
        v = args[key]
        valid = (spec[0]=='int' and type(v) is int and spec[1]<=v<=spec[2]) or (spec[0]=='enum' and type(v) is str and v in spec[1:]) or (spec[0]=='str' and type(v) is str and 0<len(v)<=64) or (spec[0]=='ids' and type(v) in (list,tuple) and 1<=len(v)<=12 and all(type(x) is str and 0<len(x)<=64 for x in v) and len(set(v))==len(v))
        if generation_version==2 and ((tag=='open_scroll' and type(v) is int and v>5) or (spec[0]=='ids' and type(v) in (list,tuple) and len(v)!=3)):
            valid=False
        if not valid:
            return None, ActionError('malformed','Invalid argument type or range.')
    args=deepcopy(args)
    if tag=='compare_seal': args['left_id'],args['right_id']=sorted((args['left_id'],args['right_id']))
    if tag=='bind_docket': args['record_ids']=sorted(args['record_ids'])
    return Action(tag,args), None


class Campaign:
    def __init__(self, world):
        self._world = world
        self._events = []
        self.reset()

    @classmethod
    def generated(cls, seed, ruleset='campaign', generation_version=2, archive_workload='standard', notebook_bytes=768, memory_profile='static'):
        from .worlds import generate
        return cls(generate(seed,ruleset,generation_version,archive_workload,notebook_bytes,memory_profile))

    def reset(self):
        self._state = CampaignState(Phase.RULE_CHAMBER,0,self._world.initial_charge,RuleState())
        if self._causal:
            self._state.room.channel = self._world.infrastructure.calibrations[0].id
        self._events = []
        t = self._transition()
        self._record('reset',None,t)
        return t

    def observe(self):
        return self._transition()

    @property
    def _causal(self):
        return self._world.generation_version == 3

    @property
    def _commissioning(self):
        return self._world.memory_profile == 'commissioning'

    def _public_record(self, record):
        result = record.to_dict()
        if self._commissioning and record.body.kind == 'circuit':
            result['ratings'] = list(self._world.infrastructure.load_schedule.curve(record.id))
        return result

    def _inventory(self, item):
        return item in self._state.inventory

    def _maze_edges(self):
        r = self._state.room
        edges = []
        idx = 0
        for cell in range(9):
            for other in (cell+1 if cell%3<2 else -1,cell+3 if cell<6 else -1):
                if other < 0:
                    continue
                perimeter = ((cell<3 and other<3) or (cell>=6 and other>=6) or (cell%3==0 and other%3==0) or (cell%3==2 and other%3==2)) and (cell,other)!=(1,2)
                timed=shutter_open(self._world.infrastructure,r.clock,idx,r.rotor_offset) if self._causal else (r.clock+self._world.maze_rotation+idx+r.rotor_offset)%4!=0
                edges.append(dict(a=cell,b=other,open=perimeter or timed,permanent=perimeter,index=idx))
                idx += 1
        return edges

    def _neighbors(self, node):
        graph = {'home':['west','east'],'west':['home','relay'],'east':['home','relay'],'relay':['west','east','enemy'],'enemy':['relay']}
        if self._state.room.bridge_available:
            graph['west'].append('enemy'); graph['enemy'].append('west')
        return graph[node]

    def _witness_edges(self):
        r = self._state.room
        edges = [(0,i) for i in (1,2,3)] + [(i,4) for i in (1,2,3)]
        if self._causal:
            return [e for e in edges if e[1] != 4 or corridor_open(self._world.infrastructure, r.clock)]
        return [e for e in edges if not(r.closure_in<=0 and e==(0,3))]

    def _board(self):
        s,r = self._state,self._state.room
        board = asdict(r)
        if not self._causal:
            for key in ('channel','phase_mark','filed','orders','loaded_crossings','clock'):
                if not (key == 'clock' and s.phase == 2): board.pop(key,None)
        if s.phase == 1:
            board.pop('experiments')
            board.pop('sensor_visible')
            if r.fixture != 'sensor' or not r.sensor_visible:
                board['live_sensor'] = None
        elif s.phase == 2:
            board.update(clock=r.clock%4,exit=8,supplies=[dict(cell=c,item=i,available=c not in r.collected) for c,i in [(2,'bridge_rig'),(4,'relay_cell')]],local_edges=[e for e in self._maze_edges() if r.cell in (e['a'],e['b'])] if r.scanned else [],rotation=self._world.maze_rotation,rotor_id='hub')
        elif s.phase == 3:
            board.pop('exposed_versions'); board.pop('compared_versions')
            board['records'] = [self._public_record(record) for record in self._world.archive.page(r.slot,r.page)] if r.slot is not None else []
            board['page_count'] = len(self._world.archive.pages[r.slot]) if r.slot is not None else 0
            board['slots'] = list(range(len(self._world.archive.pages)))
        elif s.phase == 4:
            board['turn_limit'] = 18
        elif s.phase == 5:
            board.update(current_open_corridors=self._witness_edges(),docket_ids=list(s.docket))
        elif s.phase == 6:
            board.pop('activation_order')
            if self._commissioning:
                for circuit in board['circuits']:
                    index = circuit['completed_tests']
                    meter = self._world.infrastructure.load_schedule.test(circuit['id'], index) if index < 3 else None
                    circuit['meter'] = dict(band=meter.band, load=meter.load, test=index+1) if meter is not None else None
        elif s.phase == 7:
            board['required_boarded'] = 2
        if self._causal:
            board['feedback'] = deepcopy(s.feedback)
            if s.phase == 1:
                board['channels'] = [c.id for c in self._world.infrastructure.calibrations]
            elif s.phase == 2:
                board['transit_plate'] = asdict(self._world.infrastructure.transit) if r.cell == 4 and r.scanned else None
            elif s.phase == 3:
                board['service_count'] = len(self._world.infrastructure.services)
            elif s.phase == 4:
                board.pop('orders'); board.pop('loaded_crossings')
                board['turn_limit'] = 48
                for token in board['allies']:
                    token['exhaustion'] = self._fatigue(token)
                    token['available'] = next(m['available'] for m in s.team if m['id'] == token['actor'])
            if s.phase >= 4:
                board['service_ids'] = list(self._world.infrastructure.services)
        return board

    def _cost(self,a):
        if a.tag=='energize' and self._inventory('relay_cell') and not self._state.room.discount_used:
            return 1
        return COST.get(a.tag,1)

    def _actions(self):
        s,r = self._state,self._state.room
        if s.outcome != 'running':
            return ()
        actions = []
        def add(tag,**args):
            a,_ = parse_action(Action(tag,args),self._world.generation_version)
            if self._cost(a)<=s.charge:
                actions.append(a)
        if self._causal and s.phase >= 4:
            for service in self._world.infrastructure.services: add('audit_service',service=service)
            if s.phase in (5,6,7):
                for member in s.team:
                    if member['available']: add('rest',actor=member['id'])
        if s.phase==1:
            if self._causal:
                for channel in self._world.infrastructure.calibrations: add('select_channel',channel=channel.id)
            for v in range(4): add('set_latch',value=v)
            for f in ('sensor','relay','gate'): add('pulse',fixture=f)
            if r.fixture=='sensor': add('observe_sensor')
            add('lock_chamber')
        elif s.phase==2:
            add('scan'); add('wait'); add('turn_rotor',rotor_id='hub')
            if r.scanned:
                for e in self._maze_edges():
                    if r.cell in (e['a'],e['b']) and e['open']:
                        other = e['b'] if r.cell==e['a'] else e['a']
                        add('walk',direction={-3:'north',3:'south',1:'east',-1:'west'}[other-r.cell])
            if r.cell in (2,4) and r.cell not in r.collected: add('collect')
            if r.cell==8: add('leave_maze')
        elif s.phase==3:
            for slot in range(len(self._world.archive.pages)): add('open_scroll',slot=slot)
            if r.slot is not None and r.page+1<len(self._world.archive.pages[r.slot]): add('advance_page')
            exposed = sorted(r.exposed_versions)
            if self._causal:
                services = {record_id: self._world.archive.current(record_id).service for record_id in exposed}
            for pair in combinations(exposed,2):
                if not self._causal or services[pair[0]] == services[pair[1]]:
                    add('compare_seal',left_id=pair[0],right_id=pair[1])
            if self._causal:
                for record_id in exposed: add('file_record',record_id=record_id)
                if len(r.filed) == len(self._world.infrastructure.services): add('bind_docket',record_ids=sorted(r.filed.values()))
            else:
                for ids in combinations(sorted(r.exposed_versions),3): add('bind_docket',record_ids=list(ids))
        elif s.phase==4:
            if r.contest_over:
                add('end_osmosis')
                return tuple(actions)
            for ally in r.allies:
                actor=ally['actor']
                if self._causal and not next(m['available'] for m in s.team if m['id']==actor): continue
                add('rest',actor=actor)
                for lane in ('west','east'): add('feint',actor=actor,lane=lane)
                for node in self._neighbors(ally['node']):
                    if self._causal or not any(e['node']==node for e in r.enemies): add('deploy',actor=actor,neighbor=node)
                for enemy in r.enemies:
                    if enemy['node']==ally['node'] or enemy['node'] in self._neighbors(ally['node']): add('challenge',actor=actor,target=enemy['actor'])
                if ally['node']=='home' and ally['flag']: add('bank',actor=actor)
                for other in r.allies:
                    if self._causal and not next(m['available'] for m in s.team if m['id']==other['actor']): continue
                    if other!=ally and other['node']==ally['node']:
                        add('support',actor=actor,ally=other['actor'])
                        if ally['flag'] or ally['support']: add('transfer',from_actor=actor,to_actor=other['actor'])
        elif s.phase==5:
            if self._causal: add('wait')
            neighbors=[b if a==r.player_cell else a for a,b in self._witness_edges() if r.player_cell in (a,b)]
            for cell in neighbors: add('visit',cell=cell)
            for witness,cell in r.witness_cells.items():
                if cell==r.player_cell:
                    add('interview',witness=witness)
                    if sum(m['available'] and m['exhaustion']<3 for m in s.team)>=2:
                        for n in neighbors: add('escort',witness=witness,neighbor=n)
            if r.claim:
                for record in s.docket: add('cross_check',claim_id=r.claim['id'],record_id=record)
            for seal in ('amber','cobalt','silver'): add('test_checkpoint',seal_id=seal)
        elif s.phase==6:
            for c in r.circuits:
                for bus in ('west','east'): add('connect',circuit=c['id'],bus=bus)
                if c['status']=='connected': add('energize',circuit=c['id'])
                add('isolate',circuit=c['id'])
            add('restore')
        else:
            if self._causal and r.valve is not None: add('repair_exit')
            if r.valve is None:
                if self._causal:
                    for socket in sorted(r.installed): add('uninstall',socket=socket)
                for item in ('coupler','exit_power'):
                    if self._inventory(item):
                        for socket in ('coupler','power'):
                            if not self._causal or socket not in r.installed: add('install',item=item,socket=socket)
                for p in range(3): add('align_track',position=p)
                for member in s.team:
                    if member['available'] and member['id'] not in r.boarded: add('board',actor=member['id'])
                for seal in ('amber','cobalt','silver'): add('arm_exit',seal_id=seal)
                for side in ('west','east'): add('open_valve',side=side)
            add('launch')
        return tuple(actions)

    def _transition(self,error=None,reward=0.0,context_reset=False):
        s=self._state
        notebook = dict(text=s.notebook,capacity_bytes=self._world.notebook_bytes,unit='UTF-8 bytes',used_bytes=len(s.notebook.encode('utf-8'))) if self._causal else dict(text=s.notebook,capacity_chars=768)
        rules = (CAUSAL_RULES if self._causal else RULES)[int(s.phase)]
        if self._commissioning and s.phase in (3, 6):
            rules = rules + ('Commissioning uses eight rating bands and thresholds 0..3. For the current public meter (band 0..7, physical load 0..2), select base calibrated bus XOR (load >= rating[band]). Each circuit needs three successful tests; predecessors must be live. Nonfinal success isolates for the next meter. Reconnecting or isolating a completed live circuit restarts its tests; partial repairs preserve progress. Archive and audits expose full applicable ratings, never future meters.',)
        o=Observation(s.phase,s.tick,s.charge,tuple(deepcopy(s.team)),tuple(s.inventory),notebook,rules,self._board(),s.outcome)
        return Transition(o,self._actions(),reward,s.outcome!='running',False,s.outcome,error,context_reset,s.revision,())

    def _record(self,kind,payload,t):
        serialized=t.to_dict()
        before=self._events[-1]['after_public_digest'] if self._events else None
        after=hashlib.sha256(canonical(serialized).encode()).hexdigest()
        self._events.append(dict(index=len(self._events),kind=kind,input=deepcopy(payload),before_public_digest=before,after_public_digest=after,transition=serialized))

    def _revision_error(self,revision):
        if revision is not None and (type(revision) is not int or revision!=self._state.revision):
            return self._transition(ActionError('stale_revision','Expected current integer revision.'))

    def replace_notebook(self,text,expected_revision=None):
        err=self._revision_error(expected_revision)
        if err: return err
        try:
            limit=self._world.notebook_bytes if self._causal else 768
            valid=type(text) is str and (len(text.encode('utf-8')) if self._causal else len(text))<=limit
        except UnicodeEncodeError:
            valid=False
        if not valid:
            return self._transition(ActionError('malformed','Notebook exceeds its '+str(limit)+' '+('UTF-8 byte' if self._causal else 'character')+' capacity.'))
        if self._causal and text == self._state.notebook:
            return self._transition()
        self._state.notebook=text
        self._state.revision+=1
        t=self._transition()
        self._record('note',text,t)
        return t

    def step(self,action,expected_revision=None):
        err=self._revision_error(expected_revision)
        if err: return err
        if self._state.outcome!='running': return self._transition(ActionError('episode_done','Episode is complete.'))
        a,error=parse_action(action,self._world.generation_version)
        if error: return self._transition(error)
        extra = ({'select_channel'} if self._state.phase == 1 else {'file_record'} if self._state.phase == 3 else {'audit_service','rest','wait','repair_exit','uninstall'}) if self._causal else set()
        if a.tag not in PHASE_TAGS[int(self._state.phase)] | extra: return self._transition(ActionError('wrong_phase','Action is unavailable in this room.'))
        legal={canonical(x.to_dict()) for x in self._actions()}
        if canonical(a.to_dict()) not in legal:
            code='unaffordable' if self._cost(a)>self._state.charge else 'precondition'
            return self._transition(ActionError(code,'Action is not executable from the current public board.'))
        before=self._state.phase
        self._state.charge-=self._cost(a)
        self._state.tick+=1
        self._state.revision+=1
        self._apply(a)
        for member in self._state.team:
            if member['exhaustion']>=4: member['available']=False
        if self._state.charge==0 and self._state.outcome=='running': self._state.outcome='exhausted'
        if self._state.tick>=240 and self._state.outcome=='running': self._state.outcome='trapped'
        reward = (terminal_objective(self._state.outcome, len(getattr(self._state.room, 'boarded', ())),
                                     self._state.charge, len(self._state.team), self._world.initial_charge)
                  if self._causal else 1.0 if self._state.outcome == 'escaped' else 0.0)
        t=self._transition(reward=reward,context_reset=(before!=6 and self._state.phase==6))
        self._record('action',a.to_dict(),t)
        return t

    def _enter(self,phase):
        s=self._state
        s.phase=Phase(phase)
        s.room={2:MazeState,3:ArchiveState,4:OsmosisState,5:WitnessState,6:BlackoutState,7:ExitState}[phase]()
        if phase==4:
            s.room.bridge_available=self._inventory('bridge_rig')
            for token,member in zip(s.room.allies,s.team):
                if self._causal: token.pop('exhaustion'); token['route_lane']=None
                else: token['exhaustion']=member['exhaustion']
        if self._causal:
            s.feedback = None
            if phase == 6:
                s.room.circuits = [dict(id=cid,bus=None,status='isolated', **({'completed_tests': 0} if self._commissioning else {})) for cid in self._world.infrastructure.circuits()]

    def _fatigue(self, token):
        return next(m['exhaustion'] for m in self._state.team if m['id'] == token['actor']) if self._causal else token['exhaustion']

    def _set_fatigue(self, token, value):
        owner = next(m for m in self._state.team if m['id'] == token['actor']) if self._causal else token
        owner['exhaustion'] = value

    def _apply(self,a):
        s,r,w=self._state,self._state.room,self._world
        tag,v=a.tag,a.arguments
        if self._causal:
            s.feedback = None
            if tag == 'audit_service':
                p = w.infrastructure
                record = p.current(v['service'])
                s.feedback = dict(audit=self._public_record(record),calibration=asdict(p.channel(record.body.channel)),applicability_calibration=asdict(p.channel(record.applies_channel)),transit=asdict(p.transit))
                return
            if tag == 'rest' and s.phase != 4:
                member = next(m for m in s.team if m['id'] == v['actor'])
                member['exhaustion'] = max(0,member['exhaustion']-1)
                if s.phase == 5: r.clock += 1
                return
        if s.phase==1:
            if tag=='select_channel': r.channel=v['channel']; r.live_sensor=None; r.fixture=None; r.sensor_visible=False; r.phase_mark=None
            elif tag=='set_latch': r.latch=v['value']; r.live_sensor=None; r.fixture=None; r.sensor_visible=False; r.phase_mark=None
            elif tag=='pulse':
                r.fixture=v['fixture']; r.pulse_count+=1; r.live_sensor=None; r.sensor_visible=False
                if r.fixture=='sensor': r.live_sensor=sensor_reading(w.infrastructure.channel(r.channel),r.latch) if self._causal else (r.latch&1)^w.polarity
                elif r.fixture=='relay':
                    r.experiments.append(('prime',r.latch>=2))
                    if self._causal: r.phase_mark=phase_reading(w.infrastructure.channel(r.channel),r.latch)
                elif r.fixture=='gate':
                    bit=w.infrastructure.calibrations[0].sensor_xor if self._causal else w.polarity
                    r.gate_open=r.latch==2+bit and ('prime',True) in r.experiments
            elif tag=='observe_sensor': r.experiments.append((r.latch,r.live_sensor)); r.sensor_visible=True
            elif tag=='lock_chamber':
                if not r.gate_open:
                    if self._causal: s.feedback='Gate remains locked. Recheck the first calibration and prime the relay.'
                    else: s.outcome='trapped'
                else:
                    s.inventory.append('coupler')
                    if w.ruleset=='pilot': s.inventory+=['bridge_rig','docket','exit_power']; s.witness_authorization=w.current_seal; self._enter(4)
                    else: self._enter(2)
        elif s.phase==2:
            if tag=='scan':
                r.scanned=True
                for e in self._maze_edges():
                    if r.cell in (e['a'],e['b']) and e not in r.discovered: r.discovered.append(e)
            elif tag=='walk': r.cell+={'north':-3,'south':3,'east':1,'west':-1}[v['direction']]; r.scanned=False
            elif tag=='turn_rotor': r.rotor_offset=(r.rotor_offset+1)%4
            elif tag=='collect':
                r.collected.append(r.cell); s.inventory.append('bridge_rig' if r.cell==2 else 'relay_cell')
                s.team[1 if r.cell==2 else 2]['exhaustion']+=1
            elif tag=='leave_maze': self._enter(3)
            r.clock+=1
        elif s.phase==3:
            if self._causal:
                self._charter(a)
                return
            if tag=='open_scroll': r.slot=v['slot']; r.page=0
            elif tag=='advance_page': r.page+=1
            elif tag=='compare_seal':
                left=w.archive.revision(v['left_id'],r.exposed_versions[v['left_id']])
                right=w.archive.revision(v['right_id'],r.exposed_versions[v['right_id']])
                older,newer=sorted((left,right),key=lambda record:record.issued_at)
                valid=older.subject==newer.subject and newer.supersedes==older.id and older.issued_at<newer.issued_at and older.authenticated and newer.authenticated
                r.result='verified exposed civic revision chain' if valid else 'seal chain inconsistent'
                if valid: r.compared_versions.add(tuple(sorted(((left.id,left.issued_at),(right.id,right.issued_at)))))
            elif tag=='bind_docket':
                ids=v['record_ids']; valid=set(ids)==set(w.correct_records)
                for record_id in ids:
                    current=w.archive.current(record_id)
                    predecessor=w.archive.current(current.supersedes) if current.supersedes else None
                    proof=tuple(sorted(((current.id,current.issued_at),(predecessor.id,predecessor.issued_at)))) if predecessor else None
                    valid=valid and r.exposed_versions.get(record_id)==current.issued_at and predecessor is not None and r.exposed_versions.get(predecessor.id)==predecessor.issued_at and proof in r.compared_versions
                if valid:
                    s.docket={record_id:r.exposed_versions[record_id] for record_id in ids}; s.inventory.append('docket'); self._enter(4)
                else: r.result='binding rejected: stale, unverified or inconsistent records'
            if s.phase==3 and tag in ('open_scroll','advance_page'):
                for record in w.archive.page(r.slot,r.page):
                    if record.authenticated:
                        r.exposed_versions[record.id]=max(r.exposed_versions.get(record.id,0),record.issued_at)
        elif s.phase==4: self._osmosis(a)
        elif s.phase==5:
            if self._causal:
                self._permit(a)
                return
            r.closure_in-=1
            if tag=='visit': r.player_cell=v['cell']; r.claim=None
            elif tag=='interview':
                witness=v['witness']; valid=witness==w.current_witness
                r.claim=dict(id='claim-'+witness,witness=witness,subject='authorization',statement=witness+'/'+(w.current_seal if valid else 'amber'),seal=w.current_seal if valid else 'amber')
            elif tag=='cross_check':
                rec=w.archive.revision(v['record_id'],s.docket[v['record_id']])
                valid=rec['subject']=='authorization' and rec['id'] in w.correct_records and rec['statement']==r.claim['statement']
                r.checks.append(dict(claim=v['claim_id'],record=v['record_id'],status='verified' if valid else 'inconsistent'))
            elif tag=='test_checkpoint': r.checkpoint_test=v['seal_id'] if v['seal_id']==w.current_seal else 'denied'
            elif tag=='escort':
                witness=v['witness']; dest=v['neighbor']
                r.witness_cells[witness]=dest; r.player_cell=dest
                s.team[2]['exhaustion']+=1
                verified=any(c['claim']=='claim-'+witness and c['status']=='verified' for c in r.checks)
                if dest==4:
                    if witness==w.current_witness and verified and r.checkpoint_test==w.current_seal:
                        s.witness_authorization=w.current_seal; self._enter(6)
                    else: s.outcome='trapped'
        elif s.phase==6:
            if self._causal:
                self._circuits(a)
                return
            if tag=='restore':
                if tuple(r.activation_order)==w.restoration_order and all(c['status']=='live' for c in r.circuits) and self._inventory('relay_core'):
                    s.inventory.remove('relay_core'); s.inventory.append('exit_power'); self._enter(7)
                else: s.team[0]['exhaustion']+=1
            else:
                c=next(c for c in r.circuits if c['id']==v['circuit'])
                if tag=='connect':
                    if c['id'] in r.activation_order: r.activation_order.remove(c['id'])
                    c['bus']=v['bus']; c['status']='connected'
                elif tag=='isolate':
                    c['status']='isolated'; c['bus']=None
                    if c['id'] in r.activation_order: r.activation_order.remove(c['id'])
                else:
                    if self._inventory('relay_cell') and not r.discount_used: r.discount_used=True; s.inventory.remove('relay_cell')
                    if c['bus']==('west','east')[w.polarity] and len(r.activation_order)<3 and c['id']==w.restoration_order[len(r.activation_order)]: c['status']='live'; r.activation_order.append(c['id'])
                    else: c['status']='tripped'; s.team[0]['exhaustion']+=1
        else:
            if tag=='install': r.installed[v['socket']]=v['item']; s.inventory.remove(v['item'])
            elif tag=='uninstall': s.inventory.append(r.installed.pop(v['socket']))
            elif tag=='align_track': r.track=v['position']
            elif tag=='board': r.boarded.append(v['actor'])
            elif tag=='arm_exit': r.armed_with=v['seal_id']
            elif tag=='repair_exit': r.valve=None; r.pressure_vented=False; s.feedback='Pressure restored. Valve can be selected again.'
            elif tag=='open_valve': r.valve=v['side']; r.pressure_vented=v['side']!=(exit_decision(w.infrastructure)[1] if self._causal else ('west','east')[w.polarity])
            elif tag=='launch':
                track=exit_decision(w.infrastructure)[0] if self._causal else w.correct_track
                good=r.installed=={'coupler':'coupler','power':'exit_power'} and r.track==track and len(r.boarded)>=2 and r.armed_with==s.witness_authorization and r.valve is not None and not r.pressure_vented
                if self._causal and not good:
                    s.feedback=dict(assembly=r.installed=={'coupler':'coupler','power':'exit_power'},track=r.track==track,team=len(r.boarded)>=2,seal=r.armed_with==s.witness_authorization,pressure=r.valve is not None and not r.pressure_vented)
                else: s.outcome='escaped' if good else 'exit_failure'

    def _charter(self, action):
        s, r, p = self._state, self._state.room, self._world.infrastructure
        tag, v = action.tag, action.arguments
        archive = self._world.archive
        if tag == 'open_scroll': r.slot=v['slot']; r.page=0
        elif tag == 'advance_page': r.page+=1
        elif tag == 'compare_seal':
            left, right = (archive.current(v[key]) for key in ('left_id','right_id'))
            older,newer=sorted((left,right),key=lambda rec:rec.issued_at)
            valid=older.service==newer.service and newer.supersedes==older.id and older.authenticated and newer.authenticated
            r.result='verified exposed civic revision chain' if valid else 'seal chain inconsistent'
            if valid: r.compared_versions.add(tuple(sorted((older.id,newer.id))))
        elif tag == 'file_record':
            record=archive.current(v['record_id'])
            r.filed[record.service]=record.id
            r.result='Filed '+record.id+' for '+record.service+'.'
        elif tag == 'bind_docket':
            records=[archive.current(rid) for rid in v['record_ids']]
            if any(record.supersedes is None or
                   tuple(sorted((record.id,record.supersedes))) not in r.compared_versions
                   for record in records):
                r.result='Missing predecessor comparison proof. Each service needs a conditional amendment and an authenticated predecessor comparison.'
                return
            valid=len(records)==len(p.services) and all(
                record == p.current(record.service)
                for record in records)
            if valid:
                s.docket={record.service:record.id for record in records}
                s.inventory.append('docket'); self._enter(4)
            else: r.result='Binding inconsistent. Recheck applicability and authenticated predecessor chains.'
        if s.phase == 3 and tag in ('open_scroll','advance_page'):
            for record in archive.page(r.slot,r.page): r.exposed_versions[record.id]=record.issued_at

    def _permit(self, action):
        s,r,p=self._state,self._state.room,self._world.infrastructure
        tag,v=action.tag,action.arguments
        witness,seal=permit_decision(p)
        r.clock+=1; r.closure_in-=1
        if tag=='visit': r.player_cell=v['cell']; r.claim=None
        elif tag=='interview':
            name=v['witness']
            r.claim=dict(id='claim-'+name,witness=name,subject='permit',statement=name+'/'+seal,seal=seal)
        elif tag=='cross_check':
            record=self._world.archive.current(s.docket[v['record_id']])
            valid=record.body.kind=='permit' and record==p.current(record.service) and r.claim['witness']==witness and r.claim['seal']==seal
            r.checks.append(dict(claim=v['claim_id'],record=v['record_id'],status='verified' if valid else 'inconsistent'))
        elif tag=='test_checkpoint':
            r.checkpoint_test=seal if v['seal_id']==seal and self._inventory('relay_core') else 'denied'
        elif tag=='escort':
            name,destination=v['witness'],v['neighbor']
            r.witness_cells[name]=destination; r.player_cell=destination
            s.team[2]['exhaustion']+=1
            verified=any(c['claim']=='claim-'+name and c['status']=='verified' for c in r.checks)
            if destination==4:
                if name==witness and verified and r.checkpoint_test==seal and self._inventory('relay_core'):
                    s.witness_authorization=seal; self._enter(6)
                else: s.feedback='Checkpoint denied. Return, verify the applicable permit and retry.'

    def _circuits(self, action):
        s,r,p=self._state,self._state.room,self._world.infrastructure
        tag,v=action.tag,action.arguments
        if tag=='restore':
            if all(c['status']=='live' for c in r.circuits) and self._inventory('relay_core'):
                s.inventory.remove('relay_core'); s.inventory.append('exit_power'); self._enter(7)
            else:
                s.team[0]['exhaustion']+=1; s.feedback='Restoration needs every live circuit and the relay core.'
            return
        circuit=next(c for c in r.circuits if c['id']==v['circuit'])
        if self._commissioning and tag in ('connect', 'isolate') and circuit['completed_tests'] == 3:
            circuit['completed_tests'] = 0
        if tag=='connect':
            circuit['bus']=v['bus']; circuit['status']='connected'
            if circuit['id'] in r.activation_order: r.activation_order.remove(circuit['id'])
        elif tag=='isolate':
            circuit['bus']=None; circuit['status']='isolated'
            if circuit['id'] in r.activation_order: r.activation_order.remove(circuit['id'])
        else:
            if self._inventory('relay_cell') and not r.discount_used:
                r.discount_used=True; s.inventory.remove('relay_cell')
            live={c['id'] for c in r.circuits if c['status']=='live'}
            predecessors=p.current(circuit['id']).body.predecessors
            bus = circuit_bus(p, circuit['id'])
            if self._commissioning:
                meter = p.load_schedule.test(circuit['id'], circuit['completed_tests'])
                bus = compensated_bus(bus, p.load_schedule.curve(p.current(circuit['id']).id), meter.band, meter.load)
            if circuit['bus']==bus and circuit_ready(p,circuit['id'],live):
                if self._commissioning:
                    circuit['completed_tests'] += 1
                if not self._commissioning or circuit['completed_tests'] == 3:
                    circuit['status']='live'; r.activation_order.append(circuit['id'])
                else:
                    circuit['status']='isolated'; circuit['bus']=None
            else:
                circuit['status']='tripped'; s.team[0]['exhaustion']+=1
                s.feedback=dict(circuit=circuit['id'],trip='wiring' if circuit['bus']!=bus else 'predecessor',unsatisfied=[cid for cid in predecessors if cid not in live])

    def _osmosis(self,a):
        s,r,w=self._state,self._state.room,self._world
        tag,v=a.tag,a.arguments
        if tag=='end_osmosis':
            defender=any(t['node']=='home' and (not self._causal or next(m['available'] for m in s.team if m['id']==t['actor'])) for t in r.allies)
            if r.allied_points>=4 and defender and r.enemy_points<3:
                s.inventory.append('relay_core')
                if not self._causal:
                    for token,member in zip(r.allies,s.team): member['exhaustion']=token['exhaustion']
                self._enter(7 if w.ruleset=='pilot' else 5)
            else: s.outcome='contest_loss'
            return
        if self._causal:
            r.enemies[0]['exhaustion'] = max(0, r.enemies[0]['exhaustion'] - 1)
        actor=next(t for t in r.allies if t['actor']==v.get('actor',v.get('from_actor')))
        if tag=='deploy':
            previous=actor['node']; actor['node']=v['neighbor']
            if actor['node']=='enemy':
                if self._causal:
                    for enemy in r.enemies:
                        if enemy['node'] != 'enemy': continue
                        strength=actor['power']+actor['support']-self._fatigue(actor)-bool(actor['flag'])
                        actor['support']=max(0,actor['support']-2)
                        if strength > enemy['power']:
                            enemy['node']='sideline'
                            if enemy['actor']=='guard': enemy['exhaustion']=2
                            if enemy['flag']: actor['flag']='keeper'; enemy['flag']=False
                        else:
                            actor['node']=previous
                            self._set_fatigue(actor,self._fatigue(actor)+1)
                            s.feedback='Base entry repelled by '+enemy['actor']+'. No capture.'
                            break
                if actor['node']=='enemy':
                    if not r.base_captured: r.allied_points+=3; r.base_captured=True
                    actor['node']=previous; self._set_fatigue(actor,self._fatigue(actor)+(bridge_fatigue(w.infrastructure) if self._causal and previous=='west' else 1))
            if actor['node']=='relay' and not r.relay_claimed and r.relay_cooldown==0 and not any(t['flag'] for t in r.allies): actor['flag']='relay'; r.relay_claimed=True
            lane=v['neighbor']
            if self._causal:
                if lane in ('west','east'): actor['route_lane']=lane
                if actor['flag'] and lane in ('west','east'): r.loaded_crossings+=1
        elif tag=='challenge':
            enemy=next(t for t in r.enemies if t['actor']==v['target'])
            lane=enemy['node']; strength=actor['power']+actor['support']-self._fatigue(actor)-bool(actor['flag']); actor['support']=max(0,actor['support']-2) if self._causal else 0
            if strength>enemy['power']-enemy['exhaustion']:
                enemy['node']='enemy' if enemy['actor']=='guard' else 'sideline'; enemy['exhaustion']=2 if self._causal and enemy['actor']=='guard' else enemy['exhaustion']+1
                if enemy['flag']: actor['flag']='keeper'; enemy['flag']=False
            else: self._set_fatigue(actor,self._fatigue(actor)+1)
        elif tag=='feint': lane=v['lane']
        elif tag=='rest': self._set_fatigue(actor,max(0,self._fatigue(actor)-1)); lane=None
        elif tag=='support':
            target=next(t for t in r.allies if t['actor']==v['ally']); target['support']+=2; lane=None
        elif tag=='transfer':
            target=next(t for t in r.allies if t['actor']==v['to_actor']); target['flag']=target['flag'] or actor['flag']; target['support']+=actor['support']; actor['flag']=False; actor['support']=0; lane=None
        elif tag=='bank':
            ready=not self._causal or delivery_ready(w.infrastructure,r.turn)
            if ready:
                if self._causal and actor['route_lane']!=delivery_lane(w.infrastructure):
                    s.charge=max(0,s.charge-3); s.feedback='Delivery accepted with 3 charge customs duty for wrong freight permit lane.'
                r.allied_points+=2
                if actor['flag']=='relay':
                    r.relay_claimed=False; r.relay_cooldown=0 if self._inventory('relay_cell') else 6
                actor['flag']=False
            else: s.feedback='Delivery window closed. Flag retained; retry in the permitted residue.'
            lane=None
        else: lane=None
        if lane in ('west','east'): setattr(r,lane+'_commitments',getattr(r,lane+'_commitments')+1)
        r.turn+=1
        r.relay_cooldown=max(0,r.relay_cooldown-1)
        home=any(t['node']=='home' and (not self._causal or next(m['available'] for m in s.team if m['id']==t['actor'])) for t in r.allies)
        if self._causal:
            r.orders.append(lane)
            threats={lane:sum(bool(t['flag']) and t.get('route_lane')==lane for t in r.allies) for lane in ('west','east')}
            threats['enemy']=int(r.bridge_available and any(t['node']=='west' and not t['flag'] for t in r.allies))
            lane=opponent_lane(w.infrastructure.opponent,r.orders,r.turn,threats,r.loaded_crossings)
            guard=r.enemies[0]
            if guard['exhaustion']:
                guard['node']='sideline'
                r.reaction='Guard is temporarily suppressed.'
            else:
                guard['node']=lane
                r.reaction='Opponent shifts to '+lane+'.'
            if w.infrastructure.opponent.kind=='ambusher' and r.loaded_crossings>=w.infrastructure.opponent.threshold and not home:
                if r.raid_telegraph: r.enemy_points+=3; r.reaction+=' Raid reached undefended home.'
                else: r.raid_telegraph=True; r.reaction+=' Opponent telegraphs a home raid.'
            else: r.raid_telegraph=False
            if not guard['exhaustion']: self._intercept(lane)
            if r.enemy_points>=3: s.outcome='contest_loss'
            if r.turn>=48 or r.allied_points>=4: r.contest_over=True
            return
        if w.doctrine=='raid' and not home:
            if r.raid_telegraph: r.enemy_points+=3; r.reaction='Raid reached undefended home.'
            else: r.raid_telegraph=True; r.reaction='Opponent telegraphs a home raid.'
        else:
            r.raid_telegraph=False
            if r.west_commitments==r.east_commitments: lane=('west','east')[r.turn%2]
            elif w.doctrine=='guard': lane='west' if r.west_commitments>r.east_commitments else 'east'
            else: lane='west' if r.west_commitments<r.east_commitments else 'east'
            guard=r.enemies[0]
            guard['node']=lane; r.reaction='Opponent shifts to '+lane+' after counting lane commitments.'
            for runner in r.allies:
                if runner['node']!=lane: continue
                defense=runner['power']+runner['support']-runner['exhaustion']-bool(runner['flag'])
                runner['support']=0
                if guard['power']-guard['exhaustion']>defense:
                    if runner['flag']=='relay': r.relay_claimed=False
                    elif runner['flag']=='keeper': r.enemies[1]['flag']=True; r.enemies[1]['node']='enemy'
                    runner['flag']=False; runner['node']='home'; r.enemy_points+=1
                    r.reaction+=' Guard intercepts '+runner['actor']+' and returns the flag.'
                else: r.reaction+=' '+runner['actor']+' holds against interception.'
                runner['exhaustion']+=1
        if r.enemy_points>=3: s.outcome='contest_loss'
        if r.turn>=18 or r.allied_points>=4: r.contest_over=True

    def _intercept(self, lane):
        r=self._state.room
        guard=r.enemies[0]
        for runner in r.allies:
            if runner['node']!=lane: continue
            defense=runner['power']+runner['support']-self._fatigue(runner)-bool(runner['flag'])
            runner['support']=max(0,runner['support']-2)
            strength=guard['power']-guard['exhaustion']
            if strength>defense:
                if runner['flag']=='relay': r.relay_claimed=False
                elif runner['flag']=='keeper': r.enemies[1]['flag']=True; r.enemies[1]['node']='enemy'
                runner['flag']=False; runner['node']='home'; r.enemy_points+=1
                r.reaction+=' Guard intercepts '+runner['actor']+' and returns the flag.'
            else: r.reaction+=' '+runner['actor']+' holds against interception.'
            if defense<=strength+1: self._set_fatigue(runner,self._fatigue(runner)+1)

    def save_replay(self,path,visibility='public'):
        if visibility not in ('public','private'): raise ValueError('visibility must be public or private')
        header=dict(format='borderland-replay-v3' if self._causal else 'borderland-replay-v2',generation_version=self._world.generation_version,visibility=visibility,reexecution=visibility=='private',event_count=len(self._events),final_public_digest=self._events[-1]['after_public_digest'],final_outcome=self._state.outcome)
        if visibility=='private':
            from .replay import source_hash
            spec=asdict(self._world)
            header.update(world=spec,source_hash=source_hash(),spec_hash=hashlib.sha256(canonical(spec).encode()).hexdigest())
        lines=[canonical(header)]+[canonical(e) for e in self._events]
        Path(path).write_text('\n'.join(lines)+'\n',encoding='utf-8')