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/improve-ddr-a9-power-launches.ts
/** Isolated, provenance-checked A9 improvement. Never edits the parent candidate. */
import {readFileSync,writeFileSync,mkdirSync,copyFileSync} from 'node:fs'
import {resolve} from 'node:path'
import {spawnSync} from 'node:child_process'
import {createHash} from 'node:crypto'
import {verifyDdrCapture} from './ddr-capture-provenance'
import {loadDdrSupportRoutingContext} from './ddr-support-routing-context'
import {verifyDdrSystemCopper} from './check-ddr-system-copper'
import {planDdrGroundAntipads} from './ddr-ground-plane-antipads'
import {refreshDdrPlaneContacts} from './ddr-plane-contact-audit'
export const objectHash=(x:any)=>createHash('sha256').update(JSON.stringify(x)).digest('hex')
const read=(p:string)=>JSON.parse(readFileSync(p,'utf8'))
const identity=(e:any)=>`${e.type}:${e[`${e.type}_id`]}`
/** Child support validation is a checked patch atop a separately validated parent.
* It deliberately does not waive the legacy loader's original-copper invariant. */
export function validateDeclaredDdrReplacements(parent:any[],child:any[],manifest:any){
if(manifest.parentCircuitSha256!==objectHash(parent)||manifest.candidateCircuitSha256!==objectHash(child))throw Error('Circuit provenance mismatch')
if(parent.length!==child.length)throw Error('Element addition/removal is undeclared')
const entries=new Map<string,any>()
for(const r of manifest.replacements){if(entries.has(r.id)||r.id!==identity(r.before)||r.id!==identity(r.after)||r.beforeSha256!==objectHash(r.before)||r.afterSha256!==objectHash(r.after))throw Error('Invalid replacement witness');entries.set(r.id,r)}
let changed=0
for(let i=0;i<parent.length;i++){
const a=parent[i],b=child[i],r=entries.get(identity(a))
if(identity(a)!==identity(b))throw Error('Element order/identity changed')
if(r){if(objectHash(a)!==r.beforeSha256||objectHash(b)!==r.afterSha256)throw Error('Replacement does not match actual circuit');changed++}
else if(objectHash(a)!==objectHash(b))throw Error(`Undeclared support change ${identity(a)}`)
}
if(changed!==entries.size)throw Error('Replacement identity absent')
return {valid:true,parentCircuitSha256:objectHash(parent),candidateCircuitSha256:objectHash(child),declaredReplacementCount:changed,allOtherElementsExact:true}
}
export async function improveA9(parentDir:string,captureDir:string,outDir:string){
if(resolve(parentDir)===resolve(outDir))throw Error('Output must be isolated')
const parent=read(`${parentDir}/candidate.circuit.json`),prior=read(`${parentDir}/report.json`),host=read(`${parentDir}/host-bundle.json`),original=read(`${captureDir}/unrouted.circuit.json`),connections=read(`${captureDir}/routing-input.json`).connections
const {captureHash}=verifyDdrCapture(captureDir)
if(host.captureHash!==captureHash||prior.captureHash!==captureHash)throw Error('Expected frozen physical host parent')
if(host.layerSpace!=='physical'||!Array.isArray(host.traces)||!host.traces.length)throw Error('Missing physical host bundle')
const hostIds=new Set(host.traces.map((t:any)=>t.pcb_trace_id)),actualHosts=parent.filter((e:any)=>e.type==='pcb_trace'&&hostIds.has(e.pcb_trace_id))
if(actualHosts.length!==host.traces.length||new Set(actualHosts.map((t:any)=>t.pcb_trace_id)).size!==host.traces.length)throw Error('Parent does not preserve every host')
const parentContext=await loadDdrSupportRoutingContext(captureDir,`${parentDir}/candidate.circuit.json`,original,actualHosts,captureHash)
const replacements:any[]=[],retiredEdgeMetadata:any[]=[],newVias:any[]=[],newTraceIds=new Set<string>(),groundTrimIds=new Set<string>()
let child=structuredClone(parent)
for(const byte of [0,1])for(const [suffix,kind] of [[48,'ground-tail'],[49,'ground-tail'],[61,'A9-drop']] as const){
const id=`saved_fanout_pcb_group_${byte?5:3}_${suffix}`,index=child.findIndex((e:any)=>e.pcb_trace_id===id),before=parent[index]
if(!before||before.type!=='pcb_trace')throw Error('Missing expected original power trace')
const source=parent.find((e:any)=>e.source_trace_id===before.source_trace_id&&e.type==='source_trace')
if(!source?.name?.startsWith(`RAM${byte}_`)||!source.name.includes(suffix===48?'VSS_A8':suffix===49?'VSSQ_B8':'VDD_A9'))throw Error('Power source identity mismatch')
const after=structuredClone(before)
if(kind==='ground-tail'){
const vi=after.route.findIndex((p:any)=>p.route_type==='via')
if(vi!==2||after.route.slice(vi+1).some((p:any)=>p.route_type!=='wire'||p.layer!=='bottom'))throw Error('Expected removal-only bottom tail')
after.route=after.route.slice(0,vi+1);groundTrimIds.add(id)
}else{
const start=after.route[0],x=start.x-.55,y=start.y
after.route=[start,{route_type:'wire',x,y,width:.12,layer:'top'},{route_type:'via',x,y,from_layer:'top',to_layer:'inner3',via_diameter:.4572,via_hole_diameter:.254}]
newTraceIds.add(id);newVias.push({x,y,net:'DDR_1V5',diameter:.4572,traceId:id,byte,padToViaMm:.55})
}
const retired=(after.connectsTo??[]).filter((s:string)=>s.startsWith('pcb_breakout_point_'))
after.connectsTo=(after.connectsTo??[]).filter((s:string)=>!retired.includes(s))
if(after.connection_name?.startsWith('breakout:'))delete after.connection_name
retiredEdgeMetadata.push({traceId:id,retiredBreakoutPointIds:retired,scope:'Historical breakout objects retained for provenance; these power traces no longer promise edge handoff.'})
child[index]=after
replacements.push({id:identity(before),reason:kind==='ground-tail'?'Retain pad and existing ground via; remove unused bottom tail beyond verified inner1 contact.':'Replace outer edge stub with straight 0.55 mm top launch into inner3 supply through via.',beforeSha256:objectHash(before),afterSha256:objectHash(after),before,after})
}
const parentPlanes=parent.filter((e:any)=>e.type==='pcb_copper_pour'),groundPlanes=parentPlanes.filter((p:any)=>['inner1','inner5'].includes(p.layer)),antipads=planDdrGroundAntipads(groundPlanes,newVias)
for(const after of antipads.planes){const index=child.findIndex((e:any)=>identity(e)===identity(after)),before=parent[index];child[index]=after;replacements.push({id:identity(before),reason:'Two foreign A9 power-via antipads; preserve outer boundary and existing holes.',beforeSha256:objectHash(before),afterSha256:objectHash(after),before,after})}
for(const v of newVias){
const oldVias=parent.flatMap((e:any)=>e.type==='pcb_via'?[{x:e.x,y:e.y,diameter:e.outer_diameter,drill:e.hole_diameter}]:e.type==='pcb_trace'?e.route.filter((p:any)=>p.route_type==='via').map((p:any)=>({x:p.x,y:p.y,diameter:p.via_diameter,drill:p.via_hole_diameter})):[])
v.minimumExistingViaCopperEdgeGapMm=Math.min(...oldVias.map((p:any)=>Math.hypot(v.x-p.x,v.y-p.y)-(v.diameter+p.diameter)/2))
if(v.minimumExistingViaCopperEdgeGapMm<.1016-1e-8)throw Error('New via violates same-net barrel spacing')
}
const manifest={captureHash,parentDirectory:resolve(parentDir),parentCircuitSha256:objectHash(parent),candidateCircuitSha256:objectHash(child),replacements,retiredEdgeMetadata,newVias}
const supportValidation=validateDeclaredDdrReplacements(parent,child,manifest)
const planes=child.filter((e:any)=>e.type==='pcb_copper_pour'),witnesses=structuredClone(prior.planeAudit)
const power=witnesses.find((a:any)=>a.layer==='inner3')
for(const v of newVias)power.viaContacts.push({id:`${v.traceId}:via:2`,x:v.x,y:v.y,annulusSamplesInPlane:32,total:32})
power.uniqueViaCount+=newVias.length
const planeAudit=refreshDdrPlaneContacts(witnesses,planes,child).map((a:any)=>({...a,foreignConductors:a.foreignConductors+(a.layer==='inner3'?0:2),minForeignClearanceMm:a.layer==='inner3'?a.minForeignClearanceMm:Math.min(a.minForeignClearanceMm,.1016)}))
const fresh=child.filter((e:any)=>e.type==='pcb_trace'&&(hostIds.has(e.pcb_trace_id)||newTraceIds.has(e.pcb_trace_id))),freshIds=new Set(fresh.map((e:any)=>e.pcb_trace_id))
// Trimmed ground traces remain fixed so rendered vias retain verified ownership.
// They are exact retained prefixes: copper removal cannot add a clearance fault.
const physical=verifyDdrSystemCopper(child.filter((e:any)=>!freshIds.has(e.pcb_trace_id)),fresh,connections,{})
if(physical.errors.length||physical.violations.length||!physical.angles.valid||physical.joinedBends.length)throw Error(`Full alias-free physical check failed: ${JSON.stringify({errors:physical.errors,violations:physical.violations,angles:physical.angles,joined:physical.joinedBends})}`)
if(actualHosts.some((t:any)=>!physical.connectivity.some((c:any)=>c.name===t.connection_name&&c.connected)))throw Error('Host connectivity lost')
// Check unchanged top prefixes and straight power launches explicitly.
for(const t of child.filter((e:any)=>e.type==='pcb_trace'&&(groundTrimIds.has(e.pcb_trace_id)||newTraceIds.has(e.pcb_trace_id)))){const w=t.route.filter((p:any)=>p.route_type==='wire');if(w.length!==2||Math.abs(w[0].y-w[1].y)>1e-8&&Math.abs(Math.abs(w[0].x-w[1].x)-Math.abs(w[0].y-w[1].y))>1e-8)throw Error('Power launch is not straight octilinear')}
mkdirSync(outDir,{recursive:true})
const write=(n:string,v:any)=>writeFileSync(`${outDir}/${n}`,JSON.stringify(v,null,2))
write('candidate.circuit.json',child);copyFileSync(`${parentDir}/host-bundle.json`,`${outDir}/host-bundle.json`)
write('original-copper-replacements.json',manifest)
const report={...prior,parentReportSha256:objectHash(prior),parentSupportValidation:parentContext.evidence,supportValidation,originalCopperReplacementsSha256:objectHash(manifest),supportValidationMethod:'Validate frozen original/inherited replacements via legacy loader on parent, then exact declared child patch; legacy loader must not be called directly on child without this patch validation.',planeAudit,planeChanges:{inherited:prior.planeChanges,addedAntipads:antipads.added,existingContactsRechecked:true,newA9PowerContacts:2},physical,externalAliasesUsed:false,scope:'Isolated A9 power improvement with all parent hosts preserved. Six explicit original trace replacements and two plane replacements; every other element exact. Actual pad-to-plane launch count is in ram-power-launch-audit.json; not complete DDR signoff.'}
write('report.json',report)
const auditRun=spawnSync(process.execPath,[resolve(import.meta.dir,'audit-ddr-global-power-launches.ts'),outDir,captureDir],{encoding:'utf8'})
if(auditRun.status!==0)throw Error(`Actual launch audit failed: ${auditRun.stderr}`)
const launchAudit=read(`${outDir}/ram-power-launch-audit.json`)
if(launchAudit.total!==60||launchAudit.launchQualified!==52||launchAudit.planeConnected!==52)throw Error('Actual source audit does not prove 52/60')
Object.assign(report,{launchAuditSha256:objectHash(launchAudit),launchQualified:52,totalRamPowerPads:60,preservedHostCount:actualHosts.length})
write('report.json',report)
return {output:resolve(outDir),captureHash,supportValidation,newVias,physical:{errors:physical.errors.length,violations:physical.violations.length,minClearanceMm:physical.minClearanceMm,anglesValid:physical.angles.valid,joinedBends:physical.joinedBends.length,connected:physical.connectivity.filter((c:any)=>c.connected).length},planeHolesAdded:antipads.added.length}
}
if(import.meta.main){const [parent='dist/ddr-integrated-nine',capture='dist/ddr-system/host-taps-54af3e346b5e',out='dist/ddr-integrated-nine-power52']=process.argv.slice(2);console.log(JSON.stringify(await improveA9(parent,capture,out),null,2))}