File size: 12,950 Bytes
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
from __future__ import annotations

from dataclasses import asdict, dataclass, field
from enum import IntEnum
import json
from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from .plant import Infrastructure, Charter


class Phase(IntEnum):
    RULE_CHAMBER = 1
    MOVING_MAZE = 2
    ARCHIVE = 3
    OSMOSIS = 4
    WITNESS_BLOCK = 5
    BLACKOUT = 6
    FINAL_EXIT = 7


def primitive(value: Any) -> Any:
    if isinstance(value, IntEnum):
        return int(value)
    if hasattr(value, 'to_dict'):
        return value.to_dict()
    if isinstance(value, dict):
        return {str(k): primitive(v) for k, v in value.items()}
    if isinstance(value, (tuple, list)):
        return [primitive(v) for v in value]
    return value


@dataclass(frozen=True)
class Action:
    tag: str
    arguments: dict = field(default_factory=dict)

    def to_dict(self):
        return {'tag': self.tag, 'arguments': primitive(self.arguments)}


@dataclass(frozen=True)
class ActionError:
    code: str
    message: str

    def to_dict(self):
        return asdict(self)


@dataclass(frozen=True)
class Observation:
    phase: Phase
    tick: int
    charge: int
    team: tuple
    inventory: tuple
    notebook: dict
    rules: tuple
    board: dict
    outcome: str

    def to_dict(self):
        return {k: primitive(v) for k, v in self.__dict__.items()}


@dataclass(frozen=True)
class Transition:
    observation: Observation
    legal_actions: tuple[Action, ...]
    reward: float = 0.0
    terminated: bool = False
    truncated: bool = False
    outcome: str = 'running'
    error: ActionError | None = None
    context_reset: bool = False
    revision: int = 0
    diagnostics: tuple = ()

    @property
    def done(self):
        return self.terminated or self.truncated

    def to_dict(self):
        return {k: primitive(v) for k, v in self.__dict__.items()}


@dataclass(frozen=True)
class RecordRevision:
    id: str
    subject: str
    statement: str
    issued_at: int
    supersedes: str | None
    seal: str
    authenticated: bool

    def __getitem__(self, key):
        return getattr(self, key)

    def to_dict(self):
        return asdict(self)


ARCHIVE_WORKLOADS = {'compact': 4, 'standard': 16, 'extended': 64}
ARCHIVE_SUBJECTS = ('restoration', 'authorization', 'egress')


@dataclass(frozen=True)
class ArchiveSpec:
    workload: str
    pages: tuple

    def page(self, slot, page):
        return self.pages[slot][page]

    def revisions(self):
        return tuple(record for scroll in self.pages for page in scroll for record in page)

    def revision(self, record_id, issued_at):
        return next(record for record in self.revisions() if record.id == record_id and record.issued_at == issued_at)

    def current(self, record_id):
        return max((record for record in self.revisions() if record.id == record_id and record.authenticated), key=lambda record: record.issued_at)

    def authoritative(self):
        return tuple(max((record for record in self.revisions() if record.subject == subject and record.authenticated), key=lambda record: record.issued_at) for subject in ARCHIVE_SUBJECTS)

    def validate(self):
        if self.workload not in ARCHIVE_WORKLOADS or type(self.pages) is not tuple or len(self.pages) != 6:
            raise ValueError('Invalid Archive workload or scroll count.')
        keys, subjects = set(), {}
        for scroll in self.pages:
            if type(scroll) is not tuple or len(scroll) != 3:
                raise ValueError('Archive scrolls require three pages.')
            series = set()
            for page in scroll:
                if type(page) is not tuple or len(page) != ARCHIVE_WORKLOADS[self.workload]:
                    raise ValueError('Archive packet size differs from workload.')
                for record in page:
                    if not isinstance(record, RecordRevision) or type(record.issued_at) is not int or record.issued_at < 1 or type(record.id) is not str or not record.id or type(record.subject) is not str or type(record.statement) is not str:
                        raise ValueError('Invalid revision identity.')
                    key = record.id, record.issued_at
                    if key in keys or record.subject not in ARCHIVE_SUBJECTS or subjects.get(record.id, record.subject) != record.subject:
                        raise ValueError('Duplicate revision or inconsistent subject.')
                    if record.seal != 'civic' or record.authenticated is not True:
                        raise ValueError('Revision packets require authenticated civic evidence.')
                    if record.subject == 'restoration' and sorted(record.statement.split('>')) != ['alpha', 'beta', 'gamma']:
                        raise ValueError('Invalid restoration statement.')
                    if record.subject == 'authorization' and record.statement not in {w+'/'+s for w in ('Iris','Juno','Kade') for s in ('amber','cobalt','silver')}:
                        raise ValueError('Invalid authorization statement.')
                    if record.subject == 'egress' and record.statement not in ('0','1','2'):
                        raise ValueError('Invalid egress statement.')
                    keys.add(key); series.add(record.id); subjects[record.id] = record.subject
            if len(series) != 1:
                raise ValueError('Each scroll must contain one stable series.')
        if len(subjects) != 6 or any(list(subjects.values()).count(subject) != 2 for subject in ARCHIVE_SUBJECTS):
            raise ValueError('Archive requires two series for each subject.')
        for record in self.revisions():
            if record.supersedes is not None and (record.supersedes == record.id or subjects.get(record.supersedes) != record.subject):
                raise ValueError('Invalid predecessor series.')
        for current in self.authoritative():
            peers = [self.current(rid) for rid, subject in subjects.items() if subject == current.subject]
            if peers[0].issued_at == peers[1].issued_at or current.supersedes is None:
                raise ValueError('Ambiguous endpoint or missing endpoint predecessor.')
            predecessor = self.current(current.supersedes)
            if predecessor.supersedes is not None or predecessor.issued_at >= current.issued_at:
                raise ValueError('Invalid endpoint chain.')


@dataclass(frozen=True)
class WorldSpec:
    generation_version: int
    ruleset: str
    private_seed: int
    polarity: int
    doctrine: str
    maze_rotation: int
    archive: ArchiveSpec | Charter
    restoration_order: tuple
    current_witness: str
    current_seal: str
    correct_track: int
    initial_charge: int
    reference_cost: int
    infrastructure: Infrastructure | None = None
    notebook_bytes: int = 768
    memory_profile: str = 'static'

    def __post_init__(self):
        if self.memory_profile not in ('static', 'commissioning') or (self.memory_profile == 'commissioning' and self.generation_version != 3):
            raise ValueError('Unsupported memory profile or generation.')
        if self.generation_version == 3:
            from .plant import Infrastructure, Charter, circuit_order, permit_decision, exit_decision, BUDGETS
            p = self.infrastructure
            if not isinstance(p, Infrastructure) or not isinstance(self.archive, Charter) or self.ruleset != 'campaign':
                raise ValueError('Generation three requires typed campaign infrastructure and charter.')
            p.validate(); self.archive.validate()
            if (p.load_schedule is not None) != (self.memory_profile == 'commissioning'):
                raise ValueError('Memory profile must match the infrastructure load schedule.')
            if sorted(self.archive.revisions(), key=lambda r: r.id) != sorted(p.revisions, key=lambda r: r.id):
                raise ValueError('Archive evidence contradicts infrastructure.')
            witness, seal = permit_decision(p)
            if (self.polarity, self.maze_rotation, self.restoration_order, self.current_witness, self.current_seal, self.correct_track, self.doctrine) != (p.calibrations[0].sensor_xor, p.calibrations[0].phase_offset, circuit_order(p), witness, seal, exit_decision(p)[0], p.opponent.kind):
                raise ValueError('Legacy compatibility values must be derived from infrastructure.')
            if self.initial_charge != BUDGETS[self.archive.workload]:
                raise ValueError('Generation three uses a profile-fixed initial charge budget.')
            if type(self.notebook_bytes) is not int or self.notebook_bytes < 0:
                raise ValueError('Notebook bytes must be a nonnegative integer.')
            return
        if self.generation_version != 2 or self.infrastructure is not None:
            raise ValueError('Unsupported generation. Use the pinned source for historical worlds.')
        self.archive.validate()
        statements = {record.subject: record.statement for record in self.archive.authoritative()}
        if statements != dict(restoration='>'.join(self.restoration_order), authorization=self.current_witness+'/'+self.current_seal, egress=str(self.correct_track)):
            raise ValueError('Archive endpoints contradict causal world facts.')

    @property
    def correct_records(self):
        if self.generation_version == 3:
            return tuple(self.infrastructure.current(service).id for service in self.infrastructure.services)
        return tuple(record.id for record in self.archive.authoritative())


@dataclass
class RuleState:
    kind: str = 'rule_chamber'
    latch: int = 0
    fixture: str | None = None
    live_sensor: int | None = None
    gate_open: bool = False
    sensor_visible: bool = False
    pulse_count: int = 0
    experiments: list = field(default_factory=list)
    channel: str | None = None
    phase_mark: int | None = None


@dataclass
class MazeState:
    kind: str = 'moving_maze'
    cell: int = 0
    clock: int = 0
    rotor_offset: int = 0
    scanned: bool = False
    collected: list = field(default_factory=list)
    discovered: list = field(default_factory=list)


@dataclass
class ArchiveState:
    kind: str = 'archive'
    slot: int | None = None
    page: int = 0
    exposed_versions: dict = field(default_factory=dict)
    compared_versions: set = field(default_factory=set)
    result: str | None = None
    filed: dict = field(default_factory=dict)


@dataclass
class OsmosisState:
    kind: str = 'osmosis'
    turn: int = 0
    allies: list = field(default_factory=lambda: [dict(actor=a, node='home', power=p, exhaustion=0, flag=False, support=0) for a, p in [('Ada', 5), ('Bo', 4), ('Cy', 3)]])
    enemies: list = field(default_factory=lambda: [dict(actor='guard', node='east', power=5, exhaustion=0, flag=False), dict(actor='keeper', node='enemy', power=3, exhaustion=0, flag=True)])
    allied_points: int = 0
    enemy_points: int = 0
    west_commitments: int = 0
    east_commitments: int = 0
    raid_telegraph: bool = False
    reaction: str = 'No opponent move yet.'
    bridge_available: bool = False
    contest_over: bool = False
    relay_claimed: bool = False
    relay_cooldown: int = 0
    base_captured: bool = False
    orders: list = field(default_factory=list)
    loaded_crossings: int = 0


@dataclass
class WitnessState:
    kind: str = 'witness_block'
    player_cell: int = 0
    witness_cells: dict = field(default_factory=lambda: {'Iris': 1, 'Juno': 2, 'Kade': 3})
    claim: dict | None = None
    checks: list = field(default_factory=list)
    checkpoint_test: str | None = None
    closure_in: int = 12
    clock: int = 0


@dataclass
class BlackoutState:
    kind: str = 'blackout'
    circuits: list = field(default_factory=lambda: [dict(id=x, bus=None, status='isolated') for x in ['alpha', 'beta', 'gamma']])
    activation_order: list = field(default_factory=list)
    discount_used: bool = False


@dataclass
class ExitState:
    kind: str = 'final_exit'
    installed: dict = field(default_factory=dict)
    track: int = 0
    boarded: list = field(default_factory=list)
    armed_with: str | None = None
    valve: str | None = None
    pressure_vented: bool = False


RoomState = RuleState | MazeState | ArchiveState | OsmosisState | WitnessState | BlackoutState | ExitState


@dataclass
class CampaignState:
    phase: Phase
    tick: int
    charge: int
    room: RoomState
    team: list = field(default_factory=lambda: [dict(id=a, power=p, exhaustion=0, available=True) for a, p in [('Ada', 5), ('Bo', 4), ('Cy', 3)]])
    inventory: list = field(default_factory=list)
    notebook: str = ''
    witness_authorization: str | None = None
    docket: dict = field(default_factory=dict)
    outcome: str = 'running'
    revision: int = 0
    feedback: Any = None


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