from __future__ import annotations import json from borderland import Action from borderland.plant import (Calibration, Transit, CharterRevision, Infrastructure, OpponentLaw, decode_clause, delivery_lane, permit_decision, circuit_bus, circuit_order, exit_decision, compensated_bus) class CausalReference: def __init__(self): self.calibrations = {} self.channel_order = [] self.transit = None self.records = {} self.ratings = {} self.seen_pages = set() self.compared = set() self.plan = {} self.rule_actions = [] self.route = None self.observed_reactions = [] self._last_observation = None self.audited = set() self.pending_audit = None def _record(self, record): if 'ratings' in record: self.ratings[record['id']] = ''.join(str(t) for t in record['ratings']) self.records[record['id']] = CharterRevision(record['id'], record['subject'], record['issued_at'], record['supersedes'], record['applies_channel'], record['applies_bit'], decode_clause(record['body']), record['authenticated'], record['seal']) def _plant(self): channels = tuple(Calibration(cid, *self.calibrations[cid]) for cid in self.channel_order) return Infrastructure(channels, self.transit, tuple(self.records.values()), OpponentLaw('tracker', 2, 1, 2, 0)) def _compile(self): p = self._plant() circuits = [[cid, circuit_bus(p, cid), list(p.current(cid).body.predecessors)] for cid in circuit_order(p)] for circuit in circuits: curve = self.ratings.get(p.current(circuit[0]).id) if curve is not None: circuit.append(curve) witness, seal = permit_decision(p) track, valve = exit_decision(p) permit_service = next(s for s in p.services if p.current(s).body.kind == 'permit') egress_service = next(s for s in p.services if p.current(s).body.kind == 'egress') delivery = p.clause('delivery') self.plan = dict(c=circuits, w=witness, s=seal, a=permit_service, g=egress_service, e=[track,valve], d=[delivery_lane(p), (p.transit.delivery_residue-p.channel(delivery.channel).phase_offset)%4]) def _ingest(self, transition): o = transition.observation.to_dict(); b=o['board'] if o == self._last_observation: return o,b self._last_observation=o if not self.plan and o['notebook']['text']: try: note=json.loads(o['notebook']['text']) if note.get('v') == 3: self.plan=note['p'] except (ValueError,TypeError,AttributeError,KeyError): pass if o['phase'] == 1: self.channel_order=b['channels'] channel=b['channel'] readings=self.calibrations.setdefault(channel,[None,None]) if b['live_sensor'] is not None: readings[0]=b['live_sensor']^(b['latch']&1) if b['phase_mark'] is not None: readings[1]=(b['phase_mark']-b['latch'])%4 elif o['phase'] == 2 and b['transit_plate']: self.transit=Transit(**b['transit_plate']) elif o['phase'] == 3: if b['records']: self.seen_pages.add((b['slot'],b['page'])) for record in b['records']: self._record(record) elif o['phase'] == 4: self.observed_reactions.append(b['reaction']) feedback=b.get('feedback') if isinstance(feedback,dict) and 'trip' in feedback: self.pending_audit=feedback['circuit'] if isinstance(feedback,dict) and 'audit' in feedback: record=feedback['audit']; body=record['body']; calibration=feedback['calibration']; transit=feedback['transit'] self.audited.add(record['subject']) if self.pending_audit==record['subject']: self.pending_audit=None self._record(record) recovered=self.records[record['id']] channels={c['id']:Calibration(**c) for c in (calibration,feedback['applicability_calibration'])} public_plant=Infrastructure(tuple(channels.values()),Transit(**transit),(recovered,),OpponentLaw('tracker',2,1,2,0)) if body['kind']=='circuit': circuit=[record['subject'],circuit_bus(public_plant,record['subject']),body['predecessors']] curve = self.ratings.get(record['id']) if curve is not None: circuit.append(curve) known={c[0]:c for c in self.plan.get('c',[])}; known[circuit[0]]=circuit self.plan['c']=list(known.values()) elif body['kind']=='egress': self.plan['e']=list(exit_decision(public_plant)) self.plan['g']=record['subject'] elif body['kind']=='permit': self.plan['s']=permit_decision(public_plant)[1] return o,b def notebook(self, transition): o,b=self._ingest(transition) if o['phase']==4 and not all(key in self.plan for key in ('c','w','s','a','g','e','d')): self._compile() if not self.plan: return None text=json.dumps(dict(v=3,p=self.plan),sort_keys=True,separators=(',',':')) if len(text.encode('utf-8')) > o['notebook']['capacity_bytes']: return None return text if text!=o['notebook']['text'] else None def choose(self, transition): o,b=self._ingest(transition) phase=o['phase'] def a(tag,**arguments): return Action(tag,arguments) if phase==1: for channel in b['channels']: readings=self.calibrations.get(channel,[None,None]) if readings == [None,None] and b['channel']!=channel: return a('select_channel',channel=channel) if readings[0] is None: if b['latch']!=0: return a('set_latch',value=0) if b['fixture']!='sensor': return a('pulse',fixture='sensor') return a('observe_sensor') if readings[1] is None: return a('pulse',fixture='relay') if b['gate_open']: return a('lock_chamber') target=2+self.calibrations[b['channels'][0]][0] if b['latch']!=target: return a('set_latch',value=target) if b['fixture']!='relay': return a('pulse',fixture='relay') return a('pulse',fixture='gate') if phase==2: target=4 if self.transit is None or 'relay_cell' not in o['inventory'] else 2 if self.transit.bridge_rating==0 and 'bridge_rig' not in o['inventory'] else 8 if not b['scanned']: return a('scan') if b['cell']==target: return a('leave_maze') if target==8 else a('collect') frontier=[(b['cell'],[])]; seen={b['cell']} while frontier: cell,path=frontier.pop(0) if cell==target: break for neighbor in (cell-3,cell+3,cell-1 if cell%3 else -1,cell+1 if cell%3<2 else -1): if 0<=neighbor<9 and neighbor not in seen: seen.add(neighbor); frontier.append((neighbor,path+[neighbor])) direction={-3:'north',3:'south',-1:'west',1:'east'}[path[0]-b['cell']] command=a('walk',direction=direction) return command if command in transition.legal_actions else a('wait') if phase==3: for slot in b['slots']: for page in range(3): if (slot,page) not in self.seen_pages: return a('open_scroll',slot=slot) if page==0 or b['slot']!=slot else a('advance_page') p=self._plant() for service in p.services: record=p.current(service) if service not in self.compared: self.compared.add(service) return a('compare_seal',left_id=record.supersedes,right_id=record.id) if b['filed'].get(service)!=record.id: return a('file_record',record_id=record.id) return a('bind_docket',record_ids=sorted(b['filed'].values())) if phase==4: if b['contest_over']: return a('end_osmosis') runner=next(t for t in b['allies'] if t['actor']=='Ada') self.route='relay' if runner['node']=='home': if runner['exhaustion']>0: return a('rest',actor='Ada') if runner['flag']: return a('bank',actor='Ada') if b['turn']%4==self.plan['d'][1] else a('rest',actor='Bo') if runner['support']<12: return a('support',actor='Bo',ally='Ada') if b['relay_cooldown']: return a('rest',actor='Bo') return a('deploy',actor='Ada',neighbor=self.plan['d'][0]) if runner['node'] in ('west','east'): return a('deploy',actor='Ada',neighbor='home' if runner['flag'] else 'relay') return a('deploy',actor='Ada',neighbor=self.plan['d'][0]) if phase==5: witness=self.plan['w'] cell=b['witness_cells'][witness] if b['player_cell']!=cell: return a('visit',cell=cell) if not b['claim'] or b['claim']['witness']!=witness: return a('interview',witness=witness) if not any(c['claim']==b['claim']['id'] and c['status']=='verified' for c in b['checks']): return a('cross_check',claim_id=b['claim']['id'],record_id=self.plan['a']) if b['checkpoint_test']!=self.plan['s']: return a('test_checkpoint',seal_id=self.plan['s']) command=a('escort',witness=witness,neighbor=4) return command if command in transition.legal_actions else a('wait') if phase==6: if self.pending_audit is not None: return a('audit_service',service=self.pending_audit) if not self.plan.get('e') or len(self.plan.get('c',[]))!=len(b['circuits']): known={c[0] for c in self.plan.get('c',[])} seen=getattr(self,'audited',set()) feedback=b.get('feedback') if isinstance(feedback,dict) and 'audit' in feedback: seen.add(feedback['audit']['subject']) self.audited=seen return a('audit_service',service=next(s for s in b['service_ids'] if s not in seen and s not in known)) circuits={c['id']:c for c in b['circuits']} live={c['id'] for c in b['circuits'] if c['status']=='live'} for entry in self.plan['c']: cid,base_bus,predecessors=entry[:3] circuit=circuits[cid] if cid in live or not set(predecessors)<=live: continue bus = base_bus if circuit.get('meter') is not None: if len(entry) < 4 or type(entry[3]) is not str or len(entry[3]) != 8 or any(t not in '0123' for t in entry[3]): return a('audit_service',service=cid) meter = circuit['meter'] bus = compensated_bus(base_bus, tuple(int(t) for t in entry[3]), meter['band'], meter['load']) if circuit['status']=='tripped': ada=next(m for m in o['team'] if m['id']=='Ada') if ada['exhaustion']: return a('rest',actor='Ada') return a('isolate',circuit=cid) if circuit['status']=='isolated' or circuit['bus']!=bus: return a('connect',circuit=cid,bus=bus) return a('energize',circuit=cid) return a('restore') if phase==7: feedback=b.get('feedback') if isinstance(feedback,dict) and feedback.get('seal') is False: return a('audit_service',service=self.plan['a']) if isinstance(feedback,dict) and (feedback.get('track') is False or feedback.get('pressure') is False): return a('audit_service',service=self.plan['g']) if b['pressure_vented'] and not (isinstance(feedback,dict) and feedback.get('audit',{}).get('body',{}).get('kind')=='egress'): return a('audit_service',service=self.plan['g']) if not self.plan.get('e'): return a('audit_service',service=next(s for s in b['service_ids'] if s not in getattr(self,'audited',set()))) for item,socket in (('coupler','coupler'),('exit_power','power')): if b['installed'].get(socket)!=item: return a('install',item=item,socket=socket) if b['valve'] is not None and (b['track']!=self.plan['e'][0] or b['valve']!=self.plan['e'][1] or b['armed_with']!=self.plan.get('s')): return a('repair_exit') if b['track']!=self.plan['e'][0] and b['valve'] is None: return a('align_track',position=self.plan['e'][0]) waiting=[m['id'] for m in o['team'] if m['available'] and m['id'] not in b['boarded']] escape_cost=1 + (4 if b['valve'] is None else 0) + int(b['armed_with']!=self.plan.get('s')) if waiting and (len(b['boarded'])<2 or o['charge']>=escape_cost+len(waiting)): return a('board',actor=waiting[0]) seal=self.plan.get('s') if seal is None: feedback=b.get('feedback') if isinstance(feedback,dict) and 'audit' in feedback: self.audited=getattr(self,'audited',set())|{feedback['audit']['subject']} return a('audit_service',service=next(s for s in b['service_ids'] if s not in getattr(self,'audited',set()))) if b['armed_with']!=seal: return a('arm_exit',seal_id=seal) if b['pressure_vented']: return a('repair_exit') if b['valve'] is None: return a('open_valve',side=self.plan['e'][1]) return a('launch') raise RuntimeError('No public reference action for this observation.')