"""Assemble the movable offline room using the research folder beside 3D Lab."""
import base64,csv,hashlib,json,subprocess,re
from pathlib import Path
import numpy as np
A=Path(__file__).resolve().parent;case=A.parent;root=case.parents[1];R=root/'research'; E=case/'experience';E.mkdir(exist_ok=True)
def b64(p):return base64.b64encode(p.read_bytes()).decode('ascii')
def j(p):return json.loads(p.read_text())
def store(p,obj):p.write_text(json.dumps(obj,indent=2,ensure_ascii=False)+'\n')
def img(p):return 'data:image/'+('jpeg' if p.suffix=='.jpg' else 'png')+';base64,'+b64(p)
entries=[];ids={}
def entry(id,title,**fields):
 if id not in ids:
  e={'id':id,'title':title,**fields};ids[id]=e;entries.append(e)
 return id
def document(id,title,rel,short=None):
 p=R/rel
 if p.is_file():entry(id,title,text=p.read_text(),source=rel,short=short or title)
idx=j(R/'research_figures/index.json')
for n,f in enumerate(idx,1):
 ref=f['source'];p=R/ref;dataid='data-'+f['id']
 entry(f['id'],f"Figure {n}. {f['title']}",short='Fig. '+str(n),caption=f['caption'],source=ref,image=img(R/'research_figures'/(f['id']+'.png')),link=dataid)
 if p.suffix=='.npz':
  with np.load(p) as z:txt='\n\n'.join(k+'\n'+np.array2string(z[k],precision=8,threshold=1050,max_line_width=110) for k in z.files)
  entry(dataid,'Matrix archive · '+f['id'],source=ref,text=txt)
 elif p.suffix=='.csv':entry(dataid,'Data · '+p.stem,source=ref,rows=list(csv.reader(p.open())))
 else:entry(dataid,'Derivation · '+p.stem,source=ref,text=p.read_text())
document('proof-map','Proof dependency map','theorem_dependency_map.json','Derivation')
document('exact30','Exact 30-dimensional block certificate','numerical_results/exact_30d.json','Exact certificate');document('computed','Computation record','numerical_results/computation_verification.json','Computed results')
document('research-report','Verification findings','verification_report.md','Report')
document('study-sources','Sources and versions','sources.md','Sources')
document('statement','Exact theorem statement','sources/formalization/Statement.lean','Statement')
document('solution','Public proof wrappers','sources/formalization/Solution.lean','Solution')
document('deviations','Formal construction differences','sources/formalization/DEVIATIONS.md','Deviations')
document('kernel','Local build record','lean_verification/formal_verification_report.md','Build record')
document('axioms','Kernel output','lean_verification/proof_verification_log.txt','Kernel log')
document('ci','Published CI receipt','lean_verification/upstream_ci.json');document('plan','Research protocol','research_plan.md');document('background','Mathematical background','mathematical_background.md');document('audit','Quantifier audit','lean_verification/theorem_statement_audit.md')
document('replication','Executable finite experiments','calculations/replicate.py');document('code-audit','Executable source audit','calculations/audit_sources.py')
for p in sorted((R/'sources/formalization/Minimal').glob('*.lean')):document('lean-'+p.stem,'Lean · '+p.stem,str(p.relative_to(R)))
for p in sorted((R/'model_session').glob('*')):
 if p.suffix in ['.md','.py','.json','.txt']:document('session-'+p.stem,'Notebook · '+p.stem,str(p.relative_to(R)))
pages=A/'textures'/'paper-pages';pages.mkdir(exist_ok=True)
if not (pages/'page-5.jpg').exists():subprocess.run(['pdftoppm','-jpeg','-scale-to','1300',str(R/'sources/paper.pdf'),str(pages/'page')],check=True)
for i in range(1,6):entry(f'paper-{i}',f'Manuscript · page {i} of 5',source='Hexagon 2612.00240v1 · 2 December 2026',image=img(pages/f'page-{i}.jpg'),url='https://hexagonmath.org/2612.00240v1',short='Manuscript')
summary=j(R/'numerical_results/computation_verification.json')
reach=list(csv.DictReader((R/'numerical_results/reach_grid.csv').open()));reach=[[float(r['abs_v0']),float(r['max_real_pairing'])] for r in reach if r['abs_v0']==r['abs_w2']]
split=[[float(v) for v in r] for r in list(csv.reader((R/'numerical_results/split_sweep.csv').open()))[1:]]
status=R/'lean_verification/status.json'
data={'entries':entries,'summary':summary,'reach':reach,'split':split,'kernel':j(status)['summary'] if status.exists() else 'The local build is running.','probe':img(A/'textures/hall-light-probe.jpg'),'glb':b64(A/'room.glb')}
panel_source=R/'model_session/evidence_panel.html'
panel_code=''
if panel_source.exists():
 original=panel_source.read_text()
 # Scope the independent notebook panel to the reader, and correct two display formulas.
 reviewed=original.replace("(good / 2) + '·μ", "good + '·μ").replace('good fraction is exactly 1/2','guaranteed good fraction is at least 1/2')
 reviewed=reviewed.replace('base n = 0','base n = 1').replace('0.25 - Math.pow','0.125 - Math.pow').replace('ρ_N = μ(1/4 − 2^{−N−2})','ρ_N ≤ μ(1/8 − 2^{−N−2})').replace('ρ_N with <span','upper bound on ρ_N with <span').replace('ρ_N / (μ/4)','Budget upper bound / (μ/4)')
 reviewed=reviewed.replace('Kernel: not run here','Notebook-only scope · see the local build record').replace('<h1>A counterexample','<h1>A counterexample')
 style=re.search(r'<style>(.*?)</style>',reviewed,re.S).group(1).replace(':root',':host').replace('body{',':host{')
 content=re.search(r'<body>(.*?)<script>',reviewed,re.S).group(1)
 panel_code=re.search(r'<script>(.*?)</script>',reviewed,re.S).group(1)
 entry('notebook-panel','Interactive proof notebook',short='Proof notebook',caption='Fable 5.2 produced this panel during the research session. This reviewed view corrects the Fibers coefficient label and evaluates the Splitting upper bound at base level one. The Status tab records the model session scope. The verification rack holds the subsequent local kernel record.',source='model_session/evidence_panel.html · reviewed display',panel='<style>'+style+'</style>'+content)
body=(A/'interface.html').read_text().replace('__DATA__',json.dumps(data,ensure_ascii=False,separators=(',',':')).replace('<','\\u003c')).replace('__THREE__',(A/'three-gltf.min.js').read_text()).replace('__APP__',(A/'lab.js').read_text().replace('__PANELCODE__',panel_code))
(E/'index.scilab').write_text(body);(root/'Operator Assembly Hall.html').write_text(body)
store(A/'content-map.json',[{k:v for k,v in e.items() if k in ['title','id','source','link']} for e in entries]);store(A/'lab-state.json',{'labId':'invariant-subspace-laboratory','revision':hashlib.sha256(body.encode()).hexdigest(),'parentRevision':None,'entry':'experience/index.scilab','researchTitle':'Invariant Subspace Problem — Independent Proof Verification','sourceCommit':(R/'sources/formalization.commit').read_text().strip()})
print(len(entries),'evidence entries;',len(body.encode()),'bytes')
