TenantAtlas/app/Support/OpsUx/OperationUxPresenter.php
ahmido 1f0cc5de56 feat: implement operator explanation layer (#191)
## Summary
- add the shared operator explanation layer with explanation families, trustworthiness semantics, count descriptors, and centralized badge mappings
- adopt explanation-first rendering across baseline compare, governance operation run detail, baseline snapshot presentation, tenant review detail, and review register rows
- extend reason translation, artifact-truth presentation, fallback ops UX messaging, and focused regression coverage for operator explanation semantics

## Testing
- vendor/bin/sail bin pint --dirty --format agent
- vendor/bin/sail artisan test --compact tests/Feature/Monitoring/OperationsTenantScopeTest.php tests/Feature/Operations/OperationRunBlockedExecutionPresentationTest.php
- vendor/bin/sail artisan test --compact

## Notes
- Livewire v4 compatible
- panel provider registration remains in bootstrap/providers.php
- no destructive Filament actions were added or changed in this PR
- no new global-search behavior was introduced in this slice

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #191
2026-03-24 11:24:33 +00:00

318 lines
11 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Support\OpsUx;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\OperationCatalog;
use App\Support\Operations\OperationRunFreshnessState;
use App\Support\ReasonTranslation\ReasonPresenter;
use App\Support\RedactionIntegrity;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter;
use App\Support\Ui\OperatorExplanation\OperatorExplanationPattern;
use Filament\Notifications\Notification as FilamentNotification;
final class OperationUxPresenter
{
public const int QUEUED_TOAST_DURATION_MS = 4000;
public const int FAILURE_MESSAGE_MAX_CHARS = 140;
/**
* Queued intent feedback toast (ephemeral, not persisted).
*/
public static function queuedToast(string $operationType): FilamentNotification
{
$operationLabel = OperationCatalog::label($operationType);
return FilamentNotification::make()
->title("{$operationLabel} queued")
->body('Queued for execution. Open the run for progress and next steps.')
->info()
->duration(self::QUEUED_TOAST_DURATION_MS);
}
/**
* Canonical dedupe feedback when a matching run is already active.
*/
public static function alreadyQueuedToast(string $operationType): FilamentNotification
{
$operationLabel = OperationCatalog::label($operationType);
return FilamentNotification::make()
->title("{$operationLabel} already queued")
->body('A matching run is already queued or running. No action needed unless it stays stuck.')
->info()
->duration(self::QUEUED_TOAST_DURATION_MS);
}
/**
* Terminal DB notification payload.
*
* Note: We intentionally return the built Filament notification builder to
* keep DB formatting consistent with existing Notification classes.
*/
public static function terminalDatabaseNotification(OperationRun $run, ?Tenant $tenant = null): FilamentNotification
{
$operationLabel = OperationCatalog::label((string) $run->type);
$presentation = self::terminalPresentation($run);
$bodyLines = [$presentation['body']];
$failureMessage = self::surfaceFailureDetail($run);
if ($failureMessage !== null) {
$bodyLines[] = $failureMessage;
}
$guidance = self::surfaceGuidance($run);
if ($guidance !== null) {
$bodyLines[] = $guidance;
}
$summary = SummaryCountsNormalizer::renderSummaryLine(is_array($run->summary_counts) ? $run->summary_counts : []);
if ($summary !== null) {
$bodyLines[] = $summary;
}
$integritySummary = RedactionIntegrity::noteForRun($run);
if (is_string($integritySummary) && trim($integritySummary) !== '') {
$bodyLines[] = trim($integritySummary);
}
$notification = FilamentNotification::make()
->title("{$operationLabel} {$presentation['titleSuffix']}")
->body(implode("\n", $bodyLines))
->status($presentation['status']);
if ($tenant instanceof Tenant) {
$notification->actions([
\Filament\Actions\Action::make('view')
->label('View run')
->url(OperationRunUrl::view($run, $tenant)),
]);
}
return $notification;
}
public static function surfaceGuidance(OperationRun $run): ?string
{
$uxStatus = OperationStatusNormalizer::toUxStatus($run->status, $run->outcome);
$reasonEnvelope = self::reasonEnvelope($run);
$reasonGuidance = app(ReasonPresenter::class)->guidance($reasonEnvelope);
$operatorExplanationGuidance = self::operatorExplanationGuidance($run);
$nextStepLabel = self::firstNextStepLabel($run);
$freshnessState = self::freshnessState($run);
if ($freshnessState->isLikelyStale()) {
return 'This run is past its lifecycle window. Review worker health and logs before retrying from the start surface.';
}
if ($freshnessState->isReconciledFailed()) {
return $operatorExplanationGuidance
?? $reasonGuidance
?? 'TenantPilot reconciled this run after lifecycle truth was lost. Review the recorded evidence before retrying.';
}
if (in_array($uxStatus, ['blocked', 'failed', 'partial'], true)) {
if ($operatorExplanationGuidance !== null) {
return $operatorExplanationGuidance;
}
if ($reasonGuidance !== null) {
return $reasonGuidance;
}
}
if ($uxStatus === 'succeeded' && $operatorExplanationGuidance !== null) {
return $operatorExplanationGuidance;
}
return match ($uxStatus) {
'queued' => 'No action needed yet. The run is waiting for a worker.',
'running' => 'No action needed yet. The run is currently in progress.',
'succeeded' => 'No action needed.',
'partial' => $nextStepLabel !== null
? 'Next step: '.$nextStepLabel.'.'
: (self::requiresFollowUp($run)
? 'Review the affected items before rerunning.'
: 'No action needed unless the recorded warnings were unexpected.'),
'blocked' => $nextStepLabel !== null
? 'Next step: '.$nextStepLabel.'.'
: 'Review the blocked prerequisite before retrying.',
default => $nextStepLabel !== null
? 'Next step: '.$nextStepLabel.'.'
: 'Review the run details before retrying.',
};
}
public static function surfaceFailureDetail(OperationRun $run): ?string
{
$operatorExplanation = self::governanceOperatorExplanation($run);
if (is_string($operatorExplanation?->dominantCauseExplanation) && trim($operatorExplanation->dominantCauseExplanation) !== '') {
return trim($operatorExplanation->dominantCauseExplanation);
}
$failureMessage = (string) (($run->failure_summary[0]['message'] ?? '') ?? '');
$sanitizedFailureMessage = self::sanitizeFailureMessage($failureMessage);
if ($sanitizedFailureMessage !== null) {
return $sanitizedFailureMessage;
}
$reasonEnvelope = self::reasonEnvelope($run);
if ($reasonEnvelope !== null) {
return $reasonEnvelope->shortExplanation;
}
if (self::freshnessState($run)->isLikelyStale()) {
return 'This run is no longer within its normal lifecycle window and may no longer be progressing.';
}
return null;
}
public static function freshnessState(OperationRun $run): OperationRunFreshnessState
{
return $run->freshnessState();
}
public static function lifecycleAttentionSummary(OperationRun $run): ?string
{
return match (self::freshnessState($run)) {
OperationRunFreshnessState::LikelyStale => 'Likely stale',
OperationRunFreshnessState::ReconciledFailed => 'Automatically reconciled',
default => null,
};
}
/**
* @return array{titleSuffix: string, body: string, status: string}
*/
private static function terminalPresentation(OperationRun $run): array
{
$uxStatus = OperationStatusNormalizer::toUxStatus($run->status, $run->outcome);
$reasonEnvelope = self::reasonEnvelope($run);
$freshnessState = self::freshnessState($run);
if ($freshnessState->isReconciledFailed()) {
return [
'titleSuffix' => 'was automatically reconciled',
'body' => $reasonEnvelope?->operatorLabel ?? 'Automatically reconciled after infrastructure failure.',
'status' => 'danger',
];
}
return match ($uxStatus) {
'succeeded' => [
'titleSuffix' => 'completed successfully',
'body' => 'Completed successfully.',
'status' => 'success',
],
'partial' => [
'titleSuffix' => self::requiresFollowUp($run) ? 'needs follow-up' : 'completed with review notes',
'body' => 'Completed with follow-up.',
'status' => 'warning',
],
'blocked' => [
'titleSuffix' => 'blocked by prerequisite',
'body' => $reasonEnvelope?->operatorLabel ?? 'Blocked by prerequisite.',
'status' => 'warning',
],
default => [
'titleSuffix' => 'execution failed',
'body' => $reasonEnvelope?->operatorLabel ?? 'Execution failed.',
'status' => 'danger',
],
};
}
private static function requiresFollowUp(OperationRun $run): bool
{
if (self::firstNextStepLabel($run) !== null) {
return true;
}
$counts = SummaryCountsNormalizer::normalize(is_array($run->summary_counts) ? $run->summary_counts : []);
return (int) ($counts['failed'] ?? 0) > 0;
}
private static function firstNextStepLabel(OperationRun $run): ?string
{
$context = is_array($run->context) ? $run->context : [];
$nextSteps = $context['next_steps'] ?? null;
if (! is_array($nextSteps)) {
return null;
}
foreach ($nextSteps as $nextStep) {
if (! is_array($nextStep)) {
continue;
}
$label = trim((string) ($nextStep['label'] ?? ''));
if ($label !== '') {
return $label;
}
}
return null;
}
private static function sanitizeFailureMessage(string $failureMessage): ?string
{
$failureMessage = trim($failureMessage);
if ($failureMessage === '') {
return null;
}
$failureMessage = RunFailureSanitizer::sanitizeMessage($failureMessage);
if (mb_strlen($failureMessage) > self::FAILURE_MESSAGE_MAX_CHARS) {
$failureMessage = mb_substr($failureMessage, 0, self::FAILURE_MESSAGE_MAX_CHARS - 1).'…';
}
return $failureMessage !== '' ? $failureMessage : null;
}
private static function reasonEnvelope(OperationRun $run): ?\App\Support\ReasonTranslation\ReasonResolutionEnvelope
{
return app(ReasonPresenter::class)->forOperationRun($run, 'notification');
}
private static function operatorExplanationGuidance(OperationRun $run): ?string
{
$operatorExplanation = self::governanceOperatorExplanation($run);
if (! is_string($operatorExplanation?->nextActionText) || trim($operatorExplanation->nextActionText) === '') {
return null;
}
$text = trim($operatorExplanation->nextActionText);
if (str_ends_with($text, '.')) {
return $text;
}
return $text === 'No action needed'
? 'No action needed.'
: 'Next step: '.$text.'.';
}
private static function governanceOperatorExplanation(OperationRun $run): ?OperatorExplanationPattern
{
if (! $run->supportsOperatorExplanation()) {
return null;
}
return app(ArtifactTruthPresenter::class)->forOperationRun($run)?->operatorExplanation;
}
}