Founder Command Center

Founder Cockpit

Global intelligence. Selective execution.
Beirut
TA
Tarek AbdallahFounder
FOUNDER MODE Canonical operating state
—System
—Execution
—Updated
⌕
FOUNDER NOW

What needs you

Protected EV—gross EV —
Execution portfolio—earned live positions
Founder decisions0authority required
Movement · 24h—commercial delta
Promotion queue—earning execution
EXECUTION PORTFOLIO

Protected commercial value & movement

—
EXECUTION + PROMOTION

Where BTWYN is creating commercial movement

—earned execution positions
—running
—runnable
—promotion
—substantive / 24h
Loading…

Reading canonical runtime state.

Research—— queued
High priority—waiting evidence
Next release—resource governor
PROMOTION QUEUE

What can earn execution next

Global universe machine-scale Promotion lane 2 slots · 4/day Evidence first R19 canonical
System health—
Red Team—
External execution—
Research queue—
Release integrity—

Operational Exceptions

0
Exception-first queue. Each row is derived from the canonical control-plane exception intelligence and drills to its underlying opportunity or system context.

Founder Now

0
This is the Founder work queue. Only decisions, approvals, exceptions and relationship interventions that genuinely require Founder authority should appear here.
OPERATIONS MODE

Autonomous Execution Control

Execution, queues, exceptions and agent runtime. Founder authority boundaries remain unchanged.

LOADING
System—
Execution—
Running—
Runnable—
Queued—
Blocked—
Research—
Exceptions—

Execution Queue

0
StatusAgentTaskOpportunityPriorityAvailable

Operational Exceptions

0

Agent Runtime

Opportunity Pipeline

Canonical commercial pipeline · dense operational view

0

Commercial Worklist

0 visible
SidesNext actionBlocker

Communications Control

0

Execution Boundary

FAIL-CLOSED

Needs Attention

0

Recent Commercial Exchanges

0

Agent Runtime

0

Recent Agent Actions

0

System & Security

Control Plane v2.0 · Auth v1.10.0

System Assurance

loading

SLO Status

0

Agent Release Health

0

Production Hardening

0

Founder Access

Loading password status…

Requirement: 14–128 characters including uppercase, lowercase, a number and a symbol. Your password is sent directly over the authenticated Supabase session and is not stored in BTWYN operating tables.

Founder MFA

Checking MFA status…

Once enabled, BTWYN requires an AAL2 Founder session for dashboard access, approvals, transport review, arming and external execution.

Email Transport Assurance

Validate Microsoft Graph credentials, deals@btwyn.co mailbox access, connector state and recorded send evidence without sending an email.

'); w.document.close(); } async function confirmFinalEmailReview(id,hash){ if(!confirm("Confirm that you reviewed the exact frozen email, including recipient, subject, body and BTWYN_FOUNDER_V1 signature?"))return; const token=await refreshSession();if(!token)throw new Error("Founder session expired. Sign in again."); const r=await fetch(API+"?api=graph-final-review",{method:"POST",headers:{Authorization:"Bearer "+token,"content-type":"application/json"},body:JSON.stringify({communication_id:id,action:"CONFIRM",transport_payload_hash:hash})}); const d=await r.json().catch(()=>({}));if(!r.ok)throw new Error(d.error||"Review confirmation failed."); alert("Final email review CONFIRMED. The email is still not sent."); await load(true);setView("commercial"); } async function armGovernedEmail(id){ if(!confirm("Arm this exact frozen email for execution? Arming does NOT send it."))return; const token=await refreshSession();if(!token)throw new Error("Founder session expired. Sign in again."); const r=await fetch(API+"?api=graph-arm",{method:"POST",headers:{Authorization:"Bearer "+token,"content-type":"application/json"},body:JSON.stringify({communication_id:id})}); const d=await r.json().catch(()=>({}));if(!r.ok)throw new Error(d.error||"Arm failed."); alert("Execution ARMED for this exact payload. No email has been sent."); await load(true);setView("commercial"); } async function sendGovernedEmail(id){ if(!confirm("FINAL SEND CONFIRMATION\n\nSend this exact armed and frozen email through Microsoft Graph now?"))return; const token=await refreshSession();if(!token)throw new Error("Founder session expired. Sign in again."); const r=await fetch(API+"?api=graph-execute",{method:"POST",headers:{Authorization:"Bearer "+token,"content-type":"application/json"},body:JSON.stringify({communication_id:id})}); const d=await r.json().catch(()=>({}));if(!r.ok)throw new Error(d.error||"Send failed."); alert("Email accepted by Microsoft Graph. Hash: "+d.transport_payload_hash); await load(true);setView("commercial"); } async function syncInboundMail(){const b=document.getElementById("syncInboundBtn"),ok=document.getElementById("syncInboundOk"),er=document.getElementById("syncInboundErr");if(ok)ok.textContent="";if(er)er.textContent="";if(b)b.disabled=true;try{const token=await refreshSession();if(!token)throw new Error("Founder session expired. Sign in again.");const r=await fetch(API+"?api=graph-inbound-sync",{method:"POST",headers:{Authorization:"Bearer "+token,"content-type":"application/json"},body:JSON.stringify({top:25,lookback_hours:168})});const d=await r.json().catch(()=>({}));if(!r.ok){if(d.error==="graph_mail_read_forbidden")throw new Error("Microsoft Graph Mail.Read application permission with admin consent is required.");throw new Error(d.error||"Inbox sync failed.");}if(ok)ok.textContent="SYNC PASS — Inbox: scanned "+String(d.messages_scanned||0)+", assessed "+String(d.assessed||0)+", unmatched "+String(d.unmatched||0)+", duplicates "+String(d.duplicates||0)+", failed "+String(d.failed||0)+". Sent: scanned "+String(d.sent_scanned||0)+", matched "+String(d.sent_matched||0)+", unmatched "+String(d.sent_unmatched||0)+", duplicates "+String(d.sent_duplicates||0)+", failed "+String(d.sent_failed||0)+", actions closed "+String(d.sent_actions_closed||0)+".";await load(true);setView("commercial");return d;}finally{if(b)b.disabled=false}}function inboundResponseCard(r){return '
'+esc(r.title||"Inbound response")+'
'+esc(r.opportunity_code)+'
'+esc(String(r.response_type||"AMBIGUOUS").replaceAll("_"," "))+'
Signal'+esc(r.commercial_signal||"UNKNOWN")+'
Summary'+esc(r.summary||"—")+'
Recommended'+esc(r.recommended_action||"—")+'
Authority'+esc(r.recommended_authority||"GREEN")+' · Red Team '+(r.red_team_required?'REQUIRED':'not required')+' · Founder '+(r.founder_action_required?'REQUIRED':'not required')+'
'}function governedEmailCard(r,sendEnabled){ const reviewed=String(r.final_review_status||"")==="CONFIRMED"; const armed=String(r.arm_status||"")==="ARMED"; let executionButton=''; if(!reviewed){ executionButton=''; }else if(!armed){ executionButton=''; }else{ executionButton=''; } return '
'+esc(r.subject||"Governed email")+'
'+esc(r.communication_code)+'
From'+esc(r.sender)+'
To'+esc(r.recipient)+'
Authority'+esc(r.authority)+' · Red Team '+esc(r.red_team_verdict)+' · Approval '+esc(r.approval_status)+'
Final review'+esc(r.final_review_status||"NOT_REVIEWED")+'
Execution arm'+esc(r.arm_status||"NOT_ARMED")+'
Payload hash'+esc(r.transport_payload_hash)+'
'+executionButton+'
' } function exceptionCard(r){return '
'+esc(r.title||r.kind)+'
'+esc(r.opportunity_code||"SYSTEM")+' · '+esc(r.reference||"")+'
'+esc(String(r.kind||"EXCEPTION").replaceAll("_"," "))+'
Detail'+esc(r.detail||"—")+'
Observed'+esc(r.occurred_at||"—")+'
'}function founderCard(r){ const controls=r.approval_id&&String(r.approval_status||'')==='PENDING'?'
':'';return '
'+esc(r.title)+'
'+esc(r.opportunity_code)+'
Decision'+esc(r.requested_action)+'
Recommendation'+esc(r.recommendation||'—')+'
Scope'+esc(r.decision_scope||'Governed action')+'
'+controls+'
'}function executionCard(r){return '
'+esc(r.title)+'
'+esc(r.opportunity_code)+'
'+esc(r.funnel_status||'Controlled execution')+'
Score'+esc(r.qualification_score??r.total_score??'—')+'
Next control'+esc(r.activation_queue||'—')+'
'}function render(d){const c=d.decision_cockpit||{},fa=c.founder_action_required||[],ai=c.ai_working||[],we=c.waiting_external||[],m=d.metrics||{},a=d.auth||{};$('#founderCount').textContent=fa.length;$('#aiCount').textContent=ai.length;$('#waitCount').textContent=we.length;$('#founderBox').innerHTML=fa.length?'
'+fa.map(founderCard).join('')+'
':'

No Founder action required now

The approval and attention gates are clear. BTWYN continues operating and will surface an item here only when your decision, authorization or relationship intervention is actually required.
';const ec=d.exception_cockpit||{},esum=ec.summary||{},eitems=ec.items||[],ecron=ec.email_reconciliation_cron||{};const ecount=eitems.length+Number(esum.inbound_failed||0)+Number(esum.sent_failed||0)+Number(esum.inbound_unmatched||0)+Number(esum.pending_external_execution||0)+Number(esum.pending_founder_approvals||0);$('#exceptionCount').textContent=ecount;$('#exceptionMetrics').innerHTML=metric('Overdue',esum.overdue_actions||0,'actions')+metric('Red Team MODIFY',esum.open_red_team_modify||0,'unresolved')+metric('Inbound Failed',esum.inbound_failed||0,'mail')+metric('Inbound Unmatched',esum.inbound_unmatched||0,'mail')+metric('External Pending',esum.pending_external_execution||0,'execution')+metric('Founder Approvals',esum.pending_founder_approvals||0,'pending');$('#exceptionBox').innerHTML=eitems.length?eitems.map(exceptionCard).join(''):'

No operational exception requires attention

Control failures, overdue actions and unresolved exception signals are clear.
';$('#emailCronState').innerHTML='Automatic Inbox + Sent reconciliation: '+(ecron.active?'ENABLED':'DISABLED')+' · schedule '+esc(ecron.schedule||'—')+' · latest run '+esc(ecron.latest_status||'awaiting first run')+'';$('#aiBox').innerHTML=ai.length?ai.map(x=>card(x,'ai')).join(''):'
No active AI work.
';$('#waitBox').innerHTML=we.length?we.map(x=>card(x,'wait')).join(''):'
No external waits.
';$('#metrics').innerHTML=metric('Opportunity Universe',m.total_opportunities,'canonical records')+metric('Controlled Execution',m.controlled_execution,'live queue')+metric('External Waits',m.external_waits,'counterpart dependency')+metric('Pending Actions',m.pending_actions,'raw queue')+metric('Blocked Actions',m.blocked_actions,'raw controls')+metric('Red-Team PASS',m.red_team_passes,'approved reviews');const ex=d.executions||[];$('#executionCount').textContent=ex.length;$('#executionBox').innerHTML=ex.length?ex.map(executionCard).join(''):'
No controlled executions.
';$('#stages').innerHTML=(d.stage_counts||[]).map(x=>'
'+esc(x.count)+''+esc(x.stage)+'
').join('');const ew=d.external_waits||[];$('#externalCount').textContent=ew.length;$('#externalBox').innerHTML=ew.length?ew.map(x=>'
'+esc(x.title)+'
'+esc(x.opportunity_code)+'
Status'+esc(x.funnel_status||'—')+'
Waiting on'+esc(x.activation_queue||'—')+'
').join(''):'
No external waits.
';$('#commercialMetrics').innerHTML=metric('Active Protections',m.active_protections,'protected accounts')+metric('Assessments',m.commercial_assessments,'commercial records')+metric('Terms',m.commercial_terms,'commercial terms')+metric('Expected Fee',m.expected_fee_value||0,'recorded value');$('#commercialText').innerHTML=(Number(m.active_protections||0)===0?'Protection register currently has no active record.
':'')+(Number(m.expected_fee_value||0)===0?'Expected fee value is not yet populated in the commercial assessment layer.':'');const ir=d.inbound_response_queue||[];$('#inboundResponseCount').textContent=ir.length;$('#inboundResponseBox').innerHTML=ir.length?ir.map(inboundResponseCard).join(''):'
No inbound commercial response currently requires handling.
';const ge=d.governed_email_queue||[],es=d.email_execution_state||{},sendEnabled=es.connector_production_enabled===true&&es.transport_production_enabled===true&&es.global_firewall_on===true;$('#emailQueueCount').textContent=ge.length;if($('#founderRailExecution'))$('#founderRailExecution').textContent=sendEnabled?'ENABLED':'FAIL-CLOSED'; if($('#founderRailExecutionSub'))$('#founderRailExecutionSub').textContent=sendEnabled?'Governed production transport available':'External execution locked unless separately authorized'; if($('#founderRailExecutionCard'))$('#founderRailExecutionCard').className='founder-status-item '+(sendEnabled?'attention':'clear');$('#emailExecutionState').innerHTML='Microsoft Graph HTML transport: VALIDATED
Production connector: '+(es.connector_production_enabled?'ON':'OFF')+'
Transport production: '+(es.transport_production_enabled?'ON':'OFF')+'
Global external-execution firewall: '+(es.global_firewall_on?'ON':'OFF')+'
Execution state: '+(sendEnabled?'GLOBAL EXECUTION ENABLED':(ge.some(x=>String(x.arm_status||'')==='ARMED')?'GLOBAL LOCKED — SCOPED ARMED SEND AVAILABLE':'LOCKED — PREVIEW ONLY'))+'';$('#emailQueueBox').innerHTML=ge.length?ge.map(x=>governedEmailCard(x,sendEnabled)).join(''):'
No governed email is currently cleared and ready for execution.
';const b=d.founder_brief||{};const sa=d.assurance||{},pr=sa.protection||{},sec=sa.security||{},sl=sa.slo||[],ah=sa.agent_health||[],rx=sa.recent_executed||[],rel=sa.release||{},sr=sa.system_release||{},hd=sa.hardening||[],si=sa.state_integrity||{},rj=sa.remote_jobs||[];$('#protectionRequirementCount').textContent=pr.requirements_total||0;$('#protectionAssurance').innerHTML=metric('Requirements',pr.requirements_total||0,'canonical')+metric('Open',pr.requirements_open||0,'protection required')+metric('Satisfied',pr.requirements_satisfied||0,'linked protection')+metric('Active Grants',pr.active_protections||0,'effective records');$('#recentExecutedCount').textContent=rx.length;$('#recentExecutedBox').innerHTML=rx.length?rx.map(x=>'
'+esc(x.subject||x.communication_code)+'
'+esc(x.communication_code)+' · '+esc(x.recipient||'—')+'
Sent'+esc(x.sent_at?new Date(x.sent_at).toLocaleString():'—')+'
Intent'+esc(x.intent_status||'—')+'
Reconciliation'+esc(x.reconciliation_status||'—')+' · '+esc(x.match_method||'—')+'
Payload'+esc(x.transport_payload_hash||'—')+'
').join(''):'
No executed outbound communications recorded.
';const stateDrift=Number(si.violations??(Number(si.qualified_without_qualification||0)+Number(si.external_wait_queue_mismatch||0)+Number(si.external_wait_gate_mismatch||0)+Number(si.external_wait_without_monitor||0)));const rpcExposure=Number(sec.anon_security_definer_exec||0)+Number(sec.authenticated_security_definer_exec||0);const sloReportOnlyCodes=new Set(['SLO-CONTROL-HEALTH']),sloActionableBreaches=sl.filter(x=>x.slo_status==='BREACH'&&!sloReportOnlyCodes.has(x.slo_code)).length,sloReportOnlyBreaches=sl.filter(x=>x.slo_status==='BREACH'&&sloReportOnlyCodes.has(x.slo_code)).length,sloInsufficient=sl.filter(x=>x.slo_status==='UNMEASURED').length;$('#assuranceState').textContent=sa.error?'UNAVAILABLE':(rpcExposure===0&&stateDrift===0&&sloActionableBreaches===0?'CONTROLLED':'ATTENTION');$('#assuranceMetrics').innerHTML=metric('Public Privileged RPC',rpcExposure,'anon/auth exposure')+metric('Founder MFA',sec.founder_verified_mfa_factors||0,'verified factors')+metric('State Drift',stateDrift,'canonical inconsistencies')+metric('SLO Status',sloActionableBreaches,sloReportOnlyBreaches+' report-only · '+sloInsufficient+' insufficient sample');if($('#founderRailAssurance'))$('#founderRailAssurance').textContent=sa.error?'UNAVAILABLE':(rpcExposure===0&&stateDrift===0&&sloActionableBreaches===0?'CONTROLLED':'ATTENTION'); if($('#founderRailAssuranceSub'))$('#founderRailAssuranceSub').textContent=sa.error?'Assurance telemetry unavailable':(stateDrift?stateDrift+' state-integrity inconsistency(ies)':rpcExposure?rpcExposure+' privileged RPC exposure(s)':sloActionableBreaches?sloActionableBreaches+' actionable SLO breach(es)':sloReportOnlyBreaches||sloInsufficient?sloReportOnlyBreaches+' report-only SLO · '+sloInsufficient+' insufficient-sample metric(s)':'State integrity, privileged RPC exposure and live SLOs controlled'); if($('#founderRailAssuranceCard'))$('#founderRailAssuranceCard').className='founder-status-item '+(sa.error||rpcExposure||stateDrift||sloActionableBreaches?'attention':'clear');$('#sloCount').textContent=sl.length;$('#sloBox').innerHTML=sl.length?sl.map(x=>{const reportOnly=x.slo_status==='BREACH'&&sloReportOnlyCodes.has(x.slo_code),insufficient=x.slo_status==='UNMEASURED',label=reportOnly?'REPORT-ONLY BREACH':(insufficient?'INSUFFICIENT SAMPLE':x.slo_status),interpretation=reportOnly?'Historical control-health reliability metric; visible for learning but does not gate current system health.':(insufficient?'Insufficient post-baseline sample; this is not a failure.':'Current operational SLO measurement.');return '
'+esc(x.metric_name)+'
'+esc(x.slo_code)+'
'+esc(label)+'
Measured'+esc(x.measured_value??'—')+' '+esc(x.unit||'')+'
Target'+esc(x.target_operator)+' '+esc(x.target_value)+' '+esc(x.unit||'')+'
Interpretation'+esc(interpretation)+'
'}).join(''):'
SLO data unavailable.
';$('#agentHealthCount').textContent=ah.length;$('#agentHealthBox').innerHTML=ah.length?ah.map(x=>'
'+esc(x.name||x.agent_code)+'
'+esc(x.agent_code)+' · '+esc(x.runtime_kind||x.source||'—')+'
'+esc(x.regression_health||'UNKNOWN')+'
Prompt'+esc(x.prompt_version||'—')+'
Model'+esc(x.model||x.candidate_model||'deterministic/component')+'
Release'+esc(x.latest_regression_status||'NEVER TESTED')+'
').join(''):'
Agent release-health data unavailable.
';$('#releaseState').innerHTML='Active release: '+esc(sr.release_code||'—')+'
Command Center: v'+esc(sr.command_center_version||'—')+' · API/Auth: v'+esc(sr.api_auth_version||'—')+' · Assurance: v'+esc(sa.version||sr.assurance_version||'—')+'
Latest DB migration: '+esc(rel.latest_migration_version||'—')+' · '+esc(rel.latest_migration_name||'—')+'
Bundle captured: '+esc(rel.bundle_captured_at?new Date(rel.bundle_captured_at).toLocaleString():'—')+'
Bundle SHA256: '+esc(rel.bundle_sha256||sr.bundle_sha256||'—')+'
Session storage: EPHEMERAL BROWSER SESSION';const openHd=hd.filter(x=>!['CLOSED','CLOSED_MONITOR'].includes(x.status));$('#hardeningCount').textContent=openHd.length;$('#hardeningBox').innerHTML=openHd.length?openHd.map(x=>'
'+esc(x.title)+'
'+esc(x.item_code)+' · '+esc(x.domain)+'
'+esc(x.status)+' · '+esc(x.severity)+'
Owner'+esc(x.owner_type||'—')+'
Blocker'+esc(x.blocking_reason||'—')+'
Remediation'+esc(x.remediation||'—')+'
').join(''):'

No open production hardening item

All registered hardening actions are closed or monitor-only.
';$('#systemText').innerHTML='Authentication: Supabase Auth
Role: Founder
Account: '+esc(a.email||EMAIL)+'
Founder MFA: '+(a.mfa_enrolled?'VERIFIED · '+esc(String(a.aal||'—').toUpperCase()):'NOT ENROLLED')+'
System health: '+esc(b.system_health||'—')+'
External execution: '+(b.external_execution_enabled?'Enabled':'Disabled')+'
Dashboard baseline: Founder Cockpit v3.6 · Control Plane v2.5.0
API/Auth layer: v1.10.0
Mode: Founder-only, read-only.
Last refresh: '+new Date(d.generated_at).toLocaleString();$('#passwordStatus').innerHTML=a.password_user_set?'Founder password set. New devices can sign in with '+EMAIL+'.':'Founder-chosen password not set yet. Set one below before relying on new-device access.';if(a.password_user_set!==true){setView('system');$('#passwordOk').textContent='Founder password setup is required before normal Command Center use.'}else if(sessionStorage.getItem('btwyn_recovery_return')==='1'){sessionStorage.removeItem('btwyn_recovery_return');setView('system');$('#passwordOk').textContent='Recovery session verified. Set your new Founder password below.'}}async function load(force=false){if(localStorage.getItem('btwyn_locked')==='1'&&!force){showGate();return}const token=await refreshSession();if(!token){showGate();return}try{await ensureMfaForSession()}catch(e){if(String(e.message||'').startsWith('MFA_CODE_REQUIRED:')){const fid=String(e.message).split(':').slice(1).join(':');sessionStorage.setItem('btwyn_pending_mfa_factor',fid);$('#unlockErr').textContent='Enter your authenticator code to complete Founder sign-in.'}else $('#unlockErr').textContent=e.message||'MFA verification required.';showGate();return}document.body.classList.add('loading');try{const r=await fetch(API+'?api=dashboard',{headers:{Authorization:'Bearer '+token}}); if(!r.ok){ const detail=await r.json().catch(()=>({})); if(r.status===401){ sessionStorage.setItem('btwyn_last_auth_failure','dashboard_401_after_'+(sessionStorage.getItem('btwyn_auth_handoff_consumed')||'session')); } throw new Error(detail?.error?('Dashboard authorization failed: '+detail.error):('Dashboard request failed ('+r.status+').')); } sessionStorage.removeItem('btwyn_last_auth_failure'); localStorage.removeItem('btwyn_auth_handoff_v360'); localStorage.removeItem('btwyn_auth_handoff_v355'); sessionStorage.setItem('btwyn_auth_handoff_state','DASHBOARD_AUTHORIZED_V357'); const d=await r.json();try{const ar=await fetch(BASE+'/functions/v1/btwyn-command-center-assurance',{headers:{Authorization:'Bearer '+token}});d.assurance=ar.ok?await ar.json():{error:true};}catch{d.assurance={error:true}}let cp=null,pipelineFallback=null;try{const cr=await fetch(CONTROLPLANE,{headers:{Authorization:'Bearer '+token}});if(cr.ok)cp=await cr.json()}catch{}if(!cp){try{const pr=await fetch(CONTROLPLANE+'?pipeline=1',{headers:{Authorization:'Bearer '+token}});if(pr.ok){const pd=await pr.json();pipelineFallback=Array.isArray(pd.opportunities)?pd.opportunities:[]}}catch{}}render(d);if(cp){renderControlPlane(cp)}else if(pipelineFallback){renderOpportunityPipeline(pipelineFallback);if($('#navOpportunityCount'))$('#navOpportunityCount').textContent=pipelineFallback.length;if($('#opportunityCount'))$('#opportunityCount').textContent=pipelineFallback.length}renderFounderCockpit(d,cp);$('#gate').style.display='none'}catch(e){$('#unlockErr').textContent='Founder session could not be verified.';showGate()}finally{document.body.classList.remove('loading')}}function showGate(){const session=hasSession();$('#gate').style.display='flex';$('#signinPanel').style.display=session?'none':'block';$('#unlockPanel').style.display=session?'block':'none';const laf=sessionStorage.getItem('btwyn_last_auth_failure');if(!session&&laf&&$('#signinErr'))$('#signinErr').textContent='Authenticated MFA session was rejected by the dashboard API: '+laf+'.';if(session){const pending=sessionStorage.getItem('btwyn_pending_mfa_factor');if(pending){$('#unlockMfaPanel').style.display='block';$('#unlockBtn').style.display='none';$('#unlockErr').textContent='Enter your authenticator code to complete Founder sign-in.'}else{$('#unlockMfaPanel').style.display='none';$('#unlockBtn').style.display=''}}}function setView(name){$$('[data-view]').forEach(x=>{const active=x.dataset.view===name;x.classList.toggle('active',active);if(x.matches('button')){if(active)x.setAttribute('aria-current','page');else x.removeAttribute('aria-current')}});$$('.view').forEach(x=>x.classList.remove('active'));const target=$('#'+name);if(!target)return;target.classList.add('active');$('#viewTitle').textContent={overview:'Founder Cockpit',operations:'Operations Mode',exceptions:'Operational Exceptions',foundernow:'Founder Now',opportunities:'Opportunity Pipeline',intelligence:'Autonomous Intelligence',communications:'Communications',agents:'Agent Runtime',system:'System & Controls'}[name]||'BTWYN Command Center';if(window.innerWidth<=760){const mt=document.querySelector('.mobiletabs [data-view="'+name+'"]');if(mt)mt.scrollIntoView({behavior:'smooth',block:'nearest',inline:'center'});window.scrollTo({top:0,behavior:'smooth'})}} function installViewNavigation(){ if(window.__btwynViewNavInstalled)return; window.__btwynViewNavInstalled=true; document.addEventListener('click',e=>{ const el=e.target&&e.target.closest?e.target.closest('[data-view]'):null; if(!el||el.disabled)return; const name=el.dataset.view; if(!name||!document.getElementById(name))return; e.preventDefault(); setView(name); },true); } installViewNavigation(); function updateMasterClock(){const el=$('#masterLocalTime');if(!el)return;const now=new Date();const fmt=new Intl.DateTimeFormat('en-GB',{timeZone:'Asia/Beirut',weekday:'short',day:'numeric',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:false});el.textContent=fmt.format(now)+' · Beirut'}updateMasterClock();setInterval(updateMasterClock,60000);updateFounderGreeting();bindFounderDrilldowns();bindSpecClosureControls();const BTWYN_AUTO_REFRESH_MS=90000;setInterval(()=>{if(document.visibilityState==='visible'&&hasSession()&&localStorage.getItem('btwyn_locked')!=='1'&&!document.body.classList.contains('loading'))load(false)},BTWYN_AUTO_REFRESH_MS);document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible'&&hasSession()&&localStorage.getItem('btwyn_locked')!=='1'&&!document.body.classList.contains('loading'))load(false)});document.addEventListener('click',e=>{const b=e.target.closest('.founder-decision-btn');if(!b||b.disabled)return;runFounderDecision(b.dataset.approvalId||'',b.dataset.decision||'',b.dataset.decisionKind||'ACTION_APPROVAL')});document.querySelectorAll('.quick-action').forEach(b=>b.addEventListener('click',()=>{const i=$('#founderCommandInput');if(i){i.value=b.dataset.cmd||'';runFounderCommand()}}));$('#founderCommandSend')?.addEventListener('click',()=>runFounderCommand());$('#founderCommandInput')?.addEventListener('keydown',e=>{if(e.key==='Enter')runFounderCommand()});const signinMfaBtn=$('#signinMfaBtn');if(signinMfaBtn)signinMfaBtn.onclick=async()=>{const code=$('#signinMfaCode').value.trim(),factorId=sessionStorage.getItem('btwyn_pending_mfa_factor')||'';$('#signinErr').textContent='';if(!factorId||!code){$('#signinErr').textContent='Enter the authenticator code.';return}try{document.body.classList.add('loading');await mfaVerifyFactor(factorId,code);sessionStorage.removeItem('btwyn_pending_mfa_factor');$('#signinMfaCode').value='';$('#signinMfaPanel').style.display='none';localStorage.removeItem('btwyn_locked');await load(true)}catch(e){$('#signinErr').textContent=e.message||'MFA verification failed.'}finally{document.body.classList.remove('loading')}};$('#signinMfaCode')?.addEventListener('keydown',e=>{if(e.key==='Enter')signinMfaBtn.click()});$('#signinBtn').onclick=async()=>{const p=$('#loginPassword').value;$('#signinErr').textContent='';$('#signinOk').textContent='';if(!p){$('#signinErr').textContent='Enter your Founder password.';return}try{document.body.classList.add('loading');await signIn(p);$('#loginPassword').value='';await ensureMfaForSession();await load(true)}catch(e){if(String(e.message||'').startsWith('MFA_CODE_REQUIRED:')){const fid=String(e.message).split(':').slice(1).join(':');sessionStorage.setItem('btwyn_pending_mfa_factor',fid);$('#signinErr').textContent='Enter your authenticator code to complete Founder sign-in.'}else $('#signinErr').textContent=e.message}finally{document.body.classList.remove('loading')}};$('#loginPassword').addEventListener('keydown',e=>{if(e.key==='Enter')$('#signinBtn').click()});$('#recoveryBtn').onclick=async()=>{$('#signinErr').textContent='';$('#signinOk').textContent='';try{document.body.classList.add('loading');await requestRecovery();$('#signinOk').textContent='Recovery email requested for '+EMAIL+'. Check that mailbox.'}catch(e){$('#signinErr').textContent=e.message}finally{document.body.classList.remove('loading')}};const unlockMfaBtn=$('#unlockMfaBtn');if(unlockMfaBtn)unlockMfaBtn.onclick=async()=>{const code=$('#unlockMfaCode').value.trim(),factorId=sessionStorage.getItem('btwyn_pending_mfa_factor')||'';$('#unlockErr').textContent='';if(!factorId||!code){$('#unlockErr').textContent='Enter the authenticator code.';return}try{document.body.classList.add('loading');await mfaVerifyFactor(factorId,code);sessionStorage.removeItem('btwyn_pending_mfa_factor');$('#unlockMfaCode').value='';$('#unlockMfaPanel').style.display='none';$('#unlockBtn').style.display='';localStorage.removeItem('btwyn_locked');await load(true)}catch(e){$('#unlockErr').textContent=e.message||'MFA verification failed.'}finally{document.body.classList.remove('loading')}};$('#unlockMfaCode')?.addEventListener('keydown',e=>{if(e.key==='Enter')unlockMfaBtn.click()});$('#unlockBtn').onclick=()=>{localStorage.removeItem('btwyn_locked');load(true)};$('#signoutBtn').onclick=()=>{clearSession();showGate()};$('#refresh').onclick=()=>load(true);$('#lock').onclick=()=>{localStorage.setItem('btwyn_locked','1');showGate()};$('#setPasswordBtn').onclick=async()=>{const p=$('#newPassword').value,c=$('#confirmPassword').value;$('#passwordErr').textContent='';$('#passwordOk').textContent='';if(p!==c){$('#passwordErr').textContent='Passwords do not match.';return}try{document.body.classList.add('loading');await setPassword(p);$('#newPassword').value='';$('#confirmPassword').value='';$('#passwordOk').textContent='Founder password updated. New-device sign-in is now enabled.';await load(true);setView('system')}catch(e){$('#passwordErr').textContent=e.message}finally{document.body.classList.remove('loading')}};$$('[data-view]').forEach(b=>b.onclick=()=>setView(b.dataset.view));const mfaEnrollBtn=$('#mfaEnrollBtn'),mfaVerifyBtn=$('#mfaVerifyBtn');async function refreshMfaUi(){try{const s=await mfaStatus();$('#mfaStatus').innerHTML=s.enrolled?'Authenticator MFA enabled. Current session: '+esc(String(s.aal).toUpperCase()):'Authenticator MFA is not enrolled yet.';if(s.enrolled&&mfaEnrollBtn)mfaEnrollBtn.style.display='none'}catch(e){if($('#mfaStatus'))$('#mfaStatus').textContent='MFA status unavailable.'}}if(mfaEnrollBtn)mfaEnrollBtn.onclick=async()=>{const ok=$('#mfaOk'),er=$('#mfaErr');ok.textContent='';er.textContent='';try{mfaEnrollBtn.disabled=true;const d=await mfaEnrollStart();$('#mfaQr').src=d.qr_code||'';$('#mfaSecret').textContent=d.secret||'';$('#mfaSetup').style.display='block';ok.textContent='MFA enrollment started. Scan the QR code, then verify a code below.'}catch(e){er.textContent=e.message}finally{mfaEnrollBtn.disabled=false}};if(mfaVerifyBtn)mfaVerifyBtn.onclick=async()=>{const ok=$('#mfaOk'),er=$('#mfaErr');ok.textContent='';er.textContent='';try{const factorId=sessionStorage.getItem('btwyn_mfa_factor_id')||'',code=$('#mfaCode').value.trim();if(!factorId||!code)throw new Error('Enter the authenticator code.');mfaVerifyBtn.disabled=true;await mfaVerifyFactor(factorId,code);sessionStorage.removeItem('btwyn_mfa_factor_id');$('#mfaSetup').style.display='none';$('#mfaCode').value='';ok.textContent='Founder MFA enabled. AAL2 protection is now active.';await load(true);await refreshMfaUi()}catch(e){er.textContent=e.message}finally{mfaVerifyBtn.disabled=false}};if(!window.__btwynEarlyBootScheduled){captureRecoveryHash();load().then(()=>refreshMfaUi())}else{setTimeout(()=>{if(window.__btwynBootComplete)refreshMfaUi().catch(()=>{})},250)}(function(){const b=document.getElementById('graphPreviewBtn');if(!b)return;b.onclick=async function(){const ok=document.getElementById('graphPreviewOk'),er=document.getElementById('graphPreviewErr');if(ok)ok.textContent='';if(er)er.textContent='';b.disabled=true;try{const d=await runGraphPreview();if(ok)ok.textContent='PASS — Graph credentials: '+String(d.credentials_configured)+'. Mailbox access: '+String(d.mailbox_access)+'. Mailbox: '+String(d.mailbox)+'. Recorded sent emails: '+String(d.sent_evidence?.sent_count||0)+'. Latest sent: '+String(d.sent_evidence?.latest_sent_at||'—')}catch(e){if(er)er.textContent=e?.message||'Graph preview failed.'}finally{b.disabled=false}}})();