TenantAtlas/app/Support/OpsUx/OperationUxPresenter.php
ahmido d98dc30520 feat: add request-scoped derived state memoization (#198)
## Summary
- add a request-scoped derived-state store with deterministic keying and freshness controls
- adopt the shared contract in ArtifactTruthPresenter, OperationUxPresenter, and RelatedNavigationResolver plus the covered Filament consumers
- add spec, plan, contracts, guardrails, and focused memoization and freshness test coverage for spec 167

## Verification
- vendor/bin/sail artisan test --compact tests/Feature/078/RelatedLinksOnDetailTest.php
- vendor/bin/sail artisan test --compact tests/Feature/078/ tests/Feature/Operations/TenantlessOperationRunViewerTest.php tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php tests/Feature/Monitoring/OperationsTenantScopeTest.php tests/Feature/Verification/VerificationAuthorizationTest.php tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php tests/Feature/Verification/VerificationReportRedactionTest.php tests/Feature/Verification/VerificationReportMissingOrMalformedTest.php tests/Feature/OpsUx/FailureSanitizationTest.php tests/Feature/OpsUx/CanonicalViewRunLinksTest.php
- vendor/bin/sail bin pint --dirty --format agent

## Notes
- Livewire v4.0+ compliance preserved
- provider registration remains in bootstrap/providers.php
- no Filament assets or panel registration changes
- no global-search behavior changes
- no destructive action behavior changes in this PR

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #198
2026-03-28 14:58:30 +00:00

454 lines
16 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\ReasonTranslation\ReasonResolutionEnvelope;
use App\Support\RedactionIntegrity;
use App\Support\Ui\DerivedState\DerivedStateFamily;
use App\Support\Ui\DerivedState\DerivedStateKey;
use App\Support\Ui\DerivedState\RequestScopedDerivedStateStore;
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
{
return self::memoizeGuidance(
run: $run,
variant: 'surface_guidance',
resolver: fn (): ?string => self::buildSurfaceGuidance($run),
);
}
public static function surfaceGuidanceFresh(OperationRun $run): ?string
{
return self::memoizeGuidance(
run: $run,
variant: 'surface_guidance',
resolver: fn (): ?string => self::buildSurfaceGuidance($run),
fresh: true,
);
}
private static function buildSurfaceGuidance(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
{
return self::memoizeExplanation(
run: $run,
variant: 'surface_failure_detail',
resolver: fn (): ?string => self::buildSurfaceFailureDetail($run),
);
}
public static function surfaceFailureDetailFresh(OperationRun $run): ?string
{
return self::memoizeExplanation(
run: $run,
variant: 'surface_failure_detail',
resolver: fn (): ?string => self::buildSurfaceFailureDetail($run),
fresh: true,
);
}
private static function buildSurfaceFailureDetail(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 self::memoizeExplanation(
run: $run,
variant: 'lifecycle_attention_summary',
resolver: fn (): ?string => self::buildLifecycleAttentionSummary($run),
);
}
public static function lifecycleAttentionSummaryFresh(OperationRun $run): ?string
{
return self::memoizeExplanation(
run: $run,
variant: 'lifecycle_attention_summary',
resolver: fn (): ?string => self::buildLifecycleAttentionSummary($run),
fresh: true,
);
}
private static function buildLifecycleAttentionSummary(OperationRun $run): ?string
{
return match (self::freshnessState($run)) {
OperationRunFreshnessState::LikelyStale => 'Likely stale',
OperationRunFreshnessState::ReconciledFailed => 'Automatically reconciled',
default => null,
};
}
public static function governanceOperatorExplanation(OperationRun $run): ?OperatorExplanationPattern
{
return self::resolveGovernanceOperatorExplanation($run);
}
public static function governanceOperatorExplanationFresh(OperationRun $run): ?OperatorExplanationPattern
{
return self::resolveGovernanceOperatorExplanation($run, fresh: true);
}
/**
* @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): ?ReasonResolutionEnvelope
{
return self::memoizeExplanation(
run: $run,
variant: 'reason_envelope_notification',
resolver: fn (): ?ReasonResolutionEnvelope => app(ReasonPresenter::class)->forOperationRun($run, 'notification'),
);
}
private static function operatorExplanationGuidance(OperationRun $run): ?string
{
$operatorExplanation = self::resolveGovernanceOperatorExplanation($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 resolveGovernanceOperatorExplanation(OperationRun $run, bool $fresh = false): ?OperatorExplanationPattern
{
if (! $run->supportsOperatorExplanation()) {
return null;
}
return self::memoizeExplanation(
run: $run,
variant: 'governance_operator_explanation',
resolver: fn (): ?OperatorExplanationPattern => $fresh
? app(ArtifactTruthPresenter::class)->forOperationRunFresh($run)?->operatorExplanation
: app(ArtifactTruthPresenter::class)->forOperationRun($run)?->operatorExplanation,
fresh: $fresh,
);
}
private static function memoizeGuidance(
OperationRun $run,
string $variant,
callable $resolver,
bool $fresh = false,
): ?string {
$key = DerivedStateKey::fromModel(DerivedStateFamily::OperationUxGuidance, $run, $variant);
/** @var ?string $value */
$value = $fresh
? self::derivedStateStore()->resolveFresh(
$key,
$resolver,
DerivedStateFamily::OperationUxGuidance->defaultFreshnessPolicy(),
DerivedStateFamily::OperationUxGuidance->allowsNegativeResultCache(),
)
: self::derivedStateStore()->resolve(
$key,
$resolver,
DerivedStateFamily::OperationUxGuidance->defaultFreshnessPolicy(),
DerivedStateFamily::OperationUxGuidance->allowsNegativeResultCache(),
);
return $value;
}
private static function memoizeExplanation(
OperationRun $run,
string $variant,
callable $resolver,
bool $fresh = false,
): mixed {
$key = DerivedStateKey::fromModel(DerivedStateFamily::OperationUxExplanation, $run, $variant);
return $fresh
? self::derivedStateStore()->resolveFresh(
$key,
$resolver,
DerivedStateFamily::OperationUxExplanation->defaultFreshnessPolicy(),
DerivedStateFamily::OperationUxExplanation->allowsNegativeResultCache(),
)
: self::derivedStateStore()->resolve(
$key,
$resolver,
DerivedStateFamily::OperationUxExplanation->defaultFreshnessPolicy(),
DerivedStateFamily::OperationUxExplanation->allowsNegativeResultCache(),
);
}
private static function derivedStateStore(): RequestScopedDerivedStateStore
{
return app(RequestScopedDerivedStateStore::class);
}
}