All requests are evaluated for safety, compliance, and execution capacity.
Forecast — Decisions Required(2)
ACO Partnership Contract
Horizon Health Partners • $4.2M annual value
Mon
Dr. Williams strategic analysis: 23% margin improvement projected, aligns with value-based care initiative
Board vote scheduled Monday. Contract includes shared savings model with 45% upside on quality metrics. CFO recommends approval with amended termination clause.
State DHHS Audit Response
Compliance Review • 42 CFR Part 2
Dec 20
Dr. Chen compliance assessment: 3 minor findings, all corrective actions documented
Annual state audit findings require executive sign-off. No material issues. Response letter drafted by compliance team.
Forecast — Strategic Items(3)
Q4 Board Presentation
Strategic Review • January 8, 2025
25 days
Annual strategic review presentation. Key topics: AI platform performance, pilot expansion plan, 2025 growth targets.
Pilot Site Expansion
3 New Facilities Proposed • Q1 2025
Planning
Phoenix Recovery (AZ), Harbor Behavioral (CA), Summit Treatment (CO) have completed technical readiness. Combined 450 new beds.
SAMHSA CCBHC Grant
$2.4M • Letter of Intent Submitted
Pending
Expansion grant for integrated care model. Funds AI-powered crisis prediction expansion to 5 additional sites.
Completed This Week(2)
BlueCross Contract Signed
In-network status • Effective Jan 1
Signed
CMO Search Finalized
Dr. Chen starts Feb 1
Complete
Financial Alerts(1)
Days in A/R Exceeds Target
48 days • Target: 35 days • $890K impact
Review
Dr. Taylor analytics: Denial rate up 12% — primarily prior auth issues with Aetna plans
Accounts receivable aging has deteriorated 37% since October. Root cause: increased denial rate from commercial payers. Revenue cycle team recommends dedicated appeals resource.
Financial Tasks(3)
Q4 Close — Accruals Review
Year-end adjustments • $2.1M accrued expenses
Dec 31
Final review of year-end accruals. Key items: deferred revenue recognition, bonus accruals, and vendor true-ups.
2025 Operating Budget
Final Board Approval • $18.4M total
Jan 8
Operating budget finalized. 12% revenue growth projected. Key investments: AI platform expansion, 3 new pilot sites, staffing increases.
CMS Reimbursement Rate Analysis
2025 OPPS Final Rule • -1.3% impact projected
Planning
New Medicare rates effective Jan 1. Behavioral health carve-in changes require payer contract renegotiations. Net impact -$340K annually.
On Track(2)
Operating Margin
8.2% YTD • Target: 7%
Exceeds
Cash Position
$4.8M • 5.2 months runway
Healthy
Nursing Attention Required(2)
Night Shift Staffing Ratio
1:8 ratio • Target: 1:6 • Unit 2B
Tonight
Dr. Olivia behavioral alert: Higher acuity patients on 2B — 3 active crisis protocols
Two call-outs for tonight's shift. Float pool contacted. PRN nurse confirmed for 11p-7a. Charge nurse aware of coverage gap 7p-11p.
Fall Risk — Unit 3A
2 incidents this week • Both during shift change
Review
Two patient falls during 7am shift change. No injuries reported. Root cause: inadequate handoff during high-risk patient transfer.
Care Coordination(2)
Discharge Planning Backlog
14 patients • Avg 2.3 days past target
Ongoing
Delayed discharges primarily due to outpatient follow-up scheduling. Case management working with community partners to expedite.
MAT Training Compliance
87% complete • 8 nurses due for recert
Dec 31
Annual MAT certification renewal. Online modules available. 8 nurses need to complete before year-end for compliance.
Meeting Standards(2)
Patient Satisfaction — Nursing
4.6/5.0 • Top quartile
Excellent
Medication Error Rate
0.02% • Below benchmark
Target Met
Clinical Quality Alerts(1)
30-Day Readmission Rate Elevated
18% • Target: 12% • 14 patients
Analyze
Dr. Olivia pattern analysis: 71% readmits had <3 days between discharge and first crisis indicator
Readmission spike correlates with shortened length of stay initiative. AI analysis suggests discharge criteria may be premature for high-acuity SUD patients.
Medical Staff Items(3)
Peer Review — 3 Cases Pending
Quality Committee • Due this month
Dec 20
Three cases flagged for peer review: 2 medication dosing questions, 1 treatment plan adequacy. Committee meeting scheduled Friday.
MAT Protocol Update
Buprenorphine guidelines • ASAM 2024 standards
Jan 15
Update clinical protocols to align with new ASAM guidelines. Key changes: flexible dosing, telehealth prescribing, take-home allowances.
Credentialing Renewals
2 physicians due • Q1 2025
Feb 1
Dr. Martinez and Dr. Patel credentials expire Feb 1. Applications submitted, pending verification. No concerns anticipated.
Quality Targets Met(2)
Treatment Completion Rate
76% • SAMHSA benchmark: 65%
Exceeds
Crisis Prediction Accuracy
94% sensitivity • AI Council validated
Validated
Operations Watch(2)
Bed Capacity at 92%
46/50 beds occupied • 4 pending admits
Monitor
Dr. Williams forecast: 3 discharges expected tomorrow, waitlist has 7 patients
Near capacity with holiday admissions surge. Discharge planning prioritized. Overflow protocols on standby if occupancy hits 96%.
Intake Evaluation Backlog
14 pending evals • Avg wait: 2.3 days
48h
Intake bottleneck due to clinical staff PTO. Telehealth evaluations offered to reduce wait times. 6 scheduled for tomorrow.
Operational Tasks(2)
Wearable Vendor Contract Renewal
BioSense Inc • $340K annual • Expires Jan 31
Jan 15
Contract renewal with 8% price increase. Negotiating volume discount based on pilot expansion. Alternative vendor quotes obtained.
CARF Survey Preparation
Accreditation survey • January 15-17
32 days
Three-year accreditation renewal. Mock survey completed with 2 minor findings (both corrected). Staff preparation sessions scheduled next week.
On Target(2)
Average Length of Stay
28 days • Target: 30 days
Efficient
Facility Utilization
89% avg • Optimal range
Balanced
`
: '';
// Show gate triggers if any
const triggerDisplay = gateTriggers.length > 0
? `
';
}
// Correlation ID + Timestamp
validationHTML += `
Correlation ID:${pcodeId}
Timestamp: ${new Date().toISOString()}
State: ${pcode.status || 'Awaiting'}
Export:
`;
// Show in a drawer or modal
showEvidenceDrawer(validationHTML, pcodeId);
}
// Show evidence drawer
function showEvidenceDrawer(content, pcodeId) {
// Check if drawer exists, if not create it
let drawer = document.getElementById('evidence-drawer');
if (!drawer) {
drawer = document.createElement('div');
drawer.id = 'evidence-drawer';
drawer.className = 'evidence-drawer';
document.body.appendChild(drawer);
}
drawer.innerHTML = `
Evidence — P-${pcodeId.substring(0,8)}...
${content}
`;
drawer.classList.add('active');
}
function closeEvidenceDrawer() {
const drawer = document.getElementById('evidence-drawer');
if (drawer) {
drawer.classList.remove('active');
}
}
// ============================================
// AUTHORIZATION - POST to /pcode/issue (VERIFIED LIVE)
// "Authorize & Start Execution" button handler
// No simulated execution. Server truth only.
// ============================================
async function authorizeFromBackend(pcodeId) {
console.log('🔐 Authorizing P-code:', pcodeId);
// Show loading state
const btn = document.querySelector('.btn-primary-action');
if (btn) {
btn.disabled = true;
btn.textContent = 'Authorizing...';
}
// Find the P-code to get its details
const pcode = liveDataset.find(p => p.pcode === pcodeId);
if (!pcode) {
showErrorInModal('P-code not found', 'Could not locate task in dataset.', 'Refresh and retry.');
return;
}
// VERIFIED PAYLOAD STRUCTURE - matches working /pcode/issue endpoint
const payload = {
source: "executive-console-authorize",
requested_by: "jb",
domain_class: pcode.primaryDomain || pcode.domain || 'Operations',
urgency_class: "Priority",
impact_class: pcode.impact || "Strategic",
authorization_class: "Executive",
tenant_id: "rni-default-tenant",
origin_request: `[AUTHORIZED] ${pcode.origin_request || pcodeId}`
};
console.log('📤 POST /pcode/issue (authorize):', payload);
try {
const response = await fetch(PCODE_ISSUE_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json().catch(() => ({}));
// RESPONSE HANDLING:
if (result.pcode) {
// Success - authorized and new P-code issued
console.log('✓ Authorization successful:', result.pcode);
showSuccessToast(`Authorized. New P-code: ${result.pcode}`);
closeGovernanceModal();
clearSelectionStates();
// Update local state
pcode.status = 'active';
pcode.percent_complete = 1;
renderSidebar();
renderMainPanel();
// Start polling for progress updates
startStatusPolling(result.pcode);
} else if (response.status === 404) {
// 404 → "Execution service not reachable" (NOT approval)
console.error('✗ Execution service not reachable (404)');
showErrorInModal('Execution service not reachable',
'The execution service is not responding. This is a system error, not a governance hold.',
'Fallback mode activated. Manual control enabled.');
activateFallbackMode({ domain: pcode.domain }, 'Authorization service unreachable (404)');
} else if (response.status === 500) {
// 500 → Blocked (red) + Fallback
console.error('✗ Server error (500):', result);
showErrorInModal('Server Error',
result.error || 'The server encountered an error processing this request.',
'Fallback mode activated. Manual control enabled.');
pcode.status = 'blocked';
pcode.error = result.error || 'Server error';
renderSidebar();
renderMainPanel();
closeGovernanceModal();
activateFallbackMode({ domain: pcode.domain }, 'Server error (500)');
} else {
console.error('✗ ISSUER ERROR:', response.status, result);
showErrorInModal('Issuer Error',
result.error || 'The issuer returned an error.',
'Manual control available.');
}
} catch (error) {
// Network failure = service unreachable - ACTIVATE FALLBACK
console.error('✗ Network error:', error);
showErrorInModal('Network Error',
`Could not reach execution service: ${error.message}`,
'Fallback mode activated. Manual control enabled.');
activateFallbackMode({ domain: pcode.domain }, `Authorization network error: ${error.message}`);
} finally {
// Reset button state
if (btn) {
btn.disabled = false;
btn.textContent = 'Authorize & Start Execution';
}
}
}
// Show error IN the modal (not as separate alert)
function showErrorInModal(title, reason, action) {
const container = document.getElementById('modal-content');
if (!container) return;
// Find or create error display area
let errorDiv = container.querySelector('.modal-error');
if (!errorDiv) {
errorDiv = document.createElement('div');
errorDiv.className = 'modal-error';
errorDiv.style.cssText = 'margin: 16px 0; padding: 12px; background: #fef2f2; border-radius: 8px; border-left: 4px solid #dc2626;';
container.querySelector('.modal-body').after(errorDiv);
}
errorDiv.innerHTML = `
✗ ${title}
Reason: ${reason}
Action: ${action}
`;
}
// ============================================
// MASTER REFRESH - Backend truth overwrites all
// Single source of truth. Left column and center mirror SAME record.
// ============================================
// ============================================
// REV 65 — PHASE 5 & 6: LIVE BACKEND POLLING
// /pcode/recent for activity panel and Phoenix check
// ============================================
async function refreshFromBackend() {
try {
console.log('🔄 Fetching /pcode/recent...');
const response = await fetch(PCODE_RECENT_ENDPOINT);
if (response.status === 404) {
console.warn('⚠️ /pcode/recent not available (404)');
updatePhoenixStatus('unknown');
return;
}
if (!response.ok) {
console.warn('⚠️ Backend fetch failed:', response.status);
updatePhoenixStatus('unknown');
return;
}
const data = await response.json();
console.log('ISSUER → UI /pcode/recent:', data);
// Extract pcodes array from response
let rawPcodes = [];
if (data && Array.isArray(data.pcodes)) {
rawPcodes = data.pcodes;
} else if (data && Array.isArray(data)) {
rawPcodes = data;
} else {
console.warn('Unexpected response format:', data);
return;
}
// Take last 5 P-codes for activity panel
liveDataset = rawPcodes.slice(0, 5).map(normalizeBackendPcode);
console.log(`✅ Loaded ${liveDataset.length} P-codes from backend`);
// PHASE 5: Check Phoenix escalation status
checkPhoenixEscalationStatus(liveDataset);
// Re-render both views
renderSidebar();
renderMainPanel();
} catch (error) {
console.error('❌ Backend refresh error:', error);
updatePhoenixStatus('unknown');
}
}
// ============================================
// PHASE 5: PHOENIX ESCALATION CHECK
// If newest P-code has no orchestrator status after 10s → ESCALATION ACTIVE
// ============================================
function checkPhoenixEscalationStatus(pcodes) {
if (!pcodes || pcodes.length === 0) {
updatePhoenixStatus('idle');
return;
}
const newest = pcodes[0];
const now = new Date();
const issuedAt = new Date(newest.started_at || newest.created_at || now);
const ageMs = now - issuedAt;
// If newest P-code is less than 10s old and has no orchestrator status
if (ageMs < PHOENIX_CHECK_DELAY && !newest.orchestrator_status) {
// Still waiting - check again later
console.log('⏳ Phoenix check: P-code too new, waiting...');
updatePhoenixStatus('watching');
return;
}
// If older than 10s and still no orchestrator status → ESCALATION
if (ageMs >= PHOENIX_CHECK_DELAY && !newest.orchestrator_status) {
console.warn('🔄 AUTOMATED RECOVERY ACTIVE - No orchestrator status');
updatePhoenixStatus('escalation');
return;
}
// Has orchestrator status → healthy
console.log('✅ Phoenix check: Orchestrator healthy');
updatePhoenixStatus('healthy');
}
// ============================================
// PHOENIX STATUS UI UPDATE
// ============================================
function updatePhoenixStatus(status) {
phoenixStatus = status;
console.log('PHOENIX STATUS:', phoenixStatus);
const phoenixNode = document.querySelector('.pipeline-node.node-blue');
if (!phoenixNode) return;
const statusEl = phoenixNode.querySelector('.pipeline-node-status');
if (!statusEl) return;
// Executive-grade status labels with color chips
switch(status) {
case 'escalation':
// Recovering - amber, brief state
statusEl.innerHTML = '🔄 Fully Self-Healing...';
statusEl.style.color = '#f59e0b';
phoenixNode.style.animation = 'subtle-pulse 2s ease-in-out infinite';
showRecoveryBanner();
break;
case 'watching':
statusEl.innerHTML = '🔄 Fully Self-Healing...';
statusEl.style.color = '#f59e0b';
phoenixNode.style.animation = '';
break;
case 'healthy':
statusEl.innerHTML = '✓ Fully Self-Healed';
statusEl.style.color = '#10b981';
phoenixNode.style.animation = '';
hideRecoveryBanner();
break;
case 'idle':
statusEl.innerHTML = '✓ Stable';
statusEl.style.color = '#10b981';
phoenixNode.style.animation = '';
hideRecoveryBanner();
break;
default:
statusEl.innerHTML = '✓ Stable';
statusEl.style.color = '#10b981';
phoenixNode.style.animation = '';
}
}
// ============================================
// AUTOMATED RECOVERY BANNER
// Executive-grade messaging, Phoenix lives in tooltip only
// ============================================
function showRecoveryBanner() {
// Remove existing banner if any
hideRecoveryBanner();
const banner = document.createElement('div');
banner.id = 'recovery-banner';
banner.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
background: linear-gradient(90deg, #f59e0b, #d97706);
color: white;
padding: 12px 20px;
text-align: center;
z-index: 10001;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
`;
banner.innerHTML = `
🔄 Fully Self-Healing
System handling automatically. No action required.
`;
document.body.prepend(banner);
}
function hideRecoveryBanner() {
const existing = document.getElementById('recovery-banner');
if (existing) existing.remove();
}
// Start periodic refresh
setInterval(refreshFromBackend, RECENT_REFRESH_INTERVAL);
// ============================================
// REV 62 — STATUS POLLING REMOVED
// No orchestrator calls. No /pcode/status polling.
// P-codes display from successful issue responses only.
// ============================================
function startStatusPolling(pcodeId) {
// REMOVED: No status polling
console.log(`📋 P-code ${pcodeId} added to local session`);
}
function stopStatusPolling(pcodeId) {
// REMOVED: No status polling
}
// ============================================
// FILE UPLOAD HANDLER
// ============================================
let uploadedFiles = [];
function handleFileUpload(files) {
if (!files || files.length === 0) return;
const maxFiles = 5;
const maxSizeMB = 10;
Array.from(files).forEach(file => {
if (uploadedFiles.length >= maxFiles) {
showErrorToast(`Maximum ${maxFiles} files allowed`);
return;
}
if (file.size > maxSizeMB * 1024 * 1024) {
showErrorToast(`${file.name} exceeds ${maxSizeMB}MB limit`);
return;
}
uploadedFiles.push(file);
console.log('📎 File attached:', file.name);
});
updateAttachedFilesDisplay();
showSuccessToast(`${files.length} file(s) attached`);
document.getElementById('file-upload-input').value = '';
}
function updateAttachedFilesDisplay() {
let container = document.getElementById('attached-files-display');
const requestBox = document.querySelector('.request-box');
const actionsDiv = requestBox.querySelector('.request-actions');
if (!container && uploadedFiles.length > 0) {
container = document.createElement('div');
container.id = 'attached-files-display';
container.style.cssText = 'margin-bottom: 12px; display: flex; flex-wrap: wrap; gap: 6px;';
requestBox.insertBefore(container, actionsDiv);
}
if (container) {
if (uploadedFiles.length === 0) {
container.remove();
return;
}
container.innerHTML = uploadedFiles.map((file, i) => `
`; downloadBlob(content, `RNI-Summary-${correlationId.substring(0,8)}.docx`, 'application/msword'); logToAudit(correlationId, 'EXPORT_WORD', 'Narrative artifact generated'); showSuccessToast('Word exported — Executive summary'); } }; // Get evidence data for a correlation ID function getEvidenceData(correlationId) { const pcode = liveDataset.find(p => p.pcode === correlationId) || {}; const outputs = pcode.council_outputs || []; // Build vote string const voteCount = outputs.filter(o => o.vote === 'approve' || o.confidence > 0.5).length; const votes = `${voteCount}/6 Council Approval`; // Build attribution const attribution = outputs.map(o => `${o.doctor || 'Unknown'}: ${o.reasoning?.substring(0,100) || 'No reasoning'}...` ).join('\n'); return { summary: pcode.origin_request || 'No description provided', rationale: pcode.forecast_rationale || 'AI Council analyzed signal patterns and recommended action based on predictive models.', attribution: attribution || 'Council analysis pending', state: pcode.status || 'Awaiting', votes: votes, canon: pcode.canon_citation || 'RNI Governance Canon v1.7', auditSummary: `Signal received → Council convened → ${voteCount}/6 approved → ${pcode.status || 'Awaiting decision'}`, auditHash: `SHA256:${correlationId.substring(0,16)}...` }; } // Download blob helper function downloadBlob(content, filename, mimeType) { const blob = new Blob([content], { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } /* ═══════════════════════════════════════════════════════════════════════════════ TASK DECISION MODAL — Gemini v1.7 Corrected Spec "The decision surface IS the artifact surface" 4 PRIMARY BUTTONS: Execute | Export Word | Export PDF | Pause Evidence is INLINE (not buried in drawer) Word/PDF are FIRST-CLASS ACTIONS (not afterthoughts) ═══════════════════════════════════════════════════════════════════════════════ */ const TASK_DATA = { 'aco-partnership': { id: 'aco-partnership', title: 'ACO Partnership Contract', subtitle: 'Horizon Health Partners • $4.2M annual value', urgency: 'critical', primaryDoctor: 'williams', council: { vote: '5/6 Approve', reasoning: [ { doctor: 'williams', text: '23% margin improvement projected. Aligns with value-based care initiative. ROI timeline: 4.2 months.' }, { doctor: 'chen', text: 'No HIPAA or compliance risk identified. Contract terms acceptable.' }, { doctor: 'olivia', text: 'No patient care disruption anticipated. Care continuity maintained.' }, { doctor: 'rivera', text: 'Care pathways compatible. Integration timeline achievable.' }, { doctor: 'taylor', text: 'Risk models show favorable 18-month outlook.' } ], recommendation: 'Approve with amended termination clause per CFO' }, documents: { terms: { title: 'Contract Terms Summary', content: `
Agreement Overview
Value-based care partnership with Horizon Health Partners for integrated behavioral health services across 12 facilities. Three-year term with two-year renewal options.
Financial Terms
Base payment: $4.2M annually. Shared savings model with 45% upside on quality metrics achievement. Performance bonuses tied to HEDIS measures.
Dr. Williams projects 23% margin improvement based on vendor consolidation and operational efficiency gains.
Break-even Analysis
Implementation costs recovered by Month 8. Full ROI of 340% projected over 36 months.
Assumptions
85% quality metric achievement, 12% patient volume growth, stable reimbursement rates, no major regulatory changes.
` } } }, 'dhhs-audit': { id: 'dhhs-audit', title: 'State DHHS Audit Response', subtitle: 'Compliance Review • 42 CFR Part 2', urgency: 'warning', primaryDoctor: 'chen', council: { vote: '6/6 Approve', reasoning: [ { doctor: 'chen', text: '3 minor findings identified. All corrective actions documented and implemented. No material compliance risk.' }, { doctor: 'williams', text: 'Clean audit supports ACO partnership negotiations. Recommend prompt sign-off.' } ], recommendation: 'Sign off - no material issues' }, documents: { sign: { title: 'Executive Sign-Off Document', content: `
Audit Summary
Annual state DHHS audit completed November 2024. 3 minor findings identified, all with documented corrective actions.
Findings Overview
Training Documentation - 3 staff members missing annual HIPAA refresher certificates. CORRECTED
Policy Update Timing - 2 policies updated 45 days past review date. CORRECTED
Access Log Retention - Logs retained 5 years vs required 6 years. CORRECTED
Certification Statement
I certify that I have reviewed the audit findings and corrective actions, and approve this response for submission to the State Department of Health and Human Services.
SAMHSA Certified Community Behavioral Health Clinic (CCBHC) expansion grant. $2.4M over 3 years. Non-dilutive funding.
Use of Funds
AI-powered crisis prediction expansion to 5 additional sites
Staff training and certification program
Technology infrastructure upgrades
Community outreach and integration
Application Status
LOI Submitted
October 15, 2024
✓
Full Application
November 30, 2024
✓
Review Period
December - February
In Progress
Decision Expected
Q1 2025
Pending
Competitive Position
Strong application with demonstrated outcomes from pilot program. Letters of support from 3 state agencies. Dr. Williams estimates 72% approval probability.