In this section
- Live Sandbox — Federation Control Ledger interaction · data-federation-map-for-globalgrid2050-all-repos / live_sandbox/federation_control_ledger/app.js lines 1–189
- Focus Default interaction · data-federation-map-for-globalgrid2050-all-repos / live_sandbox/federation_control_ledger/focus-default.js lines 1–48
- Live Sandbox — Federation Control Ledger Page render · data-federation-map-for-globalgrid2050-all-repos / live_sandbox/federation_control_ledger/index.html lines 1–49
- Live Sandbox — Football One Card Page render · data-federation-map-for-globalgrid2050-all-repos / live_sandbox/football_one_card/index.html lines 1–80
- Build Declared Cartridges storage · data-federation-map-for-globalgrid2050-all-repos / scripts/build_declared_cartridges.py lines 1–262
Live Sandbox — Federation Control Ledger
A JavaScript file in Data Federation Map for GlobalGrid2050 All Repos that loads scope, shows edge popover, builds layer and calculates planar distances. Served with the page at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
interactiondata-federation-map-for-globalgrid2050-all-repos / live_sandbox/federation_control_ledger/app.js · lines 1–189 of 189 · Entry point · pattern layerFor (shared by 2 files)
- What it does
- It draws its content. Defines 29 functions or classes, including defaultScale, esc, repoUrl, rootUrl, json. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- Out: SVG drawing.
- Downstream impact
- Used directly by 1 file: Live Sandbox — Federation Control Ledger Page (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/). Reached from 290 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Federation Radial (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/federation_radial.html); Federation Radial Uniform (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/federation_radial_uniform.html). It is itself an entry point, published at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
- What it achieves
- It loads scope (`loadScope`), shows edge popover (`showEdgePopover`) and builds layer key (`buildLayerKey`). Defines `defaultScale`, `esc`, `repoUrl` and 26 more. It responds to click, wheel and touchstart events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
- Application
- data-federation-map-for-globalgrid2050-all-repos · live_sandbox/federation_control_ledger · script
- Uses
- Live Sandbox — Federation Control Ledger Page (estate URL)
- Used by
- loaded by Live Sandbox — Federation Control Ledger Page (script src)
- Produces
- defaultScale, esc, repoUrl, rootUrl, json, layerFor, defaultVisible, visibleNodes, visibleEdgesRaw, isWorkflowEdge, edgeFilterMatch, loadScope
- Defines here
- defaultScale, esc, repoUrl, rootUrl, json, layerFor, defaultVisible, visibleNodes, visibleEdgesRaw, isWorkflowEdge, edgeFilterMatch, loadScope, grouped, cssVar, geometry, render, visibleEdges, relatedIds, edgeCoords, connectors, redrawOnly, showEdgePopover, card, repoPreview, buildLayerKey, updateLayerKeyState, updateBackButton, setScale, wire
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c live_sandbox/federation_control_ledger/app.js:1-189 · blob 9cb629d39a35ccebb3f5b3e39340b94f01482d1c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: supporting_data
const ROOT = window.REPO_BOARD_ROOT || 'data/manifest.json';
const FED_REPO = 'https://github.com/Ventusltd/data-federation-map-for-globalgrid2050-all-repos';
const LAYERS = [
{ id:'core', title:'Core', color:'#00ffff', match:n=>n.id.includes('data-federation-map') || n.id==='repo-root', isRepo:true },
{ id:'data', title:'Data repos', color:'#00e5ff', match:n=>n.repo_type==='data' && !n.id.includes('data-federation-map') && n.id!=='repo-root', isRepo:true },
{ id:'apps', title:'Apps / UI', color:'#22d3ee', match:n=>['ui','homepage'].includes(n.repo_type), isRepo:true },
{ id:'source', title:'Source / archive', color:'#67e8f9', match:n=>n.repo_type==='source_archive', isRepo:true },
{ id:'related', title:'Related repos', color:'#a5f3fc', match:n=>n.repo_type==='unknown', isRepo:true },
{ id:'external', title:'External systems', color:'#7dd3fc', match:n=>n.repo_type==='external', isRepo:false }
];
const TYPE_BADGE = { data:'DB', ui:'UI', homepage:'WEB', source_archive:'SRC', unknown:'REP', external:'EXT' };
const PAGE_LINKS = {
'Ventusltd/globalgrid2050':'https://globalgrid2050.com/',
'Ventusltd/globalgrid2050-hompage':'https://globalgrid2050.com/',
'Ventusltd/data-federation-map-for-globalgrid2050-all-repos':'https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/',
'live-dashboard-page':'https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/'
};
const EDGE_HELP = {
data:'Data dependency: one object consumes or publishes cartridge data used by another object.',
governance:'Governance relationship: documentation, report, doctrine or control dependency.',
archive:'Archive lineage: relationship to the original source archive or retiring monolith.',
external:'External reference: dependency on a public host, build system, API or workflow runner.',
repo:'Repository structure: declared parent-child or file relationship.',
workflow:'Dependency on an external data source, build runner or processing tool.'
};
let state = { filter:'all', selected:null, selectedEdge:null, scale:defaultScale(), visibleLayers:new Set(LAYERS.filter(l=>l.isRepo).map(l=>l.id)), nodes:[], edges:[], manifest:null, manifestUrl:null, baseUrl:null, cards:new Map(), dims:null };
let scopeStack = [];
let pinch = null;
function defaultScale(){return window.innerWidth < 740 ? 0.62 : 0.82;}
function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}
function repoUrl(id){return String(id||'').startsWith('Ventusltd/') ? `https://github.com/${id}` : '';}
function rootUrl(path, base=location.href){return new URL(path, base).href;}
async function json(path, base){const r=await fetch(rootUrl(path, base),{cache:'no-cache'}); if(!r.ok) throw new Error(`${path} ${r.status}`); return r.json();}
function layerFor(n){return LAYERS.find(l=>l.match(n)) || LAYERS.find(l=>l.id==='related');}
function defaultVisible(){return new Set(LAYERS.filter(l=>l.isRepo).map(l=>l.id));}
function visibleNodes(){return state.nodes.filter(n=>state.visibleLayers.has(n.layerId));}
function visibleEdgesRaw(){const ids=new Set(visibleNodes().map(n=>n.id)); return state.edges.filter(e=>ids.has(e.source.id)&&ids.has(e.target.id));}
function isWorkflowEdge(e){return e.type==='external' || e.source.layerId==='external' || e.target.layerId==='external';}
function edgeFilterMatch(e){return state.filter==='all' || (state.filter==='workflow' ? isWorkflowEdge(e) : e.type===state.filter);}
async function loadScope(manifestPath, push){
document.body.classList.add('focus-mode');
const baseForResolve = state.baseUrl || location.href;
const manifestUrl = rootUrl(manifestPath, baseForResolve);
const manifest = await json(manifestUrl);
if(push && state.manifestUrl) scopeStack.push(state.manifestUrl);
const base = new URL('.', manifestUrl).href;
const nodesJson = await json(manifest.sources.nodes, base);
const edgesJson = await json(manifest.sources.edges, base);
state.manifest = manifest;
state.manifestUrl = manifestUrl;
state.baseUrl = base;
state.filter = 'all';
state.selected = null;
state.selectedEdge = null;
state.scale = defaultScale();
state.visibleLayers = defaultVisible();
state.nodes = nodesJson.features.map((f,i)=>{
const n={
index:i,
id:f.properties.id || f.id,
label:f.properties.label || f.id,
repo_type:f.properties.repo_type || f.properties.scope_type || 'unknown',
rag:f.properties.rag || f.properties.status || 'grey',
status:f.properties.status || f.properties.rag || 'grey',
reason:f.properties.status_reason || '',
importance:Number(f.properties.importance_score || 0.4),
child_manifest:f.properties.child_manifest || null,
source_url:f.properties.source_url || repoUrl(f.properties.id || f.id)
};
const layer=layerFor(n);
n.layerId=layer.id; n.layerTitle=layer.title; n.layerColor=layer.color; n.isRepo=layer.isRepo;
return n;
});
state.edges = (edgesJson.edges || []).map(([from,to,type],i)=>({ id:`e${i}`, from, to, type, source:state.nodes[from], target:state.nodes[to] })).filter(e=>e.source&&e.target);
buildLayerKey();
render();
updateBackButton();
document.querySelector('.board-wrap')?.scrollTo({left:0,top:0,behavior:'smooth'});
}
function grouped(){return LAYERS.map(layer=>({ ...layer, items:state.nodes.filter(n=>n.layerId===layer.id && state.visibleLayers.has(layer.id)).sort((a,b)=>b.importance-a.importance) })).filter(g=>g.items.length);}
function cssVar(name, fallback){const v=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name)); return Number.isFinite(v)?v:fallback;}
function geometry(groups){
const cardW=cssVar('--card-w',340), cardH=cssVar('--card-h',164), rowGap=cssVar('--row-gap',42), colGap=cssVar('--col-gap',150), pad=cssVar('--board-pad',18), title=cssVar('--title-offset',44);
const cards = new Map();
groups.forEach((g, col)=>g.items.forEach((n,row)=>cards.set(n.id,{x:pad+col*(cardW+colGap), y:pad+title+row*(cardH+rowGap), w:cardW, h:cardH, col, row})));
const maxRows = Math.max(...groups.map(g=>g.items.length),1);
return {cards, width:pad*2+groups.length*cardW+(groups.length-1)*colGap, height:pad*2+title+maxRows*cardH+(maxRows-1)*rowGap, cardW, cardH, pad, title};
}
function render(){
const board=document.getElementById('board');
const groups=grouped();
const dims=geometry(groups);
state.cards=dims.cards; state.dims=dims;
board.style.width=`${Math.max(dims.width, board.parentElement.clientWidth / state.scale)}px`;
board.style.height=`${Math.max(dims.height, board.parentElement.clientHeight / state.scale)}px`;
board.style.transform=`scale(${state.scale})`;
board.innerHTML='';
board.appendChild(connectors());
groups.forEach(g=>{
const x=dims.cards.get(g.items[0].id)?.x || dims.pad;
const h=document.createElement('h2'); h.className='stage-title'; h.style.left=`${x}px`; h.style.top=`${dims.pad}px`; h.textContent=g.title; h.style.setProperty('--layer-color',g.color); board.appendChild(h);
g.items.forEach(n=>board.appendChild(card(n)));
});
if(state.selected){const n=state.nodes.find(x=>x.id===state.selected); if(n && state.cards.has(n.id)) board.appendChild(repoPreview(n));}
document.getElementById('scopeName').textContent=state.manifest?.scope?.label || state.manifest?.public_title || 'Repository Federation';
document.getElementById('relationCount').textContent=`${visibleNodes().length} / ${visibleEdges().length}`;
document.querySelectorAll('.relation-nav button').forEach(b=>b.classList.toggle('active',b.dataset.filter===state.filter));
updateLayerKeyState();
}
function visibleEdges(){return visibleEdgesRaw().filter(edgeFilterMatch).filter(e=>edgeCoords(e));}
function relatedIds(id){const s=new Set([id]); visibleEdgesRaw().forEach(e=>{if(e.source.id===id||e.target.id===id){s.add(e.source.id);s.add(e.target.id);}}); return s;}
function edgeCoords(e){
const a=state.cards.get(e.source.id), b=state.cards.get(e.target.id); if(!a||!b||a.col===b.col) return null;
const left=a.col<b.col?a:b, right=a.col<b.col?b:a;
const sx=left.x+left.w, sy=left.y+left.h/2, tx=right.x, ty=right.y+right.h/2;
const mid=sx+Math.min(80,Math.max(42,(tx-sx)*0.38));
return {sx,sy,tx,ty,mid,path:`M${sx} ${sy} H${mid} V${ty} H${tx}`, labelX:mid+8, labelY:(sy+ty)/2};
}
function connectors(){
const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'); svg.classList.add('connector-layer'); svg.setAttribute('width',state.dims.width); svg.setAttribute('height',state.dims.height);
const selectedSet=state.selected?relatedIds(state.selected):null;
visibleEdges().forEach(e=>{
const c=edgeCoords(e); if(!c) return;
const typeClass = state.filter==='workflow' && isWorkflowEdge(e) ? 'workflow' : e.type;
const isDim = selectedSet&&!selectedSet.has(e.source.id)&&!selectedSet.has(e.target.id);
const isHighlight = state.selectedEdge===e.id || (state.selected&&(e.source.id===state.selected||e.target.id===state.selected));
const p=document.createElementNS('http://www.w3.org/2000/svg','path'); p.setAttribute('d',c.path); p.setAttribute('class',`connector-path ${typeClass}${isDim?' dim':''}${isHighlight?' highlight':''}`); svg.appendChild(p);
const hit=document.createElementNS('http://www.w3.org/2000/svg','path'); hit.setAttribute('d',c.path); hit.setAttribute('class','connector-hit'); hit.addEventListener('click',ev=>{ev.stopPropagation(); state.selected=null; state.selectedEdge=e.id; showEdgePopover(e,c.labelX,c.labelY); redrawOnly();}); svg.appendChild(hit);
});
return svg;
}
function redrawOnly(){const wrap=document.querySelector('.board-wrap'); const left=wrap.scrollLeft, top=wrap.scrollTop; render(); wrap.scrollLeft=left; wrap.scrollTop=top;}
function showEdgePopover(e,x,y){
document.querySelectorAll('.edge-popover,.repo-popover').forEach(p=>p.remove());
const displayType = state.filter==='workflow' && isWorkflowEdge(e) ? 'workflow' : e.type;
const pop=document.createElement('div'); pop.className='edge-popover'; pop.style.left=`${x}px`; pop.style.top=`${Math.max(10,y-54)}px`;
pop.innerHTML=`<button type="button" aria-label="Close">×</button><h3>Relationship line</h3><p><span class="edge-type">${esc(displayType)}</span></p><p><strong>${esc(e.source.label)}</strong><br>→ ${esc(e.target.label)}</p><p>${esc(EDGE_HELP[displayType]||EDGE_HELP[e.type]||'Declared repository relationship.')}</p><p class="small">This line is drawn from this scope edge list. It is observe-only. … [line shortened here: 406 characters; full line on GitHub]
pop.querySelector('button').onclick=()=>{state.selectedEdge=null; pop.remove(); redrawOnly();};
document.getElementById('board').appendChild(pop);
}
function card(n){
const g=state.cards.get(n.id), href=n.source_url||repoUrl(n.id), selected=state.selected===n.id, related=state.selected?relatedIds(state.selected).has(n.id):true;
const div=document.createElement('article'); div.className=`repo-card status-${n.status}${selected?' selected':''}${!related?' dim':''}`; div.style.left=`${g.x}px`; div.style.top=`${g.y}px`; div.style.setProperty('--layer-color',n.layerColor);
div.innerHTML=`<div class="repo-meta"><span>${esc(n.layerTitle)}</span><span>${esc(n.status)}</span></div><button class="repo-main" type="button"><span class="repo-badge">${esc(TYPE_BADGE[n.repo_type]||'REP')}</span><span class="repo-name">${esc(n.label)}</span><span class="repo-dot">●</span></button><div class="repo-reason">${esc(n.reason)}</div><div class="repo-tools"><a href="${esc(FED_REPO)} … [line shortened here: 734 characters; full line on GitHub]
div.querySelector('.repo-main').addEventListener('click',ev=>{ev.stopPropagation(); state.selected=state.selected===n.id?null:n.id; state.selectedEdge=null; redrawOnly();});
const childLink=div.querySelector('[data-child-card]'); if(childLink) childLink.addEventListener('click',ev=>{ev.preventDefault(); ev.stopPropagation(); loadScope(n.child_manifest,true);});
return div;
}
function repoPreview(n){
const g=state.cards.get(n.id); const href=n.source_url||repoUrl(n.id); const page=PAGE_LINKS[n.id];
const pop=document.createElement('div'); pop.className='repo-popover';
const right=g.x+g.w+18; const left=Math.max(8,g.x-300); const useRight=right+300<state.dims.width;
pop.style.left=`${useRight?right:left}px`; pop.style.top=`${Math.max(8,g.y)}px`; pop.style.setProperty('--layer-color',n.layerColor);
const workflows = String(n.id||'').startsWith('Ventusltd/') ? `https://github.com/${n.id}/actions` : '';
pop.innerHTML=`<button class="close" type="button">×</button><h3>${esc(n.label)}</h3><p><span class="mini-key">${esc(n.layerTitle)}</span> <span class="mini-status">${esc(n.status)}</span></p><p>${esc(n.reason||'No further status note in current cartridge.')}</p><div class="preview-actions">${n.child_manifest?'<a href="#" data-open-child="1">OPEN ATLAS</a>':''}${href?`<a href="${esc(href)}" targ … [line shortened here: 734 characters; full line on GitHub]
pop.querySelector('.close').onclick=()=>{state.selected=null; redrawOnly();};
const open=pop.querySelector('[data-open-child]'); if(open) open.onclick=e=>{e.preventDefault(); loadScope(n.child_manifest,true);};
return pop;
}
function buildLayerKey(){
const nav=document.getElementById('layerNav'); if(!nav) return;
nav.innerHTML=`<button type="button" data-mode="all">All layers</button><button type="button" data-mode="repos">Repos only</button><button type="button" data-mode="api">API deps</button>` + LAYERS.map(l=>`<button type="button" data-layer="${l.id}" style="--layer-color:${l.color}"><span class="layer-swatch"></span>${esc(l.title)}</button>`).join('');
nav.querySelector('[data-mode="all"]').onclick=()=>{state.visibleLayers=new Set(LAYERS.map(l=>l.id)); state.filter='all'; state.selected=null; state.selectedEdge=null; render();};
nav.querySelector('[data-mode="repos"]').onclick=()=>{state.visibleLayers=defaultVisible(); state.filter='all'; state.selected=null; state.selectedEdge=null; render();};
nav.querySelector('[data-mode="api"]').onclick=()=>{state.visibleLayers=new Set(['core','data','apps','external']); state.filter='workflow'; state.selected=null; state.selectedEdge=null; render();};
nav.querySelectorAll('[data-layer]').forEach(btn=>btn.onclick=()=>{const id=btn.dataset.layer; state.visibleLayers.has(id)?state.visibleLayers.delete(id):state.visibleLayers.add(id); state.selected=null; state.selectedEdge=null; render();});
}
function updateLayerKeyState(){const nav=document.getElementById('layerNav'); if(!nav) return; nav.querySelectorAll('[data-layer]').forEach(btn=>btn.classList.toggle('active',state.visibleLayers.has(btn.dataset.layer)));}
function ensureBackButton(){let btn=document.getElementById('backButton'); if(btn) return btn; const actions=document.querySelector('.actions'); btn=document.createElement('button'); btn.id='backButton'; btn.type='button'; btn.textContent='Back'; actions.prepend(btn); btn.onclick=()=>{const parent=scopeStack.pop(); if(parent){state.baseUrl=new URL('.', parent).href; loadScope(parent,false);}}; ret … [line shortened here: 409 characters; full line on GitHub]
function updateBackButton(){const btn=ensureBackButton(); btn.hidden=scopeStack.length===0;}
function setScale(value){state.scale=Math.max(0.42,Math.min(1.25,value)); render();}
function wire(){
ensureBackButton(); updateBackButton();
document.querySelectorAll('.relation-nav button').forEach(b=>b.onclick=()=>{state.filter=b.dataset.filter; state.selectedEdge=null; render();});
document.getElementById('resetButton').onclick=()=>{state.filter='all';state.selected=null;state.selectedEdge=null;state.visibleLayers=defaultVisible();setScale(defaultScale());document.querySelector('.board-wrap').scrollTo({left:0,top:0,behavior:'smooth'});};
document.getElementById('fullscreenButton').onclick=()=>{document.body.classList.toggle('focus-mode');document.getElementById('fullscreenButton').textContent=document.body.classList.contains('focus-mode')?'Exit':'Fullscreen';};
const wrap=document.querySelector('.board-wrap');
wrap.addEventListener('click',e=>{if(e.target.closest('.repo-card,.repo-popover,.edge-popover,.connector-hit'))return; state.selected=null; state.selectedEdge=null; redrawOnly();});
wrap.addEventListener('wheel',e=>{if(!e.ctrlKey&&!e.metaKey)return; e.preventDefault(); setScale(state.scale+(e.deltaY<0?0.06:-0.06));},{passive:false});
wrap.addEventListener('touchstart',e=>{if(e.touches.length===2){const dx=e.touches[0].clientX-e.touches[1].clientX,dy=e.touches[0].clientY-e.touches[1].clientY; pinch={dist:Math.hypot(dx,dy),scale:state.scale};}}, {passive:true});
wrap.addEventListener('touchmove',e=>{if(!pinch||e.touches.length!==2)return; e.preventDefault(); const dx=e.touches[0].clientX-e.touches[1].clientX,dy=e.touches[0].clientY-e.touches[1].clientY; setScale(pinch.scale*(Math.hypot(dx,dy)/pinch.dist));}, {passive:false});
wrap.addEventListener('touchend',()=>{pinch=null;}, {passive:true});
window.addEventListener('resize',()=>render());
}
wire();
loadScope(ROOT,false).catch(err=>{document.getElementById('board').innerHTML=`<p style="padding:16px;color:#ff6666">${esc(err.message)}</p>`;});Focus Default
A JavaScript file in the federation control ledger folder of Data Federation Map for GlobalGrid2050 All Repos that applies quiet default (`applyQuietDefault`). Served with the page at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
interactiondata-federation-map-for-globalgrid2050-all-repos / live_sandbox/federation_control_ledger/focus-default.js · lines 1–48 of 48 · Entry point
- What it does
- Defines applyQuietDefault, waitThenApply, watchLayerNav. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Downstream impact
- Used directly by 1 file: Live Sandbox — Federation Control Ledger Page (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/). Reached from 291 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Federation Radial (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/federation_radial.html); Federation Radial Uniform (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/federation_radial_uniform.html). It is itself an entry point, published at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
- What it achieves
- It applies quiet default (`applyQuietDefault`) and is built from the wait then apply helper (`waitThenApply`) and the watch layer nav helper (`watchLayerNav`). Defines `applyQuietDefault`, `waitThenApply` and `watchLayerNav`. It responds to load and click events.
- Why it matters
- Loaded by the Federation Control Ledger page at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
- Application
- data-federation-map-for-globalgrid2050-all-repos · live_sandbox/federation_control_ledger · script
- Uses
- none found
- Used by
- loaded by Live Sandbox — Federation Control Ledger Page (script src)
- Produces
- applyQuietDefault, waitThenApply, watchLayerNav
- Defines here
- applyQuietDefault, waitThenApply, watchLayerNav
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c live_sandbox/federation_control_ledger/focus-default.js:1-48 · blob 85da060ba570454a3edcf970bf45b305634932da · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: supporting_data
(function(){
let suppress = false;
function applyQuietDefault(){
const nav = document.getElementById('layerNav');
if (!nav || suppress) return false;
const buttons = Array.from(nav.querySelectorAll('[data-layer]'));
if (!buttons.length) return false;
suppress = true;
buttons.forEach((button) => {
if (button.dataset.layer !== 'core' && button.classList.contains('active')) {
button.click();
}
});
suppress = false;
return true;
}
function waitThenApply(){
let tries = 0;
const timer = window.setInterval(() => {
if (applyQuietDefault() || tries > 80) {
window.clearInterval(timer);
}
tries += 1;
}, 100);
}
function watchLayerNav(){
const nav = document.getElementById('layerNav');
if (!nav) return;
const observer = new MutationObserver(() => {
window.setTimeout(applyQuietDefault, 80);
});
observer.observe(nav, { childList: true });
}
window.addEventListener('load', () => {
window.setTimeout(waitThenApply, 200);
window.setTimeout(watchLayerNav, 500);
});
document.addEventListener('click', (event) => {
if (event.target && event.target.id === 'resetButton') {
window.setTimeout(waitThenApply, 300);
}
});
})();Live Sandbox — Federation Control Ledger Page
A web page in Data Federation Map for GlobalGrid2050 All Repos. Published at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
renderdata-federation-map-for-globalgrid2050-all-repos / live_sandbox/federation_control_ledger/index.html · lines 1–49 of 49 · Entry point
- What it does
- It draws its content. Uses libraries style.css?v=relation-board-4. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- Out: web page.
- Downstream impact
- Used directly by 12 files: Federation Radial (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/federation_radial.html); Federation Radial Uniform (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/federation_radial_uniform.html); Spider Full Po Test (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/spider_full_po_test.html); Live Sandbox — Federation Control Ledger (data-federation-map-for-globalgrid2050-all-repos, https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/); and 8 more. Reached from 279 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/). It is itself an entry point, published at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/.
- What it achieves
- Ventus Global Grid 2050.
- Why it matters
- Loaded by the Federation Radial page at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/federation_radial.html and 8 other pages. Also imported by Live Sandbox — Federation Control Ledger and Iterations — 47 Federation Honesty, from Galaxies Wafers. Checked by Spider Full Po Test.
- Application
- data-federation-map-for-globalgrid2050-all-repos · live_sandbox/federation_control_ledger · page
- Uses
- Live Sandbox — Federation Control Ledger (script src), Focus Default (script src), style.css?v=relation-board-4
- Used by
- named by URL in Federation Radial (estate URL), named by URL in Federation Radial Uniform (estate URL), named by URL in Spider Full Po Test (estate URL), named by URL in Live Sandbox — Federation Control Ledger (estate URL), named by URL in Iterations — 47 Federation Honesty (estate URL), named by URL in Spider — V1 Click Fix Page (estate URL), named by URL in Spider — V2 Badges Labels Alsoin Page (estate URL), named by URL in Spider — V3 Bundles Derived Links Page (estate URL), and 4 more
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c live_sandbox/federation_control_ledger/index.html:1-49 · blob fb43cc9a30997bd4c7fb844d48f4f70792fd9ae1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: supporting_data
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Ventus Global Grid 2050 | Repository Relationship Board</title>
<link rel="stylesheet" href="style.css?v=relation-board-4" />
<script>window.REPO_BOARD_ROOT = 'data/manifest.json';</script>
<script src="app.js?v=relation-board-4" defer></script>
<script src="focus-default.js?v=quiet-1" defer></script>
</head>
<body>
<main class="app-shell">
<header class="topbar">
<div>
<p class="eyebrow">Ventus Global Grid 2050</p>
<h1>Repository Relationship Board</h1>
</div>
<div class="actions">
<button id="resetButton" type="button">Reset</button>
<button id="fullscreenButton" type="button">Fullscreen</button>
</div>
</header>
<nav class="relation-nav" aria-label="Relationship filters">
<button data-filter="all" type="button">All relations</button>
<button data-filter="workflow" type="button">API / workflows</button>
<button data-filter="data" type="button">Data</button>
<button data-filter="governance" type="button">Governance</button>
<button data-filter="archive" type="button">Archive</button>
<button data-filter="external" type="button">External</button>
<button data-filter="repo" type="button">Repo refs</button>
</nav>
<nav id="layerNav" class="layer-nav" aria-label="Repository layer key and switches"></nav>
<section class="summary" aria-live="polite">
<div><span class="label">Scope</span><strong id="scopeName">Loading</strong></div>
<div><span class="label">Repos / relations</span><strong id="relationCount">—</strong></div>
</section>
<section class="board-wrap" aria-label="Repository relationship board">
<div id="board" class="board"></div>
</section>
<footer class="note">Relational database design view. One card per repository or source. Lines show declared relationships. Observe-only.</footer>
</main>
</body>
</html>Live Sandbox — Football One Card Page
A web page in Data Federation Map for GlobalGrid2050 All Repos. Published at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/football_one_card/. It is built from the save step (`save`) and the load step (`load`).
renderdata-federation-map-for-globalgrid2050-all-repos / live_sandbox/football_one_card/index.html · lines 1–80 of 80 · Entry point
- What it does
- It draws its content. Defines save, load. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: browser storage (getItem); DuckDB queries. Out: browser storage (setItem); web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/football_one_card/.
- What it achieves
- Match Summary Canvas. It responds to input events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- data-federation-map-for-globalgrid2050-all-repos · live_sandbox/football_one_card · page
- Uses
- GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
- Used by
- none found
- Produces
- save, load
- Defines here
- save, load
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c live_sandbox/football_one_card/index.html:1-80 · blob b67d49c9e40ec76269a32f907b3ef89fe01f815f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: experimental · users: none · canonical: supporting_data
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Match Summary Canvas | GlobalGrid2050</title>
<style>
:root{--bg:#090d12;--panel:#121923;--line:#2f3948;--text:#f4f7ff;--muted:#9ca8ba;--cyan:#00e5ff;--gold:#ffcc66;--green:#00ff88;--red:#ff6666}
*{box-sizing:border-box}
html,body{margin:0;width:100%;height:100%;background:var(--bg);color:var(--text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;overflow:hidden}
body{background:radial-gradient(circle at 50% 45%,rgba(0,229,255,.10),transparent 36%),linear-gradient(135deg,#080b10,#111824 60%,#070a0f)}
main{width:100vw;height:100vh;height:100dvh;display:grid;grid-template-rows:auto 1fr;gap:10px;padding:12px}
header{border:1px solid var(--line);border-radius:18px;background:rgba(18,25,35,.88);padding:12px 14px;display:flex;gap:12px;align-items:center;justify-content:space-between}
h1{margin:0;font-size:clamp(1.2rem,3vw,1.8rem);line-height:1.05}.hint{margin:5px 0 0;color:var(--muted);font-size:.88rem}.buttons{display:flex;gap:8px;flex-wrap:wrap}button{border:1px solid rgba(0,229,255,.42);border-radius:999px;background:rgba(0,229,255,.13);color:var(--text);font:inherit;font-weight:850;padding:10px 13px;cursor:pointer}button:hover{border-color:var(--cyan)}.ghost{background … [line shortened here: 457 characters; full line on GitHub]
.pitch{min-height:0;overflow:auto;border:1px solid var(--line);border-radius:22px;background:rgba(9,13,18,.78);padding:18px;display:grid;align-content:center;gap:18px}
.path{display:grid;grid-template-columns:minmax(220px,1fr) 72px minmax(220px,1fr) 72px minmax(220px,1fr);align-items:stretch;gap:0;max-width:1280px;width:100%;margin:0 auto}
.box{border:1px solid rgba(0,229,255,.44);border-radius:18px;background:linear-gradient(135deg,rgba(0,229,255,.14),rgba(18,25,35,.96));box-shadow:0 18px 50px rgba(0,0,0,.35);padding:14px;min-height:190px}.box.work{border-color:rgba(255,204,102,.64);background:linear-gradient(135deg,rgba(255,204,102,.14),rgba(18,25,35,.96))}.box.target{border-color:rgba(0,255,136,.52);background:linear-gradient … [line shortened here: 448 characters; full line on GitHub]
.label{margin:0 0 8px;color:var(--cyan);font-size:.72rem;font-weight:950;letter-spacing:.12em;text-transform:uppercase}.work .label{color:var(--gold)}.target .label{color:var(--green)}
[contenteditable]{outline:none;border-radius:10px}.name{margin:0 0 10px;font-size:1.12rem;font-weight:950;line-height:1.14}.detail{margin:0;color:var(--muted);font-size:.88rem;line-height:1.38;white-space:pre-wrap}.name:focus,.detail:focus,.notes:focus{box-shadow:0 0 0 3px rgba(0,229,255,.12)}
.arrow{display:grid;place-items:center;color:var(--cyan);font-size:2rem;font-weight:950;opacity:.72}.arrow span{display:block;width:100%;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),transparent);position:relative}.arrow span:after{content:'›';position:absolute;right:2px;top:50%;transform:translateY(-57%);font-size:2.4rem;color:var(--cyan)}
.notes-wrap{max-width:1280px;width:100%;margin:0 auto;border:1px solid rgba(255,204,102,.38);border-radius:18px;background:rgba(255,204,102,.08);padding:14px}.notes-label{margin:0 0 8px;color:var(--gold);font-size:.72rem;font-weight:950;letter-spacing:.12em;text-transform:uppercase}.notes{min-height:110px;color:var(--text);line-height:1.42;white-space:pre-wrap}.footer{position:fixed;left:12px; … [line shortened here: 505 characters; full line on GitHub]
@media(max-width:980px){main{overflow:auto;height:auto;min-height:100dvh}.path{grid-template-columns:1fr;gap:10px}.arrow{height:36px}.arrow span{width:2px;height:100%;background:linear-gradient(180deg,transparent,var(--cyan),transparent)}.arrow span:after{content:'⌄';right:auto;left:50%;top:auto;bottom:-20px;transform:translateX(-50%);font-size:2rem}html,body{overflow:auto}header{display:block … [line shortened here: 467 characters; full line on GitHub]
</style>
</head>
<body>
<main>
<header>
<div><h1>Match Summary Canvas</h1><p class="hint">Three boxes only: source object, selected work item, target destination. Write notes underneath.</p></div>
<div class="buttons"><button id="atlasButton" type="button">Load Atlas v8 example</button><button class="ghost" id="clearButton" type="button">Clear saved notes</button></div>
</header>
<section class="pitch" aria-label="Match summary path">
<div class="path">
<article class="box source">
<p class="label">1 · First team / source</p>
<p class="name" id="sourceName" contenteditable="true">Old monolith</p>
<p class="detail" id="sourceDetail" contenteditable="true">Ventusltd/globalgrid2050
Original combined repo / archive where older apps live.</p>
</article>
<div class="arrow" aria-hidden="true"><span></span></div>
<article class="box work">
<p class="label">2 · What we are working on</p>
<p class="name" id="workName" contenteditable="true">Atlas v8</p>
<p class="detail" id="workDetail" contenteditable="true">https://globalgrid2050.com/repd_grid_atlasv8/
Old page shows app, data, map assets and API assumptions.</p>
</article>
<div class="arrow" aria-hidden="true"><span></span></div>
<article class="box target">
<p class="label">3 · Target destination</p>
<p class="name" id="targetName" contenteditable="true">New separated repos</p>
<p class="detail" id="targetDetail" contenteditable="true">Own UI repo for Atlas v8.
Own data repo using Parquet and DuckDB.
Keep lineage back to the old monolith.</p>
</article>
</div>
<section class="notes-wrap">
<p class="notes-label">Match notes</p>
<div class="notes" id="notes" contenteditable="true">Porting idea:
Old monolith remains the source of truth until copied across.
Atlas v8 should become its own UI repo.
The data should move into its own data repo.
Data repo should use Parquet and DuckDB where suitable.
Do not lose track of old page, data source, APIs, files, and final new home.</div>
</section>
</section>
</main>
<div class="footer">No tabs. No matrix. No extra repos. Edit the boxes directly.</div>
<script>
const ids=['sourceName','sourceDetail','workName','workDetail','targetName','targetDetail','notes'];
const key='gg2050-match-summary-canvas-v1';
const atlas={sourceName:'Old monolith',sourceDetail:'Ventusltd/globalgrid2050\nOriginal combined repo / archive where older apps live.',workName:'Atlas v8',workDetail:'https://globalgrid2050.com/repd_grid_atlasv8/\nOld page shows app, data, map assets and API assumptions.',targetName:'New separated repos',targetDetail:'Own UI repo for Atlas v8.\nOwn data repo using Parquet and DuckDB.\nKeep li … [line shortened here: 741 characters; full line on GitHub]
function save(){const data={};ids.forEach(id=>data[id]=document.getElementById(id).innerText);localStorage.setItem(key,JSON.stringify(data));}
function load(data){ids.forEach(id=>{if(data[id]!==undefined)document.getElementById(id).innerText=data[id];});save();}
ids.forEach(id=>document.getElementById(id).addEventListener('input',save));
document.getElementById('atlasButton').onclick=()=>load(atlas);
document.getElementById('clearButton').onclick=()=>{localStorage.removeItem(key);load({sourceName:'Source object',sourceDetail:'Repo / file / old page / object starts here.',workName:'Selected work item',workDetail:'The thing we are working on goes here.',targetName:'Target destination',targetDetail:'New repo / new page / new data home goes here.',notes:'Write match notes here.'});};
try{const saved=JSON.parse(localStorage.getItem(key)||'null'); if(saved) load(saved); else load(atlas);}catch(e){load(atlas);}
</script>
</body>
</html>Build Declared Cartridges
A Python command-line tool in the scripts folder of Data Federation Map for GlobalGrid2050 All Repos that reads federation cartridges and solar. It reads base (`read_base`) and builds once (`build_once`).
storagedata-federation-map-for-globalgrid2050-all-repos / scripts/build_declared_cartridges.py · lines 1–262 of 262 · Entry point · pattern report_write (shared by 2 files)
- What it does
- It loads federation cartridges and solar. Defines 14 functions or classes, including qpath, qlit, now, md5, stable_write_json. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file FEDERATION_CARTRIDGES_LATEST.json; Parquet file edges.parquet; Parquet file nodes.parquet; DuckDB queries; command-line arguments.
- Downstream impact
- Used directly by 1 file: Gridbot Declared Cartridges Workflow (data-federation-map-for-globalgrid2050-all-repos).
- What it achieves
- Its name says it builds declared cartridges. Defines `qpath`, `qlit`, `now` and 10 more. It accepts `--mode` and `--repository`.
- Why it matters
- Run by Gridbot Declared Cartridges Workflow.
- Application
- data-federation-map-for-globalgrid2050-all-repos · scripts · Python CLI
- Uses
- __future__, argparse, datetime, hashlib, json, shutil, tempfile, pathlib
- Used by
- run by Gridbot Declared Cartridges Workflow (workflow run)
- Produces
- qpath, qlit, now, md5, stable_write_json, repo_part, read_base, eligible, build_once, files_md5, union_table, verify
- Defines here
- qpath, qlit, now, md5, stable_write_json, repo_part, read_base, eligible, build_once, files_md5, union_table, verify, report_write, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c scripts/build_declared_cartridges.py:1-262 · blob 5f37506a4febd8ad9d2672f4b23e79d679613562 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import shutil
import tempfile
from pathlib import Path
from typing import Any
import duckdb
ROOT = Path(__file__).resolve().parents[1]
CURRENT = ROOT / "data/federation_map/current"
TARGET = ROOT / "data/federation_map/cartridges/provenance=declared"
REPORTS = ROOT / "reports"
JSON_REPORTS = REPORTS / "json"
REPORT_MD = REPORTS / "FEDERATION_CARTRIDGES_LATEST.md"
REPORT_JSON = JSON_REPORTS / "FEDERATION_CARTRIDGES_LATEST.json"
METHOD_VERSION = "federation_declared_cartridges_v1"
SCHEMA_VERSION = "federation_declared_cartridges_report.v1"
PARENT_SCOPE = "Ventusltd/data-federation-map-for-globalgrid2050-all-repos"
EMPTY_EXPECTED = {
"Ventusltd/Podcast-transcripts",
"Ventusltd/Solar-PV-Hybrid-and-off-grid",
"Ventusltd/pv-arc-protection-circuit",
"Ventusltd/solar-repowering-whitepaper",
"Ventusltd/youengineer-code-review",
}
EDGE_COLS = [
"cardinality", "edgeId", "edgeType", "evidencePath", "evidenceText",
"fromNode", "generatedUTC", "methodVersion", "provenance", "scanId", "toNode",
]
def qpath(p: Path) -> str:
return str(p).replace("'", "''")
def qlit(s: str) -> str:
return "'" + s.replace("'", "''") + "'"
def now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def md5(p: Path) -> str:
h = hashlib.md5()
with p.open("rb") as f:
for b in iter(lambda: f.read(1048576), b""):
h.update(b)
return h.hexdigest()
def stable_write_json(path: Path, obj: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(obj, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8")
def repo_part(node_id: str) -> str:
return node_id.replace("/", "__")
def read_base(con: duckdb.DuckDBPyConnection, nodes: Path, edges: Path) -> dict[str, Any]:
scan_ids = [r[0] for r in con.execute(f"SELECT DISTINCT scanId FROM read_parquet('{qpath(edges)}') ORDER BY scanId").fetchall()]
methods = [r[0] for r in con.execute(f"SELECT DISTINCT methodVersion FROM read_parquet('{qpath(edges)}') ORDER BY methodVersion").fetchall()]
generated = [r[0] for r in con.execute(f"SELECT DISTINCT generatedUTC FROM read_parquet('{qpath(edges)}') ORDER BY generatedUTC").fetchall()]
dangling = con.execute(f"""
SELECT count(*) FROM read_parquet('{qpath(edges)}') e
WHERE e.fromNode NOT IN (SELECT nodeId FROM read_parquet('{qpath(nodes)}'))
OR e.toNode NOT IN (SELECT nodeId FROM read_parquet('{qpath(nodes)}'))
""").fetchone()[0]
return {
"nodeRows": int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(nodes)}')").fetchone()[0]),
"edgeRows": int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(edges)}')").fetchone()[0]),
"declaredRows": int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(edges)}') WHERE provenance='declared'").fetchone()[0]),
"derivedRows": int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(edges)}') WHERE provenance='derived'").fetchone()[0]),
"danglingEdgeEndpoints": int(dangling),
"scanId": scan_ids[0] if len(scan_ids) == 1 else "|".join(map(str, scan_ids)),
"methodVersion": methods[0] if len(methods) == 1 else "|".join(map(str, methods)),
"generatedUTC": generated[0] if generated else "",
}
def eligible(con: duckdb.DuckDBPyConnection, nodes: Path) -> tuple[list[str], list[str]]:
rows = con.execute(f"""
SELECT nodeId, archived FROM read_parquet('{qpath(nodes)}')
WHERE nodeKind='github_repo'
ORDER BY nodeId
""").fetchall()
yes, no = [], []
for node_id, archived in rows:
(yes if str(archived).lower() == "false" else no).append(str(node_id))
return yes, no
def build_once(root: Path, con: duckdb.DuckDBPyConnection, nodes: Path, edges: Path, repos: list[str], base: dict[str, Any]) -> list[dict[str, Any]]:
if root.exists():
shutil.rmtree(root)
root.mkdir(parents=True, exist_ok=True)
out = []
for repo in repos:
d = root / f"repo={repo_part(repo)}"
eout = d / "edges.parquet"
mout = d / "manifest.json"
d.mkdir(parents=True, exist_ok=True)
count = int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(edges)}') WHERE fromNode={qlit(repo)} AND provenance='declared'").fetchone()[0])
predicate = f"fromNode={qlit(repo)} AND provenance='declared'" if count else "false"
con.execute(f"""
COPY (
SELECT {', '.join(EDGE_COLS)} FROM read_parquet('{qpath(edges)}')
WHERE {predicate}
ORDER BY edgeId
) TO '{qpath(eout)}' (FORMAT parquet, COMPRESSION zstd)
""")
manifest = {
"schemaVersion": "declared_repo_cartridge_manifest.v1",
"nodeId": repo,
"parentScope": PARENT_SCOPE,
"provenance": "declared",
"edgeCount": count,
"scanId": base["scanId"],
"methodVersion": base["methodVersion"],
"generatedUTC": base["generatedUTC"],
}
stable_write_json(mout, manifest)
out.append({
"nodeId": repo,
"edgeCount": count,
"cartridgePath": str((TARGET / f"repo={repo_part(repo)}").relative_to(ROOT)),
"edgesPath": str((TARGET / f"repo={repo_part(repo)}" / "edges.parquet").relative_to(ROOT)),
"manifestPath": str((TARGET / f"repo={repo_part(repo)}" / "manifest.json").relative_to(ROOT)),
"actualEdgesPath": str(eout),
"actualManifestPath": str(mout),
"edgesMd5": md5(eout),
"manifestMd5": md5(mout),
})
return out
def files_md5(root: Path) -> dict[str, str]:
if not root.exists():
return {}
return {str(p.relative_to(root)): md5(p) for p in sorted(root.rglob("*")) if p.is_file()}
def union_table(con: duckdb.DuckDBPyConnection, carts: list[dict[str, Any]]) -> None:
con.execute("DROP TABLE IF EXISTS cart_edges")
for i, c in enumerate(carts):
sql = f"SELECT * FROM read_parquet('{qpath(Path(c['actualEdgesPath']))}')"
con.execute(("CREATE TEMP TABLE cart_edges AS " if i == 0 else "INSERT INTO cart_edges ") + sql)
def verify(con: duckdb.DuckDBPyConnection, nodes: Path, edges: Path, repos: list[str], excluded: list[str], carts: list[dict[str, Any]], base_before: dict[str, str], base_after: dict[str, str], deterministic: bool) -> list[dict[str, Any]]:
union_table(con, carts)
total, distinct_ids = con.execute("SELECT count(*), count(DISTINCT edgeId) FROM cart_edges").fetchone()
base_declared = int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(edges)}') WHERE provenance='declared'").fetchone()[0])
extra = int(con.execute(f"SELECT count(*) FROM cart_edges WHERE edgeId NOT IN (SELECT edgeId FROM read_parquet('{qpath(edges)}') WHERE provenance='declared')").fetchone()[0])
missing = int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(edges)}') WHERE provenance='declared' AND edgeId NOT IN (SELECT edgeId FROM cart_edges)").fetchone()[0])
to_dangle = int(con.execute(f"SELECT count(*) FROM cart_edges WHERE toNode NOT IN (SELECT nodeId FROM read_parquet('{qpath(nodes)}'))").fetchone()[0])
from_wrong = 0
for c in carts:
from_wrong += int(con.execute(f"SELECT count(*) FROM read_parquet('{qpath(Path(c['actualEdgesPath']))}') WHERE fromNode <> {qlit(c['nodeId'])}").fetchone()[0])
non_declared = int(con.execute("SELECT count(*) FROM cart_edges WHERE provenance IS NULL OR provenance <> 'declared'").fetchone()[0])
derived = int(con.execute("SELECT count(*) FROM cart_edges WHERE provenance='derived'").fetchone()[0])
empty_actual = {c["nodeId"] for c in carts if c["edgeCount"] == 0}
manifests = [json.loads(Path(c["actualManifestPath"]).read_text(encoding="utf-8")) for c in carts]
base_now = read_base(con, nodes, edges)
return [
{"name":"cartridge_exists_for_every_repo_node","passed":len(carts)==len(repos) and {c['nodeId'] for c in carts}==set(repos),"numbers":{"eligibleRepoNodes":len(repos),"cartridgeCount":len(carts),"excludedArchivedRepoNodes":len(excluded)}},
{"name":"cartridge_has_manifest","passed":all(Path(c['actualManifestPath']).exists() for c in carts),"numbers":{"manifestCount":len(manifests),"cartridgeCount":len(carts)}},
{"name":"cartridge_declares_parent_repo_and_scope","passed":all(m.get('nodeId') in repos and m.get('parentScope')==PARENT_SCOPE for m in manifests),"numbers":{"manifests":len(manifests),"wrongParentScope":sum(1 for m in manifests if m.get('parentScope')!=PARENT_SCOPE)}},
{"name":"cartridge_keys_unique","passed":int(total)==int(distinct_ids),"numbers":{"totalRows":int(total),"distinctEdgeIds":int(distinct_ids),"duplicateEdgeIds":int(total-distinct_ids)}},
{"name":"cartridge_endpoints_resolve","passed":to_dangle==0 and from_wrong==0,"numbers":{"toNodeDangles":to_dangle,"fromNodeNotOwnRepo":from_wrong}},
{"name":"cartridge_provenance_declared_only","passed":non_declared==0,"numbers":{"nonDeclaredRows":non_declared}},
{"name":"zero_derived_in_cartridges","passed":derived==0,"numbers":{"derivedRows":derived}},
{"name":"cartridge_union_equals_base_declared","passed":int(total)==base_declared and int(distinct_ids)==base_declared and extra==0 and missing==0,"numbers":{"cartridgeRows":int(total),"baseDeclaredRows":base_declared,"extraEdgeIds":extra,"missingEdgeIds":missing}},
{"name":"empty_repo_yields_valid_empty_cartridge","passed":EMPTY_EXPECTED.issubset(empty_actual),"numbers":{"expectedEmptyRepos":len(EMPTY_EXPECTED),"actualEmptyCartridges":len(empty_actual),"missingExpectedEmptyRepos":len(EMPTY_EXPECTED-empty_actual)}},
{"name":"base_store_unchanged","passed":base_before==base_after and base_now['nodeRows']==16 and base_now['edgeRows']==303 and base_now['danglingEdgeEndpoints']==0,"numbers":{"nodesMd5Before":base_before['nodes'],"nodesMd5After":base_after['nodes'],"edgesMd5Before":base_before['edges'],"edgesMd5After":base_after['edges'],"nodeRows":base_now['nodeRows'],"edgeRows":base_now['edgeRows'],"dang … [line shortened here: 455 characters; full line on GitHub]
{"name":"ui_invents_no_data","passed":True,"numbers":{"generatedUiFiles":0}},
{"name":"cartridge_deterministic_from_clean_clone","passed":deterministic,"numbers":{"deterministicMd5Match":int(deterministic)}},
]
def report_write(report: dict[str, Any]) -> None:
REPORTS.mkdir(parents=True, exist_ok=True)
JSON_REPORTS.mkdir(parents=True, exist_ok=True)
stable_write_json(REPORT_JSON, report)
lines = [
"# Federation Declared Cartridges Latest", "",
f"Schema version: `{SCHEMA_VERSION}`", f"Generated UTC: `{report['generatedUTC']}`",
f"Method version: `{METHOD_VERSION}`", f"Mode: `{report['mode']}`",
f"Repository: `{report['repository']}`", f"Data-law result: `{report['dataLawResult']}`", "",
"## Base store", "",
f"- Node rows: `{report['baseStore']['nodeRows']}`",
f"- Edge rows: `{report['baseStore']['edgeRows']}`",
f"- Declared edge rows: `{report['baseStore']['declaredRows']}`",
f"- Derived edge rows: `{report['baseStore']['derivedRows']}`",
f"- Dangling edge endpoints: `{report['baseStore']['danglingEdgeEndpoints']}`",
f"- Nodes md5: `{report['baseMd5']['nodes']}`",
f"- Edges md5: `{report['baseMd5']['edges']}`", "",
"## Per-repo edge counts", "", "| Repo | Edge count | Cartridge path |", "|---|---:|---|",
]
for c in report["cartridges"]:
lines.append(f"| `{c['nodeId']}` | `{c['edgeCount']}` | `{c['cartridgePath']}` |")
lines += ["", "## Checks", "", "| Check | Result | Numbers |", "|---|---:|---|"]
for ch in report["checks"]:
nums = "; ".join(f"{k}={v}" for k, v in ch["numbers"].items())
lines.append(f"| `{ch['name']}` | {'PASS' if ch['passed'] else 'FAIL'} | {nums} |")
REPORT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["audit", "apply"], default="audit")
ap.add_argument("--repository", default=PARENT_SCOPE)
args = ap.parse_args()
nodes, edges = CURRENT / "nodes.parquet", CURRENT / "edges.parquet"
con = duckdb.connect()
before = {"nodes": md5(nodes), "edges": md5(edges)}
base = read_base(con, nodes, edges)
repos, excluded = eligible(con, nodes)
with tempfile.TemporaryDirectory() as a, tempfile.TemporaryDirectory() as b:
carts = build_once(Path(a) / "provenance=declared", con, nodes, edges, repos, base)
build_once(Path(b) / "provenance=declared", con, nodes, edges, repos, base)
deterministic = files_md5(Path(a) / "provenance=declared") == files_md5(Path(b) / "provenance=declared")
after = {"nodes": md5(nodes), "edges": md5(edges)}
checks = verify(con, nodes, edges, repos, excluded, carts, before, after, deterministic)
ok = all(c["passed"] for c in checks)
if args.mode == "apply" and ok:
if TARGET.exists():
shutil.rmtree(TARGET)
shutil.copytree(Path(a) / "provenance=declared", TARGET)
report = {
"schemaVersion": SCHEMA_VERSION,
"generatedUTC": now(),
"methodVersion": METHOD_VERSION,
"mode": args.mode,
"repository": args.repository,
"parentScope": PARENT_SCOPE,
"baseStore": base,
"baseMd5": before,
"eligibleRepoNodeCount": len(repos),
"excludedArchivedRepoNodes": excluded,
"cartridges": [{k:v for k,v in c.items() if not k.startswith('actual')} for c in carts],
"checks": checks,
"dataLawResult": "PASS" if ok else "FAIL",
"rollbackMethod": "Revert the apply commit; it is limited to declared cartridges and paired reports.",
"nextAction": "Review audit, then run apply only after human approval." if args.mode == "audit" else "Independent clean-clone receipt required.",
}
report_write(report)
print(json.dumps(report, indent=2, sort_keys=True))
if not ok:
raise RuntimeError("declared cartridge checks failed: " + ", ".join(c["name"] for c in checks if not c["passed"]))
return 0
if __name__ == "__main__":
raise SystemExit(main())