diff --git a/.github/agents/copilot-instructions.md b/.github/agents/copilot-instructions.md index 17a1fa86..69f2046a 100644 --- a/.github/agents/copilot-instructions.md +++ b/.github/agents/copilot-instructions.md @@ -228,6 +228,8 @@ ## Active Technologies - PostgreSQL via existing `operation_runs` plus related `baseline_snapshots`, `evidence_snapshots`, `tenant_reviews`, and `review_packs`; no schema changes planned (220-governance-run-summaries) - PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin panel pages, `Finding`, `FindingResource`, `WorkspaceOverviewBuilder`, `WorkspaceContext`, `WorkspaceCapabilityResolver`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, and `CanonicalNavigationContext` (221-findings-operator-inbox) - PostgreSQL via existing `findings`, `tenants`, `tenant_memberships`, and workspace context session state; no schema changes planned (221-findings-operator-inbox) +- PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin pages/tables/actions/notifications, `Finding`, `FindingResource`, `FindingWorkflowService`, `FindingPolicy`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, `CanonicalNavigationContext`, `WorkspaceContext`, and `UiEnforcement` (222-findings-intake-team-queue) +- PostgreSQL via existing `findings`, `tenants`, `tenant_memberships`, `audit_logs`, and workspace session context; no schema changes planned (222-findings-intake-team-queue) - PHP 8.4.15 (feat/005-bulk-operations) @@ -262,6 +264,7 @@ ## Code Style PHP 8.4.15: Follow standard conventions ## Recent Changes +- 222-findings-intake-team-queue: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin pages/tables/actions/notifications, `Finding`, `FindingResource`, `FindingWorkflowService`, `FindingPolicy`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, `CanonicalNavigationContext`, `WorkspaceContext`, and `UiEnforcement` - 221-findings-operator-inbox: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin panel pages, `Finding`, `FindingResource`, `WorkspaceOverviewBuilder`, `WorkspaceContext`, `WorkspaceCapabilityResolver`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, and `CanonicalNavigationContext` - 220-governance-run-summaries: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament v5, Livewire v4, Pest v4, Laravel Sail, `TenantlessOperationRunViewer`, `OperationRunResource`, `ArtifactTruthPresenter`, `OperatorExplanationBuilder`, `ReasonPresenter`, `OperationUxPresenter`, `SummaryCountsNormalizer`, and the existing enterprise-detail builders - 219-finding-ownership-semantics: Added PHP 8.4.15 / Laravel 12 + Filament v5, Livewire v4.0+, Pest v4, Tailwind CSS v4 diff --git a/apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php b/apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php new file mode 100644 index 00000000..cb1e37a8 --- /dev/null +++ b/apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php @@ -0,0 +1,775 @@ +|null + */ + private ?array $authorizedTenants = null; + + /** + * @var array|null + */ + private ?array $visibleTenants = null; + + private ?Workspace $workspace = null; + + public string $queueView = 'unassigned'; + + public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration + { + return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport) + ->withListRowPrimaryActionLimit(1) + ->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions keep the shared-unassigned scope fixed and expose only a tenant-prefilter clear action when needed.') + ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value) + ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The intake queue keeps Claim finding inline and does not render a secondary More menu on rows.') + ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The intake queue does not expose bulk actions in v1.') + ->satisfy(ActionSurfaceSlot::ListEmptyState, 'Empty state stays calm and offers exactly one recovery CTA per branch.') + ->exempt(ActionSurfaceSlot::DetailHeader, 'Row navigation returns to the existing tenant finding detail page while Claim finding remains the only inline safe shortcut.'); + } + + public function mount(): void + { + $this->queueView = $this->resolveRequestedQueueView(); + $this->authorizePageAccess(); + + app(CanonicalAdminTenantFilterState::class)->sync( + $this->getTableFiltersSessionKey(), + [], + request(), + ); + + $this->applyRequestedTenantPrefilter(); + $this->mountInteractsWithTable(); + $this->normalizeTenantFilterState(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('clear_tenant_filter') + ->label('Clear tenant filter') + ->icon('heroicon-o-x-mark') + ->color('gray') + ->visible(fn (): bool => $this->currentTenantFilterId() !== null) + ->action(fn (): mixed => $this->clearTenantFilter()), + ]; + } + + public function table(Table $table): Table + { + return $table + ->query(fn (): Builder => $this->queueViewQuery()) + ->paginated(TablePaginationProfiles::customPage()) + ->persistFiltersInSession() + ->columns([ + TextColumn::make('tenant.name') + ->label('Tenant'), + TextColumn::make('subject_display_name') + ->label('Finding') + ->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey()) + ->description(fn (Finding $record): ?string => $this->ownerContext($record)) + ->wrap(), + TextColumn::make('severity') + ->badge() + ->formatStateUsing(BadgeRenderer::label(BadgeDomain::FindingSeverity)) + ->color(BadgeRenderer::color(BadgeDomain::FindingSeverity)) + ->icon(BadgeRenderer::icon(BadgeDomain::FindingSeverity)) + ->iconColor(BadgeRenderer::iconColor(BadgeDomain::FindingSeverity)), + TextColumn::make('status') + ->badge() + ->formatStateUsing(BadgeRenderer::label(BadgeDomain::FindingStatus)) + ->color(BadgeRenderer::color(BadgeDomain::FindingStatus)) + ->icon(BadgeRenderer::icon(BadgeDomain::FindingStatus)) + ->iconColor(BadgeRenderer::iconColor(BadgeDomain::FindingStatus)) + ->description(fn (Finding $record): ?string => $this->reopenedCue($record)), + TextColumn::make('due_at') + ->label('Due') + ->dateTime() + ->placeholder('—') + ->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($record->due_at) ?? FindingResource::dueAttentionLabelFor($record)), + TextColumn::make('intake_reason') + ->label('Queue reason') + ->badge() + ->state(fn (Finding $record): string => $this->queueReason($record)) + ->color(fn (Finding $record): string => $this->queueReasonColor($record)), + ]) + ->filters([ + SelectFilter::make('tenant_id') + ->label('Tenant') + ->options(fn (): array => $this->tenantFilterOptions()) + ->searchable(), + ]) + ->actions([ + $this->claimAction(), + ]) + ->bulkActions([]) + ->recordUrl(fn (Finding $record): string => $this->findingDetailUrl($record)) + ->emptyStateHeading(fn (): string => $this->emptyState()['title']) + ->emptyStateDescription(fn (): string => $this->emptyState()['body']) + ->emptyStateIcon(fn (): string => $this->emptyState()['icon']) + ->emptyStateActions($this->emptyStateActions()); + } + + /** + * @return array + */ + public function appliedScope(): array + { + $tenant = $this->filteredTenant(); + $queueView = $this->currentQueueView(); + + return [ + 'workspace_scoped' => true, + 'fixed_scope' => 'visible_unassigned_open_findings_only', + 'queue_view' => $queueView, + 'queue_view_label' => $this->queueViewLabel($queueView), + 'tenant_prefilter_source' => $this->tenantPrefilterSource(), + 'tenant_label' => $tenant?->name, + ]; + } + + /** + * @return array> + */ + public function queueViews(): array + { + $queueView = $this->currentQueueView(); + + return [ + [ + 'key' => 'unassigned', + 'label' => 'Unassigned', + 'fixed' => true, + 'active' => $queueView === 'unassigned', + 'badge_count' => (clone $this->filteredQueueQuery(queueView: 'unassigned', applyOrdering: false))->count(), + 'url' => $this->queueUrl(['view' => null]), + ], + [ + 'key' => 'needs_triage', + 'label' => 'Needs triage', + 'fixed' => true, + 'active' => $queueView === 'needs_triage', + 'badge_count' => (clone $this->filteredQueueQuery(queueView: 'needs_triage', applyOrdering: false))->count(), + 'url' => $this->queueUrl(['view' => 'needs_triage']), + ], + ]; + } + + /** + * @return array{visible_unassigned: int, visible_needs_triage: int, visible_overdue: int} + */ + public function summaryCounts(): array + { + $visibleQuery = $this->filteredQueueQuery(queueView: 'unassigned', applyOrdering: false); + + return [ + 'visible_unassigned' => (clone $visibleQuery)->count(), + 'visible_needs_triage' => (clone $this->filteredQueueQuery(queueView: 'needs_triage', applyOrdering: false))->count(), + 'visible_overdue' => (clone $visibleQuery) + ->whereNotNull('due_at') + ->where('due_at', '<', now()) + ->count(), + ]; + } + + /** + * @return array + */ + public function emptyState(): array + { + if ($this->tenantFilterAloneExcludesRows()) { + return [ + 'title' => 'No intake findings match this tenant scope', + 'body' => 'Your current tenant filter is hiding shared intake work that is still visible elsewhere in this workspace.', + 'icon' => 'heroicon-o-funnel', + 'action_name' => 'clear_tenant_filter_empty', + 'action_label' => 'Clear tenant filter', + 'action_kind' => 'clear_tenant_filter', + ]; + } + + return [ + 'title' => 'Shared intake is clear', + 'body' => 'No visible unassigned findings currently need first routing across your entitled tenants. Open your personal queue if you want to continue with claimed work.', + 'icon' => 'heroicon-o-inbox-stack', + 'action_name' => 'open_my_findings_empty', + 'action_label' => 'Open my findings', + 'action_kind' => 'url', + 'action_url' => MyFindingsInbox::getUrl(panel: 'admin'), + ]; + } + + public function updatedTableFilters(): void + { + $this->normalizeTenantFilterState(); + } + + public function clearTenantFilter(): void + { + $this->removeTableFilter('tenant_id'); + $this->resetTable(); + } + + /** + * @return array + */ + public function visibleTenants(): array + { + if ($this->visibleTenants !== null) { + return $this->visibleTenants; + } + + $user = auth()->user(); + $tenants = $this->authorizedTenants(); + + if (! $user instanceof User || $tenants === []) { + return $this->visibleTenants = []; + } + + $resolver = app(CapabilityResolver::class); + $resolver->primeMemberships( + $user, + array_map(static fn (Tenant $tenant): int => (int) $tenant->getKey(), $tenants), + ); + + return $this->visibleTenants = array_values(array_filter( + $tenants, + fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW), + )); + } + + private function claimAction(): Action + { + return UiEnforcement::forTableAction( + Action::make('claim') + ->label('Claim finding') + ->icon('heroicon-o-user-plus') + ->color('gray') + ->visible(fn (Finding $record): bool => $record->assignee_user_id === null && in_array((string) $record->status, Finding::openStatuses(), true)) + ->requiresConfirmation() + ->modalHeading('Claim finding') + ->modalDescription(function (?Finding $record = null): string { + $findingLabel = $record?->resolvedSubjectDisplayName() ?? ($record instanceof Finding ? 'Finding #'.$record->getKey() : 'this finding'); + $tenantLabel = $record?->tenant?->name ?? 'this tenant'; + + return sprintf( + 'Claim "%s" in %s? It will move into your personal queue, while the accountable owner and lifecycle state stay unchanged.', + $findingLabel, + $tenantLabel, + ); + }) + ->modalSubmitActionLabel('Claim finding') + ->action(function (Finding $record): void { + $tenant = $record->tenant; + $user = auth()->user(); + + if (! $tenant instanceof Tenant) { + throw new NotFoundHttpException; + } + + if (! $user instanceof User) { + abort(403); + } + + try { + $claimedFinding = app(FindingWorkflowService::class)->claim($record, $tenant, $user); + + Notification::make() + ->success() + ->title('Finding claimed') + ->body('The finding left shared intake and is now assigned to you.') + ->actions([ + Action::make('open_my_findings') + ->label('Open my findings') + ->url(MyFindingsInbox::getUrl(panel: 'admin')), + Action::make('open_finding') + ->label('Open finding') + ->url($this->findingDetailUrl($claimedFinding)), + ]) + ->send(); + } catch (ConflictHttpException) { + Notification::make() + ->warning() + ->title('Finding already claimed') + ->body('Another operator claimed this finding first. The intake queue has been refreshed.') + ->send(); + } + + $this->resetTable(); + + if (method_exists($this, 'unmountAction')) { + $this->unmountAction(); + } + }), + fn () => null, + ) + ->preserveVisibility() + ->requireCapability(Capabilities::TENANT_FINDINGS_ASSIGN) + ->tooltip(UiTooltips::INSUFFICIENT_PERMISSION) + ->apply(); + } + + private function authorizePageAccess(): void + { + $user = auth()->user(); + $workspace = $this->workspace(); + + if (! $user instanceof User) { + abort(403); + } + + if (! $workspace instanceof Workspace) { + throw new NotFoundHttpException; + } + + $resolver = app(WorkspaceCapabilityResolver::class); + + if (! $resolver->isMember($user, $workspace)) { + throw new NotFoundHttpException; + } + + if ($this->visibleTenants() === []) { + abort(403); + } + } + + /** + * @return array + */ + private function authorizedTenants(): array + { + if ($this->authorizedTenants !== null) { + return $this->authorizedTenants; + } + + $user = auth()->user(); + $workspace = $this->workspace(); + + if (! $user instanceof User || ! $workspace instanceof Workspace) { + return $this->authorizedTenants = []; + } + + return $this->authorizedTenants = $user->tenants() + ->where('tenants.workspace_id', (int) $workspace->getKey()) + ->where('tenants.status', 'active') + ->orderBy('tenants.name') + ->get(['tenants.id', 'tenants.name', 'tenants.external_id', 'tenants.workspace_id']) + ->all(); + } + + private function workspace(): ?Workspace + { + if ($this->workspace instanceof Workspace) { + return $this->workspace; + } + + $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request()); + + if (! is_int($workspaceId)) { + return null; + } + + return $this->workspace = Workspace::query()->whereKey($workspaceId)->first(); + } + + private function queueBaseQuery(): Builder + { + $workspace = $this->workspace(); + $tenantIds = array_map( + static fn (Tenant $tenant): int => (int) $tenant->getKey(), + $this->visibleTenants(), + ); + + if (! $workspace instanceof Workspace) { + return Finding::query()->whereRaw('1 = 0'); + } + + return Finding::query() + ->with(['tenant', 'ownerUser', 'assigneeUser']) + ->withSubjectDisplayName() + ->where('workspace_id', (int) $workspace->getKey()) + ->whereIn('tenant_id', $tenantIds === [] ? [-1] : $tenantIds) + ->whereNull('assignee_user_id') + ->whereIn('status', Finding::openStatuses()); + } + + private function queueViewQuery(): Builder + { + return $this->filteredQueueQuery(includeTenantFilter: false, queueView: $this->currentQueueView(), applyOrdering: true); + } + + private function filteredQueueQuery( + bool $includeTenantFilter = true, + ?string $queueView = null, + bool $applyOrdering = true, + ): Builder { + $query = $this->queueBaseQuery(); + $resolvedQueueView = $queueView ?? $this->queueView; + + if ($includeTenantFilter && ($tenantId = $this->currentTenantFilterId()) !== null) { + $query->where('tenant_id', $tenantId); + } + + if ($resolvedQueueView === 'needs_triage') { + $query->whereIn('status', [ + Finding::STATUS_NEW, + Finding::STATUS_REOPENED, + ]); + } + + if (! $applyOrdering) { + return $query; + } + + return $query + ->orderByRaw( + "case + when due_at is not null and due_at < ? then 0 + when status = ? then 1 + when status = ? then 2 + else 3 + end asc", + [now(), Finding::STATUS_REOPENED, Finding::STATUS_NEW], + ) + ->orderByRaw('case when due_at is null then 1 else 0 end asc') + ->orderBy('due_at') + ->orderByDesc('id'); + } + + /** + * @return array + */ + private function tenantFilterOptions(): array + { + return collect($this->visibleTenants()) + ->mapWithKeys(static fn (Tenant $tenant): array => [ + (string) $tenant->getKey() => (string) $tenant->name, + ]) + ->all(); + } + + private function applyRequestedTenantPrefilter(): void + { + $requestedTenant = request()->query('tenant'); + + if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) { + return; + } + + foreach ($this->visibleTenants() as $tenant) { + if ((string) $tenant->getKey() !== (string) $requestedTenant && (string) $tenant->external_id !== (string) $requestedTenant) { + continue; + } + + $this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); + $this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); + + return; + } + } + + private function normalizeTenantFilterState(): void + { + $configuredTenantFilter = data_get($this->currentQueueFiltersState(), 'tenant_id.value'); + + if ($configuredTenantFilter === null || $configuredTenantFilter === '') { + return; + } + + if ($this->currentTenantFilterId() !== null) { + return; + } + + $this->removeTableFilter('tenant_id'); + } + + /** + * @return array + */ + private function currentQueueFiltersState(): array + { + $persisted = session()->get($this->getTableFiltersSessionKey(), []); + + return array_replace_recursive( + is_array($persisted) ? $persisted : [], + $this->tableFilters ?? [], + ); + } + + private function currentTenantFilterId(): ?int + { + $tenantFilter = data_get($this->currentQueueFiltersState(), 'tenant_id.value'); + + if (! is_numeric($tenantFilter)) { + return null; + } + + $tenantId = (int) $tenantFilter; + + foreach ($this->visibleTenants() as $tenant) { + if ((int) $tenant->getKey() === $tenantId) { + return $tenantId; + } + } + + return null; + } + + private function filteredTenant(): ?Tenant + { + $tenantId = $this->currentTenantFilterId(); + + if (! is_int($tenantId)) { + return null; + } + + foreach ($this->visibleTenants() as $tenant) { + if ((int) $tenant->getKey() === $tenantId) { + return $tenant; + } + } + + return null; + } + + private function activeVisibleTenant(): ?Tenant + { + $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); + + if (! $activeTenant instanceof Tenant) { + return null; + } + + foreach ($this->visibleTenants() as $tenant) { + if ($tenant->is($activeTenant)) { + return $tenant; + } + } + + return null; + } + + private function tenantPrefilterSource(): string + { + $tenant = $this->filteredTenant(); + + if (! $tenant instanceof Tenant) { + return 'none'; + } + + $activeTenant = $this->activeVisibleTenant(); + + if ($activeTenant instanceof Tenant && $activeTenant->is($tenant)) { + return 'active_tenant_context'; + } + + return 'explicit_filter'; + } + + private function ownerContext(Finding $record): ?string + { + if ($record->owner_user_id === null) { + return null; + } + + return 'Owner: '.FindingResource::accountableOwnerDisplayFor($record); + } + + private function reopenedCue(Finding $record): ?string + { + if ($record->reopened_at === null) { + return null; + } + + return 'Reopened'; + } + + private function queueReason(Finding $record): string + { + return in_array((string) $record->status, [ + Finding::STATUS_NEW, + Finding::STATUS_REOPENED, + ], true) + ? 'Needs triage' + : 'Unassigned'; + } + + private function queueReasonColor(Finding $record): string + { + return $this->queueReason($record) === 'Needs triage' + ? 'warning' + : 'gray'; + } + + private function tenantFilterAloneExcludesRows(): bool + { + if ($this->currentTenantFilterId() === null) { + return false; + } + + if ((clone $this->filteredQueueQuery())->exists()) { + return false; + } + + return (clone $this->filteredQueueQuery(includeTenantFilter: false))->exists(); + } + + private function findingDetailUrl(Finding $record): string + { + $tenant = $record->tenant; + + if (! $tenant instanceof Tenant) { + return '#'; + } + + $url = FindingResource::getUrl('view', ['record' => $record], panel: 'tenant', tenant: $tenant); + + return $this->appendQuery($url, $this->navigationContext()->toQuery()); + } + + private function navigationContext(): CanonicalNavigationContext + { + return new CanonicalNavigationContext( + sourceSurface: 'findings.intake', + canonicalRouteName: static::getRouteName(Filament::getPanel('admin')), + tenantId: $this->currentTenantFilterId(), + backLinkLabel: 'Back to findings intake', + backLinkUrl: $this->queueUrl(), + ); + } + + private function queueUrl(array $overrides = []): string + { + $resolvedTenant = array_key_exists('tenant', $overrides) + ? $overrides['tenant'] + : $this->filteredTenant()?->external_id; + $resolvedView = array_key_exists('view', $overrides) + ? $overrides['view'] + : $this->currentQueueView(); + + return static::getUrl( + panel: 'admin', + parameters: array_filter([ + 'tenant' => is_string($resolvedTenant) && $resolvedTenant !== '' ? $resolvedTenant : null, + 'view' => $resolvedView === 'needs_triage' ? 'needs_triage' : null, + ], static fn (mixed $value): bool => $value !== null && $value !== ''), + ); + } + + private function resolveRequestedQueueView(): string + { + $requestedView = request()->query('view'); + + return $requestedView === 'needs_triage' + ? 'needs_triage' + : 'unassigned'; + } + + private function currentQueueView(): string + { + return $this->queueView === 'needs_triage' + ? 'needs_triage' + : 'unassigned'; + } + + private function queueViewLabel(string $queueView): string + { + return $queueView === 'needs_triage' + ? 'Needs triage' + : 'Unassigned'; + } + + /** + * @return array + */ + private function emptyStateActions(): array + { + $emptyState = $this->emptyState(); + $action = Action::make((string) $emptyState['action_name']) + ->label((string) $emptyState['action_label']) + ->icon('heroicon-o-arrow-right') + ->color('gray'); + + if (($emptyState['action_kind'] ?? null) === 'clear_tenant_filter') { + return [ + $action->action(fn (): mixed => $this->clearTenantFilter()), + ]; + } + + return [ + $action->url((string) $emptyState['action_url']), + ]; + } + + /** + * @param array $query + */ + private function appendQuery(string $url, array $query): string + { + if ($query === []) { + return $url; + } + + return $url.(str_contains($url, '?') ? '&' : '?').http_build_query($query); + } +} diff --git a/apps/platform/app/Filament/Pages/Findings/MyFindingsInbox.php b/apps/platform/app/Filament/Pages/Findings/MyFindingsInbox.php index 264ca077..e2d547cc 100644 --- a/apps/platform/app/Filament/Pages/Findings/MyFindingsInbox.php +++ b/apps/platform/app/Filament/Pages/Findings/MyFindingsInbox.php @@ -74,6 +74,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport) ->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions keep the assigned-to-me scope fixed and expose only a tenant-prefilter clear action when needed.') ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value) + ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The personal findings inbox exposes row click as the only inspect path and does not render a secondary More menu.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The personal findings inbox does not expose bulk actions.') ->satisfy(ActionSurfaceSlot::ListEmptyState, 'The empty state stays calm, explains scope boundaries, and offers exactly one recovery CTA.') ->exempt(ActionSurfaceSlot::DetailHeader, 'Row navigation returns to the existing tenant finding detail page.'); diff --git a/apps/platform/app/Filament/Pages/Operations/TenantlessOperationRunViewer.php b/apps/platform/app/Filament/Pages/Operations/TenantlessOperationRunViewer.php index b1cb71b6..71b4b450 100644 --- a/apps/platform/app/Filament/Pages/Operations/TenantlessOperationRunViewer.php +++ b/apps/platform/app/Filament/Pages/Operations/TenantlessOperationRunViewer.php @@ -246,10 +246,22 @@ public function blockedExecutionBanner(): ?array return null; } + $reasonEnvelope = app(ReasonPresenter::class)->forOperationRun($this->run, 'detail'); + $body = 'This run was blocked before the artifact-producing work could finish. Review the summary below for the dominant blocker and next step.'; + + if ($reasonEnvelope !== null) { + $body = trim(sprintf( + '%s %s %s', + $body, + rtrim($reasonEnvelope->operatorLabel, '.'), + $reasonEnvelope->shortExplanation, + )); + } + return [ 'tone' => 'amber', 'title' => 'Blocked by prerequisite', - 'body' => 'This run was blocked before the artifact-producing work could finish. Review the summary below for the dominant blocker and next step.', + 'body' => $body, ]; } diff --git a/apps/platform/app/Filament/Resources/FindingResource.php b/apps/platform/app/Filament/Resources/FindingResource.php index e065f515..a223f4e0 100644 --- a/apps/platform/app/Filament/Resources/FindingResource.php +++ b/apps/platform/app/Filament/Resources/FindingResource.php @@ -764,7 +764,8 @@ public static function table(Table $table): Table ->dateTime() ->sortable() ->placeholder('—') - ->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($record->due_at) ?? static::dueAttentionLabelFor($record)), + ->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($record->due_at) ?? static::dueAttentionLabelFor($record)) + ->toggleable(isToggledHiddenByDefault: true), Tables\Columns\TextColumn::make('ownerUser.name') ->label('Accountable owner') ->placeholder('—'), @@ -773,7 +774,10 @@ public static function table(Table $table): Table ->placeholder('—'), Tables\Columns\TextColumn::make('subject_external_id')->label('External ID')->toggleable(isToggledHiddenByDefault: true), Tables\Columns\TextColumn::make('scope_key')->label('Scope')->toggleable(isToggledHiddenByDefault: true), - Tables\Columns\TextColumn::make('created_at')->since()->label('Created'), + Tables\Columns\TextColumn::make('created_at') + ->since() + ->label('Created') + ->toggleable(isToggledHiddenByDefault: true), ]) ->filters([ Tables\Filters\Filter::make('open') diff --git a/apps/platform/app/Providers/Filament/AdminPanelProvider.php b/apps/platform/app/Providers/Filament/AdminPanelProvider.php index 52d293f1..4cd16573 100644 --- a/apps/platform/app/Providers/Filament/AdminPanelProvider.php +++ b/apps/platform/app/Providers/Filament/AdminPanelProvider.php @@ -5,6 +5,7 @@ use App\Filament\Pages\Auth\Login; use App\Filament\Pages\ChooseTenant; use App\Filament\Pages\ChooseWorkspace; +use App\Filament\Pages\Findings\FindingsIntakeQueue; use App\Filament\Pages\Findings\MyFindingsInbox; use App\Filament\Pages\InventoryCoverage; use App\Filament\Pages\Monitoring\FindingExceptionsQueue; @@ -177,6 +178,7 @@ public function panel(Panel $panel): Panel InventoryCoverage::class, TenantRequiredPermissions::class, WorkspaceSettings::class, + FindingsIntakeQueue::class, MyFindingsInbox::class, FindingExceptionsQueue::class, ReviewRegister::class, diff --git a/apps/platform/app/Services/Findings/FindingWorkflowService.php b/apps/platform/app/Services/Findings/FindingWorkflowService.php index 10168bc5..21bb0884 100644 --- a/apps/platform/app/Services/Findings/FindingWorkflowService.php +++ b/apps/platform/app/Services/Findings/FindingWorkflowService.php @@ -17,6 +17,7 @@ use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Support\Facades\DB; use InvalidArgumentException; +use Symfony\Component\HttpKernel\Exception\ConflictHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; final class FindingWorkflowService @@ -143,6 +144,53 @@ public function assign( ); } + public function claim(Finding $finding, Tenant $tenant, User $actor): Finding + { + $this->authorize($finding, $tenant, $actor, [Capabilities::TENANT_FINDINGS_ASSIGN]); + + $assigneeUserId = (int) $actor->getKey(); + $ownerUserId = is_numeric($finding->owner_user_id) ? (int) $finding->owner_user_id : null; + $changeClassification = $this->responsibilityChangeClassification( + beforeOwnerUserId: $ownerUserId, + beforeAssigneeUserId: is_numeric($finding->assignee_user_id) ? (int) $finding->assignee_user_id : null, + afterOwnerUserId: $ownerUserId, + afterAssigneeUserId: $assigneeUserId, + ); + $changeSummary = $this->responsibilityChangeSummary( + beforeOwnerUserId: $ownerUserId, + beforeAssigneeUserId: is_numeric($finding->assignee_user_id) ? (int) $finding->assignee_user_id : null, + afterOwnerUserId: $ownerUserId, + afterAssigneeUserId: $assigneeUserId, + ); + + return $this->mutateAndAudit( + finding: $finding, + tenant: $tenant, + actor: $actor, + action: AuditActionId::FindingAssigned, + context: [ + 'metadata' => [ + 'assignee_user_id' => $assigneeUserId, + 'owner_user_id' => $ownerUserId, + 'responsibility_change_classification' => $changeClassification, + 'responsibility_change_summary' => $changeSummary, + 'claim_self_service' => true, + ], + ], + mutate: function (Finding $record) use ($assigneeUserId): void { + if (! in_array((string) $record->status, Finding::openStatuses(), true)) { + throw new ConflictHttpException('Finding is no longer claimable.'); + } + + if ($record->assignee_user_id !== null) { + throw new ConflictHttpException('Finding is already assigned.'); + } + + $record->assignee_user_id = $assigneeUserId; + }, + ); + } + public function responsibilityChangeClassification( ?int $beforeOwnerUserId, ?int $beforeAssigneeUserId, diff --git a/apps/platform/app/Support/Baselines/BaselineCompareStats.php b/apps/platform/app/Support/Baselines/BaselineCompareStats.php index e1ca94e3..9deaa8d5 100644 --- a/apps/platform/app/Support/Baselines/BaselineCompareStats.php +++ b/apps/platform/app/Support/Baselines/BaselineCompareStats.php @@ -94,6 +94,7 @@ public static function forTenant(?Tenant $tenant): self } $assignment = BaselineTenantAssignment::query() + ->with('baselineProfile') ->where('tenant_id', $tenant->getKey()) ->first(); diff --git a/apps/platform/app/Support/Middleware/EnsureFilamentTenantSelected.php b/apps/platform/app/Support/Middleware/EnsureFilamentTenantSelected.php index 50473329..6a2ca4f9 100644 --- a/apps/platform/app/Support/Middleware/EnsureFilamentTenantSelected.php +++ b/apps/platform/app/Support/Middleware/EnsureFilamentTenantSelected.php @@ -76,7 +76,7 @@ public function handle(Request $request, Closure $next): Response return $next($request); } - if ($path === '/admin/findings/my-work') { + if (in_array($path, ['/admin/findings/my-work', '/admin/findings/intake'], true)) { $this->configureNavigationForRequest($panel); return $next($request); @@ -119,7 +119,7 @@ public function handle(Request $request, Closure $next): Response str_starts_with($path, '/admin/w/') || str_starts_with($path, '/admin/workspaces') || str_starts_with($path, '/admin/operations') - || in_array($path, ['/admin', '/admin/choose-workspace', '/admin/choose-tenant', '/admin/no-access', '/admin/alerts', '/admin/audit-log', '/admin/onboarding', '/admin/settings/workspace', '/admin/findings/my-work'], true) + || in_array($path, ['/admin', '/admin/choose-workspace', '/admin/choose-tenant', '/admin/no-access', '/admin/alerts', '/admin/audit-log', '/admin/onboarding', '/admin/settings/workspace', '/admin/findings/my-work', '/admin/findings/intake'], true) ) { $this->configureNavigationForRequest($panel); @@ -261,6 +261,10 @@ private function adminPathRequiresTenantSelection(string $path): bool return false; } + if (str_starts_with($path, '/admin/findings/intake')) { + return false; + } + return preg_match('#^/admin/(inventory|policies|policy-versions|backup-sets|backup-schedules|findings|finding-exceptions)(/|$)#', $path) === 1; } } diff --git a/apps/platform/app/Support/OperationCatalog.php b/apps/platform/app/Support/OperationCatalog.php index fbc0bb72..f99e802b 100644 --- a/apps/platform/app/Support/OperationCatalog.php +++ b/apps/platform/app/Support/OperationCatalog.php @@ -294,6 +294,8 @@ private static function operationAliases(): array new OperationTypeAlias('policy_version.force_delete', 'policy_version.force_delete', 'canonical', true), new OperationTypeAlias('alerts.evaluate', 'alerts.evaluate', 'canonical', true), new OperationTypeAlias('alerts.deliver', 'alerts.deliver', 'canonical', true), + new OperationTypeAlias('baseline.capture', 'baseline.capture', 'canonical', true), + new OperationTypeAlias('baseline.compare', 'baseline.compare', 'canonical', true), new OperationTypeAlias('baseline_capture', 'baseline.capture', 'legacy_alias', true, 'Historical baseline_capture values resolve to baseline.capture.', 'Prefer baseline.capture on canonical read paths.'), new OperationTypeAlias('baseline_compare', 'baseline.compare', 'legacy_alias', true, 'Historical baseline_compare values resolve to baseline.compare.', 'Prefer baseline.compare on canonical read paths.'), new OperationTypeAlias('permission_posture_check', 'permission.posture.check', 'legacy_alias', true, 'Historical permission_posture_check values resolve to permission.posture.check.', 'Prefer dotted permission posture naming on new read paths.'), diff --git a/apps/platform/app/Support/Workspaces/WorkspaceOverviewBuilder.php b/apps/platform/app/Support/Workspaces/WorkspaceOverviewBuilder.php index c63075ab..18699bff 100644 --- a/apps/platform/app/Support/Workspaces/WorkspaceOverviewBuilder.php +++ b/apps/platform/app/Support/Workspaces/WorkspaceOverviewBuilder.php @@ -217,29 +217,26 @@ private function myFindingsSignal(int $workspaceId, Collection $accessibleTenant ->values() ->all(); - $openAssignedCount = $visibleTenantIds === [] - ? 0 - : (int) $this->scopeToVisibleTenants( + $assignedCounts = $visibleTenantIds === [] + ? null + : $this->scopeToVisibleTenants( Finding::query(), $workspaceId, $visibleTenantIds, ) ->where('assignee_user_id', (int) $user->getKey()) ->whereIn('status', Finding::openStatusesForQuery()) - ->count(); + ->selectRaw('count(*) as open_assigned_count') + ->selectRaw('sum(case when due_at is not null and due_at < ? then 1 else 0 end) as overdue_assigned_count', [now()]) + ->first(); - $overdueAssignedCount = $visibleTenantIds === [] - ? 0 - : (int) $this->scopeToVisibleTenants( - Finding::query(), - $workspaceId, - $visibleTenantIds, - ) - ->where('assignee_user_id', (int) $user->getKey()) - ->whereIn('status', Finding::openStatusesForQuery()) - ->whereNotNull('due_at') - ->where('due_at', '<', now()) - ->count(); + $openAssignedCount = is_numeric($assignedCounts?->open_assigned_count) + ? (int) $assignedCounts->open_assigned_count + : 0; + + $overdueAssignedCount = is_numeric($assignedCounts?->overdue_assigned_count) + ? (int) $assignedCounts->overdue_assigned_count + : 0; $isCalm = $openAssignedCount === 0; @@ -1434,10 +1431,9 @@ private function canManageWorkspaces(Workspace $workspace, User $user): bool } $roles = WorkspaceRoleCapabilityMap::rolesWithCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE); + $role = $this->workspaceCapabilityResolver->getRole($user, $workspace); - return $user->workspaceMemberships() - ->whereIn('role', $roles) - ->exists(); + return $role !== null && in_array($role->value, $roles, true); } private function tenantRouteKey(Tenant $tenant): string diff --git a/apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php b/apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php new file mode 100644 index 00000000..456f50b7 --- /dev/null +++ b/apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php @@ -0,0 +1,103 @@ + + @php($scope = $this->appliedScope()) + @php($summary = $this->summaryCounts()) + @php($queueViews = $this->queueViews()) + +
+ +
+
+
+ + Shared unassigned work +
+ +
+

+ Findings intake +

+ +

+ Review visible unassigned open findings across entitled tenants in one queue. Tenant context can narrow the view, but the intake scope stays fixed. +

+
+
+ +
+
+
+ Visible unassigned +
+
+ {{ $summary['visible_unassigned'] }} +
+
+ Visible unassigned intake rows after the current tenant scope. +
+
+ +
+
+ Needs triage +
+
+ {{ $summary['visible_needs_triage'] }} +
+
+ Visible `new` and `reopened` intake rows that still need first routing. +
+
+ +
+
+ Overdue +
+
+ {{ $summary['visible_overdue'] }} +
+
+ Intake rows that are already past due. +
+
+ +
+
+ Applied scope +
+
+ {{ $scope['queue_view_label'] }} +
+
+ @if (($scope['tenant_prefilter_source'] ?? 'none') === 'active_tenant_context') + Tenant prefilter from active context: + {{ $scope['tenant_label'] }} + @elseif (($scope['tenant_prefilter_source'] ?? 'none') === 'explicit_filter') + Tenant filter applied: + {{ $scope['tenant_label'] }} + @else + All visible tenants are currently included. + @endif +
+
+
+ +
+ @foreach ($queueViews as $queueView) + + {{ $queueView['label'] }} + + {{ $queueView['badge_count'] }} + + Fixed + + @endforeach +
+
+
+ + {{ $this->table }} +
+
diff --git a/apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php b/apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php new file mode 100644 index 00000000..dff8301b --- /dev/null +++ b/apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php @@ -0,0 +1,138 @@ +create(); + + $workspaceA = Workspace::factory()->create(); + $workspaceB = Workspace::factory()->create(); + + WorkspaceMembership::factory()->create([ + 'workspace_id' => (int) $workspaceA->getKey(), + 'user_id' => (int) $user->getKey(), + 'role' => 'owner', + ]); + + WorkspaceMembership::factory()->create([ + 'workspace_id' => (int) $workspaceB->getKey(), + 'user_id' => (int) $user->getKey(), + 'role' => 'owner', + ]); + + $this->actingAs($user) + ->get(FindingsIntakeQueue::getUrl(panel: 'admin')) + ->assertRedirect('/admin/choose-workspace'); +}); + +it('returns 404 for users outside the active workspace on the intake route', function (): void { + $user = User::factory()->create(); + $workspace = Workspace::factory()->create(); + + WorkspaceMembership::factory()->create([ + 'workspace_id' => (int) Workspace::factory()->create()->getKey(), + 'user_id' => (int) $user->getKey(), + 'role' => 'owner', + ]); + + $this->actingAs($user) + ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()]) + ->get(FindingsIntakeQueue::getUrl(panel: 'admin')) + ->assertNotFound(); +}); + +it('returns 403 for workspace members with no currently viewable findings scope anywhere', function (): void { + $user = User::factory()->create(); + $workspace = Workspace::factory()->create(); + + WorkspaceMembership::factory()->create([ + 'workspace_id' => (int) $workspace->getKey(), + 'user_id' => (int) $user->getKey(), + 'role' => 'owner', + ]); + + Tenant::factory()->create([ + 'workspace_id' => (int) $workspace->getKey(), + 'status' => 'active', + ]); + + $this->actingAs($user) + ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()]) + ->get(FindingsIntakeQueue::getUrl(panel: 'admin')) + ->assertForbidden(); +}); + +it('suppresses hidden-tenant findings and keeps their detail route not found', function (): void { + $visibleTenant = Tenant::factory()->create(['status' => 'active']); + [$user, $visibleTenant] = createUserWithTenant($visibleTenant, role: 'readonly', workspaceRole: 'readonly'); + + $hiddenTenant = Tenant::factory()->create([ + 'status' => 'active', + 'workspace_id' => (int) $visibleTenant->workspace_id, + ]); + + $visibleFinding = Finding::factory()->for($visibleTenant)->create([ + 'workspace_id' => (int) $visibleTenant->workspace_id, + 'status' => Finding::STATUS_TRIAGED, + 'assignee_user_id' => null, + ]); + + $hiddenFinding = Finding::factory()->for($hiddenTenant)->create([ + 'workspace_id' => (int) $hiddenTenant->workspace_id, + 'status' => Finding::STATUS_NEW, + 'assignee_user_id' => null, + ]); + + $this->actingAs($user); + setAdminPanelContext(); + session()->put(WorkspaceContext::SESSION_KEY, (int) $visibleTenant->workspace_id); + + Livewire::actingAs($user) + ->test(FindingsIntakeQueue::class) + ->assertCanSeeTableRecords([$visibleFinding]) + ->assertCanNotSeeTableRecords([$hiddenFinding]); + + $this->actingAs($user) + ->withSession([WorkspaceContext::SESSION_KEY => (int) $visibleTenant->workspace_id]) + ->get(FindingResource::getUrl('view', ['record' => $hiddenFinding], panel: 'tenant', tenant: $hiddenTenant)) + ->assertNotFound(); +}); + +it('keeps inspect access while disabling claim for members without assign capability', function (): void { + $tenant = Tenant::factory()->create(['status' => 'active']); + [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly', workspaceRole: 'readonly'); + + $finding = Finding::factory()->for($tenant)->create([ + 'workspace_id' => (int) $tenant->workspace_id, + 'status' => Finding::STATUS_NEW, + 'assignee_user_id' => null, + ]); + + $this->actingAs($user); + setAdminPanelContext(); + session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id); + + Livewire::actingAs($user) + ->test(FindingsIntakeQueue::class) + ->assertCanSeeTableRecords([$finding]) + ->assertTableActionVisible('claim', $finding) + ->assertTableActionDisabled('claim', $finding) + ->callTableAction('claim', $finding); + + expect($finding->refresh()->assignee_user_id)->toBeNull(); + + $this->actingAs($user) + ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) + ->get(FindingResource::getUrl('view', ['record' => $finding], panel: 'tenant', tenant: $tenant)) + ->assertOk(); +}); diff --git a/apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php b/apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php new file mode 100644 index 00000000..173d4d89 --- /dev/null +++ b/apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php @@ -0,0 +1,104 @@ +create(['status' => 'active']); + [$user, $tenant] = createUserWithTenant($tenant, role: 'manager', workspaceRole: 'manager'); + + $owner = User::factory()->create(); + createUserWithTenant($tenant, $owner, role: 'owner', workspaceRole: 'manager'); + + $finding = Finding::factory()->reopened()->for($tenant)->create([ + 'workspace_id' => (int) $tenant->workspace_id, + 'owner_user_id' => (int) $owner->getKey(), + 'assignee_user_id' => null, + 'subject_external_id' => 'claimable', + ]); + + $this->actingAs($user); + setAdminPanelContext(); + session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id); + + Livewire::actingAs($user) + ->test(FindingsIntakeQueue::class) + ->assertTableActionVisible('claim', $finding) + ->mountTableAction('claim', $finding) + ->callMountedTableAction() + ->assertCanNotSeeTableRecords([$finding]); + + $finding->refresh(); + + expect((int) $finding->assignee_user_id)->toBe((int) $user->getKey()) + ->and((int) $finding->owner_user_id)->toBe((int) $owner->getKey()) + ->and($finding->status)->toBe(Finding::STATUS_REOPENED); + + $audit = AuditLog::query() + ->where('tenant_id', (int) $tenant->getKey()) + ->where('resource_type', 'finding') + ->where('resource_id', (string) $finding->getKey()) + ->where('action', AuditActionId::FindingAssigned->value) + ->latest('id') + ->first(); + + expect($audit)->not->toBeNull() + ->and(data_get($audit?->metadata ?? [], 'assignee_user_id'))->toBe((int) $user->getKey()) + ->and(data_get($audit?->metadata ?? [], 'owner_user_id'))->toBe((int) $owner->getKey()); + + Livewire::actingAs($user) + ->test(MyFindingsInbox::class) + ->assertCanSeeTableRecords([$finding]); +}); + +it('refuses a stale claim after another operator already claimed the finding first', function (): void { + $tenant = Tenant::factory()->create(['status' => 'active']); + [$operatorA, $tenant] = createUserWithTenant($tenant, role: 'manager', workspaceRole: 'manager'); + + $operatorB = User::factory()->create(); + createUserWithTenant($tenant, $operatorB, role: 'manager', workspaceRole: 'manager'); + + $finding = Finding::factory()->for($tenant)->create([ + 'workspace_id' => (int) $tenant->workspace_id, + 'status' => Finding::STATUS_NEW, + 'assignee_user_id' => null, + ]); + + $this->actingAs($operatorA); + setAdminPanelContext(); + session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id); + + $component = Livewire::actingAs($operatorA) + ->test(FindingsIntakeQueue::class) + ->mountTableAction('claim', $finding); + + app(FindingWorkflowService::class)->claim($finding, $tenant, $operatorB); + + $component + ->callMountedTableAction(); + + expect((int) $finding->refresh()->assignee_user_id)->toBe((int) $operatorB->getKey()); + + Livewire::actingAs($operatorA) + ->test(FindingsIntakeQueue::class) + ->assertCanNotSeeTableRecords([$finding]); + + expect( + AuditLog::query() + ->where('tenant_id', (int) $tenant->getKey()) + ->where('resource_type', 'finding') + ->where('resource_id', (string) $finding->getKey()) + ->where('action', AuditActionId::FindingAssigned->value) + ->count() + )->toBe(1); +}); diff --git a/apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php b/apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php new file mode 100644 index 00000000..6ed71893 --- /dev/null +++ b/apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php @@ -0,0 +1,347 @@ +create(['status' => 'active']); + [$user, $tenant] = createUserWithTenant($tenant, role: $role, workspaceRole: $workspaceRole); + + test()->actingAs($user); + setAdminPanelContext(); + session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id); + + return [$user, $tenant]; +} + +function findingsIntakePage(?User $user = null, array $query = []) +{ + if ($user instanceof User) { + test()->actingAs($user); + } + + setAdminPanelContext(); + + $factory = $query === [] + ? Livewire::actingAs(auth()->user()) + : Livewire::withQueryParams($query)->actingAs(auth()->user()); + + return $factory->test(FindingsIntakeQueue::class); +} + +function makeIntakeFinding(Tenant $tenant, array $attributes = []): Finding +{ + return Finding::factory()->for($tenant)->create(array_merge([ + 'workspace_id' => (int) $tenant->workspace_id, + 'status' => Finding::STATUS_TRIAGED, + 'assignee_user_id' => null, + 'owner_user_id' => null, + 'subject_external_id' => fake()->uuid(), + ], $attributes)); +} + +it('shows only visible unassigned open findings and exposes fixed queue view counts', function (): void { + [$user, $tenantA] = findingsIntakeActingUser(); + $tenantA->forceFill(['name' => 'Alpha Tenant'])->save(); + + $tenantB = Tenant::factory()->create([ + 'status' => 'active', + 'workspace_id' => (int) $tenantA->workspace_id, + 'name' => 'Tenant Bravo', + ]); + createUserWithTenant($tenantB, $user, role: 'readonly', workspaceRole: 'readonly'); + + $hiddenTenant = Tenant::factory()->create([ + 'status' => 'active', + 'workspace_id' => (int) $tenantA->workspace_id, + 'name' => 'Hidden Tenant', + ]); + + $otherAssignee = User::factory()->create(); + createUserWithTenant($tenantA, $otherAssignee, role: 'operator', workspaceRole: 'readonly'); + + $otherOwner = User::factory()->create(); + createUserWithTenant($tenantB, $otherOwner, role: 'owner', workspaceRole: 'readonly'); + + $visibleNew = makeIntakeFinding($tenantA, [ + 'subject_external_id' => 'visible-new', + 'severity' => Finding::SEVERITY_HIGH, + 'status' => Finding::STATUS_NEW, + ]); + + $visibleReopened = makeIntakeFinding($tenantB, [ + 'subject_external_id' => 'visible-reopened', + 'status' => Finding::STATUS_REOPENED, + 'reopened_at' => now()->subHours(6), + 'owner_user_id' => (int) $otherOwner->getKey(), + ]); + + $visibleTriaged = makeIntakeFinding($tenantA, [ + 'subject_external_id' => 'visible-triaged', + 'status' => Finding::STATUS_TRIAGED, + ]); + + $visibleInProgress = makeIntakeFinding($tenantB, [ + 'subject_external_id' => 'visible-progress', + 'status' => Finding::STATUS_IN_PROGRESS, + 'due_at' => now()->subDay(), + ]); + + $assignedOpen = makeIntakeFinding($tenantA, [ + 'subject_external_id' => 'assigned-open', + 'assignee_user_id' => (int) $otherAssignee->getKey(), + ]); + + $acknowledged = Finding::factory()->for($tenantA)->acknowledged()->create([ + 'workspace_id' => (int) $tenantA->workspace_id, + 'assignee_user_id' => null, + 'subject_external_id' => 'acknowledged', + ]); + + $terminal = Finding::factory()->for($tenantA)->resolved()->create([ + 'workspace_id' => (int) $tenantA->workspace_id, + 'assignee_user_id' => null, + 'subject_external_id' => 'terminal', + ]); + + $hidden = makeIntakeFinding($hiddenTenant, [ + 'subject_external_id' => 'hidden-intake', + ]); + + $component = findingsIntakePage($user) + ->assertCanSeeTableRecords([$visibleNew, $visibleReopened, $visibleTriaged, $visibleInProgress]) + ->assertCanNotSeeTableRecords([$assignedOpen, $acknowledged, $terminal, $hidden]) + ->assertSee('Owner: '.$otherOwner->name) + ->assertSee('Needs triage') + ->assertSee('Unassigned'); + + expect($component->instance()->summaryCounts())->toBe([ + 'visible_unassigned' => 4, + 'visible_needs_triage' => 2, + 'visible_overdue' => 1, + ]); + + $queueViews = collect($component->instance()->queueViews())->keyBy('key'); + + expect($queueViews['unassigned']['badge_count'])->toBe(4) + ->and($queueViews['unassigned']['active'])->toBeTrue() + ->and($queueViews['needs_triage']['badge_count'])->toBe(2) + ->and($queueViews['needs_triage']['active'])->toBeFalse(); +}); + +it('defaults to the active tenant prefilter and lets the operator clear it without dropping intake scope', function (): void { + [$user, $tenantA] = findingsIntakeActingUser(); + + $tenantB = Tenant::factory()->create([ + 'status' => 'active', + 'workspace_id' => (int) $tenantA->workspace_id, + 'name' => 'Beta Tenant', + ]); + createUserWithTenant($tenantB, $user, role: 'readonly', workspaceRole: 'readonly'); + + $findingA = makeIntakeFinding($tenantA, [ + 'subject_external_id' => 'tenant-a', + 'status' => Finding::STATUS_NEW, + ]); + $findingB = makeIntakeFinding($tenantB, [ + 'subject_external_id' => 'tenant-b', + 'status' => Finding::STATUS_TRIAGED, + ]); + + session()->put(WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY, [ + (string) $tenantA->workspace_id => (int) $tenantB->getKey(), + ]); + + $component = findingsIntakePage($user) + ->assertSet('tableFilters.tenant_id.value', (string) $tenantB->getKey()) + ->assertCanSeeTableRecords([$findingB]) + ->assertCanNotSeeTableRecords([$findingA]) + ->assertActionVisible('clear_tenant_filter'); + + expect($component->instance()->appliedScope())->toBe([ + 'workspace_scoped' => true, + 'fixed_scope' => 'visible_unassigned_open_findings_only', + 'queue_view' => 'unassigned', + 'queue_view_label' => 'Unassigned', + 'tenant_prefilter_source' => 'active_tenant_context', + 'tenant_label' => $tenantB->name, + ]); + + $component->callAction('clear_tenant_filter') + ->assertCanSeeTableRecords([$findingA, $findingB]); + + expect($component->instance()->appliedScope())->toBe([ + 'workspace_scoped' => true, + 'fixed_scope' => 'visible_unassigned_open_findings_only', + 'queue_view' => 'unassigned', + 'queue_view_label' => 'Unassigned', + 'tenant_prefilter_source' => 'none', + 'tenant_label' => null, + ]); +}); + +it('keeps the needs triage view active when clearing the tenant prefilter', function (): void { + [$user, $tenantA] = findingsIntakeActingUser(); + + $tenantB = Tenant::factory()->create([ + 'status' => 'active', + 'workspace_id' => (int) $tenantA->workspace_id, + 'name' => 'Beta Tenant', + ]); + createUserWithTenant($tenantB, $user, role: 'readonly', workspaceRole: 'readonly'); + + $tenantATriage = makeIntakeFinding($tenantA, [ + 'subject_external_id' => 'tenant-a-triage', + 'status' => Finding::STATUS_NEW, + ]); + $tenantBTriage = makeIntakeFinding($tenantB, [ + 'subject_external_id' => 'tenant-b-triage', + 'status' => Finding::STATUS_REOPENED, + 'reopened_at' => now()->subHour(), + ]); + $tenantBBacklog = makeIntakeFinding($tenantB, [ + 'subject_external_id' => 'tenant-b-backlog', + 'status' => Finding::STATUS_TRIAGED, + ]); + + session()->put(WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY, [ + (string) $tenantA->workspace_id => (int) $tenantB->getKey(), + ]); + + $component = findingsIntakePage($user, ['view' => 'needs_triage']) + ->assertSet('tableFilters.tenant_id.value', (string) $tenantB->getKey()) + ->assertCanSeeTableRecords([$tenantBTriage]) + ->assertCanNotSeeTableRecords([$tenantATriage, $tenantBBacklog]); + + expect($component->instance()->appliedScope())->toBe([ + 'workspace_scoped' => true, + 'fixed_scope' => 'visible_unassigned_open_findings_only', + 'queue_view' => 'needs_triage', + 'queue_view_label' => 'Needs triage', + 'tenant_prefilter_source' => 'active_tenant_context', + 'tenant_label' => $tenantB->name, + ]); + + $component->callAction('clear_tenant_filter') + ->assertCanSeeTableRecords([$tenantBTriage, $tenantATriage], inOrder: true) + ->assertCanNotSeeTableRecords([$tenantBBacklog]); + + expect($component->instance()->appliedScope())->toBe([ + 'workspace_scoped' => true, + 'fixed_scope' => 'visible_unassigned_open_findings_only', + 'queue_view' => 'needs_triage', + 'queue_view_label' => 'Needs triage', + 'tenant_prefilter_source' => 'none', + 'tenant_label' => null, + ]); + + $queueViews = collect($component->instance()->queueViews())->keyBy('key'); + + expect($queueViews['unassigned']['active'])->toBeFalse() + ->and($queueViews['needs_triage']['active'])->toBeTrue(); +}); + +it('separates needs triage from the remaining backlog and keeps deterministic urgency ordering', function (): void { + [$user, $tenant] = findingsIntakeActingUser(); + + $overdue = makeIntakeFinding($tenant, [ + 'subject_external_id' => 'overdue', + 'status' => Finding::STATUS_TRIAGED, + 'due_at' => now()->subDay(), + ]); + + $reopened = makeIntakeFinding($tenant, [ + 'subject_external_id' => 'reopened', + 'status' => Finding::STATUS_REOPENED, + 'reopened_at' => now()->subHours(2), + 'due_at' => now()->addDay(), + ]); + + $newFinding = makeIntakeFinding($tenant, [ + 'subject_external_id' => 'new-finding', + 'status' => Finding::STATUS_NEW, + 'due_at' => now()->addDays(2), + ]); + + $remainingBacklog = makeIntakeFinding($tenant, [ + 'subject_external_id' => 'remaining-backlog', + 'status' => Finding::STATUS_TRIAGED, + 'due_at' => now()->addHours(12), + ]); + + $undatedBacklog = makeIntakeFinding($tenant, [ + 'subject_external_id' => 'undated-backlog', + 'status' => Finding::STATUS_IN_PROGRESS, + 'due_at' => null, + ]); + + findingsIntakePage($user) + ->assertCanSeeTableRecords([$overdue, $reopened, $newFinding, $remainingBacklog, $undatedBacklog], inOrder: true); + + findingsIntakePage($user, ['view' => 'needs_triage']) + ->assertCanSeeTableRecords([$reopened, $newFinding], inOrder: true) + ->assertCanNotSeeTableRecords([$overdue, $remainingBacklog, $undatedBacklog]); +}); + +it('builds tenant detail drilldowns with intake continuity', function (): void { + [$user, $tenant] = findingsIntakeActingUser(); + + $finding = makeIntakeFinding($tenant, [ + 'subject_external_id' => 'continuity', + 'status' => Finding::STATUS_NEW, + ]); + + $component = findingsIntakePage($user, [ + 'tenant' => (string) $tenant->external_id, + 'view' => 'needs_triage', + ]); + + $detailUrl = $component->instance()->getTable()->getRecordUrl($finding); + + expect($detailUrl)->toContain(FindingResource::getUrl('view', ['record' => $finding], panel: 'tenant', tenant: $tenant)) + ->and($detailUrl)->toContain('nav%5Bback_label%5D=Back+to+findings+intake'); + + $this->actingAs($user) + ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) + ->get($detailUrl) + ->assertOk() + ->assertSee('Back to findings intake'); +}); + +it('renders both intake empty-state branches with the correct single recovery action', function (): void { + [$user, $tenantA] = findingsIntakeActingUser(); + + $tenantB = Tenant::factory()->create([ + 'status' => 'active', + 'workspace_id' => (int) $tenantA->workspace_id, + 'name' => 'Work Tenant', + ]); + createUserWithTenant($tenantB, $user, role: 'readonly', workspaceRole: 'readonly'); + + makeIntakeFinding($tenantB, [ + 'subject_external_id' => 'available-elsewhere', + ]); + + findingsIntakePage($user, [ + 'tenant' => (string) $tenantA->external_id, + ]) + ->assertSee('No intake findings match this tenant scope') + ->assertTableEmptyStateActionsExistInOrder(['clear_tenant_filter_empty']); + + Finding::query()->delete(); + session()->forget(WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY); + Filament::setTenant(null, true); + + findingsIntakePage($user) + ->assertSee('Shared intake is clear') + ->assertTableEmptyStateActionsExistInOrder(['open_my_findings_empty']); +}); diff --git a/docs/product/spec-candidates.md b/docs/product/spec-candidates.md index d905d288..f8fc7e6d 100644 --- a/docs/product/spec-candidates.md +++ b/docs/product/spec-candidates.md @@ -45,6 +45,7 @@ ## Promoted to Spec - Finding Ownership Semantics Clarification → Spec 219 (`finding-ownership-semantics`) - Humanized Diagnostic Summaries for Governance Operations → Spec 220 (`governance-run-summaries`) - Findings Operator Inbox v1 → Spec 221 (`findings-operator-inbox`) +- Findings Intake & Team Queue v1 -> Spec 222 (`findings-intake-team-queue`) - Provider-Backed Action Preflight and Dispatch Gate Unification → Spec 216 (`provider-dispatch-gate`) - Record Page Header Discipline & Contextual Navigation → Spec 192 (`record-header-discipline`) - Monitoring Surface Action Hierarchy & Workbench Semantics → Spec 193 (`monitoring-action-hierarchy`) @@ -360,18 +361,6 @@ ### Tenant Operational Readiness & Status Truth Hierarchy > Findings execution layer cluster: complementary to existing Spec 154 (`finding-risk-acceptance`). Keep these split so prioritization can pull workflow semantics, operator work surfaces, alerts, external handoff, and later portfolio operating slices independently instead of collapsing them into one oversized "Findings v2" spec. -### Findings Intake & Team Queue v1 -- **Type**: workflow execution / team operations -- **Source**: findings execution layer candidate pack 2026-04-17; missing intake surface before personal assignment -- **Problem**: A personal inbox does not solve how new or unassigned findings enter the workflow. Operators need an intake surface before work is personally assigned. -- **Why it matters**: Without intake, backlog triage stays hidden in general-purpose lists and unassigned work becomes easy to ignore or duplicate. -- **Proposed direction**: Introduce unassigned and needs-triage views, an optional claim action, and basic shared-worklist conventions; use filters or tabs that clearly separate intake from active execution; make the difference between unowned backlog and personally assigned work explicit. -- **Explicit non-goals**: Full team model, capacity planning, auto-routing, and load-balancing logic. -- **Dependencies**: Ownership semantics, findings filters/tabs, open-status definitions. -- **Roadmap fit**: Findings Workflow v2; prerequisite for a broader team operating model. -- **Strategic sequencing**: Third, after personal inbox foundations exist. -- **Priority**: high - ### Findings Notifications & Escalation v1 - **Type**: alerts / workflow execution - **Source**: findings execution layer candidate pack 2026-04-17; gap between assignment metadata and actionable control loop diff --git a/specs/222-findings-intake-team-queue/checklists/requirements.md b/specs/222-findings-intake-team-queue/checklists/requirements.md new file mode 100644 index 00000000..9640f1d1 --- /dev/null +++ b/specs/222-findings-intake-team-queue/checklists/requirements.md @@ -0,0 +1,36 @@ +# Specification Quality Checklist: Findings Intake & Team Queue V1 + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-04-21 +**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 + +- Validation passed on 2026-04-21 in the first review iteration. +- The repository template requires route, authorization, and surface-contract metadata; the spec still avoids code-level implementation, language, and architecture detail beyond those mandatory contract fields. +- No clarification markers remain, so the spec is ready for `/speckit.plan`. \ No newline at end of file diff --git a/specs/222-findings-intake-team-queue/contracts/findings-intake-team-queue.logical.openapi.yaml b/specs/222-findings-intake-team-queue/contracts/findings-intake-team-queue.logical.openapi.yaml new file mode 100644 index 00000000..f263608c --- /dev/null +++ b/specs/222-findings-intake-team-queue/contracts/findings-intake-team-queue.logical.openapi.yaml @@ -0,0 +1,470 @@ +openapi: 3.1.0 +info: + title: Findings Intake & Team Queue Surface Contract + version: 1.1.0 + description: >- + Internal reference contract for the canonical Findings intake queue, + the narrow Claim finding shortcut, and intake continuity into tenant + finding detail and My Findings. The application continues to return + rendered HTML through Filament and Livewire. The vendor media types + below document the structured page and action models that must be + derivable before rendering. This is not a public API commitment. +paths: + /admin/findings/intake: + get: + summary: Canonical shared findings intake queue + description: >- + Returns the rendered admin-plane intake queue for visible unassigned + findings in the current workspace. The page always keeps the fixed + intake scope and may apply an active-tenant prefilter. Queue views are + limited to Unassigned and Needs triage. + responses: + '302': + description: Redirects into the existing workspace chooser flow when workspace context is not yet established + '200': + description: Rendered Findings intake page + content: + text/html: + schema: + type: string + application/vnd.tenantpilot.findings-intake+json: + schema: + $ref: '#/components/schemas/FindingsIntakePage' + '403': + description: Workspace membership exists but no currently viewable findings scope exists for intake disclosure anywhere in the workspace + '404': + description: Workspace scope is not visible because membership is missing or out of scope + /admin/findings/intake/{finding}/claim: + post: + summary: Claim a visible intake finding into personal execution + description: >- + Logical contract for the Livewire-backed Claim finding row action after + the operator has reviewed the lightweight preview/confirmation content. + The server must re-check entitlement, assign capability, and current + assignee under lock before mutating the record. + parameters: + - name: finding + in: path + required: true + schema: + type: integer + responses: + '200': + description: Claim succeeded and the finding left intake + content: + application/vnd.tenantpilot.findings-intake-claim+json: + schema: + $ref: '#/components/schemas/ClaimFindingResult' + '403': + description: Viewer is in scope but lacks the existing findings assign capability + '404': + description: Workspace or tenant scope is not visible for the referenced finding + '409': + description: The row is no longer claimable because another operator claimed it first or it otherwise left intake scope before mutation + /admin/t/{tenant}/findings/{finding}: + get: + summary: Tenant finding detail with intake continuity support + description: >- + Returns the rendered tenant finding detail page. The logical contract + below documents only the continuity inputs required when the page is + opened from Findings intake. + parameters: + - name: tenant + in: path + required: true + schema: + type: integer + - name: finding + in: path + required: true + schema: + type: integer + - name: nav + in: query + required: false + style: deepObject + explode: true + schema: + $ref: '#/components/schemas/CanonicalNavigationContext' + responses: + '200': + description: Rendered tenant finding detail page + content: + text/html: + schema: + type: string + application/vnd.tenantpilot.finding-detail-from-intake+json: + schema: + $ref: '#/components/schemas/FindingDetailContinuation' + '403': + description: Viewer is in scope but lacks the existing findings capability for the tenant detail destination + '404': + description: Tenant or finding is not visible because workspace or tenant entitlement is missing +components: + schemas: + FindingsIntakePage: + type: object + required: + - header + - appliedScope + - queueViews + - summaryCounts + - rows + - emptyState + properties: + header: + $ref: '#/components/schemas/IntakeHeader' + appliedScope: + $ref: '#/components/schemas/IntakeAppliedScope' + queueViews: + type: array + items: + $ref: '#/components/schemas/QueueViewDefinition' + summaryCounts: + $ref: '#/components/schemas/IntakeSummaryCounts' + rows: + description: >- + Rows are ordered overdue first, reopened second, new third, then + remaining unassigned backlog. Within each bucket, rows with due + dates sort by dueAt ascending, rows without due dates sort last, + and remaining ties sort by findingId descending. + type: array + items: + $ref: '#/components/schemas/IntakeFindingRow' + emptyState: + oneOf: + - $ref: '#/components/schemas/IntakeEmptyState' + - type: 'null' + IntakeHeader: + type: object + required: + - title + - description + properties: + title: + type: string + enum: + - Findings intake + description: + type: string + clearTenantFilterAction: + oneOf: + - $ref: '#/components/schemas/ActionLink' + - type: 'null' + IntakeAppliedScope: + type: object + required: + - workspaceScoped + - fixedScope + - queueView + - tenantPrefilterSource + properties: + workspaceScoped: + type: boolean + fixedScope: + type: string + enum: + - visible_unassigned_open_findings_only + queueView: + type: string + enum: + - unassigned + - needs_triage + tenantPrefilterSource: + type: string + enum: + - active_tenant_context + - explicit_filter + - none + tenantLabel: + type: + - string + - 'null' + QueueViewDefinition: + type: object + required: + - key + - label + - fixed + - active + properties: + key: + type: string + enum: + - unassigned + - needs_triage + label: + type: string + fixed: + type: boolean + active: + type: boolean + badgeCount: + type: + - integer + - 'null' + minimum: 0 + IntakeSummaryCounts: + type: object + description: Counts derived only from visible intake rows. + required: + - visibleUnassigned + - visibleNeedsTriage + - visibleOverdue + properties: + visibleUnassigned: + type: integer + minimum: 0 + visibleNeedsTriage: + type: integer + minimum: 0 + visibleOverdue: + type: integer + minimum: 0 + IntakeFindingRow: + type: object + required: + - findingId + - tenantId + - tenantLabel + - summary + - severity + - status + - intakeReason + - dueState + - detailUrl + properties: + findingId: + type: integer + tenantId: + type: integer + tenantLabel: + type: string + summary: + type: string + severity: + $ref: '#/components/schemas/Badge' + status: + $ref: '#/components/schemas/Badge' + dueAt: + type: + - string + - 'null' + format: date-time + dueState: + $ref: '#/components/schemas/DueState' + ownerLabel: + type: + - string + - 'null' + intakeReason: + type: string + enum: + - Unassigned + - Needs triage + claimAction: + oneOf: + - $ref: '#/components/schemas/ClaimFindingAffordance' + - type: 'null' + detailUrl: + type: string + navigationContext: + oneOf: + - $ref: '#/components/schemas/CanonicalNavigationContext' + - type: 'null' + ClaimFindingAffordance: + type: object + required: + - actionId + - label + - enabled + - requiresConfirmation + properties: + actionId: + type: string + enum: + - claim + label: + type: string + enum: + - Claim finding + enabled: + type: boolean + requiresConfirmation: + type: boolean + enum: + - true + confirmationTitle: + type: + - string + - 'null' + confirmationBody: + type: + - string + - 'null' + disabledReason: + type: + - string + - 'null' + DueState: + type: object + required: + - label + - tone + properties: + label: + type: string + tone: + type: string + enum: + - calm + - warning + - danger + IntakeEmptyState: + type: object + required: + - title + - body + - action + properties: + title: + type: string + body: + type: string + reason: + type: string + enum: + - no_visible_intake_work + - active_tenant_prefilter_excludes_rows + action: + oneOf: + - $ref: '#/components/schemas/OpenMyFindingsActionLink' + - $ref: '#/components/schemas/ClearTenantFilterActionLink' + ClaimFindingResult: + type: object + required: + - findingId + - tenantId + - assigneeUserId + - auditActionId + - queueOutcome + - nextPrimaryAction + properties: + findingId: + type: integer + tenantId: + type: integer + assigneeUserId: + type: integer + auditActionId: + type: string + enum: + - finding.assigned + queueOutcome: + type: string + enum: + - removed_from_intake + nextPrimaryAction: + $ref: '#/components/schemas/OpenMyFindingsActionLink' + nextInspectAction: + oneOf: + - $ref: '#/components/schemas/OpenFindingActionLink' + - type: 'null' + FindingDetailContinuation: + type: object + description: >- + Continuity payload for tenant finding detail when it is opened from the + Findings intake queue. The backLink is present whenever canonical intake + navigation context is provided and may be null only for direct entry + without intake continuity context. + required: + - findingId + - tenantId + properties: + findingId: + type: integer + tenantId: + type: integer + backLink: + oneOf: + - $ref: '#/components/schemas/BackToFindingsIntakeActionLink' + - type: 'null' + CanonicalNavigationContext: + type: object + required: + - source_surface + - canonical_route_name + properties: + source_surface: + type: string + canonical_route_name: + type: string + tenant_id: + type: + - integer + - 'null' + back_label: + type: + - string + - 'null' + back_url: + type: + - string + - 'null' + ActionLink: + type: object + required: + - label + - url + properties: + label: + type: string + url: + type: string + OpenMyFindingsActionLink: + allOf: + - $ref: '#/components/schemas/ActionLink' + - type: object + properties: + label: + type: string + enum: + - Open my findings + OpenFindingActionLink: + allOf: + - $ref: '#/components/schemas/ActionLink' + - type: object + properties: + label: + type: string + enum: + - Open finding + ClearTenantFilterActionLink: + allOf: + - $ref: '#/components/schemas/ActionLink' + - type: object + properties: + label: + type: string + enum: + - Clear tenant filter + BackToFindingsIntakeActionLink: + allOf: + - $ref: '#/components/schemas/ActionLink' + - type: object + properties: + label: + type: string + enum: + - Back to findings intake + Badge: + type: object + required: + - label + properties: + label: + type: string + color: + type: + - string + - 'null' \ No newline at end of file diff --git a/specs/222-findings-intake-team-queue/data-model.md b/specs/222-findings-intake-team-queue/data-model.md new file mode 100644 index 00000000..cfeb37b1 --- /dev/null +++ b/specs/222-findings-intake-team-queue/data-model.md @@ -0,0 +1,204 @@ +# Data Model: Findings Intake & Team Queue V1 + +## Overview + +This feature does not add or modify persisted entities. It introduces three derived models: + +- the canonical admin-plane `Findings intake` queue at `/admin/findings/intake` +- the fixed `Unassigned` and `Needs triage` queue-view state +- the post-claim handoff result that points the operator into the existing `My Findings` surface + +All three remain projections over existing finding, tenant membership, workspace context, and audit truth. + +## Existing Persistent Inputs + +### 1. Finding + +- Purpose: Tenant-owned workflow record representing current governance or remediation work. +- Key persisted fields used by this feature: + - `id` + - `workspace_id` + - `tenant_id` + - `status` + - `severity` + - `due_at` + - `subject_display_name` + - `owner_user_id` + - `assignee_user_id` + - `reopened_at` + - `triaged_at` + - `in_progress_at` +- Relationships used by this feature: + - `tenant()` + - `ownerUser()` + - `assigneeUser()` + +Relevant existing semantics: + +- `Finding::openStatuses()` defines intake inclusion and intentionally excludes `acknowledged`. +- `Finding::openStatusesForQuery()` remains relevant for `My Findings`, but not for intake. +- Spec 219 defines owner-versus-assignee meaning. +- Spec 221 defines the post-claim destination when a finding becomes assigned to the current user. + +### 2. Tenant + +- Purpose: Tenant boundary for queue disclosure, claim authorization, and tenant-plane detail drilldown. +- Key persisted fields used by this feature: + - `id` + - `workspace_id` + - `name` + - `external_id` + - `status` + +### 3. TenantMembership And Capability Truth + +- Purpose: Per-tenant entitlement and capability boundary for queue visibility and claim. +- Sources: + - `tenant_memberships` + - existing `CapabilityResolver` +- Key values used by this feature: + - tenant membership presence + - role-derived `TENANT_FINDINGS_VIEW` + - role-derived `TENANT_FINDINGS_ASSIGN` + +Queue disclosure, tab badges, filter options, and claim affordances must only materialize for tenants where the actor remains a member and is authorized for the relevant finding capability. + +### 4. Workspace Context + +- Purpose: Active workspace selection in the admin plane. +- Source: Existing workspace session context, not a new persisted model for this feature. +- Effect on this feature: + - gates entry into the admin intake page + - constrains visible tenants to the current workspace + - feeds the default active-tenant prefilter through `CanonicalAdminTenantFilterState` + +### 5. AuditLog + +- Purpose: Existing audit record for security- and workflow-relevant mutations. +- Effect on this feature: + - successful claims write an audit entry through the existing `finding.assigned` action ID + - the audit payload records before/after assignment state, workspace, tenant, actor, and target finding + +## Derived Presentation Entities + +### 1. IntakeFindingRow + +Logical row model for `/admin/findings/intake`. + +| Field | Meaning | Source | +|---|---|---| +| `findingId` | Target finding identifier | `Finding.id` | +| `tenantId` | Tenant route scope for detail drilldown | `Finding.tenant_id` | +| `tenantLabel` | Tenant name visible in the queue | `Tenant.name` | +| `summary` | Operator-facing finding summary | `Finding.subject_display_name` plus existing fallback logic | +| `severity` | Severity badge value | `Finding.severity` | +| `status` | Lifecycle badge value | `Finding.status` | +| `dueAt` | Due date if present | `Finding.due_at` | +| `dueState` | Derived urgency label such as overdue or due soon | existing findings due-state logic | +| `ownerLabel` | Accountable owner when present | `ownerUser.name` | +| `intakeReason` | Why the row still belongs in shared intake | derived from lifecycle plus assignment truth | +| `detailUrl` | Tenant finding detail route | derived from tenant finding view route | +| `navigationContext` | Return-path payload back to intake | derived from `CanonicalNavigationContext` | +| `claimEnabled` | Whether the current actor may claim now | derived from assign capability and current claimable state | + +Validation rules: + +- Row inclusion requires all of the following: + - finding belongs to the current workspace + - finding belongs to a tenant the current user may inspect + - finding status is in `Finding::openStatuses()` + - `assignee_user_id` is `null` +- Already-assigned findings are excluded even if overdue or reopened. +- `acknowledged` findings are excluded. +- Hidden-tenant or capability-blocked findings produce no row, no count, no tab badge contribution, and no tenant filter option. + +Derived queue reason: + +- `Needs triage` when status is `new` or `reopened` +- `Unassigned` when status is `triaged` or `in_progress` + +### 2. FindingsIntakeState + +Logical state model for the intake page. + +| Field | Meaning | +|---|---| +| `workspaceId` | Current admin workspace scope | +| `queueView` | Fixed queue mode: `unassigned` or `needs_triage` | +| `tenantFilter` | Optional active-tenant prefilter, defaulted from canonical admin tenant context | +| `fixedScope` | Constant indicator that the page remains restricted to unassigned intake rows | + +Rules: + +- `queueView` is limited to `unassigned` and `needs_triage`. +- `tenantFilter` is clearable; `fixedScope` is not. +- `tenantFilter` values may only reference entitled tenants. +- Invalid or stale tenant filter state is discarded rather than widening visibility. +- Summary counts and tab badges reflect only visible intake rows after the active queue view and tenant prefilter are applied. + +### 3. ClaimOutcome + +Logical mutation result for `Claim finding`. + +| Field | Meaning | Source | +|---|---|---| +| `findingId` | Claimed finding identifier | `Finding.id` | +| `tenantId` | Tenant scope of the claimed finding | `Finding.tenant_id` | +| `assigneeUserId` | New assignee after success | current user ID | +| `auditActionId` | Stable audit action identifier | existing `finding.assigned` | +| `nextPrimaryAction` | Primary handoff after success | `Open my findings` | +| `nextInspectAction` | Optional inspect fallback | existing tenant finding detail route | + +Validation rules: + +- Actor must remain a tenant member for the target finding. +- Actor must have `TENANT_FINDINGS_ASSIGN`. +- The locked record must still have `assignee_user_id = null` at mutation time. +- Claim leaves `owner_user_id` unchanged. +- Claim leaves workflow status unchanged. +- Success removes the row from intake immediately because the assignee is no longer null. +- Conflict does not mutate the row and must return honest feedback so the queue can refresh. + +## State And Ordering Rules + +### Intake inclusion order + +1. Restrict to the current workspace. +2. Restrict to visible tenant IDs. +3. Restrict to `assignee_user_id IS NULL`. +4. Restrict to `Finding::openStatuses()`. +5. Apply the fixed queue view: + - `unassigned` keeps all included rows + - `needs_triage` keeps only `new` and `reopened` +6. Apply optional tenant prefilter. +7. Sort overdue rows first, reopened rows second, new rows third, then remaining backlog. +8. Within each bucket, rows with due dates sort by `dueAt` ascending, rows without due dates sort last, and remaining ties sort by `findingId` descending. + +### Urgency semantics + +- Overdue rows are the highest-priority bucket. +- Reopened non-overdue rows are the next bucket. +- New rows follow reopened rows. +- Triaged and in-progress unassigned rows remain visible in `Unassigned`, but never in `Needs triage`. + +### Claim semantics + +- Claim is not a lifecycle status transition. +- Claim performs one responsibility transition only: `assignee_user_id` moves from `null` to the current user. +- Owner accountability remains unchanged. +- Successful claim makes the finding eligible for `My Findings` immediately because the record is now assigned. +- Stale-row conflicts must fail before save when the locked record already has an assignee. + +### Empty-state semantics + +- If no visible intake rows exist anywhere in scope, the page shows a calm empty state with one CTA into `My Findings`. +- If the active tenant prefilter causes the empty state while other visible tenants still contain intake rows, the empty state must explain the tenant boundary and offer `Clear tenant filter`. +- Neither branch may reveal hidden tenant names or hidden queue quantities. + +## Authorization-Sensitive Output + +- Tenant labels, tab badges, filter values, rows, and counts are only derived from entitled tenants. +- Queue visibility remains workspace-context dependent. +- Claim affordances remain visible only inside in-scope membership context and must still enforce `403` server-side for members missing assign capability. +- Detail navigation remains tenant-scoped and must preserve existing `404` and `403` semantics on the destination. +- The derived queue state remains useful without revealing hidden tenant names, row counts, or empty-state hints. \ No newline at end of file diff --git a/specs/222-findings-intake-team-queue/plan.md b/specs/222-findings-intake-team-queue/plan.md new file mode 100644 index 00000000..b8cdae69 --- /dev/null +++ b/specs/222-findings-intake-team-queue/plan.md @@ -0,0 +1,237 @@ +# Implementation Plan: Findings Intake & Team Queue V1 + +**Branch**: `222-findings-intake-team-queue` | **Date**: 2026-04-21 | **Spec**: `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/222-findings-intake-team-queue/spec.md` +**Input**: Feature specification from `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/222-findings-intake-team-queue/spec.md` + +**Note**: This plan keeps the work inside the existing admin workspace shell, tenant-owned `Finding` truth, current tenant finding detail surface, and the already-shipped `My Findings` destination from Spec 221. The intended implementation is one new canonical `/admin` page plus one narrow self-claim shortcut. It does not add persistence, a team model, a second permission family, bulk claim, queue automation, or provider-side work. + +## Summary + +Add one canonical admin-plane intake queue at `/admin/findings/intake` that shows visible unassigned findings across the current workspace, separates `Unassigned` from the stricter `Needs triage` subset, and lets an authorized operator claim an item into the existing `/admin/findings/my-work` surface through a lightweight preview/confirmation flow without opening the broader assignment form first. Reuse the existing `MyFindingsInbox` page shape, `FindingResource` badge and navigation helpers, `CanonicalAdminTenantFilterState` for active-tenant prefiltering, `CanonicalNavigationContext` for intake-to-detail continuity, and `FindingWorkflowService` plus the current `finding.assigned` audit path, while adding one claim-specific stale-row guard so a delayed click cannot silently overwrite another operator's successful claim. + +## Technical Context + +**Language/Version**: PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade +**Primary Dependencies**: Filament admin pages/tables/actions/notifications, `Finding`, `FindingResource`, `FindingWorkflowService`, `FindingPolicy`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, `CanonicalNavigationContext`, `WorkspaceContext`, and `UiEnforcement` +**Storage**: PostgreSQL via existing `findings`, `tenants`, `tenant_memberships`, `audit_logs`, and workspace session context; no schema changes planned +**Testing**: Pest v4 feature tests with Livewire/Filament assertions; existing action-surface and Filament guard suites remain ambient CI protection +**Validation Lanes**: fast-feedback, confidence +**Target Platform**: Dockerized Laravel web application via Sail locally and Linux containers in deployment +**Project Type**: Laravel monolith inside the `wt-plattform` monorepo +**Performance Goals**: Keep intake rendering and claim DB-only, eager-load tenant and owner display context, avoid N+1 capability lookups across visible tenants, and keep first operator scan within the 10-second acceptance target +**Constraints**: No Graph calls, no new `OperationRun`, no new capabilities, no new persistence, no hidden-tenant leakage, no bulk claim, no new assets, no silent overwrite on stale claim attempts, and no expansion of lifecycle or ownership semantics +**Scale/Scope**: One admin page and Blade view, one derived intake query, one narrow workflow-service extension or guard for claim conflict handling, three focused feature suites, and ambient compliance with existing action-surface and Filament table guards + +## UI / Surface Guardrail Plan + +- **Guardrail scope**: changed surfaces +- **Native vs custom classification summary**: native Filament page, table, tab, badge, row-action, notification, and empty-state primitives only +- **Shared-family relevance**: findings workflow family and canonical admin findings pages +- **State layers in scope**: shell, page, detail, URL-query +- **Handling modes by drift class or surface**: review-mandatory +- **Repository-signal treatment**: review-mandatory +- **Special surface test profiles**: global-context-shell +- **Required tests or manual smoke**: functional-core, state-contract +- **Exception path and spread control**: none; the queue stays list-first with one safe inline shortcut while dangerous lifecycle actions remain on existing tenant detail and tenant findings list surfaces +- **Active feature PR close-out entry**: Guardrail + +## Constitution Check + +*GATE: Passed before Phase 0 research. Re-check after Phase 1 design.* + +| Principle | Pre-Research | Post-Design | Notes | +|-----------|--------------|-------------|-------| +| Inventory-first / snapshots-second | PASS | PASS | The queue remains a live derived view over `Finding` truth only; no snapshot or backup semantics are introduced | +| Read/write separation | PASS | PASS | The only write is the narrow `Claim` assignment shortcut; it uses a lightweight preview and explicit confirmation step, is TenantPilot-only, audit-logged, race-checked, and covered by focused tests while dangerous workflow mutations remain on existing tenant detail surfaces | +| Graph contract path | PASS | PASS | No Graph client, contract-registry, or provider API work is added | +| Deterministic capabilities / RBAC-UX | PASS | PASS | Workspace membership plus at least one currently viewable findings scope gates the admin page, per-tenant findings visibility gates rows and counts once inside the queue, `TENANT_FINDINGS_ASSIGN` gates claim, non-members stay `404`, workspace members with no currently viewable findings scope get `403`, and in-scope members missing claim capability remain `403` on execution | +| Workspace / tenant isolation | PASS | PASS | The admin queue is workspace-scoped, row disclosure remains tenant-entitlement checked, and drilldown stays on `/admin/t/{tenant}/findings/{finding}` with tenant-safe continuity | +| Run observability / Ops-UX | PASS | PASS | No long-running work, no `OperationRun`, and no queue/progress surface changes are introduced; the short DB-only claim write is audit-logged | +| Proportionality / no premature abstraction | PASS | PASS | The intake query stays page-local and the claim behavior extends existing workflow seams instead of creating a new queue framework or team-routing abstraction | +| Persisted truth / few layers | PASS | PASS | Intake views, queue reason, and summary counts remain derived from existing finding status, assignee, owner, due-date, and entitlement truth | +| Behavioral state discipline | PASS | PASS | `Unassigned` and `Needs triage` remain derived queue views; no new persisted status, reason family, or ownership role is introduced | +| Badge semantics (BADGE-001) | PASS | PASS | Severity and lifecycle cues reuse existing findings badge rendering and due-attention helpers | +| Filament-native UI (UI-FIL-001) | PASS | PASS | The design stays within Filament page, table, tabs, row actions, notifications, and empty-state primitives | +| Action surface / inspect model | PASS | PASS | Row click remains the primary inspect model, `Claim` is the only inline safe shortcut, and there is no redundant `View` or bulk action lane | +| Decision-first / OPSURF | PASS | PASS | The intake queue is the primary decision surface for pre-assignment routing and keeps diagnostics secondary behind finding detail | +| Test governance (TEST-GOV-001) | PASS | PASS | Proof remains in three focused feature suites with explicit lane fit and no new heavy-governance or browser family | +| Filament v5 / Livewire v4 compliance | PASS | PASS | The feature remains inside Filament v5 patterns and Livewire v4-compatible page/table behavior only | +| Provider registration / global search / assets | PASS | PASS | Panel providers already live in `apps/platform/bootstrap/providers.php`; the new page only extends `AdminPanelProvider`, `FindingResource` global search is unchanged and already has a View page, and no new assets are introduced so the deploy `filament:assets` step is unchanged | + +## Test Governance Check + +- **Test purpose / classification by changed surface**: `Feature` for the admin intake page, authorization boundaries, and claim handoff behavior +- **Affected validation lanes**: `fast-feedback`, `confidence` +- **Why this lane mix is the narrowest sufficient proof**: The feature risk is visible queue truth, tenant-safe filtering, `Needs triage` subset semantics, claim authorization, stale-row conflict handling, and handoff into an existing personal queue. Focused feature tests prove that integrated behavior without adding unit seams, browser coverage, or heavy-governance breadth. +- **Narrowest proving command(s)**: + - `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsIntakeQueueTest.php tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php` + - `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsClaimHandoffTest.php` +- **Fixture / helper / factory / seed / context cost risks**: Moderate. The tests need one workspace, multiple visible and hidden tenants, owner-versus-assignee combinations, unassigned and assigned findings across open and terminal states, explicit active-tenant session context, and one stale-claim race scenario. +- **Expensive defaults or shared helper growth introduced?**: no; the new suites should reuse `createUserWithTenant(...)` and `Finding::factory()` and keep any intake-specific helper local to the new tests +- **Heavy-family additions, promotions, or visibility changes**: none +- **Surface-class relief / special coverage rule**: named special profile `global-context-shell` is required because the page depends on workspace context, active-tenant prefilter continuity, tenant-safe detail drilldown, and row-level capability visibility +- **Closing validation and reviewer handoff**: Reviewers should rely on the exact commands above and verify that hidden-tenant or capability-blocked findings never leak into rows, counts, tab badges, or tenant filter values; `acknowledged` findings stay out of intake; `Needs triage` remains limited to `new` and `reopened`; claim leaves owner and workflow status unchanged; and stale claims fail honestly instead of overwriting another operator's assignment. +- **Budget / baseline / trend follow-up**: none +- **Review-stop questions**: Did the intake query accidentally include assigned or `acknowledged` rows? Did claim mutate owner or lifecycle state? Did a second inline action or bulk lane appear? Did any new shared queue abstraction or team model appear without a second real consumer? Did stale-claim behavior degrade into silent overwrite? +- **Escalation path**: document-in-feature unless a second shared intake surface or reusable cross-tenant queue framework is introduced, in which case follow-up-spec or split +- **Active feature PR close-out entry**: Guardrail +- **Why no dedicated follow-up spec is needed**: The feature remains bounded to one derived queue surface and one narrow claim path, with no new persistence, no new workflow family, and no structural test-cost center + +## Project Structure + +### Documentation (this feature) + +```text +specs/222-findings-intake-team-queue/ +├── plan.md +├── research.md +├── data-model.md +├── quickstart.md +├── contracts/ +│ └── findings-intake-team-queue.logical.openapi.yaml +├── checklists/ +│ └── requirements.md +└── tasks.md +``` + +### Source Code (repository root) + +```text +apps/platform/ +├── app/ +│ ├── Filament/ +│ │ ├── Pages/ +│ │ │ └── Findings/ +│ │ │ └── FindingsIntakeQueue.php +│ │ └── Resources/ +│ │ └── FindingResource.php +│ ├── Providers/ +│ │ └── Filament/ +│ │ └── AdminPanelProvider.php +│ └── Services/ +│ └── Findings/ +│ └── FindingWorkflowService.php +├── resources/ +│ └── views/ +│ └── filament/ +│ └── pages/ +│ └── findings/ +│ └── findings-intake-queue.blade.php +└── tests/ + └── Feature/ + ├── Authorization/ + │ └── FindingsIntakeAuthorizationTest.php + └── Findings/ + ├── FindingsClaimHandoffTest.php + └── FindingsIntakeQueueTest.php +``` + +**Structure Decision**: Standard Laravel monolith. The feature stays inside the existing admin panel provider, finding domain model, workflow service, and focused Pest feature suites. No new base directory, package, or persisted model is required. + +## Complexity Tracking + +| Violation | Why Needed | Simpler Alternative Rejected Because | +|-----------|------------|-------------------------------------| +| none | — | — | + +## Proportionality Review + +- **Current operator problem**: Unassigned findings exist in the current workflow, but there is no single trustworthy workspace-safe queue for the pre-assignment backlog. +- **Existing structure is insufficient because**: Tenant-local findings lists and ad hoc filters still force tenant hopping and do not provide a clean handoff from shared backlog into the existing personal queue. +- **Narrowest correct implementation**: Add one admin intake page and one safe self-claim shortcut derived directly from existing finding lifecycle, due-state, ownership, and entitlement truth. +- **Ownership cost created**: One page/view pair, one small claim conflict guard inside the existing workflow service seam, and three focused feature suites. +- **Alternative intentionally rejected**: A broader team workboard, notification-first routing model, or queue framework was rejected because those shapes add durable workflow machinery before this smaller intake slice is proven useful. +- **Release truth**: Current-release truth. The work operationalizes an already-existing unassigned backlog now rather than preparing a later team-orchestration system. + +## Phase 0 Research + +Research outcomes are captured in `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/222-findings-intake-team-queue/research.md`. + +Key decisions: + +- Implement the intake queue as a new Filament admin page with slug `findings/intake` under the existing `AdminPanelProvider`, not as a tenant resource variant and not as a standalone controller route. +- Keep queue truth as a direct `Finding` query scoped by workspace, visible tenant IDs, `assignee_user_id IS NULL`, and `Finding::openStatuses()` rather than `Finding::openStatusesForQuery()`, because `acknowledged` rows are intentionally excluded from intake. +- Model `Unassigned` and `Needs triage` as fixed queue views inside the page shell, not as a new taxonomy, persisted preference, or generic filter framework. +- Reuse `CanonicalAdminTenantFilterState` for the active-tenant prefilter and `CanonicalNavigationContext` for intake-to-detail continuity and `Back to findings intake` behavior. +- Add `Claim finding` as a narrow row action that reuses the existing findings assign capability, success notification patterns, lightweight preview/confirmation content, and `finding.assigned` audit trail, but adds a claim-specific stale-row guard so delayed clicks fail honestly when another operator claimed the row first. +- Prove the feature with three focused Pest feature suites while relying on existing action-surface and Filament-table guards as ambient CI coverage. + +## Phase 1 Design + +Design artifacts are created under `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/222-findings-intake-team-queue/`: + +- `research.md`: routing, query, fixed-view, claim, and continuity decisions +- `data-model.md`: existing entities plus derived intake row, queue state, and claim outcome projections +- `contracts/findings-intake-team-queue.logical.openapi.yaml`: internal logical contract for intake rendering, claim, and continuity inputs +- `quickstart.md`: focused validation workflow for implementation and review + +Design decisions: + +- No schema migration is required; the queue, view counts, and empty states remain fully derived. +- The canonical implementation seam is one new admin page plus one narrow workflow-service claim guard and lightweight preview/confirmation surface, not a new shared queue or team-routing subsystem. +- Active tenant context remains canonical through `CanonicalAdminTenantFilterState`, while detail continuity remains canonical through `CanonicalNavigationContext`. +- Claim remains a TenantPilot-only assignee mutation. It leaves owner and lifecycle state unchanged, uses a lightweight preview/confirmation modal before execution, writes an audit entry, refuses silent overwrite under lock, and points the operator to the existing `My Findings` destination after success. + +## Phase 1 Agent Context Update + +Run: + +- `.specify/scripts/bash/update-agent-context.sh copilot` + +## Constitution Check — Post-Design Re-evaluation + +- PASS — the design stays inside existing admin, finding, and workflow seams with no new persistence, no Graph work, no `OperationRun`, no new capability family, and no new assets. +- PASS — Livewire v4.0+ and Filament v5 constraints remain satisfied, panel provider registration stays in `apps/platform/bootstrap/providers.php`, `FindingResource` global search remains unchanged and still has a View page, and the non-destructive `Claim` action still uses an explicit lightweight preview/confirmation flow to satisfy write-governance without expanding into a broader assignment form. + +## Implementation Strategy + +### Phase A — Add The Canonical Shared Intake Surface + +**Goal**: Create one workspace-scoped intake queue under `/admin/findings/intake`. + +| Step | File | Change | +|------|------|--------| +| A.1 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | Add a new Filament admin page with slug `findings/intake`, `HasTable`, workspace membership access checks, explicit `403` handling when no findings-viewable scope exists, visible-tenant resolution, active-tenant sync, and action-surface declaration for row-click inspect plus one safe `Claim` shortcut | +| A.2 | `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php` | Render the page shell, page description, fixed `Unassigned` and `Needs triage` view controls, native Filament table, and calm empty-state branches with either `Clear tenant filter` or `Open my findings` | +| A.3 | `apps/platform/app/Providers/Filament/AdminPanelProvider.php` | Register the new page in the existing admin panel; do not move provider registration because it already lives in `apps/platform/bootstrap/providers.php` | + +### Phase B — Derive Intake Truth From Existing Finding Semantics + +**Goal**: Keep inclusion, queue reason, and ordering aligned with Specs 111, 219, and 221. + +| Step | File | Change | +|------|------|--------| +| B.1 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | Build the base query from `Finding`, restricted to the current workspace, visible tenant IDs, `assignee_user_id IS NULL`, and `Finding::openStatuses()` rather than `openStatusesForQuery()` | +| B.2 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` and `apps/platform/app/Filament/Resources/FindingResource.php` | Reuse existing severity, lifecycle, due-attention, and owner display helpers; derive queue reason as `Needs triage` for `new` and `reopened`, otherwise `Unassigned` | +| B.3 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | Add visible summary counts, fixed queue-view metadata, capability-safe tenant filter options, and deterministic urgency ordering: overdue first, then reopened, then new, then remaining unassigned backlog, with due-date and finding-ID tie breaks | + +### Phase C — Add The Safe Claim Shortcut Without Expanding Workflow Scope + +**Goal**: Turn shared backlog into personal work in one short confirmed flow without inventing a second assignment system. + +| Step | File | Change | +|------|------|--------| +| C.1 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | Add one inline `Claim finding` row action using `UiEnforcement`, lightweight preview/confirmation content, preserved visibility for in-scope members, and success/failure notifications that keep the queue honest | +| C.2 | `apps/platform/app/Services/Findings/FindingWorkflowService.php` | Add a claim-specific path or guard that reuses existing assignment semantics and `AuditActionId::FindingAssigned`, but under lock refuses any record whose assignee is no longer null before mutation | +| C.3 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | After confirmed claim success, refresh the queue so the row disappears immediately and provide a clear next step into `My Findings` or the tenant finding detail without changing owner or workflow state | + +### Phase D — Preserve Canonical Context And Continuity + +**Goal**: Make intake behave like a first-class admin-plane queue rather than a detached filter. + +| Step | File | Change | +|------|------|--------| +| D.1 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | Reuse `CanonicalAdminTenantFilterState` so the active tenant becomes the default prefilter and can be cleared without dropping the fixed intake scope or queue view | +| D.2 | `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` | Build row URLs to tenant finding detail with `CanonicalNavigationContext` carrying `Back to findings intake` continuity | +| D.3 | Existing tenant finding detail seam | Keep the existing tenant detail page as the deeper workflow surface and ensure it continues to consume navigation context without queue-specific detail forks | + +### Phase E — Protect Visibility, Claim Safety, And Handoff Truth + +**Goal**: Lock down queue inclusion, authorization, conflict handling, and continuity with focused regression coverage. + +| Step | File | Change | +|------|------|--------| +| E.1 | `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php` | Cover visible unassigned rows only, active-tenant prefilter behavior, fixed queue views, queue reason rendering, owner-context rendering, assigned and `acknowledged` exclusion, hidden-tenant suppression, deterministic ordering, empty states, and intake-to-detail continuity | +| E.2 | `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php` | Cover workspace context recovery, non-member `404`, queue-access `403` when no currently viewable findings scope exists, disabled or rejected claim for members missing assign capability, and tenant-safe detail disclosure | +| E.3 | `apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php` | Cover claim preview/confirmation rendering, successful claim, audit side effects, immediate queue removal, `My Findings` next-step alignment, and stale-row conflict refusal when another operator claims first | +| E.4 | `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` plus the focused Pest commands above | Run formatting and the narrowest proving suites before closing implementation | diff --git a/specs/222-findings-intake-team-queue/quickstart.md b/specs/222-findings-intake-team-queue/quickstart.md new file mode 100644 index 00000000..1f49f4ca --- /dev/null +++ b/specs/222-findings-intake-team-queue/quickstart.md @@ -0,0 +1,158 @@ +# Quickstart: Findings Intake & Team Queue V1 + +## Goal + +Validate that `/admin/findings/intake` gives the current user one trustworthy shared queue for visible unassigned findings, that `Needs triage` remains the strict `new` and `reopened` subset, and that `Claim finding` moves eligible work into `/admin/findings/my-work` through a lightweight preview and explicit confirmation without silent overwrite. + +## Prerequisites + +1. Start Sail if it is not already running. +2. Use a test user who is a member of one workspace and at least two tenants inside that workspace. +3. Seed or create findings for these cases: + - unassigned `new` finding in tenant A + - unassigned `reopened` finding in tenant B + - unassigned `triaged` finding in tenant A + - unassigned `in_progress` finding in tenant B + - unassigned finding with owner set but no assignee + - already-assigned open finding + - `acknowledged` finding with no assignee + - terminal finding + - unassigned finding in a hidden tenant + - unassigned finding in a tenant where the acting user can view findings but a second acting user lacks assign capability + - one claim-race fixture where another operator can successfully claim after the first queue render +4. Ensure `/admin/findings/my-work` already works for the acting workspace user. + +## Focused Automated Verification + +Run formatting first: + +```bash +cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent +``` + +Then run the focused proving set: + +```bash +cd apps/platform && ./vendor/bin/sail artisan test --compact \ + tests/Feature/Findings/FindingsIntakeQueueTest.php \ + tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php +``` + +```bash +cd apps/platform && ./vendor/bin/sail artisan test --compact \ + tests/Feature/Findings/FindingsClaimHandoffTest.php +``` + +## Manual Validation Pass + +### 1. Canonical intake route + +Open `/admin/findings/intake`. + +Confirm that: + +- the page title and copy use findings-intake vocabulary, +- rows show tenant, finding summary, severity, lifecycle, due urgency, owner when present, and queue reason, +- the page is clearly fixed to shared unassigned work, +- a workspace member with no currently viewable findings scope receives `403` instead of a pseudo-empty queue, +- and already-assigned, `acknowledged`, terminal, hidden-tenant, and capability-blocked rows do not appear. + +### 2. Fixed queue views + +On the same page: + +Confirm that: + +- `Unassigned` shows all visible unassigned open findings, +- `Needs triage` shows only visible `new` and `reopened` findings, +- `triaged` and `in_progress` findings disappear from `Needs triage`, +- and already-assigned `reopened` findings never re-enter intake. + +### 3. Active tenant prefilter + +Set an active tenant context before opening the intake queue. + +Confirm that: + +- the queue defaults to that tenant, +- the fixed intake scope and selected queue view remain intact, +- a `Clear tenant filter` affordance is available, +- summary state stays consistent with the visible rows, +- and clearing the tenant filter returns the queue to all visible tenants without widening beyond intake truth. + +### 4. Ordering and urgency + +With overdue, reopened, new, and undated unassigned findings: + +Confirm that: + +- overdue rows appear first, +- reopened rows appear ahead of new rows, +- new rows appear ahead of the remaining triaged or in-progress unassigned backlog, +- rows with due dates sort ahead of rows without due dates inside the same bucket, +- and tie breaks remain deterministic. + +### 5. Claim happy path + +Claim an eligible row as a user with assign capability. + +Confirm that: + +- the preview clearly summarizes the tenant, finding, and assignee change before execution, +- the claim succeeds only after explicit confirmation, +- assignee becomes the current user, +- owner and workflow status stay unchanged, +- the row disappears from intake immediately, +- and the success path points clearly into `Open my findings` while row-open detail remains available for deeper context. + +### 6. Claim forbidden path + +Use a workspace member who can inspect findings but lacks assign capability. + +Confirm that: + +- intake rows remain inspectable, +- claim is not successfully executable, +- the server rejects direct claim attempts with `403`, +- and the queue remains honest after the failed attempt. + +### 7. Stale-row conflict path + +Load intake as operator A, then claim the same finding as operator B before operator A clicks `Claim finding`. + +Confirm that: + +- operator A does not overwrite operator B, +- the system reports the conflict honestly, +- the queue refreshes so the stale row disappears, +- and the audit trail reflects only the successful claim. + +### 8. Detail continuity + +Open a row from intake. + +Confirm that: + +- the destination is the existing tenant finding detail route, +- tenant scope is correct, +- and the page offers `Back to findings intake` continuity. + +### 9. Empty-state behavior + +Validate two empty states: + +- no visible intake work anywhere +- no rows only because the active tenant prefilter narrows the queue + +Confirm that: + +- the zero-visible-work branch stays calm and offers `Open my findings`, +- the tenant-prefilter branch explains the narrowing honestly instead of claiming the intake queue is globally empty, +- the tenant-prefilter branch offers only `Clear tenant filter`, +- and neither branch leaks hidden tenant information. + +## Final Verification Notes + +- The queue remains the shared pre-assignment surface; deeper workflow mutations stay on tenant finding detail and tenant findings list. +- Claim is not destructive, but it still uses a lightweight preview/confirmation step because write/change flows in this repo require explicit confirmation. +- If a reviewer can infer hidden tenant work, or if stale claim attempts can overwrite another operator's success, treat that as a release blocker. \ No newline at end of file diff --git a/specs/222-findings-intake-team-queue/research.md b/specs/222-findings-intake-team-queue/research.md new file mode 100644 index 00000000..c520b47f --- /dev/null +++ b/specs/222-findings-intake-team-queue/research.md @@ -0,0 +1,57 @@ +# Research: Findings Intake & Team Queue V1 + +## Decision 1: Implement the intake queue as an admin panel page with slug `findings/intake` + +- **Decision**: Add a new Filament admin page under the existing `AdminPanelProvider` for the canonical route `/admin/findings/intake`. +- **Rationale**: The feature is an admin-plane, workspace-scoped decision surface, not a tenant-local variant of the existing findings resource. A page registration keeps the same Filament middleware, route shape, session handling, and Livewire page lifecycle already used by `MyFindingsInbox`. +- **Alternatives considered**: + - Reuse the tenant-local `FindingResource` list with a preset filter. Rejected because it still forces tenant-first navigation and does not answer the cross-tenant intake question. + - Add a standalone controller route in `routes/web.php`. Rejected because this is a normal admin panel surface and should stay inside Filament routing and guardrails. + +## Decision 2: Keep intake truth as a direct `Finding` query, but use `Finding::openStatuses()` instead of `openStatusesForQuery()` + +- **Decision**: Build the intake queue from `Finding` records scoped by current workspace, visible tenant IDs, `assignee_user_id IS NULL`, and `Finding::openStatuses()`. +- **Rationale**: Spec 222 explicitly reuses Spec 111 open statuses for intake: `new`, `triaged`, `in_progress`, and `reopened`. The broader `openStatusesForQuery()` helper includes `acknowledged`, which belongs in existing tenant-local workflows but not in this shared intake queue. +- **Alternatives considered**: + - Reuse `Finding::openStatusesForQuery()` exactly as `MyFindingsInbox` does. Rejected because it would leak `acknowledged` rows into intake and violate FR-003. + - Introduce a new shared intake-query service immediately. Rejected because there is still only one concrete intake consumer and the repo guidance prefers direct implementation until reuse pressure is real. + +## Decision 3: Model `Unassigned` and `Needs triage` as fixed page-level views, not a new taxonomy or generic filter framework + +- **Decision**: Represent `Unassigned` and `Needs triage` as fixed queue-view controls in the page shell, with `Needs triage` implemented as the strict subset of intake rows in `new` or `reopened` status. +- **Rationale**: The two views are product vocabulary, not a reusable classification framework. Page-local view state keeps the implementation explicit, honors the spec's fixed queue contract, and avoids adding new persisted preferences or a generic queue-view registry. +- **Alternatives considered**: + - Add a reusable taxonomy or enum for queue view types. Rejected because two concrete values do not justify new semantic machinery. + - Model the views as ordinary optional filters only. Rejected because the spec treats them as fixed queue modes, not ad hoc filter combinations. + +## Decision 4: Reuse canonical admin tenant filter and navigation context helpers + +- **Decision**: Use `CanonicalAdminTenantFilterState` to apply the active tenant as the default prefilter and `CanonicalNavigationContext` to carry `Back to findings intake` continuity into tenant finding detail. +- **Rationale**: The repo already uses these helpers for canonical admin-plane filters and cross-surface back links. Reusing them keeps intake aligned with the existing admin shell, keeps row and count disclosure tenant-safe, and avoids adding another page-specific context mechanism. If a workspace member has no currently viewable findings scope anywhere, the queue should fail with `403` instead of pretending the backlog is simply empty. +- **Alternatives considered**: + - Store active tenant and return-path state in a queue-local session structure. Rejected because the existing helpers already solve both problems and another state path would add drift. + - Depend on browser history for return links. Rejected because it is brittle across reloads, tabs, and copied URLs. + +## Decision 5: Add `Claim finding` as a narrow row action that reuses assignment semantics, adds a lightweight preview/confirmation step, and adds a stale-row conflict guard + +- **Decision**: Implement `Claim finding` as the single inline safe shortcut on the intake row, gated by `Capabilities::TENANT_FINDINGS_ASSIGN`, surfaced through a lightweight preview/confirmation modal, and routed through `FindingWorkflowService` plus the existing `finding.assigned` audit action while adding a claim-specific re-check that refuses rows whose assignee is no longer null under lock. +- **Rationale**: The current assignment service already owns audit logging, tenant ownership checks, and capability enforcement, but plain assign semantics would allow a stale queue click to overwrite a newer assignee and would not satisfy the repository write-flow governance. A lightweight preview/confirmation step plus a narrow guard inside the existing service seam solves both needs without inventing a second assignment system. +- **Alternatives considered**: + - Reuse the existing `Assign` form unchanged. Rejected because the intake surface needs a lighter self-claim preview/confirmation flow, not a broader owner/assignee form. + - Reuse `assign()` without an extra guard. Rejected because it could silently overwrite another operator's successful claim, violating FR-014. + +## Decision 6: Keep post-claim continuity explicit through `My Findings` rather than auto-redirecting away from intake + +- **Decision**: Refresh the queue after a successful claim so the row disappears immediately, then provide a clear next step into `/admin/findings/my-work` while leaving row-open detail continuity available when the operator needs deeper context first. +- **Rationale**: The queue is still the canonical shared backlog surface. Auto-redirecting every successful claim would interrupt batch intake review, while a clear `Open my findings` next step satisfies the spec without hiding the updated queue truth. +- **Alternatives considered**: + - Redirect to `My Findings` after every claim. Rejected because it would add navigation churn when multiple intake items are reviewed in sequence. + - Keep success feedback to a generic toast only. Rejected because the spec requires a clear next step into the existing personal execution destination. + +## Decision 7: Prove the feature with three focused feature suites and rely on existing UI guard tests as ambient protection + +- **Decision**: Add `FindingsIntakeQueueTest`, `FindingsIntakeAuthorizationTest`, and `FindingsClaimHandoffTest` as the focused proving suites while allowing existing action-surface and Filament-table guards to stay in their normal CI role. +- **Rationale**: The user-visible risk is queue truth, hidden-tenant isolation, claim authorization, stale-row conflict handling, and handoff continuity. Those are best proven with focused feature tests that exercise the real Livewire and Filament seams. +- **Alternatives considered**: + - Add browser coverage. Rejected because the surface is straightforward and already well served by existing feature-test patterns. + - Add a new heavy-governance suite for this page. Rejected because the change is still one bounded feature surface, not a new cross-cutting UI family. \ No newline at end of file diff --git a/specs/222-findings-intake-team-queue/spec.md b/specs/222-findings-intake-team-queue/spec.md new file mode 100644 index 00000000..9e284ddf --- /dev/null +++ b/specs/222-findings-intake-team-queue/spec.md @@ -0,0 +1,236 @@ +# Feature Specification: Findings Intake & Team Queue V1 + +**Feature Branch**: `222-findings-intake-team-queue` +**Created**: 2026-04-21 +**Status**: Draft +**Input**: User description: "Findings Intake & Team Queue v1" + +## Spec Candidate Check *(mandatory - SPEC-GATE-001)* + +- **Problem**: Spec 221 created a trustworthy personal queue for assigned findings, but it did not solve where newly detected or otherwise unassigned findings enter the workflow before someone claims them. +- **Today's failure**: Unassigned backlog is still scattered across tenant-local findings pages and ad hoc filters. Operators cannot answer "what is still unowned right now?" from one shared workspace-safe surface, so intake work is easy to miss, duplicate, or defer accidentally. +- **User-visible improvement**: One shared intake queue shows visible unassigned open findings across tenants, separates triage-first backlog from later execution, and provides a direct handoff into personal work when an operator claims an item. +- **Smallest enterprise-capable version**: A canonical read-first intake page for unassigned open findings, fixed `Unassigned` and `Needs triage` views, one optional self-claim action, and tenant-safe drilldown into the existing finding detail and `My Findings` execution surface. +- **Explicit non-goals**: No team model, no capacity dashboard, no auto-routing, no escalation engine, no load balancing, no notifications, no bulk claim workflow, and no new permission system. +- **Permanent complexity imported**: One canonical intake page, one derived intake-query contract, one quick claim action reusing existing assignment semantics, one fixed queue vocabulary for `Unassigned` and `Needs triage`, and focused regression coverage for visibility, claim safety, and handoff continuity. +- **Why now**: Spec 219 clarified owner-versus-assignee meaning and Spec 221 made assigned work discoverable. The next smallest missing workflow slice is the shared pre-assignment intake surface that feeds those personal queues. +- **Why not local**: A tenant-local filter still forces tenant hopping and does not create one trustworthy workspace-wide intake queue or a consistent handoff from shared backlog into personal execution. +- **Approval class**: Core Enterprise +- **Red flags triggered**: None after scope cut. The spec adds one derived queue and one reuse-first claim action rather than a broader team-routing framework. +- **Score**: Nutzen: 2 | Dringlichkeit: 2 | Scope: 2 | Komplexitaet: 2 | Produktnaehe: 2 | Wiederverwendung: 1 | **Gesamt: 11/12** +- **Decision**: approve + +## Spec Scope Fields *(mandatory)* + +- **Scope**: canonical-view +- **Primary Routes**: + - `/admin/findings/intake` as the new canonical shared intake queue + - `/admin/findings/my-work` as the existing personal execution destination after claim + - `/admin/t/{tenant}/findings` as the existing tenant findings list fallback + - `/admin/t/{tenant}/findings/{finding}` as the existing tenant finding detail drilldown +- **Data Ownership**: Tenant-owned findings remain the only source of truth. The intake queue is a derived cross-tenant view over existing finding status, assignee, owner, due state, and tenant-entitlement truth. +- **RBAC**: Workspace membership is required for the canonical intake page in the admin plane. Every visible row and count additionally requires tenant entitlement plus the existing findings view capability for the referenced tenant. The `Claim` action reuses the existing findings assign capability. Non-members and out-of-scope users remain deny-as-not-found. Members missing the required capability remain forbidden on protected actions. + +For canonical-view specs, the spec MUST define: + +- **Default filter behavior when tenant-context is active**: The intake page always keeps its fixed unassigned-open scope. When an active tenant context exists, the page additionally applies that tenant as a default prefilter while allowing the operator to clear only the tenant prefilter, not the intake scope itself. +- **Explicit entitlement checks preventing cross-tenant leakage**: Rows, counts, tenant filter values, claim affordances, and drilldown links are derived only from tenants the current user may already inspect. Hidden tenants contribute nothing to queue rows, counts, filter values, or empty-state hints. + +## UI / Surface Guardrail Impact *(mandatory when operator-facing surfaces are changed; otherwise write `N/A`)* + +| Surface / Change | Operator-facing surface change? | Native vs Custom | Shared-Family Relevance | State Layers Touched | Exception Needed? | Low-Impact / `N/A` Note | +|---|---|---|---|---|---|---| +| Findings intake queue | yes | Native Filament page + existing table, filter, badge, and row-action primitives | Same findings workflow family as tenant findings list, finding detail, and `My Findings` | table, fixed queue views, claim action, return path | no | Read-first shared queue only; no new mutation family beyond claim | + +## Decision-First Surface Role *(mandatory when operator-facing surfaces are changed)* + +| Surface | Decision Role | Human-in-the-loop Moment | Immediately Visible for First Decision | On-Demand Detail / Evidence | Why This Is Primary or Why Not | Workflow Alignment | Attention-load Reduction | +|---|---|---|---|---|---|---|---| +| Findings intake queue | Primary Decision Surface | The operator reviews unowned findings and decides what needs first triage or self-claim before personal execution begins | Tenant, finding summary, severity, lifecycle status, due or overdue state, owner when present, and why the row is still in intake | Full finding detail, evidence, audit trail, exception context, and tenant-local workflow actions after opening the finding | Primary because this is the missing shared entry point before work moves into `My Findings` | Aligns the first-routing workflow around one queue instead of tenant hopping | Removes repeated searches across tenant findings pages just to locate unassigned backlog | + +## UI/UX Surface Classification *(mandatory when operator-facing surfaces are changed)* + +| Surface | Action Surface Class | Surface Type | Likely Next Operator Action | 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 / Justification | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| Findings intake queue | List / Table / Bulk | Workflow queue / list-first canonical view | Claim a finding or open it for verification | Finding | required | One inline safe shortcut for `Claim`; fixed queue-view controls stay outside row-action noise | None on the queue; dangerous lifecycle actions remain on tenant-local finding detail | /admin/findings/intake | /admin/t/{tenant}/findings/{finding} | Active workspace, optional active-tenant prefilter, tenant column, fixed queue-view indicator | Findings intake / Finding | Which open findings are still unassigned, which ones still need first triage, and which tenant they belong to | none | + +## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)* + +| Surface | Primary Persona | Decision / Operator Action Supported | Surface Type | Primary Operator Question | Default-visible Information | Diagnostics-only Information | Status Dimensions Used | Mutation Scope | Primary Actions | Dangerous Actions | +|---|---|---|---|---|---|---|---|---|---|---| +| Findings intake queue | Tenant operator or tenant manager | Decide which unassigned finding needs first team attention and optionally claim it into personal execution | Shared workflow queue | What open findings are still unclaimed right now, and which ones should move into execution first? | Tenant, finding summary, severity, lifecycle status, due date or overdue state, owner when present, and queue reason (`Unassigned` or `Needs triage`) | Raw evidence, run context, exception history, and full audit trail | lifecycle, due urgency, severity, responsibility state | TenantPilot only | Claim finding, Open finding, Apply queue filters | none | + +## Proportionality Review *(mandatory when structural complexity is introduced)* + +- **New source of truth?**: no +- **New persisted entity/table/artifact?**: no +- **New abstraction?**: no +- **New enum/state/reason family?**: no +- **New cross-domain UI framework/taxonomy?**: no +- **Current operator problem**: Unassigned findings already exist, but there is no single trustworthy place to review and route that shared backlog before it becomes personal work. +- **Existing structure is insufficient because**: Tenant-local findings pages and ad hoc filters do not answer the cross-tenant intake question and do not provide a clean handoff from shared backlog into `My Findings`. +- **Narrowest correct implementation**: One derived intake page with fixed inclusion rules and one self-claim action that reuses the current assignment model and existing finding detail as the deeper workflow surface. +- **Ownership cost**: One cross-tenant queue query, one small queue vocabulary, one claim race-safety rule, and focused regression tests for visibility, claim authorization, and handoff continuity. +- **Alternative intentionally rejected**: A full team workboard, notifications-first intake model, or auto-routing engine was rejected because those shapes add durable workflow machinery before the product has proven the smaller intake queue. +- **Release truth**: Current-release truth. This slice makes existing findings workflow usable before later escalation and hygiene follow-ups land. + +### Compatibility posture + +This feature assumes a pre-production environment. + +Backward compatibility, legacy aliases, migration shims, historical fixtures, and compatibility-specific tests are out of scope unless explicitly required by this spec. + +Canonical replacement is preferred over preservation. + +## Testing / Lane / Runtime Impact *(mandatory for runtime behavior changes)* + +- **Test purpose / classification**: Feature +- **Validation lane(s)**: fast-feedback, confidence +- **Why this classification and these lanes are sufficient**: The change is proven by visible operator behavior on one canonical queue and one claim handoff into an existing surface. Focused feature coverage is sufficient to prove visibility, authorization, claim safety, and queue continuity without introducing browser or heavy-governance cost. +- **New or expanded test families**: Add focused coverage for the intake queue visibility contract, active-tenant prefilter behavior, `Needs triage` slice behavior, positive and negative claim authorization, and post-claim handoff into `My Findings`. +- **Fixture / helper cost impact**: Low to moderate. Tests need one workspace, multiple visible and hidden tenants, memberships, and findings in open and terminal states with explicit owner and assignee combinations. +- **Heavy-family visibility / justification**: none +- **Special surface test profile**: global-context-shell +- **Standard-native relief or required special coverage**: Ordinary feature coverage is sufficient, plus explicit assertions that hidden-tenant findings never leak into rows or filter values, that assigned findings never re-enter intake, that `Needs triage` remains a strict subset of unassigned open work, and that claim removes the row from intake before the operator continues in `My Findings`. +- **Reviewer handoff**: Reviewers must confirm that intake includes only unassigned open findings from visible tenants, that claim reuses the existing assign permission instead of inventing a new one, that stale rows cannot silently overwrite another operator's claim, and that tenant-prefilter empty states explain scope narrowing honestly. +- **Budget / baseline / trend impact**: none +- **Escalation needed**: none +- **Active feature PR close-out entry**: Guardrail +- **Planned validation commands**: + - `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsIntakeQueueTest.php tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php` + - `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsClaimHandoffTest.php` + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - See shared unassigned backlog in one queue (Priority: P1) + +As a tenant operator, I want one shared intake queue across my visible tenants so I can see unassigned open findings before they disappear into tenant-local lists. + +**Why this priority**: This is the core missing workflow slice. If unassigned backlog remains scattered, later claim, escalation, or hygiene work starts from unreliable visibility. + +**Independent Test**: Can be fully tested by seeding multiple visible and hidden tenants with assigned and unassigned findings, then verifying that the intake queue shows only visible unassigned open findings. + +**Acceptance Scenarios**: + +1. **Given** the current user can inspect multiple tenants with unassigned open findings, **When** the user opens the intake queue, **Then** the page shows only those visible unassigned open findings with tenant and urgency context. +2. **Given** an active tenant context exists, **When** the user opens the intake queue, **Then** the queue is prefiltered to that tenant while keeping the shared unassigned-open scope intact. +3. **Given** a finding is already assigned to any user, **When** the intake queue renders, **Then** that finding does not appear even if it is still open or overdue. + +--- + +### User Story 2 - Separate triage-first backlog from later shared backlog (Priority: P1) + +As a tenant manager, I want a fixed `Needs triage` view inside the intake queue so brand-new or reopened unassigned findings are not buried under older shared backlog. + +**Why this priority**: Visibility alone is not enough. The shared queue must also show which rows still need first routing versus which ones are simply waiting for someone to claim them. + +**Independent Test**: Can be fully tested by seeding unassigned findings in `new`, `reopened`, `triaged`, and `in_progress` states, then verifying the difference between the default unassigned view and the `Needs triage` subset. + +**Acceptance Scenarios**: + +1. **Given** unassigned findings exist in `new`, `reopened`, `triaged`, and `in_progress` states, **When** the operator selects `Needs triage`, **Then** only `new` and `reopened` findings remain visible. +2. **Given** the same backlog, **When** the operator selects `Unassigned`, **Then** all unassigned open findings remain visible regardless of open workflow state. +3. **Given** a `reopened` finding is already assigned, **When** the operator selects `Needs triage`, **Then** that finding stays out of intake because the queue is strictly pre-assignment. + +--- + +### User Story 3 - Claim a finding into personal execution (Priority: P2) + +As a tenant operator, I want to claim an item from the shared intake queue so it leaves shared backlog and becomes personal work without opening a separate reassignment workflow first. + +**Why this priority**: This is the smallest action that turns shared backlog into owned execution while keeping the intake surface calm and bounded. + +**Independent Test**: Can be fully tested by claiming an eligible intake item, verifying that assignment changes to the current user, that the row disappears from intake, and that the operator has a clear next step into `My Findings` or the existing finding detail. + +**Acceptance Scenarios**: + +1. **Given** an unassigned open finding is visible in intake and the operator has assign permission, **When** the operator confirms the claim after reviewing the lightweight preview, **Then** the finding assignee becomes the current user, the row leaves intake, and the operator can continue into `My Findings` or the finding detail. +2. **Given** a workspace member can view findings but lacks assign capability, **When** the intake queue renders, **Then** the finding remains inspectable but the operator cannot successfully claim it and the server rejects direct claim attempts with `403`. +3. **Given** another operator claims the same finding after the current queue has already loaded, **When** the current operator attempts to claim the stale row, **Then** the system refuses to overwrite the existing assignee and refreshes the queue truth honestly. + +### Edge Cases + +- A finding may already have an owner but no assignee; it still belongs in intake because active execution is unclaimed. +- An active tenant prefilter may produce an empty queue while other visible tenants still contain intake items; the empty state must explain the tenant boundary instead of claiming that no intake work exists anywhere. +- A `reopened` finding assigned to a user must stay in personal execution surfaces, not re-enter intake, because the queue is strictly pre-assignment. +- Claim attempts can race; the mutation must re-check current assignee server-side and refuse silent overwrite. +- Hidden-tenant or capability-blocked findings must not influence queue rows, counts, tenant filter values, or empty-state hints. + +## Requirements *(mandatory)* + +**Constitution alignment (required):** This feature adds no Microsoft Graph calls and no new long-running work. It introduces one derived read surface and one DB-only claim mutation. Claim intentionally skips `OperationRun` because it is a short tenant-local assignment write, but it MUST present a lightweight pre-commit preview of the exact assignee change, require explicit confirmation before writing, and write an `AuditLog` entry that records actor, workspace, tenant, target finding, and before/after assignment state. + +**Constitution alignment (RBAC-UX):** The feature operates in the admin `/admin` plane for the canonical intake queue and crosses into tenant-context detail routes at `/admin/t/{tenant}/findings/{finding}`. Tenant entitlement is enforced per referenced finding before disclosure and before claim. Non-members or out-of-scope users continue to receive `404`. Workspace members with at least one currently viewable findings scope may open the queue shell, but rows, counts, tenant filter values, and empty-state hints remain derived only from currently authorized tenant findings. Workspace members with no currently viewable findings scope for intake anywhere in the workspace receive `403` on queue access. Members with findings view but lacking findings assign capability may inspect rows but must receive `403` on claim attempts. No raw capability strings, role checks, or second permission system may be introduced. Global search behavior is unchanged. + +**Constitution alignment (UI-FIL-001):** The intake queue must use native Filament page, table, filter, badge, action, notification, and empty-state primitives or existing shared UI helpers. No page-local badge markup, local color language, or custom task-board chrome may be introduced for queue semantics. + +**Constitution alignment (UI-NAMING-001):** The canonical operator-facing vocabulary is `Findings intake`, `Unassigned`, `Needs triage`, `Claim finding`, and `Open my findings`. The page is about findings workflow, not a generic task engine. Terms such as `task`, `work item`, or `queue record` must not replace the finding domain language in primary labels. + +**Constitution alignment (DECIDE-001):** The intake queue is a primary decision surface because it answers the team's first-routing question in one place before work becomes personal. `My Findings` remains the personal execution surface. Default-visible content must be enough to choose whether to claim or open a finding without reconstructing tenant context elsewhere. + +**Constitution alignment (UI-CONST-001 / UI-SURF-001 / ACTSURF-001 / HDR-001):** The intake queue has exactly one primary inspect model: the finding. Row click is required. There is no redundant `View` action. The only visible row mutation shortcut in v1 is `Claim`, because it is the smallest safe handoff into personal execution. Dangerous lifecycle actions remain on the existing tenant finding detail and tenant findings list rather than moving into the queue. + +**Constitution alignment (OPSURF-001):** Default-visible queue content must stay operator-first: finding summary, tenant, severity, lifecycle state, due urgency, owner context, and intake reason before diagnostics. The `Claim` action is a `TenantPilot only` mutation on assignment metadata and does not imply provider-side change. Raw evidence, run context, and exception history remain secondary behind finding detail. + +**Constitution alignment (UI-SEM-001 / LAYER-001 / TEST-TRUTH-001):** Direct reuse of a tenant-local `Unassigned` filter is insufficient because it does not create one workspace-safe shared intake surface or a clear handoff into `My Findings`. This feature still avoids new semantic infrastructure by deriving intake directly from existing open-status, owner, assignee, due-date, and entitlement truth. Tests must prove the business consequences: shared visibility, pre-assignment boundaries, claim safety, and handoff continuity. + +### Functional Requirements + +- **FR-001**: The system MUST provide a canonical shared findings intake queue at `/admin/findings/intake` for the current workspace member. +- **FR-002**: The intake queue MUST include only findings that are in an open workflow status, have no current assignee, and belong to tenants the current user is entitled and currently authorized to inspect. +- **FR-003**: Open workflow status for intake MUST reuse the existing findings contract from Spec 111: `new`, `triaged`, `in_progress`, and `reopened`. +- **FR-004**: The intake queue MUST expose fixed queue views for `Unassigned` and `Needs triage`. `Unassigned` includes all visible intake rows. `Needs triage` is a strict subset limited to visible intake rows in `new` or `reopened` status. +- **FR-005**: Queue rows MUST show at minimum the tenant, finding summary, severity, lifecycle status, due date or overdue state, owner when present, and why the finding is still in intake. +- **FR-006**: Findings that already have an assignee MUST NOT appear in intake, including overdue or reopened findings. Assigned work remains in personal or tenant-local execution surfaces. +- **FR-007**: When an active tenant context exists, the intake queue MUST apply that tenant as a default prefilter and allow the operator to clear only that tenant prefilter to return to all visible tenants. +- **FR-008**: Intake rows, counts, tenant filter values, and queue summary state MUST be derived only from findings the current user is entitled and currently authorized to inspect and MUST NOT leak hidden or capability-blocked tenant scope through labels, counts, filter values, or empty-state hints. +- **FR-009**: Authorized operators with the existing findings assign capability MUST be able to claim an intake item through a lightweight pre-commit preview and explicit confirmation step. Claim sets `assignee = current user`, leaves owner and workflow status unchanged, and writes an audit entry for the assignment change. +- **FR-010**: Successful claim MUST remove the finding from the shared intake queue immediately and provide a clear next step into the existing `My Findings` route or the finding detail view. +- **FR-011**: Members who can inspect findings but lack assign capability MAY open rows from intake but MUST NOT be able to claim them. Server-side enforcement remains `403` for in-scope members lacking capability and `404` for non-members or out-of-scope users. +- **FR-012**: Opening a row from intake MUST navigate to the existing tenant finding detail for the correct tenant and preserve a return path back to intake. +- **FR-013**: The intake queue MUST render calm empty states. If the active tenant prefilter alone causes the queue to become empty while other visible tenants still contain intake items, the empty-state CTA MUST clear the tenant prefilter. If no visible intake items exist at all, the empty state MUST explain that shared backlog is clear and offer one clear CTA into `My Findings`. +- **FR-014**: Claim attempts MUST re-check the current assignee server-side at mutation time and MUST NOT silently overwrite another operator's successful claim. +- **FR-015**: The feature MUST reuse the owner-versus-assignee contract from Spec 219 and MUST NOT introduce a team model, queue-specific lifecycle states, new ownership roles, or a second permission family. +- **FR-016**: Default queue ordering MUST surface urgent intake first: overdue rows first, then `reopened`, then `new`, then remaining unassigned backlog. Within each bucket, rows with due dates sort by `due_at` ascending, rows without due dates sort last, and remaining ties sort by finding ID descending. + +## 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 | +|---|---|---|---|---|---|---|---|---|---|---| +| Findings intake queue | `/admin/findings/intake` | `Clear tenant filter` only when an active tenant prefilter is applied | Full-row open to `/admin/t/{tenant}/findings/{finding}` | `Claim` only when the current user may assign and the finding is still unassigned, with lightweight preview and explicit confirmation before execution | none | `Clear tenant filter` for tenant-prefilter-empty state; otherwise `Open my findings` | n/a | n/a | yes for successful claim | Action Surface Contract satisfied. One inspect model only, no redundant `View`, no dangerous queue actions, and no empty action groups. | + +### Key Entities *(include if feature involves data)* + +- **Intake finding**: An open tenant-owned finding with no current assignee that the current user is entitled and authorized to inspect. +- **Findings intake queue**: A derived canonical shared queue over intake findings that emphasizes first routing before personal execution. +- **Needs triage view**: The strict subset of intake findings that are still in `new` or `reopened` status and therefore need first routing attention. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: In acceptance review, an operator can determine within 10 seconds from `/admin/findings/intake` whether visible unassigned findings exist and whether the current tenant filter is narrowing the queue. +- **SC-002**: 100% of covered automated tests show only visible unassigned open findings in the intake queue and exclude all assigned, terminal, hidden-tenant, or capability-blocked rows. +- **SC-003**: 100% of covered automated tests show that `Needs triage` contains only `new` and `reopened` intake rows while `Unassigned` continues to show the full visible intake backlog. +- **SC-004**: From the intake queue, an authorized operator can claim an eligible finding in one short confirmed flow and the finding leaves shared intake immediately without losing a clear next step into personal execution. + +## Assumptions + +- Spec 111 remains the authoritative contract for findings open-status semantics and due-state behavior. +- Spec 219 remains the authoritative contract for owner-versus-assignee meaning. +- Spec 221 remains the canonical personal destination for claimed finding work. +- The existing tenant finding detail remains the canonical deeper workflow surface for triage, reassignment, resolve, close, and exception actions beyond the new intake claim shortcut. + +## Non-Goals + +- Introduce a full team workboard, team metrics, or capacity planning +- Add notifications, reminders, or escalation from the intake queue +- Add bulk claim, bulk triage, or a second mutation lane on the intake surface +- Introduce automatic routing, load balancing, delegation, or fallback-to-role logic +- Reframe the findings domain as a generic task or ticketing system + +## Dependencies + +- Spec 111, Findings Workflow V2 + SLA, remains the lifecycle and open-status baseline. +- Spec 219, Finding Ownership Semantics Clarification, remains the accountability and assignment baseline. +- Spec 221, Findings Operator Inbox V1, remains the personal execution destination after claim. diff --git a/specs/222-findings-intake-team-queue/tasks.md b/specs/222-findings-intake-team-queue/tasks.md new file mode 100644 index 00000000..526ad296 --- /dev/null +++ b/specs/222-findings-intake-team-queue/tasks.md @@ -0,0 +1,210 @@ +# Tasks: Findings Intake & Team Queue V1 + +**Input**: Design documents from `/specs/222-findings-intake-team-queue/` +**Prerequisites**: `plan.md`, `spec.md`, `research.md`, `data-model.md`, `contracts/findings-intake-team-queue.logical.openapi.yaml`, `quickstart.md` + +**Tests**: Required. This feature changes runtime behavior on a new Filament/Livewire queue surface and a claim mutation path, so Pest coverage must be added in `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php`, `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php`, and `apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php`. +**Operations**: No new `OperationRun` is introduced. The queue remains DB-only and read-first, while `Claim finding` must reuse the existing `finding.assigned` audit flow in `apps/platform/app/Services/Findings/FindingWorkflowService.php`. +**RBAC**: The intake queue lives on the admin `/admin` plane and must preserve workspace chooser or resume behavior when workspace context is missing, workspace-membership `404` semantics for out-of-scope users, tenant-safe row and count disclosure inside the queue, and existing `404` and `403` behavior on drilldown to `/admin/t/{tenant}/findings/{finding}` and claim execution. +**UI / Surface Guardrails**: `Findings intake` remains the primary decision surface for pre-assignment routing. `/admin/findings/my-work` remains the personal execution destination after claim, and the intake queue must not become a second dangerous-action hub. +**Filament UI Action Surfaces**: `FindingsIntakeQueue` gets one primary inspect model, one conditional `Clear tenant filter` header action, one inline safe `Claim finding` row action with lightweight preview and explicit confirmation, no bulk actions, and one empty-state CTA per branch. +**Badges**: Existing finding severity, lifecycle, and due-state semantics remain authoritative. No page-local badge mappings are introduced. + +**Organization**: Tasks are grouped by user story so each slice stays independently testable. Recommended delivery order is `US1 -> US2 -> US3`, because US2 extends the shared queue behavior established in US1, US1 plus US2 make up the recommended first releasable intake slice, and US3 depends on the queue truth from US1 but not on every refinement from US2. + +## Test Governance Checklist + +- [x] Lane assignment is named and is the narrowest sufficient proof for the changed behavior. +- [x] New or changed tests stay in the smallest honest family, and any heavy-governance or browser addition is explicit. +- [x] Shared helpers, factories, seeds, fixtures, and context defaults stay cheap by default; any widening is isolated or documented. +- [x] Planned validation commands cover the change without pulling in unrelated lane cost. +- [x] The declared surface test profile or `standard-native-filament` relief is explicit. +- [x] Any material budget, baseline, trend, or escalation note is recorded in the active spec or PR. + +## Phase 1: Setup (Queue Scaffolding) + +**Purpose**: Prepare the new admin intake files and focused regression suites used across all stories. + +- [x] T001 [P] Create the new intake page scaffold in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` +- [x] T002 [P] Create the new intake page view scaffold in `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php` +- [x] T003 [P] Create focused Pest scaffolding in `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php`, `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php`, and `apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php` + +**Checkpoint**: The new intake surface and focused test files exist and are ready for shared implementation work. + +--- + +## Phase 2: Foundational (Blocking Route And Scope Seams) + +**Purpose**: Establish the canonical admin route, page access shell, and base workspace and tenant scoping every story depends on. + +**⚠️ CRITICAL**: No user story work should begin until this phase is complete. + +- [x] T004 Register `FindingsIntakeQueue` in `apps/platform/app/Providers/Filament/AdminPanelProvider.php` and define the page slug and admin-plane access shell in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` +- [x] T005 Implement workspace-membership gating, visible-tenant resolution, capability-primed tenant disclosure, and active-tenant filter synchronization in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` +- [x] T006 Add foundational page-entry coverage for workspace chooser or resume behavior, non-member `404`, queue-access `403` when no currently viewable findings scope exists, and base queue disclosure boundaries in `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php` + +**Checkpoint**: The canonical intake route exists, the page is workspace-scoped, and tenant-safe base access rules are covered. + +--- + +## Phase 3: User Story 1 - See Shared Unassigned Backlog In One Queue (Priority: P1) + +**Goal**: Give the current user one trustworthy cross-tenant queue for visible unassigned open findings. + +**Independent Test**: Seed multiple visible and hidden tenants with unassigned, assigned, `acknowledged`, and terminal findings, then verify `/admin/findings/intake` shows only visible unassigned rows from `Finding::openStatuses()`. + +### Tests for User Story 1 + +- [x] T007 [P] [US1] Add visible-unassigned queue coverage, active-tenant prefilter behavior, assigned and `acknowledged` exclusion, terminal exclusion, hidden-tenant suppression, and both empty-state branches in `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php` +- [x] T008 [P] [US1] Add workspace-context recovery, positive tenant-safe queue disclosure for members with viewable findings scope, and protected destination authorization coverage in `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php` + +### Implementation for User Story 1 + +- [x] T009 [US1] Implement the base intake query with workspace scope, visible tenant IDs, `assignee_user_id IS NULL`, `Finding::openStatuses()`, and eager-loaded row context in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` +- [x] T010 [US1] Implement tenant, finding summary, severity, lifecycle, due-state, owner-context, and explicit tenant-prefilter-empty versus backlog-clear empty-state rendering with the correct CTA branch in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` and `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php` +- [x] T011 [US1] Implement capability-safe tenant filter options, applied-scope metadata, visible summary counts, and the conditional `Clear tenant filter` header action in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` + +**Checkpoint**: User Story 1 is independently functional and the intake page answers “what is still unassigned right now?” without tenant hopping. + +--- + +## Phase 4: User Story 2 - Separate Triage-First Backlog From Later Shared Backlog (Priority: P1) + +**Goal**: Make the queue distinguish `Needs triage` from the broader unassigned backlog and surface urgent intake in a deterministic order. + +**Independent Test**: Seed unassigned findings in `new`, `reopened`, `triaged`, and `in_progress` states, then verify the difference between `Unassigned` and `Needs triage`, along with overdue and reopened ordering and intake-to-detail continuity. + +### Tests for User Story 2 + +- [x] T012 [P] [US2] Add fixed `Unassigned` versus `Needs triage` coverage, queue-reason rendering, and view-specific count coverage in `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php` +- [x] T013 [US2] Add deterministic urgency ordering and intake-to-detail continuity coverage in `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php` + +### Implementation for User Story 2 + +- [x] T014 [US2] Implement fixed `Unassigned` and `Needs triage` queue views plus derived queue-reason labels in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` and `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php` +- [x] T015 [US2] Implement deterministic overdue, reopened, new, and remaining-backlog ordering plus view-specific summary state in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` +- [x] T016 [US2] Build intake row URLs with `CanonicalNavigationContext` so tenant finding detail preserves `Back to findings intake` continuity from `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` + +**Checkpoint**: User Story 2 is independently functional and the queue now highlights what still needs first routing versus what is simply waiting to be claimed. + +--- + +## Phase 5: User Story 3 - Claim A Finding Into Personal Execution (Priority: P2) + +**Goal**: Let an authorized operator claim a visible intake row into `/admin/findings/my-work` without opening a broader reassignment workflow first. + +**Independent Test**: Claim an eligible intake row, verify assignee becomes the current user, owner and workflow status stay unchanged, the row leaves intake immediately, and a stale or unauthorized claim fails honestly. + +### Tests for User Story 3 + +- [x] T017 [P] [US3] Add claim preview/confirmation, successful claim, audit side-effect, immediate intake removal, `Open my findings` handoff, and stale-row conflict coverage in `apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php` +- [x] T018 [P] [US3] Add members-without-assign-capability claim rejection and inspect-allowed coverage in `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php` + +### Implementation for User Story 3 + +- [x] T019 [US3] Implement the `Claim finding` row action with lightweight pre-commit preview and explicit confirmation, visibility rules, and success or error notifications in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` +- [x] T020 [US3] Add the claim-specific locked-assignee guard while reusing existing assignment audit semantics in `apps/platform/app/Services/Findings/FindingWorkflowService.php` +- [x] T021 [US3] Align post-confirmation claim queue refresh and the personal-work handoff state in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php` and `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php` + +**Checkpoint**: User Story 3 is independently functional and the shared queue now hands work into personal execution without silent overwrite. + +--- + +## Phase 6: Polish & Cross-Cutting Concerns + +**Purpose**: Finish guardrail alignment, formatting, and focused validation across the full feature. + +- [x] T022 Review operator-facing copy, action-surface discipline, and no-bulk-action guardrail alignment in `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php`, `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php`, `apps/platform/app/Providers/Filament/AdminPanelProvider.php`, and `apps/platform/app/Services/Findings/FindingWorkflowService.php` +- [x] T023 Run formatting for `apps/platform/app/Filament/Pages/Findings/FindingsIntakeQueue.php`, `apps/platform/resources/views/filament/pages/findings/findings-intake-queue.blade.php`, `apps/platform/app/Providers/Filament/AdminPanelProvider.php`, `apps/platform/app/Services/Findings/FindingWorkflowService.php`, `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php`, `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php`, and `apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php` with `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` +- [x] T024 Run the focused verification workflow from `specs/222-findings-intake-team-queue/quickstart.md` against `apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php`, `apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php`, and `apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php` + +--- + +## Dependencies & Execution Order + +### Phase Dependencies + +- **Setup (Phase 1)**: Starts immediately and prepares the new page, view, and focused Pest files. +- **Foundational (Phase 2)**: Depends on Setup and blocks all user stories until the canonical route and base access shell exist. +- **User Story 1 (Phase 3)**: Depends on Foundational completion and establishes the base queue behavior required for the first releasable slice. +- **User Story 2 (Phase 4)**: Depends on User Story 1 because it extends the same queue surface with fixed views and ordering behavior and completes the recommended MVP cut. +- **User Story 3 (Phase 5)**: Depends on User Story 1 because claim requires established intake truth, but it does not require User Story 2 to be finished first. +- **Polish (Phase 6)**: Depends on all desired user stories being complete. + +### User Story Dependencies + +- **US1**: No dependencies beyond Foundational. +- **US2**: Builds directly on the intake surface introduced in US1. +- **US3**: Builds on the intake surface and audit-safe assignment semantics from US1, but is independent of the triage-view refinements in US2. + +### Within Each User Story + +- Write the story tests first and confirm they fail before implementation is considered complete. +- Keep page-query and authorization behavior in `FindingsIntakeQueue.php` authoritative before adjusting Blade copy. +- Finish story-level verification before moving to the next priority slice. + +### Parallel Opportunities + +- `T001`, `T002`, and `T003` can run in parallel during Setup. +- `T007` and `T008` can run in parallel for User Story 1. +- `T017` and `T018` can run in parallel for User Story 3. + +--- + +## Parallel Example: User Story 1 + +```bash +# User Story 1 tests in parallel +T007 apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php +T008 apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php +``` + +## Parallel Example: User Story 2 + +```bash +# No recommended parallel split inside US2 after queue-truth coverage was consolidated +T012 apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php +T013 apps/platform/tests/Feature/Findings/FindingsIntakeQueueTest.php +``` + +## Parallel Example: User Story 3 + +```bash +# User Story 3 tests in parallel +T017 apps/platform/tests/Feature/Findings/FindingsClaimHandoffTest.php +T018 apps/platform/tests/Feature/Authorization/FindingsIntakeAuthorizationTest.php +``` + +--- + +## Implementation Strategy + +### MVP First (User Stories 1 And 2) + +1. Complete Phase 1: Setup. +2. Complete Phase 2: Foundational. +3. Complete Phase 3: User Story 1. +4. Complete Phase 4: User Story 2. +5. Validate the intake queue against the focused US1 and US2 tests before widening the slice. + +### Incremental Delivery + +1. Ship US1 to establish the canonical shared intake queue. +2. Add US2 to separate triage-first backlog from later shared backlog. +3. Add US3 to hand eligible rows into `My Findings` safely. +4. Finish with copy review, formatting, and the focused verification pack. + +### Parallel Team Strategy + +1. One contributor can scaffold the page and view while another prepares the focused Pest suites. +2. After Foundational work lands, one contributor can drive queue visibility and another can harden authorization boundaries. +3. Once US1 is stable, US2 queue-view refinements and US3 claim behavior can proceed in parallel if the shared page seam is coordinated. + +--- + +## Notes + +- `[P]` tasks target different files and can be worked independently once upstream blockers are cleared. +- `[US1]`, `[US2]`, and `[US3]` map directly to the feature specification user stories. +- The suggested MVP scope is Phase 1 through Phase 4. +- All implementation tasks above follow the required checklist format with task ID, optional parallel marker, story label where applicable, and exact file paths.