Hugdrigo's picture
Upload 3 files
9854b61 verified
Raw History Blame Contribute Delete
46.2 kB
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="description" content="MilestoneIQ: Project schedule, critical path and risk intelligence"><title>MilestoneIQ | Project Delivery Intelligence Studio</title><style>:root{color-scheme:dark;--bg:#080e18;--side:#0d1624;--panel:#121e2d;--panel2:#172637;--line:#26394b;--muted:#93a6b7;--ink:#e9f5f2;--accent:#70e1b5;--sky:#69bcf8;--orange:#f6ba73;--red:#ff8284;--purple:#bba8ff;--shadow:0 10px 28px #020a1240}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;line-height:1.5}button,input,select{font:inherit}button{cursor:pointer}button:disabled{opacity:.5;cursor:not-allowed}a{color:var(--sky)}.layout{display:flex;min-height:100vh}.sidebar{width:252px;position:sticky;top:0;height:100vh;flex-shrink:0;background:var(--side);border-right:1px solid var(--line);padding:28px 15px;display:flex;flex-direction:column;gap:24px;z-index:10}.brand{display:flex;gap:10px;align-items:center;padding:0 10px}.brandmark{width:38px;height:38px;display:grid;place-items:center;background:#144b45;color:var(--accent);font-size:22px;border:1px solid #2d7768;border-radius:12px}.brand h1{font-size:19px;line-height:1;margin:0}.brand small{font-size:10px;color:var(--accent);letter-spacing:.16em;font-weight:750}.nav{display:flex;flex-direction:column;gap:5px}.nav button{background:none;border:1px solid transparent;color:#9bafbf;border-radius:10px;display:flex;align-items:center;gap:12px;padding:12px 13px;text-align:left;font-weight:600;width:100%}.nav button:hover{background:#1c2a38;color:white}.nav button.active{background:#18332f;border-color:#315b4e;color:#9df2cd}.nav .symbol{font-size:18px;width:20px;text-align:center}.sidebarfoot{margin-top:auto;color:#859cac;font-size:11px;border-top:1px solid var(--line);padding:18px 8px 0}.chip{color:#8bf4ce;background:#123c34;border:1px solid #286453;border-radius:7px;padding:4px 8px;font-size:10px;font-weight:800;letter-spacing:.06em}.main{min-width:0;flex:1;padding:29px 35px 65px;max-width:1700px;margin:0 auto}.top{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:29px}.eyebrow{color:var(--accent);font-size:11px;font-weight:800;letter-spacing:.16em;text-transform:uppercase}.top h2{font-size:30px;line-height:1.15;letter-spacing:-.035em;margin:6px 0 9px}.subtitle{color:var(--muted);max-width:790px;margin:0}.topright{display:flex;align-items:center;gap:8px}.button{background:#214b40;border:1px solid #42866c;color:#dcfff0;padding:10px 14px;border-radius:9px;font-size:12px;font-weight:750}.button:hover{filter:brightness(1.17)}.button.secondary{background:#1b2b3d;border-color:#34506a;color:#d0e5f6}.button.minor{padding:7px 10px}.section-title{display:flex;justify-content:space-between;gap:12px;align-items:center;margin-bottom:15px}.section-title h3{font-size:16px;margin:0;letter-spacing:-.015em}.section-title .hint{font-size:12px;color:var(--muted)}.controlstrip{display:flex;align-items:end;gap:13px;flex-wrap:wrap;margin-bottom:22px}.controlstrip label,.form-field{display:flex;flex-direction:column;gap:7px;color:#a9bbca;font-size:11px;font-weight:700}.controlstrip input,.controlstrip select,.form-field input,.form-field select{background:#111e2c;color:var(--ink);border:1px solid #35475a;border-radius:9px;padding:10px 12px;outline:none;min-width:130px;max-width:100%}.controlstrip input:focus,.controlstrip select:focus{border-color:var(--accent)}.controlstrip .grow{flex:1}.card{background:var(--panel);border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow);padding:20px;min-width:0}.cards{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:17px}.metric{padding:19px 19px 17px;min-height:124px}.metric .m-label{color:var(--muted);font-size:11px;font-weight:700}.metric .value{font-size:32px;font-weight:820;letter-spacing:-.035em;margin:11px 0 4px;line-height:1}.metric .foot{font-size:11px;color:#b1c1cc}.green{color:var(--accent)}.red{color:var(--red)}.blue{color:var(--sky)}.amber{color:var(--orange)}.cols{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(280px,1fr);gap:16px;margin-bottom:17px}.cols.equal{grid-template-columns:repeat(2,minmax(0,1fr))}.chart{width:100%;height:auto;display:block}.chart-label{fill:#8fa6b6;font:11px system-ui}.chart-line{stroke:#365167;stroke-width:1}.legend{display:flex;align-items:center;gap:15px;flex-wrap:wrap;margin:13px 0 0;color:#a9bbca;font-size:11px}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:5px}.progress{height:8px;border-radius:99px;background:#263b47;overflow:hidden}.progress>i{display:block;height:100%;background:var(--accent);border-radius:99px}.small{font-size:11px;color:var(--muted)}.muted{color:var(--muted)}.summary{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:13px 0;border-bottom:1px solid #24384a}.summary:last-child{border:0}.summary strong{font-size:14px}.summary small{color:var(--muted)}.pill{font-size:10px;font-weight:750;padding:4px 8px;border-radius:20px;background:#20384a;color:#a9cbe0;white-space:nowrap}.pill.hot{color:#ffb7a8;background:#552c36}.pill.good{color:#a1f3d0;background:#23443d}.scroll{overflow:auto;width:100%;scrollbar-color:#46657a transparent}table{border-collapse:collapse;width:100%;font-size:12px;min-width:640px}th{text-align:left;background:#152536;color:#b2c7d4;font-size:10px;font-weight:800;letter-spacing:.04em}td,th{padding:12px 11px;border-bottom:1px solid #283848}td{color:#cbdce5}tr:last-child td{border:0}.table-id{color:var(--accent);font-weight:800}.heading-note{margin:0 0 16px;color:var(--muted);font-size:12px}.callout{border:1px solid #446557;background:#152d2a;border-radius:10px;padding:13px 16px;color:#d1eadd;font-size:12px;margin-top:17px}.callout.warning{border-color:#71553a;background:#30271f;color:#e8d5b8}.bad{color:#ff9f9f}.mono{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:11px}.graph-scroller{width:100%;overflow:auto;border-radius:10px;background:radial-gradient(circle at 50% 10%,#20364a55,transparent 70%),#0f1b28;border:1px solid #2a4050;padding:12px}.graph-scroller svg{min-width:700px;display:block;width:100%;height:auto}.grid3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px;margin-bottom:17px}.axis-key{font-size:11px;fill:#9eb4bf}.progressrow{margin:13px 0}.progressrow .above{display:flex;justify-content:space-between;gap:5px;color:#c3d4dd;margin-bottom:7px;font-size:12px}.empty{padding:24px;text-align:center;color:var(--muted)}.two-actions{display:flex;gap:9px;flex-wrap:wrap}.download-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.download-grid button{background:#1b3043;border:1px solid #35546c;border-radius:10px;color:#d0e5f2;text-align:left;padding:15px;font-weight:750}.download-grid button:hover{border-color:var(--accent)}.download-grid small{display:block;color:#9eb5c4;font-weight:400;margin-top:6px}.upload{border:1px dashed #587185;border-radius:12px;padding:23px;background:#132536;text-align:center}.upload input{max-width:250px}.subnav{display:none}.footer-note{font-size:11px;color:#8194a7;margin-top:24px}.hover-tip{cursor:help;border-bottom:1px dotted #6a8593}.toast{position:fixed;bottom:22px;right:22px;max-width:min(480px,calc(100vw - 24px));background:#204b3b;border:1px solid #60b38e;color:#eafff4;padding:12px 18px;border-radius:10px;box-shadow:var(--shadow);z-index:40}.toast.err{background:#55232d;border-color:#d46872}.hide{display:none!important}.desc{color:#94abbb;font-size:12px;max-width:790px}.stat-split{display:flex;justify-content:space-between;gap:12px;border-top:1px solid #294053;padding:12px 0;color:#b9cad5}.stat-split b{color:#e9f5f2}.num{font-variant-numeric:tabular-nums}.hamburger{display:none}.mobile-overlay{display:none}.mini-tag{font-size:10px;color:#9fcdbd;text-transform:uppercase;letter-spacing:.05em}.feature-note{margin-top:12px;border-top:1px solid #2b3e4c;padding-top:11px}.ring{border-radius:50%;width:11px;height:11px;border:2px solid var(--accent);display:inline-block}
@media(max-width:1150px){.cards{grid-template-columns:repeat(2,minmax(0,1fr))}.cols{grid-template-columns:1fr}.grid3{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:800px){.sidebar{transform:translateX(-110%);transition:transform .2s;position:fixed;box-shadow:0 0 30px #0008}.sidebar.open{transform:translateX(0)}.mobile-overlay.on{display:block;position:fixed;inset:0;background:#0008;z-index:9}.main{padding:20px 15px 45px}.hamburger{display:block;background:#1c2d3c;color:white;border:1px solid #3b5063;padding:9px 12px;border-radius:9px}.top{align-items:start}.top h2{font-size:25px}.topright{flex-shrink:0}.topright .button{display:none}.cards{gap:10px}.metric{min-height:106px;padding:15px}.metric .value{font-size:25px}.card{padding:16px}.grid3,.cols.equal,.download-grid{grid-template-columns:1fr}.controlstrip{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-items:end}.controlstrip label{min-width:0}.controlstrip input,.controlstrip select{width:100%;min-width:0}.controlstrip .grow{grid-column:1/-1}.controlstrip .button{grid-column:1/-1}.section-title{align-items:start}.graph-scroller svg{width:850px;min-width:850px}.top .subtitle{font-size:12px}}
@media(max-width:390px){.metric .value{font-size:23px}.controlstrip{grid-template-columns:1fr}}
</style></head><body><div class="mobile-overlay" id="overlay"></div><div class="layout"><aside class="sidebar" id="sidebar"><div class="brand"><div class="brandmark">◈</div><div><h1>MilestoneIQ</h1><small>DELIVERY INTELLIGENCE</small></div></div><div class="nav" id="nav"></div><div class="sidebarfoot"><span class="chip">LOCAL-FIRST · v1.0</span><p>Transparent project forecasting with no backend, API keys, or external dependencies.</p><p>© 2026 · Synthetic demonstration datasets</p></div></aside><main class="main"><header class="top"><div><div class="eyebrow">PROJECT #58 / INTELLIGENCE STUDIO</div><h2 id="page-title">Command Center</h2><p id="page-subtitle" class="subtitle">Project scheduling, probabilistic delivery risk and transparent decisions.</p></div><div class="topright"><button id="menu" class="hamburger" aria-label="Open navigation">☰</button><span class="chip">STATIC SPACE</span></div></header><div id="controls"></div><div id="content"></div><div class="footer-note">Model: Critical Path Method, Beta-PERT Monte Carlo and a greedy acceleration heuristic. Synthetic examples are educational; outputs are not project guarantees or actual prices.</div></main></div><div class="toast hide" id="toast" role="status"></div><script>(function(global){'use strict';
const E={};
const round=(n,p=2)=>Math.round((n+Number.EPSILON)*10**p)/10**p;
E.round=round;
E.mean=t=>(t.a+4*t.m+t.b)/6;
E.variance=t=>Math.pow((t.b-t.a)/6,2);
E.validate=tasks=>{
if(!Array.isArray(tasks)||tasks.length<2||tasks.length>40)throw Error('Provide 2 to 40 tasks.');
const ids=new Set();
for(const t of tasks){
if(!/^[A-Za-z0-9_-]{1,20}$/.test(String(t.id)))throw Error('Task IDs must be unique, 1–20 letters, numbers, _ or -.');
if(ids.has(t.id))throw Error('Duplicate task ID: '+t.id);ids.add(t.id);
if(typeof t.name!=='string'||!t.name.trim()||t.name.length>90)throw Error('Task name missing or too long.');
if(typeof t.phase!=='string'||!t.phase.trim()||t.phase.length>35)throw Error('Task phase missing or too long.');
if(![t.a,t.m,t.b,t.cost,t.crashMax,t.crashRate].every(v=>Number.isFinite(v)))throw Error('All numerical fields must be finite.');
if(t.a<0.1||t.a>t.m||t.m>t.b||t.b>365||t.cost<0||t.cost>1e9||!Number.isInteger(t.crashMax)||t.crashMax<0||t.crashMax>5||t.crashRate<0||t.crashRate>1e8)throw Error('Invalid PERT estimates, cost or acceleration values.');
if(!Array.isArray(t.deps)||t.deps.length>10||new Set(t.deps).size!==t.deps.length)throw Error('Invalid predecessor list.');
if(t.crashMax>Math.floor(E.mean(t)*10)/10-.1 && t.crashMax>0)throw Error('Acceleration exceeds baseline duration: '+t.id);
}
for(const t of tasks)for(const d of t.deps)if(!ids.has(d)||d===t.id)throw Error('Unknown or self-referencing predecessor in '+t.id);
E.order(tasks); return true;
};
E.order=tasks=>{
const m=new Map(tasks.map(t=>[t.id,t]));const indeg=new Map(tasks.map(t=>[t.id,t.deps.length]));const child=new Map(tasks.map(t=>[t.id,[]]));
tasks.forEach(t=>t.deps.forEach(d=>{if(!child.has(d))throw Error('Unknown predecessor: '+d);child.get(d).push(t.id);}));
const q=tasks.filter(t=>indeg.get(t.id)===0).map(t=>t.id),o=[];
while(q.length){const id=q.shift();o.push(m.get(id));for(const c of child.get(id)){indeg.set(c,indeg.get(c)-1);if(indeg.get(c)===0)q.push(c);}}
if(o.length!==tasks.length)throw Error('Circular dependency detected.');return o;
};
E.schedule=(tasks,durations)=>{
const order=E.order(tasks), byId=new Map(order.map(t=>[t.id,t]));const successors=new Map(tasks.map(t=>[t.id,[]]));
for(const t of tasks)for(const d of t.deps)successors.get(d).push(t.id);
const rec=new Map();
for(const t of order){const duration=durations&&durations[t.id]!==undefined?durations[t.id]:E.mean(t);if(!Number.isFinite(duration)||duration<0)throw Error('Invalid task duration.');const es=t.deps.length?Math.max(...t.deps.map(id=>rec.get(id).ef)):0;rec.set(t.id,{...t,es,ef:es+duration,duration});}
const total=Math.max(...Array.from(rec.values(),r=>r.ef));
for(const t of [...order].reverse()){const r=rec.get(t.id),next=successors.get(t.id),lf=next.length?Math.min(...next.map(id=>rec.get(id).ls)):total;r.lf=lf;r.ls=lf-r.duration;r.slack=Math.max(0,r.ls-r.es);r.critical=Math.abs(r.ls-r.es)<1e-7;}
const rows=tasks.map(t=>rec.get(t.id));let path=[];const criticalEnds=rows.filter(r=>r.critical&&Math.abs(r.ef-total)<1e-7);if(criticalEnds.length){let cur=criticalEnds[0];while(cur){path.unshift(cur.id);cur=cur.deps.map(id=>rec.get(id)).find(r=>r.critical&&Math.abs(r.ef-cur.es)<1e-7);}}
return{total,rows,criticalPath:path,criticalCount:rows.filter(r=>r.critical).length,meanCost:tasks.reduce((s,t)=>s+t.cost,0)};
};
E.rng=seed=>{let a=(seed>>>0)||1;return()=>{a=(a+0x6D2B79F5)|0;let t=Math.imul(a^a>>>15,1|a);t^=t+Math.imul(t^t>>>7,61|t);return ((t^t>>>14)>>>0)/4294967296;};};
E.normal=rand=>Math.sqrt(-2*Math.log(Math.max(1e-12,rand())))*Math.cos(2*Math.PI*rand());
E.gamma=(shape,rand)=>{if(shape<1)return E.gamma(shape+1,rand)*Math.pow(Math.max(1e-12,rand()),1/shape);const d=shape-1/3,c=1/Math.sqrt(9*d);for(let i=0;i<1000;i++){const x=E.normal(rand),v=1+c*x;if(v<=0)continue;const v3=v*v*v,u=rand();if(u<1-0.0331*x*x*x*x||Math.log(Math.max(1e-12,u))<.5*x*x+d*(1-v3+Math.log(v3)))return d*v3;}return shape;};
E.samplePERT=(t,rand)=>{if(Math.abs(t.b-t.a)<1e-12)return t.a;const alpha=1+4*(t.m-t.a)/(t.b-t.a),beta=1+4*(t.b-t.m)/(t.b-t.a);const x=E.gamma(alpha,rand),y=E.gamma(beta,rand);return t.a+(t.b-t.a)*x/(x+y);};
E.quantile=(sorted,p)=>{if(!sorted.length)return NaN;const i=(sorted.length-1)*p,k=Math.floor(i),f=i-k;return sorted[k]+(sorted[Math.min(sorted.length-1,k+1)]-sorted[k])*f;};
E.simulate=(tasks,{runs=600,seed=1103,deadline=35}={})=>{
E.validate(tasks);if(!Number.isInteger(runs)||runs<20||runs>3000)throw Error('Invalid trial count.');const rand=E.rng(seed),durations=[],hits=Object.fromEntries(tasks.map(t=>[t.id,0]));let exceed=0,sum=0;
for(let i=0;i<runs;i++){
const ds=Object.fromEntries(tasks.map(t=>[t.id,E.samplePERT(t,rand)]));const sc=E.schedule(tasks,ds);durations.push(sc.total);sum+=sc.total;if(sc.total>deadline+1e-9)exceed++;for(const r of sc.rows)if(r.critical)hits[r.id]++;
}
const sorted=[...durations].sort((a,b)=>a-b),avg=sum/runs,sd=Math.sqrt(durations.reduce((s,d)=>s+(d-avg)**2,0)/runs);
const bins=Array.from({length:18},(_,i)=>({i,n:0})),min=sorted[0],max=sorted[sorted.length-1];for(const v of durations){let ix=max===min?0:Math.min(17,Math.floor((v-min)/(max-min)*18));bins[ix].n++;}
return{runs,seed,deadline,avg,sd,p10:E.quantile(sorted,.1),p50:E.quantile(sorted,.5),p80:E.quantile(sorted,.8),p90:E.quantile(sorted,.9),p95:E.quantile(sorted,.95),chance:exceed/runs,criticality:tasks.map(t=>({id:t.id,name:t.name,prob:hits[t.id]/runs})),bins:bins.map(b=>({n:b.n,from:min+(max-min)*b.i/18,to:min+(max-min)*(b.i+1)/18})),samples:durations};
};
E.accelerate=(tasks,budget=12000,target=30)=>{
E.validate(tasks);if(!Number.isFinite(budget)||budget<0)throw Error('Invalid budget.');const base=E.schedule(tasks),crashed=Object.fromEntries(tasks.map(t=>[t.id,0]));let spent=0,steps=[];
const calc=()=>E.schedule(tasks,Object.fromEntries(tasks.map(t=>[t.id,Math.max(.1,E.mean(t)-crashed[t.id])])));
let current=calc();for(let k=0;k<tasks.length*5;k++){
if(current.total<=target+1e-8)break;
let candidates=[];
for(const t of tasks){if(crashed[t.id]>=t.crashMax||spent+t.crashRate>budget+1e-6||E.mean(t)-crashed[t.id]<=1.1)continue;crashed[t.id]++;const next=calc(),gain=current.total-next.total;crashed[t.id]--;candidates.push({t,next,gain});}
candidates=candidates.filter(c=>c.gain>1e-8).sort((a,b)=> (a.t.crashRate/a.gain)-(b.t.crashRate/b.gain)||b.gain-a.gain);
if(!candidates.length)break;const best=candidates[0];crashed[best.t.id]++;spent+=best.t.crashRate;current=best.next;steps.push({id:best.t.id,name:best.t.name,days:crashed[best.t.id],cost:best.t.crashRate,duration:current.total});
}
return{base:base.total,newDuration:current.total,daysSaved:base.total-current.total,spent,remaining:Math.max(0,budget-spent),steps,crashed,met:current.total<=target+1e-8,method:'Greedy one-day reductions on the current critical path; not globally optimal.'};
};
E.parseCSV=text=>{
if(typeof text!=='string'||text.length>200000)throw Error('CSV exceeds 200 KB.');const rows=[];let row=[],cell='',q=false,ended=false;let s=text.replace(/^\uFEFF/,'');
for(let i=0;i<s.length;i++){let c=s[i];if(ended){if(c===','){row.push(cell);cell='';ended=false;}else if(c==='\n'||c==='\r'){row.push(cell);rows.push(row);row=[];cell='';ended=false;if(c==='\r'&&s[i+1]==='\n')i++;}else throw Error('Unexpected characters after closing quote.');}
else if(q){if(c==='"'){if(s[i+1]==='"'){cell+='"';i++;}else{q=false;ended=true;}}else cell+=c;}
else if(c==='"'){if(cell!=='')throw Error('Unexpected quote in unquoted field.');q=true;}
else if(c===','){row.push(cell);cell='';}else if(c==='\n'||c==='\r'){row.push(cell);rows.push(row);row=[];cell='';if(c==='\r'&&s[i+1]==='\n')i++;}else cell+=c;
}
if(q)throw Error('Unclosed quoted CSV field.');if(ended||row.length||cell.length){row.push(cell);rows.push(row);}return rows.filter(r=>r.some(x=>x.trim()));
};
E.fromCSV=text=>{
const rows=E.parseCSV(text),headers=rows.shift();const expected=['id','name','phase','deps','a','m','b','cost','crashMax','crashRate'];
if(!headers||headers.length!==expected.length||!expected.every((x,i)=>headers[i].trim()===x))throw Error('CSV headers must be: '+expected.join(', '));
const tasks=rows.map((r,i)=>{if(r.length!==headers.length)throw Error('Wrong number of fields at row '+(i+2));for(const cell of r.slice(4))if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(cell.trim()))throw Error('Missing or invalid numeric field at row '+(i+2));return{id:r[0].trim(),name:r[1].trim(),phase:r[2].trim(),deps:r[3].trim()?r[3].split('|').map(d=>d.trim()):[],a:Number(r[4]),m:Number(r[5]),b:Number(r[6]),cost:Number(r[7]),crashMax:Number(r[8]),crashRate:Number(r[9])};});
E.validate(tasks);return tasks;
};
E.csvField=(v,kind='string')=>{let s=String(v??'');if(kind!=='number'&&/^[\s]*[=+\-@\t\r]/.test(s))s="'"+s;return '"'+s.replace(/"/g,'""')+'"';};
E.toCSV=(headers,rows,kinds={})=>[headers.map(h=>E.csvField(h)).join(','),...rows.map(r=>headers.map(h=>E.csvField(r[h],kinds[h]||'string')).join(','))].join('\r\n');
E.taskCSV=tasks=>E.toCSV(['id','name','phase','deps','a','m','b','cost','crashMax','crashRate'],tasks.map(t=>({...t,deps:t.deps.join('|')})),{a:'number',m:'number',b:'number',cost:'number',crashMax:'number',crashRate:'number'});
E.demos=[
{key:'solar',label:'Solar Microgrid',description:'Distributed energy installation',deadline:45,budget:12000,tasks:[
['S01','Feasibility assessment','Design','',3,5,8,4500,1,1100],['S02','Permits & approvals','Compliance','S01',5,8,14,6800,2,2200],['S03','Grid connection design','Design','S01',4,6,10,7200,2,1700],['S04','Procurement','Supply','S03',8,11,17,19500,3,2100],['S05','Civil works','Build','S02',5,8,12,14300,2,2600],['S06','Equipment delivery','Supply','S04',4,7,13,5800,2,1900],['S07','Electrical installation','Build','S05|S06',6,9,14,21000,3,3100],['S08','Safety inspection','Compliance','S07',2,4,7,3900,1,900],['S09','Commissioning','Launch','S08',3,5,9,6700,2,1300],['S10','Training & handover','Launch','S09',2,3,5,2200,1,600]]},
{key:'research',label:'Research Consortium',description:'Cross-border academic research program',deadline:42,budget:8000,tasks:[
['R01','Research design','Design','',4,6,9,3800,1,1000],['R02','Ethics approval','Compliance','R01',5,8,13,2400,1,950],['R03','Instrument development','Design','R01',4,7,10,4200,2,1200],['R04','Partner agreements','Coordination','R01',3,6,11,2900,2,1100],['R05','Pilot interviews','Fieldwork','R02|R03',3,5,8,3200,1,700],['R06','Field recruitment','Fieldwork','R04|R05',5,8,13,6000,2,1700],['R07','Data collection','Fieldwork','R06',7,11,17,9800,3,2250],['R08','Transcription','Analysis','R07',4,6,10,3500,2,850],['R09','Coding & synthesis','Analysis','R08',5,8,13,5100,2,1400],['R10','Report & dissemination','Delivery','R09',4,6,9,2800,1,950]]},
{key:'product',label:'Product Release',description:'Enterprise software go-to-market',deadline:33,budget:9500,tasks:[
['P01','Discovery & requirements','Strategy','',3,5,8,5500,1,1200],['P02','Interface design','Build','P01',4,6,9,4800,2,900],['P03','API specification','Build','P01',3,5,9,4500,1,1250],['P04','Backend implementation','Build','P03',6,9,14,11400,3,1500],['P05','Frontend implementation','Build','P02',6,8,13,9100,2,1800],['P06','Security review','Quality','P04',3,5,9,5300,2,1400],['P07','Integration QA','Quality','P04|P05',5,8,12,7600,2,1750],['P08','Pilot customers','Launch','P06|P07',4,6,10,4400,2,1350],['P09','Documentation','Delivery','P05',3,5,8,2300,1,700],['P10','General launch','Launch','P08|P09',2,4,7,3700,1,900]]}
].map(d=>({...d,tasks:d.tasks.map(r=>({id:r[0],name:r[1],phase:r[2],deps:r[3]?r[3].split('|'):[],a:r[4],m:r[5],b:r[6],cost:r[7],crashMax:r[8],crashRate:r[9]}))}));
E.demos.forEach(d=>E.validate(d.tasks));global.MilestoneEngine=E;
})(typeof window!=='undefined'?window:globalThis);
</script><script>(()=>{'use strict';
const E=window.MilestoneEngine,$=id=>document.getElementById(id),htmlEsc=x=>String(x??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const pages=[['overview','◫','Command Center'],['network','◇','Dependency Network'],['critical','◷','Critical Path Lab'],['risk','▥','Risk Simulator'],['accelerate','↗','Acceleration Planner'],['data','▤','Data & Methods']];
let state={demo:0,custom:null,view:'overview',deadline:E.demos[0].deadline,budget:E.demos[0].budget,runs:600,seed:5182,selected:'',sim:null,plan:null};
const getTasks=()=>state.custom||E.demos[state.demo].tasks;
const fmt=(x,d=1)=>Number(x).toLocaleString('en-US',{maximumFractionDigits:d,minimumFractionDigits:d});
const money=x=>'$'+Math.round(x).toLocaleString('en-US');const pct=x=>fmt(x*100,1)+'%';
const latest=()=>({tasks:getTasks(),base:E.schedule(getTasks()),sim:state.sim,plan:state.plan});
function recalc(){const tasks=getTasks();state.sim=E.simulate(tasks,{deadline:state.deadline,runs:state.runs,seed:state.seed});state.plan=E.accelerate(tasks,state.budget,state.deadline);}
function navigate(view){state.view=view;render();closeMenu();}
function message(msg,isError=false){const t=$('toast');t.textContent=msg;t.className='toast'+(isError?' err':'');setTimeout(()=>{if(t.textContent===msg)t.className='toast hide';},4000);}
function closeMenu(){$('sidebar').classList.remove('open');$('overlay').classList.remove('on');}
function navMarkup(){return pages.map(([id,ico,name])=>`<button type="button" class="${state.view===id?'active':''}" data-nav="${id}"><span class="symbol">${ico}</span>${name}</button>`).join('');}
function panel(head,body,subtitle=''){return `<div class="card"><div class="section-title"><h3>${head}</h3>${subtitle?`<span class="hint">${subtitle}</span>`:''}</div>${body}</div>`;}
function metric(label,value,foot,color=''){return `<div class="card metric"><div class="m-label">${label}</div><div class="value num ${color}">${value}</div><div class="foot">${foot}</div></div>`;}
function barChart(labels,series,max=0){const W=700,H=Math.max(230,labels.length*45+40),l=170,r=42,hi=H-30;max=max||Math.max(1,...series.map(s=>s.value));let svg=`<svg viewBox="0 0 ${W} ${H}" class="chart" aria-label="Duration chart">`;for(let i=0;i<=4;i++){let x=l+(W-l-r)*i/4;svg+=`<line x1="${x}" y1="10" x2="${x}" y2="${hi}" class="chart-line" stroke-dasharray="3 4"/><text x="${x}" y="${H-5}" text-anchor="middle" class="chart-label">${fmt(max*i/4,0)}</text>`;}
series.forEach((s,i)=>{const y=19+i*45;svg+=`<text x="${l-11}" y="${y+12}" text-anchor="end" class="chart-label">${htmlEsc(labels[i].slice(0,23))}</text><rect x="${l}" y="${y}" width="${Math.max(0,(W-l-r)*s.value/max)}" height="18" fill="${s.color||'#70e1b5'}" rx="4"/><text x="${Math.min(W-r-33,l+(W-l-r)*s.value/max+7)}" y="${y+13}" class="chart-label">${fmt(s.value,1)}</text>`;});return svg+'</svg>';}
function histogram(sim){const W=700,H=240,base=198,l=43,r=18;let max=Math.max(1,...sim.bins.map(b=>b.n));let svg=`<svg viewBox="0 0 ${W} ${H}" class="chart" aria-label="Project duration distribution">`;
for(let i=0;i<=4;i++){let y=base-i*38;svg+=`<line x1="${l}" y1="${y}" x2="${W-r}" y2="${y}" class="chart-line" stroke-dasharray="3 5"/><text x="5" y="${y+4}" class="chart-label">${Math.round(max*i/4)}</text>`;}
const bw=(W-l-r)/sim.bins.length;sim.bins.forEach((b,i)=>{let h=b.n/max*152;svg+=`<rect x="${l+i*bw+2}" y="${base-h}" width="${bw-4}" height="${h}" fill="#65cba6" opacity=".85" rx="3"><title>${b.n} runs · ${fmt(b.from)}–${fmt(b.to)} days</title></rect>`;});const min=sim.bins[0].from,maxX=sim.bins.at(-1).to;if(maxX>min){let x=l+(state.deadline-min)/(maxX-min)*(W-l-r);if(x>l&&x<W-r)svg+=`<line x1="${x}" y1="8" x2="${x}" y2="${base}" stroke="#ffa983" stroke-width="2" stroke-dasharray="5 4"/><text x="${Math.min(W-90,Math.max(l,x+5))}" y="15" class="chart-label">Deadline</text>`;}
for(let i=0;i<=4;i++){let x=l+(W-l-r)*i/4;svg+=`<text x="${x}" y="${base+23}" class="chart-label" text-anchor="middle">${fmt(min+(maxX-min)*i/4,1)}d</text>`;}return svg+'</svg>';
}
function stepsDiagram(tasks,base){const order=E.order(tasks),depth={};for(const t of order)depth[t.id]=t.deps.length?Math.max(...t.deps.map(id=>depth[id]))+1:0;const maxDepth=Math.max(...Object.values(depth)),groups=Array.from({length:maxDepth+1},()=>[]);order.forEach(t=>groups[depth[t.id]].push(t));const rowHeight=105,colWidth=175,width=Math.max(840,(maxDepth+1)*colWidth+65),height=Math.max(240,Math.max(...groups.map(g=>g.length))*rowHeight+80),coords={};groups.forEach((g,i)=>g.forEach((t,j)=>coords[t.id]=[40+i*colWidth,40+j*rowHeight]));const crit=new Set(base.rows.filter(r=>r.critical).map(r=>r.id));let svg=`<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="Project dependency network">`;
for(const t of tasks)for(const dep of t.deps){const a=coords[dep],b=coords[t.id];svg+=`<path d="M${a[0]+139} ${a[1]+30} C${a[0]+160} ${a[1]+30} ${b[0]-25} ${b[1]+30} ${b[0]-5} ${b[1]+30}" stroke="${crit.has(dep)&&crit.has(t.id)?'#70e1b5':'#61788a'}" stroke-width="${crit.has(dep)&&crit.has(t.id)?2.5:1.3}" fill="none" opacity=".85"/>`;}
for(const t of tasks){const [x,y]=coords[t.id],c=crit.has(t.id);svg+=`<g><rect x="${x}" y="${y}" width="140" height="61" rx="8" fill="${c?'#1c4038':'#203248'}" stroke="${c?'#63cda6':'#4b667c'}" stroke-width="1.3"/><text x="${x+10}" y="${y+17}" style="font:700 11px system-ui" fill="${c?'#85f3c7':'#a5c7e3'}">${htmlEsc(t.id)}</text><text x="${x+10}" y="${y+34}" style="font:11px system-ui" fill="#e0f2ed">${htmlEsc(t.name.slice(0,19))}</text><text x="${x+10}" y="${y+51}" style="font:10px system-ui" fill="#9fb2c0">${fmt(E.mean(t),1)} days · ${htmlEsc(t.phase.slice(0,14))}</text></g>`;}
return svg+'</svg>';
}
function topControls(){const opts=E.demos.map((d,i)=>`<option value="${i}" ${!state.custom&&state.demo===i?'selected':''}>${d.label}</option>`).join('');return `<div class="controlstrip"><label>Project dataset<select id="dataset"><option value="custom" ${state.custom?'selected':''} ${state.custom?'':'disabled'}>${state.custom?'Imported project':'Import data to enable'}</option>${opts}</select></label><label>Deadline (days)<input id="deadline" type="number" value="${state.deadline}" min="1" max="365" step="1"/></label><label>Acceleration budget ($)<input id="budget" type="number" value="${state.budget}" min="0" max="10000000" step="500"/></label><label>Simulated runs<select id="runs"><option value="300" ${state.runs===300?'selected':''}>300</option><option value="600" ${state.runs===600?'selected':''}>600</option><option value="1200" ${state.runs===1200?'selected':''}>1,200</option></select></label><button class="button" id="run">↻ Recalculate</button></div>`;}
function overview({tasks,base,sim,plan}){const latest=base.rows.filter(r=>r.critical).sort((a,b)=>b.duration-a.duration).slice(0,5);return `<div class="cards">${metric('BASELINE COMPLETION',fmt(base.total,1)+'d','PERT expected duration','green')}${metric('P80 COMPLETION',fmt(sim.p80,1)+'d','80% simulated finish by this time','blue')}${metric('DEADLINE MISS RISK',pct(sim.chance),`${state.runs.toLocaleString()} reproducible scenarios`,sim.chance>.5?'red':'green')}${metric('CRITICAL TASKS',String(base.criticalCount),`${tasks.length} connected activities`,'amber')}</div><div class="cols">${panel('Schedule uncertainty',histogram(sim)+`<div class="legend"><span><span class="dot" style="background:#65cba6"></span>Simulation distribution</span><span><span class="dot" style="background:#ffa983"></span>Required deadline (${state.deadline}d)</span></div>`,'Beta-PERT · '+state.runs+' runs')}${panel('Decision brief',`<div class="summary"><div><small>Expected baseline cost</small><br><strong>${money(base.meanCost)}</strong></div><span class="pill">Illustrative</span></div><div class="summary"><div><small>Median completion (P50)</small><br><strong>${fmt(sim.p50,1)} days</strong></div><span class="pill">${fmt(sim.p90,1)}d P90</span></div><div class="summary"><div><small>Acceleration estimate</small><br><strong>${fmt(plan.daysSaved,1)} days faster</strong></div><span class="pill ${plan.met?'good':'hot'}">${plan.met?'Target met':'Target not met'}</span></div><div class="summary"><div><small>Added acceleration cost</small><br><strong>${money(plan.spent)}</strong></div><span class="pill">${plan.steps.length} actions</span></div><div class="callout warning">Forecasts assume independent Beta-PERT task times with fixed dependencies. The acceleration recommendation uses a greedy heuristic, not a globally optimal plan.</div>`)}</div><div class="cols equal">${panel('Longest critical activities',latest.map(r=>`<div class="progressrow"><div class="above"><span>${htmlEsc(r.name)}</span><strong>${fmt(r.duration,1)}d</strong></div><div class="progress"><i style="width:${r.duration/Math.max(...latest.map(x=>x.duration))*100}%"></i></div></div>`).join(''))}${panel('Project snapshot',`<p class="desc">${htmlEsc(state.custom?'Imported user dataset':E.demos[state.demo].description)}. Dates are relative working-time units, not calendar dates.</p><div class="stat-split"><span>Tasks / dependencies</span><b>${tasks.length} / ${tasks.reduce((s,t)=>s+t.deps.length,0)}</b></div><div class="stat-split"><span>Critical path</span><b>${base.criticalPath.join(' → ')}</b></div><div class="stat-split"><span>Schedule margin versus deadline</span><b class="${state.deadline<base.total?'bad':'green'}">${fmt(state.deadline-base.total,1)} days</b></div><div class="stat-split"><span>Duration standard deviation</span><b>${fmt(sim.sd,2)} days</b></div>`)}</div>`;}
function network({tasks,base}){return `${panel('Project dependency map',`<p class="heading-note">Green tasks are on at least one critical path. Arrows represent required predecessors. Scroll sideways on smaller screens.</p><div class="graph-scroller">${stepsDiagram(tasks,base)}</div><div class="legend"><span><span class="dot" style="background:#70e1b5"></span>Critical tasks</span><span><span class="dot" style="background:#789fc6"></span>Non-critical</span></div>`,'DAG · '+tasks.length+' tasks')}<div class="card" style="margin-top:16px"><div class="section-title"><h3>Dependency ledger</h3></div><div class="scroll"><table><thead><tr><th>Task</th><th>Phase</th><th>Predecessors</th><th>Expected duration</th><th>Critical?</th></tr></thead><tbody>${base.rows.map(r=>`<tr><td><span class="table-id">${htmlEsc(r.id)}</span> ${htmlEsc(r.name)}</td><td>${htmlEsc(r.phase)}</td><td>${htmlEsc(r.deps.join(', ')||'Start')}</td><td>${fmt(r.duration,1)}d</td><td><span class="pill ${r.critical?'hot':''}">${r.critical?'Critical':'Flexible'}</span></td></tr>`).join('')}</tbody></table></div></div>`;}
function critical({base}){return `<div class="cards">${metric('EXPECTED FINISH',fmt(base.total,1)+'d','Network finish date')}${metric('CRITICAL PATH TASKS',String(base.criticalCount),'Zero schedule slack')}${metric('MAX AVAILABLE SLACK',fmt(Math.max(...base.rows.map(r=>r.slack)),1)+'d','Most flexible activity')}${metric('COST BASELINE',money(base.meanCost),'Sum of synthetic task costs')}</div>${panel('CPM forward / backward pass',`<p class="desc">Earliest start (ES), earliest finish (EF), latest start (LS), latest finish (LF), and slack are derived from the full project DAG.</p><div class="scroll"><table><thead><tr><th>Task</th><th>Expected</th><th>ES</th><th>EF</th><th>LS</th><th>LF</th><th>Slack</th></tr></thead><tbody>${[...base.rows].sort((a,b)=>a.es-b.es).map(r=>`<tr><td><span class="table-id">${htmlEsc(r.id)}</span> ${htmlEsc(r.name)}</td><td>${fmt(r.duration,1)}</td><td>${fmt(r.es,1)}</td><td>${fmt(r.ef,1)}</td><td>${fmt(r.ls,1)}</td><td>${fmt(r.lf,1)}</td><td><span class="pill ${r.critical?'hot':''}">${fmt(r.slack,1)}d</span></td></tr>`).join('')}</tbody></table></div><div class="callout">Critical path: ${htmlEsc(base.criticalPath.join(' → '))}. Critical status can change when task durations change.</div>`)}`;}
function risk({sim,base}){return `<div class="cards">${metric('P50',fmt(sim.p50,1)+'d','Median simulated completion')}${metric('P80',fmt(sim.p80,1)+'d','80th percentile')}${metric('P95',fmt(sim.p95,1)+'d','95th percentile')}${metric('MISS PROBABILITY',pct(sim.chance),'Finish later than required',sim.chance>.5?'red':'green')}</div><div class="cols">${panel('Monte Carlo duration distribution',histogram(sim)+`<p class="small">Seed ${state.seed} · ${state.runs} trials · Beta-PERT (shape concentration 4) · Fixed task dependency network</p>`)}${panel('Simulation diagnostics',`<div class="stat-split"><span>Expected duration</span><b>${fmt(sim.avg,2)}d</b></div><div class="stat-split"><span>Standard deviation</span><b>${fmt(sim.sd,2)}d</b></div><div class="stat-split"><span>P10 / P90 range</span><b>${fmt(sim.p10,1)}–${fmt(sim.p90,1)}d</b></div><div class="stat-split"><span>Baseline PERT CPM</span><b>${fmt(base.total,1)}d</b></div><div class="stat-split"><span>Required deadline</span><b>${state.deadline}d</b></div><div class="callout warning">The Monte Carlo model assumes task durations are independent. Shared weather, staffing, funding or supply shocks can increase tail risk and are not modeled.</div>`)}</div>${panel('Criticality index by task',barChart([...sim.criticality].sort((a,b)=>b.prob-a.prob).slice(0,10).map(t=>t.name),[...sim.criticality].sort((a,b)=>b.prob-a.prob).slice(0,10).map(t=>({value:t.prob*100,color:'#70e1b5'})),100)+`<p class="small">Percentage of simulated paths on which a task had zero slack. Different tasks can simultaneously be critical.</p>`,'% of trials')}`;}
function accelerate({tasks,base,plan}){const chart=barChart(['Baseline','Accelerated'],[{value:base.total,color:'#6ca7d1'},{value:plan.newDuration,color:'#75dfad'}],Math.max(base.total,plan.newDuration)*1.12);return `<div class="cards">${metric('BASELINE',fmt(base.total,1)+'d','Expected PERT schedule')}${metric('PLANNED FINISH',fmt(plan.newDuration,1)+'d','After selected reductions','green')}${metric('TIME SAVED',fmt(plan.daysSaved,1)+'d','Compared to baseline','blue')}${metric('EXTRA SPEND',money(plan.spent),money(state.budget)+' budget')}</div><div class="cols">${panel('Schedule compression',chart+`<div class="callout ${plan.met?'':'warning'}">${plan.met?'The heuristic reaches the deadline with the current budget.':'The heuristic does not reach the deadline under the current budget and per-task acceleration limits.'}</div>`)}${panel('Planning boundaries',`<p class="desc">The planner shortens one critical task at a time, choosing the most time gained per additional dollar. The plan is a heuristic, not a proven minimum-cost solution.</p><div class="stat-split"><span>Time target</span><b>${state.deadline} days</b></div><div class="stat-split"><span>Available budget</span><b>${money(state.budget)}</b></div><div class="stat-split"><span>Remaining budget</span><b>${money(plan.remaining)}</b></div><div class="stat-split"><span>Compression steps</span><b>${plan.steps.length}</b></div><div class="callout warning">Acceleration changes expected durations only. To assess schedule risk after acceleration, update the task estimates and rerun simulation.</div>`)}</div>${panel('Recommended actions',plan.steps.length?`<div class="scroll"><table><thead><tr><th>Step</th><th>Task</th><th>Total reduction</th><th>Additional cost</th><th>Revised finish</th></tr></thead><tbody>${plan.steps.map((s,i)=>`<tr><td>${i+1}</td><td><span class="table-id">${htmlEsc(s.id)}</span> ${htmlEsc(s.name)}</td><td>${s.days}d</td><td>${money(s.cost)}</td><td>${fmt(s.duration,1)}d</td></tr>`).join('')}</tbody></table></div>`:'<div class="empty">No feasible single-task acceleration improves the current project completion time within budget.</div>')}`;}
function download(name,text,type='text/plain;charset=utf-8'){const blob=new Blob([text],{type}),a=document.createElement('a'),u=URL.createObjectURL(blob);a.href=u;a.download=name;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(u),3000);message('Downloaded '+name);}
function report(){const {tasks,base,sim,plan}=latest();return{project:'MilestoneIQ',version:'1.0',synthetic:!state.custom,dataset:state.custom?'Imported':E.demos[state.demo].label,method:'PERT CPM; independent Beta-PERT Monte Carlo; greedy project crashing',assumptions:{deadline:state.deadline,budget:state.budget,seed:state.seed,runs:state.runs},baseline:{duration:base.total,criticalPath:base.criticalPath,cost:base.meanCost,activities:base.rows.map(r=>({id:r.id,name:r.name,es:r.es,ef:r.ef,ls:r.ls,lf:r.lf,slack:r.slack,critical:r.critical}))},risk:{avg:sim.avg,sd:sim.sd,p50:sim.p50,p80:sim.p80,p90:sim.p90,p95:sim.p95,deadlineMissProb:sim.chance,criticality:sim.criticality},acceleration:plan,tasks};}
function data({tasks,base,sim}){return `${panel('Import your task network',`<p class="desc">Use the CSV template provided below. All processing happens in your browser. Loading a malformed file preserves the previous project. The file must contain 2–40 tasks and form a directed acyclic graph.</p><div class="upload"><input id="upload" type="file" accept=".csv,text/csv" aria-label="Upload tasks CSV"/><p class="small">Required columns: id, name, phase, deps, a, m, b, cost, crashMax, crashRate. Multiple predecessors separated by |.</p></div>`)}<div class="card" style="margin-top:16px"><div class="section-title"><h3>Download your analysis</h3></div><div class="download-grid"><button data-download="report">◩ Project audit JSON<small>Full calculations and assumptions</small></button><button data-download="schedule">▤ Schedule CSV<small>ES, EF, LS, LF and slack</small></button><button data-download="risk">▥ Simulation CSV<small>All Monte Carlo durations</small></button><button data-download="tasks">◫ Current task data CSV<small>Round-trip compatible task input</small></button><button data-download="template">⊞ Blank CSV template<small>Input schema with two sample rows</small></button><button data-download="methods">◉ Methodology Markdown<small>Model scope, cautions and reproduction</small></button></div></div>${panel('Data quality and methodology',`<div class="stat-split"><span>Input activities</span><b>${tasks.length}</b></div><div class="stat-split"><span>Dependency edges</span><b>${tasks.reduce((n,t)=>n+t.deps.length,0)}</b></div><div class="stat-split"><span>Independent simulation trials</span><b>${sim.runs}</b></div><div class="stat-split"><span>Random generator seed</span><b>${sim.seed}</b></div><div class="stat-split"><span>Cost baseline</span><b>${money(base.meanCost)}</b></div><div class="callout warning">All bundled scenarios use fictional costs and projects. No live market inputs, calendar holidays, capacity-constrained resource leveling, correlations, contractual legal evaluation or guarantees are provided.</div>`)}`;}
function handleDownload(kind){const {tasks,base,sim}=latest();if(kind==='report')return download('milestoneiq-audit.json',JSON.stringify(report(),null,2),'application/json');if(kind==='schedule')return download('milestoneiq-schedule.csv',E.toCSV(['id','name','phase','es','ef','ls','lf','slack','critical'],base.rows.map(r=>({id:r.id,name:r.name,phase:r.phase,es:E.round(r.es,3),ef:E.round(r.ef,3),ls:E.round(r.ls,3),lf:E.round(r.lf,3),slack:E.round(r.slack,3),critical:r.critical?'yes':'no'})),{es:'number',ef:'number',ls:'number',lf:'number',slack:'number'}),'text/csv');if(kind==='risk')return download('milestoneiq-simulations.csv',E.toCSV(['trial','duration_days'],sim.samples.map((v,i)=>({trial:i+1,duration_days:E.round(v,5)})),{trial:'number',duration_days:'number'}),'text/csv');if(kind==='tasks')return download('milestoneiq-tasks.csv',E.taskCSV(tasks),'text/csv');if(kind==='template')return download('milestoneiq-template.csv',E.taskCSV([{id:'T01',name:'Initial discovery',phase:'Design',deps:[],a:2,m:3,b:6,cost:1000,crashMax:1,crashRate:300},{id:'T02',name:'Final validation',phase:'Delivery',deps:['T01'],a:3,m:5,b:8,cost:2000,crashMax:1,crashRate:500}]),'text/csv');if(kind==='methods'){return download('milestoneiq-methodology.md',`# MilestoneIQ research notes\n\nDataset: ${state.custom?'Imported':E.demos[state.demo].label} (${state.custom?'user-provided':'fictional data'}).\n\n- Baseline duration: PERT (a + 4m + b)/6 for every task.\n- Directed acyclic precedence graph, unlimited parallel capacity, forward and backward critical path passes.\n- Monte Carlo: independent four-weight Beta-PERT distributions, ${sim.runs} trials, pseudo-random seed ${sim.seed}.\n- Deadline: ${state.deadline} project time units (illustrated as days). No weekends or holidays.\n- Acceleration: greedy, one-day compression of tasks where it directly shortens the current critical completion. NOT optimal. Budget: USD ${state.budget}.\n- No inference of causal effects, industry benchmarks, actual prices or probability guarantees.\n\n## Results\n- Baseline: ${base.total.toFixed(3)} days\n- P80: ${sim.p80.toFixed(3)} days\n- Miss probability: ${(sim.chance*100).toFixed(2)}%\n`,'text/markdown');}}
function render(){const snapshot=latest();$('nav').innerHTML=navMarkup();$('page-title').textContent=pages.find(p=>p[0]===state.view)[2];$('page-subtitle').textContent=state.view==='overview'?'Project scheduling, probabilistic delivery risk and transparent decisions.':'Local-first project analytics based on an explicit dependency graph.';
$('controls').innerHTML=topControls();const pagesRender={overview,network,critical,risk,accelerate,data};$('content').innerHTML=pagesRender[state.view](snapshot);}
function onChange(e){if(e.target.id==='dataset'){if(e.target.value==='custom'){if(!state.custom)return;}else{state.custom=null;state.demo=Number(e.target.value);state.deadline=E.demos[state.demo].deadline;state.budget=E.demos[state.demo].budget;recalc();render();}return;}if(e.target.id==='runs'){state.runs=Number(e.target.value);recalc();render();}}
function changeValue(id,value){const n=Number(value);if(!Number.isFinite(n))throw Error('Enter a valid number.');if(id==='deadline'){if(n<1||n>365||!Number.isInteger(n))throw Error('Deadline must be an integer from 1 to 365.');state.deadline=n;}if(id==='budget'){if(n<0||n>1e7)throw Error('Budget must be 0 to 10 million.');state.budget=n;}}
function handleClick(e){const nav=e.target.closest('[data-nav]');if(nav)return navigate(nav.dataset.nav);if(e.target.closest('#menu')){$('sidebar').classList.add('open');$('overlay').classList.add('on');return;}if(e.target.closest('#overlay'))return closeMenu();const d=e.target.closest('[data-download]');if(d)return handleDownload(d.dataset.download);if(e.target.closest('#run')){try{changeValue('deadline',$('deadline').value);changeValue('budget',$('budget').value);state.runs=Number($('runs').value);recalc();render();message('Analysis recalculated.');}catch(err){message(err.message,true);}return;}}
async function handleFile(e){if(e.target.id!=='upload'||!e.target.files?.[0])return;try{const file=e.target.files[0];if(file.size>200000)throw Error('CSV must be 200 KB or smaller.');const text=await file.text(),tasks=E.fromCSV(text);state.custom=tasks;state.deadline=Math.ceil(E.schedule(tasks).total*1.1);state.budget=10000;recalc();render();message('Imported '+tasks.length+' tasks successfully.');}catch(err){message('Import rejected: '+err.message,true);e.target.value='';}}
function init(){document.addEventListener('click',handleClick);document.addEventListener('change',onChange);document.addEventListener('change',handleFile);recalc();render();}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
})();
</script></body></html>