367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
288 lines
18 KiB
Python
288 lines
18 KiB
Python
"""Bounded read-only collection of public native opcode metadata during UI input.
|
|
|
|
The engine ring has only32 rows; keep polling while commands are typed rather
|
|
than requiring request and response to survive together in the final snapshot.
|
|
No payloads, credentials, engine calls or state-changing RPCs are accepted here.
|
|
"""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import threading
|
|
import time
|
|
|
|
|
|
def summarize_source_health(report,guid,field,*,after_index=-1):
|
|
"""Summarize retained source health changes, including heals and resets.
|
|
|
|
Decreases between retained samples are observations, not total damage or
|
|
attribution to an attacker. Missing samples can hide damage and healing.
|
|
This helper makes no claim that the engine or its UI applied these values.
|
|
"""
|
|
if (not isinstance(report,dict)or type(guid)not in(int,str)or not str(guid).isdecimal()
|
|
or str(int(guid))!=str(guid)or not 0<int(guid)<2**64 or type(field)is not int
|
|
or not 0<=field<=65535 or type(after_index)is not int or after_index< -1):
|
|
raise ValueError('Source health identity and trace boundary required')
|
|
source=report.get('source_unit_fields',{})
|
|
if not isinstance(source,dict):raise ValueError('Source field report required')
|
|
rows=source.get('rows',[])
|
|
if not isinstance(rows,list)or len(rows)>65536:raise ValueError('Bounded source health rows required')
|
|
values=[];last_sequence=-1;uncorrelated=0
|
|
for row in rows:
|
|
if not isinstance(row,dict):raise ValueError('Source field metadata row required')
|
|
if row.get('legacy_guid')!=str(guid)or row.get('field')!=field:continue
|
|
index=row.get('world_trace_index')
|
|
if type(index)is not int:uncorrelated+=1;continue
|
|
if index<=after_index:continue
|
|
value=row.get('value');sequence=row.get('sequence')
|
|
if type(value)is not int or not 0<=value<=0xffffffff or type(sequence)is not int or sequence<=last_sequence:
|
|
raise ValueError('Source health value or sequence differs')
|
|
last_sequence=sequence;values.append(value)
|
|
return dict(samples=len(values),first=values[0]if values else None,minimum=min(values)if values else None,
|
|
last=values[-1]if values else None,net_decrease=values[0]-values[-1]if values else None,
|
|
observed_decreases=sum(max(0,a-b)for a,b in zip(values,values[1:])),
|
|
observed_increases=sum(max(0,b-a)for a,b in zip(values,values[1:])),uncorrelated_rows=uncorrelated,
|
|
complete_retained_capture=bool(source.get('available')is True and source.get('counter_offset_confirmed')is True
|
|
and source.get('lost_rows')==0 and report.get('lost_metadata_rows')==0 and report.get('observer_error')is None and not uncorrelated),
|
|
total_damage_verified=False,attacker_attribution_verified=False,engine_application_verified=False)
|
|
|
|
|
|
class WorldTrace:
|
|
def __init__(self, controller, *, collect_fields=True,action_log=None,metadata_scope='world'):
|
|
if type(collect_fields)is not bool:raise ValueError('Explicit source-field observation boolean required')
|
|
if metadata_scope not in ('world','pipe') or (metadata_scope=='pipe' and collect_fields):
|
|
raise ValueError('Pipe metadata scope requires explicit header-only collection')
|
|
self.metadata_scope=metadata_scope
|
|
self.collect_fields=collect_fields
|
|
self.controller=controller;self.records=[];self.lost=0;self.error=None
|
|
self.last=None;self.lock=threading.Lock();self.stop=threading.Event()
|
|
self.motion_latest=None;self.motion_guid=None;self.motion_started=None
|
|
self.motion_baseline_ids=set();self.motion_seen=set();self.motion_records=[]
|
|
self.field_last=None;self.field_packets=None;self.field_lost=0;self.field_records=[]
|
|
self.field_available=False;self.field_overwritten=0;self.world_received=None;self.source_events={}
|
|
self.field_retryable_reads=0;self.field_latest_available=False
|
|
self.field_offset_candidate=None;self.field_offset_sample=None;self.field_offset_confirmed=False
|
|
self.action_available=False
|
|
self.action_last_sequence=0
|
|
self.action_first_sequence=None
|
|
self.action_observed=0
|
|
self.action_sequence_gaps=0
|
|
self.action_records=[]
|
|
self.action_memory_dropped=0
|
|
self.action_log=Path(action_log) if action_log is not None else None
|
|
self.action_streamed=0
|
|
self.action_log_error=None
|
|
|
|
@staticmethod
|
|
def _motion_key(row):
|
|
return (row['id'],row['facing'],row['duration'],row['points'],tuple(row['start']),tuple(row['destination']))
|
|
|
|
ACTION_RECORD_LIMIT=32768
|
|
|
|
def capture_actions(self,motion):
|
|
"""Retain the owned numeric ABI2 action stream independently of NPC tracking."""
|
|
if motion is None or "actions" not in motion:
|
|
return
|
|
with self.lock:
|
|
self.action_available=True
|
|
for row in sorted(motion["actions"],key=lambda item:int(item["sequence"])):
|
|
sequence=int(row["sequence"])
|
|
if sequence<=self.action_last_sequence:
|
|
continue
|
|
if self.action_last_sequence:
|
|
self.action_sequence_gaps+=max(0,sequence-self.action_last_sequence-1)
|
|
if self.action_first_sequence is None:
|
|
self.action_first_sequence=sequence
|
|
self.action_last_sequence=sequence
|
|
self.action_observed+=1
|
|
record=dict(row,seen_monotonic=time.monotonic())
|
|
if len(self.action_records)<self.ACTION_RECORD_LIMIT:
|
|
self.action_records.append(record)
|
|
else:
|
|
self.action_memory_dropped+=1
|
|
if self.action_log is not None and self.action_log_error is None:
|
|
try:
|
|
payload=json.dumps(record,separators=(",",":"),allow_nan=False)+"\n"
|
|
flags=os.O_WRONLY|os.O_CREAT|os.O_APPEND|getattr(os,"O_NOFOLLOW",0)|getattr(os,"O_CLOEXEC",0)
|
|
fd=os.open(self.action_log,flags,0o600)
|
|
with os.fdopen(fd,"a",encoding="utf-8") as stream:
|
|
stream.write(payload)
|
|
self.action_streamed+=1
|
|
except (OSError,ValueError,TypeError) as error:
|
|
self.action_log_error=type(error).__name__
|
|
|
|
def _action_report(self):
|
|
return dict(available=self.action_available,observed=self.action_observed,
|
|
first_sequence=self.action_first_sequence,last_sequence=self.action_last_sequence,
|
|
missing_between_reads=self.action_sequence_gaps,
|
|
memory_dropped=self.action_memory_dropped,records=list(self.action_records),
|
|
log_path=str(self.action_log) if self.action_log is not None else None,
|
|
streamed=self.action_streamed,log_error=self.action_log_error)
|
|
|
|
def track_motion(self,guid):
|
|
"""Arm one exact actor from the latest existing poll; make no RPC/input."""
|
|
if type(guid) not in (int,str) or not str(guid).isdecimal() or not 0<int(guid)<2**64:raise ValueError('Require a bounded source actor GUID')
|
|
with self.lock:
|
|
if self.error:raise RuntimeError('Read-only observer failed: '+self.error)
|
|
if self.motion_guid is not None:raise RuntimeError('Actor motion tracking is already armed')
|
|
if self.motion_latest is None:raise RuntimeError('Public native motion metadata unavailable')
|
|
self.motion_guid=str(int(guid));self.motion_started=time.monotonic()
|
|
baseline=[r for r in self.motion_latest['rows'] if r['legacy_guid']==self.motion_guid]
|
|
self.motion_seen={self._motion_key(r) for r in baseline};self.motion_baseline_ids={r['id'] for r in baseline}
|
|
return set(self.motion_baseline_ids)
|
|
|
|
def capture_motion(self,motion):
|
|
with self.lock:
|
|
if motion is None:
|
|
if self.motion_guid is not None:raise RuntimeError('Tracked actor motion metadata disappeared')
|
|
return
|
|
if len(motion['rows'])>16:raise RuntimeError('Public motion ring exceeds declared bound')
|
|
if self.motion_guid is not None and self.motion_latest is not None and any(motion[k]<self.motion_latest[k] for k in ('received','sent','unknown','rejected')):raise RuntimeError('Actor motion counters reset during operation')
|
|
self.motion_latest=motion
|
|
if self.motion_guid is None:return
|
|
for row in motion['rows']:
|
|
if row['legacy_guid']!=self.motion_guid:continue
|
|
key=self._motion_key(row)
|
|
if key in self.motion_seen:continue
|
|
if len(self.motion_records)>=512:raise RuntimeError('Bounded actor motion observation exhausted')
|
|
self.motion_seen.add(key);self.motion_records.append(dict(seen_monotonic=time.monotonic(),**row))
|
|
|
|
def motion_rows(self):
|
|
with self.lock:return list(self.motion_records)
|
|
|
|
def bookmark(self):
|
|
"""Last observed event index for the strict after_index contract.
|
|
|
|
last is the next event index (the source count), so last itself is
|
|
not a pre-action bookmark: it would exclude the first immediate event.
|
|
A ready but empty trace correctly returns-1.
|
|
"""
|
|
with self.lock:
|
|
if self.error:raise RuntimeError('Read-only observer failed: '+self.error)
|
|
if self.last is None:raise RuntimeError('World trace is not initialized')
|
|
return self.last-1
|
|
|
|
def capture(self, world):
|
|
count=world['trace_count'];rows=world['trace'];start=count-len(rows)
|
|
with self.lock:
|
|
# Source ordinals belong to the host counter. The independent
|
|
# translation counter is correlated below, never assumed equal.
|
|
received=world.get('received');source_count=sum(r['direction']==1 for r in rows)
|
|
ordinal=received-source_count if type(received) is int and received>=source_count else None
|
|
enriched=[]
|
|
for i,row in enumerate(rows,start):
|
|
item=dict(index=i,**row)
|
|
if item['direction']==1 and ordinal is not None:
|
|
ordinal+=1;item['host_source_packet']=ordinal;self.source_events[ordinal]=item
|
|
enriched.append(item)
|
|
if len(self.source_events)>65536:raise RuntimeError('Bounded source-event correlation exhausted')
|
|
if type(received) is int:
|
|
if self.world_received is not None and received<self.world_received:raise RuntimeError('World source counter reset during operation')
|
|
self.world_received=received
|
|
if self.last is None:self.last=count;return
|
|
if count<self.last:raise RuntimeError('World trace reset during operation')
|
|
self.lost+=max(0,start-self.last)
|
|
self.records.extend(row for row in enriched if row['index']>=self.last)
|
|
self.last=count
|
|
if len(self.records)>65536:raise RuntimeError('Bounded world trace exhausted')
|
|
|
|
def capture_fields(self,fields):
|
|
if not self.collect_fields:return
|
|
with self.lock:
|
|
if fields is None:
|
|
if self.field_available:raise RuntimeError('Public source-field metadata disappeared')
|
|
return
|
|
if fields.get('retryable'):
|
|
if fields.get('available') is not False or fields.get('reason')!='source-field-snapshot-busy' or fields.get('attempts')!=3 or fields.get('rows')!=[]:raise RuntimeError('Public source-field unavailable result differs')
|
|
self.field_retryable_reads+=1;self.field_latest_available=False
|
|
self.field_offset_sample=None;self.field_offset_candidate=None;self.field_offset_confirmed=False
|
|
return
|
|
total=fields['total'];packets=fields['source_packets'];rows=fields['rows']
|
|
if fields['overflow'] or len(rows)>64:raise RuntimeError('Public source-field counters overflowed')
|
|
if rows and [r['sequence'] for r in rows]!=list(range(total-len(rows)+1,total+1)):raise RuntimeError('Public source-field rows are not a contiguous tail')
|
|
if self.field_last is not None and (total<self.field_last or packets<self.field_packets):raise RuntimeError('Source-field counters reset during operation')
|
|
self.field_available=True;self.field_latest_available=True;self.field_overwritten=fields['overwritten']
|
|
sample=(self.world_received,packets)
|
|
if self.world_received is not None:
|
|
offset=self.world_received-packets
|
|
previous=self.field_offset_sample
|
|
if offset!=self.field_offset_candidate:
|
|
self.field_offset_candidate=offset;self.field_offset_confirmed=False
|
|
elif previous and sample[0]>previous[0] and sample[1]>previous[1] and sample[0]-previous[0]==sample[1]-previous[1]:
|
|
self.field_offset_confirmed=True
|
|
self.field_offset_sample=sample
|
|
if self.field_last is None:self.field_last=total;self.field_packets=packets;return
|
|
start=total-len(rows)+1;self.field_lost+=max(0,start-self.field_last-1)
|
|
for row in rows:
|
|
if row['sequence']<=self.field_last:continue
|
|
if len(self.field_records)>=65536:raise RuntimeError('Bounded source-field observation exhausted')
|
|
item=dict(row);item['world_trace_index']=None;item['correlation']='unverified'
|
|
if self.field_offset_confirmed:
|
|
event=self.source_events.get(row['source_packet']+self.field_offset_candidate)
|
|
if event and event['opcode']==row['opcode']:
|
|
item['world_trace_index']=event['index'];item['correlation']='stable-counter-delta-and-opcode'
|
|
self.field_records.append(item)
|
|
self.field_last=total;self.field_packets=packets
|
|
|
|
def _collect(self):
|
|
try:
|
|
while not self.stop.wait(.05):
|
|
pipe=self.controller.rpc('inspect-engine-pipe',unit_fields_only=True)
|
|
if self.metadata_scope=='pipe':
|
|
# Preworld submit() writes the existing PIPE header ring.
|
|
# The separate World ring omits advertisement/reply rows.
|
|
self.capture(pipe)
|
|
if pipe['error'] or pipe['closed']:raise RuntimeError('Native pipe failed during observation')
|
|
continue
|
|
self.capture_actions(pipe.get("motion"))
|
|
self.capture(pipe['world'])
|
|
self.capture_motion(pipe.get('motion'))
|
|
self.capture_fields(pipe.get('source_unit_fields'))
|
|
if pipe['error'] or pipe['closed']:raise RuntimeError('Native pipe failed during observation')
|
|
except Exception as error:self.error=str(error);self.stop.set()
|
|
|
|
def __enter__(self):
|
|
pipe=self.controller.rpc('inspect-engine-pipe',unit_fields_only=True)
|
|
if self.metadata_scope=='pipe':self.capture(pipe)
|
|
else:
|
|
self.capture(pipe['world']);self.capture_motion(pipe.get('motion'));self.capture_fields(pipe.get('source_unit_fields'))
|
|
self.thread=threading.Thread(target=self._collect,daemon=True);self.thread.start();return self
|
|
|
|
def __exit__(self,*exception):
|
|
self.stop.set();self.thread.join(5)
|
|
if self.thread.is_alive():self.error='Read-only observer did not finish'
|
|
|
|
def wait(self,direction,opcode,timeout=5,*,after_index=None):
|
|
deadline=time.monotonic()+timeout
|
|
while time.monotonic()<deadline:
|
|
if self.error:raise RuntimeError(self.error)
|
|
with self.lock:
|
|
match=next((r for r in self.records if r['direction']==direction and r['opcode']==opcode and (after_index is None or r['index']>after_index)),None)
|
|
if match:return match
|
|
self.stop.wait(.02)
|
|
raise RuntimeError('Bounded native opcode observation expired; do not repeat a state change without inspection')
|
|
|
|
def source_before(self,native,opcode,*,after_index=None):
|
|
"""Correlate a native emission to its immediately preceding source event.
|
|
|
|
The adapter records source->translated outputs before its next source
|
|
packet. Reject missing/overwritten rows rather than choosing an earlier
|
|
unrelated NPC spell with the same opcode.
|
|
"""
|
|
if native['direction']!=3:raise ValueError('Require native receive emission')
|
|
with self.lock:
|
|
source=next((r for r in reversed(self.records) if r['direction']==1 and r['index']<native['index']),None)
|
|
if source is None or source['opcode']!=opcode or (after_index is not None and source['index']<=after_index):raise RuntimeError('Correlated source opcode unavailable; preserve trace without replay')
|
|
return source
|
|
|
|
def report(self):
|
|
with self.lock:
|
|
report=dict(trace=list(self.records),lost_metadata_rows=self.lost,observer_error=self.error,source_actions=self._action_report())
|
|
report['source_unit_fields']=dict(observation_enabled=self.collect_fields,available=self.field_available,rows=list(self.field_records),lost_rows=self.field_lost,
|
|
latest_available=self.field_latest_available,retryable_reads=self.field_retryable_reads,
|
|
last_sequence=self.field_last,source_packets=self.field_packets,snapshot_overwritten=self.field_overwritten,
|
|
counter_offset_candidate=self.field_offset_candidate,counter_offset_confirmed=self.field_offset_confirmed,
|
|
host_received=self.world_received,engine_application_verified=False,
|
|
correlation_limit='Stable advancing counter deltas and a matching retained opcode support the index association; missing/gapped/non-atomic snapshots leave it unverified.')
|
|
if self.motion_guid is not None:report['tracked_actor_motion']=dict(legacy_guid=self.motion_guid,armed_monotonic=self.motion_started,baseline_ids=sorted(self.motion_baseline_ids),complete_capture_verified=False,rows=list(self.motion_records))
|
|
return report
|