0hmX/am3352
This code suite comprises TypeScript scripts that analyze, verify, and assemble complex DDR memory interface hardware, focusing on physical routing, via and pad placement, electrical clearance, and physical constraints, often involving precise geometric calculations and consistent provenance tracking.
- Version
- 1.0.5
- License
- unset
- Stars
- 0
scripts/plan-ddr-ram0-d1-codesign.ts
/** RAM0 coupled C1/E2/D1 relocation and existing-winding DQ2 local repair. */
import{readFileSync,writeFileSync,mkdirSync}from'node:fs'
import{resolve}from'node:path'
import{createHash}from'node:crypto'
import{supportCopperObstacles}from'./ddr-support-routing-context'
import{explicitFacingViaContinuation}from'./ddr-facing-via-continuation'
import{verifyDdrSystemCopper,auditDdrTraceJunctions}from'./check-ddr-system-copper'
import{auditRouteAngles}from'./check-route-angles'
import{auditCompositeHostTopology}from'./ddr-composite-routing-context'
import{sharedViaApproaches}from'./plan-ddr-ram-power-via-reuse'
const[dirArg,outArg]=process.argv.slice(2),dir=resolve(dirArg!),out=resolve(outArg!),hash=(v:any)=>createHash('sha256').update(JSON.stringify(v)).digest('hex'),bound:Record<string,string>={},read=(p:string)=>{p=resolve(p);bound[p]=createHash('sha256').update(readFileSync(p)).digest('hex');return JSON.parse(readFileSync(p,'utf8'))},parent=read(`${dir}/candidate.circuit.json`),host=read(`${dir}/host-bundle.json`),input=read(`${dir}/routing-input.json`),prior=read(`${dir}/report.json`),c1proof=read('dist/ddr-c1-outward-launch/report.json'),old=parent.find((e:any)=>e.type==='pcb_trace'&&e.pcb_trace_id==='saved_fanout_pcb_group_3_13'),exit=parent.find((e:any)=>e.type==='pcb_breakout_point'&&e.source_trace_id===old.source_trace_id),connection=input.connections.find((c:any)=>c.pointsToConnect.some((p:any)=>p.pointId===exit.pcb_breakout_point_id)),vi=old.route.findIndex((p:any)=>p.route_type==='via'),via=old.route[vi],suffix=old.route.slice(-2),target=suffix[0],source=old.route[0],ram=resolve('/Users/ankan/Documents/Codex/2026-09-10/what-x20/outputs/mt41k512m8da-107-it-p-fanout'),native=read(`${ram}/src/generated/bus_grouped.trace-paths.json`)
if(prior.candidateCircuitSha256!==hash(parent)||host.traces.length!==21||prior.launchQualified!==58||connection.ramTerminal!=='DQ2')throw Error('Expected checked20/57 RAM0 DQ2')
for(const f of['am3352-host.ts','am3352-power-escapes.ts','am3352-trunk-taps.ts'])bound[`${ram}/src/${f}`]=createHash('sha256').update(readFileSync(`${ram}/src/${f}`)).digest('hex')
const{adaptRamPathsToHost}=await import(`${ram}/src/am3352-host.ts`),paths=adaptRamPathsToHost(native,'am3352-byte0'),e2=parent.find((e:any)=>e.type==='pcb_trace'&&e.pcb_trace_id==='saved_fanout_pcb_group_3_15'),e2via=e2.route.find((p:any)=>p.route_type==='via'),e2after={...e2,route:paths.find((p:any)=>p.connection==='U1.ball_E2').route.map((p:any)=>({...p,x:-12-p.x,y:-6.5-p.y}))};e2after.route[0].start_pcb_port_id=e2.route[0].start_pcb_port_id
const newE2via=e2after.route.find((p:any)=>p.route_type==='via'),rendered=parent.find((e:any)=>e.type==='pcb_via'&&e.pcb_trace_id===e2.pcb_trace_id),c1=c1proof.changes.find((c:any)=>c.byte===0),actualC1=parent.find((e:any)=>e.type==='pcb_trace'&&e.pcb_trace_id===c1.before.pcb_trace_id);if(hash(actualC1)!==hash(c1.before))throw Error('Root C1 witness changed')
const d1=parent.find((e:any)=>e.type==='pcb_trace'&&e.pcb_trace_id==='saved_fanout_pcb_group_3_3'),d1after={...d1,route:[...sharedViaApproaches(d1.route[0],e2via)[0]!,{route_type:'via',x:e2via.x,y:e2via.y,from_layer:'top',to_layer:'inner1',via_diameter:.4572,via_hole_diameter:.254}],connectsTo:[d1.source_trace_id,d1.route[0].start_pcb_port_id]};delete d1after.connection_name
const changes=[{before:actualC1,after:c1.after},{before:e2,after:e2after},{before:rendered,after:{...rendered,x:newE2via.x,y:newE2via.y}},{before:d1,after:d1after}],base=parent.map((e:any)=>changes.find(c=>c.before===e)?.after??e),powerTraces=[c1.after,e2after,d1after],hostIds=new Set(host.traces.map((t:any)=>t.pcb_trace_id)),preflight=verifyDdrSystemCopper([...base.filter((e:any)=>e.type!=='pcb_copper_pour'&&!hostIds.has(e.pcb_trace_id)),...powerTraces],[...host.traces,...powerTraces],input.connections,{},50,{reportSameNetContacts:true}),nonDq2=preflight.violations.filter((v:any)=>v.aShape.traceId!==old.pcb_trace_id&&v.bShape.traceId!==old.pcb_trace_id)
mkdirSync(out,{recursive:true});const write=(n:string,v:any)=>writeFileSync(`${out}/${n}`,JSON.stringify(v,null,2));write('power-preflight.json',{captureHash:prior.captureHash,parentCircuitSha256:hash(parent),sourceHashes:bound,changes,preflight,nonDq2Violations:nonDq2,scope:'Three source-owned power launches; current E1 retained. Planes not yet repoured. Fresh bottom-layer E2 signal policy errors are explicit, not relaxed.'})
if(nonDq2.length){console.log(JSON.stringify({stage:'power-conductor-preflight',nonDq2Violations:nonDq2.length,violations:nonDq2.map((v:any)=>({a:v.aShape.traceId??v.aShape.join,b:v.bShape.traceId??v.bShape.join,layer:v.layer,gap:v.gapMm}))}));process.exit(0)}
const obstacles=base.filter((e:any)=>['pcb_trace','pcb_via','pcb_smtpad'].includes(e.type)).flatMap((e:any)=>{const isTrace=e===old,projected=isTrace?{...e,route:e.route.slice(0,vi+1)}:e,own=isTrace||(e.type==='pcb_via'&&e.pcb_trace_id===old.pcb_trace_id)||(e.type==='pcb_smtpad'&&e.pcb_port_id===source.start_pcb_port_id);return supportCopperObstacles([projected]).map((o:any)=>({...o,...((e.type==='pcb_smtpad'&&e.shape==='circle')||e.type==='pcb_via'||o.obstacleId.startsWith('fixed_via_')||o.obstacleId.endsWith('_cap')?{shape:'circle'}:{}),connectedTo:[own?connection.name:`reserved:${e[`${e.type}_id`]}`]}))}),sourceObstacle=obstacles.find((o:any)=>o.connectedTo[0]===connection.name&&o.layers.includes('top')&&Math.abs(o.center.x-source.x)<=o.width/2+1e-7&&Math.abs(o.center.y-source.y)<=o.height/2+1e-7),local={...connection,pointsToConnect:[source,target]},pc={connection:local,connectionIndex:0,sourcePoint:source,sourcePointIndex:0,sourceLayer:'top',sourceObstacle,targetPoint:target},bounds={minX:-11,maxX:-6.040077,minY:-11.8,maxY:-7.5},bus={busId:'RAM0-DQ2-around-C1',direction:'right',exitEdge:'right',termination:{type:'boundary'},connections:[pc],componentId:'RAM0-DQ2',componentObstacles:[sourceObstacle],componentBounds:bounds,sharedBoundary:bounds,xCoordinates:[via.x],yCoordinates:[via.y],pitchX:.8,pitchY:.8}
const{routeViaMinimalWindingAlternativesSteps}=await import(resolve('node_modules/@tscircuit/fanout-solver/lib/route-via-minimal-winding.ts')),params={srj:{...input,obstacles,traces:[]},bus,targetLayer:via.to_layer,terminals:[{connection:pc,viaPoint:via,exitPoint:target}],acceptedPlans:[],layerNames:['top',...Array.from({length:8},(_,i)=>`inner${i+1}`),'bottom'],traceWidth:.12,viaDiameter:.4572,viaHoleDiameter:.254,clearance:.1016,allowBlindAndBuriedVias:false,allowSourceLayerRouting:true,gridStep:.02,gridOrigin:{x:via.x,y:via.y},alignGridToPads:true,gridStepDivisor:2,maximumRouteOrderAttempts:1,maximumSearchStates:300000,heuristicWeight:1,sourceEscapePaths:new Map([[0,old.route.slice(0,vi).map((p:any)=>({x:p.x,y:p.y}))]])},steps=routeViaMinimalWindingAlternativesSteps(params as any,1),progress:any[]=[],started=Date.now();let results:any[]=[],finished=false
while(Date.now()-started<55000){const s=steps.next();if(s.done){results=s.value;finished=true;break}progress.push({...s.value,visualization:undefined})}if(!finished)steps.return([])
let diagnostic:any;if(results[0]?.length===1){const after=explicitFacingViaContinuation(old,results[0][0].trace,via.to_layer).after;after.route.push(...suffix.slice(1));changes.push({before:old,after});const child=base.map((e:any)=>e===old?after:e),fresh=[...host.traces,...powerTraces,after],ids=new Set(fresh.map((e:any)=>e.pcb_trace_id)),fixed=child.filter((e:any)=>e.type!=='pcb_copper_pour'&&(e.type!=='pcb_trace'||!ids.has(e.pcb_trace_id)));fixed.push(e2after,after);const physical=verifyDdrSystemCopper(fixed,fresh,input.connections,{},50,{reportSameNetContacts:true}),angles=auditRouteAngles(child.filter((e:any)=>e.type==='pcb_trace')),junctions=auditDdrTraceJunctions(child,input.connections),planar=(r:any[])=>r.slice(1).reduce((n:number,p:any,i:number)=>{const q=r[i];return n+(p.route_type==='wire'&&q.route_type==='wire'&&p.layer===q.layer?Math.hypot(p.x-q.x,p.y-q.y):0)},0);diagnostic={physical,angles,junctions,oldLocalMm:planar(old.route),newLocalMm:planar(after.route),deltaMm:planar(after.route)-planar(old.route),allHostsExact:host.traces.every((t:any)=>child.some((e:any)=>hash(e)===hash(t))),scope:'Conductor-only proposal. New source rail contacts/plane repour/reference and exact DQ2 total still require qualification.'};write('candidate.circuit.json',child);write('original-copper-replacements.json',{parentCircuitSha256:hash(parent),candidateCircuitSha256:hash(child),replacements:changes.map(c=>({id:`${c.before.type}:${c.before[`${c.before.type}_id`]}`,before:c.before,after:c.after,beforeSha256:hash(c.before),afterSha256:hash(c.after)}))})}
for(const[p,h]of Object.entries(bound))if(createHash('sha256').update(readFileSync(p)).digest('hex')!==h)throw Error('Input changed');write('report.json',{captureHash:prior.captureHash,parentCircuitSha256:hash(parent),sourceHashes:bound,finished,progress,results,diagnostic,accepted:false});console.log(JSON.stringify({finished,states:progress.at(-1)?.expandedStateCount,alternatives:results[0]?.length??0,deltaMm:diagnostic?.deltaMm,violations:diagnostic?.physical.violations.length,angles:diagnostic?.angles.valid,junctions:diagnostic?.junctions.valid}))