# decryption_complete: false # source: /Voynich/run_external_anchor_attack_018.py # stated_sha256: 757b3a0a3e661f44637fac1167306970aba258dc9b402545dfda8f5ae3675450 # matches_stated_sha256: false # pdf_pages: 146-150 # note: The stated SHA-256 is the digest printed in the PDF. # The PDF page extract follows the form feed. decryption_complete stays false. run_external_anchor_attack_018.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 1 run_external_anchor_attack_018.py Source: /Voynich/run_external_anchor_attack_018.py SHA-256: 757b3a0a3e661f44637fac1167306970aba258dc9b402545dfda8f5ae3675450 !/usr/bin/env python3 """EXTERNAL-ANCHOR-ATTACK-018: blinded label/prose ranking then referent reveal. Frozen before reveal: - Universe: the previously fixed 77 productive stems. - Primary witnesses: ZL3b and GC2a/v101, independently. - Candidate gate per witness: >=2 exact label tokens, >=2 label folios, >=10 prose tokens, positive register-enrichment z, and familywise p < .05. - Cross-witness gate: both witnesses pass and label-folio Jaccard >= .50. - Reveal gate for 1:1 promotion: the same independently supplied, specific referent on >=2 distinct label folios. Broad section/domain is insufficient. - 1,000 nulls shuffle label/prose status within folio and witness; the maximum z over all 77 stems supplies the selection-aware familywise p-value. """ from __future__ import annotations import csv, hashlib, json, math, re from collections import Counter, defaultdict from pathlib import Path import fitz import numpy as np from PIL import Image, ImageDraw, ImageFont ROOT=Path('crosswalk002_inputs/Voynich_Line_Local_Reproducibility_2026-08-22/data') LEX=Path('proto_stem_lexicon_003/proto_stem_lexicon.csv') META=Path('external_voynich_units/data/voynich-units/ZL3b.txt') PDF=Path('library_scan/Voynich_Manuscript.pdf') OUT=Path('external_anchor_attack_018'); OUT.mkdir(exist_ok=True) SEED=20260829; REPS=1000 MISSING={12,*range(59,65),74,91,92,97,98,109,110} TOK_RE=re.compile(r'[A-Z][0-9a-z]') LOC_RE=re.compile(r'^<([^>.]+)\.([^,>]+),([^>]*)>\s*(.*)$') L={'A2':'ENTRY','C2':'ENTRY','Q2':'ENTRY','A1':'REFERENCE','A3':'REFERENCE','B2':'DOMAIN_SELECTOR','U2': 'DOMAIN_SELECTOR','D1':'CONTEXT','K1':'CONTEXT','L1':'CONTEXT','Q1':'CONTEXT'} R={'B1':'CLOSURE','B3':'CLOSURE','A1':'HANDOFF','C1':'HANDOFF','C2':'HANDOFF','F1':'HANDOFF','F3':'HANDO FF','A2':'TERMINAL','B2':'TERMINAL'} def section(f): n=int(re.search(r'\d+',f).group()) return 'Herbal' if n<=66 else 'Astro' if n<=73 else 'Bio' if 75<=n<=84 else 'Pharma' if 87<=n<=102 else 'Recipes' if 103<=n<=116 else 'Other' def clean_tokens(text): clean=re.sub(r'<[^>]*>','',text).replace('[','').replace(']','').replace(':','') out=[] for i,w in enumerate(re.split(r'[.,\s]+',clean)): a=TOK_RE.findall(w) if len(a)>=3: out.append((i,a,' '.join(a[1:-1]))) return out def parse_sta(path,witness,stems): rows=[]; pending=None for raw in path.read_text(errors='ignore').splitlines(): m=LOC_RE.match(raw) if m: fol,line,tag,text=m.groups(); pending=[fol,line,tag,text] if text.strip(): rows.append(tuple(pending)); pending=None elif pending and raw and not raw.startswith(('<','#')): pending[3]=(pending[3]+' '+raw).strip(); rows.append(tuple(pending)); pending=None events=[] for fol,line,tag,text in rows: run_external_anchor_attack_018.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 2 if not re.match(r'^f\d+[rv]\d?$',fol): continue reg='LABEL' if 'L' in tag else 'PROSE' if 'P' in tag else 'OTHER' if reg not in {'LABEL','PROSE'}: continue for idx,a,payload in clean_tokens(text): if payload not in stems: continue events.append({'witness':witness,'folio':fol,'line':line,'tag':tag,'register':reg, 'token_index':idx,'surface_atoms':' '.join(a),'payload':payload, 'left_atom':a[0],'right_atom':a[-1], 'left_function':L.get(a[0],'UNRESOLVED'),'right_function':R.get(a[-1],'UNRESO LVED'), 'section':section(fol)}) return events def stats(events,stems): out={} for s in stems: q=[e for e in events if e['payload']==s]; lab=[e for e in q if e['register']=='LABEL']; pro=[e for e in q if e['register']=='PROSE'] out[s]={'label_n':len(lab),'prose_n':len(pro),'label_folios':len({e['folio'] for e in lab}), 'prose_folios':len({e['folio'] for e in pro}),'label_folio_set':sorted({e['folio'] for e in lab}), 'label_sections':'|'.join(f'{a}:{b}' for a,b in Counter(e['section'] for e in lab).most_common()), 'label_surfaces':'|'.join(f'{a}:{b}' for a,b in Counter(e['surface_atoms'] for e in lab).most_common())} return out def null_enrichment(events,stems,observed): # Shuffle register assignments among retained stem events within each folio. byfolio=defaultdict(list) for i,e in enumerate(events): byfolio[e['folio']].append(i) stem_index={s:i for i,s in enumerate(stems)}; n=len(stems) null=np.zeros((REPS,n),dtype=np.int32); rng=np.random.default_rng(SEED+(events[0]['witness']=='GC')* 10000) regs=np.array([e['register']=='LABEL' for e in events],dtype=np.int8) for rep in range(REPS): x=regs.copy() for ids in byfolio.values(): vals=x[ids].copy(); rng.shuffle(vals); x[ids]=vals for i,e in enumerate(events): if x[i]: null[rep,stem_index[e['payload']]]+=1 mu=null.mean(0); sd=null.std(0,ddof=1); obs=np.array([observed[s]['label_n'] for s in stems]) z=(obs-mu)/np.where(sd>0,sd,np.inf) nz=(null-mu)/np.where(sd>0,sd,np.inf); maxz=nz.max(1) results={} for i,s in enumerate(stems): results[s]={'null_mean':float(mu[i]),'null_sd':float(sd[i]),'z':float(z[i]), 'familywise_p':float((1+(maxz>=z[i]).sum())/(REPS+1))} return results,maxz def parse_metadata(path): meta=defaultdict(lambda:{'plant_id':'','same_plant_as':'','comments':[]}) current=None for raw in path.read_text(errors='replace').splitlines(): m=re.match(r'^<(f\d+[rv]\d?)>\s',raw) if m: current=m.group(1); continue if current and raw.startswith('#'): t=raw[1:].strip(); meta[current]['comments'].append(t) if t.lower().startswith('plant id:'): meta[current]['plant_id']=t.split(':',1)[1].strip() if t.lower().startswith('same plant as'): meta[current]['same_plant_as']=(t.split(':',1)[1] if ':' in t else t[len('same plant as'):]).strip(' :') return meta def clear_specific_plant(s): if not s:return '' run_external_anchor_attack_018.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 3 low=s.lower() if any(x in low for x in ('?',' or ','unknown','unidentified')):return '' # Commas and equals often encode competing identifications/synonyms. Preserve # them in the reveal table but do not treat them as a unique ground truth. if ',' in s or '=' in s:return '' return re.sub(r'\s+',' ',s.strip().lower()) def page_map(): sides=[] for n in range(1,117): if n not in MISSING:sides += [f'f{n}r',f'f{n}v'] return {f:i+2 for i,f in enumerate(sides)} def basefolio(f): return re.sub(r'([rv])\d+$',r'\1',f) def render_contact(folios,labels): if not folios:return None doc=fitz.open(PDF); pm=page_map(); tiles=[] font=ImageFont.load_default() for fol in folios[:24]: base=basefolio(fol) if base not in pm:continue pix=doc[pm[base]].get_pixmap(matrix=fitz.Matrix(1.0,1.0),alpha=False) im=Image.frombytes('RGB',(pix.width,pix.height),pix.samples); im.thumbnail((360,470)) tile=Image.new('RGB',(380,520),'white'); tile.paste(im,((380-im.width)//2,32)); d=ImageDraw.Draw(tile) d.text((8,8),f'{fol} {labels.get(fol,"")}',fill='black',font=font) tiles.append(tile) if not tiles:return None cols=3; rows=math.ceil(len(tiles)/cols); sheet=Image.new('RGB',(cols*380,rows*520),(230,233,236)) for i,t in enumerate(tiles):sheet.paste(t,((i%cols)*380,(i//cols)*520)) out=OUT/'frozen_candidate_folio_reveal.jpg';sheet.save(out,quality=88);return out def main(): lex=list(csv.DictReader(LEX.open())); stems=[r['payload'] for r in lex]; stem_id={r['payload']:r['stem_id'] for r in lex} events=[] for wit in ('ZL','GC'):events += parse_sta(ROOT/(wit+'.txt'),wit,set(stems)) with (OUT/'label_prose_events.csv').open('w',newline='') as f: w=csv.DictWriter(f,fieldnames=events[0]);w.writeheader();w.writerows(events) witness_stats={}; nullrows=[] for wit in ('ZL','GC'): ev=[e for e in events if e['witness']==wit]; ob=stats(ev,stems); nr,maxz=null_enrichment(ev,stems,ob); witness_stats[wit]=(ob,nr) for s in stems: nullrows.append({'witness':wit,'stem_id':stem_id[s],'payload':s,**{k:v for k,v in ob[s].items() if k!='label_folio_set'},**nr[s]}) with (OUT/'register_enrichment_ledger.csv').open('w',newline='') as f: w=csv.DictWriter(f,fieldnames=nullrows[0]);w.writeheader();w.writerows(nullrows) # Freeze candidate ranking before reading metadata/illustrations. frozen=[] for s in stems: z,zn=witness_stats['ZL'];g,gn=witness_stats['GC']; zs=set(z[s]['label_folio_set']);gs=set(g[s][' label_folio_set']);union=zs|gs jac=len(zs&gs)/len(union) if union else 0 gate=all([z[s]['label_n']>=2,g[s]['label_n']>=2,z[s]['label_folios']>=2,g[s]['label_folios']>=2, z[s]['prose_n']>=10,g[s]['prose_n']>=10,zn[s]['z']>0,gn[s]['z']>0, zn[s]['familywise_p']<.05,gn[s]['familywise_p']<.05,jac>=.5]) score=min(zn[s]['z'],gn[s]['z'])+math.log2(1+min(z[s]['label_n'],g[s]['label_n']))+jac frozen.append({'stem_id':stem_id[s],'payload':s,'frozen_score':score,'strict_candidate_gate':int (gate), 'zl_label_n':z[s]['label_n'],'gc_label_n':g[s]['label_n'],'zl_prose_n':z[s]['pros e_n'],'gc_prose_n':g[s]['prose_n'], 'zl_label_folios':z[s]['label_folios'],'gc_label_folios':g[s]['label_folios'],'la bel_folio_jaccard':jac, run_external_anchor_attack_018.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 4 'zl_z':zn[s]['z'],'gc_z':gn[s]['z'],'zl_familywise_p':zn[s]['familywise_p'],'gc_f amilywise_p':gn[s]['familywise_p'], 'frozen_label_folios':'|'.join(sorted(union))}) frozen.sort(key=lambda r:(-r['strict_candidate_gate'],-r['frozen_score'],r['stem_id'])) with (OUT/'frozen_candidate_ranking.csv').open('w',newline='') as f: w=csv.DictWriter(f,fieldnames=frozen[0]);w.writeheader();w.writerows(frozen) # Reveal stage begins only here. metadata=parse_metadata(META); reveal=[] for r in frozen: if not r['strict_candidate_gate'] and len(reveal)>=12:continue folios=r['frozen_label_folios'].split('|') if r['frozen_label_folios'] else [] specific=[clear_specific_plant(metadata[f]['plant_id']) for f in folios]; specific=[x for x in specific if x] counts=Counter(specific); best,bn=counts.most_common(1)[0] if counts else ('',0) one_to_one=int(bool(best) and bn>=2 and bn==len(folios)) reveal.append({**r,'revealed_folio_metadata':' || '.join(f'{f}:PlantID={metadata[f]["plant_id"]} ;SameAs={metadata[f]["same_plant_as"]};Section={section(f)}' for f in folios), 'specific_referent':best,'specific_referent_support_folios':bn,'one_to_one_pass': one_to_one, 'decision':'PROMOTE_1_TO_1' if one_to_one else 'RETAIN_ANONYMOUS'}) with (OUT/'referent_reveal_ledger.csv').open('w',newline='') as f: w=csv.DictWriter(f,fieldnames=reveal[0]);w.writeheader();w.writerows(reveal) labels={} for r in reveal: for fol in r['frozen_label_folios'].split('|') if r['frozen_label_folios'] else []: labels[fol]=labels.get(fol,'')+r['stem_id']+' ' contact=render_contact(sorted(labels),labels) strict=sum(r['strict_candidate_gate'] for r in frozen); promoted=sum(r['one_to_one_pass'] for r in reveal) summary={'test':'EXTERNAL-ANCHOR-ATTACK-018','date':'2026-08-29','seed':SEED,'null_replicates':REPS, 'stem_universe':len(stems), 'events':len(events),'label_events':sum(e['register']=='LABEL' for e in events),'prose_events':sum(e['register']=='PROSE' for e in events), 'strict_blind_candidates':strict,'revealed_ranked_candidates':len(reveal),'one_to_one_promo tions':promoted, 'literal_known_language_words_added':0,'contact_sheet':str(contact) if contact else None, 'decision':'NO_UNIQUE_EXTERNAL_ANCHOR' if promoted==0 else 'UNIQUE_ANCHOR_FOUND', 'boundary':'Broad domain or a plausible illustration is not a unique referent. Only repeated independent specific identity can promote.'} (OUT/'summary.json').write_text(json.dumps(summary,indent=2)) strict_rows=[r for r in frozen if r['strict_candidate_gate']] strict_text='\n'.join(f"- `{r['stem_id']}` / `{r['payload']}`: ZL z={r['zl_z']:.3f}, p={r['zl_familywise_p']:.6f}; GC z={r['gc_z']:.3f}, p={r['gc_familywise_p']:.6f}; label folios `{r['frozen_label_folios']}`." for r in strict_rows) or '- None.' report=f'''# Voynich EXTERNAL-ANCHOR-ATTACK-018\n\nDate: 2026-08-29\n\n## Frozen test\n\nThe fixed 77-stem proto-lexicon was ranked using label/prose recurrence only. ZL and GC were tested independently with 1,000 within-folio register permutations. Illustrations and page-identification comments were unavailable until the candidate ranking was written.\n\nA strict candidate required at least two label tokens on two folios in each witness, at least ten prose tokens in each witness, positive enrichment, familywise p < 0.05 in both witnesses, and label-folio Jaccard >= 0.50. A 1:1 promotion additionally required the same specific externally supplied referent on at least two independent label folios.\n\n## Result\n\n- Stem universe: {len(stems)}\n- Eligible label/prose events: {len(events)}\n- Label events: {summary['label_events']}\n- Prose events: {summary['prose_events']}\n- Strict blinded candidates: {strict}\n- Ranked candidates revealed: {len(reveal)}\n- Unique 1:1 promotions: {promoted}\n- Literal known-language words added: 0\n\n## Strict blinded candidates\n\n{strict_text}\n\nBoth candidates cross incompatible illustrated subjects and manuscript sections. `A3 C1` spans Herbal, Astro, Bio, and Pharma label folios. `Q1 A3 B2` spans Herbal, Astro, and Bio. Coordinate-level reveals that could be aligned include zodiac/astronomical labels and a biological-container label, not repeated instances of one object. This supports a label/register-function interpretation, not a unique noun. That interpretation remains anonymous.\n\n## Decision\n\n{summary['decision']}. The reveal localizes two payloads toward label-register behavior, but no payload is assigned a unique word or object. A broad domain, repeated label role, or visually plausible object is insufficient under the frozen gate.\n\n## Rule recovery audit\n\nThe six-rule ledger remains unchanged. The cross-domain label enrichment strengthens REGISTER run_external_anchor_attack_018.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 5 SHIFT and suggests that part of the nominal payload inventory still contains register realization rather than referential content. No seventh rule is added. DOMAIN SPECIALIZATION is not a substitute for repeated specific-referent grounding.\n''' (OUT/'Voynich_EXTERNAL_ANCHOR_ATTACK_018_REPORT_2026-08-29.md').write_text(report) rule=[{'rule':'LINE RESET','effect':'unchanged'},{'rule':'CORE PRESERVATION','effect':'unchanged'},{'rule':'EDGE HANDOFF','effect':'unchanged'},{'rule':'CONTEXTUAL INTERNAL REALIZATION','effect':'unchanged'},{'rule':'REGISTER SHIFT','effect':'strengthened: two cross-domain payloads are independently label-enriched'},{'rule':'DOMAIN SPECIALIZATION','effect':'unchanged; no semantic promotion without repeated referent'}] with (OUT/'Voynich_EXTERNAL_ANCHOR_ATTACK_018_RULE_AUDIT.csv').open('w',newline='') as f:w=csv.DictWriter(f,fieldnames=rule[0]);w.writeheader();w.writerows(rule) paths=[Path(__file__),OUT/'summary.json',OUT/'label_prose_events.csv',OUT/'register_enrichment_ledge r.csv',OUT/'frozen_candidate_ranking.csv',OUT/'referent_reveal_ledger.csv',OUT/'Voynich_EXTERNAL_ANCHOR_ ATTACK_018_REPORT_2026-08-29.md',OUT/'Voynich_EXTERNAL_ANCHOR_ATTACK_018_RULE_AUDIT.csv'] helper=Path('render_external_anchor_label_crops_018.py');coord=OUT/'strict_candidate_label_coordinat e_reveal.jpg' if helper.exists():paths.append(helper) if coord.exists():paths.append(coord) if contact:paths.append(contact) with (OUT/'Voynich_EXTERNAL_ANCHOR_ATTACK_018_SHA256_2026-08-29.txt').open('w') as f: for p in paths:f.write(hashlib.sha256(p.read_bytes()).hexdigest()+' '+p.name+'\n') print(json.dumps(summary,indent=2));print('\nTOP FROZEN') for r in frozen[:15]:print(r['stem_id'],r['payload'],'gate',r['strict_candidate_gate'],'score',round (r['frozen_score'],3),'labels',r['zl_label_n'],r['gc_label_n'],'p',round(r['zl_familywise_p'],4),round(r ['gc_familywise_p'],4)) if __name__=='__main__':main()