@push('styles') @endpush
{{-- HEADER STRIP --}}

{{ __('AI Self-Healing Engine') }}

@php $engineEnabled = (bool) ($settings['ai_healing_enabled'] ?? false) && (bool) ($providerInfo['enabled'] ?? false) && (bool) ($providerInfo['has_key'] ?? false); @endphp {{ $engineEnabled ? 'ENGINE ACTIVE' : 'ENGINE DISABLED' }} · Provider: {{ $providerInfo['provider'] }} · Last incident: {{ $lastIncident ? $lastIncident->diffForHumans() : '—' }}

@can('manage ai self-healing') @endcan
{{-- ROW 1: CAPABILITIES (LEFT) | VITAL NUMBERS (MIDDLE) | CRITICAL (RIGHT) --}}
{{-- LEFT: ENGINE CAPABILITIES --}}
{{ __('Engine Capabilities') }}
{{ $engineEnabled ? 'OPERATIONAL' : 'STANDBY' }}
{{-- AI Provider Link --}}
AI Provider Link
{{ $providerInfo['provider'] }} @if(!$providerInfo['has_key']) · KEY MISSING @endif
{{ $providerInfo['enabled'] && $providerInfo['has_key'] ? 'LINKED' : 'OFFLINE' }}
{{-- Exception Interceptor --}}
Exception Interceptor
Captures runtime exceptions for AI analysis
{{ $engineEnabled ? 'LISTENING' : 'PAUSED' }}
{{-- Cache Clearing --}}
Cache Clearing
Flush config / route / view cache
{{ ($settings['ai_healing_allow_cache'] ?? false) ? 'ALLOWED' : 'BLOCKED' }}
{{-- Queue Restart --}}
Queue Restart
Restart failed Horizon / queue workers
{{ ($settings['ai_healing_allow_queue'] ?? false) ? 'ALLOWED' : 'BLOCKED' }}
{{-- Maintenance --}}
Maintenance Toggle
Auto-enable maintenance during critical fixes
{{ ($settings['ai_healing_allow_maintenance'] ?? false) ? 'ALLOWED' : 'BLOCKED' }}
{{-- DB Migration --}}
Database Migration HIGH RISK
Allow AI to run schema migrations
{{ ($settings['ai_healing_allow_db'] ?? false) ? 'ALLOWED' : 'BLOCKED' }}
{{-- MIDDLE: VITAL NUMBERS --}}
TOTAL INTERCEPTS

{{ $stats['total'] }}

{{ $stats['last_24h'] }} in last 24h

AUTO-RESOLVED

{{ $stats['resolved'] }}

FAILED

{{ $stats['failed'] }}

Requires manual review

RESOLUTION RATE

{{ $stats['rate'] }}%

Healing success ratio

{{-- RIGHT: CRITICAL INDICATORS --}}
PENDING ANALYSIS

{{ $stats['pending'] }}

CRITICAL

{{ $stats['failed'] }}

{{-- TABS CONSOLE --}}
{{-- TAB: ACTIVITY FEED --}}
Runtime Activity
ALL · {{ $stats['total'] }} RESOLVED · {{ $stats['resolved'] }} FAILED · {{ $stats['failed'] }} PENDING · {{ $stats['pending'] }} @can('manage ai self-healing') @endcan
@if(count($logs) > 0) @foreach($logs as $log) @endforeach @endif
INCIDENT TIME STATUS EXCEPTION MANIFEST AI DIAGNOSIS INTEL
{{ $log->created_at->format('d M, H:i:s') }} @if($log->status === 'resolved') RESOLVED @elseif($log->status === 'failed') FAILED @else {{ strtoupper($log->status) }} @endif
{{ Str::limit(class_basename($log->error_type), 38) }}
{{ Str::limit($log->error_message, 56) }}
{{ Str::limit($log->ai_diagnosis ?? '-', 60) }}
@can('manage ai self-healing') @if(in_array($log->status, ['failed', 'diagnosing', 'pending'])) @endif @endcan
{{-- TAB: ANALYTICS --}}
Healing Analytics · Last 24 Hours Hourly bucket
Intercept Volume
Top Exception Types
@forelse($topExceptions as $i => $exc)
#{{ $i + 1 }}
{{ $exc['type'] }}
{{ $exc['count'] }} occurrence(s)
{{ $exc['count'] }}
@empty

No data yet

Top exceptions will appear here.

@endforelse
{{-- TAB: CONFIGURATION --}}
Engine Configuration Open Global Settings
@csrf
AI Healing Engine {{ $engineEnabled ? 'ACTIVE' : 'INACTIVE' }}
Master switch · controls whether the interceptor pipeline is active at all.
user()->cannot('manage ai self-healing'))>
Cache Clearing SAFE
Permits the AI to flush application caches (config / route / view / app).
user()->cannot('manage ai self-healing'))>
Queue Restart SAFE
Permits the AI to restart Horizon / queue workers when stalled.
user()->cannot('manage ai self-healing'))>
Maintenance Toggle MEDIUM
Permits the AI to enable maintenance mode during critical incidents.
user()->cannot('manage ai self-healing'))>
Database Migration HIGH RISK
Permits the AI to run schema migrations. Recommended OFF in production.
user()->cannot('manage ai self-healing'))>
Circuit Breaker Threshold
Maximum autonomous repair attempts allowed per hour to prevent infinite loops.
user()->cannot('manage ai self-healing'))>
@can('manage ai self-healing')
@endcan
{{-- TAB: FORENSICS --}}
Incident Distribution
Engine Telemetry
Last Incident
{{ $lastIncident ? $lastIncident->diffForHumans() : 'No incidents' }}
Records (24h)
{{ $stats['last_24h'] }}
All-Time Total
{{ $stats['total'] }}
Success Rate
{{ $stats['rate'] }}%
$ engine.status
provider={{ strtolower($providerInfo['provider']) }} · enabled={{ $engineEnabled ? 'true' : 'false' }} · keyed={{ $providerInfo['has_key'] ? 'true' : 'false' }}
{{-- TAB: DOCUMENTATION --}}
Engine Documentation & Reference v1.1 · Autonomous mode · Tier-based decisions
{{-- HERO INTRO --}}

How the AI Self-Healing Engine works

When an exception is thrown anywhere in the application, the engine intercepts it, reads 25 lines of code around the fault, and asks the AI to classify the bug into one of three tiers with a confidence score. Tier 1 & 2 errors are auto-fixed immediately — no confirmation required. Tier 3 errors (truly ambiguous) are logged for human review. Every code edit writes a .bak.YYYYMMDDhhmmss backup, and one click rolls it back.

PIPELINE
Exception → Tier → Auto-Fix
Capture & classify exception
Resolve fault file from trace
AI tier & confidence scoring
Gate against toggles
Backup → apply → rollback option
{{-- 3-TIER POLICY (NEW) --}}
Three-tier auto-fix policy
TIER 1 conf ≥ 0.80
AUTO-FIX MANDATORY

AI must return a remedy. Applied immediately without human confirmation.

Examples:
  • Typo (variable, method, route, class)
  • Missing use import
  • Unescaped @@can / @@if in Blade text
  • Unmatched directive pairs
  • Stale cache / view / route
  • Failed worker after deploy
  • Wrong helper API (::set vs ::put)
TIER 2 conf 0.50–0.79
BEST-EFFORT FIX

AI attempts the most likely fix when it can identify a concrete change.

Examples:
  • Type mismatch → cast ((int) $id)
  • SQL not portable across drivers (e.g. Postgres lacks DATE_FORMAT) → use Carbon in PHP
  • Missing model attribute with safe fallback
  • Argument count mismatch with obvious signature
TIER 3 conf < 0.50
DO NOT AUTO-FIX

AI returns null with a precise diagnosis. A human must review.

Examples:
  • Business logic / data semantics
  • Multi-file refactor
  • Race conditions / concurrency
  • Anything in vendor/
  • Major block re-creation
  • Healer's own pipeline errors
{{-- CONFIDENCE TAG EXPLAINER --}}
Reading the confidence tag
AI_DIAGNOSIS
[conf=0.92][tier=1] Found unescaped @@can directive in
documentation text at line 1140. Replaced with @@can to make
Blade output it as literal HTML.
Every diagnosis is prefixed with:
  • [conf=0.00–1.00] — how confident the AI was in this fix
  • [tier=1|2|3] — which decision tier was applied
  • Then a ≤ 2-sentence plain-language explanation of what was wrong AND what was changed

Visible in the terminal INCIDENT_DUMP modal under the AI_DIAGNOSIS section.

{{-- ROLLBACK FEATURE (NEW) --}}
One-click rollback for code edits
Every code edit is reversible.

Before the AI overwrites a file, the original is copied to filename.bak.YYYYMMDDhhmmss in the same directory. Open the INCIDENT_DUMP modal of any resolved code-edit incident and you'll see a ↻ ROLLBACK button in the modal header.

Clicking it restores the file from the backup, runs optimize:clear, and tags the log with [rolled back by <user>] in the diagnosis. The rollback button only appears when the backup file still exists on disk — if you delete .bak files manually, rollback becomes unavailable.

{{-- WORKFLOW STEPS --}}
Lifecycle of an incident
@php $steps = [ ['icon'=>'bi-bug', 'color'=>'#ef4444', 'title'=>'1. Intercept', 'desc'=>'Any Throwable (except HttpException & healer-internal errors) is caught at the framework level. A 5-min stuck-state reset frees any orphaned diagnosing logs.'], ['icon'=>'bi-clipboard-data', 'color'=>'#f59e0b', 'title'=>'2. Pending', 'desc'=>'A row is written to ai_healing_logs with status pending. Duplicate exceptions within 2 minutes are skipped.'], ['icon'=>'bi-cpu', 'color'=>'#3b82f6', 'title'=>'3. Diagnosing', 'desc'=>'The healer job runs synchronously, reads ±25 lines of context, builds a tiered prompt with your enabled commands, and calls the AI.'], ['icon'=>'bi-bullseye', 'color'=>'#8b5cf6', 'title'=>'4. Tier & gate', 'desc'=>'AI returns {confidence, tier, code_edit?, action_command?}. Tier 1/2 → proceed. Tier 3 → bail with diagnosis. Commands must pass capability-toggle gate.'], ['icon'=>'bi-floppy', 'color'=>'#06b6d4', 'title'=>'5. Backup', 'desc'=>'Before any code edit, the original file is copied to .bak.YYYYMMDDhhmmss in the same directory. This is what makes rollback possible.'], ['icon'=>'bi-check2-circle', 'color'=>'#22c55e', 'title'=>'6. Resolved', 'desc'=>'Edit applied or Artisan command executed. optimize:clear runs automatically after code edits. Diagnosis is tagged with [conf=][tier=].'], ['icon'=>'bi-arrow-counterclockwise','color'=>'#f59e0b','title'=>'7. Rollback (optional)','desc'=>'Anytime later, open the incident modal → click ↻ ROLLBACK. File is restored from .bak, caches cleared, log tagged [rolled back by <user>].'], ['icon'=>'bi-x-octagon', 'color'=>'#dc2626', 'title'=>'Failed (alt)', 'desc'=>'If invalid JSON, target not found, command refused, or AI marked it Tier 3 — status becomes failed with a precise reason. Click to retry.'], ]; @endphp @foreach($steps as $s)
{{ $s['title'] }}
{!! $s['desc'] !!}
@endforeach
{{-- SOLVABLE GRID --}}
What the engine can resolve
Artisan commands GATED BY TOGGLES
Each command requires the matching capability toggle to be ON.
cache:clear — stale class / model cache
view:clear — deleted / renamed blade
config:clear — .env not reflected
route:clear — route not found after edit
optimize:clear — catch-all (most common)
queue:restart — Horizon workers stale
down / up — maintenance gate
migrate — pending schema change (HIGH RISK)
Code edits .BAK BACKUP WRITTEN
AI must return an EXACT string match that exists in the file.
Typos in variables, methods, class names
Missing or wrong use imports
Wrong route name in helpers
Undefined array keys → safe defaults
Null dereference → null-safe (?->)
Wrong helper API (e.g. Cache::set::put)
Mistyped argument types / casts
{{-- NOT SOLVABLE --}}
What the engine WON'T solve
@php $blockers = [ ['Business logic bugs', 'AI cannot infer intent (e.g. 10% VAT vs 11%).'], ['Race conditions / concurrency', 'Not deducible from a single stack trace.'], ['Performance issues (N+1, slow SQL)', 'Not thrown as exceptions — skipped by the interceptor.'], ['HTTP 4xx / 5xx responses', 'HttpException is intentionally ignored.'], ['Errors inside vendor/', 'Healer refuses to touch third-party code.'], ['Multi-file refactors', 'Only one file / one string replacement per incident.'], ['migrate:fresh', 'Always refused, even when DB toggle is ON (data loss).'], ['Errors from the healer itself', 'Trace-based filter prevents infinite loops.'], ]; @endphp @foreach($blockers as $b)
{!! $b[0] !!}
{!! $b[1] !!}
@endforeach
{{-- REAL-WORLD EXAMPLES --}}
Real-world examples
@php $examples = [ ['View [dashboard] not found', 'yes', 'view:clear if Cache toggle ON'], ['Class "App\\Foo\\Bar" not found', 'yes', 'optimize:clear (stale autoload)'], ['Undefined property: stdClass::$nama in blade', 'yes', 'Code edit: $user->nama$user?->nama ?? \'—\''], ['Route [admin.users.editt] not defined', 'yes', 'Code edit: typo edittedit'], ['QueryException: function date_format() does not exist (Postgres)', 'yes', 'Code edit: bucket in PHP with Carbon instead of SQL'], ['Horizon worker not picking up new code', 'yes', 'queue:restart if Queue toggle ON'], ['TypeError: Argument #1 ($id) must be int, string given', 'yes', 'Code edit: (int) $id cast'], ['User balance goes negative due to race condition', 'no', 'Needs DB::transaction + lockForUpdate — out of scope'], ['Endpoint returns 401 but should return 200', 'no', 'HTTP responses are intentionally not intercepted'], ['Slow query causing timeout', 'no', 'Not thrown as exception'], ]; @endphp @foreach($examples as $ex) @endforeach
EXCEPTION RESOLVABLE HOW
{{ $ex[0] }} @if($ex[1] === 'yes') YES @else NO @endif {!! $ex[2] !!}
{{-- STATUS DICTIONARY --}}
Status dictionary
PENDING
Queued for the healer. Has not been picked up yet.
DIAGNOSING
AI is analyzing. Auto-resets to pending after 5 minutes if stuck.
RESOLVED
Action executed successfully. Reason is stored in action_taken.
FAILED
Refused, invalid, or AI couldn't help. Click to retry.
{{-- TROUBLESHOOTING --}}
Troubleshooting checklist
$ healer --diagnose-self
[1] Provider link is {{ $providerInfo['enabled'] && $providerInfo['has_key'] ? 'LINKED' : 'OFFLINE — set API key in Global Settings → AI Config' }}
[2] Healing engine is {{ $engineEnabled ? 'ENABLED' : 'DISABLED — toggle on Configuration tab' }}
[3] Cache toggle:        {{ ($settings['ai_healing_allow_cache'] ?? false) ? 'on' : 'off' }}
[4] Queue toggle:        {{ ($settings['ai_healing_allow_queue'] ?? false) ? 'on' : 'off' }}
[5] Maintenance toggle:  {{ ($settings['ai_healing_allow_maintenance'] ?? false) ? 'on' : 'off' }}
[6] DB migration toggle: {{ ($settings['ai_healing_allow_db'] ?? false) ? 'on (HIGH RISK)' : 'off' }}
# DEBUGGING A SPECIFIC INCIDENT:
#   1. Click row in Activity Feed → opens terminal modal
#   2. Read [conf=][tier=] tag — tells you why AI chose this path
#   3. If FAILED, action_taken explains the exact refusal reason
#   4. If RESOLVED but fix is wrong, click ↻ ROLLBACK in modal header
#   5. To re-run AI on a failed/stuck log, click ↻ RE-RUN AI
{{-- FOOTER NOTE --}}
Security posture under autonomous mode
Even though Tier 1 & Tier 2 fixes apply without confirmation, the safety perimeter is unchanged: the healer never executes arbitrary shell commands, never touches vendor/, never runs migrate:fresh, and never applies a command that your capability toggles have disabled. Every code edit produces a timestamped .bak next to the original and is reversible via the ↻ ROLLBACK button. A re-entrancy guard (AI_HEALER_RUNNING constant + trace-based filter) prevents the healer from healing its own exceptions.
{{-- TERMINAL INSPECT MODAL --}} @push('scripts') @endpush