Compare commits

..

2 Commits

Author SHA1 Message Date
e840007127 feat: add backup quality truth surfaces (#211)
## Summary
- add a shared backup-quality resolver and summary model for backup sets, backup items, policy versions, and restore selection
- surface backup-quality truth across Filament backup-set, policy-version, and restore-wizard entry points
- add focused Pest coverage and the full Spec Kit artifact set for spec 176

## Testing
- focused backup-quality verification and integrated-browser smoke coverage were completed during implementation
- degraded browser smoke path was validated with temporary seeded records and then cleaned up again
- the workspace already has a prior `vendor/bin/sail artisan test --compact` run exiting non-zero; that full-suite failure was not reworked as part of this PR

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #211
2026-04-07 11:39:40 +00:00
a107e7e41b feat: restore safety integrity and queue slide-over (#210)
## Summary
- add the Spec 181 restore-safety layer with scope fingerprinting, preview/check integrity states, execution safety snapshots, result attention, and operator-facing copy across the wizard, restore detail, and canonical operation detail
- add focused unit and feature coverage for restore-safety assessment, result attention, and restore-linked operation detail
- switch the finding exceptions queue `Inspect exception` action to a native Filament slide-over while preserving query-param-backed inline summary behavior

## Testing
- `vendor/bin/sail artisan test --compact tests/Feature/Monitoring/FindingExceptionsQueueTest.php tests/Feature/Filament/RestoreSafetyIntegrityWizardTest.php tests/Feature/Filament/RestoreResultAttentionSurfaceTest.php tests/Feature/Operations/RestoreLinkedOperationDetailTest.php tests/Unit/Support/RestoreSafety`

## Notes
- Spec 181 checklist is complete (`specs/181-restore-safety-integrity/checklists/requirements.md`)
- the branch still has unchecked follow-up tasks in `specs/181-restore-safety-integrity/tasks.md`: `T012`, `T018`, `T019`, `T023`, `T025`, `T029`, `T032`, `T033`, `T041`, `T042`, `T043`, `T044`
- Filament v5 / Livewire v4 compliance is preserved, no panel provider registration changes were made, no global-search behavior was added, destructive actions remain confirmation-gated, and no new Filament assets were introduced

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #210
2026-04-06 23:37:14 +00:00
32 changed files with 3431 additions and 62 deletions

View File

@ -137,6 +137,8 @@ ## Active Technologies
- PostgreSQL unchanged; existing `operation_runs` JSONB-backed `context`, `summary_counts`, and `failure_summary`; no schema change (178-ops-truth-alignment) - PostgreSQL unchanged; existing `operation_runs` JSONB-backed `context`, `summary_counts`, and `failure_summary`; no schema change (178-ops-truth-alignment)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers (181-restore-safety-integrity) - PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers (181-restore-safety-integrity)
- PostgreSQL with existing `restore_runs` and `operation_runs` records plus JSON or array-backed `metadata`, `preview`, `results`, and `context`; no schema change planned (181-restore-safety-integrity) - PostgreSQL with existing `restore_runs` and `operation_runs` records plus JSON or array-backed `metadata`, `preview`, `results`, and `context`; no schema change planned (181-restore-safety-integrity)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BackupSetResource`, `BackupItemsRelationManager`, `PolicyVersionResource`, `RestoreRunResource`, `CreateRestoreRun`, `AssignmentBackupService`, `VersionService`, `PolicySnapshotService`, `RestoreRiskChecker`, `BadgeRenderer`, `PolicySnapshotModeBadge`, `EnterpriseDetailBuilder`, and existing RBAC helpers (176-backup-quality-truth)
- PostgreSQL with existing tenant-owned `backup_sets`, `backup_items`, `policy_versions`, and restore wizard input state; JSON-backed `metadata`, `snapshot`, `assignments`, and `scope_tags`; no schema change planned (176-backup-quality-truth)
- PHP 8.4.15 (feat/005-bulk-operations) - PHP 8.4.15 (feat/005-bulk-operations)
@ -156,8 +158,8 @@ ## Code Style
PHP 8.4.15: Follow standard conventions PHP 8.4.15: Follow standard conventions
## Recent Changes ## Recent Changes
- 176-backup-quality-truth: Added PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BackupSetResource`, `BackupItemsRelationManager`, `PolicyVersionResource`, `RestoreRunResource`, `CreateRestoreRun`, `AssignmentBackupService`, `VersionService`, `PolicySnapshotService`, `RestoreRiskChecker`, `BadgeRenderer`, `PolicySnapshotModeBadge`, `EnterpriseDetailBuilder`, and existing RBAC helpers
- 181-restore-safety-integrity: Added PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers - 181-restore-safety-integrity: Added PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers
- 178-ops-truth-alignment: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `OperationRun`, `OperationLifecyclePolicy`, `OperationRunFreshnessState`, `OperationUxPresenter`, `OperationRunLinks`, `ActiveRuns`, `StuckRunClassifier`, `WorkspaceOverviewBuilder`, dashboard widgets, workspace widgets, and system ops pages - 178-ops-truth-alignment: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `OperationRun`, `OperationLifecyclePolicy`, `OperationRunFreshnessState`, `OperationUxPresenter`, `OperationRunLinks`, `ActiveRuns`, `StuckRunClassifier`, `WorkspaceOverviewBuilder`, dashboard widgets, workspace widgets, and system ops pages
- 177-inventory-coverage-truth: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `InventoryItem`, `OperationRun`, `InventoryCoverage`, `InventoryPolicyTypeMeta`, `CoverageCapabilitiesResolver`, `InventoryKpiHeader`, `InventoryCoverage` page, and `OperationRunResource` enterprise-detail stack
<!-- MANUAL ADDITIONS START --> <!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END --> <!-- MANUAL ADDITIONS END -->

View File

@ -18,6 +18,7 @@
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Operations\BulkSelectionIdentity; use App\Services\Operations\BulkSelectionIdentity;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\BackupQuality\BackupQualityResolver;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
use App\Support\Filament\TablePaginationProfiles; use App\Support\Filament\TablePaginationProfiles;
@ -161,6 +162,15 @@ public static function table(Table $table): Table
->persistFiltersInSession() ->persistFiltersInSession()
->persistSearchInSession() ->persistSearchInSession()
->persistSortInSession() ->persistSortInSession()
->modifyQueryUsing(fn (Builder $query): Builder => $query->with([
'items' => fn ($itemQuery) => $itemQuery->select([
'id',
'backup_set_id',
'payload',
'metadata',
'assignments',
]),
]))
->columns([ ->columns([
Tables\Columns\TextColumn::make('name') Tables\Columns\TextColumn::make('name')
->searchable() ->searchable()
@ -172,6 +182,11 @@ public static function table(Table $table): Table
->icon(BadgeRenderer::icon(BadgeDomain::BackupSetStatus)) ->icon(BadgeRenderer::icon(BadgeDomain::BackupSetStatus))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::BackupSetStatus)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::BackupSetStatus)),
Tables\Columns\TextColumn::make('item_count')->label('Items')->numeric()->sortable(), Tables\Columns\TextColumn::make('item_count')->label('Items')->numeric()->sortable(),
Tables\Columns\TextColumn::make('backup_quality')
->label('Backup quality')
->state(fn (BackupSet $record): string => static::backupQualitySummary($record)->compactSummary)
->description(fn (BackupSet $record): string => static::backupQualitySummary($record)->nextAction)
->wrap(),
Tables\Columns\TextColumn::make('created_by')->label('Created by')->toggleable(isToggledHiddenByDefault: true), Tables\Columns\TextColumn::make('created_by')->label('Created by')->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('completed_at')->label('Completed')->dateTime()->since()->sortable(), Tables\Columns\TextColumn::make('completed_at')->label('Completed')->dateTime()->since()->sortable(),
Tables\Columns\TextColumn::make('created_at')->label('Captured')->dateTime()->since()->sortable()->toggleable(isToggledHiddenByDefault: true), Tables\Columns\TextColumn::make('created_at')->label('Captured')->dateTime()->since()->sortable()->toggleable(isToggledHiddenByDefault: true),
@ -659,6 +674,12 @@ private static function enterpriseDetailPage(BackupSet $record): EnterpriseDetai
$metadataKeyCount = count($metadata); $metadataKeyCount = count($metadata);
$relatedContext = static::relatedContextEntries($record); $relatedContext = static::relatedContextEntries($record);
$isArchived = $record->trashed(); $isArchived = $record->trashed();
$qualitySummary = static::backupQualitySummary($record);
$qualityBadge = match (true) {
$qualitySummary->totalItems === 0 => $factory->statusBadge('No items', 'gray'),
$qualitySummary->hasDegradations() => $factory->statusBadge('Degraded input', 'warning', 'heroicon-m-exclamation-triangle'),
default => $factory->statusBadge('No degradations', 'success', 'heroicon-m-check-circle'),
};
return EnterpriseDetailBuilder::make('backup_set', 'tenant') return EnterpriseDetailBuilder::make('backup_set', 'tenant')
->header(new SummaryHeaderData( ->header(new SummaryHeaderData(
@ -667,14 +688,37 @@ private static function enterpriseDetailPage(BackupSet $record): EnterpriseDetai
statusBadges: [ statusBadges: [
$factory->statusBadge($statusSpec->label, $statusSpec->color, $statusSpec->icon, $statusSpec->iconColor), $factory->statusBadge($statusSpec->label, $statusSpec->color, $statusSpec->icon, $statusSpec->iconColor),
$factory->statusBadge($isArchived ? 'Archived' : 'Active', $isArchived ? 'warning' : 'success'), $factory->statusBadge($isArchived ? 'Archived' : 'Active', $isArchived ? 'warning' : 'success'),
$qualityBadge,
], ],
keyFacts: [ keyFacts: [
$factory->keyFact('Items', $record->item_count), $factory->keyFact('Items', $record->item_count),
$factory->keyFact('Backup quality', $qualitySummary->compactSummary),
$factory->keyFact('Created by', $record->created_by), $factory->keyFact('Created by', $record->created_by),
$factory->keyFact('Completed', static::formatDetailTimestamp($record->completed_at)), $factory->keyFact('Completed', static::formatDetailTimestamp($record->completed_at)),
$factory->keyFact('Captured', static::formatDetailTimestamp($record->created_at)), $factory->keyFact('Captured', static::formatDetailTimestamp($record->created_at)),
], ],
descriptionHint: 'Lifecycle status, recovery readiness, and related operations stay ahead of raw backup metadata.', descriptionHint: 'Backup quality, lifecycle status, and related operations stay ahead of raw backup metadata.',
))
->decisionZone($factory->decisionZone(
facts: array_values(array_filter([
$factory->keyFact('Backup quality', $qualitySummary->compactSummary, badge: $qualityBadge),
$factory->keyFact('Degraded items', $qualitySummary->degradedItemCount),
$factory->keyFact('Metadata only', $qualitySummary->metadataOnlyCount),
$factory->keyFact('Assignment issues', $qualitySummary->assignmentIssueCount),
$factory->keyFact('Orphaned assignments', $qualitySummary->orphanedAssignmentCount),
$factory->keyFact('Integrity warnings', $qualitySummary->integrityWarningCount),
$qualitySummary->unknownQualityCount > 0
? $factory->keyFact('Unknown quality', $qualitySummary->unknownQualityCount)
: null,
])),
primaryNextStep: $factory->primaryNextStep(
$qualitySummary->nextAction,
'Backup quality',
),
description: 'Start here to judge whether this backup set looks strong or weak as restore input before reading diagnostics or raw metadata.',
compactCounts: $factory->countPresentation(summaryLine: $qualitySummary->summaryMessage),
attentionNote: $qualitySummary->positiveClaimBoundary,
title: 'Backup quality',
)) ))
->addSection( ->addSection(
$factory->factsSection( $factory->factsSection(
@ -700,11 +744,12 @@ private static function enterpriseDetailPage(BackupSet $record): EnterpriseDetai
->addSupportingCard( ->addSupportingCard(
$factory->supportingFactsCard( $factory->supportingFactsCard(
kind: 'status', kind: 'status',
title: 'Recovery readiness', title: 'Backup quality counts',
items: [ items: [
$factory->keyFact('Backup state', $statusSpec->label, badge: $factory->statusBadge($statusSpec->label, $statusSpec->color, $statusSpec->icon, $statusSpec->iconColor)), $factory->keyFact('Degraded items', $qualitySummary->degradedItemCount),
$factory->keyFact('Archived', $isArchived), $factory->keyFact('Metadata only', $qualitySummary->metadataOnlyCount),
$factory->keyFact('Metadata keys', $metadataKeyCount), $factory->keyFact('Assignment issues', $qualitySummary->assignmentIssueCount),
$factory->keyFact('Orphaned assignments', $qualitySummary->orphanedAssignmentCount),
], ],
), ),
$factory->supportingFactsCard( $factory->supportingFactsCard(
@ -740,4 +785,29 @@ private static function formatDetailTimestamp(mixed $value): string
return $value->toDayDateTimeString(); return $value->toDayDateTimeString();
} }
private static function backupQualitySummary(BackupSet $record): \App\Support\BackupQuality\BackupQualitySummary
{
if ($record->trashed()) {
$record->setRelation('items', $record->items()->withTrashed()->select([
'id',
'backup_set_id',
'payload',
'metadata',
'assignments',
])->get());
} elseif (! $record->relationLoaded('items')) {
$record->loadMissing([
'items' => fn ($query) => $query->select([
'id',
'backup_set_id',
'payload',
'metadata',
'assignments',
]),
]);
}
return app(BackupQualityResolver::class)->summarizeBackupSet($record);
}
} }

View File

@ -11,6 +11,7 @@
use App\Models\User; use App\Models\User;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\BackupQuality\BackupQualityResolver;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
use App\Support\Badges\TagBadgeDomain; use App\Support\Badges\TagBadgeDomain;
@ -279,11 +280,32 @@ public function table(Table $table): Table
->sortable() ->sortable()
->searchable() ->searchable()
->getStateUsing(fn (BackupItem $record) => $record->resolvedDisplayName()), ->getStateUsing(fn (BackupItem $record) => $record->resolvedDisplayName()),
Tables\Columns\TextColumn::make('snapshot_mode')
->label('Snapshot')
->badge()
->state(fn (BackupItem $record): string => $this->backupItemQualitySummary($record)->snapshotMode)
->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicySnapshotMode))
->color(BadgeRenderer::color(BadgeDomain::PolicySnapshotMode))
->icon(BadgeRenderer::icon(BadgeDomain::PolicySnapshotMode))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicySnapshotMode)),
Tables\Columns\TextColumn::make('policyVersion.version_number') Tables\Columns\TextColumn::make('policyVersion.version_number')
->label('Version') ->label('Version')
->badge() ->badge()
->default('—') ->default('—')
->getStateUsing(fn (BackupItem $record): ?int => $record->policyVersion?->version_number), ->getStateUsing(fn (BackupItem $record): ?int => $record->policyVersion?->version_number),
Tables\Columns\TextColumn::make('backup_quality')
->label('Backup quality')
->state(fn (BackupItem $record): string => $this->backupItemQualitySummary($record)->compactSummary)
->description(function (BackupItem $record): string {
$summary = $this->backupItemQualitySummary($record);
if ($summary->assignmentCaptureReason === 'separate_role_assignments') {
return 'Assignments are captured separately for this item type.';
}
return $summary->nextAction;
})
->wrap(),
Tables\Columns\TextColumn::make('policy_type') Tables\Columns\TextColumn::make('policy_type')
->label('Type') ->label('Type')
->badge() ->badge()
@ -480,6 +502,11 @@ private function backupItemInspectUrl(BackupItem $record): ?string
return PolicyResource::getUrl('view', ['record' => $resolvedRecord->policy_id], tenant: $tenant); return PolicyResource::getUrl('view', ['record' => $resolvedRecord->policy_id], tenant: $tenant);
} }
private function backupItemQualitySummary(BackupItem $record): \App\Support\BackupQuality\BackupQualitySummary
{
return app(BackupQualityResolver::class)->forBackupItem($record);
}
private function resolveOwnerScopedBackupItemId(BackupSet $backupSet, mixed $record): int private function resolveOwnerScopedBackupItemId(BackupSet $backupSet, mixed $record): int
{ {
$recordId = $this->normalizeBackupItemKey($record); $recordId = $this->normalizeBackupItemKey($record);

View File

@ -21,6 +21,9 @@
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Operations\BulkSelectionIdentity; use App\Services\Operations\BulkSelectionIdentity;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\BackupQuality\BackupQualityResolver;
use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer;
use App\Support\Badges\TagBadgeDomain; use App\Support\Badges\TagBadgeDomain;
use App\Support\Badges\TagBadgeRenderer; use App\Support\Badges\TagBadgeRenderer;
use App\Support\Baselines\PolicyVersionCapturePurpose; use App\Support\Baselines\PolicyVersionCapturePurpose;
@ -107,7 +110,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value) ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions are grouped under "More".') ->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions are grouped under "More".')
->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More".') ->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More".')
->exempt(ActionSurfaceSlot::ListEmptyState, 'Empty-state CTA is intentionally omitted; versions appear after policy sync/capture workflows.') ->satisfy(ActionSurfaceSlot::ListEmptyState, 'Empty-state CTA routes operators to backup sets when no versions are available yet.')
->exempt(ActionSurfaceSlot::DetailHeader, 'View page header actions are intentionally minimal for now.'); ->exempt(ActionSurfaceSlot::DetailHeader, 'View page header actions are intentionally minimal for now.');
} }
@ -129,6 +132,37 @@ public static function infolist(Schema $schema): Schema
->color(TagBadgeRenderer::color(TagBadgeDomain::Platform)), ->color(TagBadgeRenderer::color(TagBadgeDomain::Platform)),
Infolists\Components\TextEntry::make('created_by')->label('Actor'), Infolists\Components\TextEntry::make('created_by')->label('Actor'),
Infolists\Components\TextEntry::make('captured_at')->dateTime(), Infolists\Components\TextEntry::make('captured_at')->dateTime(),
Section::make('Backup quality')
->schema([
Infolists\Components\TextEntry::make('quality_snapshot_mode')
->label('Snapshot')
->badge()
->state(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->snapshotMode)
->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicySnapshotMode))
->color(BadgeRenderer::color(BadgeDomain::PolicySnapshotMode))
->icon(BadgeRenderer::icon(BadgeDomain::PolicySnapshotMode))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicySnapshotMode)),
Infolists\Components\TextEntry::make('quality_summary')
->label('Backup quality')
->state(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->compactSummary),
Infolists\Components\TextEntry::make('quality_assignment_signal')
->label('Assignment quality')
->state(fn (PolicyVersion $record): string => static::policyVersionAssignmentQualityLabel($record)),
Infolists\Components\TextEntry::make('quality_next_action')
->label('Next action')
->state(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->nextAction),
Infolists\Components\TextEntry::make('quality_integrity_warning')
->label('Integrity note')
->state(fn (PolicyVersion $record): ?string => static::policyVersionQualitySummary($record)->integrityWarning)
->visible(fn (PolicyVersion $record): bool => static::policyVersionQualitySummary($record)->hasIntegrityWarning())
->columnSpanFull(),
Infolists\Components\TextEntry::make('quality_boundary')
->label('Boundary')
->state(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->positiveClaimBoundary)
->columnSpanFull(),
])
->columns(2)
->columnSpanFull(),
Section::make('Related context') Section::make('Related context')
->schema([ ->schema([
Infolists\Components\ViewEntry::make('related_context') Infolists\Components\ViewEntry::make('related_context')
@ -528,6 +562,19 @@ public static function table(Table $table): Table
->searchable() ->searchable()
->getStateUsing(fn (PolicyVersion $record): string => static::resolvedDisplayName($record)), ->getStateUsing(fn (PolicyVersion $record): string => static::resolvedDisplayName($record)),
Tables\Columns\TextColumn::make('version_number')->sortable(), Tables\Columns\TextColumn::make('version_number')->sortable(),
Tables\Columns\TextColumn::make('snapshot_mode')
->label('Snapshot')
->badge()
->state(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->snapshotMode)
->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicySnapshotMode))
->color(BadgeRenderer::color(BadgeDomain::PolicySnapshotMode))
->icon(BadgeRenderer::icon(BadgeDomain::PolicySnapshotMode))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicySnapshotMode)),
Tables\Columns\TextColumn::make('backup_quality')
->label('Backup quality')
->state(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->compactSummary)
->description(fn (PolicyVersion $record): string => static::policyVersionQualitySummary($record)->nextAction)
->wrap(),
Tables\Columns\TextColumn::make('policy_type') Tables\Columns\TextColumn::make('policy_type')
->badge() ->badge()
->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::PolicyType)) ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::PolicyType))
@ -536,7 +583,7 @@ public static function table(Table $table): Table
->badge() ->badge()
->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::Platform)) ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::Platform))
->color(TagBadgeRenderer::color(TagBadgeDomain::Platform)), ->color(TagBadgeRenderer::color(TagBadgeDomain::Platform)),
Tables\Columns\TextColumn::make('created_by')->label('Actor'), Tables\Columns\TextColumn::make('created_by')->label('Actor')->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('captured_at')->dateTime()->sortable(), Tables\Columns\TextColumn::make('captured_at')->dateTime()->sortable(),
]) ])
->filters([ ->filters([
@ -578,7 +625,7 @@ public static function table(Table $table): Table
return $resolver->isMember($user, $tenant); return $resolver->isMember($user, $tenant);
}) })
->disabled(function (PolicyVersion $record): bool { ->disabled(function (PolicyVersion $record): bool {
if (($record->metadata['source'] ?? null) === 'metadata_only') { if (static::policyVersionQualitySummary($record)->snapshotMode === 'metadata_only') {
return true; return true;
} }
@ -617,7 +664,7 @@ public static function table(Table $table): Table
return 'You do not have permission to create restore runs.'; return 'You do not have permission to create restore runs.';
} }
if (($record->metadata['source'] ?? null) === 'metadata_only') { if (static::policyVersionQualitySummary($record)->snapshotMode === 'metadata_only') {
return 'Disabled for metadata-only snapshots (Graph did not provide policy settings).'; return 'Disabled for metadata-only snapshots (Graph did not provide policy settings).';
} }
@ -642,7 +689,7 @@ public static function table(Table $table): Table
abort(403); abort(403);
} }
if (($record->metadata['source'] ?? null) === 'metadata_only') { if (static::policyVersionQualitySummary($record)->snapshotMode === 'metadata_only') {
Notification::make() Notification::make()
->title('Restore disabled for metadata-only snapshot') ->title('Restore disabled for metadata-only snapshot')
->body('This snapshot only contains metadata; Graph did not provide policy settings to restore.') ->body('This snapshot only contains metadata; Graph did not provide policy settings to restore.')
@ -699,11 +746,15 @@ public static function table(Table $table): Table
$backupItemMetadata = [ $backupItemMetadata = [
'source' => 'policy_version', 'source' => 'policy_version',
'snapshot_source' => $record->snapshotSource(),
'display_name' => $policy->display_name, 'display_name' => $policy->display_name,
'policy_version_id' => $record->id, 'policy_version_id' => $record->id,
'policy_version_number' => $record->version_number, 'policy_version_number' => $record->version_number,
'version_captured_at' => $record->captured_at?->toIso8601String(), 'version_captured_at' => $record->captured_at?->toIso8601String(),
'redaction_version' => $record->redaction_version, 'redaction_version' => $record->redaction_version,
'warnings' => $record->warningMessages(),
'assignments_fetch_failed' => $record->assignmentsFetchFailed(),
'has_orphaned_assignments' => $record->hasOrphanedAssignments(),
]; ];
$integrityWarning = RedactionIntegrity::noteForPolicyVersion($record); $integrityWarning = RedactionIntegrity::noteForPolicyVersion($record);
@ -891,7 +942,13 @@ public static function table(Table $table): Table
]) ])
->emptyStateHeading('No policy versions') ->emptyStateHeading('No policy versions')
->emptyStateDescription('Capture or sync policy snapshots to build a version history.') ->emptyStateDescription('Capture or sync policy snapshots to build a version history.')
->emptyStateIcon('heroicon-o-clock'); ->emptyStateIcon('heroicon-o-clock')
->emptyStateActions([
Actions\Action::make('open_backup_sets')
->label('Open backup sets')
->url(fn (): string => BackupSetResource::getUrl('index', tenant: static::resolveTenantContextForCurrentPanel()))
->color('gray'),
]);
} }
public static function getEloquentQuery(): Builder public static function getEloquentQuery(): Builder
@ -980,6 +1037,23 @@ private static function primaryRelatedAction(): Actions\Action
->color('gray'); ->color('gray');
} }
private static function policyVersionQualitySummary(PolicyVersion $record): \App\Support\BackupQuality\BackupQualitySummary
{
return app(BackupQualityResolver::class)->forPolicyVersion($record);
}
private static function policyVersionAssignmentQualityLabel(PolicyVersion $record): string
{
$summary = static::policyVersionQualitySummary($record);
return match (true) {
$summary->hasAssignmentIssues && $summary->hasOrphanedAssignments => 'Assignment fetch failed and orphaned targets were detected.',
$summary->hasAssignmentIssues => 'Assignment fetch failed during capture.',
$summary->hasOrphanedAssignments => 'Orphaned assignment targets were detected.',
default => 'No assignment issues were detected from captured metadata.',
};
}
private static function primaryRelatedEntry(PolicyVersion $record): ?RelatedContextEntry private static function primaryRelatedEntry(PolicyVersion $record): ?RelatedContextEntry
{ {
return app(RelatedNavigationResolver::class) return app(RelatedNavigationResolver::class)

View File

@ -27,6 +27,7 @@
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Operations\BulkSelectionIdentity; use App\Services\Operations\BulkSelectionIdentity;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\BackupQuality\BackupQualityResolver;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
use App\Support\Filament\FilterOptionCatalog; use App\Support\Filament\FilterOptionCatalog;
@ -128,24 +129,8 @@ public static function form(Schema $schema): Schema
->schema([ ->schema([
Forms\Components\Select::make('backup_set_id') Forms\Components\Select::make('backup_set_id')
->label('Backup set') ->label('Backup set')
->options(function () { ->options(fn () => static::restoreBackupSetOptions())
$tenantId = static::resolveTenantContextForCurrentPanelOrFail()->getKey(); ->helperText(fn (Get $get): string => static::restoreBackupSetHelperText($get('backup_set_id')))
return BackupSet::query()
->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
->orderByDesc('created_at')
->get()
->mapWithKeys(function (BackupSet $set) {
$label = sprintf(
'%s • %s items • %s',
$set->name,
$set->item_count ?? 0,
optional($set->created_at)->format('Y-m-d H:i')
);
return [$set->id => $label];
});
})
->reactive() ->reactive()
->afterStateUpdated(function (Set $set): void { ->afterStateUpdated(function (Set $set): void {
$set('scope_mode', 'all'); $set('scope_mode', 'all');
@ -163,7 +148,7 @@ public static function form(Schema $schema): Schema
->bulkToggleable() ->bulkToggleable()
->reactive() ->reactive()
->afterStateUpdated(fn (Set $set) => $set('group_mapping', [])) ->afterStateUpdated(fn (Set $set) => $set('group_mapping', []))
->helperText('Search by name, type, or ID. Preview-only types stay in dry-run; leave empty to include all items. Include foundations (scope tags, assignment filters) with policies to re-map IDs.'), ->helperText(fn (): string => static::restoreItemQualityHelperText()),
Section::make('Group mapping') Section::make('Group mapping')
->description('Some source groups do not exist in the target tenant. Map them or choose Skip.') ->description('Some source groups do not exist in the target tenant. Map them or choose Skip.')
->schema(function (Get $get): array { ->schema(function (Get $get): array {
@ -191,7 +176,7 @@ public static function form(Schema $schema): Schema
$cacheNotice = match (true) { $cacheNotice = match (true) {
! $hasCachedGroups => 'No cached groups found. Run "Sync Groups" first.', ! $hasCachedGroups => 'No cached groups found. Run "Sync Groups" first.',
$isStale => "Cached groups may be stale (>${stalenessDays} days). Consider running \"Sync Groups\".", $isStale => "Cached groups may be stale (>{$stalenessDays} days). Consider running \"Sync Groups\".",
default => null, default => null,
}; };
@ -310,28 +295,12 @@ public static function getWizardSteps(): array
{ {
return [ return [
Step::make('Select Backup Set') Step::make('Select Backup Set')
->description('What are we restoring from?') ->description('What are we restoring from? Backup quality is visible here before safety checks run.')
->schema([ ->schema([
Forms\Components\Select::make('backup_set_id') Forms\Components\Select::make('backup_set_id')
->label('Backup set') ->label('Backup set')
->options(function () { ->options(fn () => static::restoreBackupSetOptions())
$tenantId = static::resolveTenantContextForCurrentPanelOrFail()->getKey(); ->helperText(fn (Get $get): string => static::restoreBackupSetHelperText($get('backup_set_id')))
return BackupSet::query()
->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
->orderByDesc('created_at')
->get()
->mapWithKeys(function (BackupSet $set) {
$label = sprintf(
'%s • %s items • %s',
$set->name,
$set->item_count ?? 0,
optional($set->created_at)->format('Y-m-d H:i')
);
return [$set->id => $label];
});
})
->reactive() ->reactive()
->afterStateUpdated(function (Set $set, Get $get): void { ->afterStateUpdated(function (Set $set, Get $get): void {
$groupMapping = static::groupMappingPlaceholders( $groupMapping = static::groupMappingPlaceholders(
@ -362,7 +331,7 @@ public static function getWizardSteps(): array
->required(), ->required(),
]), ]),
Step::make('Define Restore Scope') Step::make('Define Restore Scope')
->description('What exactly should be restored?') ->description('What exactly should be restored? Item quality hints appear here before restore risk checks.')
->schema([ ->schema([
Forms\Components\Radio::make('scope_mode') Forms\Components\Radio::make('scope_mode')
->label('Scope') ->label('Scope')
@ -485,7 +454,7 @@ public static function getWizardSteps(): array
->visible(fn (Get $get): bool => $get('scope_mode') === 'selected') ->visible(fn (Get $get): bool => $get('scope_mode') === 'selected')
->action(fn (Set $set) => $set('backup_item_ids', [], shouldCallUpdatedHooks: true)), ->action(fn (Set $set) => $set('backup_item_ids', [], shouldCallUpdatedHooks: true)),
]) ])
->helperText('Search by name or ID. Include foundations (scope tags, assignment filters) with policies to re-map IDs. Options are grouped by category, type, and platform.'), ->helperText(fn (): string => static::restoreItemQualityHelperText()),
Section::make('Group mapping') Section::make('Group mapping')
->description('Some source groups do not exist in the target tenant. Map them or choose Skip.') ->description('Some source groups do not exist in the target tenant. Map them or choose Skip.')
->schema(function (Get $get): array { ->schema(function (Get $get): array {
@ -520,7 +489,7 @@ public static function getWizardSteps(): array
$cacheNotice = match (true) { $cacheNotice = match (true) {
! $hasCachedGroups => 'No cached groups found. Run "Sync Groups" first.', ! $hasCachedGroups => 'No cached groups found. Run "Sync Groups" first.',
$isStale => "Cached groups may be stale (>${stalenessDays} days). Consider running \"Sync Groups\".", $isStale => "Cached groups may be stale (>{$stalenessDays} days). Consider running \"Sync Groups\".",
default => null, default => null,
}; };
@ -1492,6 +1461,7 @@ private static function restoreItemOptionData(?int $backupSetId): array
foreach ($items as $item) { foreach ($items as $item) {
$meta = static::typeMeta($item->policy_type); $meta = static::typeMeta($item->policy_type);
$qualitySummary = static::backupItemQualitySummary($item);
$typeLabel = $meta['label'] ?? $item->policy_type; $typeLabel = $meta['label'] ?? $item->policy_type;
$category = $meta['category'] ?? 'Policies'; $category = $meta['category'] ?? 'Policies';
$restore = $meta['restore'] ?? 'enabled'; $restore = $meta['restore'] ?? 'enabled';
@ -1506,6 +1476,7 @@ private static function restoreItemOptionData(?int $backupSetId): array
$category, $category,
$typeLabel, $typeLabel,
$platform, $platform,
'quality: '.$qualitySummary->compactSummary,
"restore: {$restore}", "restore: {$restore}",
$versionNumber ? "version: {$versionNumber}" : null, $versionNumber ? "version: {$versionNumber}" : null,
$item->hasAssignments() ? "assignments: {$item->assignment_count}" : null, $item->hasAssignments() ? "assignments: {$item->assignment_count}" : null,
@ -1571,12 +1542,111 @@ private static function restoreItemGroupedOptions(?int $backupSetId): array
])); ]));
$groups[$groupLabel] ??= []; $groups[$groupLabel] ??= [];
$groups[$groupLabel][$item->id] = $item->resolvedDisplayName(); $groups[$groupLabel][$item->id] = static::restoreItemSelectionLabel($item);
} }
return $groups; return $groups;
} }
/**
* @return array<int, string>
*/
private static function restoreBackupSetOptions(): array
{
$tenantId = static::resolveTenantContextForCurrentPanelOrFail()->getKey();
return BackupSet::query()
->where('tenant_id', $tenantId)
->with([
'items' => fn ($query) => $query->select([
'id',
'backup_set_id',
'payload',
'metadata',
'assignments',
]),
])
->orderByDesc('created_at')
->get()
->mapWithKeys(fn (BackupSet $set): array => [
(int) $set->getKey() => static::restoreBackupSetSelectionLabel($set),
])
->all();
}
private static function restoreBackupSetSelectionLabel(BackupSet $set): string
{
$qualitySummary = static::backupSetQualitySummary($set);
return implode(' • ', array_filter([
$set->name,
sprintf('%d items', (int) ($set->item_count ?? 0)),
optional($set->created_at)->format('Y-m-d H:i'),
$qualitySummary->compactSummary,
]));
}
private static function restoreBackupSetHelperText(mixed $backupSetId): string
{
$default = 'Backup quality hints describe input strength only. They do not approve restore execution or prove recoverability.';
if (! is_numeric($backupSetId)) {
return $default;
}
$tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) {
return $default;
}
$backupSet = BackupSet::query()
->where('tenant_id', (int) $tenant->getKey())
->with([
'items' => fn ($query) => $query->select([
'id',
'backup_set_id',
'payload',
'metadata',
'assignments',
]),
])
->find((int) $backupSetId);
if (! $backupSet instanceof BackupSet) {
return $default;
}
$summary = static::backupSetQualitySummary($backupSet);
return $summary->compactSummary.'. '.$summary->positiveClaimBoundary;
}
private static function restoreItemSelectionLabel(BackupItem $item): string
{
$summary = static::backupItemQualitySummary($item);
return implode(' • ', array_filter([
$item->resolvedDisplayName(),
$summary->compactSummary,
]));
}
private static function restoreItemQualityHelperText(): string
{
return 'Quality hints describe input strength before risk checks. Include foundations with policies when you need ID re-mapping context.';
}
private static function backupSetQualitySummary(BackupSet $backupSet): \App\Support\BackupQuality\BackupQualitySummary
{
return app(BackupQualityResolver::class)->summarizeBackupSet($backupSet);
}
private static function backupItemQualitySummary(BackupItem $backupItem): \App\Support\BackupQuality\BackupQualitySummary
{
return app(BackupQualityResolver::class)->forBackupItem($backupItem);
}
public static function createRestoreRun(array $data): RestoreRun public static function createRestoreRun(array $data): RestoreRun
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();

View File

@ -86,6 +86,63 @@ public function assignmentsFetchFailed(): bool
return $this->metadata['assignments_fetch_failed'] ?? false; return $this->metadata['assignments_fetch_failed'] ?? false;
} }
public function assignmentCaptureReason(): ?string
{
$reason = $this->metadata['assignment_capture_reason'] ?? null;
return is_string($reason) && trim($reason) !== ''
? trim($reason)
: null;
}
public function snapshotSource(): ?string
{
$source = $this->metadata['snapshot_source']
?? $this->metadata['source']
?? null;
return is_string($source) && trim($source) !== ''
? trim($source)
: null;
}
/**
* @return list<string>
*/
public function warningMessages(): array
{
$warnings = $this->metadata['warnings'] ?? [];
if (! is_array($warnings)) {
return [];
}
return collect($warnings)
->filter(fn (mixed $warning): bool => is_string($warning) && trim($warning) !== '')
->map(fn (string $warning): string => trim($warning))
->values()
->all();
}
public function integrityWarning(): ?string
{
$warning = $this->metadata['integrity_warning'] ?? null;
return is_string($warning) && trim($warning) !== ''
? trim($warning)
: null;
}
public function protectedPathsCount(): int
{
return max(0, (int) ($this->metadata['protected_paths_count'] ?? 0));
}
public function hasCapturedPayload(): bool
{
return is_array($this->payload) && $this->payload !== [];
}
public function isFoundation(): bool public function isFoundation(): bool
{ {
$types = array_column(config('tenantpilot.foundation_types', []), 'type'); $types = array_column(config('tenantpilot.foundation_types', []), 'type');

View File

@ -4,6 +4,7 @@
use App\Support\Baselines\PolicyVersionCapturePurpose; use App\Support\Baselines\PolicyVersionCapturePurpose;
use App\Support\Concerns\DerivesWorkspaceIdFromTenant; use App\Support\Concerns\DerivesWorkspaceIdFromTenant;
use App\Support\RedactionIntegrity;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@ -59,6 +60,55 @@ public function baselineProfile(): BelongsTo
return $this->belongsTo(BaselineProfile::class); return $this->belongsTo(BaselineProfile::class);
} }
public function snapshotSource(): ?string
{
$source = $this->metadata['source']
?? $this->metadata['snapshot_source']
?? null;
return is_string($source) && trim($source) !== ''
? trim($source)
: null;
}
/**
* @return list<string>
*/
public function warningMessages(): array
{
$warnings = $this->metadata['warnings'] ?? [];
if (! is_array($warnings)) {
return [];
}
return collect($warnings)
->filter(fn (mixed $warning): bool => is_string($warning) && trim($warning) !== '')
->map(fn (string $warning): string => trim($warning))
->values()
->all();
}
public function assignmentsFetchFailed(): bool
{
return (bool) ($this->metadata['assignments_fetch_failed'] ?? false);
}
public function hasOrphanedAssignments(): bool
{
return (bool) ($this->metadata['has_orphaned_assignments'] ?? false);
}
public function integrityWarning(): ?string
{
return RedactionIntegrity::noteForPolicyVersion($this);
}
public function hasCapturedPayload(): bool
{
return is_array($this->snapshot) && $this->snapshot !== [];
}
public function scopePruneEligible($query, int $days = 90) public function scopePruneEligible($query, int $days = 90)
{ {
return $query return $query

View File

@ -0,0 +1,474 @@
<?php
declare(strict_types=1);
namespace App\Support\BackupQuality;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\PolicyVersion;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
final class BackupQualityResolver
{
public function summarizeBackupSet(BackupSet $backupSet): BackupQualitySummary
{
$items = $backupSet->relationLoaded('items')
? $backupSet->items
: $backupSet->items()->get();
return $this->summarizeBackupItems(
$items,
max((int) ($backupSet->item_count ?? 0), $items->count()),
);
}
/**
* @param iterable<BackupItem> $items
*/
public function summarizeBackupItems(iterable $items, ?int $totalItems = null): BackupQualitySummary
{
$itemSummaries = Collection::make($items)
->map(fn (BackupItem $item): BackupQualitySummary => $this->forBackupItem($item))
->values();
$resolvedTotalItems = max($itemSummaries->count(), (int) ($totalItems ?? 0));
$metadataOnlyCount = $itemSummaries->where('metadataOnlyCount', '>', 0)->count();
$assignmentIssueCount = $itemSummaries->where('assignmentIssueCount', '>', 0)->count();
$orphanedAssignmentCount = $itemSummaries->where('orphanedAssignmentCount', '>', 0)->count();
$integrityWarningCount = $itemSummaries->where('integrityWarningCount', '>', 0)->count();
$unknownQualityCount = $itemSummaries->where('unknownQualityCount', '>', 0)->count();
$degradedItemCount = $itemSummaries->filter(
fn (BackupQualitySummary $summary): bool => $summary->hasDegradations()
)->count();
$degradationFamilies = $this->orderedFamilies(
$itemSummaries
->flatMap(fn (BackupQualitySummary $summary): array => $summary->degradationFamilies)
->all(),
);
$qualityHighlights = $this->setHighlights(
totalItems: $resolvedTotalItems,
degradedItemCount: $degradedItemCount,
metadataOnlyCount: $metadataOnlyCount,
assignmentIssueCount: $assignmentIssueCount,
orphanedAssignmentCount: $orphanedAssignmentCount,
integrityWarningCount: $integrityWarningCount,
unknownQualityCount: $unknownQualityCount,
);
$compactSummary = $qualityHighlights === []
? $this->defaultSetCompactSummary($resolvedTotalItems)
: implode(' • ', $qualityHighlights);
$summaryMessage = match (true) {
$resolvedTotalItems === 0 => 'No backup items were captured in this set.',
$degradedItemCount === 0 => sprintf(
'No degradations were detected across %d captured item%s.',
$resolvedTotalItems,
$resolvedTotalItems === 1 ? '' : 's',
),
default => sprintf(
'%d of %d captured item%s show degraded input quality.',
$degradedItemCount,
$resolvedTotalItems,
$resolvedTotalItems === 1 ? '' : 's',
),
};
$nextAction = match (true) {
$resolvedTotalItems === 0 => 'Create or refresh a backup set before starting a restore review.',
$degradedItemCount > 0 => 'Open the backup set detail and inspect degraded items before continuing into restore.',
default => 'Open the backup set detail to verify item-level context before relying on it for restore work.',
};
return new BackupQualitySummary(
kind: 'backup_set',
snapshotMode: $this->aggregateSnapshotMode($resolvedTotalItems, $metadataOnlyCount, $unknownQualityCount),
totalItems: $resolvedTotalItems,
degradedItemCount: $degradedItemCount,
metadataOnlyCount: $metadataOnlyCount,
assignmentIssueCount: $assignmentIssueCount,
orphanedAssignmentCount: $orphanedAssignmentCount,
integrityWarningCount: $integrityWarningCount,
unknownQualityCount: $unknownQualityCount,
hasAssignmentIssues: $assignmentIssueCount > 0,
hasOrphanedAssignments: $orphanedAssignmentCount > 0,
assignmentCaptureReason: null,
integrityWarning: null,
degradationFamilies: $degradationFamilies,
qualityHighlights: $qualityHighlights,
compactSummary: $compactSummary,
summaryMessage: $summaryMessage,
nextAction: $nextAction,
positiveClaimBoundary: $this->positiveClaimBoundary(),
);
}
public function forBackupItem(BackupItem $backupItem): BackupQualitySummary
{
$snapshotMode = $this->resolveSnapshotMode(
source: $backupItem->snapshotSource(),
warnings: $backupItem->warningMessages(),
hasCapturedPayload: $backupItem->hasCapturedPayload(),
);
$assignmentCaptureReason = $backupItem->assignmentCaptureReason();
$integrityWarning = $backupItem->integrityWarning();
$hasAssignmentIssues = $backupItem->assignmentsFetchFailed();
$hasOrphanedAssignments = $backupItem->hasOrphanedAssignments();
$degradationFamilies = $this->singleRecordFamilies(
snapshotMode: $snapshotMode,
hasAssignmentIssues: $hasAssignmentIssues,
hasOrphanedAssignments: $hasOrphanedAssignments,
integrityWarning: $integrityWarning,
);
$qualityHighlights = $this->singleRecordHighlights(
snapshotMode: $snapshotMode,
hasAssignmentIssues: $hasAssignmentIssues,
hasOrphanedAssignments: $hasOrphanedAssignments,
integrityWarning: $integrityWarning,
assignmentCaptureReason: $assignmentCaptureReason,
);
return new BackupQualitySummary(
kind: 'backup_item',
snapshotMode: $snapshotMode,
totalItems: 1,
degradedItemCount: $degradationFamilies === [] ? 0 : 1,
metadataOnlyCount: $snapshotMode === 'metadata_only' ? 1 : 0,
assignmentIssueCount: $hasAssignmentIssues ? 1 : 0,
orphanedAssignmentCount: $hasOrphanedAssignments ? 1 : 0,
integrityWarningCount: $integrityWarning !== null ? 1 : 0,
unknownQualityCount: $degradationFamilies === ['unknown_quality'] ? 1 : 0,
hasAssignmentIssues: $hasAssignmentIssues,
hasOrphanedAssignments: $hasOrphanedAssignments,
assignmentCaptureReason: $assignmentCaptureReason,
integrityWarning: $integrityWarning,
degradationFamilies: $degradationFamilies,
qualityHighlights: $qualityHighlights,
compactSummary: $this->compactSummaryFromHighlights($qualityHighlights, $snapshotMode),
summaryMessage: $this->singleRecordSummaryMessage($qualityHighlights, $snapshotMode),
nextAction: $degradationFamilies === []
? 'Open the linked detail if you need deeper restore context.'
: 'Inspect the linked detail before relying on this backup item for restore.',
positiveClaimBoundary: $this->positiveClaimBoundary(),
);
}
public function forPolicyVersion(PolicyVersion $policyVersion): BackupQualitySummary
{
$snapshotMode = $this->resolveSnapshotMode(
source: $policyVersion->snapshotSource(),
warnings: $policyVersion->warningMessages(),
hasCapturedPayload: $policyVersion->hasCapturedPayload(),
);
$integrityWarning = $policyVersion->integrityWarning();
$hasAssignmentIssues = $policyVersion->assignmentsFetchFailed();
$hasOrphanedAssignments = $policyVersion->hasOrphanedAssignments();
$degradationFamilies = $this->singleRecordFamilies(
snapshotMode: $snapshotMode,
hasAssignmentIssues: $hasAssignmentIssues,
hasOrphanedAssignments: $hasOrphanedAssignments,
integrityWarning: $integrityWarning,
);
$qualityHighlights = $this->singleRecordHighlights(
snapshotMode: $snapshotMode,
hasAssignmentIssues: $hasAssignmentIssues,
hasOrphanedAssignments: $hasOrphanedAssignments,
integrityWarning: $integrityWarning,
);
return new BackupQualitySummary(
kind: 'policy_version',
snapshotMode: $snapshotMode,
totalItems: 1,
degradedItemCount: $degradationFamilies === [] ? 0 : 1,
metadataOnlyCount: $snapshotMode === 'metadata_only' ? 1 : 0,
assignmentIssueCount: $hasAssignmentIssues ? 1 : 0,
orphanedAssignmentCount: $hasOrphanedAssignments ? 1 : 0,
integrityWarningCount: $integrityWarning !== null ? 1 : 0,
unknownQualityCount: $degradationFamilies === ['unknown_quality'] ? 1 : 0,
hasAssignmentIssues: $hasAssignmentIssues,
hasOrphanedAssignments: $hasOrphanedAssignments,
assignmentCaptureReason: null,
integrityWarning: $integrityWarning,
degradationFamilies: $degradationFamilies,
qualityHighlights: $qualityHighlights,
compactSummary: $this->compactSummaryFromHighlights($qualityHighlights, $snapshotMode),
summaryMessage: $this->singleRecordSummaryMessage($qualityHighlights, $snapshotMode),
nextAction: $degradationFamilies === []
? 'Open the version detail if you need raw settings or diff context.'
: 'Prefer a stronger version or inspect the version detail before restore.',
positiveClaimBoundary: $this->positiveClaimBoundary(),
);
}
/**
* @param list<string> $warnings
*/
private function resolveSnapshotMode(?string $source, array $warnings, bool $hasCapturedPayload): string
{
if ($source === 'metadata_only' || $this->warningsIndicateMetadataOnly($warnings)) {
return 'metadata_only';
}
if ($hasCapturedPayload) {
return 'full';
}
return 'unknown';
}
/**
* @param list<string> $warnings
*/
private function warningsIndicateMetadataOnly(array $warnings): bool
{
return Collection::make($warnings)
->contains(function (mixed $warning): bool {
if (! is_string($warning)) {
return false;
}
$normalized = Str::lower($warning);
return str_contains($normalized, 'metadata')
&& (
str_contains($normalized, 'only')
|| str_contains($normalized, 'fallback')
);
});
}
/**
* @return list<string>
*/
private function singleRecordFamilies(
string $snapshotMode,
bool $hasAssignmentIssues,
bool $hasOrphanedAssignments,
?string $integrityWarning,
): array {
$families = [];
if ($snapshotMode === 'metadata_only') {
$families[] = 'metadata_only';
}
if ($hasAssignmentIssues) {
$families[] = 'assignment_capture_issue';
}
if ($hasOrphanedAssignments) {
$families[] = 'orphaned_assignments';
}
if ($integrityWarning !== null) {
$families[] = 'integrity_warning';
}
if ($families === [] && $snapshotMode === 'unknown') {
$families[] = 'unknown_quality';
}
return $this->orderedFamilies($families);
}
/**
* @return list<string>
*/
private function singleRecordHighlights(
string $snapshotMode,
bool $hasAssignmentIssues,
bool $hasOrphanedAssignments,
?string $integrityWarning,
?string $assignmentCaptureReason = null,
): array {
$highlights = [];
if ($snapshotMode === 'metadata_only') {
$highlights[] = 'Metadata only';
}
if ($hasAssignmentIssues) {
$highlights[] = 'Assignment fetch failed';
} elseif ($assignmentCaptureReason === 'separate_role_assignments') {
$highlights[] = 'Assignments captured separately';
}
if ($hasOrphanedAssignments) {
$highlights[] = 'Orphaned assignments';
}
if ($integrityWarning !== null) {
$highlights[] = 'Integrity warning';
}
if ($snapshotMode === 'unknown' && $highlights === []) {
$highlights[] = 'Unknown quality';
}
return array_values(array_unique($highlights));
}
private function compactSummaryFromHighlights(array $qualityHighlights, string $snapshotMode): string
{
if ($qualityHighlights !== []) {
return implode(' • ', $qualityHighlights);
}
return match ($snapshotMode) {
'full' => 'Full payload',
'unknown' => 'Unknown quality',
default => 'No degradations detected',
};
}
private function singleRecordSummaryMessage(array $qualityHighlights, string $snapshotMode): string
{
if ($qualityHighlights === []) {
return match ($snapshotMode) {
'full' => 'No degradations were detected from the captured snapshot and assignment metadata.',
'unknown' => 'Quality is unknown because this record lacks enough completeness metadata to justify a stronger claim.',
default => 'No degradations were detected.',
};
}
return implode(' • ', $qualityHighlights).'.';
}
private function aggregateSnapshotMode(int $totalItems, int $metadataOnlyCount, int $unknownQualityCount): string
{
if ($totalItems === 0) {
return 'unknown';
}
if ($metadataOnlyCount === $totalItems) {
return 'metadata_only';
}
if ($metadataOnlyCount === 0 && $unknownQualityCount === 0) {
return 'full';
}
return 'unknown';
}
/**
* @return list<string>
*/
private function orderedFamilies(array $families): array
{
$weights = [
'metadata_only' => 10,
'assignment_capture_issue' => 20,
'orphaned_assignments' => 30,
'integrity_warning' => 40,
'unknown_quality' => 50,
];
$families = array_values(array_unique(array_filter(
$families,
static fn (mixed $family): bool => is_string($family) && $family !== '',
)));
usort($families, static function (string $left, string $right) use ($weights): int {
return ($weights[$left] ?? 999) <=> ($weights[$right] ?? 999);
});
return $families;
}
/**
* @return list<string>
*/
private function setHighlights(
int $totalItems,
int $degradedItemCount,
int $metadataOnlyCount,
int $assignmentIssueCount,
int $orphanedAssignmentCount,
int $integrityWarningCount,
int $unknownQualityCount,
): array {
if ($totalItems === 0) {
return [];
}
$highlights = [];
if ($degradedItemCount > 0) {
$highlights[] = sprintf(
'%d degraded item%s',
$degradedItemCount,
$degradedItemCount === 1 ? '' : 's',
);
}
if ($metadataOnlyCount > 0) {
$highlights[] = sprintf(
'%d metadata-only',
$metadataOnlyCount,
);
}
if ($assignmentIssueCount > 0) {
$highlights[] = sprintf(
'%d assignment issue%s',
$assignmentIssueCount,
$assignmentIssueCount === 1 ? '' : 's',
);
}
if ($orphanedAssignmentCount > 0) {
$highlights[] = sprintf(
'%d orphaned assignment%s',
$orphanedAssignmentCount,
$orphanedAssignmentCount === 1 ? '' : 's',
);
}
if ($integrityWarningCount > 0) {
$highlights[] = sprintf(
'%d integrity warning%s',
$integrityWarningCount,
$integrityWarningCount === 1 ? '' : 's',
);
}
if ($unknownQualityCount > 0) {
$highlights[] = sprintf(
'%d unknown quality',
$unknownQualityCount,
);
}
return $highlights;
}
private function defaultSetCompactSummary(int $totalItems): string
{
if ($totalItems === 0) {
return 'No items captured';
}
return sprintf(
'No degradations detected across %d item%s',
$totalItems,
$totalItems === 1 ? '' : 's',
);
}
private function positiveClaimBoundary(): string
{
return 'Input quality signals do not prove safe restore, restore readiness, or tenant-wide recoverability.';
}
}

View File

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Support\BackupQuality;
final readonly class BackupQualitySummary
{
/**
* @param list<string> $degradationFamilies
* @param list<string> $qualityHighlights
*/
public function __construct(
public string $kind,
public string $snapshotMode,
public int $totalItems,
public int $degradedItemCount,
public int $metadataOnlyCount,
public int $assignmentIssueCount,
public int $orphanedAssignmentCount,
public int $integrityWarningCount,
public int $unknownQualityCount,
public bool $hasAssignmentIssues,
public bool $hasOrphanedAssignments,
public ?string $assignmentCaptureReason,
public ?string $integrityWarning,
public array $degradationFamilies,
public array $qualityHighlights,
public string $compactSummary,
public string $summaryMessage,
public string $nextAction,
public string $positiveClaimBoundary,
) {}
public function hasDegradations(): bool
{
return $this->degradationFamilies !== [];
}
public function hasIntegrityWarning(): bool
{
return $this->integrityWarning !== null;
}
}

View File

@ -5,7 +5,7 @@ # Spec Candidates
> >
> **Flow**: Inbox → Qualified → Planned → Spec created → moved to `Promoted to Spec` > **Flow**: Inbox → Qualified → Planned → Spec created → moved to `Promoted to Spec`
**Last reviewed**: 2026-03-28 (added request-scoped performance foundation candidates for derived state, governance aggregates, and workspace access context) **Last reviewed**: 2026-04-07 (added UI Discipline Trilogy: Record Page Header Discipline, Monitoring Surface Action Hierarchy, Governance Friction & Vocabulary Hardening)
--- ---
@ -1480,6 +1480,91 @@ ### Detail Page Hierarchy & Progressive Disclosure (UI/UX Audit)
- **Status**: Directly covered by Spec 133 (View Page Template Standard for Enterprise Detail Screens). Spec 133 defines the shared enterprise detail-page composition standard including summary-first header, main-and-supporting layout, dedicated related-context section, secondary technical detail separation, optional section support, and degraded-state resilience. Spec.md, plan.md, research.md, data-model.md, and tasks.md (all tasks complete) exist for 4 initial target pages (BaselineSnapshot, BackupSet, EntraGroup, OperationRun). If additional pages require alignment beyond the initial 4 targets, that is a Spec 133 follow-up scope extension, not a new candidate. - **Status**: Directly covered by Spec 133 (View Page Template Standard for Enterprise Detail Screens). Spec 133 defines the shared enterprise detail-page composition standard including summary-first header, main-and-supporting layout, dedicated related-context section, secondary technical detail separation, optional section support, and degraded-state resilience. Spec.md, plan.md, research.md, data-model.md, and tasks.md (all tasks complete) exist for 4 initial target pages (BaselineSnapshot, BackupSet, EntraGroup, OperationRun). If additional pages require alignment beyond the initial 4 targets, that is a Spec 133 follow-up scope extension, not a new candidate.
- **Reference specs**: 133 - **Reference specs**: 133
### Record Page Header Discipline & Contextual Navigation
- **Type**: hardening
- **Source**: Constitution compliance audit 2026-04 — systematic review of Record/Detail page header-action usage across all View/Detail surfaces
- **Problem**: Many Record/Detail pages violate the Constitution by using header actions as a catch-all for navigation, secondary actions, and governance actions. The 5-second-scan rule is broken because the primary action is not clearly prioritized, related navigation sits in the wrong place (equal-weight header buttons instead of inline context), and danger/governance actions are not friction-separated. This is the largest systemic Constitution gap on current View/Detail surfaces.
- **Why it matters**: As long as this pattern drift persists, the UI remains noisy and inconsistent despite strong foundations. Every new View page risks inheriting the same anti-pattern. Fixing this is the single largest visible lever to close the Constitution gap across the product.
- **Proposed direction**:
- Define a binding Constitution rule for Record/Detail page header actions: max one visible primary header action, no navigation in headers, related links inline at context, danger/governance actions separated, rare secondary actions in Action Group
- Define a standard pattern for header actions on Record/Detail pages
- Define a standard pattern for related-context navigation in Infolists (inline, operator-proximate)
- Move navigation out of headers into field/status/relation context
- Roll out the pattern to all affected View/Detail pages
- **Affected surfaces**: Finding Exception, Finding, Tenant Review, Baseline Profile, Evidence Snapshot, Tenant, Provider Connection, and potentially Backup Set, Baseline Snapshot, and other View pages
- **Non-goals**: Queue/Workbench surface restructuring (separate candidate), Monitoring header architecture (separate candidate), general visual redesign, deep layout polish of all pages
- **Acceptance points**:
- Record page Constitution rule is documented
- Affected View pages have no navigation buttons as equal-weight header CTAs
- Each View page has a clearly prioritized primary action
- Danger actions are separated and friction-gated
- Related navigation is inline and operator-proximate
- **Dependencies**: Spec 133 (View Page Template Standard — provides the detail-page layout foundation this candidate builds on for header-action discipline)
- **Related specs / candidates**: Monitoring Surface Action Hierarchy & Workbench Semantics (adjacent but distinct — queue/workbench surfaces need their own rules), Governance Friction & Operator Vocabulary Hardening (complements this with friction/reason-capture/vocabulary hardening)
- **Strategic importance**: This is the central lever to eliminate the largest visible Constitution drift in the product. Recommended as the first of three coordinated UI-discipline specs.
- **Priority**: high
### Monitoring Surface Action Hierarchy & Workbench Semantics
- **Type**: hardening
- **Source**: Constitution compliance audit 2026-04 — Queue/Monitoring/Workbench surfaces mix global surface controls, selection-aware object actions, context navigation, utility actions, and object workflow in the same header/action area
- **Problem**: Queue and Monitoring surfaces mix global surface controls, selection-aware object actions, context navigation, filter/utility actions, and scope/back/context signals in the same equal-weight header area. This is a different problem than Record page header noise — it is an information architecture/workbench semantics question that needs its own rules rather than forcing the Record page header pattern onto surfaces with fundamentally different interaction models.
- **Why it matters**: After Record page header cleanup, these surfaces would remain the next large inconsistent block. Applying Record page rules to Workbench/Queue surfaces would be a category error — they need their own action hierarchy that respects surface-level controls, selection-aware workflows, and scope context.
- **Proposed direction**:
- Define a Constitution/pattern rule for Queue/Workbench/Monitoring surfaces with clear action hierarchy layers: global surface actions, selection-aware object actions, context navigation, filter/utility actions, scope/back/context signals
- Semantically clean up OperateHub/Monitoring headers so these layers are not presented as equal-weight header items
- Extract scope and back-context from header-action noise
- Correctly place selection-based workflow actions
- Move navigation out of global headers
- Make workbench/detail-pane/selection flows cleaner
- **Affected surfaces**: Finding Exceptions Queue, Tenantless Operation Viewer, Operations, and potentially Alerts, Audit Log, and other Monitoring pages with OperateHub/scope/selection patterns
- **Non-goals**: Solving all Record/View page problems (separate candidate), reinventing the sidebar/navigation, building new large Monitoring features
- **Acceptance points**:
- Queue/Monitoring Constitution rule is defined
- Global and object-level actions are clearly separated
- Selection-aware governance actions are not in the same header bucket as utility/navigation
- Scope/back context is cleanly placed
- Monitoring surfaces are noticeably calmer and faster to scan
- **Dependencies**: Record Page Header Discipline (recommended to ship first — establishes the Record page header contract that this candidate explicitly does not reuse for Workbench surfaces)
- **Related specs / candidates**: Record Page Header Discipline & Contextual Navigation (adjacent — Record pages vs Workbench surfaces), Governance Friction & Operator Vocabulary Hardening (complements with friction/vocabulary hardening)
- **Strategic importance**: Prevents applying a wrong solution (Record page header rules) to a fundamentally different surface class. Recommended as the second of three coordinated UI-discipline specs.
- **Priority**: high
### Governance Friction & Operator Vocabulary Hardening
- **Type**: hardening
- **Source**: Constitution compliance audit 2026-04 — residual gaps in friction, reason capture, and UI vocabulary consistency across governance-impacting actions
- **Problem**: Smaller but important gaps exist in governance friction, reason capture, and UI vocabulary. These are not large enough for the Header/Workbench architecture specs but are critical for enterprise trust, auditability, and consistent operator language. Governance-changing actions lack consistent friction rules, reason capture is missing where governance truth or review/acceptance decisions are affected, danger/confirmation standards vary, and UI vocabulary has naming outliers that diverge from the Constitution.
- **Why it matters**: This is the right finishing step after the two architecture-focused specs. Without it, the product would have clean action architecture but inconsistent governance friction and operator language — undermining the enterprise-trust story. It turns a "better UI" into a credible governance-of-record surface.
- **Proposed direction**:
- Close confirmation/reason-capture gaps across governance-impacting actions
- Define a friction heuristic: when only confirm, when optional reason, when mandatory reason
- Unify danger semantics across all destructive actions
- Fix individual naming/label outliers that diverge from Constitution vocabulary
- Harden action naming and operator-facing wording for remaining inconsistencies
- **Affected surfaces**: Exception approval/reject flows, evidence/review publish/expire/revoke/renew patterns, individual Resources with inconsistent labels, shared helpers / review heuristics / guardrails where applicable
- **Non-goals**: Large IA refactor, re-touching all Monitoring/Record patterns, cosmetic text changes without semantic relevance
- **Acceptance points**:
- Governance friction rules are clearly documented
- Relevant actions have consistent confirmation/reason semantics
- Danger semantics are unified
- Named UI outliers are corrected
- Operator-facing wording follows the Constitution more closely
- **Dependencies**: Record Page Header Discipline (recommended first), Monitoring Surface Action Hierarchy (recommended second) — this spec is designed as the targeted finishing step
- **Related specs / candidates**: Record Page Header Discipline & Contextual Navigation, Monitoring Surface Action Hierarchy & Workbench Semantics, Spec 156 (operator-outcome-taxonomy), Spec 157 (reason-code-translation)
- **Strategic importance**: The targeted closer that turns structural UI improvements into a credible governance-of-record surface. Recommended as the third and final spec in the coordinated UI-discipline trilogy.
- **Priority**: high
> **UI Discipline Trilogy — Sequencing Note**
>
> These three candidates form a coordinated trilogy that addresses the largest remaining Constitution drift in the product UI:
>
> 1. **Record Page Header Discipline & Contextual Navigation** — largest visible lever; establishes the binding header-action contract for all Record/Detail pages
> 2. **Monitoring Surface Action Hierarchy & Workbench Semantics** — separates Workbench/Queue surfaces from Record page rules; defines the action hierarchy for Monitoring surfaces
> 3. **Governance Friction & Operator Vocabulary Hardening** — targeted finishing step for friction, reason capture, and vocabulary consistency
>
> **Why this order:** Record pages are the most numerous and most directly visible gap. Monitoring surfaces need their own rules (not a Record page derivative). Governance friction is the smallest scope and benefits from the architectural cleanup of the first two specs.
>
> **Why three specs instead of one:** Each has different affected surfaces, different interaction models, and different implementation patterns. Merging them would create an unshippable monolith. Keeping them sequenced preserves independent delivery while converging on one coherent UI discipline.
--- ---
## Planned ## Planned

View File

@ -0,0 +1,34 @@
# Specification Quality Checklist: Backup Quality Truth Surfaces
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-04-07
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- Validated on 2026-04-07. The spec keeps solution details out of the behavior sections; the only structural references are the mandatory surface-identification fields required by this repository's constitution and spec template.

View File

@ -0,0 +1,498 @@
openapi: 3.1.0
info:
title: Backup Quality Truth Surface Contracts
version: 1.0.0
description: >-
Internal reference contract for backup-quality truth surfaces. The application
continues to return rendered HTML through Filament and Livewire. The vendor
media types below document the structured list, detail, and selection models
that must be derivable before rendering. This is not a public API commitment.
paths:
/admin/t/{tenant}/backup-sets:
get:
summary: Backup-set list surface
description: >-
Returns the rendered backup-set list page. The vendor media type documents
the quality summary model that each visible row must expose.
parameters:
- name: tenant
in: path
required: true
schema:
type: integer
responses:
'200':
description: Rendered backup-set list page
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.backup-set-collection+json:
schema:
$ref: '#/components/schemas/BackupSetCollectionSurface'
'403':
description: Viewer is in scope but lacks backup or version viewing capability
'404':
description: Tenant scope is not visible because workspace or tenant membership is missing
/admin/t/{tenant}/backup-sets/{backupSet}:
get:
summary: Backup-set detail surface
description: >-
Returns the rendered backup-set detail page. The vendor media type documents
the summary-first quality model and the related per-item quality rows.
parameters:
- name: tenant
in: path
required: true
schema:
type: integer
- name: backupSet
in: path
required: true
schema:
type: integer
responses:
'200':
description: Rendered backup-set detail page
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.backup-set-detail+json:
schema:
$ref: '#/components/schemas/BackupSetDetailSurface'
'403':
description: Viewer is in scope but lacks required capability for a linked maintenance action
'404':
description: Backup set is not visible because workspace or tenant membership is missing
/admin/t/{tenant}/policy-versions:
get:
summary: Policy-version list surface
description: >-
Returns the rendered policy-version list page. The vendor media type documents
the snapshot mode and backup-quality model that each row must expose.
parameters:
- name: tenant
in: path
required: true
schema:
type: integer
responses:
'200':
description: Rendered policy-version list page
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.policy-version-collection+json:
schema:
$ref: '#/components/schemas/PolicyVersionCollectionSurface'
'403':
description: Viewer is in scope but lacks policy-version viewing capability
'404':
description: Tenant scope is not visible because workspace or tenant membership is missing
/admin/t/{tenant}/policy-versions/{policyVersion}:
get:
summary: Policy-version detail surface
description: >-
Returns the rendered policy-version detail page. The vendor media type documents
the explicit backup-quality model that must be available before rendering.
parameters:
- name: tenant
in: path
required: true
schema:
type: integer
- name: policyVersion
in: path
required: true
schema:
type: integer
responses:
'200':
description: Rendered policy-version detail page
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.policy-version-detail+json:
schema:
$ref: '#/components/schemas/PolicyVersionDetailSurface'
'403':
description: Viewer is in scope but lacks capability for a linked mutation action
'404':
description: Policy version is not visible because workspace or tenant membership is missing
/admin/t/{tenant}/restore-runs/create:
get:
summary: Restore selection surface with backup-quality hints
description: >-
Returns the rendered restore wizard. The vendor media type documents the
selection-stage backup-quality hints that must appear before risk checks.
parameters:
- name: tenant
in: path
required: true
schema:
type: integer
- name: backup_set_id
in: query
required: false
schema:
type: integer
responses:
'200':
description: Rendered restore wizard page
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.restore-selection-quality+json:
schema:
$ref: '#/components/schemas/RestoreSelectionSurface'
'403':
description: Viewer is in scope but lacks restore capability
'404':
description: Restore surface is not visible because workspace or tenant membership is missing
components:
schemas:
BackupSetCollectionSurface:
type: object
required:
- rows
properties:
rows:
type: array
items:
$ref: '#/components/schemas/BackupSetRow'
BackupSetRow:
type: object
required:
- id
- name
- lifecycleStatus
- itemCount
- qualitySummary
properties:
id:
type: integer
name:
type: string
lifecycleStatus:
$ref: '#/components/schemas/Fact'
itemCount:
type: integer
capturedAt:
type:
- string
- 'null'
format: date-time
completedAt:
type:
- string
- 'null'
format: date-time
qualitySummary:
$ref: '#/components/schemas/QualitySummary'
BackupSetDetailSurface:
type: object
required:
- header
- qualitySummary
- itemRows
properties:
header:
$ref: '#/components/schemas/BackupSetHeader'
qualitySummary:
$ref: '#/components/schemas/QualitySummary'
itemRows:
type: array
items:
$ref: '#/components/schemas/BackupItemQualityRow'
positiveClaimBoundary:
$ref: '#/components/schemas/Fact'
BackupSetHeader:
type: object
required:
- id
- name
- lifecycleStatus
properties:
id:
type: integer
name:
type: string
lifecycleStatus:
$ref: '#/components/schemas/Fact'
archived:
type: boolean
itemCount:
type: integer
BackupItemQualityRow:
type: object
required:
- id
- label
- policyType
- snapshotCompleteness
- assignmentCapture
- hasDegradations
- summaryMessage
properties:
id:
type: integer
label:
type: string
policyType:
type: string
platform:
type:
- string
- 'null'
versionNumber:
type:
- integer
- 'null'
snapshotCompleteness:
$ref: '#/components/schemas/SnapshotCompleteness'
assignmentCapture:
$ref: '#/components/schemas/AssignmentCapture'
integrityWarning:
type:
- string
- 'null'
hasDegradations:
type: boolean
degradationFamilies:
type: array
items:
type: string
summaryMessage:
type: string
nextAction:
$ref: '#/components/schemas/Fact'
PolicyVersionCollectionSurface:
type: object
required:
- rows
properties:
rows:
type: array
items:
$ref: '#/components/schemas/PolicyVersionRow'
PolicyVersionRow:
type: object
required:
- id
- label
- versionNumber
- snapshotCompleteness
- hasDegradations
- summaryMessage
properties:
id:
type: integer
label:
type: string
versionNumber:
type: integer
capturedAt:
type:
- string
- 'null'
format: date-time
snapshotCompleteness:
$ref: '#/components/schemas/SnapshotCompleteness'
assignmentCapture:
$ref: '#/components/schemas/AssignmentCapture'
integrityWarning:
type:
- string
- 'null'
hasDegradations:
type: boolean
degradationFamilies:
type: array
items:
type: string
summaryMessage:
type: string
PolicyVersionDetailSurface:
type: object
required:
- header
- qualityFact
- positiveClaimBoundary
properties:
header:
$ref: '#/components/schemas/PolicyVersionHeader'
qualityFact:
$ref: '#/components/schemas/QualityFact'
positiveClaimBoundary:
$ref: '#/components/schemas/Fact'
PolicyVersionHeader:
type: object
required:
- id
- label
- versionNumber
properties:
id:
type: integer
label:
type: string
versionNumber:
type: integer
capturedAt:
type:
- string
- 'null'
format: date-time
RestoreSelectionSurface:
type: object
required:
- backupSetOptions
- positiveClaimBoundary
properties:
backupSetOptions:
type: array
items:
$ref: '#/components/schemas/RestoreBackupSetOption'
itemOptions:
type: array
items:
$ref: '#/components/schemas/RestoreBackupItemOption'
positiveClaimBoundary:
$ref: '#/components/schemas/Fact'
RestoreBackupSetOption:
type: object
required:
- id
- label
- qualitySummary
properties:
id:
type: integer
label:
type: string
qualitySummary:
$ref: '#/components/schemas/QualitySummary'
RestoreBackupItemOption:
type: object
required:
- id
- label
- qualityFact
properties:
id:
type: integer
label:
type: string
qualityFact:
$ref: '#/components/schemas/QualityFact'
QualitySummary:
type: object
required:
- hasDegradations
- degradedItemCount
- metadataOnlyCount
- assignmentIssueCount
- orphanedAssignmentCount
- summaryLabel
properties:
hasDegradations:
type: boolean
degradedItemCount:
type: integer
metadataOnlyCount:
type: integer
assignmentIssueCount:
type: integer
orphanedAssignmentCount:
type: integer
integrityWarningCount:
type: integer
unknownQualityCount:
type: integer
degradationFamilies:
type: array
items:
type: string
summaryLabel:
type: string
nextAction:
$ref: '#/components/schemas/Fact'
QualityFact:
type: object
required:
- snapshotCompleteness
- assignmentCapture
- hasDegradations
- summaryMessage
properties:
snapshotCompleteness:
$ref: '#/components/schemas/SnapshotCompleteness'
assignmentCapture:
$ref: '#/components/schemas/AssignmentCapture'
integrityWarning:
type:
- string
- 'null'
hasDegradations:
type: boolean
degradationFamilies:
type: array
items:
type: string
summaryMessage:
type: string
nextAction:
$ref: '#/components/schemas/Fact'
SnapshotCompleteness:
type: object
required:
- mode
- badgeLabel
properties:
mode:
type: string
enum:
- full
- metadata_only
- unknown
badgeLabel:
type: string
sourceSignal:
type:
- string
- 'null'
AssignmentCapture:
type: object
required:
- issuePresent
- orphanedAssignments
properties:
issuePresent:
type: boolean
fetchFailed:
type: boolean
captureReason:
type:
- string
- 'null'
orphanedAssignments:
type: boolean
assignmentCount:
type:
- integer
- 'null'
Fact:
type: object
required:
- label
properties:
label:
type: string
description:
type:
- string
- 'null'

View File

@ -0,0 +1,247 @@
# Data Model: Backup Quality Truth Surfaces
## Overview
This feature does not add or change a top-level persisted domain entity. It introduces a tighter derived backup-quality model around the existing tenant-owned backup, version, and restore-selection surfaces.
The central design task is to make existing backup truth visible without changing:
- `BackupSet`, `BackupItem`, or `PolicyVersion` ownership
- existing backup or restore route identity
- existing restore-safety, preview, and execution authority
- existing audit and RBAC responsibilities
- the no-new-table boundary of this feature
## Existing Persistent Entities
### 1. BackupSet
- Purpose: Tenant-owned backup collection that records lifecycle state and groups captured backup items.
- Existing persistent fields used by this feature:
- `id`
- `tenant_id`
- `name`
- `status`
- `item_count`
- `metadata`
- `created_by`
- `completed_at`
- `created_at`
- Existing relationships used by this feature:
- `tenant`
- `items`
- `restoreRuns`
#### Proposed nested metadata additions
None. Backup-set quality is derived from related backup items and existing set facts. No new backup-set status or metadata field is required.
### 2. BackupItem
- Purpose: Tenant-owned captured recovery input for one backed-up policy or foundation record.
- Existing persistent fields used by this feature:
- `id`
- `tenant_id`
- `backup_set_id`
- `policy_id`
- `policy_version_id`
- `policy_identifier`
- `policy_type`
- `platform`
- `payload`
- `assignments`
- `metadata`
- `captured_at`
- Existing relationships used by this feature:
- `tenant`
- `backupSet`
- `policy`
- `policyVersion`
#### Existing metadata signals used by this feature
| Key | Type | Meaning |
|---|---|---|
| `source` | string or null | Primary source marker; may be `metadata_only` |
| `snapshot_source` | string or null | Copied source marker from a linked policy version when a backup item is created from a version |
| `warnings` | array<string> | Warning messages; may include metadata-only fallback wording |
| `assignments_fetch_failed` | boolean | Assignment capture failed for this item |
| `assignment_capture_reason` | string or null | Informational reason such as `separate_role_assignments`; not all reasons are degradations |
| `has_orphaned_assignments` | boolean | One or more resolved assignment targets were orphaned |
| `assignment_count` | integer or null | Captured assignment count |
| `scope_tag_ids` | array<int|string> | Captured scope-tag identifiers |
| `scope_tag_names` | array<string> | Captured scope-tag names |
| `integrity_warning` | string or null | Existing integrity or redaction warning copied into the backup item |
| `protected_paths_count` | integer or null | Count of protected or redacted paths copied from the policy version context |
### 3. PolicyVersion
- Purpose: Tenant-owned immutable version record for a policy snapshot.
- Existing persistent fields used by this feature:
- `id`
- `tenant_id`
- `policy_id`
- `version_number`
- `snapshot`
- `metadata`
- `assignments`
- `scope_tags`
- `secret_fingerprints`
- `redaction_version`
- `captured_at`
- `capture_purpose`
- Existing relationships used by this feature:
- `tenant`
- `policy`
- `operationRun`
#### Existing metadata signals used by this feature
| Key | Type | Meaning |
|---|---|---|
| `source` | string or null | Snapshot source marker; `metadata_only` is the primary degraded completeness signal |
| `warnings` | array<string> | Snapshot warnings; may include metadata-only fallback language |
| `assignments_fetch_failed` | boolean | Assignment capture failed during version capture |
| `assignments_fetch_error` | string or null | Human-readable assignment capture error |
| `assignments_fetch_error_code` | int or string or null | Technical assignment capture error code |
| `has_orphaned_assignments` | boolean | One or more captured assignment targets were orphaned |
| `capture_source` | string or null | Existing capture context such as `version_capture` |
#### Related persisted integrity context used by this feature
| Field | Type | Meaning |
|---|---|---|
| `secret_fingerprints` | array | Existing redaction context used to expose integrity notes on version-derived restore inputs |
| `redaction_version` | integer | Existing redaction version for operator diagnostics |
| `scope_tags` | array | Existing scope-tag context surfaced alongside quality truth where useful |
### 4. Restore selection context
- Purpose: Existing wizard state that lets operators choose a backup set and optional backup-item subset before running risk checks.
- Existing state used by this feature:
- `backup_set_id`
- `scope_mode`
- `backup_item_ids`
- `group_mapping`
- `is_dry_run`
No new persisted restore-selection state is planned. This feature only enriches the current rendered option models.
## Derived Models
### 1. SnapshotCompletenessFact
Derived completeness truth shared by backup items and policy versions.
| Field | Type | Source | Notes |
|---|---|---|---|
| `mode` | string | metadata-derived | `full`, `metadata_only`, or `unknown` |
| `sourceSignal` | string or null | `metadata.source` or `metadata.snapshot_source` | Authoritative direct signal when present |
| `warningEvidence` | list<string> | `metadata.warnings` | Secondary fallback signal |
| `badgeState` | string | derived | Routes to the existing `PolicySnapshotModeBadge` state |
Rules:
- `metadata_only` when `source` or `snapshot_source` equals `metadata_only`, or when warning evidence clearly states metadata-only capture.
- `full` only when there is no metadata-only evidence and the record contains enough captured payload context to justify a complete-snapshot claim.
- `unknown` only when existing metadata cannot prove either `full` or `metadata_only`.
### 2. AssignmentCaptureFact
Derived assignment-quality truth for backup items and policy versions.
| Field | Type | Source | Notes |
|---|---|---|---|
| `fetchFailed` | boolean | `assignments_fetch_failed` | Primary degraded assignment signal |
| `captureReason` | string or null | `assignment_capture_reason` | Informational reason; not always degraded |
| `orphanedAssignments` | boolean | `has_orphaned_assignments` | Secondary degraded signal |
| `assignmentCount` | integer or null | `assignment_count` or `assignments` length | Informational support data |
| `issuePresent` | boolean | derived | True when fetch failed or orphaned targets exist |
Rules:
- `assignment_capture_reason = separate_role_assignments` is informative and must not be misread as a failure on its own.
- `fetchFailed = true` is a degraded quality signal.
- `orphanedAssignments = true` is a degraded quality signal even if fetch succeeded.
### 3. BackupItemQualityFact
Default item-level backup-quality model for backup items.
| Field | Type | Source | Notes |
|---|---|---|---|
| `backupItemId` | integer | record id | Identity |
| `snapshotCompleteness` | `SnapshotCompletenessFact` | derived | Primary completeness truth |
| `assignmentCapture` | `AssignmentCaptureFact` | derived | Assignment quality truth |
| `integrityWarning` | string or null | `metadata.integrity_warning` | Existing integrity signal |
| `degradationFamilies` | list<string> | derived | Examples: `metadata_only`, `assignment_capture_issue`, `orphaned_assignments`, `integrity_warning`, `unknown_quality` |
| `hasDegradations` | boolean | derived | True when one or more degradation families apply |
| `summaryMessage` | string | derived | Concise operator-facing truth |
| `nextAction` | string | derived | Primary next step such as inspect detail or continue with caution |
### 4. BackupSetQualitySummary
Aggregate backup-quality truth for one backup set.
| Field | Type | Source | Notes |
|---|---|---|---|
| `backupSetId` | integer | record id | Identity |
| `totalItems` | integer | `item_count` or related count | Informational total |
| `degradedItemCount` | integer | aggregated item facts | Number of degraded items |
| `metadataOnlyCount` | integer | aggregated item facts | Count of metadata-only items |
| `assignmentIssueCount` | integer | aggregated item facts | Count of assignment capture failures |
| `orphanedAssignmentCount` | integer | aggregated item facts | Count of orphaned-assignment signals |
| `integrityWarningCount` | integer | aggregated item facts | Count of integrity warnings carried into backup items |
| `unknownQualityCount` | integer | aggregated item facts | Count of items whose quality is truly unknown |
| `degradationFamilies` | list<string> | derived | Set-level union of degradation families |
| `summaryMessage` | string | derived | Compact summary for list and detail |
| `nextAction` | string | derived | Open detail, inspect degraded items, prefer stronger version, or continue with caution |
| `positiveClaimBoundary` | string | derived | Explains that quality does not equal safe restore or tenant recoverability |
Rules:
- Aggregate counts are computed from related `BackupItemQualityFact` values, never from `BackupSet.status`.
- `completed but degraded` remains a display combination of lifecycle plus quality summary, not a new persisted backup-set status.
### 5. PolicyVersionQualityFact
Version-level backup-quality truth for policy versions.
| Field | Type | Source | Notes |
|---|---|---|---|
| `policyVersionId` | integer | record id | Identity |
| `snapshotCompleteness` | `SnapshotCompletenessFact` | derived from version metadata | Primary completeness truth |
| `assignmentCapture` | `AssignmentCaptureFact` | derived from version metadata and assignments | Assignment quality truth |
| `integrityWarning` | string or null | derived from existing redaction or integrity context | Existing warning already present in current restore and version flows |
| `degradationFamilies` | list<string> | derived | Same family as backup items where applicable |
| `hasDegradations` | boolean | derived | True when one or more degradation families apply |
| `summaryMessage` | string | derived | Concise operator-facing truth |
| `nextAction` | string | derived | Prefer stronger version, inspect raw settings, or continue to restore with caution |
### 6. RestoreSelectionQualityHint
Selection-stage quality model for restore wizard step 1 and step 2.
| Field | Type | Source | Notes |
|---|---|---|---|
| `targetType` | string | derived | `backup_set` or `backup_item` |
| `targetId` | integer | selected record id | Identity |
| `summaryMessage` | string | derived | Early warning before risk checks |
| `degradationFamilies` | list<string> | derived | Carries through set-level or item-level truth |
| `nextAction` | string | derived | Inspect detail or continue with caution |
| `positiveClaimBoundary` | string | derived | Explicitly states that input quality is not restore safety |
Rules:
- Step 1 uses `BackupSetQualitySummary` facts.
- Step 2 uses `BackupItemQualityFact` facts.
- Neither step may claim `safe to restore`, `restore ready`, or `tenant recoverable`.
## Validation Rules
- Never derive backup quality from `BackupSet.status`, `PolicyVersion` action availability, or restore gating alone.
- `assignments_fetch_failed` and `has_orphaned_assignments` are distinct signals and must be surfaced separately where the UI can support it.
- `assignment_capture_reason` is explanatory metadata, not automatically a degraded state.
- `unknown quality` is permitted only when current metadata cannot justify `full` or `metadata_only` and cannot justify an assignment-quality claim.
- `TENANT_VIEW` visibility for backup-quality truth must remain independent from `TENANT_MANAGE` restore capability.
- Restore selection hints must explicitly preserve the claim boundary that backup quality is not restore safety.

View File

@ -0,0 +1,288 @@
# Implementation Plan: Backup Quality Truth Surfaces
**Branch**: `176-backup-quality-truth` | **Date**: 2026-04-07 | **Spec**: `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/176-backup-quality-truth/spec.md`
**Input**: Feature specification from `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/176-backup-quality-truth/spec.md`
## Summary
Harden the backup and versioning surfaces so operators can distinguish `stored` from `usable` and `degraded` recovery input before they reach restore-safety or execution surfaces. The implementation keeps `BackupSet`, `BackupItem`, and `PolicyVersion` as the existing sources of truth, introduces only a narrow derived backup-quality layer over current metadata and relationships, aggregates existing metadata-only and assignment-quality signals into summary facts, and hardens backup-set list and detail, backup-item relation, policy-version list and detail, and restore wizard step 1 and step 2 selection seams without adding a new persistence model.
Key approach: work inside the existing `BackupSetResource`, `BackupItemsRelationManager`, `PolicyVersionResource`, `RestoreRunResource`, and `CreateRestoreRun` seams; derive per-item and aggregate quality from existing metadata keys such as `source`, `snapshot_source`, `assignments_fetch_failed`, `assignment_capture_reason`, and `has_orphaned_assignments`; reuse Filament v5 tables, infolists, enterprise-detail builders, and shared badge infrastructure; keep all changes Livewire v4 compliant; avoid new tables, new Graph calls, and new asset registration; validate the result with focused Pest, Livewire, RBAC, and regression coverage.
## Technical Context
**Language/Version**: PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4
**Primary Dependencies**: Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BackupSetResource`, `BackupItemsRelationManager`, `PolicyVersionResource`, `RestoreRunResource`, `CreateRestoreRun`, `AssignmentBackupService`, `VersionService`, `PolicySnapshotService`, `RestoreRiskChecker`, `BadgeRenderer`, `PolicySnapshotModeBadge`, `EnterpriseDetailBuilder`, and existing RBAC helpers
**Storage**: PostgreSQL with existing tenant-owned `backup_sets`, `backup_items`, `policy_versions`, and restore wizard input state; JSON-backed `metadata`, `snapshot`, `assignments`, and `scope_tags`; no schema change planned
**Testing**: Pest feature tests, Livewire page or action tests, unit tests for narrow derived backup-quality helpers, all run through Sail
**Target Platform**: Laravel web application in Sail locally and containerized Linux deployment in staging and production
**Project Type**: Laravel monolith web application
**Performance Goals**: Keep backup, version, and restore-selection surfaces server-driven and DB-backed at render time, avoid new render-time external calls, preserve fast list scanability, and avoid introducing new N+1 query hotspots while computing quality summaries
**Constraints**: No new backup-health table, no new Graph contract path, no new queue or `OperationRun`, no route identity change, no RBAC drift, no conflation of backup quality with restore safety or tenant recoverability, no page-local badge mappings, and no new global Filament assets
**Scale/Scope**: One tenant-scoped backup-set list and detail flow, one backup-items relation-manager table, one tenant-scoped policy-version list and detail flow, restore wizard step 1 and step 2 selection surfaces, one narrow derived backup-quality helper layer, and focused regression coverage across truth presentation and RBAC behavior
## Constitution Check
*GATE: Passed before Phase 0 research. Re-checked after Phase 1 design and still passing.*
| Principle | Status | Notes |
|-----------|--------|-------|
| Inventory-first | Pass | Backups and versions remain immutable snapshot truth; no inventory ownership rule changes |
| Read/write separation | Pass | This slice is read-first truth hardening; existing restore and delete flows retain their current confirmations, audits, and tests |
| Graph contract path | Pass | No new Graph endpoints, no new Graph calls, and no contract registry changes are introduced |
| Deterministic capabilities | Pass | Existing capability registry, `CapabilityResolver`, and `UiEnforcement` remain authoritative |
| RBAC-UX planes and 404 vs 403 | Pass | All changed surfaces remain tenant-scoped; non-members still get 404, in-scope members without mutation capability still get 403 on execution |
| Workspace isolation | Pass | No workspace-scope broadening or cross-workspace visibility changes are planned |
| Tenant isolation | Pass | `BackupSet`, `BackupItem`, and `PolicyVersion` stay tenant-owned and tenant-entitled across list, detail, and wizard selection surfaces |
| Dangerous and destructive confirmations | Pass | Existing archive, restore, force-delete, and remove actions stay confirmation-gated and server-authorized |
| Global search safety | Pass | This feature adds no new globally searchable resource. `PolicyVersionResource` remains non-globally-searchable. `BackupSetResource` already has a view page if current configuration exposes it to search, and this slice adds no new cross-tenant hints |
| Run observability | Pass | No new long-running work or `OperationRun` usage is introduced |
| Ops-UX 3-surface feedback | Pass | No new operation start, toast, progress, or terminal notification surface is added |
| Ops-UX lifecycle ownership | Pass | `OperationRun.status` and `OperationRun.outcome` are untouched |
| Ops-UX summary counts | Pass | No new `summary_counts` keys or operation metrics are required |
| Data minimization | Pass | The slice reuses existing metadata and keeps diagnostics secondary; no new secret or raw payload exposure is planned |
| Proportionality (PROP-001) | Pass | Added logic is limited to a narrow derived backup-quality helper and direct surface integration across existing resources |
| Persisted truth (PERSIST-001) | Pass | No new table, column, or stored mirror is introduced; quality remains derived |
| Behavioral state (STATE-001) | Pass | Quality distinctions remain derived presentation truth from existing metadata, not new persisted lifecycle state |
| Badge semantics (BADGE-001) | Pass | Snapshot-mode rendering continues through `BadgeDomain::PolicySnapshotMode`; any new quality chips or labels stay inside shared badge or copy seams |
| Filament-native UI (UI-FIL-001) | Pass | Existing Filament tables, infolists, enterprise-detail cards, and wizard form descriptions remain the primary seams |
| UI naming (UI-NAMING-001) | Pass | The plan preserves operator vocabulary such as `metadata-only`, `assignment issues`, `degraded`, `full payload`, and `recovery input`, while avoiding `safe to restore` claims |
| Operator surfaces (OPSURF-001) | Pass | Changed surfaces become more operator-first by surfacing quality summary before diagnostics or later restore checks |
| Filament Action Surface Contract | Pass | No new inspect model, redundant View action, or empty action group is introduced; action placement remains unchanged |
| Filament UX-001 | Pass with documented variance | Backup-set detail continues to use the existing enterprise-detail layout and relation manager, but the plan adds a summary-first quality section before technical detail |
| Filament v5 / Livewire v4 compliance | Pass | The implementation stays inside the current Filament v5 and Livewire v4 stack |
| Provider registration location | Pass | No provider or panel changes; Laravel 11+ registration remains in `bootstrap/providers.php` |
| Asset strategy | Pass | No new panel assets are planned; deployment keeps the existing `php artisan filament:assets` step unchanged |
## Phase 0 Research
Research outcomes are captured in `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/176-backup-quality-truth/research.md`.
Key decisions:
- Derive backup quality from existing item and version metadata rather than introducing a persisted backup-health model.
- Treat backup lifecycle status and backup quality as separate truths on every affected surface.
- Reuse the central snapshot-mode badge and shared badge semantics instead of introducing page-local color or status logic.
- Extend the existing backup-set enterprise-detail builder, backup-items relation manager, policy-version resource, and restore wizard descriptions instead of creating a parallel dashboard or UI shell.
- Surface backup-set and item quality in restore wizard selection steps before the current restore-safety checks and preview steps, without turning quality hints into safety claims.
- Keep quality truth visible for `TENANT_VIEW` users even when restore actions remain unavailable.
- Use `unknown quality` only when the existing record does not contain authoritative metadata that can justify a stronger claim.
- Extend the existing Pest and Livewire test surfaces rather than creating a new browser-first harness.
## Phase 1 Design
Design artifacts are created under `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/176-backup-quality-truth/`:
- `research.md`: design and framework decisions for deriving and surfacing backup quality
- `data-model.md`: existing entities, current metadata signals, and narrow derived backup-quality models
- `contracts/backup-quality-truth.openapi.yaml`: internal logical contract for backup-set list and detail, backup-item relation rows, policy-version list and detail, and restore wizard selection surfaces
- `quickstart.md`: focused automated and manual validation workflow for backup-quality truth hardening
Design decisions:
- No schema migration is required; the design derives quality from existing `backup_items.metadata`, `policy_versions.metadata`, relationships, and current restore wizard state.
- A narrow derived helper layer is justified because the same quality truth must appear consistently across backup-set list, backup-set detail, backup-items, policy versions, and restore selection surfaces.
- Backup-set detail hardening stays inside `BackupSetResource::enterpriseDetailPage()` and existing enterprise-detail cards or sections rather than a new page shell.
- Policy-version hardening stays inside the existing table and infolist schema, replacing disabled-action-only signaling with explicit quality truth.
- Restore selection hardening stays inside `RestoreRunResource::getWizardSteps()` and `restoreItemOptionData()` so input quality appears before the existing checks and preview steps.
- Snapshot mode remains the primary quality badge, while aggregate counts and next-action language stay derived and secondary.
## Project Structure
### Documentation (this feature)
```text
specs/176-backup-quality-truth/
├── spec.md
├── plan.md
├── research.md
├── data-model.md
├── quickstart.md
├── contracts/
│ └── backup-quality-truth.openapi.yaml
├── checklists/
│ └── requirements.md
└── tasks.md
```
### Source Code (repository root)
```text
app/
├── Filament/
│ └── Resources/
│ ├── BackupSetResource.php
│ ├── PolicyVersionResource.php
│ ├── RestoreRunResource.php
│ └── BackupSetResource/
│ └── RelationManagers/
│ └── BackupItemsRelationManager.php
├── Models/
│ ├── BackupItem.php
│ ├── BackupSet.php
│ └── PolicyVersion.php
├── Services/
│ ├── AssignmentBackupService.php
│ └── Intune/
│ ├── PolicySnapshotService.php
│ ├── RestoreRiskChecker.php
│ ├── RestoreService.php
│ └── VersionService.php
└── Support/
├── BackupQuality/
│ ├── BackupQualityResolver.php
│ └── BackupQualitySummary.php
├── Badges/
│ └── Domains/
│ └── PolicySnapshotModeBadge.php
├── Ui/
│ └── EnterpriseDetail/
tests/
├── Feature/
│ ├── Filament/
│ │ ├── BackupSetUiEnforcementTest.php
│ │ ├── BackupSetEnterpriseDetailPageTest.php
│ │ ├── BackupItemsRelationManagerFiltersTest.php
│ │ ├── BackupQualityTruthSurfaceTest.php
│ │ ├── PolicyVersionQualityTruthSurfaceTest.php
│ │ ├── PolicyVersionTest.php
│ │ ├── PolicyVersionRestoreViaWizardTest.php
│ │ ├── RestoreItemSelectionTest.php
│ │ └── RestoreSelectionQualityTruthTest.php
│ └── Rbac/
│ ├── BackupItemsRelationManagerUiEnforcementTest.php
│ ├── BackupQualityVisibilityTest.php
│ ├── CreateRestoreRunAuthorizationTest.php
│ └── PolicyVersionsRestoreToIntuneUiEnforcementTest.php
│ └── RestoreRiskChecksWizardTest.php
└── Unit/
├── Support/
│ └── BackupQuality/
│ ├── BackupQualityResolverTest.php
│ └── BackupSetQualitySummaryTest.php
├── AssignmentBackupServiceTest.php
└── BackupItemTest.php
```
**Structure Decision**: Standard Laravel monolith. The implementation stays inside existing Filament resources, existing models and services that already hold the underlying metadata, and the current test structure. Any new helper types stay under the existing `app/Support/BackupQuality/` namespace as a narrow derived layer shared across backup, version, and restore-selection surfaces.
## Implementation Strategy
### Phase A — Introduce Narrow Derived Backup-Quality Facts
**Goal**: Create one reusable derivation path for backup quality from current metadata without adding a new persistence model.
| Step | File | Change |
|------|------|--------|
| A.1 | New narrow helper(s) under `app/Support/` if needed | Introduce a minimal backup-quality resolver or read-model helper that computes snapshot mode, assignment capture issues, orphaned assignment flags, integrity warnings, aggregate counts, and next-action guidance from existing `BackupItem` and `PolicyVersion` metadata |
| A.2 | `app/Models/BackupItem.php` and, only if clearly justified, `app/Models/PolicyVersion.php` | Add small convenience helpers for repeated metadata checks where this reduces duplication without embedding presentation language into the models |
| A.3 | `app/Support/Badges/Domains/PolicySnapshotModeBadge.php` and shared copy seams only if needed | Reuse the current snapshot-mode badge as the canonical item or version completeness signal; add no new badge domain unless a shared value cannot be expressed through current badge semantics |
### Phase B — Harden Backup-Set List And Detail Truth
**Goal**: Make backup-set surfaces answer `stored versus degraded` before diagnostics or restore intent.
| Step | File | Change |
|------|------|--------|
| B.1 | `app/Filament/Resources/BackupSetResource.php` | Add a compact backup-quality summary to the table that stays separate from lifecycle status and uses aggregate degraded counts rather than `status` to imply quality |
| B.2 | `app/Filament/Resources/BackupSetResource.php` | Update `enterpriseDetailPage()` to place a quality summary card or section ahead of technical detail, including metadata-only count, assignment issue count, orphaned assignment count, one primary next action, and contextual related links that stay out of the header |
| B.3 | `app/Filament/Resources/BackupSetResource.php` query seams | Ensure the list and detail surfaces eager-load or aggregate the needed backup-item quality facts without introducing a new N+1 hotspot |
### Phase C — Harden Backup-Item And Policy-Version Truth
**Goal**: Expose item-level and version-level input quality directly where operators inspect captured records.
| Step | File | Change |
|------|------|--------|
| C.1 | `app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php` | Add per-item snapshot mode, assignment capture issue, and orphaned-assignment truth to the relation table, preserving the current inspect model and action placement |
| C.2 | `app/Filament/Resources/PolicyVersionResource.php` | Add explicit snapshot mode or quality columns plus a single empty-state CTA to the policy-version list so metadata-only versions are visible at scan speed |
| C.3 | `app/Filament/Resources/PolicyVersionResource.php` | Add an explicit backup-quality section to the policy-version detail infolist so restore availability no longer acts as the only quality signal |
| C.4 | `app/Filament/Resources/PolicyVersionResource.php` | Preserve current restore-via-wizard gating and tooltip behavior while making quality truth visible independently from action disablement |
### Phase D — Harden Restore Selection Entry Points
**Goal**: Expose weak backup inputs before existing restore-safety checks and preview steps begin.
| Step | File | Change |
|------|------|--------|
| D.1 | `app/Filament/Resources/RestoreRunResource.php` | Enrich backup-set option labels or helper copy on wizard step 1 with backup-quality summary facts and degraded counts |
| D.2 | `app/Filament/Resources/RestoreRunResource.php` | Enrich `restoreItemOptionData()` so wizard step 2 descriptions include snapshot mode and item-level degradation truth before any risk checks run |
| D.3 | `app/Filament/Resources/RestoreRunResource.php` and `app/Filament/Resources/RestoreRunResource/Pages/CreateRestoreRun.php` | Preserve the current step order and restore-safety authority, while ensuring backup-quality messaging stops short of `safe to restore` or `recovery guaranteed` language |
### Phase E — Regression Protection And Focused Verification
**Goal**: Lock the new truth semantics into automated tests without weakening existing backup or restore behavior.
| Step | File | Change |
|------|------|--------|
| E.1 | Existing and new unit tests under `tests/Unit/Support/` | Add deterministic coverage for item-level quality derivation, aggregate backup-set counts, metadata-only detection, assignment failure mapping, and unknown-quality fallback |
| E.2 | `tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php` and new backup-set truth tests | Cover list or detail quality summary visibility, mixed-quality aggregation, and summary-first ordering |
| E.3 | `tests/Feature/Filament/PolicyVersionTest.php`, `tests/Feature/Filament/PolicyVersionRestoreViaWizardTest.php`, and new policy-version truth tests | Cover snapshot mode visibility, explicit detail quality truth, and non-reliance on disabled actions |
| E.4 | `tests/Feature/Filament/RestoreItemSelectionTest.php` and new restore-selection truth tests | Cover backup-set quality in step 1 and per-item quality in step 2 before risk checks |
| E.5 | RBAC tests under `tests/Feature/Rbac/` | Preserve 404 versus 403 behavior and verify that `TENANT_VIEW` users still see quality truth without restore rights |
| E.6 | `vendor/bin/sail bin pint --dirty --format agent` and focused Pest runs | Required formatting and targeted verification before implementation is considered complete |
## Key Design Decisions
### D-001 — Backup quality is derived from existing capture truth, not stored separately
The current product already records the signals that matter: metadata-only source markers, assignment fetch failures, orphaned assignments, warnings, and integrity hints. The missing piece is a consistent way to aggregate and display them across surfaces.
### D-002 — Backup lifecycle status and backup quality stay orthogonal
`completed`, `partial`, and `failed` remain capture-lifecycle truth. Aggregate backup-quality summaries answer whether the captured inputs appear strong or degraded as recovery input. The plan never reuses lifecycle status as a proxy for quality.
### D-003 — Snapshot completeness stays on the central badge system
The existing `PolicySnapshotModeBadge` already defines the primary `full` versus `metadata only` language. This slice reuses that badge instead of introducing a second status vocabulary for the same truth.
### D-004 — Restore selection surfaces expose input quality, not safety approval
Step 1 and step 2 only need to tell the operator whether the chosen backup set or items look degraded. Restore safety, preview decisions, and execution readiness remain owned by the later steps and existing restore-safety logic.
### D-005 — RBAC can suppress actions, not truth
Users with view rights must still see backup-quality truth even when restore entry points or maintenance actions are unavailable. Hiding or muting quality because of missing restore capability would falsify the surface.
### D-006 — Existing Filament seams are sufficient
The current enterprise-detail builder, table columns, infolist sections, and checkbox-list descriptions already provide the UI seams this slice needs. A dashboard, custom shell, or new client-side state layer would be disproportionate.
### D-007 — Unknown quality is an explicit fallback, not the default
The product should only emit `unknown quality` where current records truly lack authoritative metadata. If existing metadata can justify `metadata-only`, `assignment issue`, or `orphaned assignments`, the surface must say so directly.
## Risk Assessment
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Aggregation logic diverges between backup items, policy versions, and restore selection descriptions | High | Medium | Use one narrow derived helper path and cover it with mixed-quality unit and feature tests |
| Quality summary introduces N+1 queries or heavy per-row work on backup-set list pages | High | Medium | Preload relations or aggregate counts deliberately and add list-focused regression coverage |
| UI wording slips from backup quality into restore safety or tenant recoverability claims | High | Medium | Keep operator copy centralized and test for explicit non-claims on degraded and healthy-looking cases |
| Read-only users lose quality visibility because existing restore gating is accidentally reused | High | Medium | Add dedicated RBAC visibility tests for `TENANT_VIEW` members without restore capability |
| Metadata-only restore blocking semantics regress because selection hints are coupled too tightly to risk checks | Medium | Medium | Keep restore selection quality read-only and rerun focused restore-safety regression tests alongside the new surface tests |
## Test Strategy
- Extend existing backup-set, backup-items, policy-version, restore-selection, and RBAC Pest coverage before introducing any new harness.
- Add unit tests for the narrow backup-quality helper so metadata-only detection, assignment issue mapping, orphaned-assignment mapping, and aggregate counts remain deterministic.
- Add feature tests that prove `completed` and `good backup` are no longer visually conflated on backup-set list and detail surfaces.
- Add feature tests that prove metadata-only and assignment-capture issues are visible on backup items and policy versions without relying on disabled actions or late restore checks.
- Add feature tests that prove restore wizard step 1 and step 2 expose degraded input before risk checks or preview generation.
- Add RBAC tests that prove `TENANT_VIEW` users still see backup-quality truth while restore actions remain unavailable, and non-members still receive 404 semantics.
- Re-run existing restore-safety and restore-selection tests so earlier input-quality visibility does not change existing risk-check or execution behavior.
- Keep all tests Livewire v4 compatible and run the smallest affected subset through Sail before asking for a full-suite pass.
## Complexity Tracking
No constitution violations or exception-driven complexity were identified. The only added structure is a narrow derived backup-quality helper layer justified by cross-surface reuse and the need to keep current metadata interpretation consistent across list, detail, and wizard selection surfaces.
## Proportionality Review
- **Current operator problem**: Operators can currently tell that a backup set, backup item, or policy version exists, but they cannot quickly tell whether it is strong, degraded, or metadata-only as recovery input before they reach deep diagnostics or restore-safety surfaces.
- **Existing structure is insufficient because**: The relevant truth is fragmented across backup metadata, version metadata, assignment fetch flags, orphaned-assignment markers, and disabled restore actions. Presence is visible earlier than usefulness, which creates false trust.
- **Narrowest correct implementation**: Add one narrow derived backup-quality helper path and integrate it directly into existing backup-set, backup-item, policy-version, and restore-selection surfaces without adding new persistence or a broad taxonomy framework.
- **Ownership cost created**: A small amount of derivation logic, additional list or detail wiring, and focused unit and feature tests to keep the mapping stable.
- **Alternative intentionally rejected**: A persisted backup-health table, a recovery-confidence score, or a dashboard-wide backup-health program. Each would create broader truth and ownership cost than the current operator problem requires.
- **Release truth**: Current-release truth. This slice corrects the truth on already-shipped backup and version surfaces before later backup-health or recovery-confidence work builds on them.

View File

@ -0,0 +1,132 @@
# Quickstart: Backup Quality Truth Surfaces
## Goal
Validate that backup-set, backup-item, policy-version, and restore-selection surfaces now communicate backup quality truth early and explicitly without overstating restore safety, restore readiness, or tenant recoverability.
## Prerequisites
1. Start Sail if it is not already running.
2. Ensure the workspace has representative fixtures for:
- a backup set with only full-payload items
- a backup set with at least one metadata-only item
- a backup set with assignment fetch failure metadata
- a backup set with orphaned-assignment metadata
- one policy version captured as full payload
- one policy version captured as metadata-only
- one user with `TENANT_VIEW` but without restore capability
- one user with restore capability for the same tenant
3. Ensure the acting users are valid workspace and tenant members.
4. Ensure archived backup-set and policy-version fixtures exist if lifecycle plus quality combinations need validation.
## Focused Automated Verification
Run the smallest existing backup, version, and restore-selection pack first:
```bash
vendor/bin/sail artisan test --compact tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BackupItemsRelationManagerFiltersTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BackupSetUiEnforcementTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/PolicyVersionTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/PolicyVersionRestoreViaWizardTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/RestoreItemSelectionTest.php
vendor/bin/sail artisan test --compact tests/Feature/Rbac/BackupItemsRelationManagerUiEnforcementTest.php
vendor/bin/sail artisan test --compact tests/Feature/Rbac/PolicyVersionsRestoreToIntuneUiEnforcementTest.php
vendor/bin/sail artisan test --compact tests/Feature/Rbac/CreateRestoreRunAuthorizationTest.php
vendor/bin/sail artisan test --compact tests/Feature/RestoreRiskChecksWizardTest.php
vendor/bin/sail artisan test --compact tests/Unit/AssignmentBackupServiceTest.php
vendor/bin/sail artisan test --compact tests/Unit/BackupItemTest.php
```
Expected new or expanded spec-scoped tests:
```bash
vendor/bin/sail artisan test --compact tests/Feature/Filament/BackupQualityTruthSurfaceTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/PolicyVersionQualityTruthSurfaceTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/RestoreSelectionQualityTruthTest.php
vendor/bin/sail artisan test --compact tests/Feature/Rbac/BackupQualityVisibilityTest.php
vendor/bin/sail artisan test --compact tests/Unit/Support/BackupQuality/
```
Use `--filter` for a smaller pass while iterating.
## Manual Validation Pass
### 1. Verify backup-set list truth
Open `/admin/t/{tenant}/backup-sets` and confirm:
- lifecycle status remains visible and separate from backup-quality summary
- a full-quality set reads as `no degradations detected` or equivalent without implying safe restore
- a degraded set shows metadata-only, assignment issues, orphaned assignments, or degraded-item count within one scan
### 2. Verify backup-set detail summary-first layout
Open a degraded backup set and confirm:
- the first visible summary answers whether the set is strong or weak as recovery input
- metadata-only count, assignment issue count, and orphaned-assignment count appear before raw metadata
- one primary next action is visible when degraded truth exists
### 3. Verify backup-items relation truth
Within the same backup-set detail page, confirm the relation table shows:
- snapshot mode per item
- assignment capture issue truth per item
- orphaned-assignment truth per item
- current inspect model and action placement remain unchanged
### 4. Verify policy-version list and detail truth
Open `/admin/t/{tenant}/policy-versions` and confirm:
- metadata-only versions are visible at scan speed in the list itself
- full-payload and degraded versions are distinguishable without hovering disabled actions
Open a degraded policy version and confirm:
- an explicit backup-quality section appears on the detail surface
- the page explains degraded input quality without claiming safe restore or meaningful rollback certainty
### 5. Verify restore-selection truth before risk checks
Open `/admin/t/{tenant}/restore-runs/create` and confirm:
- step 1 backup-set choices expose degraded input before the wizard reaches checks or preview
- step 2 item descriptions expose metadata-only and assignment-quality truth before risk checks run
- the page still treats backup quality as input truth, not restore safety approval
### 6. Verify RBAC-safe truth visibility
Repeat the list and detail checks as a user with `TENANT_VIEW` but without restore permission and confirm:
- backup-quality truth remains visible
- restore entry points remain unavailable or disabled with the current RBAC behavior
- non-members still receive deny-as-not-found behavior rather than resource hints
## Non-Regression Checks
Confirm the feature did not change:
- tenant route identity for backup, version, or restore pages
- current archive, restore, force-delete, or remove confirmation behavior
- existing restore-safety blocking behavior for metadata-only input
- existing assignment capture semantics and orphaned-assignment detection
- current global asset registration and deployment requirements
## Formatting And Final Verification
Before finalizing implementation work:
```bash
vendor/bin/sail bin pint --dirty --format agent
```
Then rerun the smallest affected test set and offer the full suite only after the focused backup-quality pack passes.
Close the feature only after manual validation confirms:
- an operator can identify degraded versus full-looking backup input within 10 seconds on backup-set list and detail surfaces
- the first restore selection step exposes weak inputs before risk-check work begins
- reduced-permission users still see truthful quality signals without gaining restore capability

View File

@ -0,0 +1,65 @@
# Research: Backup Quality Truth Surfaces
## Decision 1: Derive backup quality from existing backup and version metadata instead of creating a persisted backup-health model
- Decision: Build backup quality from the metadata already present on `BackupItem` and `PolicyVersion`, then aggregate backup-set truth from those per-item facts. Do not add a new table, column, or stored backup-health projection.
- Rationale: The current data model already records the core quality signals this feature needs: metadata-only source markers, assignment fetch failures, orphaned assignments, warnings, scope-tag context, and integrity notes. The product problem is weak surfacing, not missing persistence.
- Alternatives considered:
- Persist a `backup_quality` or `backup_health` table. Rejected because it would create a second source of truth for information that is already derivable.
- Add materialized quality fields to `backup_sets` or `policy_versions`. Rejected because the feature does not need independent lifecycle state.
## Decision 2: Keep capture lifecycle and backup quality as separate truths on every affected surface
- Decision: Render capture lifecycle (`completed`, `partial`, `failed`, `archived`) independently from backup quality (`metadata-only present`, `assignment issues present`, degraded-count summary, or no degradations detected).
- Rationale: Operators currently overread `completed` as `good backup`. The feature must stop that conflation without erasing the lifecycle truth that the system already tracks.
- Alternatives considered:
- Blend quality into one stronger status badge. Rejected because that would collapse two different truths into one ambiguous state.
- Treat `completed` plus degraded counts as a new status family. Rejected because it would introduce new state where derived summary is sufficient.
## Decision 3: Reuse the central snapshot-mode badge and shared badge infrastructure instead of page-local mapping
- Decision: Use the existing `BadgeDomain::PolicySnapshotMode` and `PolicySnapshotModeBadge` semantics for `full` versus `metadata only`. Any new quality chips or labels should stay inside shared badge or copy seams rather than page-local `match` statements.
- Rationale: The codebase already centralizes status-like badge semantics, and Filament v5 tables or schema text badges can render those shared specs directly. This keeps backup quality aligned with BADGE-001 and avoids a second vocabulary for snapshot completeness.
- Alternatives considered:
- Add local badge mapping per surface. Rejected because it would drift from the central badge catalog.
- Introduce a generic trust score badge. Rejected because the spec explicitly avoids a new scoring engine.
## Decision 4: Use existing Filament tables, infolists, enterprise-detail sections, and checkbox-list descriptions instead of a new UI shell
- Decision: Implement the feature inside `BackupSetResource`, `BackupItemsRelationManager`, `PolicyVersionResource`, and `RestoreRunResource` using the current Filament table columns, infolist sections, enterprise-detail builder, and wizard descriptions.
- Rationale: Filament v5 already supports badge columns, summary-first view content, relation-manager tables, and descriptive checkbox list options. The repository also already uses `enterpriseDetailPage()` for backup-set detail and schema-driven wizard steps for restore selection.
- Alternatives considered:
- Build a dedicated backup-health dashboard. Rejected because it is explicitly out of scope.
- Add a custom client-side wizard overlay. Rejected because the needed truth is server-driven and fits existing Filament seams.
## Decision 5: Surface backup-set and item quality in restore selection before risk checks, but keep restore safety as a separate authority
- Decision: Enrich restore wizard step 1 backup-set labels or helper copy and step 2 item descriptions with input-quality truth before preview or risk checks run. Do not block degraded selections at this stage unless existing restore safety already blocks them later.
- Rationale: Operators need early warning before the risk-check stage, but this spec is about backup quality, not execution safety. The restore-safety layer already owns blocker and preview-only semantics.
- Alternatives considered:
- Leave degraded truth exclusively to restore risk checks. Rejected because it preserves the current late-discovery trust failure.
- Prevent selecting degraded inputs in step 1 or step 2. Rejected because the spec requires truthful surfacing, not a new restore policy.
## Decision 6: Preserve truth visibility for `TENANT_VIEW` users even when restore actions remain unavailable
- Decision: Quality truth remains visible on backup-set and policy-version surfaces for users who can view tenant backup or version records, even if they cannot create restore runs or use maintenance actions.
- Rationale: Missing restore permission must not make degraded inputs appear calmer or cleaner. Authorization can suppress mutation, but it must not suppress source-of-truth visibility.
- Alternatives considered:
- Couple quality sections to restore permissions. Rejected because it would falsify the operator surface.
- Rely on disabled restore actions as the quality indicator for lower-privilege users. Rejected because disabled actions are not an adequate explanation of input quality.
## Decision 7: Use `unknown quality` only when existing metadata cannot justify a stronger claim
- Decision: Emit `unknown quality` only when the record lacks authoritative metadata for snapshot completeness or assignment-quality interpretation. Absence of an error is not enough to call an item or version `full` if the record never captured the relevant quality signal.
- Rationale: Defaulting to `unknown` too often would hide real degradations, while defaulting to `full` from silence would overstate confidence. This feature needs a narrow, evidence-based fallback.
- Alternatives considered:
- Default all older records to `unknown`. Rejected because many records already carry usable source metadata.
- Infer `full` whenever `metadata_only` is absent. Rejected because silence is not always proof of completeness.
## Decision 8: Extend the existing Pest and Livewire test surface rather than introducing a browser-first harness
- Decision: Add focused unit coverage for backup-quality derivation and extend existing backup, version, restore-selection, and RBAC feature tests for UI truth. Keep the current Pest and Livewire patterns as the main verification path.
- Rationale: The affected behavior is server-driven list, detail, and wizard state, which the current test suite already covers well. The repo also already has restore and RBAC tests that should remain authoritative.
- Alternatives considered:
- Rely only on manual validation. Rejected because the feature is specifically about preventing subtle trust regressions.
- Introduce a large browser-only test pack. Rejected because the most important assertions are deterministic server-side state and rendered truth.

View File

@ -0,0 +1,193 @@
# Feature Specification: Backup Quality Truth Surfaces
**Feature Branch**: `[176-backup-quality-truth]`
**Created**: 2026-04-07
**Status**: Draft
**Input**: User description: "Spec 176 - Backup Quality Truth Surfaces"
## Spec Scope Fields *(mandatory)*
- **Scope**: tenant
- **Primary Routes**: `/admin/t/{tenant}/backup-sets`, `/admin/t/{tenant}/backup-sets/{record}`, `/admin/t/{tenant}/policy-versions`, `/admin/t/{tenant}/policy-versions/{record}`, `/admin/t/{tenant}/restore-runs/create`
- **Data Ownership**: Tenant-owned `BackupSet`, `BackupItem`, `PolicyVersion`, and `RestoreRun` draft-selection state within the active workspace and tenant scope.
- **RBAC**: Workspace plus tenant membership is required on every affected surface. Members with `TENANT_VIEW` must see backup-quality truth on backup and version surfaces. Restore creation remains gated by `TENANT_MANAGE`. Backup-set mutation actions remain gated by existing `TENANT_SYNC`, `TENANT_MANAGE`, and `TENANT_DELETE` capabilities.
## UI/UX Surface Classification *(mandatory when operator-facing surfaces are changed)*
| Surface | Surface Type | Primary Inspect/Open Model | Row Click | Secondary Actions Placement | Destructive Actions Placement | Canonical Collection Route | Canonical Detail Route | Scope Signals | Canonical Noun | Critical Truth Visible by Default | Exception Type |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Backup sets page | CRUD / list-first resource | Full-row click to backup-set detail | required | One inline safe shortcut plus More | More menu and bulk More | `/admin/t/{tenant}/backup-sets` | `/admin/t/{tenant}/backup-sets/{record}` | Workspace context plus tenant context | Backup sets / Backup set | Capture lifecycle and backup quality summary | none |
| Backup set detail | Detail plus relation manager | Direct detail page | forbidden | Contextual summary links plus relation header actions | Resource More and relation-manager More | `/admin/t/{tenant}/backup-sets` | `/admin/t/{tenant}/backup-sets/{record}` | Tenant context plus related policy context | Backup set | Quality summary before per-item diagnostics | none |
| Backup items table | Relation-manager table | Full-row click within backup-set detail | required | Relation header actions plus More | More menu and bulk More | `/admin/t/{tenant}/backup-sets/{record}` | `/admin/t/{tenant}/backup-sets/{record}` | Parent backup set plus tenant context | Backup items / Backup item | Snapshot mode and assignment-quality truth per item | existing relation-manager pattern |
| Policy versions page | CRUD / list-first resource | Full-row click to policy-version detail | required | More menu | More menu and bulk More | `/admin/t/{tenant}/policy-versions` | `/admin/t/{tenant}/policy-versions/{record}` | Workspace context plus tenant context | Policy versions / Policy version | Snapshot mode and version input quality | Empty-state CTA routes to backup sets |
| Policy version detail | Detail / infolist page | Direct detail page | forbidden | Minimal related navigation only | No new destructive detail action placement | `/admin/t/{tenant}/policy-versions` | `/admin/t/{tenant}/policy-versions/{record}` | Tenant context plus related policy context | Policy version | Explicit backup-quality truth separate from restore availability | existing minimal header pattern |
| Restore run create wizard | Wizard / selection workflow | Step-driven selection inside restore-run creation | forbidden | Inline descriptions and next-action guidance | None at selection stage | `/admin/t/{tenant}/restore-runs` | `/admin/t/{tenant}/restore-runs/create` | Tenant context plus selected backup set | Restore run / Backup selection | Backup-set and item quality before safety checks | none |
## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)*
| Surface | Primary Persona | Surface Type | Primary Operator Question | Default-visible Information | Diagnostics-only Information | Status Dimensions Used | Mutation Scope | Primary Actions | Dangerous Actions |
|---|---|---|---|---|---|---|---|---|---|
| Backup sets page | Tenant operator | List | Which backup sets look strong or weak as recovery input? | Name, item count, capture timing, lifecycle status, compact backup-quality summary | Raw item metadata, per-item details, restore safety analysis | Capture lifecycle, input quality | TenantPilot only for existing archive and restore maintenance | Open backup set, Create backup set | Archive, Restore archived set, Force delete |
| Backup set detail | Tenant operator | Detail | Is this backup set a strong or weak recovery input, and why? | Quality summary, degraded counts, next actions, related context | Raw payloads, raw assignment JSON, integrity detail | Input quality, assignment completeness, lifecycle status | TenantPilot only for existing maintenance actions | Inspect backup items, open related context from contextual links | Archive, Restore archived set, Force delete |
| Backup items table | Tenant operator | Table inside detail | Which items are degraded inside this backup set? | Display name, type, snapshot mode, assignment issue signal, orphaned-assignment signal | Full metadata, raw assignments, low-level IDs | Snapshot completeness, assignment completeness | TenantPilot only for add and remove maintenance; none for visibility | Refresh, Add Policies, inspect row | Remove, Remove selected |
| Policy versions page | Tenant operator | List | Which versions are full-payload versus metadata-only or otherwise degraded? | Policy identity, version number, capture time, snapshot mode, quality signal | Raw JSON, diff payload, redaction detail | Version lifecycle, input quality | TenantPilot only for existing archive and maintenance actions | Open version, open related policy, open backup sets from empty state | Restore via Wizard, Archive, Restore archived version, Force delete, bulk prune |
| Policy version detail | Tenant operator | Detail | Is this version worth using as restore input? | Version identity, explicit backup-quality section, related context | Normalized settings, raw JSON, diff, redaction detail | Input quality, version lineage | None for visibility; existing restore entry remains separately gated | Open related policy | No new destructive detail action |
| Restore run create wizard | Tenant operator with restore rights | Wizard | Which backup set or items should I avoid or inspect before running safety checks? | Backup-set quality summary, per-item quality descriptions, stronger or weaker input hints | Risk-check output, preview diff, unresolved mapping detail | Input quality first, restore safety later | Simulation only until later confirmation and execution steps | Select backup set, select items, continue through wizard | Final restore execution remains later in the flow |
## Proportionality Review *(mandatory when structural complexity is introduced)*
- **New source of truth?**: no
- **New persisted entity/table/artifact?**: no
- **New abstraction?**: yes
- **New enum/state/reason family?**: no
- **New cross-domain UI framework/taxonomy?**: no
- **Current operator problem**: Operators can currently tell that a backup, item, or version exists, but they cannot quickly tell whether it is strong, degraded, or metadata-only as recovery input before they reach deep detail or restore-safety surfaces.
- **Existing structure is insufficient because**: The relevant truth is split across backup metadata, assignment metadata, disabled restore actions, and later restore-safety checks. That fragmentation causes false confidence and late discovery.
- **Narrowest correct implementation**: Introduce at most one narrow derived backup-quality helper that reads existing `BackupSet`, `BackupItem`, and `PolicyVersion` metadata and exposes a compact summary for existing list, detail, and wizard surfaces.
- **Ownership cost**: A small amount of shared derivation logic plus unit, feature, and RBAC regression tests that keep quality labels aligned with the underlying metadata keys.
- **Alternative intentionally rejected**: A persisted backup-health table, a tenant-wide scoring model, or a new recovery-confidence engine were rejected because they would create new truth, new state, and new ownership cost before the current surfaces tell the existing truth well.
- **Release truth**: current-release truth hardening
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Judge Backup Sets Early (Priority: P1)
A tenant operator opens the backup-set list or detail page and needs to tell within seconds whether a backup set is merely stored or also looks strong enough to inspect further as recovery input.
**Why this priority**: This is the earliest point where false confidence must be prevented. If the operator misreads `completed` as `good backup`, every later restore decision inherits that error.
**Independent Test**: Can be fully tested by loading backup-set list and detail pages with full-quality and degraded fixtures and verifying that lifecycle status and backup quality are shown separately.
**Acceptance Scenarios**:
1. **Given** a tenant has one full-quality backup set and one degraded backup set, **When** the operator opens the backup-set list, **Then** each row shows capture status separately from a compact backup-quality summary.
2. **Given** a backup set contains degraded items, **When** the operator opens backup-set detail, **Then** the page shows a quality summary with degradation counts before per-item diagnostics or raw metadata.
3. **Given** a completed backup set contains only metadata-only items, **When** the operator scans the list or detail surface, **Then** the surface does not imply that the set is safe to restore or broadly recoverable.
---
### User Story 2 - Inspect Item and Version Strength (Priority: P2)
A tenant operator reviewing backup items or policy versions needs to distinguish full payloads from metadata-only or assignment-degraded inputs without inferring that truth from disabled actions or hidden metadata.
**Why this priority**: Item-level and version-level truth determines whether a backup set is actually useful. If this information stays implicit, operators cannot compare restore inputs confidently.
**Independent Test**: Can be fully tested by loading the backup-items table, policy-version list, and policy-version detail page with mixed-quality records and verifying explicit per-record quality signals.
**Acceptance Scenarios**:
1. **Given** backup items include full payload, metadata-only, assignment-fetch-failed, and orphaned-assignment examples, **When** the operator reviews the backup-items table, **Then** each item shows explicit snapshot mode and assignment-quality signals.
2. **Given** policy versions include both full payload and metadata-only snapshots, **When** the operator reviews the policy-version list, **Then** snapshot mode is visible without needing to hover disabled actions.
3. **Given** a policy-version detail page represents a degraded version, **When** the operator opens the page, **Then** the page shows an explicit backup-quality section that explains the weakness without using restore availability as the only signal.
---
### User Story 3 - Select Restore Inputs With Early Warning (Priority: P3)
A tenant operator starting a restore run needs to see weak backup sets and weak items before risk checks or preview steps so that poor input quality is visible at the first selection point.
**Why this priority**: Restore-safety hardening already exists later in the flow. This story closes the trust gap before the operator commits to a candidate backup set or item selection.
**Independent Test**: Can be fully tested by opening the restore-run creation wizard with degraded backup-set and backup-item fixtures and verifying that selection step labels or descriptions expose quality truth before safety checks run.
**Acceptance Scenarios**:
1. **Given** a degraded backup set is available for restore, **When** the operator opens restore wizard step 1, **Then** the backup-set selection surface shows that the set contains degraded input before the operator reaches safety checks.
2. **Given** selected restore items include metadata-only and assignment-degraded inputs, **When** the operator reviews restore wizard step 2, **Then** each affected item is clearly marked as degraded before any risk-check action occurs.
3. **Given** a backup set is full-quality, **When** the operator reviews steps 1 and 2, **Then** the wizard can communicate that no degradations are currently detected without claiming that restore is safe.
---
### User Story 4 - Preserve Truth Under RBAC Boundaries (Priority: P4)
A tenant member with backup or version viewing rights but without restore or maintenance rights still needs to see the same backup-quality truth so that authorization boundaries do not make weak inputs look calmer than they are.
**Why this priority**: Security boundaries must not distort source-of-truth visibility. Otherwise the UI becomes less truthful for read-only operators than for managers.
**Independent Test**: Can be fully tested by signing in as a tenant member with `TENANT_VIEW` but without restore capabilities and verifying that list and detail surfaces still expose quality truth while restore actions remain unavailable.
**Acceptance Scenarios**:
1. **Given** a tenant member has backup and version viewing rights but lacks restore permission, **When** they open backup-set or policy-version surfaces, **Then** backup-quality signals remain visible while restore actions stay unavailable.
2. **Given** a non-member requests the same tenant-scoped surfaces, **When** the request is made, **Then** the system responds with deny-as-not-found semantics instead of exposing resource existence.
### Edge Cases
- A backup set is `completed` and has zero degradations; the surface must explicitly show that no degradations are detected rather than leaving quality unstated.
- A backup set mixes full payload items with metadata-only and assignment-degraded items; the summary must show mixed quality without collapsing to a single misleading label.
- Assignment capture is marked not applicable for a policy type; the surface must not mislabel that condition as a failure.
- Older items or versions lack enough metadata to derive quality; the surface may show `unknown` only when no existing authoritative signal is available.
- Archived backup sets and archived policy versions must retain the same quality truth on list and detail surfaces as active records.
## Requirements *(mandatory)*
This feature introduces no new Microsoft Graph calls, no new background work, no new `OperationRun`, and no new persistence. It is a read-first truth-hardening feature that makes existing backup and version metadata visible earlier and more clearly.
Authorization remains in the tenant/admin plane under `/admin/t/{tenant}/...`. Non-members must continue to receive 404 responses. Established members missing mutation capabilities must continue to receive 403 on execution. Members with `TENANT_VIEW` must still see backup-quality truth on backup and version surfaces even when restore entry points remain unavailable.
Badge and UI semantics must stay centralized. Existing shared badge semantics, especially snapshot-mode badges, remain the canonical language for status-like signals. Any new quality labels or summaries must be derived from shared backup-quality rules rather than page-local color or wording decisions.
The affected Filament surfaces must keep exactly one primary inspect or open model, must not add redundant View actions, and must preserve destructive-action placement and confirmation behavior already defined by the action-surface contract. Quality truth is additive to existing surfaces, not a new local action framework.
If a shared backup-quality helper is introduced, it must replace duplicated page-local derivation instead of layering a second semantic system on top of existing restore-safety logic. Restore safety, preview eligibility, and execution outcome remain separate truths.
### Functional Requirements
- **FR-176-001**: The system MUST present backup existence truth separately from backup quality truth so that `completed`, `partial`, and `failed` remain capture-lifecycle states rather than quality claims.
- **FR-176-002**: The backup-set list MUST show a compact backup-quality summary per row that indicates either no detected degradations or the presence of one or more degradation families.
- **FR-176-003**: The backup-set detail surface MUST show a default-visible quality summary before deep diagnostics, including counts for metadata-only items, assignment-capture issues, orphaned-assignment signals, and any other degradation families that are already authoritatively derivable.
- **FR-176-004**: The backup-items table MUST show per-item snapshot mode and per-item assignment-quality signals without requiring the operator to open raw JSON or later restore surfaces.
- **FR-176-005**: The policy-version list MUST show snapshot mode for every visible version and MUST make degraded versions distinguishable from full-payload versions at scan speed.
- **FR-176-006**: The policy-version detail page MUST show explicit backup-quality truth and MUST NOT rely on disabled restore actions or tooltips as the only signal that a version is weak.
- **FR-176-007**: Restore wizard step 1 MUST expose backup-set quality before the operator reaches safety checks, preview generation, or execution confirmation.
- **FR-176-008**: Restore wizard step 2 MUST expose item-level quality before safety checks, including metadata-only and assignment-quality degradations where the underlying data already exists.
- **FR-176-009**: Metadata-only state MUST appear on backup and version surfaces as soon as the source metadata can establish it, and MUST NOT first surface as a restore-stage surprise.
- **FR-176-010**: Assignment-capture failures and orphaned-assignment signals MUST be operator-visible on backup-quality surfaces whenever the metadata already records them.
- **FR-176-011**: Backup-quality surfaces MUST NOT claim that a backup set, item, or version is safe to restore, restore-ready, or guaranteed to succeed.
- **FR-176-012**: Backup-quality surfaces MUST NOT imply that a strong-looking backup set proves tenant-wide recoverability, a guaranteed rollback path, or a recovery certification outcome.
- **FR-176-013**: Version history surfaces MUST separate three truths: version exists, version is selectable under current permissions and lifecycle state, and version has stronger or weaker payload quality.
- **FR-176-014**: When a backup set, item, or version is weak, the surface MUST suggest meaningful next actions such as opening detail, inspecting degraded items, preferring a stronger version, or continuing into restore with caution.
- **FR-176-015**: Quality signals MUST remain visible to users with backup or version viewing rights even when deeper restore or operations surfaces are inaccessible.
- **FR-176-016**: The feature MUST derive backup-quality truth from existing tenant-owned records and metadata and MUST NOT require a new persistence model, new materialized state, or a new cross-tenant scoring engine.
## Assumptions
- Existing metadata keys such as `source`, `snapshot_source`, `assignments_fetch_failed`, `assignment_capture_reason`, `has_orphaned_assignments`, scope-tag metadata, and redaction or integrity notes are authoritative enough for first-pass backup-quality truth.
- Existing restore-safety checks remain the sole owner of blocker, warning, preview-only, and execution-gating language.
- Older records may lack some quality metadata; in those cases the product may show `unknown quality` only when the existing record truly does not contain enough information to derive a stronger statement.
## Dependencies
- Existing tenant-scoped backup, version, and restore resources remain the operator entry points.
- Existing centralized badge semantics, especially snapshot-mode badges, remain the canonical language for visible status.
- Existing restore-safety integrity behavior and metadata-only execution blocking remain unchanged and continue to run after the earlier backup-quality surfaces.
## Out of Scope and Follow-up
- No redesign of restore execution, restore-safety logic, backup capture, retention or pruning, tenant-wide recovery scoring, notification domains, or new persisted backup-health artifacts.
- Reasonable follow-up work includes a backup-health dashboard, a broader recovery-confidence rollup, and version-rollback usefulness guidance after the current truth-hardening slice is complete.
## UI Action Matrix *(mandatory when Filament is changed)*
| Surface | Location | Header Actions | Inspect Affordance (List/Table) | Row Actions (max 2 visible) | Bulk Actions (grouped) | Empty-State CTA(s) | View Header Actions | Create/Edit Save+Cancel | Audit log? | Notes / Exemptions |
|---|---|---|---|---|---|---|---|---|---|---|
| BackupSetResource | `app/Filament/Resources/BackupSetResource.php` | Create backup set | `recordUrl()` clickable row | Primary related action, More: Restore / Archive / Force delete | More: Archive Backup Sets / Restore Backup Sets / Force Delete Backup Sets | Create backup set | Grouped existing mutations remain; related navigation stays in contextual summary links, not the header | Create backup set submit plus cancel | Existing audit logging remains for restore, archive, and force delete; read-only quality truth adds no new audit event | Action surface contract stays satisfied. Quality summary is additive only. |
| BackupItemsRelationManager | `app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php` | Refresh, Add Policies | Clickable row | More: Remove | More: Remove selected | Add Policies | n/a | n/a | Existing operation-run and audit behavior for remove flows remains; visibility changes are read-only | Existing relation-manager exception remains; no redundant View action is added. |
| PolicyVersionResource | `app/Filament/Resources/PolicyVersionResource.php` | none | `recordUrl()` clickable row | Primary related action, More: Restore via Wizard / Archive / Force delete / Restore archived version | More: Prune Versions / Restore Versions / Force Delete Versions | Open backup sets | Existing detail header remains intentionally minimal | n/a | Existing audit logging remains for archive, force delete, and restore; restore-via-wizard keeps existing restore-run and backup creation behavior | Policy-version detail gains explicit quality truth so disabled actions stop being the only signal. |
| Restore run create wizard | `app/Filament/Resources/RestoreRunResource.php`, `app/Filament/Resources/RestoreRunResource/Pages/CreateRestoreRun.php` | none | n/a | n/a | n/a | none | n/a | Wizard Previous / Next / Create restore run | Existing restore-run create and execute audit behavior remains unchanged; selection-stage quality visibility is read-only | Step 1 and step 2 gain quality descriptions only. No new destructive action is introduced. |
## Key Entities *(include if feature involves data)*
- **BackupSet**: A tenant-owned capture collection that already records lifecycle state, timestamps, item count, and metadata describing how the set was produced.
- **BackupItem**: A tenant-owned captured recovery input for one policy or foundation item, including payload, assignments, and metadata that can expose snapshot completeness and assignment-quality issues.
- **PolicyVersion**: An immutable tenant-owned version record that stores captured snapshot data, related metadata, assignments, redaction context, and capture timing.
- **Restore selection context**: The tenant-scoped backup-set and optional item selection that an operator builds before restore-safety checks and preview generation.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: In validation sessions and acceptance tests, an operator can identify whether a backup set is full-quality or degraded from the list or detail surface in under 10 seconds without opening raw JSON or preview surfaces.
- **SC-002**: In 100% of tested cases where existing records contain metadata-only, assignment-fetch-failed, or orphaned-assignment signals, at least one default-visible backup-quality signal appears on every affected list, detail, or wizard selection surface.
- **SC-003**: In 100% of RBAC test cases, users with backup or version viewing rights but without restore rights can still see backup-quality truth on list and detail surfaces while restore actions remain unavailable.
- **SC-004**: In 100% of degraded restore-input scenarios covered by acceptance tests, backup-set and item quality is visible before the operator reaches restore-safety checks or preview generation.

View File

@ -0,0 +1,249 @@
# Tasks: Backup Quality Truth Surfaces
**Input**: Design documents from `/specs/176-backup-quality-truth/`
**Prerequisites**: `plan.md` (required), `spec.md` (required for user stories), `research.md`, `data-model.md`, `contracts/`, `quickstart.md`
**Tests**: Tests are REQUIRED for this feature. Use focused Pest coverage in existing backup, version, restore-selection, and RBAC suites, plus new backup-quality tests under `tests/Feature/Filament/`, `tests/Feature/Rbac/`, and `tests/Unit/Support/BackupQuality/`.
**Operations**: This feature introduces no new `OperationRun`, no queued or scheduled work, and no new audit event family. Work is limited to read-first quality truth on existing backup, version, and restore-selection surfaces.
**RBAC**: Existing tenant membership, capability-registry usage, and `404` vs `403` behavior must remain unchanged across `/admin/t/{tenant}/backup-sets/...`, `/admin/t/{tenant}/policy-versions/...`, and `/admin/t/{tenant}/restore-runs/create`. Users with `TENANT_VIEW` must see backup-quality truth on read surfaces even when restore actions remain unavailable.
**Operator Surfaces**: Backup-set list and detail, backup-items relation rows, policy-version list and detail, and restore wizard step 1 and step 2 must show backup-quality truth before diagnostics or later restore-safety conclusions. Quality copy must remain distinct from lifecycle, restore readiness, and tenant recoverability claims.
**Filament UI Action Surfaces**: No new primary inspect model, redundant View action, or destructive-action placement is introduced. Existing archive, restore, force-delete, remove, and bulk actions remain confirmation-gated and server-authorized.
**Filament UI UX-001**: This feature keeps the existing Filament list, relation-manager, infolist, enterprise-detail, and wizard layouts. New quality sections must be summary-first and diagnostics-second.
**Badges**: Snapshot completeness must continue to use centralized badge semantics through `app/Support/Badges/Domains/PolicySnapshotModeBadge.php`. Any additional quality wording must come from the shared backup-quality layer rather than page-local mappings.
**Organization**: Tasks are grouped by user story so each story can be implemented and validated as an independent increment after the shared backup-quality scaffolding is in place.
## Phase 1: Setup (Shared Backup-Quality Scaffolding)
**Purpose**: Add the narrow derived backup-quality layer and base test scaffolding used by every story.
- [X] T001 Create the shared backup-quality resolver and summary types in `app/Support/BackupQuality/BackupQualityResolver.php` and `app/Support/BackupQuality/BackupQualitySummary.php`
- [X] T002 [P] Add unit test scaffolding for resolver rules and aggregate summaries in `tests/Unit/Support/BackupQuality/BackupQualityResolverTest.php` and `tests/Unit/Support/BackupQuality/BackupSetQualitySummaryTest.php`
- [X] T003 Add metadata convenience helpers for item evidence in `app/Models/BackupItem.php` and mirror them in `app/Models/PolicyVersion.php` only if resolver wiring still leaves justified duplication there
- [X] T004 [P] Extend metadata semantics regression coverage in `tests/Unit/BackupItemTest.php` and `tests/Unit/AssignmentBackupServiceTest.php`
---
## Phase 2: Foundational (Blocking Shared Wiring)
**Purpose**: Wire the shared backup-quality contract into the existing Filament seams before any story-specific surface work begins.
**⚠️ CRITICAL**: No user story work should begin until this phase is complete.
- [X] T005 Thread shared backup-quality loading and aggregation hooks through `app/Filament/Resources/BackupSetResource.php`, `app/Filament/Resources/PolicyVersionResource.php`, and `app/Filament/Resources/RestoreRunResource.php`
- [X] T006 [P] Reuse centralized snapshot-mode and summary copy seams in `app/Support/Badges/Domains/PolicySnapshotModeBadge.php` and `app/Support/BackupQuality/BackupQualitySummary.php`
- [X] T007 [P] Add shared mixed-signal, integrity-warning, and unknown-quality regression coverage in `tests/Unit/Support/BackupQuality/BackupQualityResolverTest.php` and `tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php`
**Checkpoint**: Backup, version, and restore-selection resources can now consume one shared backup-quality contract.
---
## Phase 3: User Story 1 - Judge Backup Sets Early (Priority: P1) 🎯 MVP
**Goal**: Let operators distinguish stored backup sets from degraded recovery input within one scan of the list or detail surface.
**Independent Test**: Load backup-set list and detail pages with full-quality, mixed-quality, and metadata-only fixtures and verify lifecycle truth stays separate from a default-visible quality summary.
### Tests for User Story 1
- [X] T008 [P] [US1] Add backup-set list truth coverage for full, mixed, metadata-only, and archived sets in `tests/Feature/Filament/BackupQualityTruthSurfaceTest.php`
- [X] T009 [P] [US1] Extend summary-first backup-set detail assertions to cover archived parity and integrity-warning counts in `tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php`
### Implementation for User Story 1
- [X] T010 [US1] Add compact backup-quality summary columns and row copy to `app/Filament/Resources/BackupSetResource.php`
- [X] T011 [US1] Add a default-visible quality summary section with integrity-warning counts, next-action guidance, and contextual related links that stay out of the header in `app/Filament/Resources/BackupSetResource.php`
- [X] T012 [US1] Ensure backup-set quality summaries use aggregated item facts without new N+1 queries in `app/Support/BackupQuality/BackupQualityResolver.php` and `app/Filament/Resources/BackupSetResource.php`
- [X] T013 [US1] Run the focused backup-set truth pack in `tests/Feature/Filament/BackupQualityTruthSurfaceTest.php` and `tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php`
**Checkpoint**: Backup-set list and detail now expose input quality early without implying restore safety.
---
## Phase 4: User Story 2 - Inspect Item and Version Strength (Priority: P2)
**Goal**: Make item-level and version-level payload quality explicit instead of forcing operators to infer it from disabled actions or hidden metadata.
**Independent Test**: Load backup-items and policy-versions surfaces with full, metadata-only, assignment-fetch-failed, orphaned-assignment, and not-applicable fixtures and verify each surface renders explicit quality truth at scan speed.
### Tests for User Story 2
- [X] T014 [P] [US2] Extend backup-item relation truth coverage for snapshot mode, assignment failures, orphaned assignments, non-failure capture reasons, and inspect-next-step cues in `tests/Feature/Filament/BackupItemsRelationManagerFiltersTest.php`
- [X] T015 [P] [US2] Add policy-version quality list and detail coverage for full, degraded, integrity-warning, and archived versions in `tests/Feature/Filament/PolicyVersionQualityTruthSurfaceTest.php` and `tests/Feature/Filament/PolicyVersionTest.php`
- [X] T016 [P] [US2] Add regression coverage that quality truth remains visible independently from restore action gating in `tests/Feature/Filament/PolicyVersionRestoreViaWizardTest.php` and `tests/Unit/Support/BackupQuality/BackupQualityResolverTest.php`
### Implementation for User Story 2
- [X] T017 [US2] Add per-item snapshot mode, assignment-quality signals, and inspect-detail next-step cues to `app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php`
- [X] T018 [US2] Add scan-speed snapshot mode, integrity-warning visibility, stronger-version or open-detail cues, and a single empty-state CTA to the table schema in `app/Filament/Resources/PolicyVersionResource.php`
- [X] T019 [US2] Add an explicit backup-quality infolist section with integrity-warning truth and non-overclaiming guidance in `app/Filament/Resources/PolicyVersionResource.php`
- [X] T020 [US2] Remove page-local quality derivation from item and version surfaces by routing them through `app/Support/BackupQuality/BackupQualityResolver.php`, `app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php`, and `app/Filament/Resources/PolicyVersionResource.php`
- [X] T021 [US2] Run the focused item and version truth pack in `tests/Feature/Filament/BackupItemsRelationManagerFiltersTest.php`, `tests/Feature/Filament/PolicyVersionQualityTruthSurfaceTest.php`, `tests/Feature/Filament/PolicyVersionTest.php`, and `tests/Feature/Filament/PolicyVersionRestoreViaWizardTest.php`
**Checkpoint**: Backup items and policy versions now expose quality truth directly where operators inspect them.
---
## Phase 5: User Story 3 - Select Restore Inputs With Early Warning (Priority: P3)
**Goal**: Show weak backup sets and items at the first restore-selection step, before later restore-safety checks or preview work begins.
**Independent Test**: Open the restore wizard with degraded backup-set and backup-item fixtures and verify step 1 and step 2 expose input quality before any risk-check output is shown.
### Tests for User Story 3
- [X] T022 [P] [US3] Add step-1 degraded backup-set hint coverage in `tests/Feature/Filament/RestoreSelectionQualityTruthTest.php`
- [X] T023 [P] [US3] Extend pre-risk-check item-quality assertions in `tests/Feature/Filament/RestoreItemSelectionTest.php` and `tests/Feature/RestoreRiskChecksWizardTest.php`
### Implementation for User Story 3
- [X] T024 [US3] Add backup-set quality summaries to step-1 option labels and helper text in `app/Filament/Resources/RestoreRunResource.php`
- [X] T025 [US3] Add item-level snapshot mode and assignment-quality descriptions to restore item option data in `app/Filament/Resources/RestoreRunResource.php`
- [X] T026 [US3] Preserve the backup-quality versus restore-safety claim boundary in `app/Filament/Resources/RestoreRunResource.php` and `app/Filament/Resources/RestoreRunResource/Pages/CreateRestoreRun.php`
- [X] T027 [US3] Run the focused restore-selection truth pack in `tests/Feature/Filament/RestoreSelectionQualityTruthTest.php`, `tests/Feature/Filament/RestoreItemSelectionTest.php`, and `tests/Feature/RestoreRiskChecksWizardTest.php`
**Checkpoint**: Restore selection now exposes degraded input before later restore-safety logic runs.
---
## Phase 6: User Story 4 - Preserve Truth Under RBAC Boundaries (Priority: P4)
**Goal**: Keep backup-quality truth visible to read-only tenant viewers while preserving existing restore and mutation restrictions plus deny-as-not-found behavior.
**Independent Test**: Sign in as a tenant member with `TENANT_VIEW` but without restore capability and verify backup-set and policy-version surfaces still show quality truth, while non-members still receive `404` and in-scope users without mutation capability still receive `403` on execution.
### Tests for User Story 4
- [X] T028 [P] [US4] Add tenant-view visibility coverage for backup-set, backup-item relation rows, and policy-version quality truth in `tests/Feature/Rbac/BackupQualityVisibilityTest.php`
- [X] T029 [P] [US4] Extend deny-as-not-found and missing-capability regressions for backup and restore entry points in `tests/Feature/Filament/BackupSetUiEnforcementTest.php`, `tests/Feature/Rbac/BackupItemsRelationManagerUiEnforcementTest.php`, `tests/Feature/Rbac/CreateRestoreRunAuthorizationTest.php`, and `tests/Feature/Rbac/PolicyVersionsRestoreToIntuneUiEnforcementTest.php`
### Implementation for User Story 4
- [X] T030 [US4] Adjust quality-section visibility so read surfaces and backup-item relation rows remain available to `TENANT_VIEW` users in `app/Filament/Resources/BackupSetResource.php`, `app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php`, and `app/Filament/Resources/PolicyVersionResource.php`
- [X] T031 [US4] Preserve `404` vs `403` semantics around restore-linked quality hints in `app/Filament/Resources/RestoreRunResource.php` and `app/Filament/Resources/RestoreRunResource/Pages/CreateRestoreRun.php`
- [X] T032 [US4] Run the focused RBAC truth pack in `tests/Feature/Rbac/BackupQualityVisibilityTest.php`, `tests/Feature/Filament/BackupSetUiEnforcementTest.php`, `tests/Feature/Rbac/BackupItemsRelationManagerUiEnforcementTest.php`, `tests/Feature/Rbac/CreateRestoreRunAuthorizationTest.php`, and `tests/Feature/Rbac/PolicyVersionsRestoreToIntuneUiEnforcementTest.php`
**Checkpoint**: Quality truth remains visible under read-only permissions without weakening authorization boundaries.
---
## Phase 7: Polish & Cross-Cutting Concerns
**Purpose**: Final consistency, cleanup, formatting, and focused verification across all stories.
- [X] T033 [P] Review and align operator-facing backup-quality copy and next-action wording in `app/Support/BackupQuality/BackupQualitySummary.php`, `app/Filament/Resources/BackupSetResource.php`, `app/Filament/Resources/PolicyVersionResource.php`, and `app/Filament/Resources/RestoreRunResource.php`
- [X] T034 Remove dead fallback derivation and duplicate helper logic left after story implementation in `app/Support/BackupQuality/BackupQualityResolver.php`, `app/Filament/Resources/BackupSetResource.php`, `app/Filament/Resources/PolicyVersionResource.php`, and `app/Filament/Resources/RestoreRunResource.php`
- [X] T035 Run formatting with `vendor/bin/sail bin pint --dirty --format agent` for `app/Support/BackupQuality/BackupQualityResolver.php`, `app/Filament/Resources/BackupSetResource.php`, `app/Filament/Resources/PolicyVersionResource.php`, `app/Filament/Resources/RestoreRunResource.php`, and `tests/Feature/Filament/BackupQualityTruthSurfaceTest.php`
- [X] T036 Run the focused verification pack from `specs/176-backup-quality-truth/quickstart.md` against `tests/Feature/Filament/BackupQualityTruthSurfaceTest.php`, `tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php`, `tests/Feature/Filament/BackupItemsRelationManagerFiltersTest.php`, `tests/Feature/Filament/BackupSetUiEnforcementTest.php`, `tests/Feature/Filament/PolicyVersionQualityTruthSurfaceTest.php`, `tests/Feature/Filament/PolicyVersionTest.php`, `tests/Feature/Filament/PolicyVersionRestoreViaWizardTest.php`, `tests/Feature/Filament/RestoreSelectionQualityTruthTest.php`, `tests/Feature/Filament/RestoreItemSelectionTest.php`, `tests/Feature/RestoreRiskChecksWizardTest.php`, `tests/Feature/Rbac/BackupQualityVisibilityTest.php`, `tests/Feature/Rbac/BackupItemsRelationManagerUiEnforcementTest.php`, `tests/Feature/Rbac/CreateRestoreRunAuthorizationTest.php`, `tests/Feature/Rbac/PolicyVersionsRestoreToIntuneUiEnforcementTest.php`, `tests/Unit/Support/BackupQuality/BackupQualityResolverTest.php`, `tests/Unit/Support/BackupQuality/BackupSetQualitySummaryTest.php`, `tests/Unit/AssignmentBackupServiceTest.php`, and `tests/Unit/BackupItemTest.php`
- [ ] T037 Run the manual validation pass in `specs/176-backup-quality-truth/quickstart.md` for backup-set, policy-version, restore-selection, and RBAC truth surfaces
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: Starts immediately and establishes the shared backup-quality namespace and test scaffolding.
- **Foundational (Phase 2)**: Depends on Setup and blocks all story work until existing Filament resources consume the shared resolver and summary contract.
- **User Story 1 (Phase 3)**: Starts after Foundational and delivers the MVP truth surface on backup-set list and detail pages.
- **User Story 2 (Phase 4)**: Starts after Foundational and can proceed alongside User Story 1 once the shared resolver contract is stable.
- **User Story 3 (Phase 5)**: Starts after User Story 1 and User Story 2 because restore selection reuses both aggregate backup-set truth and item-level quality facts.
- **User Story 4 (Phase 6)**: Starts after User Story 1 and User Story 2 and should finish after User Story 3 if restore-selection RBAC visibility is included in the same pass.
- **Polish (Phase 7)**: Starts after the desired user stories are complete.
### User Story Dependencies
- **US1**: Depends only on Setup and Foundational work.
- **US2**: Depends only on Setup and Foundational work and shares the same resolver contract as US1.
- **US3**: Depends on US1 and US2 because step 1 and step 2 reuse the backup-set and item-level quality models introduced there.
- **US4**: Depends on US1 and US2 for truth surfaces and should include US3 when restore-wizard visibility checks are part of the same test pass.
### Within Each User Story
- Tests should be added or updated before the corresponding behavior change is considered complete.
- Shared resolver and resource wiring should land before story-specific copy cleanup for the same surface.
- Story-level focused test runs should pass before moving to the next priority slice.
### Parallel Opportunities
- `T002` and `T004` can run in parallel once `T001` and `T003` establish the helper signatures and metadata rules.
- `T006` and `T007` can run in parallel after `T005` lands the shared wiring points.
- `T008` and `T009` can run in parallel for US1.
- `T014`, `T015`, and `T016` can run in parallel for US2.
- `T022` and `T023` can run in parallel for US3.
- `T028` and `T029` can run in parallel for US4.
- `T033` and story-specific cleanup reviews can run in parallel once feature behavior is stable.
---
## Parallel Example: User Story 1
```bash
# Story 1 tests in parallel:
Task: T008 tests/Feature/Filament/BackupQualityTruthSurfaceTest.php
Task: T009 tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php
# Story 1 implementation after assertions are set:
Task: T010 app/Filament/Resources/BackupSetResource.php
Task: T012 app/Support/BackupQuality/BackupQualityResolver.php
```
## Parallel Example: User Story 2
```bash
# Story 2 tests in parallel:
Task: T014 tests/Feature/Filament/BackupItemsRelationManagerFiltersTest.php
Task: T015 tests/Feature/Filament/PolicyVersionQualityTruthSurfaceTest.php
Task: T016 tests/Feature/Filament/PolicyVersionRestoreViaWizardTest.php
# Story 2 implementation split after the resolver contract is fixed:
Task: T017 app/Filament/Resources/BackupSetResource/RelationManagers/BackupItemsRelationManager.php
Task: T018 app/Filament/Resources/PolicyVersionResource.php
```
## Parallel Example: User Story 3
```bash
# Story 3 tests in parallel:
Task: T022 tests/Feature/Filament/RestoreSelectionQualityTruthTest.php
Task: T023 tests/Feature/Filament/RestoreItemSelectionTest.php
# Story 3 implementation split after the selection copy is agreed:
Task: T024 app/Filament/Resources/RestoreRunResource.php
Task: T025 app/Filament/Resources/RestoreRunResource.php
```
## Parallel Example: User Story 4
```bash
# Story 4 tests in parallel:
Task: T028 tests/Feature/Rbac/BackupQualityVisibilityTest.php
Task: T029 tests/Feature/Rbac/CreateRestoreRunAuthorizationTest.php
# Story 4 implementation split after RBAC expectations are locked:
Task: T030 app/Filament/Resources/BackupSetResource.php
Task: T031 app/Filament/Resources/RestoreRunResource/Pages/CreateRestoreRun.php
```
---
## Implementation Strategy
### MVP First
- Complete Phase 1 and Phase 2.
- Deliver User Story 1 as the first usable increment so operators can judge backup-set quality early.
- Validate that lifecycle truth and backup-quality truth are clearly separated on backup-set list and detail surfaces.
### Incremental Delivery
- Add User Story 2 next so item and version strength become explicit everywhere operators inspect backup inputs.
- Add User Story 3 after that so restore selection inherits the same quality truth before risk checks.
- Add User Story 4 last to verify RBAC-safe truth visibility across read and restore-linked surfaces.
### Verification Finish
- Run Pint on touched files.
- Run the focused verification pack from `quickstart.md`.
- Run the manual quickstart validation pass for backup-set, policy-version, restore-selection, and RBAC outcomes.
- Offer the broader test suite only after the focused pack passes.

View File

@ -190,3 +190,45 @@ function backupItemsRelationManagerComponent(BackupSet $backupSet)
->assertSet('tableSort', 'policy.display_name:desc') ->assertSet('tableSort', 'policy.display_name:desc')
->assertSet('tableFilters.policy_type.value', 'intuneRoleDefinition'); ->assertSet('tableFilters.policy_type.value', 'intuneRoleDefinition');
}); });
it('shows snapshot mode and backup quality hints for backup items', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
$tenant->makeCurrent();
Filament::setTenant($tenant, true);
$backupSet = BackupSet::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
]);
$policy = Policy::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'external_id' => 'quality-policy',
'policy_type' => 'settingsCatalogPolicy',
'display_name' => 'Quality Policy',
'platform' => 'windows',
]);
BackupItem::factory()->for($backupSet)->for($tenant)->create([
'policy_id' => (int) $policy->getKey(),
'policy_identifier' => 'quality-policy',
'policy_type' => 'settingsCatalogPolicy',
'platform' => 'windows',
'payload' => [],
'metadata' => [
'displayName' => 'Quality Policy',
'source' => 'metadata_only',
'assignment_capture_reason' => 'separate_role_assignments',
'has_orphaned_assignments' => true,
],
'assignments' => [],
]);
backupItemsRelationManagerComponent($backupSet)
->assertSee('Snapshot')
->assertSee('Backup quality')
->assertSee('Metadata only')
->assertSee('Assignments captured separately')
->assertSee('Orphaned assignments');
});

View File

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
use App\Filament\Resources\BackupSetResource;
use App\Models\BackupItem;
use App\Models\BackupSet;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('shows lifecycle status separately from backup quality on the backup-set list', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$fullSet = BackupSet::factory()->for($tenant)->create([
'name' => 'Full quality set',
'status' => 'completed',
'item_count' => 1,
]);
BackupItem::factory()->for($tenant)->for($fullSet)->create([
'payload' => ['id' => 'policy-full'],
'metadata' => [],
'assignments' => [],
]);
$degradedSet = BackupSet::factory()->for($tenant)->create([
'name' => 'Degraded quality set',
'status' => 'completed',
'item_count' => 2,
]);
BackupItem::factory()->for($tenant)->for($degradedSet)->create([
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
'assignments_fetch_failed' => true,
],
'assignments' => [],
]);
BackupItem::factory()->for($tenant)->for($degradedSet)->create([
'payload' => ['id' => 'policy-warning'],
'metadata' => [
'has_orphaned_assignments' => true,
'integrity_warning' => 'Protected values are intentionally hidden.',
],
'assignments' => [],
]);
$this->get(BackupSetResource::getUrl('index', tenant: $tenant))
->assertOk()
->assertSee('Backup quality')
->assertSee('Full quality set')
->assertSee('No degradations detected across 1 item')
->assertSee('Degraded quality set')
->assertSee('2 degraded items')
->assertSee('1 metadata-only')
->assertSee('1 assignment issue')
->assertSee('Completed');
});

View File

@ -24,6 +24,16 @@
], ],
]); ]);
\App\Models\BackupItem::factory()->for($backupSet)->for($tenant)->create([
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
'assignments_fetch_failed' => true,
'integrity_warning' => 'Protected values are intentionally hidden.',
],
'assignments' => [],
]);
$run = OperationRun::factory()->for($tenant)->create([ $run = OperationRun::factory()->for($tenant)->create([
'workspace_id' => (int) $tenant->workspace_id, 'workspace_id' => (int) $tenant->workspace_id,
'type' => 'backup_set.add_policies', 'type' => 'backup_set.add_policies',
@ -34,14 +44,18 @@
$this->get(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant)) $this->get(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant))
->assertOk() ->assertOk()
->assertSee('Recovery readiness') ->assertSee('Backup quality')
->assertSee('1 degraded item')
->assertSee('1 metadata-only')
->assertSee('1 assignment issue')
->assertSee('1 integrity warning')
->assertSee('Timing') ->assertSee('Timing')
->assertSee('Archive') ->assertSee('Archive')
->assertSee('More') ->assertSee('More')
->assertSee('/admin/operations/'.$run->getKey(), false) ->assertSee('/admin/operations/'.$run->getKey(), false)
->assertDontSee('Related record') ->assertDontSee('Related record')
->assertDontSee('>Completed</span>', false) ->assertDontSee('>Completed</span>', false)
->assertSeeInOrder(['Nightly backup', 'Lifecycle overview', 'Related context', 'Technical detail']); ->assertSeeInOrder(['Nightly backup', 'Backup quality', 'Lifecycle overview', 'Related context', 'Technical detail']);
}); });
it('keeps operations context and technical empty states readable for sparse backup sets', function (): void { it('keeps operations context and technical empty states readable for sparse backup sets', function (): void {
@ -53,13 +67,44 @@
$backupSet = BackupSet::factory()->create([ $backupSet = BackupSet::factory()->create([
'tenant_id' => (int) $tenant->getKey(), 'tenant_id' => (int) $tenant->getKey(),
'name' => 'Sparse backup', 'name' => 'Sparse backup',
'item_count' => 0,
'metadata' => [], 'metadata' => [],
]); ]);
$this->get(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant)) $this->get(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant))
->assertOk() ->assertOk()
->assertSee('Operations') ->assertSee('No items captured')
->assertSee('No backup metadata was recorded for this backup set.') ->assertSee('No backup metadata was recorded for this backup set.')
->assertSee('Metadata keys') ->assertSee('Metadata keys')
->assertDontSee('Related record'); ->assertDontSee('Related record');
}); });
it('keeps backup quality counts visible for archived backup sets', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$backupSet = BackupSet::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'name' => 'Archived backup',
'item_count' => 1,
]);
$item = \App\Models\BackupItem::factory()->for($backupSet)->for($tenant)->create([
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
],
'assignments' => [],
]);
$item->delete();
$backupSet->delete();
$this->get(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant))
->assertOk()
->assertSee('Archived')
->assertSee('1 degraded item')
->assertSee('1 metadata-only');
});

View File

@ -112,3 +112,32 @@ function getTableEmptyStateAction($component, string $name): ?\Filament\Actions\
expect($action->isDisabled())->toBeTrue(); expect($action->isDisabled())->toBeTrue();
expect($action->getTooltip())->toBe(UiTooltips::insufficientPermission()); expect($action->getTooltip())->toBe(UiTooltips::insufficientPermission());
}); });
test('readonly members still see backup quality truth on the backup-set list', function () {
$tenant = Tenant::factory()->create();
[$user] = createUserWithTenant($tenant, role: 'readonly');
$backupSet = BackupSet::factory()->create([
'tenant_id' => $tenant->getKey(),
'status' => 'completed',
'item_count' => 1,
]);
\App\Models\BackupItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'backup_set_id' => $backupSet->getKey(),
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
],
'assignments' => [],
]);
Filament::setTenant($tenant, true);
$this->actingAs($user)
->get(BackupSetResource::getUrl('index', tenant: $tenant))
->assertOk()
->assertSee('Backup quality')
->assertSee('1 metadata-only');
});

View File

@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
use App\Filament\Resources\PolicyVersionResource;
use App\Models\Policy;
use App\Models\PolicyVersion;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('shows snapshot mode and backup quality on the policy-version list', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$policy = Policy::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'display_name' => 'Windows Policy',
'policy_type' => 'settingsCatalogPolicy',
'platform' => 'windows',
]);
PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'version_number' => 1,
'snapshot' => ['id' => 'policy-1'],
'metadata' => [],
]);
PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'version_number' => 2,
'snapshot' => [],
'metadata' => [
'source' => 'metadata_only',
'assignments_fetch_failed' => true,
],
]);
$this->get(PolicyVersionResource::getUrl('index', tenant: $tenant))
->assertOk()
->assertSee('Snapshot')
->assertSee('Backup quality')
->assertSee('Full payload')
->assertSee('Metadata only')
->assertSee('Assignment fetch failed');
});
it('shows explicit backup quality on the policy-version detail page', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$policy = Policy::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'display_name' => 'Versioned policy',
'policy_type' => 'settingsCatalogPolicy',
'platform' => 'windows',
]);
$version = PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'snapshot' => ['id' => 'policy-1'],
'metadata' => [
'has_orphaned_assignments' => true,
],
'secret_fingerprints' => [
'snapshot' => ['/clientSecret' => 'abc123'],
'assignments' => [],
'scope_tags' => [],
],
]);
$this->get(PolicyVersionResource::getUrl('view', ['record' => $version], tenant: $tenant))
->assertOk()
->assertSee('Backup quality')
->assertSee('Orphaned assignments')
->assertSee('Integrity note')
->assertSee('Boundary')
->assertSee('Input quality signals do not prove safe restore');
});

View File

@ -124,12 +124,55 @@
Livewire::test(ListPolicyVersions::class) Livewire::test(ListPolicyVersions::class)
->assertTableActionDisabled('restore_via_wizard', $version) ->assertTableActionDisabled('restore_via_wizard', $version)
->assertSee('Full payload')
->callTableAction('restore_via_wizard', $version); ->callTableAction('restore_via_wizard', $version);
expect(BackupSet::query()->where('metadata->source', 'policy_version')->exists())->toBeFalse(); expect(BackupSet::query()->where('metadata->source', 'policy_version')->exists())->toBeFalse();
expect(BackupItem::query()->exists())->toBeFalse(); expect(BackupItem::query()->exists())->toBeFalse();
}); });
test('metadata-only versions keep quality visible while restore-via-wizard stays disabled', function () {
$tenant = Tenant::create([
'tenant_id' => 'tenant-policy-version-wizard-quality',
'name' => 'Tenant',
'metadata' => [],
]);
$tenant->makeCurrent();
$policy = Policy::create([
'tenant_id' => $tenant->id,
'external_id' => 'policy-quality',
'policy_type' => 'settingsCatalogPolicy',
'display_name' => 'Settings Catalog',
'platform' => 'windows',
]);
$version = PolicyVersion::create([
'tenant_id' => $tenant->id,
'policy_id' => $policy->id,
'version_number' => 1,
'policy_type' => $policy->policy_type,
'platform' => $policy->platform,
'captured_at' => now(),
'snapshot' => [],
'metadata' => [
'source' => 'metadata_only',
],
]);
$user = User::factory()->create(['email' => 'owner@example.com']);
$user->tenants()->syncWithoutDetaching([
$tenant->getKey() => ['role' => 'owner'],
]);
$this->actingAs($user);
Filament::setTenant($tenant, true);
Livewire::test(ListPolicyVersions::class)
->assertSee('Metadata only')
->assertTableActionDisabled('restore_via_wizard', $version);
});
test('restore run wizard can be prefilled from query params for policy version backup set', function () { test('restore run wizard can be prefilled from query params for policy version backup set', function () {
$tenant = Tenant::create([ $tenant = Tenant::create([
'tenant_id' => 'tenant-policy-version-prefill', 'tenant_id' => 'tenant-policy-version-prefill',

View File

@ -32,6 +32,8 @@
->get(route('filament.admin.resources.policy-versions.index', filamentTenantRouteParams($tenant))) ->get(route('filament.admin.resources.policy-versions.index', filamentTenantRouteParams($tenant)))
->assertOk() ->assertOk()
->assertSee('Policy A') ->assertSee('Policy A')
->assertSee('Backup quality')
->assertSee('Full payload')
->assertSee((string) PolicyVersion::max('version_number')); ->assertSee((string) PolicyVersion::max('version_number'));
}); });
@ -78,6 +80,7 @@
->get(\App\Filament\Resources\PolicyVersionResource::getUrl('view', ['record' => $version]).'?tab=normalized-settings&tenant='.(string) $tenant->external_id); ->get(\App\Filament\Resources\PolicyVersionResource::getUrl('view', ['record' => $version]).'?tab=normalized-settings&tenant='.(string) $tenant->external_id);
$response->assertOk(); $response->assertOk();
$response->assertSee('Backup quality');
$response->assertSee('Helpdesk Assignment'); $response->assertSee('Helpdesk Assignment');
$response->assertSee('Role assignment'); $response->assertSee('Role assignment');
$response->assertSee('Policy and Profile Manager (role-1)'); $response->assertSee('Policy and Profile Manager (role-1)');

View File

@ -129,13 +129,15 @@
->reduce(fn (array $carry, array $options): array => $carry + $options, []); ->reduce(fn (array $carry, array $options): array => $carry + $options, []);
expect($flattenedOptions)->toHaveKey($policyItem->id); expect($flattenedOptions)->toHaveKey($policyItem->id);
expect($flattenedOptions[$policyItem->id])->toBe('Policy Display'); expect($flattenedOptions[$policyItem->id])->toContain('Policy Display')
->and($flattenedOptions[$policyItem->id])->toContain('Full payload');
expect($flattenedOptions)->not->toHaveKey($ignoredPolicyItem->id); expect($flattenedOptions)->not->toHaveKey($ignoredPolicyItem->id);
expect($flattenedOptions)->toHaveKey($scopeTagItem->id); expect($flattenedOptions)->toHaveKey($scopeTagItem->id);
expect($flattenedOptions[$scopeTagItem->id])->toBe('Scope Tag Alpha'); expect($flattenedOptions[$scopeTagItem->id])->toContain('Scope Tag Alpha');
expect($flattenedOptions)->toHaveKey($previewOnlyItem->id); expect($flattenedOptions)->toHaveKey($previewOnlyItem->id);
expect($flattenedOptions[$previewOnlyItem->id])->toBe('Conditional Access Policy'); expect($flattenedOptions[$previewOnlyItem->id])->toContain('Conditional Access Policy')
->and($flattenedOptions[$previewOnlyItem->id])->toContain('Full payload');
}); });

View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
use App\Filament\Resources\RestoreRunResource\Pages\CreateRestoreRun;
use App\Models\BackupItem;
use App\Models\BackupSet;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('shows degraded backup-set hints before restore safety checks run', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$backupSet = BackupSet::factory()->for($tenant)->create([
'name' => 'Recovery candidate',
'item_count' => 1,
]);
BackupItem::factory()->for($tenant)->for($backupSet)->create([
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
'assignments_fetch_failed' => true,
],
'assignments' => [],
]);
Livewire::test(CreateRestoreRun::class)
->assertSee('Backup quality is visible here before safety checks run.')
->assertSee('Recovery candidate')
->assertSee('1 degraded item')
->assertSee('Backup quality hints describe input strength only.');
});

View File

@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
use App\Filament\Resources\BackupSetResource;
use App\Filament\Resources\PolicyVersionResource;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\PolicyVersion;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('keeps backup quality visible to readonly tenant members on backup and version surfaces', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'readonly');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$backupSet = BackupSet::factory()->for($tenant)->create([
'name' => 'Readonly backup',
'item_count' => 1,
]);
BackupItem::factory()->for($tenant)->for($backupSet)->create([
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
],
'assignments' => [],
]);
$policy = Policy::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'display_name' => 'Readonly policy',
'policy_type' => 'settingsCatalogPolicy',
'platform' => 'windows',
]);
$version = PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'snapshot' => [],
'metadata' => [
'source' => 'metadata_only',
],
]);
$this->get(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant))
->assertOk()
->assertSee('Backup quality')
->assertSee('Metadata only');
$this->get(PolicyVersionResource::getUrl('view', ['record' => $version], tenant: $tenant))
->assertOk()
->assertSee('Backup quality')
->assertSee('Metadata only');
});

View File

@ -159,3 +159,81 @@
->and(data_get($updated->metadata, 'assignments_fetch_failed'))->toBeFalse() ->and(data_get($updated->metadata, 'assignments_fetch_failed'))->toBeFalse()
->and(data_get($updated->metadata, 'assignments_fetch_error'))->toBeNull(); ->and(data_get($updated->metadata, 'assignments_fetch_error'))->toBeNull();
}); });
it('records orphaned assignment metadata when resolved groups are missing in the tenant', function () {
$tenant = Tenant::factory()->create([
'tenant_id' => 'tenant-123',
'external_id' => 'tenant-123',
]);
ensureDefaultProviderConnection($tenant, 'microsoft');
$backupItem = BackupItem::factory()->create([
'tenant_id' => $tenant->id,
'metadata' => [],
'assignments' => null,
]);
$this->mock(AssignmentFetcher::class, function (MockInterface $mock) {
$mock->shouldReceive('supportsStandardAssignments')
->once()
->with('settingsCatalogPolicy', null)
->andReturnTrue();
$mock->shouldReceive('fetch')
->once()
->andReturn([
[
'id' => 'assignment-1',
'intent' => 'apply',
'target' => [
'@odata.type' => '#microsoft.graph.groupAssignmentTarget',
'groupId' => 'group-123',
],
],
]);
});
$this->mock(GroupResolver::class, function (MockInterface $mock) {
$mock->shouldReceive('resolveGroupIds')
->once()
->andReturn([
'group-123' => [
'id' => 'group-123',
'displayName' => 'Missing Group',
'orphaned' => true,
],
]);
});
$this->mock(AssignmentFilterResolver::class, function (MockInterface $mock) {
$mock->shouldReceive('resolve')
->once()
->with([], \Mockery::type(Tenant::class))
->andReturn([]);
});
$this->mock(ScopeTagResolver::class, function (MockInterface $mock) use ($tenant) {
$mock->shouldReceive('resolve')
->once()
->with(['0'], $tenant)
->andReturn([
['id' => '0', 'displayName' => 'Default'],
]);
});
$updated = app(AssignmentBackupService::class)->enrichWithAssignments(
backupItem: $backupItem,
tenant: $tenant,
policyType: 'settingsCatalogPolicy',
policyId: 'policy-123',
policyPayload: [
'roleScopeTagIds' => ['0'],
],
includeAssignments: true,
);
expect($updated->assignments)->toHaveCount(1)
->and(data_get($updated->metadata, 'assignments_fetch_failed'))->toBeFalse()
->and(data_get($updated->metadata, 'has_orphaned_assignments'))->toBeTrue();
});

View File

@ -139,6 +139,60 @@
expect($backupItem->assignmentsFetchFailed())->toBeFalse(); expect($backupItem->assignmentsFetchFailed())->toBeFalse();
}); });
test('snapshotSource prefers snapshot source metadata when present', function () {
$backupItem = BackupItem::factory()->create([
'metadata' => [
'source' => 'policy_version',
'snapshot_source' => 'metadata_only',
],
]);
expect($backupItem->snapshotSource())->toBe('metadata_only');
});
test('assignmentCaptureReason returns trimmed capture reason metadata', function () {
$backupItem = BackupItem::factory()->create([
'metadata' => [
'assignment_capture_reason' => ' separate_role_assignments ',
],
]);
expect($backupItem->assignmentCaptureReason())->toBe('separate_role_assignments');
});
test('warningMessages filters non-string and empty warning entries', function () {
$backupItem = BackupItem::factory()->create([
'metadata' => [
'warnings' => [' metadata fallback ', '', null, 123],
],
]);
expect($backupItem->warningMessages())->toBe(['metadata fallback']);
});
test('integrityWarning returns trimmed integrity metadata', function () {
$backupItem = BackupItem::factory()->create([
'metadata' => [
'integrity_warning' => ' Protected values are intentionally hidden. ',
],
]);
expect($backupItem->integrityWarning())->toBe('Protected values are intentionally hidden.');
});
test('hasCapturedPayload reflects whether payload data exists', function () {
$emptyPayload = BackupItem::factory()->create([
'payload' => [],
]);
$capturedPayload = BackupItem::factory()->create([
'payload' => ['id' => 'policy-1'],
]);
expect($emptyPayload->hasCapturedPayload())->toBeFalse()
->and($capturedPayload->hasCapturedPayload())->toBeTrue();
});
test('scopeWithAssignments filters items with assignments', function () { test('scopeWithAssignments filters items with assignments', function () {
BackupItem::factory()->create(['assignments' => null]); BackupItem::factory()->create(['assignments' => null]);
BackupItem::factory()->create(['assignments' => []]); BackupItem::factory()->create(['assignments' => []]);

View File

@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
use App\Models\BackupItem;
use App\Models\PolicyVersion;
use App\Support\BackupQuality\BackupQualityResolver;
use App\Support\RedactionIntegrity;
it('derives metadata-only and assignment degradations from backup item metadata', function (): void {
$summary = app(BackupQualityResolver::class)->forBackupItem(new BackupItem([
'payload' => [],
'assignments' => [],
'metadata' => [
'source' => 'metadata_only',
'assignments_fetch_failed' => true,
'has_orphaned_assignments' => true,
'integrity_warning' => 'Protected values are intentionally hidden.',
'assignment_capture_reason' => 'separate_role_assignments',
],
]));
expect($summary->snapshotMode)->toBe('metadata_only')
->and($summary->hasAssignmentIssues)->toBeTrue()
->and($summary->hasOrphanedAssignments)->toBeTrue()
->and($summary->hasIntegrityWarning())->toBeTrue()
->and($summary->degradationFamilies)->toBe([
'metadata_only',
'assignment_capture_issue',
'orphaned_assignments',
'integrity_warning',
])
->and($summary->qualityHighlights)->toContain(
'Metadata only',
'Assignment fetch failed',
'Orphaned assignments',
'Integrity warning',
);
});
it('uses unknown quality only when backup item metadata cannot justify a stronger claim', function (): void {
$resolver = app(BackupQualityResolver::class);
$unknownSummary = $resolver->forBackupItem(new BackupItem([
'payload' => [],
'assignments' => [],
'metadata' => [],
]));
$assignmentIssueSummary = $resolver->forBackupItem(new BackupItem([
'payload' => [],
'assignments' => [],
'metadata' => [
'assignments_fetch_failed' => true,
],
]));
expect($unknownSummary->degradationFamilies)->toBe(['unknown_quality'])
->and($unknownSummary->compactSummary)->toBe('Unknown quality')
->and($assignmentIssueSummary->degradationFamilies)->toBe(['assignment_capture_issue'])
->and($assignmentIssueSummary->qualityHighlights)->not->toContain('Unknown quality');
});
it('derives policy version integrity warnings from existing redaction context', function (): void {
$summary = app(BackupQualityResolver::class)->forPolicyVersion(new PolicyVersion([
'snapshot' => [
'id' => 'policy-1',
'displayName' => 'Policy One',
],
'metadata' => [
'assignments_fetch_failed' => true,
],
'secret_fingerprints' => [
'snapshot' => ['/clientSecret' => 'abc123'],
'assignments' => [],
'scope_tags' => [],
],
]));
expect($summary->snapshotMode)->toBe('full')
->and($summary->hasAssignmentIssues)->toBeTrue()
->and($summary->integrityWarning)->toBe(RedactionIntegrity::protectedValueNote())
->and($summary->degradationFamilies)->toBe([
'assignment_capture_issue',
'integrity_warning',
]);
});

View File

@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Support\BackupQuality\BackupQualityResolver;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
it('renders a clear backup-set summary when no degradations are detected', function (): void {
$backupSet = new BackupSet([
'status' => 'completed',
'item_count' => 2,
]);
$backupSet->setRelation('items', new EloquentCollection([
new BackupItem([
'payload' => ['id' => 'one'],
'metadata' => [],
'assignments' => [],
]),
new BackupItem([
'payload' => ['id' => 'two'],
'metadata' => [],
'assignments' => [],
]),
]));
$summary = app(BackupQualityResolver::class)->summarizeBackupSet($backupSet);
expect($summary->degradedItemCount)->toBe(0)
->and($summary->compactSummary)->toBe('No degradations detected across 2 items')
->and($summary->summaryMessage)->toBe('No degradations were detected across 2 captured items.');
});
it('aggregates degraded backup-set counts from existing item metadata', function (): void {
$backupSet = new BackupSet([
'status' => 'completed',
'item_count' => 3,
]);
$backupSet->setRelation('items', new EloquentCollection([
new BackupItem([
'payload' => ['id' => 'healthy'],
'metadata' => [],
'assignments' => [],
]),
new BackupItem([
'payload' => [],
'metadata' => [
'source' => 'metadata_only',
'assignments_fetch_failed' => true,
],
'assignments' => [],
]),
new BackupItem([
'payload' => ['id' => 'warning'],
'metadata' => [
'has_orphaned_assignments' => true,
'integrity_warning' => 'Protected values are intentionally hidden.',
],
'assignments' => [],
]),
]));
$summary = app(BackupQualityResolver::class)->summarizeBackupSet($backupSet);
expect($summary->degradedItemCount)->toBe(2)
->and($summary->metadataOnlyCount)->toBe(1)
->and($summary->assignmentIssueCount)->toBe(1)
->and($summary->orphanedAssignmentCount)->toBe(1)
->and($summary->integrityWarningCount)->toBe(1)
->and($summary->compactSummary)->toBe('2 degraded items • 1 metadata-only • 1 assignment issue • 1 orphaned assignment • 1 integrity warning')
->and($summary->nextAction)->toBe('Open the backup set detail and inspect degraded items before continuing into restore.');
});