Add frozen TikZRefinery demo baseline and build pipeline
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good

This commit is contained in:
2026-11-25 22:46:33 -05:00
parent 6064cce05e
commit 27b82c169e
456 changed files with 66509 additions and 0 deletions
@@ -0,0 +1,121 @@
"""Diagram audit: authored-source checks, PDF navigation, raster review only."""
from pathlib import Path
import re, json, hashlib, argparse
from collections import Counter
from pypdf import PdfReader
import pypdfium2 as pdfium
from PIL import Image, ImageDraw
ROOT=next(p for p in Path(__file__).resolve().parents if (p/'AGENTS.md').is_file())
EVIDENCE=Path(__file__).resolve().parent
TASK=ROOT/'work/diagram-audit-2026-11-24'
BUILD=TASK/'report'
RENDER=TASK/'review'
def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
def groups(text,start):
values=[]
while start<len(text) and text[start]=='{':
depth=1; end=start+1
while depth:
if text[end]=='{' and text[end-1]!='\\':depth+=1
if text[end]=='}' and text[end-1]!='\\':depth-=1
end+=1
values.append(text[start+1:end-1]);start=end
return values
def checks(strict):
protected=json.loads((EVIDENCE/'protected-hashes.json').read_text(encoding='utf-8-sig'))
for item in protected:
p=Path(item['Path']); assert p.is_file() and sha(p).upper()==item['Hash'],str(p)
text='\n'.join(p.read_text(encoding='utf-8-sig') for p in (ROOT/'documents/latex').glob('*.tex'))
counts={}
for macro,total in [('RequirementID',111),('TestCaseID',82),('VerificationID',111),('UseCaseID',9),('UserStoryID',11),('ValidationID',11),('AIRequirementID',17),('ReportRequirementID',58)]:
ids=re.findall(r'\\'+macro+r'\{([^}]+)\}',text)
assert len(ids)==len(set(ids))==total,(macro,len(ids))
counts[macro]=total
# Product obligations and reciprocal mappings are untouched in this audit.
index=json.loads((ROOT/'documents/diagram-index.json').read_text())
assert index['version']=='0.1.4-alpha' and len(index['figures'])==51
result=dict(version=index['version'],protectedFilesUnchanged=len(protected),registerCounts=counts,applicationTestsRun=False,pdfs={})
for key,stem in [('submission','TikZRefinerySubmission'),('developer','TikZRefinery')]:
folder=BUILD/stem; reader=PdfReader(folder/(stem+'.pdf'));dest=reader.named_destinations
aux='\n'.join(p.read_text(errors='replace') for p in folder.glob('*.aux'))
links=0
for page in reader.pages:
for ref in page.get('/Annots',[]):
ann=ref.get_object();target=ann.get('/Dest');action=ann.get('/A')
if action and action.get('/S')=='/GoTo':target=action.get('/D')
if target is None:continue
links+=1
if isinstance(target,str):assert target in dest,target
for row in index['figures']:
label=row['label']; match=re.search(r'\\newlabel\{'+re.escape(label)+r'\}\{',aux)
assert match,label
fields=groups(aux,match.end())
assert len(fields)>=4,(label,fields)
anchor=fields[3]; physical=reader.get_destination_page_number(dest[anchor])+1
assert physical==row[key]['physical'],(label,physical,row[key])
assert reader.page_labels[physical-1]==row[key]['printed']
log=(folder/(stem+'.log')).read_text(errors='replace')
problems=re.findall(r'^.*(?:Overfull|Float too large|undefined references|undefined citations|Citation .+ undefined|Reference .+ undefined|destination with the same identifier|LaTeX Error).*$' ,log,re.M)
if strict:assert not problems,problems
result['pdfs'][key]=dict(pages=len(reader.pages),internalLinks=links,namedDestinations=len(dest),figuresChecked=len(index['figures']),diagnostics=problems,underfullNotices=log.count('Underfull'),sha256=sha(folder/(stem+'.pdf')))
(EVIDENCE/'checks.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
def render():
RENDER.mkdir(parents=True,exist_ok=True)
index=json.loads((ROOT/'documents/diagram-index.json').read_text())
selection={}; previous={}
for key,stem in [('submission','TikZRefinerySubmission'),('developer','TikZRefinery')]:
folder=BUILD/stem; reader=PdfReader(folder/(stem+'.pdf'));doc=pdfium.PdfDocument(str(folder/(stem+'.pdf')))
aux='\n'.join(p.read_text(errors='replace') for p in folder.glob('*.aux'))
locations={m[1]:m[3] for m in re.finditer(r'\\newlabel\{([^}]+)\}\{\{([^}]*)\}\{([^}]*)\}',aux)}
pages={row[key]['physical'] for row in index['figures']}
# Navigation/front matter and changed history/roadmap/guide/log text.
pages.update(i+1 for i,label in enumerate(reader.page_labels) if not label.isdigit())
for label in ['Table:DocumentHistory','ReportRequirement:RPT-050','Section:M3Coverage','Section:UMLAuthoring','Section:AIGuideDocumentBuild','Section:AIGuideChecklist','Section:DiagramAuditLog']:
if label in locations:
start=reader.page_labels.index(locations[label])+1
pages.update(range(max(1,start-1),min(len(reader.pages),start+3)+1))
if key=='developer':
# New final prompt record occurs at the end of the prompt-log chapter.
begin=reader.page_labels.index(locations['Chapter:AIPromptLog'])+1
# Bibliography bookmark bounds the chapter without PDF text lookup.
end=reader.get_destination_page_number(reader.named_destinations['chapter*.3'])+1 if 'chapter*.3' in reader.named_destinations else len(reader.pages)-12
pages.update(range(max(begin,end-5),min(end,len(reader.pages))+1))
tiles=[]; duplicates=[]
for physical in sorted(pages):
im=doc[physical-1].render(scale=1.5).to_pil().convert('RGB')
digest=hashlib.sha256(im.tobytes()).hexdigest()
if digest in previous:
duplicates.append(dict(physical=physical,same_as=previous[digest]));continue
previous[digest]=f'{key}-{physical}'
im.save(RENDER/f'{key}-{physical}.png')
thumb=im.copy();thumb.thumbnail((540,700))
tile=Image.new('RGB',(560,730),'#ddd');tile.paste(thumb,((560-thumb.width)//2,25))
ImageDraw.Draw(tile).text((8,7),f'{key}: PDF {physical} / printed {reader.page_labels[physical-1]}',fill='black')
tiles.append(tile)
for start in range(0,len(tiles),6):
sheet=Image.new('RGB',(1120,2190),'white')
for n,tile in enumerate(tiles[start:start+6]):sheet.paste(tile,((n%2)*560,(n//2)*730))
sheet.save(RENDER/f'{key}-sheet-{start//6+1:02}.jpg',quality=87)
# Entire-document layout overview, at thumbnail scale; targeted figures
# above retain readable resolution for detailed review.
for start in range(0,len(reader.pages),24):
sheet=Image.new('RGB',(1600,3180),'white')
for n,i in enumerate(range(start,min(len(reader.pages),start+24))):
im=doc[i].render(scale=0.45).to_pil().convert('RGB');im.thumbnail((385,490))
x=(n%4)*400;y=(n//4)*530
sheet.paste(im,(x+(400-im.width)//2,y+22))
ImageDraw.Draw(sheet).text((x+8,y+4),f'{key} PDF {i+1}',fill='black')
sheet.save(RENDER/f'{key}-overview-{start//24+1:02}.jpg',quality=85)
selection[key]=dict(selectedPages=sorted(pages),pixelIdenticalPages=duplicates,sheets=(len(tiles)+5)//6,overviewSheets=(len(reader.pages)+23)//24)
(EVIDENCE/'render-selection.json').write_text(json.dumps(selection,indent=2)+'\n')
print(json.dumps({key:{k:v for k,v in info.items() if k not in ['selectedPages','pixelIdenticalPages']} for key,info in selection.items()},indent=2))
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--render',action='store_true');parser.add_argument('--strict',action='store_true');args=parser.parse_args()
checks(args.strict)
if args.render:render()