"""Immutable native5: independently validated Excel1904 YEARFRAC compatibility."""
from pathlib import Path
import argparse,json,gzip,hashlib,shutil,datetime
p=argparse.ArgumentParser();p.add_argument('--stage',type=Path,required=True);p.add_argument('--wasm',type=Path,required=True);a=p.parse_args();root=Path.cwd();out=root/'third_party/office/26.2-fc03117-office5';assert not out.exists(),'Runtime/source versions are immutable';reg=root/'benchmarks/research/office-legacy/2026-10-25T02-52-35-334Z-0a408ef3';new=root/'benchmarks/research/office-legacy/2026-10-25T02-53-43-616Z-ffd44d83';odf=root/'benchmarks/research/office-legacy/2026-10-25T02-54-39-441Z-e24e6d1f';r=json.loads((reg/'yearfrac2-excel-validation.json').read_text());assert r['sourceCells']==2666 and r['observations']==10664 and r['failures']==0;n=json.loads((new/'new-probe-validation.json').read_text());assert n['sourceCells']==760 and n['checks']==3040 and n['failures']==0
for folder,total,unchanged in [(reg,36,32),(odf,20,20)]:
 v=json.loads((folder/'native4-regression.json').read_text());assert v['outputs']==total and v['unchangedOutputs']==unchanged and not v['failures']
info=lambda b:dict(bytes=len(b),sha256=hashlib.sha256(b).hexdigest());code=(a.stage/'office-combined.js').read_bytes();wasm=a.wasm.read_bytes();capture=json.loads((reg/'capture.json').read_text());assert info(wasm)=={k:capture['runtimeFiles']['soffice.wasm'][k]for k in ['bytes','sha256']};assert info(code)=={k:capture['runtimeFiles']['generalAdapter'][k]for k in ['bytes','sha256']};build=json.loads((a.stage/'cli-guarded-build.json').read_text());assert info(code)==dict(bytes=build['outputBytes'],sha256=build['outputSha256'])
base=root/'third_party/office/26.2-fc03117-office4';shutil.copytree(base/'sources',out/'sources');(out/'runtime').mkdir();runtime={}
for name,b in [('office-combined.js',code),('soffice.wasm',wasm)]:runtime[name]=info(b);(out/'runtime'/f'{name}.gz').write_bytes(gzip.compress(b,compresslevel=9,mtime=0))
patch=root/'benchmarks/research/office-yearfrac2/yearfrac-1904-double-epoch.patch';shutil.copy2(patch,out/'sources/build'/patch.name)
for name in ['soffice-csp.js','office-preflight-sax.js','sax-preflight-build.json','cli-guarded-build.json']:shutil.copy2(a.stage/name,out/'sources'/name)
for name in ['scripts/package-office5.py','scripts/stage-office-native-candidate.mjs','scripts/patch-yearfrac-1904-offset.py','scripts/compare-yearfrac2-regressions.py','scripts/validate-yearfrac2.py','scripts/validate-yearfrac2-probes.py']:
 t=out/'sources/tree'/name;t.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(root/name,t)
shutil.copy2(base/'MPL-2.0.txt',out/'MPL-2.0.txt')
(out/'NOTICE.txt').write_text('''Tabmorph Office5 native PDF engine and matching worker.
Modified LibreOffice26.2 MPL subset at fc03117d3f8f2d7137d973e5db3b2514e8eba990;
not an official LibreOffice distribution. Full original licenses/notices and59
complete source archives: ../26.2-fc03117-office1/SOURCE.html. All native3 and4
patches are retained in sources/build and the earlier immutable offers.
New source patch changes only YEARFRAC on trusted XLS/XLSX1904 inputs to match
separately observed Excel16.88 displayed values. It applies the1462-day epoch
displacement once more for date interpretation, preserving raw elapsed days,
source-system range checks, ODS,1900 inputs and all other functions. This is an
observed compatibility rule, not a claim about Microsoft's implementation or
other Excel versions. Original inputs/formulas/date metadata are unchanged.
The paired generated glue and all accepted worker policy bytes equal native4;
this was checked against this new build's actual generated JS. Matching ABI
alone never permits substituting glue. All network/macro/update/clipboard/
preflight/disposal/CSP/desktop-memory/input-size/deadline policies are unchanged.
Unchanged47OFL/Apache fonts/data: ../26.2-fc03117-fonts3/SOURCE.html.
Independent Poppler/pypdf reads in Chromium/WebKit match3426original source-cell
displays:2666retained plus760new controls; expected errors are included, not
counts of successful calculations.126retained differences repaired.32unrelated
regression outputs and20ODF/RTF outputs preserve full decoded streams; four
financial outputs legitimately change. Saved same-input CloudConvert outputs
match672retained cells too; new/large suites remain competitively UNVERIFIED.
No new provider requests, uploads, dependencies, GPL/AGPL, ads or payments.
Known raw-reader, RGB, finite-unit PPT, mobile and advanced Office limits remain.
Compatible modified runtime files may replace this build for use/debugging.
''')
(out/'sources/BUILD.txt').write_text('''Rebuild native5 and its exact matching worker
Use office1's59complete archives, pinned Emscripten4.0.10/native tools and base
MPL_SUBSET=TRUE/DISABLE_GUI=TRUE/DYNAMIC_EXECUTION=0 make-j4 recipe. Apply the
base build/thread/CLI patches, native3 excel1900-calendar/office-addin-bridge/
calendar-finance patches, native4 precise-ppt-page-size.patch, then the new
build/yearfrac-1904-double-epoch.patch to scaddins/source/analysis/analysis.cxx.
Keep all80staticUNO signatures, scripts and current native4 policy. Paired
soffice-csp.js comes from the new build's generatedsoffice.js; verify its CSP
invoker and retain the exact clipboard denial. This build's generated glue
happens to equal native4 byte for byte after the accepted substitutions; that
does not authorize assuming equality on later builds. Use the owned frozen
sources/tree paths, unchanged bounded SAX preflight,39PDF defaults and
stage-office-native-candidate.mjs. Only the existing metadata fetch becomes the
preloaded metadata Promise. Matching manifests and source bytes are included.
Use unchanged fonts3 data/metadata. Gzip9/mtime0 reproduces delivery files.
Current application sources are a separate immutable offer. Prior BUILD.txt
and native3/native4 owned snapshots remain historical build provenance, not
claims that those historical runtime binaries include this new patch.
''')
(out/'runtime-integrity.json').write_text(json.dumps(runtime,indent=2)+'\n')
(out/'SOURCE.html').write_text('<!doctype html><meta charset="utf-8"><title>Office5 native and worker sources</title><h1>Office5 native and worker sources</h1><p><a href="NOTICE.txt">Notices and limitations</a> · <a href="sources/BUILD.txt">Rebuild</a> · <a href="../26.2-fc03117-office1/SOURCE.html">Complete59source archives and base licenses</a> · <a href="../26.2-fc03117-office4/SOURCE.html">Prior native4 sources</a> · <a href="../26.2-fc03117-fonts3/SOURCE.html">Unchanged fonts/data</a></p><ul>'+''.join('<li><a href="'+str(f.relative_to(out))+'">'+str(f.relative_to(out))+'</a></li>'for f in sorted((out/'sources').rglob('*'))if f.is_file())+'</ul>')
manifest=dict(version=out.name,baseSourceVersion='26.2-fc03117-office1',fontDataVersion='26.2-fc03117-fonts3',sourceCommit='fc03117d3f8f2d7137d973e5db3b2514e8eba990',runtime=runtime,files={str(f.relative_to(out)):info(f.read_bytes())for f in sorted(out.rglob('*'))if f.is_file()});(out/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n');print(json.dumps(dict(version=out.name,runtime=runtime,files=len(manifest['files']))))
