File size: 6,061 Bytes
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from copy import deepcopy
import json
from types import SimpleNamespace

from borderland import Action
from borderland.plant import LANES, WITNESSES, SEALS
from borderland_verify.causal_reference import CausalReference


def encode(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False)


class PublicTransition:
    def __init__(self, public):
        self.observation = SimpleNamespace(to_dict=lambda: deepcopy(public['observation']))
        self.legal_actions = tuple(Action(a['tag'], a['arguments']) for a in public['legal_actions'])


class StreamingController:
    def decide(self, public):
        o = public['observation']
        b = o['board']
        text = o['notebook']['text']
        note = json.loads(text) if text else {'v': 4, 'a': [], 'p': {}}
        if note['v'] == 3 and o['phase'] == 3:
            return {'tool': 'execute_action', 'arguments': {'tag': 'bind_docket', 'arguments': {'record_ids': sorted(b['filed'].values())}}}
        if o['phase'] >= 4:
            assert note['v'] == 3
            reference = CausalReference()
            action = reference.choose(PublicTransition(public))
            return {'tool': 'execute_action', 'arguments': action.to_dict()}
        assert note['v'] == 4
        previous = encode(note)
        readings = {cid: [bit, phase] for cid, bit, phase in note['a']}
        if o['phase'] == 1:
            pair = readings.setdefault(b['channel'], [None, None])
            if b['live_sensor'] is not None:
                pair[0] = b['live_sensor'] ^ (b['latch'] & 1)
            if b['phase_mark'] is not None:
                pair[1] = (b['phase_mark'] - b['latch']) % 4
            note['a'] = [[cid, *values] for cid, values in readings.items() if values != [None, None]]
        if o['phase'] == 2 and b['transit_plate'] is not None:
            plate = b['transit_plate']
            note['t'] = [LANES.index(plate['freight_lane']), plate['delivery_residue'], plate['closure_residue'], plate['bridge_rating']]
        if o['phase'] == 3 and b['records']:
            for record in b['records']:
                if not record['authenticated'] or record['applies_channel'] is None:
                    continue
                if readings[record['applies_channel']][0] != record['applies_bit']:
                    continue
                active = note.get('q')
                if active and active[0] == record['subject'] and active[3] > record['issued_at']:
                    continue
                self.compile_service(note, readings, record)
                note['q'] = [record['subject'], record['id'], record['supersedes'], record['issued_at']]
        if encode(note) != previous:
            return self.save(note, o)
        reference = CausalReference()
        reference.calibrations = readings
        reference.channel_order = b.get('channels', list(readings))
        if 't' in note:
            from borderland.plant import Transit
            t = note['t']
            reference.transit = Transit(LANES[t[0]], *t[1:])
        if o['phase'] in (1, 2):
            action = reference.choose(PublicTransition(public))
        else:
            p = note['p']
            if len(b['filed']) == b['service_count']:
                return self.save({'v': 3, 'p': self.ordered_plan(p)}, o)
            active = note.get('q')
            current_service = b['records'][0]['subject'] if b['records'] else None
            if b['slot'] is None or current_service in b['filed']:
                slot = 0 if b['slot'] is None else b['slot'] + 1
                action = Action('open_scroll', {'slot': slot})
            elif b['page'] + 1 < b['page_count']:
                action = Action('advance_page', {})
            else:
                assert active and active[0] == current_service
                if b['result'] == 'verified exposed civic revision chain':
                    action = Action('file_record', {'record_id': active[1]})
                else:
                    action = Action('compare_seal', {'left_id': active[2], 'right_id': active[1]})
        return {'tool': 'execute_action', 'arguments': action.to_dict()}

    def save(self, note, observation):
        text = encode(note)
        assert len(text.encode('utf-8')) <= observation['notebook']['capacity_bytes'], len(text.encode('utf-8'))
        assert text != observation['notebook']['text']
        return {'tool': 'replace_notebook', 'arguments': {'text': text}}

    def compile_service(self, note, readings, record):
        p = note['p']
        body = record['body']
        bit, phase = readings[body['channel']]
        freight, residue, _, _ = note['t']
        service = record['subject']
        if body['kind'] == 'circuit':
            entry = [service, LANES[bit ^ freight ^ body['bus_shift']], body['predecessors'], ''.join(map(str, record['ratings']))]
            circuits = {c[0]: c for c in p.get('c', [])}
            circuits[service] = entry
            p['c'] = list(circuits.values())
        elif body['kind'] == 'delivery':
            p['d'] = [LANES[freight ^ bit ^ LANES.index(body['lane'])], (residue - phase) % 4]
        elif body['kind'] == 'permit':
            p['w'] = WITNESSES[(WITNESSES.index(body['witness']) + freight) % 3]
            p['s'] = SEALS[(SEALS.index(body['seal']) + phase) % 3]
            p['a'] = service
        elif body['kind'] == 'egress':
            p['e'] = [(freight + phase + body['track_delta']) % 3, LANES[bit ^ freight ^ body['valve_shift']]]
            p['g'] = service

    def ordered_plan(self, plan):
        plan = deepcopy(plan)
        remaining = {entry[0]: entry for entry in plan['c']}
        ordered = []
        while remaining:
            live = {entry[0] for entry in ordered}
            ready = sorted(cid for cid, entry in remaining.items() if set(entry[2]) <= live)
            assert ready
            ordered.append(remaining.pop(ready[0]))
        plan['c'] = ordered
        return plan


def choose(public):
    return StreamingController().decide(deepcopy(public))