# Generated by build_bundle.py. Edit source modules, regenerate, then test.

# SOURCE: action.py
"""Enterprise Action Requests 0.1.0 candidate: a bounded synthetic local adapter.

Host administration, authenticated actor IDs, time, policy verification and file
access are TRUSTED fixture inputs, not production authentication. No network,
shell, financial, personnel or other real-world effect is supported.
"""
from contextlib import contextmanager
from pathlib import Path
import hashlib
import json
import re
import sqlite3
import uuid
from jsonschema import Draft202012Validator

MAX_BYTES=131072
SCHEMA=json.loads(Path(__file__).with_name('action.schema.json').read_text(encoding='utf-8'))
WITHHELD={'status':'withheld'}
STATES={'pending','committed','cancelled','expired','rejected-precondition'}

class Refused(ValueError): pass
class ResponseLost(RuntimeError): pass

def require(condition, code):
    if not condition: raise Refused(code)

def _bounded(value, depth=0):
    require(depth<=24,'wire-depth')
    if value is None or type(value) is bool: return
    if type(value) is int:
        require(abs(value)<=9007199254740991,'wire-integer'); return
    if type(value) is str:
        require(len(value)<=4096 and not any(0xD800<=ord(c)<=0xDFFF for c in value),'wire-string'); return
    if type(value) is list:
        require(len(value)<=256,'wire-array')
        for item in value: _bounded(item,depth+1)
        return
    if type(value) is dict:
        require(len(value)<=128 and all(type(k) is str for k in value),'wire-object')
        for k,v in value.items(): _bounded(k,depth+1); _bounded(v,depth+1)
        return
    raise Refused('wire-type')

def encoded(value):
    """Python code-point sorted, ordered arrays, UTF-8; explicitly NOT JCS."""
    _bounded(value)
    result=json.dumps(value,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False).encode('utf-8')
    require(len(result)<=MAX_BYTES,'wire-bytes')
    return result

def digest(value): return hashlib.sha256(encoded(value)).hexdigest()

def _pairs(items):
    result={}
    for k,v in items:
        require(k not in result,'duplicate-key'); result[k]=v
    return result

def parse(raw):
    require(type(raw) in (str,bytes),'wire-input')
    try:
        if isinstance(raw,bytes): raw=raw.decode('utf-8',errors='strict')
        require(len(raw.encode('utf-8'))<=MAX_BYTES,'wire-bytes')
        def bad(_): raise Refused('wire-number')
        value=json.loads(raw,object_pairs_hook=_pairs,parse_float=bad,parse_constant=bad)
        encoded(value)
        return value
    except (UnicodeError,json.JSONDecodeError,RecursionError): raise Refused('wire-json') from None

def validate(kind, value):
    encoded(value)
    validator=Draft202012Validator({'$ref':'#/$defs/'+kind,'$defs':SCHEMA['$defs']})
    require(not list(validator.iter_errors(value)),'schema-'+kind)
    if kind=='ActionDefinition':
        require(value['validFrom']<value['validUntil'],'definition-window')
        if value['mode']=='synthetic-executable':
            require(value['parameterContract']=='ordered-label-list/1' and value['targetType']=='urn:vercy:synthetic:OrderedLabelResource' and value['adapter']=='local-sqlite-ordered-labels/1' and value['compensation']=='new-request-restores-before-labels-at-exact-after-revision','executable-definition')
            require(value['precondition']=='resource-revision-and-retained-compensation-v1' and value['effectBoundary']=='local-atomic-ordered-label-replacement-v1','executable-boundary')
        else:
            require(type(value['parameterContract']) is dict and value['adapter']=='none' and value['compensation']=='external-unspecified','descriptive-definition')
    if kind=='Policy':
        for rule in value:
            require((rule['actorId']==rule['principalId'])==(rule['mode']=='self'),'representation-mode')
            for name in ('principalScope','delegateScope'):
                require(rule[name]['validFrom']<rule[name]['validUntil'],'scope-window')
    return value

def definition_ref(definition):
    validate('ActionDefinition',definition)
    return {'definitionId':definition['definitionId'],'version':definition['version'],'sha256':digest(definition)}

def matching_rules(policy,intent,action,now):
    matches=[]
    for rule in policy:
        if (rule['actorId'],rule['principalId'])!=(intent['actorId'],intent['principalId']): continue
        def contains(scope):
            return all(scope[k]==intent[k] for k in ('dimensionId','definition','resourceId','purpose','audience')) and action in scope['actions'] and scope['validFrom']<=now<scope['validUntil']
        if contains(rule['principalScope']) and contains(rule['delegateScope']): matches.append(digest(rule))
    return sorted(set(matches))

def _json(value): return encoded(value).decode('utf-8')
def _id(prefix): return prefix+'.'+uuid.uuid4().hex

SQL='''
CREATE TABLE meta (id INTEGER PRIMARY KEY CHECK(id=1), dimension TEXT NOT NULL, issuer TEXT NOT NULL, epoch TEXT NOT NULL, clock INTEGER NOT NULL, policy_revision INTEGER NOT NULL, control_sequence INTEGER NOT NULL);
CREATE TABLE definitions (id TEXT NOT NULL, version TEXT NOT NULL, body TEXT NOT NULL, digest TEXT NOT NULL, available INTEGER NOT NULL, recorded_at INTEGER NOT NULL, control_sequence INTEGER NOT NULL, retired_sequence INTEGER, ordinal INTEGER PRIMARY KEY AUTOINCREMENT, UNIQUE(id,version));
CREATE TABLE policies (revision INTEGER PRIMARY KEY, body TEXT NOT NULL, recorded_at INTEGER NOT NULL, control_sequence INTEGER NOT NULL);
CREATE TABLE resources (id TEXT NOT NULL, revision INTEGER NOT NULL, labels TEXT NOT NULL, recorded_at INTEGER NOT NULL, PRIMARY KEY(id,revision));
CREATE TABLE requests (id TEXT PRIMARY KEY, slot TEXT UNIQUE NOT NULL, body TEXT NOT NULL);
CREATE TABLE events (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, body TEXT NOT NULL);
'''

class Executor:
    """One database is the authoritative fixture. Public methods return redacted results.

    The host must construct authenticated actor/time inputs and isolate admin API,
    exports and database access. The epoch pin detects a wrong store, not a coherent
    rollback. Restored stores require external continuity reconciliation before use.
    """
    def __init__(self,path,expected_epoch):
        self.path=Path(path).resolve(); self.expected_epoch=expected_epoch

    @classmethod
    def create(cls,path,dimension,issuer,now):
        require(re.fullmatch(SCHEMA['$defs']['Intent']['properties']['dimensionId']['pattern'],dimension) is not None,'dimension-id')
        require(re.fullmatch(SCHEMA['$defs']['Intent']['properties']['dimensionId']['pattern'],issuer) is not None,'issuer-id')
        cls._time(now)
        path=Path(path).resolve(); path.parent.mkdir(parents=True,exist_ok=True)
        # Exclusive create, so accidental use never truncates a prior history.
        with path.open('xb'): pass
        epoch=_id('epoch')
        c=sqlite3.connect(path)
        try:
            c.executescript(SQL)
            c.execute('INSERT INTO meta VALUES(1,?,?,?,?,0,0)',(dimension,issuer,epoch,now))
            c.execute('INSERT INTO policies VALUES(0,?,?,0)',('[]',now)); c.commit()
        finally: c.close()
        return cls(path,epoch)

    @staticmethod
    def _time(now): require(type(now) is int and 946684800<=now<=4102444800,'host-time')

    @contextmanager
    def _tx(self,now):
        self._time(now)
        c=sqlite3.connect(self.path.as_uri()+'?mode=rw',uri=True,timeout=15,isolation_level=None)
        c.row_factory=sqlite3.Row
        try:
            c.execute('PRAGMA synchronous=FULL'); c.execute('BEGIN IMMEDIATE')
            meta=dict(c.execute('SELECT * FROM meta WHERE id=1').fetchone())
            require(meta['epoch']==self.expected_epoch,'store-epoch')
            require(now>=meta['clock'],'host-clock-regression')
            mseq=meta['control_sequence']+1
            require(mseq<=9007199254740991,'control-sequence-overflow')
            c.execute('UPDATE meta SET clock=?,control_sequence=? WHERE id=1',(now,mseq))
            meta['control_sequence']=mseq; meta['clock']=now
            yield c,meta
            c.execute('COMMIT')
        except BaseException:
            if c.in_transaction: c.execute('ROLLBACK')
            raise
        finally: c.close()

    def set_policy(self,policy,now):
        """TRUSTED fixture host administration: verify issuer standing/basis externally."""
        validate('Policy',policy)
        with self._tx(now) as (c,m):
            rev=m['policy_revision']+1
            c.execute('INSERT INTO policies VALUES(?,?,?,?)',(rev,_json(policy),now,m['control_sequence']))
            c.execute('UPDATE meta SET policy_revision=? WHERE id=1',(rev,))
            return rev

    def add_definition(self,definition,now):
        validate('ActionDefinition',definition)
        with self._tx(now) as (c,m):
            require(not c.execute('SELECT 1 FROM resources WHERE id=?',(definition['definitionId'],)).fetchone(),'object-kind-collision')
            old=c.execute('SELECT body FROM definitions WHERE id=? AND version=?',(definition['definitionId'],definition['version'])).fetchone()
            if old:
                require(old['body']==_json(definition),'definition-version-conflict'); return
            c.execute('INSERT INTO definitions(id,version,body,digest,available,recorded_at,control_sequence) VALUES(?,?,?,?,1,?,?)',
                      (definition['definitionId'],definition['version'],_json(definition),digest(definition),now,m['control_sequence']))

    def retire_definition(self,reference,now):
        validate('DefinitionRef',reference)
        with self._tx(now) as (c,m):
            require(c.execute('UPDATE definitions SET available=0,retired_sequence=COALESCE(retired_sequence,?) WHERE id=? AND version=? AND digest=?',
                  (m['control_sequence'],reference['definitionId'],reference['version'],reference['sha256'])).rowcount==1,'unknown-definition')

    def add_resource(self,resource_id,labels,now):
        validate('Labels',labels)
        require(type(resource_id) is str and re.fullmatch(SCHEMA['$defs']['Intent']['properties']['resourceId']['pattern'],resource_id) is not None,'resource-id')
        with self._tx(now) as (c,m):
            require(not c.execute('SELECT 1 FROM definitions WHERE id=?',(resource_id,)).fetchone(),'object-kind-collision')
            require(not c.execute('SELECT 1 FROM resources WHERE id=?',(resource_id,)).fetchone(),'resource-exists')
            c.execute('INSERT INTO resources VALUES(?,0,?,?)',(resource_id,_json(labels),now))

    @staticmethod
    def _policy(c,m): return json.loads(c.execute('SELECT body FROM policies WHERE revision=?',(m['policy_revision'],)).fetchone()[0])
    @staticmethod
    def _slot(actor,key):
        require(type(key) is str and re.fullmatch('[A-Za-z0-9._:-]{8,128}',key) is not None,'retry-key')
        return digest({'actorId':actor,'key':key})
    @staticmethod
    def _get(c,slot):
        row=c.execute('SELECT body FROM requests WHERE slot=?',(slot,)).fetchone()
        return json.loads(row[0]) if row else None
    @staticmethod
    def _save(c,request): c.execute('UPDATE requests SET body=? WHERE id=?',(_json(request),request['requestId']))
    @staticmethod
    def _event(c,m,request,kind,payload,now):
        eid=_id('evt')
        cur=c.execute('INSERT INTO events(id,body) VALUES(?,?)',(eid,'{}'))
        e={'eventId':eid,'sequence':cur.lastrowid,'controlSequence':m['control_sequence'],'kind':kind,'requestId':request['requestId'],'recordedAt':now,'issuerId':m['issuer'],'payload':payload}
        validate('Event',e)
        c.execute('UPDATE events SET body=? WHERE sequence=?',(_json(e),cur.lastrowid)); return e
    @staticmethod
    def _definition(c,intent,now):
        pin=intent['definition']
        row=c.execute('SELECT * FROM definitions WHERE id=? AND version=? AND digest=?',(pin['definitionId'],pin['version'],pin['sha256'])).fetchone()
        if not row: return None,False
        d=json.loads(row['body'])
        return d,bool(row['available'] and d['validFrom']<=now<d['validUntil'])
    @staticmethod
    def _out(c,request,readable,code=None):
        if not readable: return dict(WITHHELD)
        if code: return {'status':code}
        result={'status':'key-retired' if request['keyRetired'] else request['state'],'requestId':request['requestId'],'intentDigest':request['intentDigest']}
        if request['receiptId']:
            result['receipt']=json.loads(c.execute('SELECT body FROM events WHERE id=?',(request['receiptId'],)).fetchone()[0])
        return result

    def dispatch(self,raw,key,actor,now,*,_fault=None):
        """Admit/try a closed synthetic intent. Key is per authenticated actor/store.

        _fault is test instrumentation, never an untrusted transport parameter.
        Malformed, absent and unauthorized diagnostics share the withheld response.
        A response does not disclose whether execute-only actions produced effects.
        """
        try:
            intent=validate('Intent',parse(raw)); require(intent['actorId']==actor,'authenticated-actor')
            slot=self._slot(actor,key)
            with self._tx(now) as (c,m):
                require(intent['dimensionId']==m['dimension'],'dimension')
                policy=self._policy(c,m); request=self._get(c,slot)
                readable=bool(matching_rules(policy,intent,'read',now))
                if request:
                    readable=readable and bool(matching_rules(policy,request['intent'],'read',now))
                    if request['intentDigest']!=digest(intent) or encoded(request['intent'])!=encoded(intent):
                        return self._out(c,request,readable,'key-conflict')
                    if request['keyRetired']: return self._out(c,request,readable)
                definition,available=self._definition(c,intent,now)
                if not request:
                    if not matching_rules(policy,intent,'submit',now): return dict(WITHHELD)
                    if not definition or definition['mode']!='synthetic-executable': return self._out(c,None,readable,'definition-not-executable')
                    if intent['purpose'] not in definition['purposes']: return self._out(c,None,readable,'definition-purpose')
                    request={'requestId':_id('req'),'keyHash':slot,'intentDigest':digest(intent),'intent':intent,'submittedAt':now,'submissionEventId':_id('placeholder'),'state':'pending','receiptId':None,'keyRetired':False}
                    e=self._event(c,m,request,'submission',{'intentDigest':request['intentDigest']},now)
                    request['submissionEventId']=e['eventId']
                    c.execute('INSERT INTO requests VALUES(?,?,?)',(request['requestId'],slot,_json(request)))
                self._event(c,m,request,'delivery',{'intentDigest':request['intentDigest']},now)
                matches=matching_rules(policy,intent,'execute',now)
                allowed=bool(matches and available)
                trial=self._event(c,m,request,'try',{'decision':{'action':'execute','policyRevision':m['policy_revision'],'allowed':allowed,'matchedRuleDigests':matches,'definitionAvailable':available}},now)
                if request['state']!='pending': return self._out(c,request,readable,None if allowed else 'current-execution-denied')
                if now>=intent['expiresAt']:
                    self._terminal(c,m,request,'expired','deadline',now,trial['eventId'])
                elif not allowed: return self._out(c,request,readable,'current-execution-denied')
                else:
                    row=c.execute('SELECT * FROM resources WHERE id=? ORDER BY revision DESC LIMIT 1',(intent['resourceId'],)).fetchone()
                    reason='resource-revision'
                    valid=bool(row and row['revision']==intent['expectedRevision'])
                    if intent['compensatesReceiptId']:
                        old=c.execute('SELECT body FROM events WHERE id=?',(intent['compensatesReceiptId'],)).fetchone()
                        original=json.loads(old[0]) if old else None
                        p=original['payload'] if original else {}
                        original_request=c.execute('SELECT body FROM requests WHERE id=?',(original['requestId'],)).fetchone() if original else None
                        oi=json.loads(original_request[0])['intent'] if original_request else {}
                        same_context=all(oi.get(k)==intent[k] for k in ('actorId','principalId','purpose','audience','dimensionId'))
                        valid=bool(valid and original and original['kind']=='receipt' and same_context and p['resourceId']==intent['resourceId'] and p['definition']==intent['definition'] and p['afterRevision']==intent['expectedRevision'] and p['beforeLabels']==intent['parameters']['labels'])
                        reason='compensation-precondition'
                    if not valid: self._terminal(c,m,request,'rejected-precondition',reason,now,trial['eventId'])
                    else:
                        if _fault=='before-effect': raise Refused('injected-rollback')
                        after=row['revision']+1
                        require(after<=9007199254740991,'revision-overflow')
                        c.execute('INSERT INTO resources VALUES(?,?,?,?)',(intent['resourceId'],after,_json(intent['parameters']['labels']),now))
                        if _fault=='after-effect': raise Refused('injected-rollback')
                        receipt=self._event(c,m,request,'receipt',{'definition':intent['definition'],'resourceId':intent['resourceId'],'beforeRevision':row['revision'],'afterRevision':after,'beforeLabels':json.loads(row['labels']),'afterLabels':intent['parameters']['labels'],'compensatesReceiptId':intent['compensatesReceiptId'],'tryEventId':trial['eventId']},now)
                        request['receiptId']=receipt['eventId']; request['state']='committed'; self._save(c,request)
                result=self._out(c,request,readable)
            if _fault=='after-commit': raise ResponseLost('Committed transaction; caller did not receive the response. Reconcile using the SAME key.')
            return result
        except (Refused,sqlite3.Error,KeyError,TypeError): return dict(WITHHELD)

    def _terminal(self,c,m,request,state,reason,now,trial=None):
        require(request['state']=='pending','terminal-transition')
        self._event(c,m,request,'disposition',{'from':'pending','to':state,'reason':reason,'tryEventId':trial},now)
        request['state']=state; self._save(c,request)

    def lookup(self,key,actor,now):
        try:
            slot=self._slot(actor,key)
            with self._tx(now) as (c,m):
                request=self._get(c,slot)
                if not request: return dict(WITHHELD)
                return self._out(c,request,bool(matching_rules(self._policy(c,m),request['intent'],'read',now)))
        except (Refused,sqlite3.Error,KeyError,TypeError): return dict(WITHHELD)

    def cancel(self,key,actor,now):
        try:
            slot=self._slot(actor,key)
            with self._tx(now) as (c,m):
                r=self._get(c,slot)
                if not r: return dict(WITHHELD)
                policy=self._policy(c,m); readable=bool(matching_rules(policy,r['intent'],'read',now))
                if r['keyRetired']: return self._out(c,r,readable)
                matches=matching_rules(policy,r['intent'],'cancel',now)
                trial=self._event(c,m,r,'try',{'decision':{'action':'cancel','policyRevision':m['policy_revision'],'allowed':bool(matches),'matchedRuleDigests':matches,'definitionAvailable':self._definition(c,r['intent'],now)[1]}},now)
                if not matches: return self._out(c,r,readable,'current-cancellation-denied')
                if r['state']=='pending':
                    state='expired' if now>=r['intent']['expiresAt'] else 'cancelled'
                    self._terminal(c,m,r,state,'deadline' if state=='expired' else 'authorized-cancellation',now,trial['eventId'])
                return self._out(c,r,readable)
        except (Refused,sqlite3.Error,KeyError,TypeError): return dict(WITHHELD)

    def observe(self,key,actor,now,claim,reason,corrects=None):
        try:
            slot=self._slot(actor,key)
            with self._tx(now) as (c,m):
                r=self._get(c,slot)
                if not r: return dict(WITHHELD)
                policy=self._policy(c,m); readable=bool(matching_rules(policy,r['intent'],'read',now))
                matches=matching_rules(policy,r['intent'],'observe',now)
                if not readable or not matches or r['keyRetired']: return dict(WITHHELD)
                if corrects:
                    old=c.execute('SELECT body FROM events WHERE id=?',(corrects,)).fetchone()
                    previous=json.loads(old[0]) if old else None
                    require(previous and previous['kind']=='observation' and previous['requestId']==r['requestId'] and previous['payload']['observerId']==actor,'observation-predecessor')
                    observations=[json.loads(x[0]) for x in c.execute('SELECT body FROM events')]
                    require(not any(x['kind']=='observation' and x['payload']['correctsEventId']==corrects for x in observations),'observation-already-corrected')
                trial=self._event(c,m,r,'try',{'decision':{'action':'observe','policyRevision':m['policy_revision'],'allowed':True,'matchedRuleDigests':matches,'definitionAvailable':self._definition(c,r['intent'],now)[1]}},now)
                e=self._event(c,m,r,'observation',{'observerId':actor,'claim':claim,'reason':reason,'correctsEventId':corrects,'tryEventId':trial['eventId']},now)
                return {'status':'recorded','event':e}
        except (Refused,sqlite3.Error,KeyError,TypeError): return dict(WITHHELD)

    def retire_key(self,key,actor,now):
        """TRUSTED retention administration: retain immutable intent/receipt forever here."""
        with self._tx(now) as (c,m):
            r=self._get(c,self._slot(actor,key)); require(r and r['state']!='pending','retire-terminal-only')
            if not r['keyRetired']:
                self._event(c,m,r,'key-retirement',{'retained':True},now)
                r['keyRetired']=True; self._save(c,r)

    def snapshot(self,now):
        """Privileged evidence export. NEVER expose this method as a caller endpoint."""
        with self._tx(now) as (c,m):
            m['clock']=now
            return {'format':'enterprise-action-snapshot/0.1.0','meta':m,
                'definitions':[dict(x) for x in c.execute('SELECT * FROM definitions ORDER BY ordinal')],
                'policies':[dict(x) for x in c.execute('SELECT * FROM policies ORDER BY revision')],
                'resources':[dict(x) for x in c.execute('SELECT * FROM resources ORDER BY id,revision')],
                'requests':[json.loads(x[0]) for x in c.execute('SELECT body FROM requests ORDER BY id')],
                'events':[json.loads(x[0]) for x in c.execute('SELECT body FROM events ORDER BY sequence')]}

# SOURCE: history.py
"""Internal consistency of complete fixture snapshots; not authenticated admission.

A coherent old or fabricated snapshot can pass. Trusted latest export/continuity
roots, authentication, authority verification and disclosure remain host duties.
"""
import re

def fields(value,names):
    require(type(value) is dict and set(value)==set(names.split()),'snapshot-fields')

def integer(value,minimum=0): require(type(value) is int and minimum<=value<=9007199254740991,'snapshot-integer')

def validate_snapshot(s):
    try: return _validate(s)
    except (KeyError,TypeError,IndexError,ValueError) as e:
        if isinstance(e,Refused): raise
        raise Refused('snapshot-malformed') from None

def _validate(s):
    fields(s,'format meta definitions policies resources requests events')
    for name in ('definitions','policies','resources','requests','events'):
        require(type(s[name]) is list and len(s[name])<=10000,'snapshot-list-bounds')
    require(s['format']=='enterprise-action-snapshot/0.1.0','snapshot-version')
    m=s['meta']; fields(m,'id dimension issuer epoch clock policy_revision control_sequence')
    require(m['id']==1 and type(m['id']) is int,'snapshot-meta')
    Executor._time(m['clock']); integer(m['policy_revision']); integer(m['control_sequence'])
    for k in ('dimension','issuer','epoch'):
        require(type(m[k]) is str and re.fullmatch('[A-Za-z0-9][A-Za-z0-9._:-]{2,127}',m[k]) is not None,'snapshot-id')
    definitions={}; ordinals=[]
    for row in s['definitions']:
        fields(row,'id version body digest available recorded_at control_sequence retired_sequence ordinal')
        d=validate('ActionDefinition',parse(row['body'])); pin=definition_ref(d)
        require(row['id']==d['definitionId'] and row['version']==d['version'] and row['digest']==pin['sha256'],'definition-digest')
        integer(row['ordinal'],1); integer(row['control_sequence'],1); Executor._time(row['recorded_at'])
        require(row['recorded_at']<=m['clock'] and row['control_sequence']<=m['control_sequence'],'definition-future')
        retired=row['retired_sequence']
        if retired is not None:
            integer(retired,1); require(row['control_sequence']<retired<=m['control_sequence'],'retirement-sequence')
        require(type(row['available']) is int and row['available']==int(retired is None),'definition-availability')
        key=(d['definitionId'],d['version']); require(key not in definitions,'definition-duplicate')
        definitions[key]=(d,row); ordinals.append(row['ordinal'])
    require(ordinals==list(range(1,len(ordinals)+1)),'definition-order')
    policies={}; previous_control=-1; previous_time=0
    for row in s['policies']:
        fields(row,'revision body recorded_at control_sequence')
        integer(row['revision']); integer(row['control_sequence']); Executor._time(row['recorded_at'])
        require(row['revision']==len(policies) and previous_control<row['control_sequence']<=m['control_sequence'],'policy-order')
        require(previous_time<=row['recorded_at']<=m['clock'],'policy-time')
        policies[row['revision']]=(validate('Policy',parse(row['body'])),row)
        previous_control=row['control_sequence']; previous_time=row['recorded_at']
    require(policies and m['policy_revision']==len(policies)-1 and policies[0][0]==[] and policies[0][1]['control_sequence']==0,'policy-root')
    def current_policy(e):
        eligible=[rev for rev,(_,row) in policies.items() if row['control_sequence']<=e['controlSequence']]
        rev=max(eligible); policy,row=policies[rev]
        require(row['recorded_at']<=e['recordedAt'],'policy-future'); return rev,policy
    def definition_at(intent,e):
        pin=intent['definition']; d,row=definitions[(pin['definitionId'],pin['version'])]
        require(definition_ref(d)==pin and row['control_sequence']<=e['controlSequence'] and row['recorded_at']<=e['recordedAt'],'definition-pin')
        available=(row['retired_sequence'] is None or e['controlSequence']<row['retired_sequence']) and d['validFrom']<=e['recordedAt']<d['validUntil']
        return d,available
    requests={}; slots=set()
    for r in s['requests']:
        validate('ActionRequestSnapshot',r); i=r['intent']
        require(r['requestId'] not in requests and r['keyHash'] not in slots,'request-identity')
        require(i['dimensionId']==m['dimension'] and digest(i)==r['intentDigest'],'intent-digest')
        require(r['submittedAt']<=m['clock'],'request-future')
        requests[r['requestId']]=r; slots.add(r['keyHash'])
    resource_rows={}; live={}; expected_resources=[]
    for row in s['resources']:
        fields(row,'id revision labels recorded_at')
        require(type(row['id']) is str and re.fullmatch('[A-Za-z0-9][A-Za-z0-9._:-]{2,127}',row['id']) is not None,'resource-id')
        integer(row['revision']); Executor._time(row['recorded_at']); validate('Labels',parse(row['labels']))
        key=(row['id'],row['revision']); require(key not in resource_rows,'resource-duplicate'); resource_rows[key]=row
        require(row['recorded_at']<=m['clock'],'resource-future')
        if row['revision']==0:
            live[row['id']]=row; expected_resources.append(row)
    seen={}; states={}; receipts={}; retired=set(); corrected=set(); last_time=0; last_control=0; used_trials=set()
    def precondition(intent):
        row=live.get(intent['resourceId'])
        valid=bool(row and row['revision']==intent['expectedRevision'])
        rid=intent['compensatesReceiptId']
        if rid:
            original=seen.get(rid)
            if not original or original['kind']!='receipt': return False
            old_i=requests[original['requestId']]['intent']; p=original['payload']
            valid=bool(valid and all(old_i[k]==intent[k] for k in ('actorId','principalId','purpose','audience','dimensionId')) and p['resourceId']==intent['resourceId'] and p['definition']==intent['definition'] and p['afterRevision']==intent['expectedRevision'] and p['beforeLabels']==intent['parameters']['labels'])
        return valid
    def trial_for(e,action,allowed=True):
        t=seen.get(e['payload']['tryEventId'])
        require(t and t['kind']=='try' and t['requestId']==e['requestId'] and t['controlSequence']==e['controlSequence'] and t['recordedAt']==e['recordedAt'],'trial-link')
        require(t['payload']['decision']['action']==action and (not allowed or t['payload']['decision']['allowed']),'trial-authority')
        require(t['eventId'] not in used_trials,'trial-reused'); used_trials.add(t['eventId'])
        return t
    for index,e in enumerate(s['events'],1):
        validate('Event',e); rid=e['requestId']; kind=e['kind']; p=e['payload']
        require(e['sequence']==index and e['eventId'] not in seen,'event-sequence')
        require(last_time<=e['recordedAt']<=m['clock'] and last_control<=e['controlSequence']<=m['control_sequence'],'event-order')
        last_time=e['recordedAt']; last_control=e['controlSequence']
        require(rid in requests and rid not in retired and e['issuerId']==m['issuer'],'event-context')
        r=requests[rid]; intent=r['intent']; now=e['recordedAt']
        require(now>=r['submittedAt'],'event-before-admission')
        rev,policy=current_policy(e); definition,available=definition_at(intent,e)
        if kind=='submission':
            require(rid not in states and e['eventId']==r['submissionEventId'] and now==r['submittedAt'],'submission-identity')
            require(p['intentDigest']==r['intentDigest'] and definition['mode']=='synthetic-executable' and intent['purpose'] in definition['purposes'],'submission-definition')
            require(matching_rules(policy,intent,'submit',now),'submission-permission'); states[rid]='pending'
        else:
            require(rid in states,'missing-submission')
            if kind=='delivery': require(p['intentDigest']==r['intentDigest'],'delivery-digest')
            elif kind=='try':
                d=p['decision']; matches=matching_rules(policy,intent,d['action'],now)
                require(d['policyRevision']==rev and d['matchedRuleDigests']==matches and d['definitionAvailable']==available,'decision-evidence')
                require(d['allowed']==bool(matches and (available if d['action']=='execute' else True)),'decision-outcome')
                if d['action']=='execute':
                    prev=s['events'][index-2] if index>=2 else None
                    require(prev and prev['kind']=='delivery' and prev['requestId']==rid and prev['controlSequence']==e['controlSequence'],'try-delivery')
            elif kind=='receipt':
                trial_for(e,'execute'); require(states[rid]=='pending' and now<intent['expiresAt'] and precondition(intent),'receipt-guard')
                row=live[intent['resourceId']]
                require(row['recorded_at']<=now,'resource-before-creation')
                expected={'definition':intent['definition'],'resourceId':intent['resourceId'],'beforeRevision':row['revision'],'afterRevision':row['revision']+1,'beforeLabels':parse(row['labels']),'afterLabels':intent['parameters']['labels'],'compensatesReceiptId':intent['compensatesReceiptId'],'tryEventId':p['tryEventId']}
                require(p==expected,'receipt-effect')
                row={'id':intent['resourceId'],'revision':p['afterRevision'],'labels':encoded(p['afterLabels']).decode('utf-8'),'recorded_at':now}
                live[row['id']]=row; expected_resources.append(row); receipts[rid]=e['eventId']; states[rid]='committed'
            elif kind=='disposition':
                require(states[rid]=='pending','terminal-rewrite')
                if p['to']=='cancelled':
                    trial_for(e,'cancel'); require(now<intent['expiresAt'] and p['reason']=='authorized-cancellation','cancel-guard')
                elif p['to']=='expired':
                    t=seen.get(p['tryEventId']); require(t and t['kind']=='try','expiry-try')
                    action=t['payload']['decision']['action']; require(action in ('cancel','execute'),'expiry-action')
                    trial_for(e,action,allowed=(action=='cancel'))
                    require(now>=intent['expiresAt'] and p['reason']=='deadline','expiry-guard')
                else:
                    trial_for(e,'execute'); require(now<intent['expiresAt'] and not precondition(intent),'rejection-guard')
                    require(p['reason']==('compensation-precondition' if intent['compensatesReceiptId'] else 'resource-revision'),'rejection-reason')
                states[rid]=p['to']
            elif kind=='observation':
                trial_for(e,'observe'); require(matching_rules(policy,intent,'read',now) and p['observerId']==intent['actorId'],'observation-rights')
                predecessor=p['correctsEventId']
                if predecessor:
                    old=seen.get(predecessor)
                    require(old and old['kind']=='observation' and old['requestId']==rid and old['payload']['observerId']==p['observerId'] and predecessor not in corrected,'correction-chain')
                    corrected.add(predecessor)
            elif kind=='key-retirement':
                require(states[rid]!='pending','pending-retirement'); retired.add(rid)
        seen[e['eventId']]=e
    require(set(states)==set(requests),'missing-history')
    for rid,r in requests.items():
        require(r['state']==states[rid] and r['receiptId']==receipts.get(rid) and r['keyRetired']==(rid in retired),'snapshot-lifecycle')
    require(sorted(expected_resources,key=lambda x:(x['id'],x['revision']))==s['resources'],'resource-history')
    return {'valid':True,'definitions':len(definitions),'requests':len(requests),'events':len(seen),'effects':len(receipts),
            'assurance':'internal-consistency-only-not-authenticity-or-latest-history'}

# SOURCE: native.py
"""Deterministic post-commit native evidence, with a manifest written LAST."""
from datetime import datetime,timezone
from pathlib import Path
import hashlib
import json

def stamp(second): return datetime.fromtimestamp(second,timezone.utc).isoformat().replace('+00:00','Z')
def file_bytes(value): return json.dumps(value,ensure_ascii=False,sort_keys=True,indent=2,allow_nan=False).encode('utf-8')+b'\n'
def sha(raw): return hashlib.sha256(raw).hexdigest()

def records(snapshot):
    validate_snapshot(snapshot)
    m=snapshot['meta']; result={}; previous={}; object_ids=set()
    provenance={'source':m['issuer'],'assurance':'synthetic-reference-only'}
    def obj(oid,rid,kind,name,time,facet,state='active'):
        record={'recordType':'object','schemaVersion':'1.0.0','recordId':rid,'objectId':oid,'objectType':kind,'name':name,
                'recordedAt':stamp(time),'previousRecordId':previous.get(oid),'state':state,'facets':facet,'provenance':provenance}
        require(rid not in result,'native-id-collision'); result[rid]=record; previous[oid]=rid; object_ids.add(oid)
    for row in snapshot['definitions']:
        d=parse(row['body'])
        obj(d['definitionId'],'rec.def.'+row['digest'],'urn:vercy:enterprise:ActionDefinition:0.1.0',d['name'],row['recorded_at'],{'enterpriseActionDefinition':d})
    for row in snapshot['resources']:
        if row['revision']==0: require(row['id'] not in object_ids,'native-subject-collision')
        obj(row['id'],'rec.resource.'+digest({'id':row['id'],'revision':row['revision']}),'urn:vercy:synthetic:OrderedLabelResource','Synthetic ordered-label resource',row['recorded_at'],{'syntheticLabels':{'revision':row['revision'],'labels':parse(row['labels'])}})
    for r in snapshot['requests']:
        require(r['requestId'] not in object_ids,'native-subject-collision')
        immutable={k:r[k] for k in ('requestId','keyHash','intentDigest','intent','submittedAt','submissionEventId')}
        obj(r['requestId'],'rec.'+r['requestId'],'urn:vercy:enterprise:ActionRequest:0.1.0','Synthetic action request',r['submittedAt'],{'enterpriseActionRequest':immutable})
    for e in snapshot['events']:
        request=next(r for r in snapshot['requests'] if r['requestId']==e['requestId'])
        subjects=[e['requestId'],request['intent']['definition']['definitionId']]
        if e['kind']=='receipt': subjects.append(e['payload']['resourceId'])
        for field in ('correctsEventId','compensatesReceiptId'):
            if e['payload'].get(field): subjects.append(e['payload'][field])
        require(e['eventId'] not in result,'native-id-collision')
        result[e['eventId']]={'recordType':'event','schemaVersion':'1.0.0','eventId':e['eventId'],
              'eventType':'urn:vercy:enterprise:action:'+e['kind']+':0.1.0','subjectIds':list(dict.fromkeys(subjects)),
              'occurredAt':stamp(e['recordedAt']),'recordedAt':stamp(e['recordedAt']),'actorId':e['issuerId'],
              'payload':{'enterpriseActionEvent':e},'provenance':provenance}
    return result

def export_snapshot(snapshot,target,*,_fail_after=None):
    """Privileged export. A retry must use the identical snapshot including cut/time.

    Files are append-only and exact-match on retry. Partial writes are detectable;
    no claim of an atomic native multi-file commit. No changes go back to execution.
    """
    target=Path(target); require(not target.is_symlink(),'export-symlink')
    recs=records(snapshot)
    blobs={'snapshot.json':file_bytes(snapshot)}
    for rid,record in recs.items(): blobs['records/'+rid+'.json']=file_bytes(record)
    manifest={'format':'enterprise-action-export/0.1.0','dimensionId':snapshot['meta']['dimension'],'executorEpoch':snapshot['meta']['epoch'],
              'controlSequence':snapshot['meta']['control_sequence'],'eventSequence':len(snapshot['events']),
              'exportedAt':stamp(snapshot['meta']['clock']),'files':{name:sha(raw) for name,raw in sorted(blobs.items())},
              'assurance':'synthetic-evidence-not-authenticated-current-state'}
    blobs['manifest.json']=file_bytes(manifest)
    for index,(name,raw) in enumerate(blobs.items(),1):
        path=target/name
        require(not path.is_symlink() and not path.parent.is_symlink(),'export-symlink')
        path.parent.mkdir(parents=True,exist_ok=True)
        if path.exists(): require(path.read_bytes()==raw,'export-existing-content')
        else:
            with path.open('xb') as f: f.write(raw)
        if _fail_after==index: raise Refused('injected-export-interruption')
    return verify_export(target)

def validate_native_records(snapshot,stored_records):
    """Explicit nested validation of the full supplied package record set.

    Caller must collect the complete authorized set for this binding; this checks
    that set against the supplied cut, not all records/permissions in a Dimension.
    """
    require(type(stored_records) is list,'native-record-list')
    expected=records(snapshot); actual={}
    for r in stored_records:
        require(type(r) is dict,'native-record-shape')
        rid=r.get('recordId') if r.get('recordType')=='object' else r.get('eventId')
        require(type(rid) is str and rid not in actual,'native-record-identity'); actual[rid]=r
    require(set(actual)==set(expected),'native-record-closure')
    for rid,value in expected.items(): require(actual[rid]==value,'native-record-projection')
    return {'valid':True,'records':len(actual),'scope':'supplied complete package set and snapshot; not authenticated latest-history'}

def verify_export(target):
    """Whole exact-file closure + deterministic semantic replay; no trust bootstrap."""
    target=Path(target)
    require(not target.is_symlink(),'export-symlink')
    require((target/'manifest.json').is_file(),'export-incomplete')
    require(not any(p.is_symlink() for p in target.rglob('*')),'export-symlink')
    # This privileged archive is larger than an individual bounded wire intent.
    manifest=json.loads((target/'manifest.json').read_text(encoding='utf-8'),object_pairs_hook=_unique_pairs)
    require(set(manifest)=={'format','dimensionId','executorEpoch','controlSequence','eventSequence','exportedAt','files','assurance'},'manifest-shape')
    require(manifest['format']=='enterprise-action-export/0.1.0','manifest-version')
    expected=set(manifest['files'])|{'manifest.json'}
    actual={p.relative_to(target).as_posix() for p in target.rglob('*') if p.is_file()}
    require(expected==actual,'export-file-closure')
    for name,expected_hash in manifest['files'].items():
        require(name in actual and '..' not in Path(name).parts and not Path(name).is_absolute(),'export-path')
        require(sha((target/name).read_bytes())==expected_hash,'export-file-digest')
    snapshot=json.loads((target/'snapshot.json').read_text(encoding='utf-8'),object_pairs_hook=_unique_pairs)
    result=validate_snapshot(snapshot); recs=records(snapshot)
    require(set(manifest['files'])=={'snapshot.json'}|{'records/'+rid+'.json' for rid in recs},'native-closure')
    for rid,record in recs.items(): require((target/'records'/f'{rid}.json').read_bytes()==file_bytes(record),'native-projection')
    m=snapshot['meta']
    require(manifest['dimensionId']==m['dimension'] and manifest['executorEpoch']==m['epoch'] and manifest['controlSequence']==m['control_sequence'] and manifest['eventSequence']==len(snapshot['events']) and manifest['exportedAt']==stamp(m['clock']),'export-cut')
    require(manifest['assurance']=='synthetic-evidence-not-authenticated-current-state','export-assurance')
    return {**result,'files':len(actual),'controlSequence':m['control_sequence'],'exportedAt':manifest['exportedAt']}

def _unique_pairs(items):
    result={}
    for key,value in items:
        require(key not in result,'duplicate-key'); result[key]=value
    return result

if __name__ == '__main__':
    import argparse
    ap=argparse.ArgumentParser(description='Validate a complete synthetic action export; not authenticated admission or execution.')
    ap.add_argument('export_directory')
    args=ap.parse_args()
    print(json.dumps(verify_export(args.export_directory),indent=2))
