Compare commits

...

4 Commits

Author SHA1 Message Date
acc8947384 feat: harden governance action semantics (#229)
## Summary
- add the Spec 194 governance action catalog, friction classes, reason policies, and regression guards
- align exception, review, evidence, finding, tenant, provider connection, and system run actions to the shared semantics model
- add focused feature, RBAC, audit, unit, and browser coverage, including the tenant detail triage header consistency update

## Verification
- ran the focused Spec 194 verification pack from the quickstart and task plan
- ran targeted tenant triage coverage after the detail-header update
- ran `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`

## Filament Notes
- Filament v5 / Livewire v4 compliance preserved
- provider registration remains in `apps/platform/bootstrap/providers.php`
- globally searchable resources were not changed
- destructive actions remain confirmation-gated and server-authorized
- no new Filament assets were introduced; the existing `cd apps/platform && php artisan filament:assets` deploy step stays unchanged

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #229
2026-04-12 21:21:44 +00:00
efd4f31ba3 docs: add decision-first operating foundations (#228)
## Summary
- add the decision-first operating constitution foundation and update the Spec Kit templates to enforce it
- extend the product roadmap with staged decision-based operating foundations and a later human-in-the-loop autonomous governance lane
- add matching spec candidates for constitution hardening, workflow-first surface classification, and a governance inbox / autonomous governance track

## Testing
- not run (documentation and template changes only)

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #228
2026-04-12 11:09:17 +00:00
68be99e27b docs: amend constitution for action surface discipline (#225)
## Summary
- bump the constitution to v2.2.0 with the new `ACTSURF-001` action-surface discipline rules
- expand the existing UI governance so record/detail/edit headers, monitoring/workbench surfaces, and grouped actions follow explicit hierarchy rules
- sync the Spec Kit plan/spec/tasks templates and the product standards index with the updated constitution gates

## Validation
- verified the edited files have no VS Code problems
- no runtime tests were run because this PR only changes governance/templates/docs

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #225
2026-04-12 10:53:51 +00:00
bef9020159 feat: implement spec 193 monitoring action hierarchy (#227)
## Summary
- codify Spec 193 as an explicit monitoring/workbench surface inventory with validator and guard coverage
- refactor the Finding Exceptions Queue, Operations landing, and tenantless operation viewer into clearer context, navigation, utility, drilldown, and focused-work lanes
- align Alerts, Audit Log, and Alert Deliveries with quiet origin-context handling while preserving calm reference surfaces and the explicit Tenant Diagnostics exception
- add focused feature coverage, guard coverage, browser smoke coverage, and the full spec artifacts for Spec 193

## Verification
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/ActionSurfaceContractTest.php tests/Feature/Guards/ActionSurfaceValidatorTest.php tests/Feature/Guards/Spec193MonitoringSurfaceHierarchyGuardTest.php tests/Feature/OpsUx/OperateHubShellTest.php tests/Feature/Operations/TenantlessOperationRunViewerTest.php tests/Feature/Monitoring/FindingExceptionsQueueHierarchyTest.php tests/Browser/Spec193MonitoringSurfaceHierarchySmokeTest.php`
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- integrated-browser smoke pass over queue, operations, operation detail, alerts, audit log, and tenant diagnostics

## Notes
- Livewire v4 / Filament v5 stack unchanged
- no provider-registration changes; Laravel 11+ provider registration remains in `bootstrap/providers.php`
- no new global-search behavior was introduced
- destructive and governance-changing actions keep their existing confirmation and authorization semantics
- no new assets or migrations were added

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #227
2026-04-12 10:48:00 +00:00
123 changed files with 9245 additions and 2392 deletions

View File

@ -171,6 +171,9 @@ ## Active Technologies
- PostgreSQL via existing baseline, assignment, compare-run, and finding tables; no new persistence planned (191-baseline-compare-operator-mode) - PostgreSQL via existing baseline, assignment, compare-run, and finding tables; no new persistence planned (191-baseline-compare-operator-mode)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `UiEnforcement`, `RelatedNavigationResolver`, `ActionSurfaceValidator`, and page-local Filament action builders (192-record-header-discipline) - PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `UiEnforcement`, `RelatedNavigationResolver`, `ActionSurfaceValidator`, and page-local Filament action builders (192-record-header-discipline)
- PostgreSQL through existing workspace-owned and tenant-owned resource models; no schema change planned (192-record-header-discipline) - PostgreSQL through existing workspace-owned and tenant-owned resource models; no schema change planned (192-record-header-discipline)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `OperateHubShell`, `CanonicalNavigationContext`, `CanonicalAdminTenantFilterState`, `UiEnforcement`, `ActionSurfaceValidator`, and Filament page or resource action builders (193-monitoring-action-hierarchy)
- PostgreSQL through existing workspace-owned and tenant-owned models; no schema change planned (193-monitoring-action-hierarchy)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `UiEnforcement`, existing audit loggers (`AuditLogger`, `WorkspaceAuditLogger`, `SystemConsoleAuditLogger`), existing mutation services (`FindingExceptionService`, `FindingWorkflowService`, `TenantReviewLifecycleService`, `EvidenceSnapshotService`, `OperationRunTriageService`) (194-governance-friction-hardening)
- PHP 8.4.15 (feat/005-bulk-operations) - PHP 8.4.15 (feat/005-bulk-operations)
@ -205,8 +208,8 @@ ## Code Style
PHP 8.4.15: Follow standard conventions PHP 8.4.15: Follow standard conventions
## Recent Changes ## Recent Changes
- 194-governance-friction-hardening: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `UiEnforcement`, existing audit loggers (`AuditLogger`, `WorkspaceAuditLogger`, `SystemConsoleAuditLogger`), existing mutation services (`FindingExceptionService`, `FindingWorkflowService`, `TenantReviewLifecycleService`, `EvidenceSnapshotService`, `OperationRunTriageService`)
- 193-monitoring-action-hierarchy: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `OperateHubShell`, `CanonicalNavigationContext`, `CanonicalAdminTenantFilterState`, `UiEnforcement`, `ActionSurfaceValidator`, and Filament page or resource action builders
- 192-record-header-discipline: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `UiEnforcement`, `RelatedNavigationResolver`, `ActionSurfaceValidator`, and page-local Filament action builders - 192-record-header-discipline: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `UiEnforcement`, `RelatedNavigationResolver`, `ActionSurfaceValidator`, and page-local Filament action builders
- 191-baseline-compare-operator-mode: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `BaselineCompareMatrixBuilder`, `BadgeCatalog`, `CanonicalNavigationContext`, and `UiEnforcement` patterns
- 190-baseline-compare-matrix: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `BaselineCompareService`, `BaselineSnapshotTruthResolver`, `BaselineCompareStats`, `RelatedNavigationResolver`, `CanonicalNavigationContext`, `BadgeCatalog`, and `UiEnforcement` patterns
<!-- MANUAL ADDITIONS START --> <!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END --> <!-- MANUAL ADDITIONS END -->

View File

@ -1,24 +1,37 @@
<!-- <!--
Sync Impact Report Sync Impact Report
- Version change: 2.0.0 -> 2.1.0 - Version change: 2.2.0 -> 2.3.0
- Modified principles: - Modified principles:
- UX-001 (Layout & IA): header action line strengthened from SHOULD to MUST - UI-CONST-001: expanded to make TenantPilot's decision-first
with cross-reference to new HDR-001 governance identity explicit
- UI-REVIEW-001: spec and PR review gates expanded for surface role,
human-in-the-loop justification, workflow-vs-storage IA, and
attention-load reduction
- Immediate Retrofit Priorities: expanded with a classification-first
wave for existing surfaces
- Added sections: - Added sections:
- Header Action Discipline & Contextual Navigation (HDR-001) - Decision-First Operating Model & Progressive Disclosure
(DECIDE-001)
- Removed sections: None - Removed sections: None
- Templates requiring updates: - Templates requiring updates:
- ✅ .specify/memory/constitution.md - ✅ .specify/memory/constitution.md
- ✅ .specify/templates/plan-template.md (Constitution Check: HDR-001 added) - ✅ .specify/templates/plan-template.md (Constitution Check updated for
- ✅ .specify/templates/tasks-template.md (Filament UI section: HDR-001 added) decision-first surface roles, workflow-first IA, and calm-surface
- ⚠ .specify/templates/spec-template.md (no changes needed; existing review)
UI/UX Surface Classification and Operator Surface Contract tables already - ✅ .specify/templates/spec-template.md (surface role classification,
cover header action placement implicitly) operator contract, and requirements updated for decision-first
governance)
- ✅ .specify/templates/tasks-template.md (implementation task guidance
updated for progressive disclosure, single-case context, and
attention-load reduction)
- ✅ docs/product/standards/README.md (Constitution index updated for
DECIDE-001)
- Commands checked: - Commands checked:
- N/A `.specify/templates/commands/*.md` directory is not present in this repo - N/A `.specify/templates/commands/*.md` directory is not present in this repo
- Follow-up TODOs: - Follow-up TODOs:
- None. - Create a dedicated surface / IA classification spec to retrofit
existing surfaces against DECIDE-001.
--> -->
# TenantPilot Constitution # TenantPilot Constitution
@ -318,13 +331,189 @@ ### Operator-Facing UI/UX Constitution v1 (UI-CONST-001)
Purpose and scope Purpose and scope
- This section governs operator-facing admin UI semantics across TenantPilot / TenantAtlas. - This section governs operator-facing admin UI semantics across TenantPilot / TenantAtlas.
- It defines allowed surface types, allowed interaction models, primary/secondary/destructive action hierarchy, list/detail/queue semantics, scope and context signals, canonical navigation and naming rules, visibility of critical operational truth, scanability and density rules, exception handling, and review and enforcement requirements. - It defines decision-first prominence roles, allowed surface types,
allowed interaction models, primary/secondary/destructive action
hierarchy, list/detail/queue semantics, scope and context signals,
canonical navigation and naming rules, visibility of critical
operational truth, scanability and density rules, exception handling,
and review and enforcement requirements.
- It does not govern branding, colors, typography, spacing tokens, marketing or landing pages, implementation details without UX effect, purely cosmetic copy changes, or backend architecture except where backend design would create false UI mental models. - It does not govern branding, colors, typography, spacing tokens, marketing or landing pages, implementation details without UX effect, purely cosmetic copy changes, or backend architecture except where backend design would create false UI mental models.
- This section is governance, not a style guide. Its purpose is to prevent ambiguity, operator risk, and UI drift before they spread through the product. - This section is governance, not a style guide. Its purpose is to prevent ambiguity, operator risk, and UI drift before they spread through the product.
#### Decision-First Operating Model & Progressive Disclosure (DECIDE-001)
Goal: TenantPilot is primarily a governance and decision platform, not
a browser for internal technical detail objects. This section governs
surface prominence and default information depth. It is orthogonal to
UI-SURF-001 and ACTSURF-001: every operator-facing surface MUST declare
both its interaction model and its decision-role prominence.
##### Surface prominence roles
- Every operator-facing surface MUST declare exactly one decision-role
prominence:
- Primary Decision Surface
- Secondary Context Surface
- Tertiary Evidence / Diagnostics Surface
- Decision-role prominence is separate from action-surface class and
detailed surface type.
- Prominence determines what deserves top-level navigation, default
emphasis, and default-visible information depth.
##### Primary surfaces are for human decisions
- Primary Decision Surfaces MUST support a clear human-in-the-loop
moment such as attention prioritization, approval, risk acceptance or
rejection, drift / findings / exception triage, review completion,
evaluation of blocked or failed automations, or execution /
escalation of the next governance action.
- A prominent surface MUST NOT exist primarily to display internal
model objects, raw data, diagnostics, or technical object hubs
without clear operator value.
- Every proposed primary surface MUST answer: what concrete decision or
operator action does this surface support?
##### Detail surfaces are evidence surfaces
- OperationRun detail, evidence detail, policy version detail, audit
log detail, JSON / payload / diff views, and deep diagnostic contexts
are normally Secondary Context or Tertiary Evidence / Diagnostics
surfaces.
- These surfaces remain essential for verification, diagnosis, and
auditability, but they MUST NOT dominate default operator workflows
or primary navigation merely because the underlying objects exist.
##### Default to decisions, not details
- Default-visible information MUST first answer what happened, why it
matters, how urgent it is, what the system recommends, what impact
the decision has, and what action or approval is required now.
- Internal IDs, relation depth, raw payloads, full snapshot history,
debug views, and unstructured technical detail MUST stay secondary
unless they are required for the first decision.
##### Progressive disclosure is the default
- Depth MUST be preserved but revealed on demand through
expand/collapse, drawers, tabs, side panels, explicit "Show details"
affordances, or focused drill-downs from a clear decision context.
- The default workflow SHOULD let the operator decide before navigating
through diagnostic depth.
- Primary flows MUST NOT force operators through multiple technical
subpages before a single governance decision can be made.
##### Navigation follows workflows, not storage structures
- Primary navigation and prominent entry points MUST follow operator
workflows such as pending decisions, alerts / escalations, reviews,
exceptions / accepted risks, governance priorities, and blocked or
failed automations.
- Internal persistence terms such as OperationRuns, EvidenceItems,
PolicyVersions, StoredReports, or relational chains MAY exist as
supporting surfaces, but they do not earn primary information
architecture status by default.
- Every navigation proposal MUST answer: does this reflect a working
task or only an internal storage structure?
##### Meaning comes before model names
- Operator-facing surfaces MUST prefer governance language such as
"Drift detected", "Exception expires soon", "Evidence incomplete",
"Review ready", "Remediation recommended", or "Further review
required".
- Model names, table/entity language, relation terminology, and
implementation-first state labels MUST NOT be the primary UX
language when business meaning can be expressed directly.
##### One case, one decision context
- A single governance case SHOULD be decidable within one focused
context that brings together the problem, risk or relevance,
recommendation, impact, ownership, next action, approval options, and
optional detail beneath or beside the decision.
- Operators MUST NOT be forced to reconstruct one decision across
multiple equal-rank Run, Evidence, Policy, Audit, and Finding pages
when the product can present one coherent decision context.
##### Audit depth is mandatory; dominance is not
- Enterprise-grade evidence, verification, and audit depth MUST remain
available.
- Audit requirements do NOT justify default surfaces that look or
behave like forensic diagnostics consoles.
- The standard operator flow SHOULD remain calm, prioritized, and
decision-led even when deep proof is available.
##### New primary surfaces require strict justification
- Every new top-level or otherwise prominent surface MUST justify:
1. which human-in-the-loop moment it supports,
2. why an existing surface is insufficient,
3. why a drawer, panel, tab, or embedded decision context is
insufficient,
4. what search, review, or click work it removes.
- If those answers are weak, the work MUST reuse an existing decision
context or remain secondary/tertiary.
##### Automation must reduce attention load
- New automation, notification, or autonomous governance behavior MUST
measurably reduce search work, review work, or click load.
- Automation that primarily creates extra lists, statuses, surfaces, or
detail work is non-conformant even if technically correct.
- The review question is: does this make the platform quieter and
clearer, or merely larger?
##### Calm default surfaces
- The default workspace experience MUST distinguish clearly between
immediately actionable work, worth-watching context, and
reference-only information.
- Unranked warning floods, parallel attention entry points, and
perpetual visual escalation are forbidden on primary surfaces.
- A surface that only creates noise instead of priority is
non-conformant.
##### Retrofit requirement
- DECIDE-001 applies to existing as well as new surfaces.
- Existing surfaces MUST be reclassified as Primary Decision,
Secondary Context, or Tertiary Evidence / Diagnostics surfaces and
then reviewed for prominence, disclosure, consolidation, and
workflow alignment.
- Surface retrofit work SHOULD prefer reclassification and
consolidation before creating new navigation branches.
##### Review gate
Every operator-facing spec or PR that changes a surface MUST answer:
1. What concrete decision or operator action does this support?
2. Who is the human in the loop?
3. What MUST be immediately visible for the first decision?
4. What is preserved but only revealed on demand?
5. Is this a Primary Decision Surface, Secondary Context Surface, or
Tertiary Evidence / Diagnostics Surface?
6. If it is primary, why can it not live inside an existing decision
context?
7. Does the navigation reflect a workflow or only storage structure?
8. Does this reduce search, review, or click work?
9. Does this make the product calmer and clearer instead of louder?
#### Surface Taxonomy (UI-SURF-001) #### Surface Taxonomy (UI-SURF-001)
Every new admin surface MUST be assigned exactly one surface type before implementation. Ad-hoc interaction models are forbidden. Every new admin surface MUST be assigned exactly one broad action-surface
class before implementation. Ad-hoc interaction models are forbidden.
The allowed broad action-surface classes are:
- Record / Detail / Edit
- Monitoring / Queue / Workbench
- List / Table / Bulk
- Wizard / Flow
- Utility / System
Operator-facing surfaces MUST also declare exactly one detailed surface
type from the taxonomy below. The broad class determines the action
hierarchy first; the detailed surface type refines it.
##### CRUD / List-first Resource ##### CRUD / List-first Resource
- Purpose: scan, find, open, and selectively mutate many business records. - Purpose: scan, find, open, and selectively mutate many business records.
@ -377,6 +566,157 @@ ##### Detail-first Operational Surface
- Destructive actions: detail header or grouped header actions only, always with confirmation. - Destructive actions: detail header or grouped header actions only, always with confirmation.
- Row click and explicit View/Inspect: not applicable. - Row click and explicit View/Inspect: not applicable.
#### Action Surface Discipline (ACTSURF-001)
Goal: actions across all surfaces MUST make the next sensible operator
step obvious, keep safe navigation distinct from mutation, and prevent
dangerous or governance-relevant actions from sitting casually beside
harmless context changes.
##### Surface class first
- Every new or materially changed surface MUST declare exactly one broad
action-surface class before actions are designed.
- Different surface classes MAY use different action models only when
the difference is deliberate, documented, and justified by the
workflow.
- Detailed surface types refine the rule set; they do not replace the
broad class requirement.
##### Record / Detail / Edit surfaces
- Classic record/detail/edit pages MUST expose at most one visible
primary header action.
- Pure navigation MUST NOT live in the header when it can be placed
inline at summary, field, badge, status, or related-context level.
- Secondary, rare, or administrative actions MUST be grouped.
- Multiple equally weighted mutation buttons in the header are
forbidden.
- Destructive, irreversible, or governance-relevant actions MUST be
clearly separated from routine actions.
- The likely next operator step MUST be recognizable within seconds.
- HDR-001 is the binding specialization for record/detail/edit headers.
##### Monitoring / Queue / Workbench surfaces
- Surface-level context, scope context, navigation, selection actions,
and object actions MUST NOT be mixed as one flat header strip.
- Scope indicators are context signals, not ordinary calls to action.
- Selection-dependent actions SHOULD become prominent only when a
selection or focused object actually exists.
- Record-page header rules MUST NOT be copied blindly onto workbench
surfaces.
- Workbench surfaces MAY use a different action model, but that model
MUST be explicit, repeatable, and internally consistent.
##### List / Table / Bulk surfaces
- Inspect/open affordances MUST remain consistent within the same
surface class.
- Bulk actions are allowed only for genuine multi-record work.
- Row actions MUST NOT dominate reading and scanning.
- Rare, destructive, or governance-relevant actions MUST NOT accumulate
casually in default row actions.
- Tables exist primarily to scan, filter, compare, and decide; they
MUST NOT become unstructured action stockpiles.
##### Wizard / Flow surfaces
- Wizard actions MUST reflect staged progression, explicit back/cancel
semantics, and safe confirmation at the step where risk becomes real.
- Wizard pages MAY expose more than one visible action when the flow
genuinely requires progression, backtracking, or guarded cancellation.
- Even in a wizard, the next primary step MUST remain obvious.
##### Utility / System surfaces
- Utility and system pages MAY use narrower tooling-oriented action
sets, but they MUST still separate safe navigation, routine control,
and dangerous intervention.
- System or recovery status does not justify casual placement of
destructive or governance-changing actions.
##### Action grouping and order
- Actions MUST be ordered by meaning, frequency, and risk.
- The preferred order is:
1. primary next step
2. common secondary action
3. rare or contextual action
4. dangerous or irreversible action
- An `ActionGroup` / More menu is not a junk drawer. Navigation,
mutation, external links, and destructive actions inside a group MUST
still be named, ordered, and separated coherently.
##### Navigation vs mutation
- Navigation and mutation are different intent classes and MUST NOT
appear as equal-weight peers without explicit hierarchy.
- Harmless context switches MUST NOT visually overpower
governance-relevant actions.
- Pure context navigation SHOULD live near the content it concerns
rather than as header filler.
##### Governance friction
- Actions with risk, blast radius, or irreversible effect MUST use
shared governance-friction rules rather than per-surface improvisation.
- Depending on impact, the required friction is confirmation, optional
reason, mandatory reason, typed confirmation, or staged flow.
- Clear danger semantics and separated placement are mandatory for
dangerous or governance-changing actions.
##### Exceptions require explicit reason
- New surfaces MAY deviate only when the surface class or workflow truly
requires it.
- Allowed justification labels are:
- Special type
- Workflow hub
- Wizard
- Utility / System surface
- Another clearly defined exception documented in the governing spec
- "Historically grew this way" and "it was easy to add to the header"
are invalid reasons.
##### Reuse before invention
- New features MUST reuse existing disciplined patterns, reference
architectures, and shared primitives when they fit the chosen surface
class.
- Reference patterns are reuse baselines, not automatic mandates for
every surface.
##### Constitution over convenience
- Local implementation speed MUST NOT override consistent action
hierarchy.
- No new feature may introduce:
- multiple equal-rank header mutations without a clear primary
- navigation as casual header filler
- unreflective mixing of record, workbench, and governance patterns
- new local exceptions without explicit rationale
##### Review gate
Every new or materially changed surface with actions MUST answer:
1. What broad action-surface class is it?
2. What is the one most likely next operator action?
3. Is navigation cleanly separated from mutation?
4. Are rare or risky actions removed from the primary plane?
5. Is the hierarchy scanable in a few seconds?
6. Is this a real special type or just an unordered exception?
If those answers are not clear, the surface is non-conformant.
##### Canonical outcome
- The goal is not the smallest possible number of buttons.
- A conformant surface highlights the next sensible step, separates
context, navigation, mutation, and danger cleanly, remains structured
as capability grows, and applies the same principles consistently
across the product.
#### Hard Rules (UI-HARD-001) #### Hard Rules (UI-HARD-001)
##### Primary inspect model ##### Primary inspect model
@ -509,6 +849,8 @@ #### Filament UI — Action Surface Contract (NON-NEGOTIABLE)
Behavior over declaration Behavior over declaration
- Every spec MUST include both a UI/UX Surface Classification and a UI Action Matrix. - Every spec MUST include both a UI/UX Surface Classification and a UI Action Matrix.
- Every changed operator-facing surface MUST declare its broad
action-surface class and the one most likely next operator action.
- Custom action-surface contracts are legitimate only when they validate rendered behavior, not only declarations or slot counts. - Custom action-surface contracts are legitimate only when they validate rendered behavior, not only declarations or slot counts.
- A change is not Done unless the implemented interaction semantics conform to the declared surface type or an approved exception documents and tests the deviation. - A change is not Done unless the implemented interaction semantics conform to the declared surface type or an approved exception documents and tests the deviation.
@ -532,7 +874,10 @@ #### Filament UI — Layout & Information Architecture Standards (UX-001)
- When records exist, that primary CTA moves to the header and MUST NOT be duplicated in the empty state shell. - When records exist, that primary CTA moves to the header and MUST NOT be duplicated in the empty state shell.
Actions and flows Actions and flows
- Pages MUST expose at most one primary header action and one secondary header action; all others belong in groups (see HDR-001 for the full header discipline rule). - Record / Detail / Edit pages MUST expose at most one visible primary
header action. Any additional visible secondary header action requires
explicit justification under ACTSURF-001 / HDR-001; the rest belong in
groups or contextual placement.
- Multi-step or high-risk flows MUST use a wizard or an equivalent staged flow with preview and confirmation. - Multi-step or high-risk flows MUST use a wizard or an equivalent staged flow with preview and confirmation.
- Destructive actions remain non-primary and confirmed. - Destructive actions remain non-primary and confirmed.
@ -545,9 +890,12 @@ #### Filament UI — Layout & Information Architecture Standards (UX-001)
- Shared layout builders such as `MainAsideForm`, `MainAsideInfolist`, and `StandardTableDefaults` SHOULD be reused where available. - Shared layout builders such as `MainAsideForm`, `MainAsideInfolist`, and `StandardTableDefaults` SHOULD be reused where available.
- A change is not Done unless UX-001 is satisfied or an approved exception documents why not. - A change is not Done unless UX-001 is satisfied or an approved exception documents why not.
#### Header Action Discipline & Contextual Navigation (HDR-001) #### Record / Detail / Edit Header Discipline & Contextual Navigation (HDR-001)
Goal: record, detail, and edit pages MUST be comprehensible within
seconds. HDR-001 is the binding record/detail/edit specialization of
ACTSURF-001.
Goal: record and detail pages MUST be comprehensible within seconds.
Header actions are reserved for the primary workflow of the current page Header actions are reserved for the primary workflow of the current page
and MUST NOT become a dumping ground for every available action or and MUST NOT become a dumping ground for every available action or
navigation jump. navigation jump.
@ -565,6 +913,8 @@ ##### Maximum one primary visible header action
primary visible header action. primary visible header action.
- That action MUST represent the most obvious next operator step on - That action MUST represent the most obvious next operator step on
exactly this page. exactly this page.
- Multiple equally weighted mutation buttons in the header are
forbidden.
##### Navigation does not belong in headers ##### Navigation does not belong in headers
@ -594,6 +944,8 @@ ##### Rare secondary actions belong in an Action Group
or are only occasionally needed MUST NOT appear as equally weighted or are only occasionally needed MUST NOT appear as equally weighted
visible header buttons. visible header buttons.
- They MUST be placed in an Action Group. - They MUST be placed in an Action Group.
- The Action Group itself MUST remain structured; it MUST NOT become an
unlabelled mix of navigation, external links, mutations, and danger.
##### Header clarity over implementation convenience ##### Header clarity over implementation convenience
@ -744,17 +1096,58 @@ #### Spec Scope Fields (SCOPE-002)
#### Enforcement Model (UI-REVIEW-001) #### Enforcement Model (UI-REVIEW-001)
Spec review requirements Spec review requirements
- Every spec that changes an operator-facing surface MUST answer: surface type, primary inspect/open model, row-click rule, whether explicit View/Inspect exists or is forbidden, where secondary actions live, where destructive actions live, canonical collection route, canonical detail route, scope signals and their exact meaning, canonical noun, critical truth visible by default, and whether an exception type is used. - Every spec that changes an operator-facing surface MUST answer:
decision-role prominence, human-in-the-loop moment, immediate-visible
decision information, on-demand evidence/diagnostics boundary,
whether a new primary surface is actually justified, broad
action-surface class, detailed surface type, one likely next operator
action, primary inspect/open model, row-click rule, whether explicit
View/Inspect exists or is forbidden, where navigation lives, where
secondary actions live, where destructive actions live, how grouped
actions are ordered, canonical collection route, canonical detail
route, scope signals and their exact meaning, canonical noun,
critical truth visible by default, workflow-vs-storage IA
justification, attention-load reduction, and whether an exception
type is used.
- Missing any of those answers makes the spec incomplete. - Missing any of those answers makes the spec incomplete.
PR review requirements PR review requirements
- A PR MUST NOT pass when it introduces more than one primary inspect model, redundant View beside row click, destructive inline actions beside inspect on standard lists, empty overflow or bulk groups, long workflow labels in dense rows, misleading scope chips, drifting domain nouns, hidden critical operational truth, or undocumented exceptions without dedicated tests. - A PR MUST NOT pass when it introduces more than one primary inspect
model, redundant View beside row click, destructive inline actions
beside inspect on standard lists, empty overflow or bulk groups, long
workflow labels in dense rows, misleading scope chips, drifting domain
nouns, hidden critical operational truth, flat record headers with
multiple equal-weight mutations, workbench headers that mix scope,
selection, navigation, and object actions as peers, a primary surface
with no clear human-in-the-loop purpose, detail/evidence objects
promoted into primary navigation without justification, one case
fragmented across multiple equal-rank pages, new automation that adds
attention surfaces without reducing operator work, noisy default
surfaces with no action/watch/reference hierarchy, or undocumented
exceptions without dedicated tests.
Guard tests Guard tests
- Repository guards SHOULD validate: declared surface type, conformant primary inspect model, absence of redundant View actions, presence of explicit Inspect on Queue / Review and History / Audit surfaces, absence of empty `ActionGroup` or `BulkActionGroup`, correct placement of destructive actions, truthful scope signals, stable canonical nouns across shells, and dedicated tests for every approved exception. - Repository guards SHOULD validate: declared surface type, declared
decision-role prominence where specs or metadata expose it,
conformant primary inspect model, absence of redundant View actions,
presence of explicit Inspect on Queue / Review and History / Audit
surfaces, absence of empty `ActionGroup` or `BulkActionGroup`,
correct placement of destructive actions, truthful scope signals,
stable canonical nouns across shells, and dedicated tests for every
approved exception.
#### Immediate Retrofit Priorities #### Immediate Retrofit Priorities
Wave 0 - Surface role classification
- First classify existing surfaces as Primary Decision, Secondary
Context, or Tertiary Evidence / Diagnostics surfaces.
- For each surface, determine whether its current prominence is
justified, which detail can move into progressive disclosure, and
whether several technical pages should collapse into one decision
context.
- Wave 0 is done only when primary navigation candidates are grounded
in workflows rather than storage structures.
Wave 1 - Interaction normalization Wave 1 - Interaction normalization
- First fixes target redundant row click plus View, destructive row actions on standard lists, empty overflow or bulk groups, and rows that have become pseudo-control centers. - First fixes target redundant row click plus View, destructive row actions on standard lists, empty overflow or bulk groups, and rows that have become pseudo-control centers.
- First-slice focus surfaces are Tenants, Workspaces, Policies, Alert Deliveries, and other CRUD-first list surfaces with the same drift pattern. - First-slice focus surfaces are Tenants, Workspaces, Policies, Alert Deliveries, and other CRUD-first list surfaces with the same drift pattern.
@ -768,6 +1161,23 @@ #### Immediate Retrofit Priorities
#### Appendix A - One-page Condensed Constitution #### Appendix A - One-page Condensed Constitution
- Every operator-facing surface declares one decision role:
Primary Decision, Secondary Context, or Tertiary Evidence /
Diagnostics.
- Primary surfaces exist to help a human prioritize, judge, approve,
reject, escalate, or act.
- Evidence and diagnostics remain available but do not dominate the
default workflow.
- Default to decisions, not details.
- Progressive disclosure preserves depth without forcing it into the
first decision.
- Navigation follows workflows, not storage structures.
- One governance case should be decidable in one focused context.
- Automation must reduce attention load.
- Default surfaces stay calm, prioritized, and explicit about what is
actionable, worth watching, and reference-only.
- Every new or materially changed surface declares one broad
action-surface class first.
- Every admin surface has one surface type. - Every admin surface has one surface type.
- Every list has exactly one primary inspect/open model. - Every list has exactly one primary inspect/open model.
- CRUD and Registry surfaces use one-click open. - CRUD and Registry surfaces use one-click open.
@ -777,6 +1187,10 @@ #### Appendix A - One-page Condensed Constitution
- Destructive actions never sit openly beside inspect on standard lists. - Destructive actions never sit openly beside inspect on standard lists.
- Overflow is standardized per surface class and is never empty. - Overflow is standardized per surface class and is never empty.
- Bulk exists only when it is genuinely useful. - Bulk exists only when it is genuinely useful.
- Navigation and mutation do not share equal visual weight without
explicit hierarchy.
- Monitoring and workbench surfaces separate scope/context, selection,
navigation, and object actions.
- Scope chips must be truthful. - Scope chips must be truthful.
- Domain nouns are canonical and stable. - Domain nouns are canonical and stable.
- Critical operational truth is default-visible. - Critical operational truth is default-visible.
@ -788,11 +1202,24 @@ #### Appendix A - One-page Condensed Constitution
#### Appendix B - Feature Review Checklist #### Appendix B - Feature Review Checklist
- Surface type is declared. - Decision-role prominence is declared.
- The human-in-the-loop moment is explicit.
- Immediate-visible decision information is explicit.
- On-demand evidence / diagnostics boundaries are explicit.
- Any new primary surface is justified against an existing decision
context.
- Navigation reflects a workflow rather than storage structure.
- One governance case stays decidable in one focused context.
- The feature reduces search, review, or click work.
- The resulting surface is calmer and clearer, not merely larger.
- Broad action-surface class is declared.
- Detailed surface type is declared.
- The one most likely next operator action is explicit.
- Primary inspect/open model is defined. - Primary inspect/open model is defined.
- Row-click rule is decided. - Row-click rule is decided.
- View/Inspect is correctly present or correctly forbidden. - View/Inspect is correctly present or correctly forbidden.
- Edit-as-inspect is used only when allowed. - Edit-as-inspect is used only when allowed.
- Navigation and mutation are separated intentionally.
- Secondary actions are grouped correctly. - Secondary actions are grouped correctly.
- Destructive actions are placed correctly. - Destructive actions are placed correctly.
- Overflow is not empty. - Overflow is not empty.
@ -806,18 +1233,32 @@ #### Appendix B - Feature Review Checklist
- Header passes the 5-second scan rule (HDR-001). - Header passes the 5-second scan rule (HDR-001).
- No pure navigation in the header. - No pure navigation in the header.
- Governance-changing actions have extra friction. - Governance-changing actions have extra friction.
- Any special type or workflow-hub exception is real and justified.
#### Appendix C - Red Flags for Future PRs #### Appendix C - Red Flags for Future PRs
- A primary surface has no clear human-in-the-loop moment.
- A technical object hub is promoted into primary navigation without
workflow justification.
- Default-visible content behaves like a diagnostics console instead of
a decision surface.
- The operator must assemble one decision from multiple equal-rank Run,
Evidence, Policy, Audit, or Finding pages.
- A feature adds automation, alerts, or statuses that increase net
attention load.
- The surface creates more noise than priority.
- Row click and View open the same destination. - Row click and View open the same destination.
- A row becomes a control center. - A row becomes a control center.
- Archive or Delete sits openly beside View or Inspect on a standard list. - Archive or Delete sits openly beside View or Inspect on a standard list.
- More menus or bulk menus are empty. - More menus or bulk menus are empty.
- A More menu becomes a mixed junk drawer with no ordering logic.
- Scope chips have no real scope effect. - Scope chips have no real scope effect.
- Runs and Operations are used as competing primary collection nouns. - Runs and Operations are used as competing primary collection nouns.
- Long workflow labels live in dense tables. - Long workflow labels live in dense tables.
- Edit is used as default inspect even though a true View surface exists. - Edit is used as default inspect even though a true View surface exists.
- Queue surfaces throw the operator out of context through row click. - Queue surfaces throw the operator out of context through row click.
- A workbench surface mixes scope, selection, navigation, and object
actions as one flat header rail.
- Critical health or operability truth is hidden by default. - Critical health or operability truth is hidden by default.
- A contract claims conformance while the rendered UI behaves differently. - A contract claims conformance while the rendered UI behaves differently.
- Header has multiple equally weighted buttons without clear prioritization. - Header has multiple equally weighted buttons without clear prioritization.
@ -893,6 +1334,9 @@ ### Scope, Compliance, and Review Expectations
- This constitution applies across the repo. Feature specs may add stricter constraints but not weaker ones. - This constitution applies across the repo. Feature specs may add stricter constraints but not weaker ones.
- Restore semantics changes require: spec update, checklist update (if applicable), and tests proving safety. - Restore semantics changes require: spec update, checklist update (if applicable), and tests proving safety.
- Specs and PRs that introduce new persisted truth, abstractions, states, DTO/presenter layers, or taxonomies MUST include the proportionality review required by BLOAT-001. - Specs and PRs that introduce new persisted truth, abstractions, states, DTO/presenter layers, or taxonomies MUST include the proportionality review required by BLOAT-001.
- Specs and PRs that change operator-facing surfaces MUST classify each
affected surface under DECIDE-001 and justify any new Primary
Decision Surface or workflow-first navigation change.
- Review and approval MUST favor simplification, replacement, and absorption over additive semantic layering. - Review and approval MUST favor simplification, replacement, and absorption over additive semantic layering.
- Future-release preparation alone is not sufficient justification for new persistence or frameworkization unless security, tenant isolation, auditability, compliance evidence, or queue correctness already require it. - Future-release preparation alone is not sufficient justification for new persistence or frameworkization unless security, tenant isolation, auditability, compliance evidence, or queue correctness already require it.
@ -906,4 +1350,4 @@ ### Versioning Policy (SemVer)
- **MINOR**: new principle/section or materially expanded guidance. - **MINOR**: new principle/section or materially expanded guidance.
- **MAJOR**: removing/redefining principles in a backward-incompatible way. - **MAJOR**: removing/redefining principles in a backward-incompatible way.
**Version**: 2.1.0 | **Ratified**: 2026-01-03 | **Last Amended**: 2026-04-07 **Version**: 2.3.0 | **Ratified**: 2026-01-03 | **Last Amended**: 2026-04-12

View File

@ -58,6 +58,14 @@ ## Constitution Check
- Badge semantics (BADGE-001): status-like badges use `BadgeCatalog` / `BadgeRenderer`; no ad-hoc mappings; new values include tests - Badge semantics (BADGE-001): status-like badges use `BadgeCatalog` / `BadgeRenderer`; no ad-hoc mappings; new values include tests
- Filament-native UI (UI-FIL-001): admin/operator surfaces use native Filament components or shared primitives first; no ad-hoc status UI, local semantic color/border decisions, or hand-built replacements when native/shared semantics exist; any exception is explicitly justified - Filament-native UI (UI-FIL-001): admin/operator surfaces use native Filament components or shared primitives first; no ad-hoc status UI, local semantic color/border decisions, or hand-built replacements when native/shared semantics exist; any exception is explicitly justified
- UI/UX surface taxonomy (UI-CONST-001 / UI-SURF-001): every changed operator-facing surface is classified as exactly one allowed surface type; ad-hoc interaction models are forbidden - UI/UX surface taxonomy (UI-CONST-001 / UI-SURF-001): every changed operator-facing surface is classified as exactly one allowed surface type; ad-hoc interaction models are forbidden
- Decision-first operating model (DECIDE-001): each changed
operator-facing surface is classified as Primary Decision,
Secondary Context, or Tertiary Evidence / Diagnostics; primary
surfaces justify the human-in-the-loop moment, default-visible info
is limited to first-decision needs, deep proof is progressive
disclosed, one governance case stays decidable in one context where
practical, navigation follows workflows not storage structures, and
automation / alerts reduce attention load instead of adding noise
- UI/UX inspect model (UI-HARD-001): each list surface has exactly one primary inspect/open model; redundant View beside row click or identifier click is forbidden; edit-as-inspect is limited to Config-lite resources - UI/UX inspect model (UI-HARD-001): each list surface has exactly one primary inspect/open model; redundant View beside row click or identifier click is forbidden; edit-as-inspect is limited to Config-lite resources
- UI/UX action hierarchy (UI-HARD-001 / UI-EX-001): standard CRUD and Registry rows expose at most one inline safe shortcut; destructive actions are grouped or in the detail header; queue exceptions are catalogued, justified, and tested - UI/UX action hierarchy (UI-HARD-001 / UI-EX-001): standard CRUD and Registry rows expose at most one inline safe shortcut; destructive actions are grouped or in the detail header; queue exceptions are catalogued, justified, and tested
- UI/UX scope, truth, and naming (UI-HARD-001 / UI-NAMING-001 / OPSURF-001): scope signals are truthful, canonical nouns stay stable across shells, critical operational truth is default-visible, and standard lists remain scanable - UI/UX scope, truth, and naming (UI-HARD-001 / UI-NAMING-001 / OPSURF-001): scope signals are truthful, canonical nouns stay stable across shells, critical operational truth is default-visible, and standard lists remain scanable
@ -71,7 +79,14 @@ ## Constitution Check
- Operator surfaces (OPSURF-001): each new or materially refactored operator-facing page defines a page contract covering persona, surface type, operator question, default-visible info, diagnostics-only info, status dimensions, mutation scope, primary actions, and dangerous actions - Operator surfaces (OPSURF-001): each new or materially refactored operator-facing page defines a page contract covering persona, surface type, operator question, default-visible info, diagnostics-only info, status dimensions, mutation scope, primary actions, and dangerous actions
- Filament UI Action Surface Contract: for any new/modified Filament Resource/RelationManager/Page, define Header/Row/Bulk/Empty-State actions, ensure every List/Table has a surface-appropriate inspect affordance, remove redundant View when row click or identifier click already opens the same destination, keep standard CRUD/Registry rows to inspect plus at most one inline safe shortcut, group or relocate the rest to “More” or detail header, forbid empty bulk/overflow groups, require confirmations for destructive actions, write audit logs for mutations, enforce RBAC via central helpers (non-member 404, member missing capability 403), and ensure CI blocks merges if the contract is violated or not explicitly exempted - Filament UI Action Surface Contract: for any new/modified Filament Resource/RelationManager/Page, define Header/Row/Bulk/Empty-State actions, ensure every List/Table has a surface-appropriate inspect affordance, remove redundant View when row click or identifier click already opens the same destination, keep standard CRUD/Registry rows to inspect plus at most one inline safe shortcut, group or relocate the rest to “More” or detail header, forbid empty bulk/overflow groups, require confirmations for destructive actions, write audit logs for mutations, enforce RBAC via central helpers (non-member 404, member missing capability 403), and ensure CI blocks merges if the contract is violated or not explicitly exempted
- Filament UI UX-001 (Layout & IA): Create/Edit uses Main/Aside (3-col grid, Main=columnSpan(2), Aside=columnSpan(1)); all fields inside Sections/Cards (no naked inputs); View uses Infolists (not disabled edit forms); status badges use BADGE-001; empty states have specific title + explanation + 1 CTA; max 1 primary + 1 secondary header action (see HDR-001); tables provide search/sort/filters for core dimensions; shared layout builders preferred for consistency - Filament UI UX-001 (Layout & IA): Create/Edit uses Main/Aside (3-col grid, Main=columnSpan(2), Aside=columnSpan(1)); all fields inside Sections/Cards (no naked inputs); View uses Infolists (not disabled edit forms); status badges use BADGE-001; empty states have specific title + explanation + 1 CTA; max 1 primary + 1 secondary header action (see HDR-001); tables provide search/sort/filters for core dimensions; shared layout builders preferred for consistency
- Header action discipline (HDR-001): record/detail pages expose at most 1 primary visible header action; pure navigation (Open finding, Open tenant, View related run, etc.) is placed at the relevant field/badge/relation, NOT in the header; destructive or governance-changing actions are separated and require friction; rare actions live in Action Groups; every record/detail page passes the 5-second scan rule - Action-surface discipline (ACTSURF-001 / HDR-001): every changed
surface declares one broad action-surface class; the spec names the
one likely next operator action; navigation is separated from
mutation; record/detail/edit pages keep at most one visible primary
header action; monitoring/workbench surfaces separate scope/context,
selection actions, navigation, and object actions; risky or rare
actions are grouped and ordered by meaning/frequency/risk; any special
type or workflow-hub exception is explicit and justified
## Project Structure ## Project Structure
### Documentation (this feature) ### Documentation (this feature)

View File

@ -35,22 +35,37 @@ ## Spec Scope Fields *(mandatory)*
- **Default filter behavior when tenant-context is active**: [e.g., prefilter to current tenant] - **Default filter behavior when tenant-context is active**: [e.g., prefilter to current tenant]
- **Explicit entitlement checks preventing cross-tenant leakage**: [Describe checks] - **Explicit entitlement checks preventing cross-tenant leakage**: [Describe checks]
## Decision-First Surface Role *(mandatory when operator-facing surfaces are changed)*
If this feature adds or materially changes an operator-facing surface,
fill out one row per affected surface. This role is orthogonal to the
Action Surface Class / Surface Type below.
| 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 |
|---|---|---|---|---|---|---|---|
| e.g. Review inbox | Primary Decision Surface | Review and release queued governance work | Case summary, severity, recommendation, required action | Full evidence, raw payloads, audit trail, provider diagnostics | Primary because it is the queue where operators decide and clear work | Follows pending-decisions workflow, not storage objects | Removes search across runs, findings, and audit pages |
## UI/UX Surface Classification *(mandatory when operator-facing surfaces are changed)* ## UI/UX Surface Classification *(mandatory when operator-facing surfaces are changed)*
If this feature adds or materially changes an operator-facing list, detail, queue, audit, config, or report surface, If this feature adds or materially changes an operator-facing list, detail, queue, audit, config, or report surface,
fill out one row per affected surface. fill out one row per affected surface. Declare the broad Action Surface
Class first, then the detailed Surface Type. Keep this table in sync
with the Decision-First Surface Role section above.
| Surface | Surface Type | Primary Inspect/Open Model | Row Click | Secondary Actions Placement | Destructive Actions Placement | Canonical Collection Route | Canonical Detail Route | Scope Signals | Canonical Noun | Critical Truth Visible by Default | Exception Type | | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| e.g. Tenant policies page | CRUD / List-first Resource | Full-row click | required | One inline safe shortcut + More | More / detail header | /admin/t/{tenant}/policies | /admin/t/{tenant}/policies/{record} | Tenant chip scopes rows and actions | Policies / Policy | Policy health, drift, assignment coverage | none | | e.g. Tenant policies page | List / Table / Bulk | CRUD / List-first Resource | Open policy for review | Full-row click | required | One inline safe shortcut + More | More / detail header | /admin/t/{tenant}/policies | /admin/t/{tenant}/policies/{record} | Tenant chip scopes rows and actions | Policies / Policy | Policy health, drift, assignment coverage | none |
## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)* ## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)*
If this feature adds a new operator-facing page or materially refactors one, fill out one row per affected page/surface. If this feature adds a new operator-facing page or materially refactors
one, fill out one row per affected page/surface. The contract MUST show
how one governance case or operator task becomes decidable without
unnecessary cross-page reconstruction.
| Surface | Primary Persona | Surface Type | Primary Operator Question | Default-visible Information | Diagnostics-only Information | Status Dimensions Used | Mutation Scope | Primary Actions | Dangerous Actions | | 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 |
|---|---|---|---|---|---|---|---|---|---| |---|---|---|---|---|---|---|---|---|---|---|
| e.g. Tenant policies page | Tenant operator | List/detail | What needs action right now? | Policy health, drift, assignment coverage | Raw payloads, provider IDs, low-level API details | lifecycle, data completeness, governance result | TenantPilot only / Microsoft tenant / simulation only | Sync policies, View policy | Restore policy | | e.g. Tenant policies page | Tenant operator | Decide whether policy state needs follow-up | List/detail | What needs action right now? | Policy health, drift, assignment coverage | Raw payloads, provider IDs, low-level API details | lifecycle, data completeness, governance result | TenantPilot only / Microsoft tenant / simulation only | Sync policies, View policy | Restore policy |
## Proportionality Review *(mandatory when structural complexity is introduced)* ## Proportionality Review *(mandatory when structural complexity is introduced)*
@ -199,19 +214,50 @@ ## Requirements *(mandatory)*
- how the same domain vocabulary is preserved across button labels, modal titles, run titles, notifications, and audit prose, - how the same domain vocabulary is preserved across button labels, modal titles, run titles, notifications, and audit prose,
- and how implementation-first terms are kept out of primary operator-facing labels. - and how implementation-first terms are kept out of primary operator-facing labels.
**Constitution alignment (UI-CONST-001 / UI-SURF-001 / UI-HARD-001 / UI-EX-001 / UI-REVIEW-001):** If this feature adds or changes an operator-facing surface, the spec MUST describe: **Constitution alignment (DECIDE-001):** If this feature adds or changes operator-facing surfaces, the spec MUST describe:
- the chosen surface type and why it is the correct classification, - whether each affected surface is a Primary Decision Surface,
Secondary Context Surface, or Tertiary Evidence / Diagnostics
Surface, and why,
- which human-in-the-loop moment each primary surface supports,
- what MUST be visible immediately for the first decision,
- what is preserved but only revealed on demand,
- why any new primary surface cannot live inside an existing decision
context,
- how navigation follows operator workflows rather than storage
structures,
- how one governance case remains decidable in one focused context,
- how any new automation, notifications, or autonomous governance logic
reduce search/review/click load,
- and how the resulting default experience is calmer and clearer rather
than merely larger.
**Constitution alignment (UI-CONST-001 / UI-SURF-001 / ACTSURF-001 / UI-HARD-001 / UI-EX-001 / UI-REVIEW-001 / HDR-001):** If this feature adds or changes an operator-facing surface, the spec MUST describe:
- the chosen broad action-surface class and why it is the correct classification,
- the chosen detailed surface type and why it is the correct refinement,
- the one most likely next operator action,
- the one and only primary inspect/open model, - the one and only primary inspect/open model,
- whether row click is required, allowed, or forbidden, - whether row click is required, allowed, or forbidden,
- whether explicit View or Inspect is present, and why it is present or forbidden, - whether explicit View or Inspect is present, and why it is present or forbidden,
- where pure navigation lives and why it is not competing with mutation,
- where secondary actions live, - where secondary actions live,
- where destructive actions live, - where destructive actions live,
- how grouped actions are ordered by meaning, frequency, and risk,
- the canonical collection route and canonical detail route, - the canonical collection route and canonical detail route,
- the scope signals shown to the operator and what real effect each one has, - the scope signals shown to the operator and what real effect each one has,
- the canonical noun used across routes, labels, runs, notifications, and audit prose, - the canonical noun used across routes, labels, runs, notifications, and audit prose,
- which critical operational truth is visible by default, - which critical operational truth is visible by default,
- and any catalogued exception type, rationale, and dedicated test coverage. - and any catalogued exception type, rationale, and dedicated test coverage.
**Constitution alignment (ACTSURF-001 - action hierarchy):** If this
feature adds or materially changes header actions, row actions, bulk
actions, or workbench controls, the spec MUST describe:
- how navigation, mutation, context signals, selection actions, and
dangerous actions are separated,
- why any visible secondary action deserves primary-plane placement,
- why any ActionGroup is structured rather than a mixed catch-all,
- and why any workflow-hub, wizard, system, or other special-type
exception is genuine rather than a convenience shortcut.
**Constitution alignment (OPSURF-001):** If this feature adds or materially refactors an operator-facing surface, the spec MUST describe: **Constitution alignment (OPSURF-001):** If this feature adds or materially refactors an operator-facing surface, the spec MUST describe:
- how the default-visible content stays operator-first on `/admin` and avoids raw implementation detail, - how the default-visible content stays operator-first on `/admin` and avoids raw implementation detail,
- which diagnostics are secondary and how they are explicitly revealed, - which diagnostics are secondary and how they are explicitly revealed,

View File

@ -39,30 +39,62 @@ # Tasks: [FEATURE NAME]
- aligning button labels, modal titles, run titles, notifications, and audit prose to the same domain vocabulary, - aligning button labels, modal titles, run titles, notifications, and audit prose to the same domain vocabulary,
- removing implementation-first wording from primary operator-facing copy. - removing implementation-first wording from primary operator-facing copy.
**Operator Surfaces**: If this feature adds or materially refactors an operator-facing page or flow, tasks MUST include: **Operator Surfaces**: If this feature adds or materially refactors an operator-facing page or flow, tasks MUST include:
- classifying each affected surface as Primary Decision, Secondary
Context, or Tertiary Evidence / Diagnostics and keeping that role in
sync with the governing spec,
- defining the human-in-the-loop moment and justifying any new Primary
Decision Surface against existing decision contexts,
- filling the specs UI/UX Surface Classification for every affected surface, - filling the specs UI/UX Surface Classification for every affected surface,
- filling the specs Operator Surface Contract for every affected page, - filling the specs Operator Surface Contract for every affected page,
- keeping default-visible content limited to first-decision needs and
moving proof, payloads, and diagnostics into progressive disclosure,
- making default-visible content operator-first and moving JSON payloads, raw IDs, internal field names, provider error details, and low-level metadata into explicitly revealed diagnostics surfaces, - making default-visible content operator-first and moving JSON payloads, raw IDs, internal field names, provider error details, and low-level metadata into explicitly revealed diagnostics surfaces,
- keeping each governance case decidable in one focused context where
practical instead of forcing cross-page reconstruction,
- modeling execution outcome, data completeness, governance result, and lifecycle/readiness as distinct status dimensions when applicable, - modeling execution outcome, data completeness, governance result, and lifecycle/readiness as distinct status dimensions when applicable,
- making mutation scope legible before execution for every state-changing action (`TenantPilot only`, `Microsoft tenant`, or `simulation only`), - making mutation scope legible before execution for every state-changing action (`TenantPilot only`, `Microsoft tenant`, or `simulation only`),
- implementing the safe-execution flow for dangerous actions (configuration, safety checks/simulation, preview, hard confirmation where required, execute) or documenting an approved exemption, - implementing the safe-execution flow for dangerous actions (configuration, safety checks/simulation, preview, hard confirmation where required, execute) or documenting an approved exemption,
- keeping canonical nouns stable across routes, buttons, run titles, notifications, and audit prose, - keeping canonical nouns stable across routes, buttons, run titles, notifications, and audit prose,
- keeping navigation aligned to operator workflows rather than storage
structures,
- ensuring new automation, alerts, or autonomous flows reduce
search/review/click load instead of adding noise, extra lists, or
extra detail work,
- preserving a calm, prioritized default state that distinguishes
actionable work from worth-watching context and reference-only
information,
- keeping scope signals truthful and ensuring critical operational truth is visible by default, - keeping scope signals truthful and ensuring critical operational truth is visible by default,
- keeping standard CRUD / Registry rows scanable rather than prose-heavy, - keeping standard CRUD / Registry rows scanable rather than prose-heavy,
- keeping workspace and tenant context explicit in navigation, actions, and page semantics so tenant pages do not silently expose workspace-wide actions. - keeping workspace and tenant context explicit in navigation, actions, and page semantics so tenant pages do not silently expose workspace-wide actions.
**Filament UI Action Surfaces**: If this feature adds/modifies any Filament Resource / RelationManager / Page, tasks MUST include: **Filament UI Action Surfaces**: If this feature adds/modifies any Filament Resource / RelationManager / Page, tasks MUST include:
- filling the specs “UI Action Matrix” for all changed surfaces, - filling the specs “UI Action Matrix” for all changed surfaces,
- assigning exactly one broad action-surface class to every changed
operator-facing surface and keeping the detailed surface type in sync
with the spec,
- identifying the one likely next operator action for each changed
surface and shaping the visible hierarchy around it,
- implementing required action surfaces (header/row/bulk/empty-state CTA for lists; header actions for view; consistent save/cancel on create/edit), - implementing required action surfaces (header/row/bulk/empty-state CTA for lists; header actions for view; consistent save/cancel on create/edit),
- ensuring every List/Table has exactly one primary inspect/open model with the correct surface-appropriate affordance, - ensuring every List/Table has exactly one primary inspect/open model with the correct surface-appropriate affordance,
- removing redundant View/Inspect actions when row click or identifier click already opens the same destination, - removing redundant View/Inspect actions when row click or identifier click already opens the same destination,
- keeping standard CRUD / Registry rows to inspect/open plus at most one inline safe shortcut, - keeping standard CRUD / Registry rows to inspect/open plus at most one inline safe shortcut,
- separating navigation from mutation so pure context changes do not
compete visually with state-changing actions,
- moving additional secondary actions into More or the detail header, - moving additional secondary actions into More or the detail header,
- ordering visible actions and grouped actions by meaning, frequency,
and risk rather than append order,
- placing destructive actions in More or the detail header for standard lists and using catalogued exceptions only where allowed, - placing destructive actions in More or the detail header for standard lists and using catalogued exceptions only where allowed,
- ensuring workbench and monitoring surfaces separate scope/context,
selection actions, navigation, and object actions instead of mixing
them into one flat header zone,
- grouping bulk actions via BulkActionGroup, - grouping bulk actions via BulkActionGroup,
- preventing empty `ActionGroup` / `BulkActionGroup` placeholders, - preventing empty `ActionGroup` / `BulkActionGroup` placeholders,
- adding confirmations for destructive actions (and typed confirmation where required by scale), - adding confirmations for destructive actions (and typed confirmation where required by scale),
- adding `AuditLog` entries for relevant mutations, - adding `AuditLog` entries for relevant mutations,
- using native Filament components or shared UI primitives before any local Blade/Tailwind assembly for badges, alerts, buttons, and semantic status surfaces, - using native Filament components or shared UI primitives before any local Blade/Tailwind assembly for badges, alerts, buttons, and semantic status surfaces,
- avoiding page-local semantic color, border, rounding, or highlight styling when Filament props or shared primitives can express the same state, - avoiding page-local semantic color, border, rounding, or highlight styling when Filament props or shared primitives can express the same state,
- documenting any workflow-hub, wizard, utility/system, or other
special-type exception in the spec/PR and adding dedicated test
coverage,
- documenting any catalogued UI exception in the spec/PR and adding dedicated test coverage, - documenting any catalogued UI exception in the spec/PR and adding dedicated test coverage,
- documenting any UI-FIL-001 exception with rationale in the spec/PR, - documenting any UI-FIL-001 exception with rationale in the spec/PR,
- adding/updated tests that enforce the contract and block merge on violations, OR documenting an explicit exemption with rationale. - adding/updated tests that enforce the contract and block merge on violations, OR documenting an explicit exemption with rationale.
@ -71,8 +103,13 @@ # Tasks: [FEATURE NAME]
- ensuring all form fields are inside Sections/Cards (no naked inputs at root schema level), - ensuring all form fields are inside Sections/Cards (no naked inputs at root schema level),
- ensuring View pages use Infolists (not disabled edit forms); status badges use BADGE-001, - ensuring View pages use Infolists (not disabled edit forms); status badges use BADGE-001,
- ensuring empty states show a specific title + explanation + exactly 1 CTA; non-empty tables move CTA to header, - ensuring empty states show a specific title + explanation + exactly 1 CTA; non-empty tables move CTA to header,
- capping header actions to max 1 primary + 1 secondary (rest grouped), - enforcing ACTSURF-001 / HDR-001 action discipline: record/detail/edit
- enforcing HDR-001 header action discipline: at most 1 primary visible action per record/detail page; pure navigation (Open finding, Open tenant, View related run, etc.) placed at the relevant field/badge/relation, NOT in the header; destructive or governance-changing actions separated and requiring friction; rare actions in Action Groups; every record/detail page passing the 5-second scan rule, pages keep at most 1 visible primary header action; pure navigation
moves to contextual placement; destructive or governance-changing
actions are separated and require friction; monitoring/workbench
surfaces use their own layered hierarchy; rare actions live in
structured Action Groups; every affected surface passes the few-second
scan rule,
- using shared layout builders (e.g., `MainAsideForm`, `MainAsideInfolist`, `StandardTableDefaults`) where available, - using shared layout builders (e.g., `MainAsideForm`, `MainAsideInfolist`, `StandardTableDefaults`) where available,
- OR documenting an explicit exemption with rationale if UX-001 is not fully satisfied. - OR documenting an explicit exemption with rationale if UX-001 is not fully satisfied.
**Badges**: If this feature changes status-like badge semantics, tasks MUST use `BadgeCatalog` / `BadgeRenderer` (BADGE-001), **Badges**: If this feature changes status-like badge semantics, tasks MUST use `BadgeCatalog` / `BadgeRenderer` (BADGE-001),

View File

@ -289,7 +289,9 @@ public function refreshMatrix(): void
{ {
$user = auth()->user(); $user = auth()->user();
abort_unless($user instanceof User, 403); if (! $user instanceof User) {
abort(403);
}
/** @var BaselineProfile $profile */ /** @var BaselineProfile $profile */
$profile = $this->getRecord(); $profile = $this->getRecord();

View File

@ -12,6 +12,10 @@
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Navigation\CanonicalNavigationContext; use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use BackedEnum; use BackedEnum;
use Filament\Actions\Action; use Filament\Actions\Action;
@ -37,6 +41,16 @@ class Alerts extends Page
protected string $view = 'filament.pages.monitoring.alerts'; protected string $view = 'filament.pages.monitoring.alerts';
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
{
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport)
->satisfy(ActionSurfaceSlot::ListHeader, 'Header keeps alerts scope and origin navigation quiet on the page-level overview.')
->exempt(ActionSurfaceSlot::InspectAffordance, 'The alerts overview is a page-level monitoring summary and does not inspect records inline.')
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The alerts overview does not render row-level secondary actions.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The alerts overview does not expose bulk actions.')
->exempt(ActionSurfaceSlot::ListEmptyState, 'The overview always renders KPI widgets and downstream drilldown navigation instead of a list-style empty state.');
}
public static function canAccess(): bool public static function canAccess(): bool
{ {
if (Filament::getCurrentPanel()?->getId() !== 'admin') { if (Filament::getCurrentPanel()?->getId() !== 'admin') {

View File

@ -17,6 +17,7 @@
use App\Support\Filament\FilterOptionCatalog; use App\Support\Filament\FilterOptionCatalog;
use App\Support\Filament\FilterPresets; use App\Support\Filament\FilterPresets;
use App\Support\Filament\TablePaginationProfiles; use App\Support\Filament\TablePaginationProfiles;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\Navigation\RelatedNavigationResolver; use App\Support\Navigation\RelatedNavigationResolver;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration; use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
@ -93,7 +94,6 @@ public function mount(): void
if ($requestedEventId !== null) { if ($requestedEventId !== null) {
$this->resolveAuditLog($requestedEventId); $this->resolveAuditLog($requestedEventId);
$this->selectedAuditLogId = $requestedEventId; $this->selectedAuditLogId = $requestedEventId;
$this->mountTableAction('inspect', (string) $requestedEventId);
} }
} }
@ -102,10 +102,24 @@ public function mount(): void
*/ */
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
return app(OperateHubShell::class)->headerActions( $actions = app(OperateHubShell::class)->headerActions(
scopeActionName: 'operate_hub_scope_audit_log', scopeActionName: 'operate_hub_scope_audit_log',
returnActionName: 'operate_hub_return_audit_log', returnActionName: 'operate_hub_return_audit_log',
); );
$navigationContext = CanonicalNavigationContext::fromRequest(request());
if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
array_splice($actions, 1, 0, [
Action::make('operate_hub_back_to_origin_audit_log')
->label($navigationContext->backLinkLabel)
->icon('heroicon-o-arrow-left')
->color('gray')
->url($navigationContext->backLinkUrl),
]);
}
return $actions;
} }
public function table(Table $table): Table public function table(Table $table): Table

View File

@ -25,9 +25,11 @@
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use BackedEnum; use BackedEnum;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Textarea; use Filament\Forms\Components\Textarea;
@ -164,34 +166,38 @@ protected function getHeaderActions(): array
return FindingExceptionResource::getUrl('index', panel: 'tenant', tenant: $tenant); return FindingExceptionResource::getUrl('index', panel: 'tenant', tenant: $tenant);
}); });
$actions[] = Action::make('clear_selected_exception') $selectedContextActions = [
->label('Close details') Action::make('clear_selected_exception')
->color('gray') ->label('Close details')
->visible(fn (): bool => $this->selectedFindingExceptionId !== null) ->color('gray')
->action(function (): void { ->visible(fn (): bool => $this->selectedFindingExceptionId !== null)
$this->selectedFindingExceptionId = null; ->action(function (): void {
$this->showSelectedExceptionSummary = false; $this->clearSelectedException();
}); }),
$actions[] = Action::make('open_selected_exception') Action::make('open_selected_exception')
->label('Open tenant detail') ->label('Open tenant detail')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->selectedFindingExceptionId !== null) ->visible(fn (): bool => $this->selectedFindingExceptionId !== null)
->url(fn (): ?string => $this->selectedExceptionUrl()); ->url(fn (): ?string => $this->selectedExceptionUrl()),
$actions[] = Action::make('open_selected_finding') Action::make('open_selected_finding')
->label('Open finding') ->label('Open finding')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->selectedFindingExceptionId !== null) ->visible(fn (): bool => $this->selectedFindingExceptionId !== null)
->url(fn (): ?string => $this->selectedFindingUrl()); ->url(fn (): ?string => $this->selectedFindingUrl()),
];
$actions[] = Action::make('approve_selected_exception') $selectedDecisionActions = [
->label('Approve exception') Action::make('approve_selected_exception')
->label(GovernanceActionCatalog::rule('approve_exception')->canonicalLabel)
->color('success') ->color('success')
->visible(fn (): bool => $this->selectedFindingException()?->isPending() ?? false) ->visible(fn (): bool => $this->selectedFindingException()?->isPending() ?? false)
->requiresConfirmation() ->requiresConfirmation()
->modalHeading(GovernanceActionCatalog::rule('approve_exception')->modalHeading)
->modalDescription(GovernanceActionCatalog::rule('approve_exception')->modalDescription)
->form([ ->form([
DateTimePicker::make('effective_from') DateTimePicker::make('effective_from')
->label('Effective from') ->label('Effective from')
@ -204,6 +210,7 @@ protected function getHeaderActions(): array
Textarea::make('approval_reason') Textarea::make('approval_reason')
->label('Approval reason') ->label('Approval reason')
->rows(3) ->rows(3)
->required()
->maxLength(2000), ->maxLength(2000),
]) ])
->action(function (array $data, FindingExceptionService $service): void { ->action(function (array $data, FindingExceptionService $service): void {
@ -220,41 +227,56 @@ protected function getHeaderActions(): array
$this->resetTable(); $this->resetTable();
Notification::make() Notification::make()
->title($wasRenewalRequest ? 'Exception renewed' : 'Exception approved') ->title($wasRenewalRequest ? 'Exception renewed' : GovernanceActionCatalog::rule('approve_exception')->successTitle)
->success() ->success()
->send(); ->send();
}); }),
$actions[] = Action::make('reject_selected_exception') Action::make('reject_selected_exception')
->label('Reject exception') ->label(GovernanceActionCatalog::rule('reject_exception')->canonicalLabel)
->color('danger') ->color('warning')
->visible(fn (): bool => $this->selectedFindingException()?->isPending() ?? false) ->visible(fn (): bool => $this->selectedFindingException()?->isPending() ?? false)
->requiresConfirmation() ->requiresConfirmation()
->form([ ->modalHeading(GovernanceActionCatalog::rule('reject_exception')->modalHeading)
Textarea::make('rejection_reason') ->modalDescription(GovernanceActionCatalog::rule('reject_exception')->modalDescription)
->label('Rejection reason') ->form([
->rows(3) Textarea::make('rejection_reason')
->required() ->label('Rejection reason')
->maxLength(2000), ->rows(3)
]) ->required()
->action(function (array $data, FindingExceptionService $service): void { ->maxLength(2000),
$record = $this->selectedFindingException(); ])
$user = auth()->user(); ->action(function (array $data, FindingExceptionService $service): void {
$record = $this->selectedFindingException();
$user = auth()->user();
if (! $record instanceof FindingException || ! $user instanceof User) { if (! $record instanceof FindingException || ! $user instanceof User) {
abort(404); abort(404);
} }
$wasRenewalRequest = $record->isPendingRenewal(); $wasRenewalRequest = $record->isPendingRenewal();
$updated = $service->reject($record, $user, $data); $updated = $service->reject($record, $user, $data);
$this->selectedFindingExceptionId = (int) $updated->getKey(); $this->selectedFindingExceptionId = (int) $updated->getKey();
$this->resetTable(); $this->resetTable();
Notification::make() Notification::make()
->title($wasRenewalRequest ? 'Renewal rejected' : 'Exception rejected') ->title($wasRenewalRequest ? 'Renewal rejected' : GovernanceActionCatalog::rule('reject_exception')->successTitle)
->success() ->success()
->send(); ->send();
}); }),
];
$actions[] = ActionGroup::make($selectedContextActions)
->label('Selected context')
->icon('heroicon-o-rectangle-stack')
->color('gray')
->visible(fn (): bool => $this->selectedFindingExceptionId !== null);
$actions[] = ActionGroup::make($selectedDecisionActions)
->label('Review selected')
->icon('heroicon-o-shield-check')
->color('primary')
->visible(fn (): bool => $this->selectedFindingException()?->isPending() ?? false);
return $actions; return $actions;
} }
@ -409,6 +431,12 @@ public function selectedFindingUrl(): ?string
return FindingResource::getUrl('view', ['record' => $record->finding], panel: 'tenant', tenant: $record->tenant); return FindingResource::getUrl('view', ['record' => $record->finding], panel: 'tenant', tenant: $record->tenant);
} }
public function clearSelectedException(): void
{
$this->selectedFindingExceptionId = null;
$this->showSelectedExceptionSummary = false;
}
/** /**
* @return array<int, Tenant> * @return array<int, Tenant>
*/ */

View File

@ -142,6 +142,49 @@ protected function getHeaderActions(): array
return $actions; return $actions;
} }
/**
* @return array{
* scope_label: string,
* scope_body: string,
* return_label: ?string,
* return_body: ?string,
* scope_reset_label: ?string,
* scope_reset_body: ?string,
* inspect_body: string
* }
*/
public function landingHierarchySummary(): array
{
$operateHubShell = app(OperateHubShell::class);
$navigationContext = $this->navigationContext();
$activeTenant = $operateHubShell->activeEntitledTenant(request());
$returnLabel = null;
$returnBody = null;
if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
$returnLabel = $navigationContext->backLinkLabel;
$returnBody = 'Return to the originating monitoring surface without competing with the current tab, filters, or row inspection flow.';
} elseif ($activeTenant instanceof Tenant) {
$returnLabel = 'Back to '.$activeTenant->name;
$returnBody = 'Return to the tenant dashboard when you need tenant-specific context outside this workspace monitoring landing.';
}
return [
'scope_label' => $operateHubShell->scopeLabel(request()),
'scope_body' => $activeTenant instanceof Tenant
? 'The landing is currently narrowed to one tenant inside the active workspace.'
: 'The landing is currently showing workspace-wide monitoring across all entitled tenants.',
'return_label' => $returnLabel,
'return_body' => $returnBody,
'scope_reset_label' => $activeTenant instanceof Tenant ? 'Show all tenants' : null,
'scope_reset_body' => $activeTenant instanceof Tenant
? 'Reset the landing back to workspace-wide monitoring when tenant-specific context is no longer needed.'
: null,
'inspect_body' => 'Open a run from the table to enter the canonical monitoring detail viewer.',
];
}
private function navigationContext(): ?CanonicalNavigationContext private function navigationContext(): ?CanonicalNavigationContext
{ {
if (! is_array($this->navigationContextPayload)) { if (! is_array($this->navigationContextPayload)) {

View File

@ -123,7 +123,7 @@ protected function getHeaderActions(): array
$actions[] = Action::make('refresh') $actions[] = Action::make('refresh')
->label('Refresh') ->label('Refresh')
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('gray') ->color('primary')
->url(fn (): string => isset($this->run) ->url(fn (): string => isset($this->run)
? OperationRunLinks::tenantlessView($this->run, $navigationContext) ? OperationRunLinks::tenantlessView($this->run, $navigationContext)
: route('admin.operations.index')); : route('admin.operations.index'));
@ -155,6 +155,57 @@ protected function getHeaderActions(): array
return $actions; return $actions;
} }
/**
* @return array{
* scope_label: string,
* scope_body: string,
* navigation_label: string,
* navigation_body: string,
* utility_body: string,
* related_body: string,
* follow_up_body: string,
* follow_up_label: ?string
* }
*/
public function monitoringDetailSummary(): array
{
$operateHubShell = app(OperateHubShell::class);
$navigationContext = $this->navigationContext();
$activeTenant = $operateHubShell->activeEntitledTenant(request());
$runTenantId = isset($this->run) ? (int) ($this->run->tenant_id ?? 0) : 0;
$navigationLabel = 'Back to Operations';
$navigationBody = 'Return to the operations landing when this review is complete.';
if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
$navigationLabel = $navigationContext->backLinkLabel;
$navigationBody = 'Return to the originating surface while keeping refresh and follow-up work separate from navigation.';
} elseif ($activeTenant instanceof Tenant && (int) $activeTenant->getKey() === $runTenantId) {
$navigationLabel = 'Back to '.$activeTenant->name;
$navigationBody = 'Return to the active tenant dashboard, then widen back to the workspace view only when you need broader monitoring context.';
}
$relatedLabels = array_values(array_keys($this->relatedLinks()));
$relatedBody = $relatedLabels === []
? 'Open keeps secondary drilldowns grouped under one control when downstream context exists.'
: 'Open keeps secondary drilldowns grouped under one control: '.implode(', ', $relatedLabels).'.';
$followUpLabel = $this->canResumeCapture() ? 'Resume capture' : null;
return [
'scope_label' => $operateHubShell->scopeLabel(request()),
'scope_body' => 'The current workspace or tenant scope remains visible without behaving like a primary task action.',
'navigation_label' => $navigationLabel,
'navigation_body' => $navigationBody,
'utility_body' => 'Refresh keeps the current run state accurate without changing scope.',
'related_body' => $relatedBody,
'follow_up_body' => $followUpLabel !== null
? 'Resume capture only appears when this run supports additional evidence collection.'
: 'No run-specific follow-up is currently available.',
'follow_up_label' => $followUpLabel,
];
}
public function mount(OperationRun $run): void public function mount(OperationRun $run): void
{ {
$user = auth()->user(); $user = auth()->user();
@ -364,6 +415,7 @@ private function resumeCaptureAction(): Action
return Action::make('resumeCapture') return Action::make('resumeCapture')
->label('Resume capture') ->label('Resume capture')
->icon('heroicon-o-forward') ->icon('heroicon-o-forward')
->color('primary')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading('Resume capture') ->modalHeading('Resume capture')
->modalDescription('This will start a follow-up operation to capture remaining baseline evidence for this scope.') ->modalDescription('This will start a follow-up operation to capture remaining baseline evidence for this scope.')
@ -532,9 +584,16 @@ private function relatedLinks(bool $fresh = false): array
$resolver = app(RelatedNavigationResolver::class); $resolver = app(RelatedNavigationResolver::class);
return $fresh $links = $fresh
? $resolver->operationLinksFresh($this->run, $this->relatedLinksTenant()) ? $resolver->operationLinksFresh($this->run, $this->relatedLinksTenant())
: $resolver->operationLinks($this->run, $this->relatedLinksTenant()); : $resolver->operationLinks($this->run, $this->relatedLinksTenant());
unset(
$links[OperationRunLinks::collectionLabel()],
$links[OperationRunLinks::openCollectionLabel()],
);
return $links;
} }
private function lifecycleAttentionSummary(bool $fresh = false): ?string private function lifecycleAttentionSummary(bool $fresh = false): ?string

View File

@ -94,7 +94,7 @@ protected function getHeaderActions(): array
->color('gray') ->color('gray')
->visible(fn (): bool => $this->hasActiveFilters()) ->visible(fn (): bool => $this->hasActiveFilters())
->action(function (): void { ->action(function (): void {
$this->resetTable(); $this->clearRegisterFilters();
}), }),
]; ];
} }
@ -209,7 +209,7 @@ public function table(Table $table): Table
->label('Clear filters') ->label('Clear filters')
->icon('heroicon-o-x-mark') ->icon('heroicon-o-x-mark')
->color('gray') ->color('gray')
->action(fn (): mixed => $this->resetTable()), ->action(fn (): mixed => $this->clearRegisterFilters()),
]); ]);
} }
@ -311,9 +311,29 @@ private function applyRequestedTenantPrefilter(): void
private function hasActiveFilters(): bool private function hasActiveFilters(): bool
{ {
$filters = array_filter((array) $this->tableFilters); return $this->currentTenantFilterId() !== null
|| is_string(data_get($this->tableFilters, 'status.value'))
|| is_string(data_get($this->tableFilters, 'completeness_state.value'))
|| is_string(data_get($this->tableFilters, 'published_state.value'))
|| filled(data_get($this->tableFilters, 'review_date.from'))
|| filled(data_get($this->tableFilters, 'review_date.until'));
}
return $filters !== []; private function clearRegisterFilters(): void
{
app(WorkspaceContext::class)->clearLastTenantId(request());
$this->removeTableFilters();
}
private function currentTenantFilterId(): ?int
{
$tenantFilter = data_get($this->tableFilters, 'tenant_id.value');
if (! is_numeric($tenantFilter)) {
$tenantFilter = data_get(session()->get($this->getTableFiltersSessionKey(), []), 'tenant_id.value');
}
return is_numeric($tenantFilter) ? (int) $tenantFilter : null;
} }
private function workspace(): ?Workspace private function workspace(): ?Workspace

View File

@ -6,7 +6,9 @@
use App\Filament\Resources\AlertDeliveryResource; use App\Filament\Resources\AlertDeliveryResource;
use App\Support\Filament\CanonicalAdminTenantFilterState; use App\Support\Filament\CanonicalAdminTenantFilterState;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
class ListAlertDeliveries extends ListRecords class ListAlertDeliveries extends ListRecords
@ -22,9 +24,23 @@ public function mount(): void
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
return app(OperateHubShell::class)->headerActions( $actions = app(OperateHubShell::class)->headerActions(
scopeActionName: 'operate_hub_scope_alerts', scopeActionName: 'operate_hub_scope_alerts',
returnActionName: 'operate_hub_return_alerts', returnActionName: 'operate_hub_return_alerts',
); );
$navigationContext = CanonicalNavigationContext::fromRequest(request());
if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
array_splice($actions, 1, 0, [
Action::make('operate_hub_back_to_origin_alert_deliveries')
->label($navigationContext->backLinkLabel)
->icon('heroicon-o-arrow-left')
->color('gray')
->url($navigationContext->backLinkUrl),
]);
}
return $actions;
} }
} }

View File

@ -69,7 +69,7 @@ private function captureAction(): Action
->label($label) ->label($label)
->icon('heroicon-o-camera') ->icon('heroicon-o-camera')
->color('primary') ->color('primary')
->hidden(fn (): bool => $this->profileHasConsumableSnapshot()) ->hidden(fn (): bool => $this->shouldHideCaptureAction())
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($label) ->modalHeading($label)
->modalDescription($modalDescription) ->modalDescription($modalDescription)
@ -469,6 +469,15 @@ private function profileHasConsumableSnapshot(): bool
return $profile->resolveCurrentConsumableSnapshot() !== null; return $profile->resolveCurrentConsumableSnapshot() !== null;
} }
private function shouldHideCaptureAction(): bool
{
if (! $this->profileHasConsumableSnapshot()) {
return false;
}
return $this->getEligibleCompareTenantOptions() !== [];
}
private function compareAssignedTenantsDisabledReason(): ?string private function compareAssignedTenantsDisabledReason(): ?string
{ {
/** @var BaselineProfile $profile */ /** @var BaselineProfile $profile */

View File

@ -31,11 +31,13 @@
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthEnvelope; use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthEnvelope;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter; use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter;
use BackedEnum; use BackedEnum;
use Filament\Actions; use Filament\Actions;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Forms\Components\Textarea;
use Filament\Infolists\Components\RepeatableEntry; use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry; use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry; use Filament\Infolists\Components\ViewEntry;
@ -314,21 +316,36 @@ public static function table(Table $table): Table
Actions\ActionGroup::make([ Actions\ActionGroup::make([
UiEnforcement::forTableAction( UiEnforcement::forTableAction(
Actions\Action::make('expire') Actions\Action::make('expire')
->label('Expire snapshot') ->label(GovernanceActionCatalog::rule('expire_snapshot')->canonicalLabel)
->color('danger') ->color('danger')
->hidden(fn (EvidenceSnapshot $record): bool => ! static::canExpireRecord($record)) ->hidden(fn (EvidenceSnapshot $record): bool => ! static::canExpireRecord($record))
->requiresConfirmation() ->requiresConfirmation()
->action(function (EvidenceSnapshot $record): void { ->modalHeading(GovernanceActionCatalog::rule('expire_snapshot')->modalHeading)
->modalDescription(GovernanceActionCatalog::rule('expire_snapshot')->modalDescription)
->form([
Textarea::make('expiration_reason')
->label('Expiry reason')
->rows(4)
->required()
->maxLength(2000),
])
->action(function (EvidenceSnapshot $record, array $data): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
abort(403); abort(403);
} }
app(EvidenceSnapshotService::class)->expire($record, $user); app(EvidenceSnapshotService::class)->expire(
$record,
$user,
(string) ($data['expiration_reason'] ?? ''),
);
static::truthEnvelope($record->refresh(), fresh: true); static::truthEnvelope($record->refresh(), fresh: true);
Notification::make()->success()->title('Snapshot expired')->send(); Notification::make()->success()->title(
GovernanceActionCatalog::rule('expire_snapshot')->successTitle,
)->send();
}), }),
fn (EvidenceSnapshot $record): EvidenceSnapshot => $record, fn (EvidenceSnapshot $record): EvidenceSnapshot => $record,
) )

View File

@ -9,7 +9,9 @@
use App\Services\Evidence\EvidenceSnapshotService; use App\Services\Evidence\EvidenceSnapshotService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Rbac\UiEnforcement; use App\Support\Rbac\UiEnforcement;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use Filament\Actions; use Filament\Actions;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord; use Filament\Resources\Pages\ViewRecord;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@ -25,14 +27,19 @@ protected function resolveRecord(int|string $key): Model
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
$refreshRule = GovernanceActionCatalog::rule('refresh_evidence');
$expireRule = GovernanceActionCatalog::rule('expire_snapshot');
return [ return [
UiEnforcement::forAction( UiEnforcement::forAction(
Actions\Action::make('refresh_snapshot') Actions\Action::make('refresh_evidence')
->label('Refresh evidence') ->label($refreshRule->canonicalLabel)
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('primary') ->color('primary')
->requiresConfirmation() ->requiresConfirmation()
->action(function (): void { ->modalHeading($refreshRule->modalHeading)
->modalDescription($refreshRule->modalDescription)
->action(function () use ($refreshRule): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
@ -41,29 +48,42 @@ protected function getHeaderActions(): array
app(EvidenceSnapshotService::class)->refresh($this->record, $user); app(EvidenceSnapshotService::class)->refresh($this->record, $user);
Notification::make()->success()->title('Refresh evidence queued')->send(); Notification::make()->success()->title($refreshRule->successTitle)->send();
}), }),
) )
->requireCapability(Capabilities::EVIDENCE_MANAGE) ->requireCapability(Capabilities::EVIDENCE_MANAGE)
->apply(), ->apply(),
UiEnforcement::forAction( UiEnforcement::forAction(
Actions\Action::make('expire_snapshot') Actions\Action::make('expire_snapshot')
->label('Expire snapshot') ->label($expireRule->canonicalLabel)
->icon('heroicon-o-x-circle') ->icon('heroicon-o-x-circle')
->color('danger') ->color('danger')
->hidden(fn (): bool => ! EvidenceSnapshotResource::canExpireRecord($this->record)) ->hidden(fn (): bool => ! EvidenceSnapshotResource::canExpireRecord($this->record))
->requiresConfirmation() ->requiresConfirmation()
->action(function (): void { ->modalHeading($expireRule->modalHeading)
->modalDescription($expireRule->modalDescription)
->form([
Textarea::make('expiration_reason')
->label('Expiry reason')
->rows(4)
->required()
->maxLength(2000),
])
->action(function (array $data) use ($expireRule): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
abort(403); abort(403);
} }
app(EvidenceSnapshotService::class)->expire($this->record, $user); app(EvidenceSnapshotService::class)->expire(
$this->record,
$user,
(string) ($data['expiration_reason'] ?? ''),
);
$this->refreshFormData(['status', 'expires_at']); $this->refreshFormData(['status', 'expires_at']);
Notification::make()->success()->title('Snapshot expired')->send(); Notification::make()->success()->title($expireRule->successTitle)->send();
}), }),
) )
->requireCapability(Capabilities::EVIDENCE_MANAGE) ->requireCapability(Capabilities::EVIDENCE_MANAGE)

View File

@ -10,6 +10,7 @@
use App\Models\User; use App\Models\User;
use App\Services\Findings\FindingExceptionService; use App\Services\Findings\FindingExceptionService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Repeater;
@ -32,9 +33,12 @@ protected function resolveRecord(int|string $key): Model
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
$renewRule = GovernanceActionCatalog::rule('renew_exception');
$revokeRule = GovernanceActionCatalog::rule('revoke_exception');
return [ return [
Action::make('renew_exception') Action::make('renew_exception')
->label('Renew exception') ->label($renewRule->canonicalLabel)
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('primary') ->color('primary')
->visible(fn (): bool => $this->canManageRecord() && $this->getRecord() instanceof FindingException && $this->getRecord()->canBeRenewed()) ->visible(fn (): bool => $this->canManageRecord() && $this->getRecord() instanceof FindingException && $this->getRecord()->canBeRenewed())
@ -42,6 +46,8 @@ protected function getHeaderActions(): array
'owner_user_id' => $this->getRecord() instanceof FindingException ? $this->getRecord()->owner_user_id : null, 'owner_user_id' => $this->getRecord() instanceof FindingException ? $this->getRecord()->owner_user_id : null,
]) ])
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($renewRule->modalHeading)
->modalDescription($renewRule->modalDescription)
->form([ ->form([
Select::make('owner_user_id') Select::make('owner_user_id')
->label('Owner') ->label('Owner')
@ -84,7 +90,7 @@ protected function getHeaderActions(): array
->defaultItems(0) ->defaultItems(0)
->collapsed(), ->collapsed(),
]) ])
->action(function (array $data, FindingExceptionService $service): void { ->action(function (array $data, FindingExceptionService $service) use ($renewRule): void {
$record = $this->getRecord(); $record = $this->getRecord();
$user = auth()->user(); $user = auth()->user();
@ -105,18 +111,20 @@ protected function getHeaderActions(): array
} }
Notification::make() Notification::make()
->title('Renewal request submitted') ->title($renewRule->successTitle)
->success() ->success()
->send(); ->send();
$this->refreshFormData(['status', 'current_validity_state', 'review_due_at']); $this->refreshFormData(['status', 'current_validity_state', 'review_due_at']);
}), }),
Action::make('revoke_exception') Action::make('revoke_exception')
->label('Revoke exception') ->label($revokeRule->canonicalLabel)
->icon('heroicon-o-no-symbol') ->icon('heroicon-o-no-symbol')
->color('danger') ->color('danger')
->visible(fn (): bool => $this->canManageRecord() && $this->getRecord() instanceof FindingException && $this->getRecord()->canBeRevoked()) ->visible(fn (): bool => $this->canManageRecord() && $this->getRecord() instanceof FindingException && $this->getRecord()->canBeRevoked())
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($revokeRule->modalHeading)
->modalDescription($revokeRule->modalDescription)
->form([ ->form([
Textarea::make('revocation_reason') Textarea::make('revocation_reason')
->label('Revocation reason') ->label('Revocation reason')
@ -124,7 +132,7 @@ protected function getHeaderActions(): array
->required() ->required()
->maxLength(2000), ->maxLength(2000),
]) ])
->action(function (array $data, FindingExceptionService $service): void { ->action(function (array $data, FindingExceptionService $service) use ($revokeRule): void {
$record = $this->getRecord(); $record = $this->getRecord();
$user = auth()->user(); $user = auth()->user();
@ -145,7 +153,7 @@ protected function getHeaderActions(): array
} }
Notification::make() Notification::make()
->title('Exception revoked') ->title($revokeRule->successTitle)
->success() ->success()
->send(); ->send();

View File

@ -33,6 +33,7 @@
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use BackedEnum; use BackedEnum;
use Filament\Actions; use Filament\Actions;
use Filament\Actions\BulkAction; use Filament\Actions\BulkAction;
@ -1121,8 +1122,10 @@ public static function table(Table $table): Table
BulkAction::make('close_selected') BulkAction::make('close_selected')
->label('Close selected') ->label('Close selected')
->icon('heroicon-o-x-circle') ->icon('heroicon-o-x-circle')
->color('danger') ->color('warning')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading(GovernanceActionCatalog::rule('close_finding')->modalHeading)
->modalDescription(GovernanceActionCatalog::rule('close_finding')->modalDescription)
->form([ ->form([
Textarea::make('closed_reason') Textarea::make('closed_reason')
->label('Close reason') ->label('Close reason')
@ -1441,13 +1444,17 @@ public static function resolveAction(): Actions\Action
public static function closeAction(): Actions\Action public static function closeAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('close_finding');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('close') Actions\Action::make('close')
->label('Close') ->label($rule->canonicalLabel)
->icon('heroicon-o-x-circle') ->icon('heroicon-o-x-circle')
->color('danger') ->color('warning')
->visible(fn (Finding $record): bool => $record->hasOpenStatus()) ->visible(fn (Finding $record): bool => $record->hasOpenStatus())
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->form([ ->form([
Textarea::make('closed_reason') Textarea::make('closed_reason')
->label('Close reason') ->label('Close reason')
@ -1455,10 +1462,10 @@ public static function closeAction(): Actions\Action
->required() ->required()
->maxLength(255), ->maxLength(255),
]) ])
->action(function (Finding $record, array $data, FindingWorkflowService $workflow): void { ->action(function (Finding $record, array $data, FindingWorkflowService $workflow) use ($rule): void {
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: 'Finding closed', successTitle: $rule->successTitle,
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->close( callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->close(
$finding, $finding,
$tenant, $tenant,
@ -1537,16 +1544,20 @@ public static function requestExceptionAction(): Actions\Action
public static function renewExceptionAction(): Actions\Action public static function renewExceptionAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('renew_exception');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('renew_exception') Actions\Action::make('renew_exception')
->label('Renew exception') ->label($rule->canonicalLabel)
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('warning') ->color('primary')
->visible(fn (Finding $record): bool => static::loadedFindingException($record)?->canBeRenewed() ?? false) ->visible(fn (Finding $record): bool => static::loadedFindingException($record)?->canBeRenewed() ?? false)
->fillForm(fn (Finding $record): array => [ ->fillForm(fn (Finding $record): array => [
'owner_user_id' => static::loadedFindingException($record)?->owner_user_id, 'owner_user_id' => static::loadedFindingException($record)?->owner_user_id,
]) ])
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->form([ ->form([
Select::make('owner_user_id') Select::make('owner_user_id')
->label('Owner') ->label('Owner')
@ -1601,13 +1612,17 @@ public static function renewExceptionAction(): Actions\Action
public static function revokeExceptionAction(): Actions\Action public static function revokeExceptionAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('revoke_exception');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('revoke_exception') Actions\Action::make('revoke_exception')
->label('Revoke exception') ->label($rule->canonicalLabel)
->icon('heroicon-o-no-symbol') ->icon('heroicon-o-no-symbol')
->color('danger') ->color('danger')
->visible(fn (Finding $record): bool => static::loadedFindingException($record)?->canBeRevoked() ?? false) ->visible(fn (Finding $record): bool => static::loadedFindingException($record)?->canBeRevoked() ?? false)
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->form([ ->form([
Textarea::make('revocation_reason') Textarea::make('revocation_reason')
->label('Revocation reason') ->label('Revocation reason')
@ -1627,18 +1642,34 @@ public static function revokeExceptionAction(): Actions\Action
public static function reopenAction(): Actions\Action public static function reopenAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('reopen_finding');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('reopen') Actions\Action::make('reopen')
->label('Reopen') ->label($rule->canonicalLabel)
->icon('heroicon-o-arrow-uturn-left') ->icon('heroicon-o-arrow-uturn-left')
->color('warning') ->color('primary')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->visible(fn (Finding $record): bool => Finding::isTerminalStatus((string) $record->status)) ->visible(fn (Finding $record): bool => Finding::isTerminalStatus((string) $record->status))
->action(function (Finding $record, FindingWorkflowService $workflow): void { ->form([
Textarea::make('reopen_reason')
->label('Reopen reason')
->rows(3)
->required()
->maxLength(255),
])
->action(function (Finding $record, array $data, FindingWorkflowService $workflow) use ($rule): void {
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: 'Finding reopened', successTitle: $rule->successTitle,
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->reopen($finding, $tenant, $user), callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->reopen(
$finding,
$tenant,
$user,
(string) ($data['reopen_reason'] ?? ''),
),
); );
}) })
) )

View File

@ -199,738 +199,26 @@ protected function getHeaderActions(): array
->tooltip('You do not have permission to view provider connections.') ->tooltip('You do not have permission to view provider connections.')
->preserveVisibility() ->preserveVisibility()
->apply(), ->apply(),
ProviderConnectionResource::makeCheckConnectionAction(),
UiEnforcement::forAction( ProviderConnectionResource::makeInventorySyncAction(),
Action::make('check_connection') ProviderConnectionResource::makeComplianceSnapshotAction(),
->label('Check connection') ProviderConnectionResource::makeSetDefaultAction(),
->icon('heroicon-o-check-badge') ProviderConnectionResource::makeEnableDedicatedOverrideAction(
->color('success') source: 'provider_connection.edit_page',
->visible(function (ProviderConnection $record): bool { modalDescription: 'Dedicated credentials are stored encrypted and reset consent to the dedicated app registration.',
$tenant = $this->currentTenant(); ),
$user = auth()->user(); ProviderConnectionResource::makeRotateDedicatedCredentialAction(
modalDescription: 'Stores a replacement dedicated client secret and refreshes dedicated identity state.',
return $tenant instanceof Tenant ),
&& $user instanceof User ProviderConnectionResource::makeDeleteDedicatedCredentialAction(
&& $user->canAccessTenant($tenant) modalDescription: 'Deletes the dedicated credential and leaves the connection blocked until a replacement is added or the type is reverted.',
&& (bool) $record->is_enabled; ),
}) ProviderConnectionResource::makeRevertToPlatformAction(
->action(function (ProviderConnection $record, StartVerification $verification): void { source: 'provider_connection.edit_page',
$tenant = $this->currentTenant(); modalDescription: 'Reverts the connection to the platform-managed identity and removes any dedicated credential.',
$user = auth()->user(); ),
ProviderConnectionResource::makeEnableConnectionAction(),
if (! $tenant instanceof Tenant) { ProviderConnectionResource::makeDisableConnectionAction(),
abort(404);
}
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($tenant)) {
abort(404);
}
$initiator = $user;
$result = $verification->providerConnectionCheck(
tenant: $tenant,
connection: $record,
initiator: $initiator,
);
if ($result->status === 'scope_busy') {
Notification::make()
->title('Scope busy')
->body('Another provider operation is already running for this connection.')
->warning()
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
Action::make('manage_connections')
->label('Manage Provider Connections')
->url(ProviderConnectionResource::getUrl('index', tenant: $tenant)),
])
->send();
return;
}
if ($result->status === 'deduped') {
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
Action::make('manage_connections')
->label('Manage Provider Connections')
->url(ProviderConnectionResource::getUrl('index', tenant: $tenant)),
])
->send();
return;
}
if ($result->status === 'blocked') {
$reasonCode = is_string($result->run->context['reason_code'] ?? null)
? (string) $result->run->context['reason_code']
: 'unknown_error';
$reasonEnvelope = app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forOperationRun($result->run, 'notification');
$bodyLines = $reasonEnvelope?->toBodyLines() ?? ['Blocked by provider configuration.'];
Notification::make()
->title('Connection check blocked')
->body(implode("\n", $bodyLines))
->warning()
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
Action::make('manage_connections')
->label('Manage Provider Connections')
->url(ProviderConnectionResource::getUrl('index', tenant: $tenant)),
])
->send();
return;
}
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::queuedToast((string) $result->run->type)
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
})
)
->preserveVisibility()
->requireCapability(Capabilities::PROVIDER_RUN)
->apply(),
UiEnforcement::forAction(
Action::make('enable_dedicated_override')
->label('Enable dedicated override')
->icon('heroicon-o-key')
->color('primary')
->requiresConfirmation()
->modalDescription('Dedicated credentials are stored encrypted and reset consent to the dedicated app registration.')
->visible(fn (ProviderConnection $record): bool => $tenant instanceof Tenant
&& $record->connection_type !== ProviderConnectionType::Dedicated)
->form([
TextInput::make('client_id')
->label('Dedicated app (client) ID')
->required()
->maxLength(255),
TextInput::make('client_secret')
->label('Dedicated client secret')
->password()
->required()
->maxLength(255),
])
->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->enableDedicatedOverride(
connection: $record,
clientId: (string) $data['client_id'],
clientSecret: (string) $data['client_secret'],
);
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.connection_type_changed',
context: [
'metadata' => [
'provider_connection_id' => (int) $record->getKey(),
'provider' => $record->provider,
'entra_tenant_id' => $record->entra_tenant_id,
'from_connection_type' => ProviderConnectionType::Platform->value,
'to_connection_type' => ProviderConnectionType::Dedicated->value,
'client_id' => (string) $data['client_id'],
'source' => 'provider_connection.edit_page',
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $record->getKey(),
status: 'success',
);
Notification::make()
->title('Dedicated override enabled')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('rotate_dedicated_credential')
->label('Rotate dedicated credential')
->icon('heroicon-o-arrow-path')
->color('primary')
->requiresConfirmation()
->modalDescription('Stores a replacement dedicated client secret and refreshes dedicated identity state.')
->visible(fn (ProviderConnection $record): bool => $tenant instanceof Tenant
&& $record->connection_type === ProviderConnectionType::Dedicated)
->form([
TextInput::make('client_id')
->label('Dedicated app (client) ID')
->default(function (ProviderConnection $record): string {
$payload = $record->credential?->payload;
return is_array($payload) ? (string) ($payload['client_id'] ?? '') : '';
})
->required()
->maxLength(255),
TextInput::make('client_secret')
->label('Dedicated client secret')
->password()
->required()
->maxLength(255),
])
->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->enableDedicatedOverride(
connection: $record,
clientId: (string) $data['client_id'],
clientSecret: (string) $data['client_secret'],
);
Notification::make()
->title('Dedicated credential rotated')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('delete_dedicated_credential')
->label('Delete dedicated credential')
->icon('heroicon-o-trash')
->color('danger')
->requiresConfirmation()
->modalDescription('Deletes the dedicated credential and leaves the connection blocked until a replacement is added or the type is reverted.')
->visible(fn (ProviderConnection $record): bool => $tenant instanceof Tenant
&& $record->connection_type === ProviderConnectionType::Dedicated
&& $record->credential()->exists())
->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->deleteDedicatedCredential($record);
Notification::make()
->title('Dedicated credential deleted')
->warning()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('revert_to_platform')
->label('Revert to platform')
->icon('heroicon-o-arrow-uturn-left')
->color('gray')
->requiresConfirmation()
->modalDescription('Reverts the connection to the platform-managed identity and removes any dedicated credential.')
->visible(fn (ProviderConnection $record): bool => $tenant instanceof Tenant
&& $record->connection_type === ProviderConnectionType::Dedicated)
->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->revertToPlatform($record);
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.connection_type_changed',
context: [
'metadata' => [
'provider_connection_id' => (int) $record->getKey(),
'provider' => $record->provider,
'entra_tenant_id' => $record->entra_tenant_id,
'from_connection_type' => ProviderConnectionType::Dedicated->value,
'to_connection_type' => ProviderConnectionType::Platform->value,
'source' => 'provider_connection.edit_page',
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $record->getKey(),
status: 'success',
);
Notification::make()
->title('Connection reverted to platform')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('set_default')
->label('Set as default')
->icon('heroicon-o-star')
->color('primary')
->requiresConfirmation()
->visible(fn (ProviderConnection $record): bool => $tenant instanceof Tenant
&& (bool) $record->is_enabled
&& ! $record->is_default
&& ProviderConnection::query()
->where('tenant_id', $tenant->getKey())
->where('provider', $record->provider)
->count() > 1)
->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
abort(404);
}
$record->makeDefault();
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.default_set',
context: [
'metadata' => [
'provider' => $record->provider,
'entra_tenant_id' => $record->entra_tenant_id,
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $record->getKey(),
status: 'success',
);
Notification::make()
->title('Default connection updated')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE)
->tooltip('You do not have permission to manage provider connections.')
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('inventory_sync')
->label('Inventory sync')
->icon('heroicon-o-arrow-path')
->color('info')
->visible(function (ProviderConnection $record): bool {
$tenant = $this->currentTenant();
$user = auth()->user();
return $tenant instanceof Tenant
&& $user instanceof User
&& $user->canAccessTenant($tenant)
&& (bool) $record->is_enabled;
})
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate): void {
$tenant = $this->currentTenant();
$user = auth()->user();
if (! $tenant instanceof Tenant) {
abort(404);
}
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($tenant)) {
abort(404);
}
$initiator = $user;
$result = $gate->start(
tenant: $tenant,
connection: $record,
operationType: 'inventory_sync',
dispatcher: function (OperationRun $operationRun) use ($tenant, $initiator, $record): void {
ProviderInventorySyncJob::dispatch(
tenantId: (int) $tenant->getKey(),
userId: (int) $initiator->getKey(),
providerConnectionId: (int) $record->getKey(),
operationRun: $operationRun,
);
},
initiator: $initiator,
);
if ($result->status === 'scope_busy') {
Notification::make()
->title('Scope is busy')
->body('Another provider operation is already running for this connection.')
->danger()
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
return;
}
if ($result->status === 'deduped') {
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
return;
}
if ($result->status === 'blocked') {
$reasonCode = is_string($result->run->context['reason_code'] ?? null)
? (string) $result->run->context['reason_code']
: 'unknown_error';
$reasonEnvelope = app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forOperationRun($result->run, 'notification');
$bodyLines = $reasonEnvelope?->toBodyLines() ?? ['Blocked by provider configuration.'];
Notification::make()
->title('Inventory sync blocked')
->body(implode("\n", $bodyLines))
->warning()
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
return;
}
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::queuedToast((string) $result->run->type)
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
})
)
->requireCapability(Capabilities::PROVIDER_RUN)
->tooltip('You do not have permission to run provider operations.')
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('compliance_snapshot')
->label('Compliance snapshot')
->icon('heroicon-o-shield-check')
->color('info')
->visible(function (ProviderConnection $record): bool {
$tenant = $this->currentTenant();
$user = auth()->user();
return $tenant instanceof Tenant
&& $user instanceof User
&& $user->canAccessTenant($tenant)
&& (bool) $record->is_enabled;
})
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate): void {
$tenant = $this->currentTenant();
$user = auth()->user();
if (! $tenant instanceof Tenant) {
abort(404);
}
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($tenant)) {
abort(404);
}
$initiator = $user;
$result = $gate->start(
tenant: $tenant,
connection: $record,
operationType: 'compliance.snapshot',
dispatcher: function (OperationRun $operationRun) use ($tenant, $initiator, $record): void {
ProviderComplianceSnapshotJob::dispatch(
tenantId: (int) $tenant->getKey(),
userId: (int) $initiator->getKey(),
providerConnectionId: (int) $record->getKey(),
operationRun: $operationRun,
);
},
initiator: $initiator,
);
if ($result->status === 'scope_busy') {
Notification::make()
->title('Scope is busy')
->body('Another provider operation is already running for this connection.')
->danger()
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
return;
}
if ($result->status === 'deduped') {
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
return;
}
if ($result->status === 'blocked') {
$reasonCode = is_string($result->run->context['reason_code'] ?? null)
? (string) $result->run->context['reason_code']
: 'unknown_error';
$reasonEnvelope = app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forOperationRun($result->run, 'notification');
$bodyLines = $reasonEnvelope?->toBodyLines() ?? ['Blocked by provider configuration.'];
Notification::make()
->title('Compliance snapshot blocked')
->body(implode("\n", $bodyLines))
->warning()
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
return;
}
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::queuedToast((string) $result->run->type)
->actions([
Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($result->run, $tenant)),
])
->send();
})
)
->requireCapability(Capabilities::PROVIDER_RUN)
->tooltip('You do not have permission to run provider operations.')
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('enable_connection')
->label('Enable connection')
->icon('heroicon-o-play')
->color('success')
->requiresConfirmation()
->visible(fn (ProviderConnection $record): bool => ! (bool) $record->is_enabled)
->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
return;
}
$hadCredentials = $record->credential()->exists();
$previousLifecycle = (bool) $record->is_enabled;
$verificationStatus = $hadCredentials ? \App\Support\Providers\ProviderVerificationStatus::Unknown : \App\Support\Providers\ProviderVerificationStatus::Blocked;
$errorReasonCode = null;
$errorMessage = null;
if (! $hadCredentials) {
$errorReasonCode = \App\Support\Providers\ProviderReasonCodes::ProviderCredentialMissing;
$errorMessage = 'Provider connection credentials are missing.';
}
$record->update([
'is_enabled' => true,
'verification_status' => $verificationStatus->value,
'last_health_check_at' => null,
'last_error_reason_code' => $errorReasonCode,
'last_error_message' => $errorMessage,
]);
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.enabled',
context: [
'metadata' => [
'provider' => $record->provider,
'entra_tenant_id' => $record->entra_tenant_id,
'from_lifecycle' => $previousLifecycle ? 'enabled' : 'disabled',
'to_lifecycle' => 'enabled',
'verification_status' => $verificationStatus->value,
'credentials_present' => $hadCredentials,
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $record->getKey(),
status: 'success',
);
if (! $hadCredentials) {
Notification::make()
->title('Connection enabled (credentials missing)')
->body('Add credentials before running checks or operations.')
->warning()
->send();
return;
}
Notification::make()
->title('Provider connection enabled')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE)
->tooltip('You do not have permission to manage provider connections.')
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Action::make('disable_connection')
->label('Disable connection')
->icon('heroicon-o-archive-box-x-mark')
->color('danger')
->requiresConfirmation()
->visible(fn (ProviderConnection $record): bool => (bool) $record->is_enabled)
->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
$tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) {
return;
}
$previousLifecycle = (bool) $record->is_enabled;
$record->update([
'is_enabled' => false,
]);
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.disabled',
context: [
'metadata' => [
'provider' => $record->provider,
'entra_tenant_id' => $record->entra_tenant_id,
'from_lifecycle' => $previousLifecycle ? 'enabled' : 'disabled',
'to_lifecycle' => 'disabled',
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $record->getKey(),
status: 'success',
);
Notification::make()
->title('Provider connection disabled')
->warning()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE)
->tooltip('You do not have permission to manage provider connections.')
->preserveVisibility()
->apply(),
]) ])
->label('Actions') ->label('Actions')
->icon('heroicon-o-ellipsis-vertical') ->icon('heroicon-o-ellipsis-vertical')

View File

@ -3,17 +3,12 @@
namespace App\Filament\Resources\ProviderConnectionResource\Pages; namespace App\Filament\Resources\ProviderConnectionResource\Pages;
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User;
use App\Services\Intune\AuditLogger;
use App\Services\Providers\ProviderConnectionMutationService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Links\RequiredPermissionsLinks; use App\Support\Links\RequiredPermissionsLinks;
use App\Support\Providers\ProviderConnectionType;
use App\Support\Rbac\UiEnforcement; use App\Support\Rbac\UiEnforcement;
use Filament\Actions; use Filament\Actions;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord; use Filament\Resources\Pages\ViewRecord;
class ViewProviderConnection extends ViewRecord class ViewProviderConnection extends ViewRecord
@ -22,228 +17,59 @@ class ViewProviderConnection extends ViewRecord
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
$tenant = $this->currentTenant();
return [ return [
UiEnforcement::forAction( UiEnforcement::forAction(
Actions\Action::make('grant_admin_consent') Actions\Action::make('grant_admin_consent')
->label('Grant admin consent') ->label('Grant admin consent')
->icon('heroicon-o-clipboard-document') ->icon('heroicon-o-clipboard-document')
->url(function (): ?string { ->url(function () use ($tenant): ?string {
$tenant = ProviderConnectionResource::resolveTenantForRecord($this->record);
return $tenant instanceof Tenant return $tenant instanceof Tenant
? RequiredPermissionsLinks::adminConsentPrimaryUrl($tenant) ? RequiredPermissionsLinks::adminConsentPrimaryUrl($tenant)
: null; : null;
}) })
->visible(function (): bool { ->visible(fn (): bool => $tenant instanceof Tenant)
return ProviderConnectionResource::resolveTenantForRecord($this->record) instanceof Tenant;
})
->openUrlInNewTab() ->openUrlInNewTab()
) )
->requireCapability(Capabilities::PROVIDER_MANAGE) ->requireCapability(Capabilities::PROVIDER_MANAGE)
->apply(), ->apply(),
UiEnforcement::forAction( Actions\ActionGroup::make($this->sharedConnectionActions())
Actions\Action::make('edit') ->label('More')
->label('Edit') ->icon('heroicon-o-ellipsis-vertical')
->icon('heroicon-o-pencil-square')
->url(fn (): string => ProviderConnectionResource::getUrl('edit', ['record' => $this->record]))
)
->requireCapability(Capabilities::PROVIDER_MANAGE)
->apply(),
Actions\ActionGroup::make([
UiEnforcement::forAction(
Actions\Action::make('enable_dedicated_override')
->label('Enable dedicated override')
->icon('heroicon-o-key')
->color('primary')
->requiresConfirmation()
->modalDescription('Dedicated credentials are stored encrypted and reset consent to the dedicated app registration.')
->visible(fn (): bool => $this->record->connection_type !== ProviderConnectionType::Dedicated)
->form([
TextInput::make('client_id')
->label('Dedicated app (client) ID')
->required()
->maxLength(255),
TextInput::make('client_secret')
->label('Dedicated client secret')
->password()
->required()
->maxLength(255),
])
->action(function (array $data, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger): void {
$tenant = ProviderConnectionResource::resolveTenantForRecord($this->record);
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->enableDedicatedOverride(
connection: $this->record,
clientId: (string) $data['client_id'],
clientSecret: (string) $data['client_secret'],
);
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.connection_type_changed',
context: [
'metadata' => [
'provider_connection_id' => (int) $this->record->getKey(),
'provider' => $this->record->provider,
'entra_tenant_id' => $this->record->entra_tenant_id,
'from_connection_type' => ProviderConnectionType::Platform->value,
'to_connection_type' => ProviderConnectionType::Dedicated->value,
'client_id' => (string) $data['client_id'],
'source' => 'provider_connection.view_page',
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $this->record->getKey(),
status: 'success',
);
Notification::make()
->title('Dedicated override enabled')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Actions\Action::make('rotate_dedicated_credential')
->label('Rotate dedicated credential')
->icon('heroicon-o-arrow-path')
->color('primary')
->requiresConfirmation()
->visible(fn (): bool => $this->record->connection_type === ProviderConnectionType::Dedicated)
->form([
TextInput::make('client_id')
->label('Dedicated app (client) ID')
->default(function (): string {
$payload = $this->record->credential?->payload;
return is_array($payload) ? (string) ($payload['client_id'] ?? '') : '';
})
->required()
->maxLength(255),
TextInput::make('client_secret')
->label('Dedicated client secret')
->password()
->required()
->maxLength(255),
])
->action(function (array $data, ProviderConnectionMutationService $mutations): void {
$tenant = ProviderConnectionResource::resolveTenantForRecord($this->record);
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->enableDedicatedOverride(
connection: $this->record,
clientId: (string) $data['client_id'],
clientSecret: (string) $data['client_secret'],
);
Notification::make()
->title('Dedicated credential rotated')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Actions\Action::make('delete_dedicated_credential')
->label('Delete dedicated credential')
->icon('heroicon-o-trash')
->color('danger')
->requiresConfirmation()
->visible(fn (): bool => $this->record->connection_type === ProviderConnectionType::Dedicated
&& $this->record->credential()->exists())
->action(function (ProviderConnectionMutationService $mutations): void {
$tenant = ProviderConnectionResource::resolveTenantForRecord($this->record);
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->deleteDedicatedCredential($this->record);
Notification::make()
->title('Dedicated credential deleted')
->warning()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
UiEnforcement::forAction(
Actions\Action::make('revert_to_platform')
->label('Revert to platform')
->icon('heroicon-o-arrow-uturn-left')
->color('gray')
->requiresConfirmation()
->visible(fn (): bool => $this->record->connection_type === ProviderConnectionType::Dedicated)
->action(function (ProviderConnectionMutationService $mutations, AuditLogger $auditLogger): void {
$tenant = ProviderConnectionResource::resolveTenantForRecord($this->record);
if (! $tenant instanceof Tenant) {
abort(404);
}
$mutations->revertToPlatform($this->record);
$user = auth()->user();
$actorId = $user instanceof User ? (int) $user->getKey() : null;
$actorEmail = $user instanceof User ? $user->email : null;
$actorName = $user instanceof User ? $user->name : null;
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.connection_type_changed',
context: [
'metadata' => [
'provider_connection_id' => (int) $this->record->getKey(),
'provider' => $this->record->provider,
'entra_tenant_id' => $this->record->entra_tenant_id,
'from_connection_type' => ProviderConnectionType::Dedicated->value,
'to_connection_type' => ProviderConnectionType::Platform->value,
'source' => 'provider_connection.view_page',
],
],
actorId: $actorId,
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'provider_connection',
resourceId: (string) $this->record->getKey(),
status: 'success',
);
Notification::make()
->title('Connection reverted to platform')
->success()
->send();
})
)
->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
->preserveVisibility()
->apply(),
])
->label('Manage dedicated override')
->icon('heroicon-o-cog-6-tooth')
->color('gray'), ->color('gray'),
]; ];
} }
/**
* @return array<int, Actions\Action>
*/
private function sharedConnectionActions(): array
{
return [
ProviderConnectionResource::makeEditNavigationAction(),
ProviderConnectionResource::makeCheckConnectionAction(),
ProviderConnectionResource::makeInventorySyncAction(),
ProviderConnectionResource::makeComplianceSnapshotAction(),
ProviderConnectionResource::makeSetDefaultAction(),
ProviderConnectionResource::makeEnableDedicatedOverrideAction(
source: 'provider_connection.view_page',
modalDescription: 'Dedicated credentials are stored encrypted and reset consent to the dedicated app registration.',
),
ProviderConnectionResource::makeRotateDedicatedCredentialAction(),
ProviderConnectionResource::makeDeleteDedicatedCredentialAction(),
ProviderConnectionResource::makeRevertToPlatformAction(source: 'provider_connection.view_page'),
ProviderConnectionResource::makeEnableConnectionAction(),
ProviderConnectionResource::makeDisableConnectionAction(),
];
}
private function currentTenant(): ?Tenant
{
if (! $this->record instanceof ProviderConnection) {
return null;
}
return ProviderConnectionResource::resolveTenantForRecord($this->record);
}
} }

View File

@ -25,8 +25,8 @@
use App\Services\Intune\RbacOnboardingService; use App\Services\Intune\RbacOnboardingService;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Operations\BulkSelectionIdentity; use App\Services\Operations\BulkSelectionIdentity;
use App\Services\Providers\AdminConsentUrlFactory;
use App\Services\PortfolioTriage\TenantTriageReviewService; use App\Services\PortfolioTriage\TenantTriageReviewService;
use App\Services\Providers\AdminConsentUrlFactory;
use App\Services\Tenants\TenantActionPolicySurface; use App\Services\Tenants\TenantActionPolicySurface;
use App\Services\Tenants\TenantOperabilityService; use App\Services\Tenants\TenantOperabilityService;
use App\Services\Verification\StartVerification; use App\Services\Verification\StartVerification;
@ -61,6 +61,7 @@
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType; use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use BackedEnum; use BackedEnum;
use Filament\Actions; use Filament\Actions;
@ -178,7 +179,423 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'At most one non-inspect row action stays primary; overflow keeps helpers first, workflow actions next, and destructive actions last.') ->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'At most one non-inspect row action stays primary; overflow keeps helpers first, workflow actions next, and destructive actions last.')
->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More".') ->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More".')
->satisfy(ActionSurfaceSlot::ListEmptyState, 'Create action is reused in the list empty state.') ->satisfy(ActionSurfaceSlot::ListEmptyState, 'Create action is reused in the list empty state.')
->satisfy(ActionSurfaceSlot::DetailHeader, 'Tenant view remains the workflow-heavy special type: pure navigation moves into contextual related content while header actions stay grouped into external-link, setup, and lifecycle buckets.'); ->satisfy(ActionSurfaceSlot::DetailHeader, 'Tenant view remains the workflow-heavy special type: shared administrative actions stay grouped into external-link, setup, triage, and lifecycle buckets, while navigation-only context stays outside the header action strip.');
}
public static function makeAdminConsentAction(): Actions\Action
{
return UiEnforcement::forAction(
Actions\Action::make('admin_consent')
->label('Grant admin consent')
->icon('heroicon-o-clipboard-document')
->url(fn (Tenant $record): string => static::adminConsentUrl($record) ?? '#')
->visible(fn (Tenant $record): bool => static::adminConsentUrl($record) !== null)
->openUrlInNewTab(),
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_MANAGE)
->apply();
}
public static function makeOpenInEntraAction(): Actions\Action
{
return Actions\Action::make('open_in_entra')
->label('Open in Entra')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (Tenant $record): string => static::entraUrl($record) ?? '#')
->visible(fn (Tenant $record): bool => static::entraUrl($record) !== null)
->openUrlInNewTab();
}
public static function makeSyncTenantAction(): Actions\Action
{
return UiEnforcement::forAction(
Actions\Action::make('syncTenant')
->label('Sync')
->icon('heroicon-o-arrow-path')
->color('warning')
->requiresConfirmation()
->visible(fn (Tenant $record): bool => static::syncActionVisible($record))
->action(function (Tenant $record, AuditLogger $auditLogger, $livewire = null): void {
static::handleSyncTenantAction($record, $auditLogger, $livewire);
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_SYNC)
->apply();
}
public static function makeVerifyConfigurationAction(string $surfaceKind = 'tenant_list_row'): Actions\Action
{
return UiEnforcement::forAction(
Actions\Action::make('verify')
->label('Verify configuration')
->icon('heroicon-o-check-badge')
->color('primary')
->requiresConfirmation()
->visible(fn (Tenant $record): bool => static::verificationActionVisible($record))
->action(function (Tenant $record, StartVerification $verification, $livewire = null) use ($surfaceKind): void {
static::handleVerifyConfigurationAction($record, $verification, $livewire, $surfaceKind);
}),
)
->preserveVisibility()
->requireCapability(Capabilities::PROVIDER_RUN)
->apply();
}
/**
* @return array<string, mixed>
*/
public static function tenantViewTriageState(): array
{
return static::portfolioReturnFiltersFromRequest(request()->query());
}
public static function tenantViewTriageGroupVisible(Tenant $tenant): bool
{
return static::selectedActionTriageReviewRowForTenant($tenant, static::tenantViewTriageState()) !== null
&& static::userCanSeeTriageReviewAction($tenant);
}
public static function makeTenantViewMarkReviewedAction(): Actions\Action
{
return Actions\Action::make('markReviewed')
->label('Mark reviewed')
->icon('heroicon-o-check-circle')
->color('success')
->requiresConfirmation()
->modalHeading('Mark reviewed')
->modalDescription(fn (Tenant $record): string => static::triageReviewActionModalDescription(
$record,
static::tenantViewTriageState(),
TenantTriageReview::STATE_REVIEWED,
))
->visible(fn (Tenant $record): bool => static::selectedActionTriageReviewRowForTenant(
$record,
static::tenantViewTriageState(),
) !== null && static::userCanSeeTriageReviewAction($record))
->disabled(fn (Tenant $record): bool => static::triageReviewActionIsDisabled($record))
->tooltip(fn (Tenant $record): ?string => static::triageReviewActionTooltip($record))
->before(function (Tenant $record): void {
static::authorizeTriageReviewAction($record);
})
->action(function (Tenant $record, TenantTriageReviewService $service): void {
static::handleTriageReviewMutation(
tenant: $record,
triageState: static::tenantViewTriageState(),
targetManualState: TenantTriageReview::STATE_REVIEWED,
service: $service,
);
});
}
public static function makeTenantViewMarkFollowUpNeededAction(): Actions\Action
{
return Actions\Action::make('markFollowUpNeeded')
->label('Mark follow-up needed')
->icon('heroicon-o-exclamation-circle')
->color('warning')
->requiresConfirmation()
->modalHeading('Mark follow-up needed')
->modalDescription(fn (Tenant $record): string => static::triageReviewActionModalDescription(
$record,
static::tenantViewTriageState(),
TenantTriageReview::STATE_FOLLOW_UP_NEEDED,
))
->visible(fn (Tenant $record): bool => static::selectedActionTriageReviewRowForTenant(
$record,
static::tenantViewTriageState(),
) !== null && static::userCanSeeTriageReviewAction($record))
->disabled(fn (Tenant $record): bool => static::triageReviewActionIsDisabled($record))
->tooltip(fn (Tenant $record): ?string => static::triageReviewActionTooltip($record))
->before(function (Tenant $record): void {
static::authorizeTriageReviewAction($record);
})
->action(function (Tenant $record, TenantTriageReviewService $service): void {
static::handleTriageReviewMutation(
tenant: $record,
triageState: static::tenantViewTriageState(),
targetManualState: TenantTriageReview::STATE_FOLLOW_UP_NEEDED,
service: $service,
);
});
}
public static function makeRestoreTenantAction(TenantActionSurface $surface, ?string $permissionTooltip = null): Actions\Action
{
$builder = UiEnforcement::forAction(
Actions\Action::make('restore')
->label(fn (): string => GovernanceActionCatalog::rule('restore_tenant')->canonicalLabel)
->color('success')
->icon(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, $surface)?->icon ?? 'heroicon-o-arrow-uturn-left')
->successNotificationTitle(fn (): string => GovernanceActionCatalog::rule('restore_tenant')->successTitle)
->requiresConfirmation()
->modalHeading(GovernanceActionCatalog::rule('restore_tenant')->modalHeading)
->modalDescription(GovernanceActionCatalog::rule('restore_tenant')->modalDescription)
->visible(fn (Tenant $record): bool => static::lifecycleActionDescriptor($record, $surface)?->key === 'restore')
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void {
static::restoreTenant($record, $auditLogger);
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE);
if ($permissionTooltip !== null && $permissionTooltip !== '') {
$builder->tooltip($permissionTooltip);
}
return $builder->apply();
}
public static function makeArchiveTenantAction(TenantActionSurface $surface, ?string $permissionTooltip = null): Actions\Action
{
$builder = UiEnforcement::forAction(
Actions\Action::make('archive')
->label(fn (): string => GovernanceActionCatalog::rule('archive_tenant')->canonicalLabel)
->color('danger')
->icon(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, $surface)?->icon ?? 'heroicon-o-archive-box-x-mark')
->successNotificationTitle(fn (): string => GovernanceActionCatalog::rule('archive_tenant')->successTitle)
->requiresConfirmation()
->modalHeading(GovernanceActionCatalog::rule('archive_tenant')->modalHeading)
->modalDescription(GovernanceActionCatalog::rule('archive_tenant')->modalDescription)
->form([
Forms\Components\Textarea::make('archive_reason')
->label('Archive reason')
->rows(4)
->required()
->maxLength(2000),
])
->visible(fn (Tenant $record): bool => static::lifecycleActionDescriptor($record, $surface)?->key === 'archive')
->action(function (Tenant $record, array $data, WorkspaceAuditLogger $auditLogger): void {
static::archiveTenant($record, $auditLogger, (string) ($data['archive_reason'] ?? ''));
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE);
if ($permissionTooltip !== null && $permissionTooltip !== '') {
$builder->tooltip($permissionTooltip);
}
return $builder->apply();
}
private static function syncActionVisible(Tenant $record): bool
{
if (! $record->isActive()) {
return false;
}
$user = auth()->user();
if (! $user instanceof User) {
return false;
}
return $user->canAccessTenant($record);
}
private static function handleSyncTenantAction(Tenant $record, AuditLogger $auditLogger, mixed $livewire = null): void
{
$user = auth()->user();
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($record)) {
abort(404);
}
/** @var CapabilityResolver $resolver */
$resolver = app(CapabilityResolver::class);
if (! $resolver->can($user, $record, Capabilities::TENANT_SYNC)) {
abort(403);
}
/** @var OperationRunService $opService */
$opService = app(OperationRunService::class);
$supportedTypes = config('tenantpilot.supported_policy_types', []);
$typeNames = array_map(
static fn (array $typeConfig): string => (string) $typeConfig['type'],
$supportedTypes,
);
sort($typeNames);
$inputs = [
'scope' => 'full',
'types' => $typeNames,
];
$opRun = $opService->ensureRun(
tenant: $record,
type: 'policy.sync',
inputs: $inputs,
initiator: $user,
);
if (! $opRun->wasRecentlyCreated && $opService->isStaleQueuedRun($opRun)) {
$opService->failStaleQueuedRun(
$opRun,
message: 'Run was queued but never started (likely a previous dispatch error). Re-queuing.'
);
$opRun = $opService->ensureRun(
tenant: $record,
type: 'policy.sync',
inputs: $inputs,
initiator: $user,
);
}
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
->actions([
Actions\Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($opRun, $record)),
])
->send();
return;
}
$opService->dispatchOrFail($opRun, function () use ($record, $supportedTypes, $opRun): void {
SyncPoliciesJob::dispatch((int) $record->getKey(), $supportedTypes, null, $opRun);
});
$auditLogger->log(
tenant: $record,
action: 'tenant.sync_dispatched',
resourceType: 'tenant',
resourceId: (string) $record->id,
status: 'success',
context: ['metadata' => ['tenant_id' => $record->tenant_id]],
);
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::queuedToast((string) $opRun->type)
->actions([
Actions\Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($opRun, $record)),
])
->send();
}
private static function handleVerifyConfigurationAction(
Tenant $record,
StartVerification $verification,
mixed $livewire = null,
string $surfaceKind = 'tenant_list_row',
): void {
$user = auth()->user();
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($record)) {
abort(404);
}
$result = $verification->providerConnectionCheckForTenant(
tenant: $record,
initiator: $user,
extraContext: [
'surface' => [
'kind' => $surfaceKind,
],
],
);
$runUrl = OperationRunLinks::tenantlessView($result->run);
if ($result->status === 'scope_busy') {
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
Notification::make()
->title('Another operation is already running')
->body('Please wait for the active operation to finish.')
->warning()
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
return;
}
if ($result->status === 'deduped') {
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
return;
}
if ($result->status === 'blocked') {
$actions = [
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
];
$nextSteps = $result->run->context['next_steps'] ?? [];
$nextSteps = is_array($nextSteps) ? $nextSteps : [];
foreach ($nextSteps as $index => $step) {
if (! is_array($step)) {
continue;
}
$label = is_string($step['label'] ?? null) ? trim((string) $step['label']) : '';
$url = is_string($step['url'] ?? null) ? trim((string) $step['url']) : '';
if ($label === '' || $url === '') {
continue;
}
$actions[] = Actions\Action::make('next_step_'.$index)
->label($label)
->url($url);
break;
}
$reasonEnvelope = app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forOperationRun($result->run, 'notification');
$bodyLines = $reasonEnvelope?->toBodyLines() ?? ['Blocked by provider configuration.'];
Notification::make()
->title('Verification blocked')
->body(implode("\n", $bodyLines))
->warning()
->actions($actions)
->send();
return;
}
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::queuedToast((string) $result->run->type)
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
} }
private static function userCanManageAnyTenant(User $user): bool private static function userCanManageAnyTenant(User $user): bool
@ -341,11 +758,13 @@ public static function table(Table $table): Table
Tables\Columns\TextColumn::make('policies_count') Tables\Columns\TextColumn::make('policies_count')
->label('Policies') ->label('Policies')
->numeric() ->numeric()
->sortable(), ->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('last_policy_sync_at') Tables\Columns\TextColumn::make('last_policy_sync_at')
->label('Last Sync') ->label('Last Sync')
->since() ->since()
->sortable(), ->sortable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('domain') Tables\Columns\TextColumn::make('domain')
->copyable() ->copyable()
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
@ -464,260 +883,10 @@ public static function table(Table $table): Table
) )
->requireCapability(Capabilities::TENANT_MANAGE) ->requireCapability(Capabilities::TENANT_MANAGE)
->apply(), ->apply(),
UiEnforcement::forAction( static::makeAdminConsentAction(),
Actions\Action::make('admin_consent') static::makeOpenInEntraAction(),
->label('Grant admin consent') static::makeSyncTenantAction(),
->icon('heroicon-o-clipboard-document') static::makeVerifyConfigurationAction(),
->url(fn (Tenant $record) => static::adminConsentUrl($record))
->visible(fn (Tenant $record) => static::adminConsentUrl($record) !== null)
->openUrlInNewTab(),
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_MANAGE)
->apply(),
Actions\Action::make('open_in_entra')
->label('Open in Entra')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (Tenant $record) => static::entraUrl($record))
->visible(fn (Tenant $record) => static::entraUrl($record) !== null)
->openUrlInNewTab(),
UiEnforcement::forAction(
Actions\Action::make('syncTenant')
->label('Sync')
->icon('heroicon-o-arrow-path')
->color('warning')
->requiresConfirmation()
->visible(function (Tenant $record): bool {
if (! $record->isActive()) {
return false;
}
$user = auth()->user();
if (! $user instanceof User) {
return false;
}
return $user->canAccessTenant($record);
})
->action(function (Tenant $record, AuditLogger $auditLogger, \Filament\Tables\Contracts\HasTable $livewire): void {
$user = auth()->user();
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($record)) {
abort(404);
}
/** @var CapabilityResolver $resolver */
$resolver = app(CapabilityResolver::class);
if (! $resolver->can($user, $record, Capabilities::TENANT_SYNC)) {
abort(403);
}
/** @var OperationRunService $opService */
$opService = app(OperationRunService::class);
$supportedTypes = config('tenantpilot.supported_policy_types', []);
$typeNames = array_map(
static fn (array $typeConfig): string => (string) $typeConfig['type'],
$supportedTypes,
);
sort($typeNames);
$inputs = [
'scope' => 'full',
'types' => $typeNames,
];
$opRun = $opService->ensureRun(
tenant: $record,
type: 'policy.sync',
inputs: $inputs,
initiator: auth()->user()
);
if (! $opRun->wasRecentlyCreated && $opService->isStaleQueuedRun($opRun)) {
$opService->failStaleQueuedRun(
$opRun,
message: 'Run was queued but never started (likely a previous dispatch error). Re-queuing.'
);
$opRun = $opService->ensureRun(
tenant: $record,
type: 'policy.sync',
inputs: $inputs,
initiator: auth()->user()
);
}
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
->actions([
Actions\Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($opRun, $record)),
])
->send();
return;
}
$opService->dispatchOrFail($opRun, function () use ($record, $supportedTypes, $opRun): void {
SyncPoliciesJob::dispatch((int) $record->getKey(), $supportedTypes, null, $opRun);
});
$auditLogger->log(
tenant: $record,
action: 'tenant.sync_dispatched',
resourceType: 'tenant',
resourceId: (string) $record->id,
status: 'success',
context: ['metadata' => ['tenant_id' => $record->tenant_id]],
);
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::queuedToast((string) $opRun->type)
->actions([
Actions\Action::make('view_run')
->label('Open operation')
->url(OperationRunLinks::view($opRun, $record)),
])
->send();
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_SYNC)
->apply(),
UiEnforcement::forAction(
Actions\Action::make('verify')
->label('Verify configuration')
->icon('heroicon-o-check-badge')
->color('primary')
->requiresConfirmation()
->visible(fn (Tenant $record): bool => static::verificationActionVisible($record))
->action(function (
Tenant $record,
StartVerification $verification,
\Filament\Tables\Contracts\HasTable $livewire,
): void {
$user = auth()->user();
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($record)) {
abort(404);
}
$result = $verification->providerConnectionCheckForTenant(
tenant: $record,
initiator: $user,
extraContext: [
'surface' => [
'kind' => 'tenant_list_row',
],
],
);
$runUrl = OperationRunLinks::tenantlessView($result->run);
if ($result->status === 'scope_busy') {
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
Notification::make()
->title('Another operation is already running')
->body('Please wait for the active operation to finish.')
->warning()
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
return;
}
if ($result->status === 'deduped') {
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
return;
}
if ($result->status === 'blocked') {
$reasonCode = is_string($result->run->context['reason_code'] ?? null)
? (string) $result->run->context['reason_code']
: 'unknown_error';
$actions = [
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
];
$nextSteps = $result->run->context['next_steps'] ?? [];
$nextSteps = is_array($nextSteps) ? $nextSteps : [];
foreach ($nextSteps as $index => $step) {
if (! is_array($step)) {
continue;
}
$label = is_string($step['label'] ?? null) ? trim((string) $step['label']) : '';
$url = is_string($step['url'] ?? null) ? trim((string) $step['url']) : '';
if ($label === '' || $url === '') {
continue;
}
$actions[] = Actions\Action::make('next_step_'.$index)
->label($label)
->url($url);
break;
}
$reasonEnvelope = app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forOperationRun($result->run, 'notification');
$bodyLines = $reasonEnvelope?->toBodyLines() ?? ['Blocked by provider configuration.'];
Notification::make()
->title('Verification blocked')
->body(implode("\n", $bodyLines))
->warning()
->actions($actions)
->send();
return;
}
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
OperationUxPresenter::queuedToast((string) $result->run->type)
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
}),
)
->preserveVisibility()
->requireCapability(Capabilities::PROVIDER_RUN)
->apply(),
Actions\Action::make('markReviewed') Actions\Action::make('markReviewed')
->label('Mark reviewed') ->label('Mark reviewed')
->icon('heroicon-o-check-circle') ->icon('heroicon-o-check-circle')
@ -782,23 +951,7 @@ public static function table(Table $table): Table
service: $service, service: $service,
); );
}), }),
UiEnforcement::forAction( static::makeRestoreTenantAction(TenantActionSurface::TenantIndexRow),
Actions\Action::make('restore')
->label(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->label ?? 'Restore')
->color('success')
->icon(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->icon ?? 'heroicon-o-arrow-uturn-left')
->successNotificationTitle(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->successNotificationTitle ?? 'Tenant restored')
->requiresConfirmation()
->modalHeading(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->modalHeading ?? 'Restore tenant')
->modalDescription(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->modalDescription ?? 'Restore this archived tenant to make it available again in normal management flows.')
->visible(fn (Tenant $record): bool => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->key === 'restore')
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void {
static::restoreTenant($record, $auditLogger);
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE)
->apply(),
static::rbacAction(), static::rbacAction(),
UiEnforcement::forAction( UiEnforcement::forAction(
Actions\Action::make('forceDelete') Actions\Action::make('forceDelete')
@ -856,23 +1009,7 @@ public static function table(Table $table): Table
->preserveVisibility() ->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE) ->requireCapability(Capabilities::TENANT_DELETE)
->apply(), ->apply(),
UiEnforcement::forAction( static::makeArchiveTenantAction(TenantActionSurface::TenantIndexRow),
Actions\Action::make('archive')
->label(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->label ?? 'Archive')
->color('danger')
->icon(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->icon ?? 'heroicon-o-archive-box-x-mark')
->successNotificationTitle(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->successNotificationTitle ?? 'Tenant archived')
->requiresConfirmation()
->modalHeading(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->modalHeading ?? 'Archive tenant')
->modalDescription(fn (Tenant $record): string => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->modalDescription ?? 'Archive this tenant to retain it for inspection while removing it from active operating flows.')
->visible(fn (Tenant $record): bool => static::lifecycleActionDescriptor($record, TenantActionSurface::TenantIndexRow)?->key === 'archive')
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void {
static::archiveTenant($record, $auditLogger);
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE)
->apply(),
]) ])
->label('More') ->label('More')
->icon('heroicon-o-ellipsis-vertical') ->icon('heroicon-o-ellipsis-vertical')
@ -2482,9 +2619,10 @@ private static function viewerHasTenantCapability(Tenant $tenant, string $capabi
&& $resolver->can($user, $tenant, $capability); && $resolver->can($user, $tenant, $capability);
} }
public static function archiveTenant(Tenant $record, WorkspaceAuditLogger $auditLogger): void public static function archiveTenant(Tenant $record, WorkspaceAuditLogger $auditLogger, string $reason): void
{ {
$user = auth()->user(); $user = auth()->user();
$reason = static::validatedLifecycleReason($reason, 'archive_reason');
if (! $user instanceof User) { if (! $user instanceof User) {
abort(403); abort(403);
@ -2519,11 +2657,11 @@ public static function archiveTenant(Tenant $record, WorkspaceAuditLogger $audit
tenant: $record, tenant: $record,
action: AuditActionId::TenantArchived, action: AuditActionId::TenantArchived,
actor: $user, actor: $user,
context: ['metadata' => ['tenant_id' => $record->tenant_id]] context: ['metadata' => ['tenant_id' => $record->tenant_id, 'reason' => $reason]]
); );
Notification::make() Notification::make()
->title($descriptor->successNotificationTitle ?? 'Tenant archived') ->title(GovernanceActionCatalog::rule('archive_tenant')->successTitle)
->body($descriptor->successNotificationBody ?? 'The tenant remains available for inspection and audit history, but it is no longer selectable as active context.') ->body($descriptor->successNotificationBody ?? 'The tenant remains available for inspection and audit history, but it is no longer selectable as active context.')
->success() ->success()
->send(); ->send();
@ -2570,12 +2708,27 @@ public static function restoreTenant(Tenant $record, WorkspaceAuditLogger $audit
); );
Notification::make() Notification::make()
->title($descriptor->successNotificationTitle ?? 'Tenant restored') ->title(GovernanceActionCatalog::rule('restore_tenant')->successTitle)
->body($descriptor->successNotificationBody ?? 'The tenant is available again in normal tenant management flows and can be selected as active context.') ->body($descriptor->successNotificationBody ?? 'The tenant is available again in normal tenant management flows and can be selected as active context.')
->success() ->success()
->send(); ->send();
} }
private static function validatedLifecycleReason(string $reason, string $field): string
{
$reason = trim($reason);
if ($reason === '') {
throw new \InvalidArgumentException(sprintf('%s is required.', $field));
}
if (mb_strlen($reason) > 2000) {
throw new \InvalidArgumentException(sprintf('%s must be at most 2000 characters.', $field));
}
return $reason;
}
public static function getPages(): array public static function getPages(): array
{ {
return [ return [

View File

@ -4,12 +4,8 @@
use App\Filament\Resources\TenantResource; use App\Filament\Resources\TenantResource;
use App\Models\Tenant; use App\Models\Tenant;
use App\Services\Audit\WorkspaceAuditLogger;
use App\Support\Auth\Capabilities;
use App\Support\Rbac\UiEnforcement;
use App\Support\Tenants\TenantActionSurface; use App\Support\Tenants\TenantActionSurface;
use Filament\Actions; use Filament\Actions;
use Filament\Actions\Action;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
class EditTenant extends EditRecord class EditTenant extends EditRecord
@ -20,42 +16,14 @@ protected function getHeaderActions(): array
{ {
return array_values(array_filter([ return array_values(array_filter([
Actions\ActionGroup::make([ Actions\ActionGroup::make([
UiEnforcement::forAction( TenantResource::makeRestoreTenantAction(
Action::make('restore') TenantActionSurface::TenantEditHeader,
->label(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->label ?? 'Restore') 'You do not have permission to restore tenants.',
->color('success') ),
->icon(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->icon ?? 'heroicon-o-arrow-uturn-left') TenantResource::makeArchiveTenantAction(
->requiresConfirmation() TenantActionSurface::TenantEditHeader,
->modalHeading(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->modalHeading ?? 'Restore tenant') 'You do not have permission to archive tenants.',
->modalDescription(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->modalDescription ?? 'Restore this archived tenant to make it available again in normal management flows.') ),
->visible(fn (Tenant $record): bool => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->key === 'restore')
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void {
TenantResource::restoreTenant($record, $auditLogger);
})
)
->requireCapability(Capabilities::TENANT_DELETE)
->tooltip('You do not have permission to restore tenants.')
->preserveVisibility()
->destructive()
->apply(),
UiEnforcement::forAction(
Action::make('archive')
->label(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->label ?? 'Archive')
->color('danger')
->icon(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->icon ?? 'heroicon-o-archive-box-x-mark')
->requiresConfirmation()
->modalHeading(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->modalHeading ?? 'Archive tenant')
->modalDescription(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->modalDescription ?? 'Archive this tenant to retain it for inspection while removing it from active operating flows.')
->visible(fn (Tenant $record): bool => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantEditHeader)?->key === 'archive')
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void {
TenantResource::archiveTenant($record, $auditLogger);
})
)
->requireCapability(Capabilities::TENANT_DELETE)
->tooltip('You do not have permission to archive tenants.')
->preserveVisibility()
->destructive()
->apply(),
]) ])
->label('Lifecycle') ->label('Lifecycle')
->icon('heroicon-o-archive-box') ->icon('heroicon-o-archive-box')

View File

@ -10,9 +10,7 @@
use App\Jobs\RefreshTenantRbacHealthJob; use App\Jobs\RefreshTenantRbacHealthJob;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Verification\StartVerification;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\OperationRunLinks; use App\Support\OperationRunLinks;
use App\Support\OperationRunType; use App\Support\OperationRunType;
@ -57,18 +55,8 @@ protected function getHeaderActions(): array
{ {
return array_values(array_filter([ return array_values(array_filter([
Actions\ActionGroup::make([ Actions\ActionGroup::make([
Actions\Action::make('admin_consent') TenantResource::makeAdminConsentAction(),
->label('Grant admin consent') TenantResource::makeOpenInEntraAction(),
->icon('heroicon-o-clipboard-document')
->url(fn (Tenant $record) => TenantResource::adminConsentUrl($record))
->visible(fn (Tenant $record) => TenantResource::adminConsentUrl($record) !== null)
->openUrlInNewTab(),
Actions\Action::make('open_in_entra')
->label('Open in Entra')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (Tenant $record) => TenantResource::entraUrl($record))
->visible(fn (Tenant $record) => TenantResource::entraUrl($record) !== null)
->openUrlInNewTab(),
]) ])
->label('External links') ->label('External links')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
@ -76,126 +64,8 @@ protected function getHeaderActions(): array
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof Tenant
&& TenantResource::tenantViewExternalGroupVisible($this->getRecord())), && TenantResource::tenantViewExternalGroupVisible($this->getRecord())),
Actions\ActionGroup::make([ Actions\ActionGroup::make([
UiEnforcement::forAction( TenantResource::makeSyncTenantAction(),
Actions\Action::make('verify') TenantResource::makeVerifyConfigurationAction('tenant_view_header'),
->label(self::verificationHeaderActionLabel())
->icon('heroicon-o-check-badge')
->color('primary')
->requiresConfirmation()
->visible(fn (Tenant $record): bool => TenantResource::verificationActionVisible($record))
->action(function (
Tenant $record,
StartVerification $verification,
): void {
$user = auth()->user();
if (! $user instanceof User) {
abort(403);
}
if (! $user->canAccessTenant($record)) {
abort(404);
}
$result = $verification->providerConnectionCheckForTenant(
tenant: $record,
initiator: $user,
extraContext: [
'surface' => [
'kind' => 'tenant_view_header',
],
],
);
$runUrl = OperationRunLinks::tenantlessView($result->run);
if ($result->status === 'scope_busy') {
OpsUxBrowserEvents::dispatchRunEnqueued($this);
Notification::make()
->title('Another operation is already running')
->body('Please wait for the active operation to finish.')
->warning()
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
return;
}
if ($result->status === 'deduped') {
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
return;
}
if ($result->status === 'blocked') {
$actions = [
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
];
$nextSteps = $result->run->context['next_steps'] ?? [];
$nextSteps = is_array($nextSteps) ? $nextSteps : [];
foreach ($nextSteps as $index => $step) {
if (! is_array($step)) {
continue;
}
$label = is_string($step['label'] ?? null) ? trim((string) $step['label']) : '';
$url = is_string($step['url'] ?? null) ? trim((string) $step['url']) : '';
if ($label === '' || $url === '') {
continue;
}
$actions[] = Actions\Action::make('next_step_'.$index)
->label($label)
->url($url);
break;
}
$reasonEnvelope = app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forOperationRun($result->run, 'notification');
$bodyLines = $reasonEnvelope?->toBodyLines() ?? ['Blocked by provider configuration.'];
Notification::make()
->title('Verification blocked')
->body(implode("\n", $bodyLines))
->warning()
->actions($actions)
->send();
return;
}
OpsUxBrowserEvents::dispatchRunEnqueued($this);
OperationUxPresenter::queuedToast((string) $result->run->type)
->actions([
Actions\Action::make('view_run')
->label(OperationRunLinks::openLabel())
->url($runUrl),
])
->send();
}),
)
->preserveVisibility()
->requireCapability(Capabilities::PROVIDER_RUN)
->apply(),
TenantResource::rbacAction(), TenantResource::rbacAction(),
UiEnforcement::forAction( UiEnforcement::forAction(
Actions\Action::make('refresh_rbac') Actions\Action::make('refresh_rbac')
@ -271,40 +141,17 @@ protected function getHeaderActions(): array
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof Tenant
&& TenantResource::tenantViewSetupGroupVisible($this->getRecord())), && TenantResource::tenantViewSetupGroupVisible($this->getRecord())),
Actions\ActionGroup::make([ Actions\ActionGroup::make([
UiEnforcement::forAction( TenantResource::makeTenantViewMarkReviewedAction(),
Actions\Action::make('restore') TenantResource::makeTenantViewMarkFollowUpNeededAction(),
->label(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->label ?? 'Restore') ])
->color('success') ->label('Triage')
->icon(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->icon ?? 'heroicon-o-arrow-uturn-left') ->icon('heroicon-o-check-circle')
->requiresConfirmation() ->color('gray')
->modalHeading(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->modalHeading ?? 'Restore tenant') ->visible(fn (): bool => $this->getRecord() instanceof Tenant
->modalDescription(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->modalDescription ?? 'Restore this archived tenant to make it available again in normal management flows.') && TenantResource::tenantViewTriageGroupVisible($this->getRecord())),
->visible(fn (Tenant $record): bool => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->key === 'restore') Actions\ActionGroup::make([
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void { TenantResource::makeRestoreTenantAction(TenantActionSurface::TenantViewHeader),
TenantResource::restoreTenant($record, $auditLogger); TenantResource::makeArchiveTenantAction(TenantActionSurface::TenantViewHeader),
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE)
->destructive()
->apply(),
UiEnforcement::forAction(
Actions\Action::make('archive')
->label(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->label ?? 'Archive')
->color('danger')
->icon(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->icon ?? 'heroicon-o-archive-box-x-mark')
->requiresConfirmation()
->modalHeading(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->modalHeading ?? 'Archive tenant')
->modalDescription(fn (Tenant $record): string => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->modalDescription ?? 'Archive this tenant to retain it for inspection while removing it from active operating flows.')
->visible(fn (Tenant $record): bool => TenantResource::lifecycleActionDescriptor($record, TenantActionSurface::TenantViewHeader)?->key === 'archive')
->action(function (Tenant $record, WorkspaceAuditLogger $auditLogger): void {
TenantResource::archiveTenant($record, $auditLogger);
})
)
->preserveVisibility()
->requireCapability(Capabilities::TENANT_DELETE)
->destructive()
->apply(),
]) ])
->label('Lifecycle') ->label('Lifecycle')
->icon('heroicon-o-archive-box') ->icon('heroicon-o-archive-box')

View File

@ -13,7 +13,9 @@
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Rbac\UiEnforcement; use App\Support\Rbac\UiEnforcement;
use App\Support\TenantReviewStatus; use App\Support\TenantReviewStatus;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use Filament\Actions; use Filament\Actions;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord; use Filament\Resources\Pages\ViewRecord;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@ -146,14 +148,18 @@ private function secondaryLifecycleActionNames(): array
private function refreshReviewAction(): Actions\Action private function refreshReviewAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('refresh_review');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('refresh_review') Actions\Action::make('refresh_review')
->label('Refresh review') ->label($rule->canonicalLabel)
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('primary') ->color('primary')
->hidden(fn (): bool => ! $this->record->isMutable()) ->hidden(fn (): bool => ! $this->record->isMutable())
->requiresConfirmation() ->requiresConfirmation()
->action(function (): void { ->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->action(function () use ($rule): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
@ -168,7 +174,7 @@ private function refreshReviewAction(): Actions\Action
return; return;
} }
Notification::make()->success()->title('Refresh review queued')->send(); Notification::make()->success()->title($rule->successTitle)->send();
}), }),
) )
->requireCapability(Capabilities::TENANT_REVIEW_MANAGE) ->requireCapability(Capabilities::TENANT_REVIEW_MANAGE)
@ -178,14 +184,25 @@ private function refreshReviewAction(): Actions\Action
private function publishReviewAction(): Actions\Action private function publishReviewAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('publish_review');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('publish_review') Actions\Action::make('publish_review')
->label('Publish review') ->label($rule->canonicalLabel)
->icon('heroicon-o-check-badge') ->icon('heroicon-o-check-badge')
->color('primary') ->color('primary')
->hidden(fn (): bool => ! $this->record->isMutable()) ->hidden(fn (): bool => ! $this->record->isMutable())
->requiresConfirmation() ->requiresConfirmation()
->action(function (): void { ->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->form([
Textarea::make('publish_reason')
->label('Publication reason')
->rows(4)
->required()
->maxLength(2000),
])
->action(function (array $data) use ($rule): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
@ -193,7 +210,11 @@ private function publishReviewAction(): Actions\Action
} }
try { try {
app(TenantReviewLifecycleService::class)->publish($this->record, $user); app(TenantReviewLifecycleService::class)->publish(
$this->record,
$user,
(string) ($data['publish_reason'] ?? ''),
);
} catch (\Throwable $throwable) { } catch (\Throwable $throwable) {
Notification::make()->danger()->title('Unable to publish review')->body($throwable->getMessage())->send(); Notification::make()->danger()->title('Unable to publish review')->body($throwable->getMessage())->send();
@ -201,7 +222,7 @@ private function publishReviewAction(): Actions\Action
} }
$this->refreshFormData(['status', 'published_at', 'published_by_user_id', 'summary']); $this->refreshFormData(['status', 'published_at', 'published_by_user_id', 'summary']);
Notification::make()->success()->title('Review published')->send(); Notification::make()->success()->title($rule->successTitle)->send();
}), }),
) )
->requireCapability(Capabilities::TENANT_REVIEW_MANAGE) ->requireCapability(Capabilities::TENANT_REVIEW_MANAGE)
@ -259,24 +280,39 @@ private function createNextReviewAction(): Actions\Action
private function archiveReviewAction(): Actions\Action private function archiveReviewAction(): Actions\Action
{ {
$rule = GovernanceActionCatalog::rule('archive_review');
return UiEnforcement::forAction( return UiEnforcement::forAction(
Actions\Action::make('archive_review') Actions\Action::make('archive_review')
->label('Archive review') ->label($rule->canonicalLabel)
->icon('heroicon-o-archive-box') ->icon('heroicon-o-archive-box')
->color('danger') ->color('danger')
->hidden(fn (): bool => $this->record->statusEnum()->isTerminal()) ->hidden(fn (): bool => $this->record->statusEnum()->isTerminal())
->requiresConfirmation() ->requiresConfirmation()
->action(function (): void { ->modalHeading($rule->modalHeading)
->modalDescription($rule->modalDescription)
->form([
Textarea::make('archive_reason')
->label('Archive reason')
->rows(4)
->required()
->maxLength(2000),
])
->action(function (array $data) use ($rule): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
abort(403); abort(403);
} }
app(TenantReviewLifecycleService::class)->archive($this->record, $user); app(TenantReviewLifecycleService::class)->archive(
$this->record,
$user,
(string) ($data['archive_reason'] ?? ''),
);
$this->refreshFormData(['status', 'archived_at']); $this->refreshFormData(['status', 'archived_at']);
Notification::make()->success()->title('Review archived')->send(); Notification::make()->success()->title($rule->successTitle)->send();
}), }),
) )
->requireCapability(Capabilities::TENANT_REVIEW_MANAGE) ->requireCapability(Capabilities::TENANT_REVIEW_MANAGE)

View File

@ -10,6 +10,7 @@
use App\Support\Auth\PlatformCapabilities; use App\Support\Auth\PlatformCapabilities;
use App\Support\OpsUx\OperationUxPresenter; use App\Support\OpsUx\OperationUxPresenter;
use App\Support\System\SystemOperationRunLinks; use App\Support\System\SystemOperationRunLinks;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Forms\Components\Textarea; use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
@ -55,6 +56,10 @@ public function getTitle(): string|Htmlable
*/ */
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
$retryRule = GovernanceActionCatalog::rule('retry_run');
$cancelRule = GovernanceActionCatalog::rule('cancel_run');
$investigatedRule = GovernanceActionCatalog::rule('mark_investigated');
return [ return [
Action::make('show_all_operations') Action::make('show_all_operations')
->label('Show all operations') ->label('Show all operations')
@ -63,8 +68,11 @@ protected function getHeaderActions(): array
->label('Go to runbooks') ->label('Go to runbooks')
->url(Runbooks::getUrl(panel: 'system')), ->url(Runbooks::getUrl(panel: 'system')),
Action::make('retry') Action::make('retry')
->label('Retry') ->label($retryRule->canonicalLabel)
->color('primary')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($retryRule->modalHeading)
->modalDescription($retryRule->modalDescription)
->visible(fn (): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canRetry($this->run)) ->visible(fn (): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canRetry($this->run))
->action(function (OperationRunTriageService $triageService): void { ->action(function (OperationRunTriageService $triageService): void {
$user = $this->requireManageUser(); $user = $this->requireManageUser();
@ -79,37 +87,50 @@ protected function getHeaderActions(): array
->send(); ->send();
}), }),
Action::make('cancel') Action::make('cancel')
->label('Cancel') ->label($cancelRule->canonicalLabel)
->color('danger') ->color('danger')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading($cancelRule->modalHeading)
->modalDescription($cancelRule->modalDescription)
->visible(fn (): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canCancel($this->run)) ->visible(fn (): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canCancel($this->run))
->action(function (OperationRunTriageService $triageService): void {
$user = $this->requireManageUser();
$triageService->cancel($this->run, $user);
Notification::make()
->title('Run cancelled')
->success()
->send();
}),
Action::make('mark_investigated')
->label('Mark investigated')
->requiresConfirmation()
->visible(fn (): bool => $this->canManageOperations())
->form([ ->form([
Textarea::make('reason') Textarea::make('reason')
->label('Reason') ->label('Cancellation reason')
->required() ->required()
->minLength(5) ->minLength(5)
->maxLength(500) ->maxLength(500)
->rows(4), ->rows(4),
]) ])
->action(function (array $data, OperationRunTriageService $triageService): void { ->action(function (array $data, OperationRunTriageService $triageService) use ($cancelRule): void {
$user = $this->requireManageUser();
$triageService->cancel($this->run, $user, (string) ($data['reason'] ?? ''));
Notification::make()
->title($cancelRule->successTitle)
->success()
->send();
}),
Action::make('mark_investigated')
->label($investigatedRule->canonicalLabel)
->color('warning')
->requiresConfirmation()
->modalHeading($investigatedRule->modalHeading)
->modalDescription($investigatedRule->modalDescription)
->visible(fn (): bool => $this->canManageOperations())
->form([
Textarea::make('reason')
->label('Investigation reason')
->required()
->minLength(5)
->maxLength(500)
->rows(4),
])
->action(function (array $data, OperationRunTriageService $triageService) use ($investigatedRule): void {
$user = $this->requireManageUser(); $user = $this->requireManageUser();
$triageService->markInvestigated($this->run, $user, (string) ($data['reason'] ?? '')); $triageService->markInvestigated($this->run, $user, (string) ($data['reason'] ?? ''));
Notification::make() Notification::make()
->title('Run marked as investigated') ->title($investigatedRule->successTitle)
->success() ->success()
->send(); ->send();
}), }),

View File

@ -37,6 +37,24 @@ class TenantTriageArrivalContinuity extends Widget implements HasActions, HasSch
*/ */
public ?array $arrivalState = null; public ?array $arrivalState = null;
private ?PortfolioArrivalContext $cachedArrivalContext = null;
private ?int $cachedArrivalContextTenantId = null;
private bool $hasCachedArrivalContext = false;
/**
* @var array{backupHealth: \App\Support\BackupHealth\TenantBackupHealthAssessment, recoveryEvidence: array<string, mixed>}|null
*/
private ?array $cachedConcernTruth = null;
private ?int $cachedConcernTruthTenantId = null;
/**
* @var array<int, array<string, array<string, mixed>|null>>
*/
private array $cachedReviewStates = [];
protected static bool $isLazy = false; protected static bool $isLazy = false;
protected int|string|array $columnSpan = 'full'; protected int|string|array $columnSpan = 'full';
@ -197,23 +215,22 @@ private function handleReviewMutation(string $targetManualState, TenantTriageRev
return; return;
} }
$backupHealth = app(TenantBackupHealthResolver::class)->assess($tenant); $concernTruth = $this->concernTruthFor($tenant);
$recoveryEvidence = app(RestoreSafetyResolver::class)->dashboardRecoveryEvidence($tenant);
$actor = auth()->user(); $actor = auth()->user();
$review = match ($targetManualState) { $review = match ($targetManualState) {
TenantTriageReview::STATE_REVIEWED => $service->markReviewed( TenantTriageReview::STATE_REVIEWED => $service->markReviewed(
tenant: $tenant, tenant: $tenant,
concernFamily: $context->concernFamily, concernFamily: $context->concernFamily,
backupHealth: $backupHealth, backupHealth: $concernTruth['backupHealth'],
recoveryEvidence: $recoveryEvidence, recoveryEvidence: $concernTruth['recoveryEvidence'],
actor: $actor instanceof User ? $actor : null, actor: $actor instanceof User ? $actor : null,
), ),
TenantTriageReview::STATE_FOLLOW_UP_NEEDED => $service->markFollowUpNeeded( TenantTriageReview::STATE_FOLLOW_UP_NEEDED => $service->markFollowUpNeeded(
tenant: $tenant, tenant: $tenant,
concernFamily: $context->concernFamily, concernFamily: $context->concernFamily,
backupHealth: $backupHealth, backupHealth: $concernTruth['backupHealth'],
recoveryEvidence: $recoveryEvidence, recoveryEvidence: $concernTruth['recoveryEvidence'],
actor: $actor instanceof User ? $actor : null, actor: $actor instanceof User ? $actor : null,
), ),
default => null, default => null,
@ -223,6 +240,8 @@ private function handleReviewMutation(string $targetManualState, TenantTriageRev
return; return;
} }
$this->clearConcernCachesFor($tenant);
Notification::make() Notification::make()
->title('Review state updated') ->title('Review state updated')
->body(sprintf( ->body(sprintf(
@ -240,15 +259,59 @@ private function handleReviewMutation(string $targetManualState, TenantTriageRev
*/ */
private function currentReviewStateFor(Tenant $tenant, string $concernFamily): ?array private function currentReviewStateFor(Tenant $tenant, string $concernFamily): ?array
{ {
$backupHealth = app(TenantBackupHealthResolver::class)->assess($tenant); $tenantId = (int) $tenant->getKey();
$recoveryEvidence = app(RestoreSafetyResolver::class)->dashboardRecoveryEvidence($tenant);
return app(TenantTriageReviewStateResolver::class)->resolveMany( if (array_key_exists($tenantId, $this->cachedReviewStates)
&& array_key_exists($concernFamily, $this->cachedReviewStates[$tenantId])) {
return $this->cachedReviewStates[$tenantId][$concernFamily];
}
$concernTruth = $this->concernTruthFor($tenant);
$reviewState = app(TenantTriageReviewStateResolver::class)->resolveMany(
workspaceId: (int) $tenant->workspace_id, workspaceId: (int) $tenant->workspace_id,
tenantIds: [(int) $tenant->getKey()], tenantIds: [$tenantId],
backupHealthByTenant: [(int) $tenant->getKey() => $backupHealth], backupHealthByTenant: [$tenantId => $concernTruth['backupHealth']],
recoveryEvidenceByTenant: [(int) $tenant->getKey() => $recoveryEvidence], recoveryEvidenceByTenant: [$tenantId => $concernTruth['recoveryEvidence']],
)['rows'][(int) $tenant->getKey()][$concernFamily] ?? null; )['rows'][$tenantId][$concernFamily] ?? null;
$this->cachedReviewStates[$tenantId][$concernFamily] = $reviewState;
return $reviewState;
}
/**
* @return array{backupHealth: \App\Support\BackupHealth\TenantBackupHealthAssessment, recoveryEvidence: array<string, mixed>}
*/
private function concernTruthFor(Tenant $tenant): array
{
$tenantId = (int) $tenant->getKey();
if ($this->cachedConcernTruthTenantId === $tenantId && is_array($this->cachedConcernTruth)) {
return $this->cachedConcernTruth;
}
$this->cachedConcernTruthTenantId = $tenantId;
$this->cachedConcernTruth = [
'backupHealth' => app(TenantBackupHealthResolver::class)->assess($tenant),
'recoveryEvidence' => app(RestoreSafetyResolver::class)->dashboardRecoveryEvidence($tenant),
];
return $this->cachedConcernTruth;
}
private function clearConcernCachesFor(Tenant $tenant): void
{
$tenantId = (int) $tenant->getKey();
if ($this->cachedConcernTruthTenantId === $tenantId) {
$this->cachedConcernTruthTenantId = null;
$this->cachedConcernTruth = null;
}
if (array_key_exists($tenantId, $this->cachedReviewStates)) {
unset($this->cachedReviewStates[$tenantId]);
}
} }
private function concernFamilyLabel(string $concernFamily): string private function concernFamilyLabel(string $concernFamily): string
@ -262,6 +325,31 @@ private function concernFamilyLabel(string $concernFamily): string
private function resolveArrivalContext(Tenant $tenant): ?PortfolioArrivalContext private function resolveArrivalContext(Tenant $tenant): ?PortfolioArrivalContext
{ {
return app(PortfolioArrivalContextResolver::class)->resolveState($tenant, $this->arrivalState); $tenantId = (int) $tenant->getKey();
if ($this->arrivalState === null) {
$this->cachedArrivalContextTenantId = $tenantId;
$this->cachedArrivalContext = null;
$this->hasCachedArrivalContext = true;
return null;
}
if ($this->hasCachedArrivalContext && $this->cachedArrivalContextTenantId === $tenantId) {
return $this->cachedArrivalContext;
}
$concernTruth = $this->concernTruthFor($tenant);
$this->cachedArrivalContextTenantId = $tenantId;
$this->cachedArrivalContext = app(PortfolioArrivalContextResolver::class)->resolveStateWithTruth(
$tenant,
$this->arrivalState,
$concernTruth['backupHealth'],
$concernTruth['recoveryEvidence'],
);
$this->hasCachedArrivalContext = true;
return $this->cachedArrivalContext;
} }
} }

View File

@ -29,6 +29,10 @@ public function __invoke(Request $request): RedirectResponse
return redirect()->route('admin.operations.index'); return redirect()->route('admin.operations.index');
} }
if ($this->isTenantScopedEvidencePath($previousPath)) {
return redirect()->route('admin.evidence.overview');
}
if (TenantPageCategory::fromPath($previousPath) === TenantPageCategory::TenantBound) { if (TenantPageCategory::fromPath($previousPath) === TenantPageCategory::TenantBound) {
$workspace = $workspaceContext->currentWorkspace($request); $workspace = $workspaceContext->currentWorkspace($request);
@ -45,4 +49,17 @@ public function __invoke(Request $request): RedirectResponse
return redirect()->to((string) $previousUrl); return redirect()->to((string) $previousUrl);
} }
private function isTenantScopedEvidencePath(string $previousPath): bool
{
if ($previousPath === '/admin/evidence') {
return true;
}
if (! str_starts_with($previousPath, '/admin/evidence/')) {
return false;
}
return ! str_starts_with($previousPath, '/admin/evidence/overview');
}
} }

View File

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Barryvdh\Debugbar\LaravelDebugbar;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class SuppressDebugbarForSmokeRequests
{
public const COOKIE_NAME = 'tp_smoke_test';
public const COOKIE_VALUE = 'ok';
public const SESSION_KEY = 'tp_smoke_test';
/**
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (! $this->shouldSuppressDebugbar($request)) {
return $next($request);
}
$debugbar = app()->bound('debugbar') ? app('debugbar') : null;
config(['debugbar.enabled' => false]);
if ($debugbar instanceof LaravelDebugbar && $debugbar->isEnabled()) {
$debugbar->disable();
}
return $next($request);
}
private function shouldSuppressDebugbar(Request $request): bool
{
if ($request->cookie(self::COOKIE_NAME) === self::COOKIE_VALUE) {
return true;
}
if (! $request->hasSession()) {
return false;
}
return $request->session()->get(self::SESSION_KEY) === self::COOKIE_VALUE;
}
}

View File

@ -125,8 +125,10 @@ public function refresh(EvidenceSnapshot $snapshot, User $user): EvidenceSnapsho
return $refreshed; return $refreshed;
} }
public function expire(EvidenceSnapshot $snapshot, User $user): EvidenceSnapshot public function expire(EvidenceSnapshot $snapshot, User $user, string $reason): EvidenceSnapshot
{ {
$reason = $this->validatedReason($reason, 'expiration_reason');
$snapshot->forceFill([ $snapshot->forceFill([
'status' => EvidenceSnapshotStatus::Expired->value, 'status' => EvidenceSnapshotStatus::Expired->value,
'expires_at' => now(), 'expires_at' => now(),
@ -142,6 +144,7 @@ public function expire(EvidenceSnapshot $snapshot, User $user): EvidenceSnapshot
'metadata' => [ 'metadata' => [
'before_status' => EvidenceSnapshotStatus::Active->value, 'before_status' => EvidenceSnapshotStatus::Active->value,
'after_status' => EvidenceSnapshotStatus::Expired->value, 'after_status' => EvidenceSnapshotStatus::Expired->value,
'reason' => $reason,
], ],
], ],
actor: $user, actor: $user,
@ -242,6 +245,25 @@ public function computeFingerprint(Tenant $tenant): string
return $this->buildSnapshotPayload($tenant)['fingerprint']; return $this->buildSnapshotPayload($tenant)['fingerprint'];
} }
private function validatedReason(mixed $reason, string $field): string
{
if (! is_string($reason)) {
throw new InvalidArgumentException(sprintf('%s is required.', $field));
}
$resolved = trim($reason);
if ($resolved === '') {
throw new InvalidArgumentException(sprintf('%s is required.', $field));
}
if (mb_strlen($resolved) > 2000) {
throw new InvalidArgumentException(sprintf('%s must be at most 2000 characters.', $field));
}
return $resolved;
}
public function checkActiveRun(Tenant $tenant): bool public function checkActiveRun(Tenant $tenant): bool
{ {
return $this->operationRuns->findCanonicalRunWithIdentity( return $this->operationRuns->findCanonicalRunWithIdentity(

View File

@ -166,11 +166,10 @@ public function approve(FindingException $exception, User $actor, array $payload
$effectiveFrom = $this->validatedDate($payload['effective_from'] ?? null, 'effective_from'); $effectiveFrom = $this->validatedDate($payload['effective_from'] ?? null, 'effective_from');
$expiresAt = $this->validatedOptionalExpiry($payload['expires_at'] ?? null, $effectiveFrom, required: true); $expiresAt = $this->validatedOptionalExpiry($payload['expires_at'] ?? null, $effectiveFrom, required: true);
$approvalReason = $this->validatedOptionalReason($payload['approval_reason'] ?? null, 'approval_reason');
$approvedAt = CarbonImmutable::now(); $approvedAt = CarbonImmutable::now();
/** @var FindingException $approvedException */ /** @var FindingException $approvedException */
$approvedException = DB::transaction(function () use ($exception, $tenant, $actor, $effectiveFrom, $expiresAt, $approvalReason, $approvedAt): FindingException { $approvedException = DB::transaction(function () use ($exception, $tenant, $actor, $payload, $effectiveFrom, $expiresAt, $approvedAt): FindingException {
/** @var FindingException $lockedException */ /** @var FindingException $lockedException */
$lockedException = FindingException::query() $lockedException = FindingException::query()
->with(['finding', 'tenant', 'requester', 'currentDecision']) ->with(['finding', 'tenant', 'requester', 'currentDecision'])
@ -186,6 +185,8 @@ public function approve(FindingException $exception, User $actor, array $payload
throw new InvalidArgumentException('Requesters cannot approve their own exception requests.'); throw new InvalidArgumentException('Requesters cannot approve their own exception requests.');
} }
$approvalReason = $this->validatedReason($payload['approval_reason'] ?? null, 'approval_reason');
$isRenewalApproval = $lockedException->isPendingRenewal(); $isRenewalApproval = $lockedException->isPendingRenewal();
$before = $this->exceptionSnapshot($lockedException); $before = $this->exceptionSnapshot($lockedException);
@ -234,7 +235,7 @@ public function approve(FindingException $exception, User $actor, array $payload
finding: $finding, finding: $finding,
tenant: $tenant, tenant: $tenant,
actor: $actor, actor: $actor,
reason: $this->findingRiskAcceptedReason($lockedException, $approvalReason), reason: $this->findingRiskAcceptedReason($approvalReason),
); );
} }
@ -695,15 +696,6 @@ private function validatedReason(mixed $reason, string $field): string
return $resolved; return $resolved;
} }
private function validatedOptionalReason(mixed $reason, string $field): ?string
{
if ($reason === null || $reason === '') {
return null;
}
return $this->validatedReason($reason, $field);
}
private function validatedDate(mixed $value, string $field): CarbonImmutable private function validatedDate(mixed $value, string $field): CarbonImmutable
{ {
try { try {
@ -842,13 +834,9 @@ private function evidenceSummary(array $references): array
]; ];
} }
private function findingRiskAcceptedReason(FindingException $exception, ?string $approvalReason): string private function findingRiskAcceptedReason(string $approvalReason): string
{ {
if (is_string($approvalReason) && $approvalReason !== '') { return mb_substr($approvalReason, 0, 255);
return mb_substr($approvalReason, 0, 255);
}
return 'Governed by approved exception #'.$exception->getKey();
} }
private function metadataDate(FindingException $exception, string $key): ?CarbonImmutable private function metadataDate(FindingException $exception, string $key): ?CarbonImmutable

View File

@ -228,7 +228,7 @@ private function riskAcceptWithoutAuthorization(Finding $finding, Tenant $tenant
); );
} }
public function reopen(Finding $finding, Tenant $tenant, User $actor): Finding public function reopen(Finding $finding, Tenant $tenant, User $actor, string $reason): Finding
{ {
$this->authorize($finding, $tenant, $actor, [ $this->authorize($finding, $tenant, $actor, [
Capabilities::TENANT_FINDINGS_TRIAGE, Capabilities::TENANT_FINDINGS_TRIAGE,
@ -239,6 +239,7 @@ public function reopen(Finding $finding, Tenant $tenant, User $actor): Finding
throw new InvalidArgumentException('Only terminal findings can be reopened.'); throw new InvalidArgumentException('Only terminal findings can be reopened.');
} }
$reason = $this->validatedReason($reason, 'reopen_reason');
$now = CarbonImmutable::now(); $now = CarbonImmutable::now();
$slaDays = $this->slaPolicy->daysForFinding($finding, $tenant); $slaDays = $this->slaPolicy->daysForFinding($finding, $tenant);
$dueAt = $this->slaPolicy->dueAtForSeverity((string) $finding->severity, $tenant, $now); $dueAt = $this->slaPolicy->dueAtForSeverity((string) $finding->severity, $tenant, $now);
@ -251,6 +252,7 @@ public function reopen(Finding $finding, Tenant $tenant, User $actor): Finding
context: [ context: [
'metadata' => [ 'metadata' => [
'reopened_at' => $now->toIso8601String(), 'reopened_at' => $now->toIso8601String(),
'reopened_reason' => $reason,
'sla_days' => $slaDays, 'sla_days' => $slaDays,
'due_at' => $dueAt->toIso8601String(), 'due_at' => $dueAt->toIso8601String(),
], ],

View File

@ -108,17 +108,19 @@ public function retry(OperationRun $run, PlatformUser $actor): OperationRun
return $retryRun; return $retryRun;
} }
public function cancel(OperationRun $run, PlatformUser $actor): OperationRun public function cancel(OperationRun $run, PlatformUser $actor, string $reason): OperationRun
{ {
if (! $this->canCancel($run)) { if (! $this->canCancel($run)) {
throw new InvalidArgumentException('Operation run is not cancelable.'); throw new InvalidArgumentException('Operation run is not cancelable.');
} }
$reason = $this->validatedReason($reason, 'reason');
$context = is_array($run->context) ? $run->context : []; $context = is_array($run->context) ? $run->context : [];
$context['triage'] = array_merge( $context['triage'] = array_merge(
is_array($context['triage'] ?? null) ? $context['triage'] : [], is_array($context['triage'] ?? null) ? $context['triage'] : [],
[ [
'cancelled_at' => now()->toISOString(), 'cancelled_at' => now()->toISOString(),
'cancel_reason' => $reason,
'cancelled_by' => [ 'cancelled_by' => [
'platform_user_id' => (int) $actor->getKey(), 'platform_user_id' => (int) $actor->getKey(),
'name' => $actor->name, 'name' => $actor->name,
@ -141,6 +143,7 @@ public function cancel(OperationRun $run, PlatformUser $actor): OperationRun
[ [
'code' => 'run.cancelled', 'code' => 'run.cancelled',
'message' => 'Run cancelled by platform operator triage action.', 'message' => 'Run cancelled by platform operator triage action.',
'reason' => $reason,
], ],
], ],
); );
@ -150,6 +153,7 @@ public function cancel(OperationRun $run, PlatformUser $actor): OperationRun
action: 'platform.system_console.cancel', action: 'platform.system_console.cancel',
metadata: [ metadata: [
'operation_type' => (string) $run->type, 'operation_type' => (string) $run->type,
'reason' => $reason,
], ],
run: $cancelledRun, run: $cancelledRun,
); );
@ -159,11 +163,7 @@ public function cancel(OperationRun $run, PlatformUser $actor): OperationRun
public function markInvestigated(OperationRun $run, PlatformUser $actor, string $reason): OperationRun public function markInvestigated(OperationRun $run, PlatformUser $actor, string $reason): OperationRun
{ {
$reason = trim($reason); $reason = $this->validatedReason($reason, 'reason');
if (mb_strlen($reason) < 5 || mb_strlen($reason) > 500) {
throw new InvalidArgumentException('Investigation reason must be between 5 and 500 characters.');
}
$context = is_array($run->context) ? $run->context : []; $context = is_array($run->context) ? $run->context : [];
$context['triage'] = array_merge( $context['triage'] = array_merge(
@ -199,4 +199,15 @@ public function markInvestigated(OperationRun $run, PlatformUser $actor, string
return $run; return $run;
} }
private function validatedReason(string $reason, string $field): string
{
$reason = trim($reason);
if (mb_strlen($reason) < 5 || mb_strlen($reason) > 500) {
throw new InvalidArgumentException(sprintf('%s must be between 5 and 500 characters.', $field));
}
return $reason;
}
} }

View File

@ -26,10 +26,11 @@ public function __construct(
private readonly RequestScopedDerivedStateStore $derivedStateStore, private readonly RequestScopedDerivedStateStore $derivedStateStore,
) {} ) {}
public function publish(TenantReview $review, User $user): TenantReview public function publish(TenantReview $review, User $user, string $reason): TenantReview
{ {
$review->loadMissing(['tenant', 'sections', 'currentExportReviewPack']); $review->loadMissing(['tenant', 'sections', 'currentExportReviewPack']);
$tenant = $review->tenant; $tenant = $review->tenant;
$reason = $this->validatedReason($reason, 'publish_reason');
if (! $tenant instanceof Tenant) { if (! $tenant instanceof Tenant) {
throw new InvalidArgumentException('Review tenant could not be resolved.'); throw new InvalidArgumentException('Review tenant could not be resolved.');
@ -59,6 +60,7 @@ public function publish(TenantReview $review, User $user): TenantReview
'review_id' => (int) $review->getKey(), 'review_id' => (int) $review->getKey(),
'before_status' => $beforeStatus, 'before_status' => $beforeStatus,
'after_status' => TenantReviewStatus::Published->value, 'after_status' => TenantReviewStatus::Published->value,
'reason' => $reason,
], ],
], ],
actor: $user, actor: $user,
@ -73,10 +75,11 @@ public function publish(TenantReview $review, User $user): TenantReview
return $review->refresh()->load(['tenant', 'sections', 'currentExportReviewPack']); return $review->refresh()->load(['tenant', 'sections', 'currentExportReviewPack']);
} }
public function archive(TenantReview $review, User $user): TenantReview public function archive(TenantReview $review, User $user, string $reason): TenantReview
{ {
$review->loadMissing('tenant'); $review->loadMissing('tenant');
$tenant = $review->tenant; $tenant = $review->tenant;
$reason = $this->validatedReason($reason, 'archive_reason');
if (! $tenant instanceof Tenant) { if (! $tenant instanceof Tenant) {
throw new InvalidArgumentException('Review tenant could not be resolved.'); throw new InvalidArgumentException('Review tenant could not be resolved.');
@ -101,6 +104,7 @@ public function archive(TenantReview $review, User $user): TenantReview
'review_id' => (int) $review->getKey(), 'review_id' => (int) $review->getKey(),
'before_status' => $beforeStatus, 'before_status' => $beforeStatus,
'after_status' => TenantReviewStatus::Archived->value, 'after_status' => TenantReviewStatus::Archived->value,
'reason' => $reason,
], ],
], ],
actor: $user, actor: $user,
@ -171,6 +175,25 @@ public function createNextReview(TenantReview $review, User $user, ?EvidenceSnap
return $nextReview; return $nextReview;
} }
private function validatedReason(mixed $reason, string $field): string
{
if (! is_string($reason)) {
throw new InvalidArgumentException(sprintf('%s is required.', $field));
}
$resolved = trim($reason);
if ($resolved === '') {
throw new InvalidArgumentException(sprintf('%s is required.', $field));
}
if (mb_strlen($resolved) > 2000) {
throw new InvalidArgumentException(sprintf('%s must be at most 2000 characters.', $field));
}
return $resolved;
}
private function invalidateArtifactTruthCache(TenantReview $review): void private function invalidateArtifactTruthCache(TenantReview $review): void
{ {
$this->derivedStateStore->invalidateModel(DerivedStateFamily::ArtifactTruth, $review, 'tenant_review'); $this->derivedStateStore->invalidateModel(DerivedStateFamily::ArtifactTruth, $review, 'tenant_review');

View File

@ -73,12 +73,34 @@ public function resolve(Request $request, Tenant $tenant): ?PortfolioArrivalCont
* }|null $state * }|null $state
*/ */
public function resolveState(Tenant $tenant, ?array $state): ?PortfolioArrivalContext public function resolveState(Tenant $tenant, ?array $state): ?PortfolioArrivalContext
{
return $this->resolveStateWithTruth($tenant, $state);
}
/**
* @param array{
* sourceSurface: string,
* tenantRouteKey: string|null,
* workspaceId: int|null,
* concernFamily: string,
* concernState: string,
* concernReason: string|null,
* returnFilters: array<string, mixed>|null
* }|null $state
* @param array<string, mixed>|null $recoveryEvidence
*/
public function resolveStateWithTruth(
Tenant $tenant,
?array $state,
?TenantBackupHealthAssessment $backupHealth = null,
?array $recoveryEvidence = null,
): ?PortfolioArrivalContext
{ {
if ($state === null || ! $this->matchesTenantScope($tenant, $state)) { if ($state === null || ! $this->matchesTenantScope($tenant, $state)) {
return null; return null;
} }
return $this->buildContext($tenant, $state); return $this->buildContext($tenant, $state, $backupHealth, $recoveryEvidence);
} }
/** /**
@ -149,10 +171,18 @@ private function matchesTenantScope(Tenant $tenant, array $state): bool
* returnFilters: array<string, mixed>|null * returnFilters: array<string, mixed>|null
* } $state * } $state
*/ */
private function buildContext(Tenant $tenant, array $state): PortfolioArrivalContext /**
* @param array<string, mixed>|null $recoveryEvidence
*/
private function buildContext(
Tenant $tenant,
array $state,
?TenantBackupHealthAssessment $backupHealth = null,
?array $recoveryEvidence = null,
): PortfolioArrivalContext
{ {
$backupHealth = $this->tenantBackupHealthResolver->assess($tenant); $backupHealth ??= $this->tenantBackupHealthResolver->assess($tenant);
$recoveryEvidence = $this->restoreSafetyResolver->dashboardRecoveryEvidence($tenant); $recoveryEvidence ??= $this->restoreSafetyResolver->dashboardRecoveryEvidence($tenant);
return new PortfolioArrivalContext( return new PortfolioArrivalContext(
sourceSurface: $state['sourceSurface'], sourceSurface: $state['sourceSurface'],

View File

@ -4,6 +4,17 @@
namespace App\Support\Ui\ActionSurface; namespace App\Support\Ui\ActionSurface;
use App\Filament\Pages\BaselineCompareLanding;
use App\Filament\Pages\BaselineCompareMatrix;
use App\Filament\Pages\Monitoring\Alerts;
use App\Filament\Pages\Monitoring\AuditLog;
use App\Filament\Pages\Monitoring\EvidenceOverview;
use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Filament\Pages\Monitoring\Operations;
use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Filament\Pages\Reviews\ReviewRegister;
use App\Filament\Pages\TenantDiagnostics;
use App\Filament\Resources\AlertDeliveryResource\Pages\ListAlertDeliveries;
use App\Filament\Resources\AlertDestinationResource\Pages\ViewAlertDestination; use App\Filament\Resources\AlertDestinationResource\Pages\ViewAlertDestination;
use App\Filament\Resources\BackupSetResource\Pages\ViewBackupSet; use App\Filament\Resources\BackupSetResource\Pages\ViewBackupSet;
use App\Filament\Resources\BaselineProfileResource\Pages\ViewBaselineProfile; use App\Filament\Resources\BaselineProfileResource\Pages\ViewBaselineProfile;
@ -38,7 +49,6 @@ public static function baseline(): self
'App\\Filament\\Pages\\BreakGlassRecovery' => 'Break-glass flow is governed by dedicated security specs and tests.', 'App\\Filament\\Pages\\BreakGlassRecovery' => 'Break-glass flow is governed by dedicated security specs and tests.',
'App\\Filament\\Pages\\ChooseTenant' => 'Tenant chooser has no contract-style table action surface.', 'App\\Filament\\Pages\\ChooseTenant' => 'Tenant chooser has no contract-style table action surface.',
'App\\Filament\\Pages\\ChooseWorkspace' => 'Workspace chooser has no contract-style table action surface.', 'App\\Filament\\Pages\\ChooseWorkspace' => 'Workspace chooser has no contract-style table action surface.',
'App\\Filament\\Pages\\Monitoring\\Alerts' => 'Monitoring alerts remains exempt because the active admin alerts surface resolves through the cluster entry at /admin/alerts, not this page-class route.',
'App\\Filament\\Pages\\Tenancy\\RegisterTenant' => 'Tenant onboarding route is covered by onboarding/RBAC specs.', 'App\\Filament\\Pages\\Tenancy\\RegisterTenant' => 'Tenant onboarding route is covered by onboarding/RBAC specs.',
'App\\Filament\\Pages\\TenantDashboard' => 'Dashboard retrofit deferred; widget and summary surfaces are excluded from this contract.', 'App\\Filament\\Pages\\TenantDashboard' => 'Dashboard retrofit deferred; widget and summary surfaces are excluded from this contract.',
'App\\Filament\\Pages\\Workspaces\\ManagedTenantOnboardingWizard' => 'Onboarding wizard has dedicated conformance tests in spec 172 (OnboardingVerificationTest, OnboardingVerificationClustersTest, OnboardingVerificationV1_5UxTest) and remains exempt from blanket discovery.', 'App\\Filament\\Pages\\Workspaces\\ManagedTenantOnboardingWizard' => 'Onboarding wizard has dedicated conformance tests in spec 172 (OnboardingVerificationTest, OnboardingVerificationClustersTest, OnboardingVerificationV1_5UxTest) and remains exempt from blanket discovery.',
@ -312,6 +322,182 @@ public static function spec192RecordPageInventory(): array
]; ];
} }
/**
* @return array<string, array{
* surfaceKey: string,
* classification: string,
* canonicalNoun: string,
* panelScope: string,
* ownerScope: string,
* surfaceKind: string,
* primaryInspectModel: string,
* sharedPattern: string,
* requiresHeaderRemediation: bool,
* requiresExplicitDeclaration: bool,
* exceptionReason: ?string,
* browserSmokeRequired: bool
* }>
*/
public static function spec193MonitoringSurfaceInventory(): array
{
return [
FindingExceptionsQueue::class => [
'surfaceKey' => 'finding_exceptions_queue',
'classification' => 'remediation_required',
'canonicalNoun' => 'Finding exceptions',
'panelScope' => 'admin',
'ownerScope' => 'workspace-visible-tenant-owned',
'surfaceKind' => 'queue_workbench',
'primaryInspectModel' => 'explicit_inspect_action',
'sharedPattern' => 'operate_hub_shell',
'requiresHeaderRemediation' => true,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
TenantlessOperationRunViewer::class => [
'surfaceKey' => 'tenantless_operation_run_viewer',
'classification' => 'remediation_required',
'canonicalNoun' => 'Operation run',
'panelScope' => 'admin',
'ownerScope' => 'workspace-owned',
'surfaceKind' => 'monitoring_detail',
'primaryInspectModel' => 'singleton_detail_surface',
'sharedPattern' => 'operate_hub_shell',
'requiresHeaderRemediation' => true,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
Operations::class => [
'surfaceKey' => 'operations',
'classification' => 'remediation_required',
'canonicalNoun' => 'Operations',
'panelScope' => 'admin',
'ownerScope' => 'workspace-owned',
'surfaceKind' => 'monitoring_landing',
'primaryInspectModel' => 'clickable_row',
'sharedPattern' => 'operate_hub_shell',
'requiresHeaderRemediation' => true,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
Alerts::class => [
'surfaceKey' => 'alerts',
'classification' => 'minor_alignment_only',
'canonicalNoun' => 'Alerts',
'panelScope' => 'admin',
'ownerScope' => 'workspace-owned',
'surfaceKind' => 'monitoring_landing',
'primaryInspectModel' => 'page_level_overview',
'sharedPattern' => 'cluster_entry',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => false,
],
AuditLog::class => [
'surfaceKey' => 'audit_log',
'classification' => 'minor_alignment_only',
'canonicalNoun' => 'Audit log',
'panelScope' => 'admin',
'ownerScope' => 'workspace-visible-tenant-owned',
'surfaceKind' => 'read_only_report',
'primaryInspectModel' => 'explicit_inspect_action',
'sharedPattern' => 'operate_hub_shell',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => false,
],
ListAlertDeliveries::class => [
'surfaceKey' => 'alert_deliveries',
'classification' => 'minor_alignment_only',
'canonicalNoun' => 'Alert deliveries',
'panelScope' => 'admin',
'ownerScope' => 'workspace-owned',
'surfaceKind' => 'read_only_report',
'primaryInspectModel' => 'clickable_row',
'sharedPattern' => 'operate_hub_shell',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => false,
'exceptionReason' => null,
'browserSmokeRequired' => false,
],
EvidenceOverview::class => [
'surfaceKey' => 'evidence_overview',
'classification' => 'compliant_no_op',
'canonicalNoun' => 'Evidence overview',
'panelScope' => 'admin',
'ownerScope' => 'workspace-visible-tenant-owned',
'surfaceKind' => 'read_only_report',
'primaryInspectModel' => 'clickable_row',
'sharedPattern' => 'none',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
BaselineCompareLanding::class => [
'surfaceKey' => 'baseline_compare_landing',
'classification' => 'compliant_no_op',
'canonicalNoun' => 'Baseline compare',
'panelScope' => 'tenant',
'ownerScope' => 'tenant-owned',
'surfaceKind' => 'monitoring_landing',
'primaryInspectModel' => 'page_level_overview',
'sharedPattern' => 'none',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
BaselineCompareMatrix::class => [
'surfaceKey' => 'baseline_compare_matrix',
'classification' => 'compliant_no_op',
'canonicalNoun' => 'Baseline compare matrix',
'panelScope' => 'tenant',
'ownerScope' => 'tenant-owned',
'surfaceKind' => 'read_only_report',
'primaryInspectModel' => 'matrix_itself',
'sharedPattern' => 'none',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
ReviewRegister::class => [
'surfaceKey' => 'review_register',
'classification' => 'compliant_no_op',
'canonicalNoun' => 'Review register',
'panelScope' => 'admin',
'ownerScope' => 'workspace-visible-tenant-owned',
'surfaceKind' => 'read_only_report',
'primaryInspectModel' => 'clickable_row',
'sharedPattern' => 'none',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => null,
'browserSmokeRequired' => true,
],
TenantDiagnostics::class => [
'surfaceKey' => 'tenant_diagnostics',
'classification' => 'special_type_acceptable',
'canonicalNoun' => 'Tenant diagnostics',
'panelScope' => 'tenant',
'ownerScope' => 'tenant-owned',
'surfaceKind' => 'diagnostic_exception',
'primaryInspectModel' => 'singleton_detail_surface',
'sharedPattern' => 'none',
'requiresHeaderRemediation' => false,
'requiresExplicitDeclaration' => true,
'exceptionReason' => 'Tenant diagnostics is already the focused diagnostic surface for the active tenant and may expose repair actions only when a real defect exists.',
'browserSmokeRequired' => true,
],
];
}
/** /**
* @return array{ * @return array{
* surfaceKey: string, * surfaceKey: string,
@ -334,4 +520,25 @@ public static function spec192RecordPageSurface(string $className): ?array
{ {
return self::spec192RecordPageInventory()[$className] ?? null; return self::spec192RecordPageInventory()[$className] ?? null;
} }
/**
* @return array{
* surfaceKey: string,
* classification: string,
* canonicalNoun: string,
* panelScope: string,
* ownerScope: string,
* surfaceKind: string,
* primaryInspectModel: string,
* sharedPattern: string,
* requiresHeaderRemediation: bool,
* requiresExplicitDeclaration: bool,
* exceptionReason: ?string,
* browserSmokeRequired: bool
* }|null
*/
public static function spec193MonitoringSurface(string $className): ?array
{
return self::spec193MonitoringSurfaceInventory()[$className] ?? null;
}
} }

View File

@ -54,6 +54,7 @@ public function validateComponents(array $components): ActionSurfaceValidationRe
{ {
$issues = []; $issues = [];
$this->validateSpec193MonitoringSurfaceInventory($issues);
$this->validateSpec192RecordPageInventory($issues); $this->validateSpec192RecordPageInventory($issues);
foreach ($components as $component) { foreach ($components as $component) {
@ -108,6 +109,146 @@ className: $component->className,
); );
} }
/**
* @param array<int, ActionSurfaceValidationIssue> $issues
*/
private function validateSpec193MonitoringSurfaceInventory(array &$issues): void
{
$allowedClassifications = [
'remediation_required',
'minor_alignment_only',
'compliant_no_op',
'special_type_acceptable',
];
$allowedPanelScopes = ['admin', 'tenant'];
$allowedOwnerScopes = ['workspace-owned', 'workspace-visible-tenant-owned', 'tenant-owned'];
$allowedSurfaceKinds = ['queue_workbench', 'monitoring_detail', 'monitoring_landing', 'read_only_report', 'diagnostic_exception'];
$allowedPrimaryInspectModels = ['explicit_inspect_action', 'clickable_row', 'page_level_overview', 'matrix_itself', 'singleton_detail_surface'];
$allowedSharedPatterns = ['operate_hub_shell', 'cluster_entry', 'none'];
$surfaceKeys = [];
foreach (ActionSurfaceExemptions::spec193MonitoringSurfaceInventory() as $className => $surface) {
if (! class_exists($className)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 inventory references a surface class that does not exist.',
hint: 'Keep ActionSurfaceExemptions::spec193MonitoringSurfaceInventory() aligned with the in-scope monitoring surface classes.',
);
continue;
}
$surfaceKey = (string) ($surface['surfaceKey'] ?? '');
if ($surfaceKey === '') {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 inventory entry is missing a non-empty surface key.',
hint: 'Provide the stable spec surface key for this monitoring surface.',
);
} elseif (isset($surfaceKeys[$surfaceKey])) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: sprintf('Spec 193 surface key "%s" is declared more than once.', $surfaceKey),
hint: 'Each in-scope monitoring surface must have a unique surface key.',
);
} else {
$surfaceKeys[$surfaceKey] = true;
}
if (! in_array($surface['classification'] ?? null, $allowedClassifications, true)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 classification is invalid or missing.',
hint: 'Use remediation_required, minor_alignment_only, compliant_no_op, or special_type_acceptable.',
);
}
if (! in_array($surface['panelScope'] ?? null, $allowedPanelScopes, true)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 panel scope is invalid or missing.',
hint: 'Use admin or tenant for each monitoring surface inventory entry.',
);
}
if (! in_array($surface['ownerScope'] ?? null, $allowedOwnerScopes, true)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 owner scope is invalid or missing.',
hint: 'Use workspace-owned, workspace-visible-tenant-owned, or tenant-owned.',
);
}
if (! in_array($surface['surfaceKind'] ?? null, $allowedSurfaceKinds, true)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 surface kind is invalid or missing.',
hint: 'Use queue_workbench, monitoring_detail, monitoring_landing, read_only_report, or diagnostic_exception.',
);
}
if (! in_array($surface['primaryInspectModel'] ?? null, $allowedPrimaryInspectModels, true)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 primary inspect model is invalid or missing.',
hint: 'Use an allowed inspect model such as explicit_inspect_action, clickable_row, or page_level_overview.',
);
}
if (! in_array($surface['sharedPattern'] ?? null, $allowedSharedPatterns, true)) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 shared pattern is invalid or missing.',
hint: 'Use operate_hub_shell, cluster_entry, or none.',
);
}
if (! is_string($surface['canonicalNoun'] ?? null) || trim((string) $surface['canonicalNoun']) === '') {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 canonical noun must be non-empty.',
hint: 'Use the stable operator-facing noun for the monitoring surface.',
);
}
$classification = (string) ($surface['classification'] ?? '');
$exceptionReason = $surface['exceptionReason'] ?? null;
if ($classification === 'special_type_acceptable') {
if (! is_string($exceptionReason) || trim($exceptionReason) === '') {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Special-type acceptable Spec 193 surfaces require an explicit exception reason.',
hint: 'Document why this surface intentionally differs from the standard monitoring hierarchy.',
);
}
} elseif ($exceptionReason !== null && trim((string) $exceptionReason) !== '') {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Only special-type acceptable Spec 193 surfaces may carry an exception reason.',
hint: 'Clear the exception reason for remediation, minor-alignment, and compliant surfaces.',
);
}
if ($classification === 'remediation_required' && ($surface['requiresHeaderRemediation'] ?? false) !== true) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Remediation-required Spec 193 surfaces must mark header remediation as required.',
hint: 'Set requiresHeaderRemediation to true for remediation_required surfaces.',
);
}
if (($surface['requiresExplicitDeclaration'] ?? false) === true && ! method_exists($className, 'actionSurfaceDeclaration')) {
$issues[] = new ActionSurfaceValidationIssue(
className: $className,
message: 'Spec 193 surface requires an explicit action-surface declaration, but the class does not define one.',
hint: 'Add actionSurfaceDeclaration() to the page class or clear requiresExplicitDeclaration if the surface is intentionally declaration-free.',
);
}
}
}
/** /**
* @param array<int, ActionSurfaceValidationIssue> $issues * @param array<int, ActionSurfaceValidationIssue> $issues
*/ */

View File

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Support\Ui\GovernanceActions\Enums;
enum GovernanceFrictionClass: string
{
case F0 = 'F0';
case F1 = 'F1';
case F2 = 'F2';
case F3 = 'F3';
public function requiresConfirmation(): bool
{
return $this !== self::F0;
}
}

View File

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Support\Ui\GovernanceActions\Enums;
enum GovernanceReasonPolicy: string
{
case None = 'none';
case Optional = 'optional';
case Required = 'required';
public function requiresReason(): bool
{
return $this === self::Required;
}
}

View File

@ -0,0 +1,637 @@
<?php
declare(strict_types=1);
namespace App\Support\Ui\GovernanceActions;
use App\Support\Ui\GovernanceActions\Enums\GovernanceFrictionClass;
use App\Support\Ui\GovernanceActions\Enums\GovernanceReasonPolicy;
use InvalidArgumentException;
final class GovernanceActionCatalog
{
/**
* @return array<string, array{
* familyKey: string,
* canonicalObject: string,
* panels: array<int, string>,
* surfaceKeys: array<int, string>,
* defaultActionOrder: array<int, string>,
* supportsDocumentedDeviation: bool,
* defaultMutationScopeSource: string
* }>
*/
public static function families(): array
{
return [
'exception_decision' => [
'familyKey' => 'exception_decision',
'canonicalObject' => 'exception',
'panels' => ['admin', 'tenant'],
'surfaceKeys' => ['finding_exceptions_queue', 'view_finding_exception', 'view_finding'],
'defaultActionOrder' => [
'approve_exception',
'reject_exception',
'renew_exception',
'revoke_exception',
],
'supportsDocumentedDeviation' => true,
'defaultMutationScopeSource' => 'exception governance',
],
'review_lifecycle' => [
'familyKey' => 'review_lifecycle',
'canonicalObject' => 'review',
'panels' => ['tenant'],
'surfaceKeys' => ['view_tenant_review'],
'defaultActionOrder' => ['refresh_review', 'publish_review', 'archive_review'],
'supportsDocumentedDeviation' => true,
'defaultMutationScopeSource' => 'tenant review lifecycle',
],
'evidence_lifecycle' => [
'familyKey' => 'evidence_lifecycle',
'canonicalObject' => 'snapshot',
'panels' => ['tenant'],
'surfaceKeys' => ['list_evidence_snapshots', 'view_evidence_snapshot'],
'defaultActionOrder' => ['refresh_evidence', 'expire_snapshot'],
'supportsDocumentedDeviation' => true,
'defaultMutationScopeSource' => 'evidence lifecycle',
],
'run_triage' => [
'familyKey' => 'run_triage',
'canonicalObject' => 'run',
'panels' => ['system'],
'surfaceKeys' => ['system_view_run'],
'defaultActionOrder' => ['retry_run', 'mark_investigated', 'cancel_run'],
'supportsDocumentedDeviation' => true,
'defaultMutationScopeSource' => 'run triage',
],
'finding_lifecycle' => [
'familyKey' => 'finding_lifecycle',
'canonicalObject' => 'finding',
'panels' => ['tenant'],
'surfaceKeys' => ['view_finding', 'finding_list_row', 'finding_bulk'],
'defaultActionOrder' => ['close_finding', 'reopen_finding'],
'supportsDocumentedDeviation' => false,
'defaultMutationScopeSource' => 'finding lifecycle',
],
'tenant_lifecycle' => [
'familyKey' => 'tenant_lifecycle',
'canonicalObject' => 'tenant',
'panels' => ['admin'],
'surfaceKeys' => ['tenant_index_row', 'view_tenant', 'edit_tenant'],
'defaultActionOrder' => ['archive_tenant', 'restore_tenant'],
'supportsDocumentedDeviation' => true,
'defaultMutationScopeSource' => 'tenant lifecycle',
],
];
}
/**
* @return array<string, GovernanceActionRule>
*/
public static function rules(): array
{
return [
'approve_exception' => new GovernanceActionRule(
actionKey: 'approve_exception',
familyKey: 'exception_decision',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'none',
canonicalLabel: 'Approve exception',
modalHeading: 'Approve exception',
modalDescription: 'Approve this exception request for the selected tenant and linked finding. TenantPilot updates the governed exception decision and risk-acceptance continuity only.',
successTitle: 'Exception approved',
auditVerb: 'approve exception',
serviceOwner: 'FindingExceptionService',
surfaceKeys: ['finding_exceptions_queue'],
),
'reject_exception' => new GovernanceActionRule(
actionKey: 'reject_exception',
familyKey: 'exception_decision',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'contextual',
canonicalLabel: 'Reject exception',
modalHeading: 'Reject exception',
modalDescription: 'Reject this exception request for the selected tenant and linked finding. TenantPilot records the governance decision and leaves the finding out of governed risk acceptance.',
successTitle: 'Exception rejected',
auditVerb: 'reject exception',
serviceOwner: 'FindingExceptionService',
surfaceKeys: ['finding_exceptions_queue'],
),
'renew_exception' => new GovernanceActionRule(
actionKey: 'renew_exception',
familyKey: 'exception_decision',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'none',
canonicalLabel: 'Renew exception',
modalHeading: 'Renew exception',
modalDescription: 'Submit a renewal request for this governed exception. TenantPilot records the request and keeps the formal decision pending until it is reviewed.',
successTitle: 'Renewal request submitted',
auditVerb: 'renew exception',
serviceOwner: 'FindingExceptionService',
surfaceKeys: ['view_finding_exception', 'view_finding'],
),
'revoke_exception' => new GovernanceActionRule(
actionKey: 'revoke_exception',
familyKey: 'exception_decision',
frictionClass: GovernanceFrictionClass::F3,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'required',
canonicalLabel: 'Revoke exception',
modalHeading: 'Revoke exception',
modalDescription: 'Revoke this active exception for the tenant and linked finding. TenantPilot records the revocation and removes the governed exception support.',
successTitle: 'Exception revoked',
auditVerb: 'revoke exception',
serviceOwner: 'FindingExceptionService',
surfaceKeys: ['view_finding_exception', 'view_finding'],
),
'refresh_review' => new GovernanceActionRule(
actionKey: 'refresh_review',
familyKey: 'review_lifecycle',
frictionClass: GovernanceFrictionClass::F1,
reasonPolicy: GovernanceReasonPolicy::None,
dangerPolicy: 'none',
canonicalLabel: 'Refresh review',
modalHeading: 'Refresh review',
modalDescription: 'Refresh this tenant review from the latest eligible evidence basis. TenantPilot queues a recomputation for this review and keeps existing publication history untouched.',
successTitle: 'Refresh review queued',
auditVerb: 'refresh review',
serviceOwner: 'TenantReviewService',
surfaceKeys: ['view_tenant_review'],
),
'publish_review' => new GovernanceActionRule(
actionKey: 'publish_review',
familyKey: 'review_lifecycle',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'none',
canonicalLabel: 'Publish review',
modalHeading: 'Publish review',
modalDescription: 'Publish this tenant review as the current governed review outcome for this tenant. TenantPilot records the publication decision only.',
successTitle: 'Review published',
auditVerb: 'publish review',
serviceOwner: 'TenantReviewLifecycleService',
surfaceKeys: ['view_tenant_review'],
),
'archive_review' => new GovernanceActionRule(
actionKey: 'archive_review',
familyKey: 'review_lifecycle',
frictionClass: GovernanceFrictionClass::F3,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'required',
canonicalLabel: 'Archive review',
modalHeading: 'Archive review',
modalDescription: 'Archive this tenant review so it stays historical only. TenantPilot preserves the evidence history but removes the review from active lifecycle work.',
successTitle: 'Review archived',
auditVerb: 'archive review',
serviceOwner: 'TenantReviewLifecycleService',
surfaceKeys: ['view_tenant_review'],
),
'refresh_evidence' => new GovernanceActionRule(
actionKey: 'refresh_evidence',
familyKey: 'evidence_lifecycle',
frictionClass: GovernanceFrictionClass::F1,
reasonPolicy: GovernanceReasonPolicy::None,
dangerPolicy: 'none',
canonicalLabel: 'Refresh evidence',
modalHeading: 'Refresh evidence',
modalDescription: 'Refresh content evidence for this tenant. TenantPilot queues a new snapshot and leaves existing governed snapshots intact.',
successTitle: 'Refresh evidence queued',
auditVerb: 'refresh evidence',
serviceOwner: 'EvidenceSnapshotService',
surfaceKeys: ['view_evidence_snapshot'],
),
'expire_snapshot' => new GovernanceActionRule(
actionKey: 'expire_snapshot',
familyKey: 'evidence_lifecycle',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'required',
canonicalLabel: 'Expire snapshot',
modalHeading: 'Expire snapshot',
modalDescription: 'Expire this evidence snapshot for the current tenant. TenantPilot records that the snapshot is no longer valid for governance use.',
successTitle: 'Snapshot expired',
auditVerb: 'expire snapshot',
serviceOwner: 'EvidenceSnapshotService',
surfaceKeys: ['list_evidence_snapshots', 'view_evidence_snapshot'],
),
'retry_run' => new GovernanceActionRule(
actionKey: 'retry_run',
familyKey: 'run_triage',
frictionClass: GovernanceFrictionClass::F1,
reasonPolicy: GovernanceReasonPolicy::None,
dangerPolicy: 'none',
canonicalLabel: 'Retry',
modalHeading: 'Retry run',
modalDescription: 'Retry this failed run. TenantPilot queues a new run and preserves the original run history.',
successTitle: 'Retry queued',
auditVerb: 'retry run',
serviceOwner: 'OperationRunTriageService',
surfaceKeys: ['system_view_run'],
),
'mark_investigated' => new GovernanceActionRule(
actionKey: 'mark_investigated',
familyKey: 'run_triage',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'none',
canonicalLabel: 'Mark investigated',
modalHeading: 'Mark investigated',
modalDescription: 'Mark this run as investigated. TenantPilot records the triage rationale on this run only.',
successTitle: 'Run marked as investigated',
auditVerb: 'mark investigated',
serviceOwner: 'OperationRunTriageService',
surfaceKeys: ['system_view_run'],
),
'cancel_run' => new GovernanceActionRule(
actionKey: 'cancel_run',
familyKey: 'run_triage',
frictionClass: GovernanceFrictionClass::F3,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'required',
canonicalLabel: 'Cancel',
modalHeading: 'Cancel run',
modalDescription: 'Cancel this in-flight run. TenantPilot records the cancellation reason and marks the run as failed.',
successTitle: 'Run cancelled',
auditVerb: 'cancel run',
serviceOwner: 'OperationRunTriageService',
surfaceKeys: ['system_view_run'],
),
'close_finding' => new GovernanceActionRule(
actionKey: 'close_finding',
familyKey: 'finding_lifecycle',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'none',
canonicalLabel: 'Close',
modalHeading: 'Close finding',
modalDescription: 'Close this finding for the current tenant. TenantPilot records the closing rationale and closes the finding lifecycle.',
successTitle: 'Finding closed',
auditVerb: 'close finding',
serviceOwner: 'FindingWorkflowService',
surfaceKeys: ['view_finding', 'finding_list_row', 'finding_bulk'],
),
'reopen_finding' => new GovernanceActionRule(
actionKey: 'reopen_finding',
familyKey: 'finding_lifecycle',
frictionClass: GovernanceFrictionClass::F2,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'none',
canonicalLabel: 'Reopen',
modalHeading: 'Reopen finding',
modalDescription: 'Reopen this closed finding for the current tenant. TenantPilot records why the lifecycle is being reopened and recalculates due attention.',
successTitle: 'Finding reopened',
auditVerb: 'reopen finding',
serviceOwner: 'FindingWorkflowService',
surfaceKeys: ['view_finding', 'finding_list_row', 'finding_bulk'],
),
'archive_tenant' => new GovernanceActionRule(
actionKey: 'archive_tenant',
familyKey: 'tenant_lifecycle',
frictionClass: GovernanceFrictionClass::F3,
reasonPolicy: GovernanceReasonPolicy::Required,
dangerPolicy: 'required',
canonicalLabel: 'Archive',
modalHeading: 'Archive tenant',
modalDescription: 'Archive this tenant. TenantPilot keeps it available for inspection and audit history but removes it from active management flows.',
successTitle: 'Tenant archived',
auditVerb: 'archive tenant',
serviceOwner: 'TenantResource',
surfaceKeys: ['tenant_index_row', 'view_tenant', 'edit_tenant'],
),
'restore_tenant' => new GovernanceActionRule(
actionKey: 'restore_tenant',
familyKey: 'tenant_lifecycle',
frictionClass: GovernanceFrictionClass::F1,
reasonPolicy: GovernanceReasonPolicy::None,
dangerPolicy: 'none',
canonicalLabel: 'Restore',
modalHeading: 'Restore tenant',
modalDescription: 'Restore this tenant so it becomes available again in normal management flows.',
successTitle: 'Tenant restored',
auditVerb: 'restore tenant',
serviceOwner: 'TenantResource',
surfaceKeys: ['tenant_index_row', 'view_tenant', 'edit_tenant'],
),
];
}
public static function rule(string $actionKey): GovernanceActionRule
{
$rule = static::rules()[$actionKey] ?? null;
if (! $rule instanceof GovernanceActionRule) {
throw new InvalidArgumentException(sprintf('Unknown governance action "%s".', $actionKey));
}
return $rule;
}
/**
* @return array<int, array{
* surfaceKey: string,
* pageClass: string,
* actionName: string,
* familyKey: string,
* statePredicate: string,
* primaryOrSecondary: string,
* capabilityKey: string|null,
* uiFieldKey: string|null,
* auditChannel: string
* }>
*/
public static function surfaceBindings(): array
{
return [
[
'surfaceKey' => 'finding_exceptions_queue',
'pageClass' => 'App\\Filament\\Pages\\Monitoring\\FindingExceptionsQueue',
'actionName' => 'approve_selected_exception',
'familyKey' => 'exception_decision',
'statePredicate' => 'selected exception is pending',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'finding_exception.approve',
'uiFieldKey' => 'approval_reason',
'auditChannel' => 'tenant_audit',
],
[
'surfaceKey' => 'finding_exceptions_queue',
'pageClass' => 'App\\Filament\\Pages\\Monitoring\\FindingExceptionsQueue',
'actionName' => 'reject_selected_exception',
'familyKey' => 'exception_decision',
'statePredicate' => 'selected exception is pending',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'finding_exception.approve',
'uiFieldKey' => 'rejection_reason',
'auditChannel' => 'tenant_audit',
],
[
'surfaceKey' => 'view_finding_exception',
'pageClass' => 'App\\Filament\\Resources\\FindingExceptionResource\\Pages\\ViewFindingException',
'actionName' => 'renew_exception',
'familyKey' => 'exception_decision',
'statePredicate' => 'exception can be renewed',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'finding_exception.manage',
'uiFieldKey' => 'request_reason',
'auditChannel' => 'tenant_audit',
],
[
'surfaceKey' => 'view_finding_exception',
'pageClass' => 'App\\Filament\\Resources\\FindingExceptionResource\\Pages\\ViewFindingException',
'actionName' => 'revoke_exception',
'familyKey' => 'exception_decision',
'statePredicate' => 'exception can be revoked',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'finding_exception.manage',
'uiFieldKey' => 'revocation_reason',
'auditChannel' => 'tenant_audit',
],
[
'surfaceKey' => 'view_evidence_snapshot',
'pageClass' => 'App\\Filament\\Resources\\EvidenceSnapshotResource\\Pages\\ViewEvidenceSnapshot',
'actionName' => 'refresh_evidence',
'familyKey' => 'evidence_lifecycle',
'statePredicate' => 'snapshot is visible to tenant operator',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'evidence.manage',
'uiFieldKey' => null,
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'view_evidence_snapshot',
'pageClass' => 'App\\Filament\\Resources\\EvidenceSnapshotResource\\Pages\\ViewEvidenceSnapshot',
'actionName' => 'expire_snapshot',
'familyKey' => 'evidence_lifecycle',
'statePredicate' => 'snapshot can expire',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'evidence.manage',
'uiFieldKey' => 'expiration_reason',
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'list_evidence_snapshots',
'pageClass' => 'App\\Filament\\Resources\\EvidenceSnapshotResource',
'actionName' => 'expire',
'familyKey' => 'evidence_lifecycle',
'statePredicate' => 'snapshot can expire',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'evidence.manage',
'uiFieldKey' => 'expiration_reason',
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'view_tenant_review',
'pageClass' => 'App\\Filament\\Resources\\TenantReviewResource\\Pages\\ViewTenantReview',
'actionName' => 'refresh_review',
'familyKey' => 'review_lifecycle',
'statePredicate' => 'review is mutable',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'tenant_review.manage',
'uiFieldKey' => null,
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'view_tenant_review',
'pageClass' => 'App\\Filament\\Resources\\TenantReviewResource\\Pages\\ViewTenantReview',
'actionName' => 'publish_review',
'familyKey' => 'review_lifecycle',
'statePredicate' => 'review is mutable and ready to publish',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'tenant_review.manage',
'uiFieldKey' => 'publish_reason',
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'view_tenant_review',
'pageClass' => 'App\\Filament\\Resources\\TenantReviewResource\\Pages\\ViewTenantReview',
'actionName' => 'archive_review',
'familyKey' => 'review_lifecycle',
'statePredicate' => 'review is not terminal',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant_review.manage',
'uiFieldKey' => 'archive_reason',
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'system_view_run',
'pageClass' => 'App\\Filament\\System\\Pages\\Ops\\ViewRun',
'actionName' => 'retry',
'familyKey' => 'run_triage',
'statePredicate' => 'run is retryable',
'primaryOrSecondary' => 'primary',
'capabilityKey' => 'platform.operations.manage',
'uiFieldKey' => null,
'auditChannel' => 'system_audit',
],
[
'surfaceKey' => 'system_view_run',
'pageClass' => 'App\\Filament\\System\\Pages\\Ops\\ViewRun',
'actionName' => 'mark_investigated',
'familyKey' => 'run_triage',
'statePredicate' => 'run is triage-owned',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'platform.operations.manage',
'uiFieldKey' => 'reason',
'auditChannel' => 'system_audit',
],
[
'surfaceKey' => 'system_view_run',
'pageClass' => 'App\\Filament\\System\\Pages\\Ops\\ViewRun',
'actionName' => 'cancel',
'familyKey' => 'run_triage',
'statePredicate' => 'run is cancellable',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'platform.operations.manage',
'uiFieldKey' => 'reason',
'auditChannel' => 'system_audit',
],
[
'surfaceKey' => 'view_finding',
'pageClass' => 'App\\Filament\\Resources\\FindingResource\\Pages\\ViewFinding',
'actionName' => 'close',
'familyKey' => 'finding_lifecycle',
'statePredicate' => 'finding has open status',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant_findings.close',
'uiFieldKey' => 'closed_reason',
'auditChannel' => 'tenant_audit',
],
[
'surfaceKey' => 'view_finding',
'pageClass' => 'App\\Filament\\Resources\\FindingResource\\Pages\\ViewFinding',
'actionName' => 'reopen',
'familyKey' => 'finding_lifecycle',
'statePredicate' => 'finding has terminal status',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant_findings.triage',
'uiFieldKey' => 'reopen_reason',
'auditChannel' => 'tenant_audit',
],
[
'surfaceKey' => 'view_tenant',
'pageClass' => 'App\\Filament\\Resources\\TenantResource\\Pages\\ViewTenant',
'actionName' => 'archive',
'familyKey' => 'tenant_lifecycle',
'statePredicate' => 'tenant is active',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant.delete',
'uiFieldKey' => 'archive_reason',
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'view_tenant',
'pageClass' => 'App\\Filament\\Resources\\TenantResource\\Pages\\ViewTenant',
'actionName' => 'restore',
'familyKey' => 'tenant_lifecycle',
'statePredicate' => 'tenant is archived',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant.delete',
'uiFieldKey' => null,
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'edit_tenant',
'pageClass' => 'App\\Filament\\Resources\\TenantResource\\Pages\\EditTenant',
'actionName' => 'archive',
'familyKey' => 'tenant_lifecycle',
'statePredicate' => 'tenant is active',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant.delete',
'uiFieldKey' => 'archive_reason',
'auditChannel' => 'workspace_audit',
],
[
'surfaceKey' => 'edit_tenant',
'pageClass' => 'App\\Filament\\Resources\\TenantResource\\Pages\\EditTenant',
'actionName' => 'restore',
'familyKey' => 'tenant_lifecycle',
'statePredicate' => 'tenant is archived',
'primaryOrSecondary' => 'secondary',
'capabilityKey' => 'tenant.delete',
'uiFieldKey' => null,
'auditChannel' => 'workspace_audit',
],
];
}
/**
* @return array<int, array{
* actionKey: string,
* surfaceKey: string,
* deviationType: string,
* rationale: string,
* reviewGate: string,
* allowedUntil: string|null
* }>
*/
public static function documentedDeviations(): array
{
return [
[
'actionKey' => 'reject_exception',
'surfaceKey' => 'finding_exceptions_queue',
'deviationType' => 'danger_override',
'rationale' => 'Reject stays visually distinct from approval without escalating into the F3 destructive family.',
'reviewGate' => 'Spec194GovernanceActionSemanticsGuardTest',
'allowedUntil' => null,
],
[
'actionKey' => 'refresh_evidence',
'surfaceKey' => 'view_evidence_snapshot',
'deviationType' => 'reason_override',
'rationale' => 'Refresh evidence remains an F1 action with no operator-entered rationale in the current release.',
'reviewGate' => 'Spec194GovernanceActionSemanticsGuardTest',
'allowedUntil' => null,
],
[
'actionKey' => 'retry_run',
'surfaceKey' => 'system_view_run',
'deviationType' => 'reason_override',
'rationale' => 'Retry stays queue-first and does not collect free-text rationale unless a documented future case requires it.',
'reviewGate' => 'Spec194GovernanceActionSemanticsGuardTest',
'allowedUntil' => null,
],
[
'actionKey' => 'restore_tenant',
'surfaceKey' => 'view_tenant',
'deviationType' => 'reason_override',
'rationale' => 'Restore remains a confirmed F1 lifecycle action with no required rationale in the current release.',
'reviewGate' => 'Spec194GovernanceActionSemanticsGuardTest',
'allowedUntil' => null,
],
];
}
/**
* @return array<int, array{
* surfaceKey: string,
* pageClass: string,
* actionName: string,
* familyKey: string,
* statePredicate: string,
* primaryOrSecondary: string,
* capabilityKey: string|null,
* uiFieldKey: string|null,
* auditChannel: string
* }>
*/
public static function bindingsForSurface(string $surfaceKey): array
{
return array_values(array_filter(
static::surfaceBindings(),
static fn (array $binding): bool => $binding['surfaceKey'] === $surfaceKey,
));
}
/**
* @return array<int, string>
*/
public static function actionKeys(): array
{
return array_keys(static::rules());
}
}

View File

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Support\Ui\GovernanceActions;
use App\Support\Ui\GovernanceActions\Enums\GovernanceFrictionClass;
use App\Support\Ui\GovernanceActions\Enums\GovernanceReasonPolicy;
final readonly class GovernanceActionRule
{
/**
* @param array<int, string> $surfaceKeys
*/
public function __construct(
public string $actionKey,
public string $familyKey,
public GovernanceFrictionClass $frictionClass,
public GovernanceReasonPolicy $reasonPolicy,
public string $dangerPolicy,
public string $canonicalLabel,
public string $modalHeading,
public string $modalDescription,
public string $successTitle,
public string $auditVerb,
public string $serviceOwner,
public array $surfaceKeys = [],
) {}
public function requiresConfirmation(): bool
{
return $this->frictionClass->requiresConfirmation();
}
public function requiresReason(): bool
{
return $this->reasonPolicy->requiresReason();
}
public function requiresDangerSeparation(): bool
{
return $this->dangerPolicy === 'required';
}
}

View File

@ -4,6 +4,9 @@
use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\SuppressDebugbarForSmokeRequests;
use App\Http\Middleware\UseSystemSessionCookieForLivewireRequests;
return Application::configure(basePath: dirname(__DIR__)) return Application::configure(basePath: dirname(__DIR__))
->withRouting( ->withRouting(
web: __DIR__.'/../routes/web.php', web: __DIR__.'/../routes/web.php',
@ -11,8 +14,14 @@
health: '/up', health: '/up',
) )
->withMiddleware(function (Middleware $middleware): void { ->withMiddleware(function (Middleware $middleware): void {
$middleware->prepend(SuppressDebugbarForSmokeRequests::class);
$middleware->encryptCookies(except: [
SuppressDebugbarForSmokeRequests::COOKIE_NAME,
]);
$middleware->web(prepend: [ $middleware->web(prepend: [
\App\Http\Middleware\UseSystemSessionCookieForLivewireRequests::class, UseSystemSessionCookieForLivewireRequests::class,
]); ]);
$middleware->alias([ $middleware->alias([

View File

@ -1,4 +1,20 @@
<x-filament-panels::page> <x-filament-panels::page>
@php($navigationContext = \App\Support\Navigation\CanonicalNavigationContext::fromRequest(request()))
@if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null)
<x-filament::section class="mb-6">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div class="text-sm text-gray-600 dark:text-gray-300">
Return path stays quiet while this overview remains focused on alert health and downstream drilldowns.
</div>
<x-filament::button tag="a" color="gray" :href="$navigationContext->backLinkUrl">
{{ $navigationContext->backLinkLabel }}
</x-filament::button>
</div>
</x-filament::section>
@endif
<x-filament::section> <x-filament::section>
<div class="flex flex-col gap-3"> <div class="flex flex-col gap-3">
<div class="text-sm text-gray-600 dark:text-gray-300"> <div class="text-sm text-gray-600 dark:text-gray-300">

View File

@ -14,10 +14,51 @@
</x-filament::section> </x-filament::section>
@if ($this->showSelectedExceptionSummary && $selectedException) @if ($this->showSelectedExceptionSummary && $selectedException)
<x-filament::section> <x-filament::section heading="Focused review lane">
@include('filament.pages.monitoring.partials.finding-exception-queue-sidebar', [ <x-slot name="description">
'selectedException' => $selectedException, Selection-bound decisions now define the active work lane. Scope, filters, and drilldowns stay visible without competing with the current review step.
]) </x-slot>
<div class="grid gap-6 xl:grid-cols-[minmax(0,2fr)_minmax(22rem,26rem)]">
@include('filament.pages.monitoring.partials.finding-exception-queue-sidebar', [
'selectedException' => $selectedException,
])
<div class="grid gap-4">
<div class="rounded-2xl border border-primary-200 bg-primary-50/80 p-4 shadow-sm dark:border-primary-500/30 dark:bg-primary-500/10">
<div class="text-sm font-semibold text-primary-900 dark:text-primary-100">
Decision lane
</div>
<div class="mt-2 text-sm text-primary-800 dark:text-primary-200">
@if ($selectedException->isPending())
Approve exception and Reject exception are the only promoted next steps while this request remains pending.
@else
This exception is no longer decision-ready. Use the selected context group to close details or drill into related records.
@endif
</div>
</div>
<div class="rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
<div class="text-sm font-semibold text-gray-900 dark:text-gray-100">
Related drilldown
</div>
<div class="mt-2 text-sm text-gray-600 dark:text-gray-300">
Open tenant detail and Open finding stay available for context, but they no longer share the same semantic lane as the review decision.
</div>
</div>
</div>
</div>
</x-filament::section>
@else
<x-filament::section heading="Quiet monitoring mode">
<x-slot name="description">
Inspect an exception to enter the focused review lane. Scope, filters, and tenant drilldowns stay secondary until one request is actively under review.
</x-slot>
<div class="text-sm text-gray-600 dark:text-gray-300">
No exception is selected right now. Use Inspect exception from the queue to review one request in context.
</div>
</x-filament::section> </x-filament::section>
@endif @endif

View File

@ -1,8 +1,45 @@
<x-filament-panels::page> <x-filament-panels::page>
@php($landingHierarchy = $this->landingHierarchySummary())
@php($lifecycleSummary = $this->lifecycleVisibilitySummary()) @php($lifecycleSummary = $this->lifecycleVisibilitySummary())
@php($staleAttentionTab = \App\Models\OperationRun::PROBLEM_CLASS_ACTIVE_STALE_ATTENTION) @php($staleAttentionTab = \App\Models\OperationRun::PROBLEM_CLASS_ACTIVE_STALE_ATTENTION)
@php($terminalFollowUpTab = \App\Models\OperationRun::PROBLEM_CLASS_TERMINAL_FOLLOW_UP) @php($terminalFollowUpTab = \App\Models\OperationRun::PROBLEM_CLASS_TERMINAL_FOLLOW_UP)
<x-filament::section heading="Monitoring landing" class="mb-6">
<p class="text-sm text-gray-600 dark:text-gray-400">
Tabs, filters, and row inspection define the active work lane. Scope context and return navigation stay secondary.
</p>
<div class="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Scope context</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">{{ $landingHierarchy['scope_label'] }}</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $landingHierarchy['scope_body'] }}</p>
</div>
@if ($landingHierarchy['return_label'] !== null && $landingHierarchy['return_body'] !== null)
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Return path</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">{{ $landingHierarchy['return_label'] }}</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $landingHierarchy['return_body'] }}</p>
</div>
@endif
@if ($landingHierarchy['scope_reset_label'] !== null && $landingHierarchy['scope_reset_body'] !== null)
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Scope reset</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">{{ $landingHierarchy['scope_reset_label'] }}</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $landingHierarchy['scope_reset_body'] }}</p>
</div>
@endif
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Inspect flow</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">Open run detail</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $landingHierarchy['inspect_body'] }}</p>
</div>
</div>
</x-filament::section>
<x-filament::tabs label="Operations tabs"> <x-filament::tabs label="Operations tabs">
<x-filament::tabs.item <x-filament::tabs.item
:active="$this->activeTab === 'all'" :active="$this->activeTab === 'all'"
@ -57,3 +94,4 @@
{{ $this->table }} {{ $this->table }}
</x-filament-panels::page> </x-filament-panels::page>

View File

@ -3,6 +3,7 @@
$blockedBanner = $this->blockedExecutionBanner(); $blockedBanner = $this->blockedExecutionBanner();
$lifecycleBanner = $this->lifecycleBanner(); $lifecycleBanner = $this->lifecycleBanner();
$restoreContinuationBanner = $this->restoreContinuationBanner(); $restoreContinuationBanner = $this->restoreContinuationBanner();
$monitoringDetail = $this->monitoringDetailSummary();
$pollInterval = $this->pollInterval(); $pollInterval = $this->pollInterval();
@endphp @endphp
@ -10,6 +11,44 @@
<div <div
@if ($pollInterval !== null) wire:poll.{{ $pollInterval }} @endif @if ($pollInterval !== null) wire:poll.{{ $pollInterval }} @endif
> >
<x-filament::section heading="Monitoring detail" class="mb-6">
<p class="text-sm text-gray-600 dark:text-gray-400">
Scope context, return navigation, utility, related drilldowns, and run-specific follow-up stay in separate lanes on this viewer.
</p>
<div class="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-5">
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Scope context</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">{{ $monitoringDetail['scope_label'] }}</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $monitoringDetail['scope_body'] }}</p>
</div>
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Navigation lane</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">{{ $monitoringDetail['navigation_label'] }}</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $monitoringDetail['navigation_body'] }}</p>
</div>
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Utility lane</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">Refresh</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $monitoringDetail['utility_body'] }}</p>
</div>
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Related drilldown</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">Open</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $monitoringDetail['related_body'] }}</p>
</div>
<div class="rounded-xl border border-gray-200 bg-white/80 p-4 dark:border-white/10 dark:bg-white/5">
<p class="text-xs font-semibold uppercase tracking-[0.2em] text-gray-500 dark:text-gray-400">Follow-up lane</p>
<p class="mt-2 text-sm font-semibold text-gray-900 dark:text-white">{{ $monitoringDetail['follow_up_label'] ?? 'No follow-up action' }}</p>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ $monitoringDetail['follow_up_body'] }}</p>
</div>
</div>
</x-filament::section>
@if ($contextBanner !== null) @if ($contextBanner !== null)
@php @php
$bannerClasses = match ($contextBanner['tone']) { $bannerClasses = match ($contextBanner['tone']) {

View File

@ -10,12 +10,14 @@
use App\Http\Controllers\SelectTenantController; use App\Http\Controllers\SelectTenantController;
use App\Http\Controllers\SwitchWorkspaceController; use App\Http\Controllers\SwitchWorkspaceController;
use App\Http\Controllers\TenantOnboardingController; use App\Http\Controllers\TenantOnboardingController;
use App\Http\Middleware\SuppressDebugbarForSmokeRequests;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\TenantOnboardingSession; use App\Models\TenantOnboardingSession;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Onboarding\OnboardingDraftResolver; use App\Services\Onboarding\OnboardingDraftResolver;
use App\Support\Auth\WorkspaceRole;
use App\Services\Tenants\TenantOperabilityService; use App\Services\Tenants\TenantOperabilityService;
use App\Support\Tenants\TenantOperabilityQuestion; use App\Support\Tenants\TenantOperabilityQuestion;
use App\Support\Tenants\TenantPageCategory; use App\Support\Tenants\TenantPageCategory;
@ -65,7 +67,213 @@
->middleware('throttle:entra-callback') ->middleware('throttle:entra-callback')
->name('auth.entra.callback'); ->name('auth.entra.callback');
Route::get('/admin/local/backup-health-browser-fixture-login', function (Request $request) { $makeSmokeCookie = static fn () => cookie()->make(
SuppressDebugbarForSmokeRequests::COOKIE_NAME,
SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
120,
);
$resolveSmokeTenant = static function (?string $identifier): ?Tenant {
$identifier = trim((string) $identifier);
if ($identifier === '') {
return null;
}
return Tenant::query()
->withTrashed()
->where(function ($query) use ($identifier): void {
$query->where('external_id', $identifier)
->orWhere('tenant_id', $identifier);
if (ctype_digit($identifier)) {
$query->orWhereKey((int) $identifier);
}
})
->first();
};
$resolveSmokeWorkspace = static function (?string $identifier, ?Tenant $tenant = null): ?Workspace {
if ($tenant instanceof Tenant) {
return Workspace::query()->whereKey($tenant->workspace_id)->first();
}
$identifier = trim((string) $identifier);
if ($identifier === '') {
return null;
}
return Workspace::query()
->where(function ($query) use ($identifier): void {
$query->where('slug', $identifier);
if (ctype_digit($identifier)) {
$query->orWhereKey((int) $identifier);
}
})
->first();
};
$resolveSmokeRedirect = static function (?string $redirect, ?Tenant $tenant = null): string {
$fallback = $tenant instanceof Tenant && ! $tenant->trashed()
? '/admin/t/'.$tenant->external_id
: '/admin';
$redirect = trim((string) $redirect);
if ($redirect === '') {
return $fallback;
}
$parsedRedirect = parse_url($redirect);
if ($parsedRedirect === false || isset($parsedRedirect['scheme']) || isset($parsedRedirect['host'])) {
return $fallback;
}
$path = '/'.ltrim((string) ($parsedRedirect['path'] ?? ''), '/');
if ($path !== '/admin' && ! str_starts_with($path, '/admin/')) {
return $fallback;
}
$query = isset($parsedRedirect['query']) ? '?'.$parsedRedirect['query'] : '';
$fragment = isset($parsedRedirect['fragment']) ? '#'.$parsedRedirect['fragment'] : '';
return $path.$query.$fragment;
};
$resolveSmokeUser = static function (?string $email, ?Workspace $workspace = null, ?Tenant $tenant = null): ?User {
$email = trim((string) $email);
if ($email !== '') {
$user = User::query()->where('email', $email)->first();
return $user instanceof User ? $user : null;
}
$scopedWorkspace = $workspace;
if (! $scopedWorkspace instanceof Workspace && $tenant instanceof Tenant) {
$scopedWorkspace = Workspace::query()->whereKey($tenant->workspace_id)->first();
}
if (! $scopedWorkspace instanceof Workspace) {
return null;
}
$rolePriority = [
WorkspaceRole::Owner->value => 0,
WorkspaceRole::Manager->value => 1,
WorkspaceRole::Operator->value => 2,
WorkspaceRole::Readonly->value => 3,
];
$users = User::query()
->whereHas('workspaceMemberships', function ($query) use ($scopedWorkspace): void {
$query->where('workspace_id', (int) $scopedWorkspace->getKey());
})
->when($tenant instanceof Tenant, function ($query) use ($tenant): void {
$query->whereHas('tenantMemberships', function ($membershipQuery) use ($tenant): void {
$membershipQuery->where('tenant_id', (int) $tenant->getKey());
});
})
->with(['workspaceMemberships' => function ($query) use ($scopedWorkspace): void {
$query->where('workspace_id', (int) $scopedWorkspace->getKey());
}])
->get()
->filter(function (User $user) use ($tenant): bool {
return ! $tenant instanceof Tenant || $user->canAccessTenant($tenant);
})
->sortBy(function (User $user) use ($rolePriority): array {
$role = $user->workspaceMemberships->first()?->role;
return [
$rolePriority[(string) $role] ?? 99,
(int) $user->getKey(),
];
})
->values();
$user = $users->first();
return $user instanceof User ? $user : null;
};
$completeSmokeLogin = static function (
Request $request,
?string $email = null,
?string $tenantIdentifier = null,
?string $workspaceIdentifier = null,
?string $redirect = null,
) use (
$makeSmokeCookie,
$resolveSmokeRedirect,
$resolveSmokeTenant,
$resolveSmokeUser,
$resolveSmokeWorkspace,
): \Illuminate\Http\RedirectResponse {
$tenant = $resolveSmokeTenant($tenantIdentifier);
$workspace = $resolveSmokeWorkspace($workspaceIdentifier, $tenant);
$user = $resolveSmokeUser($email, $workspace, $tenant);
abort_unless($user instanceof User, 404);
$workspaceContext = app(WorkspaceContext::class);
if (! $workspace instanceof Workspace) {
$workspace = $workspaceContext->resolveInitialWorkspaceFor($user, $request);
}
abort_unless($workspace instanceof Workspace, 404);
abort_unless($workspaceContext->isMember($user, $workspace), 404);
if ($tenant instanceof Tenant) {
abort_unless((int) $tenant->workspace_id === (int) $workspace->getKey(), 404);
abort_unless($user->canAccessTenant($tenant), 404);
}
Auth::guard('web')->login($user);
$request->session()->regenerate();
$request->session()->put(
SuppressDebugbarForSmokeRequests::SESSION_KEY,
SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
);
$workspaceContext->setCurrentWorkspace($workspace, $user, $request);
if ($tenant instanceof Tenant) {
$workspaceContext->rememberTenantContext($tenant, $request);
} else {
$workspaceContext->clearRememberedTenantContext($request);
}
return redirect()
->to($resolveSmokeRedirect($redirect, $tenant))
->withCookie($makeSmokeCookie());
};
Route::get('/admin/local/smoke-login', function (Request $request) use ($completeSmokeLogin) {
abort_unless(app()->environment(['local', 'testing']), 404);
$fixture = config('tenantpilot.backup_health.browser_smoke_fixture');
$defaultEmail = is_array($fixture) ? data_get($fixture, 'user.email') : null;
$defaultTenant = is_array($fixture)
? (data_get($fixture, 'blocked_drillthrough.tenant_external_id') ?? data_get($fixture, 'blocked_drillthrough.tenant_id'))
: null;
$defaultWorkspace = is_array($fixture) ? data_get($fixture, 'workspace.slug') : null;
return $completeSmokeLogin(
$request,
email: (string) ($request->query('email', $defaultEmail ?? '')),
tenantIdentifier: (string) ($request->query('tenant', $defaultTenant ?? '')),
workspaceIdentifier: (string) ($request->query('workspace', $defaultWorkspace ?? '')),
redirect: (string) ($request->query('redirect', '')),
);
})->name('admin.local.smoke-login');
Route::get('/admin/local/backup-health-browser-fixture-login', function (Request $request) use ($completeSmokeLogin) {
abort_unless(app()->environment(['local', 'testing']), 404); abort_unless(app()->environment(['local', 'testing']), 404);
$fixture = config('tenantpilot.backup_health.browser_smoke_fixture'); $fixture = config('tenantpilot.backup_health.browser_smoke_fixture');
@ -77,18 +285,12 @@
abort_unless(is_string($userEmail) && $userEmail !== '', 404); abort_unless(is_string($userEmail) && $userEmail !== '', 404);
abort_unless(is_string($tenantRouteKey) && $tenantRouteKey !== '', 404); abort_unless(is_string($tenantRouteKey) && $tenantRouteKey !== '', 404);
$user = User::query()->where('email', $userEmail)->firstOrFail(); return $completeSmokeLogin(
$tenant = Tenant::query()->where('external_id', $tenantRouteKey)->firstOrFail(); $request,
$workspace = Workspace::query()->whereKey($tenant->workspace_id)->firstOrFail(); email: $userEmail,
tenantIdentifier: $tenantRouteKey,
Auth::login($user); workspaceIdentifier: is_array($fixture) ? data_get($fixture, 'workspace.slug') : null,
$request->session()->regenerate(); );
$workspaceContext = app(WorkspaceContext::class);
$workspaceContext->setCurrentWorkspace($workspace, $user, $request);
$workspaceContext->rememberTenantContext($tenant, $request);
return redirect()->to('/admin/t/'.$tenant->external_id);
})->name('admin.local.backup-health-browser-fixture-login'); })->name('admin.local.backup-health-browser-fixture-login');
Route::middleware(['web', 'auth', 'ensure-correct-guard:web']) Route::middleware(['web', 'auth', 'ensure-correct-guard:web'])

View File

@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Models\Finding;
use App\Models\FindingException;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\TenantMembership;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
pest()->browser()->timeout(15_000);
uses(RefreshDatabase::class);
it('smokes remediated, calm-reference, and explicit-exception monitoring surfaces', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');
$finding = Finding::factory()->for($tenant)->create();
FindingException::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'finding_id' => (int) $finding->getKey(),
'requested_by_user_id' => (int) $user->getKey(),
'owner_user_id' => (int) $user->getKey(),
'status' => FindingException::STATUS_PENDING,
'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
'request_reason' => 'Browser hierarchy smoke',
'requested_at' => now()->subDay(),
'review_due_at' => now()->addDay(),
'evidence_summary' => ['reference_count' => 0],
]);
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => null,
'type' => 'provider.connection.check',
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::Succeeded->value,
]);
$diagnosticsTenant = Tenant::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
]);
createUserWithTenant(
tenant: $diagnosticsTenant,
user: $user,
role: 'readonly',
workspaceRole: 'manager',
ensureDefaultMicrosoftProviderConnection: false,
);
TenantMembership::query()
->where('tenant_id', (int) $diagnosticsTenant->getKey())
->update(['role' => 'readonly']);
$this->actingAs($user)->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
]);
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
Filament::setTenant(null, true);
visit(FindingExceptionsQueue::getUrl(panel: 'admin'))
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Quiet monitoring mode');
visit(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Monitoring detail')
->assertSee('Follow-up lane');
visit('/admin/alerts')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Alert deliveries');
visit('/admin/t/'.$diagnosticsTenant->external_id.'/diagnostics')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Missing owner');
});

View File

@ -0,0 +1,274 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Filament\Resources\EvidenceSnapshotResource;
use App\Filament\Resources\FindingExceptionResource;
use App\Filament\Resources\TenantResource;
use App\Filament\Resources\TenantReviewResource;
use App\Models\EvidenceSnapshot;
use App\Models\Finding;
use App\Models\FindingException;
use App\Models\OperationRun;
use App\Models\PlatformUser;
use App\Models\ReviewPack;
use App\Models\Tenant;
use App\Models\User;
use App\Services\Findings\FindingExceptionService;
use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\TenantReviewCompletenessState;
use App\Support\TenantReviewStatus;
use App\Support\Auth\PlatformCapabilities;
use App\Support\System\SystemOperationRunLinks;
use Illuminate\Foundation\Testing\RefreshDatabase;
pest()->browser()->timeout(20_000);
uses(RefreshDatabase::class);
function spec194ApprovedFindingException(Tenant $tenant, User $requester): FindingException
{
$approver = User::factory()->create();
createUserWithTenant(
tenant: $tenant,
user: $approver,
role: 'owner',
workspaceRole: 'manager',
ensureDefaultMicrosoftProviderConnection: false,
);
$finding = Finding::factory()->for($tenant)->create([
'workspace_id' => (int) $tenant->workspace_id,
'status' => Finding::STATUS_RISK_ACCEPTED,
]);
/** @var FindingExceptionService $service */
$service = app(FindingExceptionService::class);
$requested = $service->request($finding, $tenant, $requester, [
'owner_user_id' => (int) $requester->getKey(),
'request_reason' => 'Spec194 browser smoke request.',
'review_due_at' => now()->addDays(7)->toDateTimeString(),
'expires_at' => now()->addDays(14)->toDateTimeString(),
]);
return $service->approve($requested, $approver, [
'effective_from' => now()->subDay()->toDateTimeString(),
'expires_at' => now()->addDays(14)->toDateTimeString(),
'approval_reason' => 'Spec194 browser smoke approval.',
]);
}
function spec194SmokeLoginUrl(User $user, Tenant $tenant, string $redirect = ''): string
{
return route('admin.local.smoke-login', array_filter([
'email' => $user->email,
'tenant' => $tenant->external_id,
'workspace' => $tenant->workspace->slug,
'redirect' => $redirect,
], static fn (?string $value): bool => filled($value)));
}
it('smokes tenant and admin governance semantics through modal entry points', function (): void {
[$user, $tenant] = createUserWithTenant(
role: 'owner',
workspaceRole: 'manager',
ensureDefaultMicrosoftProviderConnection: false,
);
$finding = Finding::factory()->for($tenant)->create();
$pendingException = FindingException::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'finding_id' => (int) $finding->getKey(),
'requested_by_user_id' => (int) $user->getKey(),
'owner_user_id' => (int) $user->getKey(),
'status' => FindingException::STATUS_PENDING,
'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
'request_reason' => 'Spec194 focused review queue smoke.',
'requested_at' => now()->subDay(),
'review_due_at' => now()->addDay(),
'evidence_summary' => ['reference_count' => 0],
]);
$approvedException = spec194ApprovedFindingException($tenant, $user);
$snapshotRun = OperationRun::factory()->forTenant($tenant)->create([
'workspace_id' => (int) $tenant->workspace_id,
]);
$snapshot = EvidenceSnapshot::query()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'operation_run_id' => (int) $snapshotRun->getKey(),
'initiated_by_user_id' => (int) $user->getKey(),
'status' => EvidenceSnapshotStatus::Active->value,
'completeness_state' => EvidenceCompletenessState::Complete->value,
'summary' => ['finding_count' => 2],
'generated_at' => now(),
]);
ReviewPack::factory()->ready()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'evidence_snapshot_id' => (int) $snapshot->getKey(),
'initiated_by_user_id' => (int) $user->getKey(),
]);
$review = composeTenantReviewForTest($tenant, $user, $snapshot);
$review->forceFill([
'status' => TenantReviewStatus::Ready->value,
'completeness_state' => TenantReviewCompletenessState::Complete->value,
'summary' => array_replace_recursive(is_array($review->summary) ? $review->summary : [], [
'publish_blockers' => [],
'section_state_counts' => [
'complete' => 6,
'partial' => 0,
'missing' => 0,
'stale' => 0,
],
]),
])->save();
$review = $review->refresh();
$archivedTenant = Tenant::factory()->archived()->create([
'workspace_id' => (int) $tenant->workspace_id,
'name' => 'Spec194 Archived Tenant',
]);
createUserWithTenant(
tenant: $archivedTenant,
user: $user,
role: 'owner',
workspaceRole: 'manager',
ensureDefaultMicrosoftProviderConnection: false,
);
visit(spec194SmokeLoginUrl($user, $tenant))
->waitForText('Dashboard')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs();
visit(FindingExceptionsQueue::getUrl(panel: 'admin').'?exception='.(int) $pendingException->getKey())
->waitForText('Focused review lane')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Approve exception')
->assertSee('Reject exception');
visit(FindingExceptionResource::getUrl('view', ['record' => $approvedException], tenant: $tenant))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Renew exception')
->assertSee('Revoke exception');
visit(TenantReviewResource::tenantScopedUrl('view', ['record' => $review], $tenant))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->click('Publish review')
->waitForText('Publication reason')
->click('Cancel')
->click('[aria-label="More"]')
->assertSee('Refresh review')
->assertSee('Export executive pack')
->click('[aria-label="Danger"]')
->click('Archive review')
->waitForText('Archive reason')
->click('Cancel')
->assertSee('Publish review')
->assertSee('Evidence snapshot');
visit(EvidenceSnapshotResource::getUrl('view', ['record' => $snapshot], tenant: $tenant))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->click('Refresh evidence')
->waitForText('Confirm')
->click('Cancel')
->click('Expire snapshot')
->waitForText('Expiry reason')
->click('Cancel')
->assertSee('Refresh evidence')
->assertSee('Expire snapshot');
visit(TenantResource::getUrl('view', ['record' => $tenant], panel: 'admin'))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->click('[aria-label="Lifecycle"]')
->click('Archive')
->waitForText('Archive reason')
->click('Cancel')
->assertSee('Lifecycle');
visit(TenantResource::getUrl('edit', ['record' => $tenant], panel: 'admin'))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Lifecycle');
visit(TenantResource::getUrl('view', ['record' => $archivedTenant], panel: 'admin'))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Lifecycle');
visit(TenantResource::getUrl('edit', ['record' => $archivedTenant], panel: 'admin'))
->waitForText('Related context')
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Lifecycle');
});
it('smokes system run triage semantics without javascript errors', function (): void {
$failedRun = OperationRun::factory()->create([
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::Failed->value,
'type' => 'inventory_sync',
]);
$runningRun = OperationRun::factory()->create([
'status' => OperationRunStatus::Running->value,
'outcome' => OperationRunOutcome::Pending->value,
'type' => 'inventory_sync',
'created_at' => now()->subMinutes(15),
'started_at' => now()->subMinutes(10),
]);
$platformUser = PlatformUser::factory()->create([
'capabilities' => [
PlatformCapabilities::ACCESS_SYSTEM_PANEL,
PlatformCapabilities::OPERATIONS_VIEW,
PlatformCapabilities::OPERATIONS_MANAGE,
],
'is_active' => true,
]);
auth('web')->logout();
$this->flushSession();
$this->actingAs($platformUser, 'platform');
visit(SystemOperationRunLinks::view($failedRun))
->waitForText('Operation #'.(int) $failedRun->getKey())
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Retry')
->assertSee('Mark investigated')
->assertDontSee('Cancel');
visit(SystemOperationRunLinks::view($runningRun))
->waitForText('Operation #'.(int) $runningRun->getKey())
->assertNoJavaScriptErrors()
->assertNoConsoleLogs()
->assertSee('Mark investigated')
->assertSee('Cancel');
});

View File

@ -150,6 +150,55 @@ function alertDeliveryFilterIndicatorLabels($component): array
->assertCanNotSeeTableRecords([$deliveryB]); ->assertCanNotSeeTableRecords([$deliveryB]);
}); });
it('keeps deep-linked delivery filters while surfacing origin context quietly', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant(null, true);
$workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);
$destination = AlertDestination::factory()->create([
'workspace_id' => $workspaceId,
'is_enabled' => true,
]);
$rule = AlertRule::factory()->create([
'workspace_id' => $workspaceId,
]);
$sentDelivery = AlertDelivery::factory()->create([
'workspace_id' => $workspaceId,
'tenant_id' => (int) $tenant->getKey(),
'alert_rule_id' => (int) $rule->getKey(),
'alert_destination_id' => (int) $destination->getKey(),
'status' => AlertDelivery::STATUS_SENT,
]);
$failedDelivery = AlertDelivery::factory()->create([
'workspace_id' => $workspaceId,
'tenant_id' => (int) $tenant->getKey(),
'alert_rule_id' => (int) $rule->getKey(),
'alert_destination_id' => (int) $destination->getKey(),
'status' => AlertDelivery::STATUS_FAILED,
]);
Livewire::withQueryParams([
'nav' => [
'source_surface' => 'alerts.overview',
'canonical_route_name' => 'admin.alert-deliveries.index',
'back_label' => 'Back to alerts',
'back_url' => \App\Filament\Clusters\Monitoring\AlertsCluster::getUrl(panel: 'admin'),
],
])
->actingAs($user)
->test(ListAlertDeliveries::class)
->assertActionVisible('operate_hub_back_to_origin_alert_deliveries')
->filterTable('status', AlertDelivery::STATUS_SENT)
->assertCanSeeTableRecords([$sentDelivery])
->assertCanNotSeeTableRecords([$failedDelivery]);
});
it('replaces the persisted tenant filter when canonical tenant context changes', function (): void { it('replaces the persisted tenant filter when canonical tenant context changes', function (): void {
$tenantA = Tenant::factory()->create(); $tenantA = Tenant::factory()->create();
[$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner'); [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

View File

@ -23,6 +23,9 @@
return $action->getLabel() === 'Archive' && $action->isConfirmationRequired(); return $action->getLabel() === 'Archive' && $action->isConfirmationRequired();
}) })
->mountAction('archive') ->mountAction('archive')
->setActionData([
'archive_reason' => 'Retiring this tenant from active management.',
])
->callMountedAction() ->callMountedAction()
->assertHasNoActionErrors(); ->assertHasNoActionErrors();
@ -35,6 +38,15 @@
->where('action', AuditActionId::TenantArchived->value) ->where('action', AuditActionId::TenantArchived->value)
->exists())->toBeTrue(); ->exists())->toBeTrue();
$archiveAudit = AuditLog::query()
->where('workspace_id', (int) $tenant->workspace_id)
->where('tenant_id', (int) $tenant->getKey())
->where('action', AuditActionId::TenantArchived->value)
->latest('id')
->first();
expect(data_get($archiveAudit?->metadata, 'reason'))->toBe('Retiring this tenant from active management.');
Filament::setTenant(null, true); Filament::setTenant(null, true);
Livewire::actingAs($user) Livewire::actingAs($user)

View File

@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\TenantDashboard;
use App\Http\Middleware\SuppressDebugbarForSmokeRequests;
use Barryvdh\Debugbar\LaravelDebugbar;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
uses(RefreshDatabase::class);
it('logs into the admin smoke helper with explicit tenant and workspace context', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');
$response = $this->get(route('admin.local.smoke-login', [
'email' => $user->email,
'tenant' => $tenant->external_id,
'workspace' => $tenant->workspace->slug,
]));
$response
->assertRedirect(TenantDashboard::getUrl(tenant: $tenant))
->assertPlainCookie(
SuppressDebugbarForSmokeRequests::COOKIE_NAME,
SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
);
$this->assertAuthenticatedAs($user);
expect(session(App\Support\Workspaces\WorkspaceContext::SESSION_KEY))->toBe((int) $tenant->workspace_id)
->and(session(SuppressDebugbarForSmokeRequests::SESSION_KEY))
->toBe(SuppressDebugbarForSmokeRequests::COOKIE_VALUE)
->and(data_get(session(App\Support\Workspaces\WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY), (string) $tenant->workspace_id))
->toBe((int) $tenant->getKey());
$this->get(TenantDashboard::getUrl(tenant: $tenant))->assertSuccessful();
});
it('suppresses debugbar only for smoke-cookie requests and restores normal state afterward', function (): void {
config(['debugbar.enabled' => true]);
Route::middleware('web')->get('/__tests/smoke-debugbar-state', function () {
$debugbarState = null;
if (app()->bound('debugbar')) {
$debugbar = app('debugbar');
if ($debugbar instanceof LaravelDebugbar) {
$debugbarState = $debugbar->isEnabled();
}
}
return response()->json([
'config_enabled' => (bool) config('debugbar.enabled'),
'service_enabled' => $debugbarState,
]);
});
$smokeResponse = $this->withUnencryptedCookies([
SuppressDebugbarForSmokeRequests::COOKIE_NAME => SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
])->get('/__tests/smoke-debugbar-state');
$smokeResponse
->assertSuccessful()
->assertJsonPath('config_enabled', false);
if ($smokeResponse->json('service_enabled') !== null) {
expect($smokeResponse->json('service_enabled'))->toBeFalse();
}
config(['debugbar.enabled' => true]);
if (app()->bound('debugbar')) {
$debugbar = app('debugbar');
if ($debugbar instanceof LaravelDebugbar) {
$debugbar->enable();
}
}
$normalMiddlewareState = null;
$middleware = app(SuppressDebugbarForSmokeRequests::class);
$middleware->handle(Request::create('/admin/operations', 'GET'), function () use (&$normalMiddlewareState) {
$normalMiddlewareState = config('debugbar.enabled');
return response('ok');
});
expect($normalMiddlewareState)->toBeTrue();
});

View File

@ -4,6 +4,7 @@
use App\Filament\Pages\TenantDashboard; use App\Filament\Pages\TenantDashboard;
use App\Filament\Resources\BackupSetResource; use App\Filament\Resources\BackupSetResource;
use App\Http\Middleware\SuppressDebugbarForSmokeRequests;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
@ -27,7 +28,11 @@
expect($tenant)->not->toBeNull(); expect($tenant)->not->toBeNull();
$this->get(route('admin.local.backup-health-browser-fixture-login')) $this->get(route('admin.local.backup-health-browser-fixture-login'))
->assertRedirect(TenantDashboard::getUrl(tenant: $tenant)); ->assertRedirect(TenantDashboard::getUrl(tenant: $tenant))
->assertPlainCookie(
SuppressDebugbarForSmokeRequests::COOKIE_NAME,
SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
);
$this->assertAuthenticatedAs($user); $this->assertAuthenticatedAs($user);
expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $workspace->getKey()); expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $workspace->getKey());

View File

@ -49,7 +49,10 @@
->assertSee('Artifact truth') ->assertSee('Artifact truth')
->assertSee($tenantA->name) ->assertSee($tenantA->name)
->assertSee($tenantB->name) ->assertSee($tenantB->name)
->assertDontSee($foreignWorkspaceTenant->name); ->assertDontSee($foreignWorkspaceTenant->name)
->assertDontSee('Monitoring landing')
->assertDontSee('Navigation lane')
->assertDontSee('Focused review lane');
}); });
it('returns 404 for users without workspace membership on the evidence overview', function (): void { it('returns 404 for users without workspace membership on the evidence overview', function (): void {

View File

@ -20,8 +20,14 @@
'completeness_state' => EvidenceCompletenessState::Complete->value, 'completeness_state' => EvidenceCompletenessState::Complete->value,
]); ]);
app(App\Services\Evidence\EvidenceSnapshotService::class)->expire($snapshot, $user); app(App\Services\Evidence\EvidenceSnapshotService::class)->expire($snapshot, $user, 'Evidence basis is obsolete.');
$expiredAudit = AuditLog::query()
->where('action', AuditActionId::EvidenceSnapshotExpired->value)
->latest('id')
->first();
expect(AuditLog::query()->where('action', AuditActionId::EvidenceSnapshotCreated->value)->exists())->toBeTrue() expect(AuditLog::query()->where('action', AuditActionId::EvidenceSnapshotCreated->value)->exists())->toBeTrue()
->and(AuditLog::query()->where('action', AuditActionId::EvidenceSnapshotExpired->value)->exists())->toBeTrue(); ->and(AuditLog::query()->where('action', AuditActionId::EvidenceSnapshotExpired->value)->exists())->toBeTrue()
->and(data_get($expiredAudit?->metadata, 'reason'))->toBe('Evidence basis is obsolete.');
}); });

View File

@ -16,6 +16,8 @@
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Evidence\EvidenceCompletenessState; use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\Evidence\EvidenceSnapshotStatus; use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup; use Filament\Actions\ActionGroup;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@ -166,17 +168,41 @@ function evidenceSnapshotHeaderActions(Testable $component): array
$tenant->makeCurrent(); $tenant->makeCurrent();
Filament::setTenant($tenant, true); Filament::setTenant($tenant, true);
$component = Livewire::actingAs($user) $refreshRule = GovernanceActionCatalog::rule('refresh_evidence');
$expireRule = GovernanceActionCatalog::rule('expire_snapshot');
$refreshComponent = Livewire::actingAs($user)
->test(ViewEvidenceSnapshot::class, ['record' => $snapshot->getKey()]) ->test(ViewEvidenceSnapshot::class, ['record' => $snapshot->getKey()])
->assertActionVisible('refresh_snapshot') ->assertActionVisible('refresh_evidence')
->assertActionVisible('expire_snapshot'); ->assertActionExists('refresh_evidence', fn (Action $action): bool => $action->getLabel() === $refreshRule->canonicalLabel
&& $action->isConfirmationRequired()
&& $action->getModalHeading() === $refreshRule->modalHeading
&& $action->getModalDescription() === $refreshRule->modalDescription)
->assertActionVisible('expire_snapshot')
->assertActionExists('expire_snapshot', fn (Action $action): bool => $action->getLabel() === $expireRule->canonicalLabel
&& $action->isConfirmationRequired()
&& $action->getModalHeading() === $expireRule->modalHeading
&& $action->getModalDescription() === $expireRule->modalDescription)
->mountAction('refresh_evidence')
->assertActionMounted('refresh_evidence');
$component = Livewire::actingAs($user)
->test(ViewEvidenceSnapshot::class, ['record' => $snapshot->getKey()]);
Livewire::actingAs($user)
->test(ViewEvidenceSnapshot::class, ['record' => $snapshot->getKey()])
->assertActionVisible('expire_snapshot')
->mountAction('expire_snapshot')
->assertActionMounted('expire_snapshot')
->callMountedAction()
->assertHasActionErrors(['expiration_reason']);
expect(collect(evidenceSnapshotHeaderActions($component)) expect(collect(evidenceSnapshotHeaderActions($component))
->map(static fn ($action): ?string => method_exists($action, 'getName') ? $action->getName() : null) ->map(static fn ($action): ?string => method_exists($action, 'getName') ? $action->getName() : null)
->filter() ->filter()
->values() ->values()
->all()) ->all())
->toEqualCanonicalizing(['refresh_snapshot', 'expire_snapshot']) ->toEqualCanonicalizing(['refresh_evidence', 'expire_snapshot'])
->and(collect(EvidenceSnapshotResource::relatedContextEntries($snapshot))->pluck('key')->all()) ->and(collect(EvidenceSnapshotResource::relatedContextEntries($snapshot))->pluck('key')->all())
->toContain('operation_run', 'review_pack'); ->toContain('operation_run', 'review_pack');
}); });
@ -386,8 +412,8 @@ function evidenceSnapshotHeaderActions(Testable $component): array
Livewire::actingAs($user) Livewire::actingAs($user)
->test(ViewEvidenceSnapshot::class, ['record' => $snapshot->getKey()]) ->test(ViewEvidenceSnapshot::class, ['record' => $snapshot->getKey()])
->assertActionVisible('refresh_snapshot') ->assertActionVisible('refresh_evidence')
->assertActionDisabled('refresh_snapshot') ->assertActionDisabled('refresh_evidence')
->assertActionVisible('expire_snapshot') ->assertActionVisible('expire_snapshot')
->assertActionDisabled('expire_snapshot'); ->assertActionDisabled('expire_snapshot');
}); });

View File

@ -136,6 +136,26 @@ function getAlertDeliveryHeaderAction(Testable $component, string $name): ?Actio
expect(getAlertDeliveryHeaderAction($component, 'view_alert_rules'))->toBeNull(); expect(getAlertDeliveryHeaderAction($component, 'view_alert_rules'))->toBeNull();
}); });
it('shows quiet origin navigation on alert deliveries when deep-linked from alerts overview', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($user);
Filament::setTenant(null, true);
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
Livewire::withQueryParams([
'nav' => [
'source_surface' => 'alerts.overview',
'canonical_route_name' => 'admin.alert-deliveries.index',
'back_label' => 'Back to alerts',
'back_url' => \App\Filament\Clusters\Monitoring\AlertsCluster::getUrl(panel: 'admin'),
],
])
->actingAs($user)
->test(ListAlertDeliveries::class)
->assertActionVisible('operate_hub_back_to_origin_alert_deliveries');
});
it('returns 404 when a member from another workspace tries to view a delivery', function (): void { it('returns 404 when a member from another workspace tries to view a delivery', function (): void {
[$user] = createUserWithTenant(role: 'owner'); [$user] = createUserWithTenant(role: 'owner');

View File

@ -53,6 +53,22 @@ function auditLogPageTestRecord(?Tenant $tenant, array $attributes = []): AuditL
->assertSee('Review governance, operational, and workspace-admin events in reverse chronological order'); ->assertSee('Review governance, operational, and workspace-admin events in reverse chronological order');
}); });
it('keeps preselected audit detail subordinate to the summary-first route', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$audit = auditLogPageTestRecord($tenant, [
'summary' => 'Preselected audit detail',
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.monitoring.audit-log', ['event' => (int) $audit->getKey()]))
->assertOk()
->assertSee('Summary-first audit history')
->assertSee('Preselected audit detail')
->assertDontSee('Focused review lane');
});
it('loads the audit page with populated filter options', function (): void { it('loads the audit page with populated filter options', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner'); [$user, $tenant] = createUserWithTenant(role: 'owner');

View File

@ -61,6 +61,8 @@
Livewire::test(BaselineCompareLanding::class) Livewire::test(BaselineCompareLanding::class)
->assertActionVisible('compareNow') ->assertActionVisible('compareNow')
->assertActionDisabled('compareNow') ->assertActionDisabled('compareNow')
->assertDontSee('Monitoring landing')
->assertDontSee('Navigation lane')
->callAction('compareNow') ->callAction('compareNow')
->assertStatus(200); ->assertStatus(200);

View File

@ -41,6 +41,8 @@
->assertOk() ->assertOk()
->assertSee('Visible-set baseline') ->assertSee('Visible-set baseline')
->assertSee('Requested: Auto mode. Resolved: Dense mode.') ->assertSee('Requested: Auto mode. Resolved: Dense mode.')
->assertDontSee('Monitoring landing')
->assertDontSee('Focused review lane')
->assertDontSee('fonts/filament/filament/inter/inter-latin-wght-normal', false) ->assertDontSee('fonts/filament/filament/inter/inter-latin-wght-normal', false)
->assertDontSee('Passive auto-refresh every 5 seconds') ->assertDontSee('Passive auto-refresh every 5 seconds')
->assertSee('Grouped legend') ->assertSee('Grouped legend')

View File

@ -48,7 +48,10 @@
Livewire::actingAs($user) Livewire::actingAs($user)
->test(ListEvidenceSnapshots::class) ->test(ListEvidenceSnapshots::class)
->callTableAction('expire', $snapshot); ->callTableAction('expire', $snapshot, [
'expiration_reason' => 'This snapshot is no longer valid for governance use.',
])
->assertHasNoTableActionErrors();
$snapshot->refresh(); $snapshot->refresh();
$truth = app(ArtifactTruthPresenter::class)->forEvidenceSnapshot($snapshot); $truth = app(ArtifactTruthPresenter::class)->forEvidenceSnapshot($snapshot);

View File

@ -409,7 +409,9 @@
Filament::setTenant($tenant, true); Filament::setTenant($tenant, true);
Livewire::test(ListTenants::class) Livewire::test(ListTenants::class)
->callTableAction('archive', $tenant); ->callTableAction('archive', $tenant, [
'archive_reason' => 'Removing this tenant from the active housekeeping list.',
]);
expect(Tenant::count())->toBe(0); expect(Tenant::count())->toBe(0);

View File

@ -42,6 +42,8 @@
$connection = ProviderConnection::factory()->create([ $connection = ProviderConnection::factory()->create([
'tenant_id' => $tenant->getKey(), 'tenant_id' => $tenant->getKey(),
'consent_status' => 'required', 'consent_status' => 'required',
'is_enabled' => true,
'provider' => 'microsoft',
]); ]);
$tenant->makeCurrent(); $tenant->makeCurrent();
@ -55,6 +57,13 @@
Livewire::actingAs($user) Livewire::actingAs($user)
->test(ViewProviderConnection::class, ['record' => $connection->getKey()]) ->test(ViewProviderConnection::class, ['record' => $connection->getKey()])
->assertActionVisible('check_connection')
->assertActionDisabled('check_connection')
->assertActionExists('check_connection', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission())
->assertActionVisible('inventory_sync')
->assertActionDisabled('inventory_sync')
->assertActionVisible('compliance_snapshot')
->assertActionDisabled('compliance_snapshot')
->assertActionVisible('edit') ->assertActionVisible('edit')
->assertActionDisabled('edit') ->assertActionDisabled('edit')
->assertActionExists('edit', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission()); ->assertActionExists('edit', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission());
@ -67,6 +76,8 @@
$connection = ProviderConnection::factory()->create([ $connection = ProviderConnection::factory()->create([
'tenant_id' => $tenant->getKey(), 'tenant_id' => $tenant->getKey(),
'consent_status' => 'required', 'consent_status' => 'required',
'is_enabled' => true,
'provider' => 'microsoft',
]); ]);
$tenant->makeCurrent(); $tenant->makeCurrent();
@ -79,6 +90,12 @@
Livewire::actingAs($user) Livewire::actingAs($user)
->test(ViewProviderConnection::class, ['record' => $connection->getKey()]) ->test(ViewProviderConnection::class, ['record' => $connection->getKey()])
->assertActionVisible('check_connection')
->assertActionEnabled('check_connection')
->assertActionVisible('inventory_sync')
->assertActionEnabled('inventory_sync')
->assertActionVisible('compliance_snapshot')
->assertActionEnabled('compliance_snapshot')
->assertActionVisible('edit') ->assertActionVisible('edit')
->assertActionEnabled('edit'); ->assertActionEnabled('edit');
}); });

View File

@ -51,8 +51,6 @@ function spec125CriticalTenantContext(bool $ensureDefaultMicrosoftProviderConnec
$table = spec125CriticalTable($component); $table = spec125CriticalTable($component);
expect($table->getDefaultSortColumn())->toBe('name');
expect($table->getDefaultSortDirection())->toBe('asc');
expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource()); expect($table->getPaginationPageOptions())->toBe(TablePaginationProfiles::resource());
expect($table->persistsSearchInSession())->toBeTrue(); expect($table->persistsSearchInSession())->toBeTrue();
expect($table->persistsSortInSession())->toBeTrue(); expect($table->persistsSortInSession())->toBeTrue();

View File

@ -64,7 +64,9 @@
->test(ListTenants::class) ->test(ListTenants::class)
->assertTableActionDisabled('archive', $tenant) ->assertTableActionDisabled('archive', $tenant)
->assertTableActionExists('archive', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), $tenant) ->assertTableActionExists('archive', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), $tenant)
->callTableAction('archive', $tenant); ->callTableAction('archive', $tenant, [
'archive_reason' => 'Readonly users should not be able to archive tenants.',
]);
expect($tenant->fresh()->trashed())->toBeFalse(); expect($tenant->fresh()->trashed())->toBeFalse();
}); });

View File

@ -16,6 +16,19 @@
uses(RefreshDatabase::class); uses(RefreshDatabase::class);
describe('Tenant diagnostics repairs', function () { describe('Tenant diagnostics repairs', function () {
it('hides repair actions when no defect is present', function () {
[$owner, $tenant] = createUserWithTenant(role: 'owner');
$this->actingAs($owner);
Filament::setTenant($tenant, true);
Livewire::test(TenantDiagnostics::class)
->assertSee('All good')
->assertActionHidden('bootstrapOwner')
->assertActionHidden('mergeDuplicateMemberships');
});
it('allows an authorized member to bootstrap an owner when a tenant has no owners', function () { it('allows an authorized member to bootstrap an owner when a tenant has no owners', function () {
[$manager, $tenant] = createUserWithTenant(role: 'manager'); [$manager, $tenant] = createUserWithTenant(role: 'manager');

View File

@ -7,6 +7,9 @@
use App\Models\Tenant; use App\Models\Tenant;
use App\Services\Graph\GraphClientInterface; use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphResponse; use App\Services\Graph\GraphResponse;
use App\Support\Providers\ProviderConnectionType;
use App\Support\Providers\ProviderConsentStatus;
use App\Support\Providers\ProviderVerificationStatus;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
@ -29,11 +32,17 @@ function tenantWithApp(): Tenant
'status' => 'active', 'status' => 'active',
]); ]);
$connection = ProviderConnection::factory()->create([ $connection = ProviderConnection::factory()->dedicated()->create([
'tenant_id' => $tenant->getKey(), 'tenant_id' => $tenant->getKey(),
'provider' => 'microsoft', 'provider' => 'microsoft',
'is_default' => true, 'is_default' => true,
'status' => 'ok', 'is_enabled' => true,
'connection_type' => ProviderConnectionType::Dedicated->value,
'consent_status' => ProviderConsentStatus::Granted->value,
'consent_granted_at' => now(),
'consent_last_checked_at' => now(),
'verification_status' => ProviderVerificationStatus::Healthy->value,
'last_health_check_at' => now(),
]); ]);
ProviderCredential::factory()->create([ ProviderCredential::factory()->create([

View File

@ -3,15 +3,21 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Resources\TenantResource\Pages\ListTenants; use App\Filament\Resources\TenantResource\Pages\ListTenants;
use App\Filament\Resources\TenantResource\Pages\ViewTenant;
use App\Models\AuditLog;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\TenantTriageReview; use App\Models\TenantTriageReview;
use App\Support\Audit\AuditActionId;
use App\Support\BackupHealth\TenantBackupHealthAssessment; use App\Support\BackupHealth\TenantBackupHealthAssessment;
use App\Support\PortfolioTriage\PortfolioArrivalContextToken; use App\Support\PortfolioTriage\PortfolioArrivalContextToken;
use App\Support\Tenants\TenantRecoveryTriagePresentation; use App\Support\Tenants\TenantRecoveryTriagePresentation;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Facades\Filament;
use Livewire\Livewire;
use App\Support\Workspaces\WorkspaceContext;
use Tests\Feature\Concerns\BuildsPortfolioTriageFixtures; use Tests\Feature\Concerns\BuildsPortfolioTriageFixtures;
uses(BuildsPortfolioTriageFixtures::class); uses(BuildsPortfolioTriageFixtures::class);
@ -166,11 +172,58 @@
$component $component
->callMountedAction(); ->callMountedAction();
expect(TenantTriageReview::query()
->where('tenant_id', (int) $actionTenant->getKey())
->where('concern_family', PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH)
->where('current_state', TenantTriageReview::STATE_REVIEWED)
->whereNull('resolved_at')
->exists())->toBeTrue()
->and(AuditLog::query()
->where('workspace_id', (int) $actionTenant->workspace_id)
->where('tenant_id', (int) $actionTenant->getKey())
->where('action', AuditActionId::TenantTriageReviewMarkedReviewed->value)
->exists())->toBeTrue()
->and($component->instance())->toBeInstanceOf(ListTenants::class);
});
it('keeps review-state mutations available on the tenant detail header for the current concern', function (): void {
[$user, $anchorTenant] = $this->makePortfolioTriageActor('Anchor Detail Action Tenant');
$actionTenant = $this->makePortfolioTriagePeer($user, $anchorTenant, 'Detail Action Backup Tenant');
$this->seedPortfolioBackupConcern($actionTenant, TenantBackupHealthAssessment::POSTURE_STALE);
$this->actingAs($user);
Filament::setCurrentPanel('admin');
Filament::setTenant(null, true);
Filament::bootCurrentPanel();
session([WorkspaceContext::SESSION_KEY => (int) $actionTenant->workspace_id]);
$component = Livewire::actingAs($user)
->test(ViewTenant::class, ['record' => $actionTenant->getRouteKey()])
->assertActionVisible('markReviewed')
->assertActionEnabled('markReviewed')
->assertActionExists('markReviewed', fn (Action $action): bool => $action->isConfirmationRequired()
&& str_contains((string) $action->getModalDescription(), 'Concern family: Backup health')
&& str_contains((string) $action->getModalDescription(), 'Target state: Reviewed')
&& str_contains((string) $action->getModalDescription(), 'TenantPilot only'))
->assertActionVisible('markFollowUpNeeded')
->assertActionExists('markFollowUpNeeded', fn (Action $action): bool => $action->isConfirmationRequired()
&& str_contains((string) $action->getModalDescription(), 'Target state: Follow-up needed')
&& str_contains((string) $action->getModalDescription(), 'TenantPilot only'))
->mountAction('markReviewed')
->assertActionMounted('markReviewed')
->callMountedAction()
->assertHasNoActionErrors();
expect(TenantTriageReview::query() expect(TenantTriageReview::query()
->where('tenant_id', (int) $actionTenant->getKey()) ->where('tenant_id', (int) $actionTenant->getKey())
->where('concern_family', PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH) ->where('concern_family', PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH)
->where('current_state', TenantTriageReview::STATE_REVIEWED) ->where('current_state', TenantTriageReview::STATE_REVIEWED)
->whereNull('resolved_at') ->whereNull('resolved_at')
->exists())->toBeTrue() ->exists())->toBeTrue()
->and($component->instance())->toBeInstanceOf(ListTenants::class); ->and(AuditLog::query()
->where('workspace_id', (int) $actionTenant->workspace_id)
->where('tenant_id', (int) $actionTenant->getKey())
->where('action', AuditActionId::TenantTriageReviewMarkedReviewed->value)
->exists())->toBeTrue()
->and($component->instance())->toBeInstanceOf(ViewTenant::class);
}); });

View File

@ -194,6 +194,9 @@
Livewire::test(ViewTenant::class, ['record' => $tenant->getRouteKey()]) Livewire::test(ViewTenant::class, ['record' => $tenant->getRouteKey()])
->mountAction('archive') ->mountAction('archive')
->setActionData([
'archive_reason' => 'Archiving this tenant from the detail workflow.',
])
->callMountedAction() ->callMountedAction()
->assertHasNoActionErrors(); ->assertHasNoActionErrors();

View File

@ -65,6 +65,9 @@
Livewire::test(ViewTenant::class, ['record' => $tenant->getRouteKey()]) Livewire::test(ViewTenant::class, ['record' => $tenant->getRouteKey()])
->assertActionDisabled('archive') ->assertActionDisabled('archive')
->mountAction('archive') ->mountAction('archive')
->setActionData([
'archive_reason' => 'Readonly users should not be able to archive tenants.',
])
->callMountedAction() ->callMountedAction()
->assertSuccessful(); ->assertSuccessful();

View File

@ -21,7 +21,7 @@
$service->triage($finding, $tenant, $user); $service->triage($finding, $tenant, $user);
$service->assign($finding->refresh(), $tenant, $user, null, (int) $user->getKey()); $service->assign($finding->refresh(), $tenant, $user, null, (int) $user->getKey());
$service->resolve($finding->refresh(), $tenant, $user, 'patched'); $service->resolve($finding->refresh(), $tenant, $user, 'patched');
$service->reopen($finding->refresh(), $tenant, $user); $service->reopen($finding->refresh(), $tenant, $user, 'The issue recurred after validation.');
$service->close($finding->refresh(), $tenant, $user, 'duplicate'); $service->close($finding->refresh(), $tenant, $user, 'duplicate');
expect(AuditLog::query() expect(AuditLog::query()
@ -40,6 +40,11 @@
->and(data_get($closedAudit->metadata, 'closed_reason'))->toBe('duplicate') ->and(data_get($closedAudit->metadata, 'closed_reason'))->toBe('duplicate')
->and(data_get($closedAudit->metadata, 'before.evidence_jsonb'))->toBeNull() ->and(data_get($closedAudit->metadata, 'before.evidence_jsonb'))->toBeNull()
->and(data_get($closedAudit->metadata, 'after.evidence_jsonb'))->toBeNull(); ->and(data_get($closedAudit->metadata, 'after.evidence_jsonb'))->toBeNull();
$reopenedAudit = $this->latestFindingAudit($finding, AuditActionId::FindingReopened);
expect($reopenedAudit)->not->toBeNull()
->and(data_get($reopenedAudit->metadata, 'reopened_reason'))->toBe('The issue recurred after validation.');
}); });
it('deduplicates repeated finding audit writes for the same successful mutation payload', function (): void { it('deduplicates repeated finding audit writes for the same successful mutation payload', function (): void {

View File

@ -52,7 +52,9 @@
Livewire::test(ListFindings::class) Livewire::test(ListFindings::class)
->filterTable('open', false) ->filterTable('open', false)
->callTableAction('reopen', $finding) ->callTableAction('reopen', $finding, [
'reopen_reason' => 'The issue recurred in a later scan.',
])
->assertHasNoTableActionErrors(); ->assertHasNoTableActionErrors();
$finding->refresh(); $finding->refresh();

View File

@ -30,7 +30,7 @@
->and($resolvedFinding->resolved_reason)->toBe('patched') ->and($resolvedFinding->resolved_reason)->toBe('patched')
->and($this->latestFindingAudit($resolvedFinding, AuditActionId::FindingResolved))->not->toBeNull(); ->and($this->latestFindingAudit($resolvedFinding, AuditActionId::FindingResolved))->not->toBeNull();
$reopenedFinding = $service->reopen($resolvedFinding, $tenant, $user); $reopenedFinding = $service->reopen($resolvedFinding, $tenant, $user, 'The issue recurred after remediation.');
expect($reopenedFinding->status)->toBe(Finding::STATUS_REOPENED) expect($reopenedFinding->status)->toBe(Finding::STATUS_REOPENED)
->and($reopenedFinding->reopened_at)->not->toBeNull() ->and($reopenedFinding->reopened_at)->not->toBeNull()
@ -81,6 +81,9 @@
expect(fn () => $service->close($this->makeFindingForWorkflow($tenant, Finding::STATUS_NEW), $tenant, $user, ' ')) expect(fn () => $service->close($this->makeFindingForWorkflow($tenant, Finding::STATUS_NEW), $tenant, $user, ' '))
->toThrow(\InvalidArgumentException::class, 'closed_reason is required.'); ->toThrow(\InvalidArgumentException::class, 'closed_reason is required.');
expect(fn () => $service->reopen($this->makeFindingForWorkflow($tenant, Finding::STATUS_RESOLVED), $tenant, $user, ' '))
->toThrow(\InvalidArgumentException::class, 'reopen_reason is required.');
expect(fn () => $service->riskAccept($this->makeFindingForWorkflow($tenant, Finding::STATUS_NEW), $tenant, $user, ' ')) expect(fn () => $service->riskAccept($this->makeFindingForWorkflow($tenant, Finding::STATUS_NEW), $tenant, $user, ' '))
->toThrow(\InvalidArgumentException::class, 'closed_reason is required.'); ->toThrow(\InvalidArgumentException::class, 'closed_reason is required.');
}); });

View File

@ -35,7 +35,11 @@
->assertActionVisible('start_progress'); ->assertActionVisible('start_progress');
Livewire::test(ViewFinding::class, ['record' => $resolvedFinding->getKey()]) Livewire::test(ViewFinding::class, ['record' => $resolvedFinding->getKey()])
->assertActionVisible('reopen'); ->assertActionVisible('reopen')
->mountAction('reopen')
->assertActionMounted('reopen')
->callMountedAction()
->assertHasActionErrors(['reopen_reason']);
}); });
it('executes workflow actions from view header and supports assignment to tenant members only', function (): void { it('executes workflow actions from view header and supports assignment to tenant members only', function (): void {
@ -69,7 +73,15 @@
->and((int) $finding->owner_user_id)->toBe((int) $user->getKey()); ->and((int) $finding->owner_user_id)->toBe((int) $user->getKey());
Livewire::test(ViewFinding::class, ['record' => $finding->getKey()]) Livewire::test(ViewFinding::class, ['record' => $finding->getKey()])
->callAction('reopen') ->mountAction('reopen')
->assertActionMounted('reopen')
->callMountedAction()
->assertHasActionErrors(['reopen_reason']);
Livewire::test(ViewFinding::class, ['record' => $finding->getKey()])
->callAction('reopen', [
'reopen_reason' => 'The finding recurred after remediation.',
])
->assertHasNoActionErrors() ->assertHasNoActionErrors()
->callAction('assign', [ ->callAction('assign', [
'assignee_user_id' => (int) $outsider->getKey(), 'assignee_user_id' => (int) $outsider->getKey(),

View File

@ -3,6 +3,8 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Pages\InventoryCoverage; use App\Filament\Pages\InventoryCoverage;
use App\Filament\Pages\BaselineCompareLanding;
use App\Filament\Pages\BaselineCompareMatrix;
use App\Filament\Pages\Monitoring\Alerts; use App\Filament\Pages\Monitoring\Alerts;
use App\Filament\Pages\Monitoring\AuditLog as AuditLogPage; use App\Filament\Pages\Monitoring\AuditLog as AuditLogPage;
use App\Filament\Pages\Monitoring\EvidenceOverview; use App\Filament\Pages\Monitoring\EvidenceOverview;
@ -47,6 +49,7 @@
use App\Filament\Resources\PolicyResource\RelationManagers\VersionsRelationManager; use App\Filament\Resources\PolicyResource\RelationManagers\VersionsRelationManager;
use App\Filament\Resources\PolicyVersionResource; use App\Filament\Resources\PolicyVersionResource;
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\ProviderConnectionResource\Pages\ViewProviderConnection;
use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections; use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections;
use App\Filament\Resources\RestoreRunResource; use App\Filament\Resources\RestoreRunResource;
use App\Filament\Resources\RestoreRunResource\Pages\ListRestoreRuns; use App\Filament\Resources\RestoreRunResource\Pages\ListRestoreRuns;
@ -635,6 +638,92 @@ function actionSurfaceSystemPanelContext(array $capabilities): PlatformUser
->toBe(TenantResource::getUrl('view', ['record' => $tenant], panel: 'admin')); ->toBe(TenantResource::getUrl('view', ['record' => $tenant], panel: 'admin'));
}); });
it('keeps tenant detail header actions aligned with the shared administrative family while preserving workflow-heavy exceptions', function (): void {
$tenant = Tenant::factory()->active()->create();
[$user, $tenant] = createUserWithTenant(
tenant: $tenant,
role: 'owner',
ensureDefaultMicrosoftProviderConnection: false,
);
ProviderConnection::factory()->platform()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'provider' => 'microsoft',
'is_default' => true,
'is_enabled' => true,
]);
$this->actingAs($user);
Filament::setCurrentPanel('admin');
Filament::setTenant(null, true);
Filament::bootCurrentPanel();
session([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]);
$listComponent = Livewire::actingAs($user)
->test(ListTenants::class)
->assertTableActionVisible('admin_consent', $tenant)
->assertTableActionVisible('open_in_entra', $tenant)
->assertTableActionVisible('syncTenant', $tenant)
->assertTableActionVisible('verify', $tenant)
->assertTableActionVisible('setup_rbac', $tenant)
->assertTableActionVisible('archive', $tenant);
$markReviewedAction = $listComponent->instance()->getTable()->getAction('markReviewed');
$markFollowUpNeededAction = $listComponent->instance()->getTable()->getAction('markFollowUpNeeded');
$component = Livewire::actingAs($user)
->test(ViewTenant::class, ['record' => $tenant->getRouteKey()])
->assertActionVisible('admin_consent')
->assertActionVisible('open_in_entra')
->assertActionVisible('syncTenant')
->assertActionVisible('verify')
->assertActionVisible('setup_rbac')
->assertActionVisible('refresh_rbac')
->assertActionVisible('archive');
$instance = $component->instance();
if ($instance->getCachedHeaderActions() === []) {
$instance->cacheInteractsWithHeaderActions();
}
$headerGroups = collect($instance->getCachedHeaderActions())
->filter(static fn ($action): bool => $action instanceof ActionGroup && $action->isVisible())
->mapWithKeys(static function (ActionGroup $group): array {
$actionNames = collect($group->getActions())
->filter(static fn ($action): bool => ! method_exists($action, 'isVisible') || $action->isVisible())
->map(static fn ($action): ?string => $action instanceof Action ? $action->getName() : null)
->filter()
->values()
->all();
return [(string) $group->getLabel() => $actionNames];
});
$visibleHeaderActionNames = $headerGroups
->flatMap(static fn (array $actionNames): array => $actionNames)
->values()
->all();
expect($markReviewedAction)->not->toBeNull()
->and($markReviewedAction?->getName())->toBe('markReviewed')
->and($markReviewedAction?->isConfirmationRequired())->toBeTrue()
->and($markFollowUpNeededAction)->not->toBeNull()
->and($markFollowUpNeededAction?->getName())->toBe('markFollowUpNeeded')
->and($markFollowUpNeededAction?->isConfirmationRequired())->toBeTrue()
->and(array_keys($headerGroups->all()))->toBe(['External links', 'Setup', 'Triage', 'Lifecycle'])
->and($headerGroups->get('External links'))->toEqualCanonicalizing(['admin_consent', 'open_in_entra'])
->and($headerGroups->get('Setup'))->toEqualCanonicalizing(['syncTenant', 'verify', 'setup_rbac', 'refresh_rbac'])
->and($headerGroups->get('Triage'))->toEqualCanonicalizing(['markReviewed', 'markFollowUpNeeded'])
->and($headerGroups->get('Lifecycle'))->toEqualCanonicalizing(['archive'])
->and($visibleHeaderActionNames)->not->toContain('edit')
->and($visibleHeaderActionNames)->toContain('markReviewed')
->and($visibleHeaderActionNames)->toContain('markFollowUpNeeded')
->and($visibleHeaderActionNames)->not->toContain('forceDelete')
->and(collect(TenantResource::tenantViewContextEntries($tenant))->pluck('key')->all())->toContain('tenant_edit');
});
it('renders the backup items relation manager on the backup set detail page', function (): void { it('renders the backup items relation manager on the backup set detail page', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner'); [$user, $tenant] = createUserWithTenant(role: 'owner');
@ -817,9 +906,8 @@ function actionSurfaceSystemPanelContext(array $capabilities): PlatformUser
expect(method_exists(TenantRequiredPermissions::class, 'actionSurfaceDeclaration'))->toBeTrue() expect(method_exists(TenantRequiredPermissions::class, 'actionSurfaceDeclaration'))->toBeTrue()
->and($baselineExemptions->hasClass(TenantRequiredPermissions::class))->toBeFalse(); ->and($baselineExemptions->hasClass(TenantRequiredPermissions::class))->toBeFalse();
expect(method_exists(Alerts::class, 'actionSurfaceDeclaration'))->toBeFalse() expect(method_exists(Alerts::class, 'actionSurfaceDeclaration'))->toBeTrue()
->and($baselineExemptions->hasClass(Alerts::class))->toBeTrue() ->and($baselineExemptions->hasClass(Alerts::class))->toBeFalse();
->and((string) $baselineExemptions->reasonForClass(Alerts::class))->toContain('cluster entry');
expect($baselineExemptions->hasClass(ManagedTenantOnboardingWizard::class))->toBeTrue() expect($baselineExemptions->hasClass(ManagedTenantOnboardingWizard::class))->toBeTrue()
->and((string) $baselineExemptions->reasonForClass(ManagedTenantOnboardingWizard::class))->toContain('dedicated conformance tests') ->and((string) $baselineExemptions->reasonForClass(ManagedTenantOnboardingWizard::class))->toContain('dedicated conformance tests')
@ -1938,6 +2026,63 @@ function actionSurfaceSystemPanelContext(array $capabilities): PlatformUser
->and($table->getBulkActions())->toBeEmpty(); ->and($table->getBulkActions())->toBeEmpty();
}); });
it('keeps provider connection detail secondary actions aligned under More', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
$connection = ProviderConnection::factory()->platform()->consentGranted()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'provider' => 'microsoft',
'is_enabled' => true,
'is_default' => false,
]);
$this->actingAs($user);
$tenant->makeCurrent();
Filament::setTenant($tenant, true);
$component = Livewire::test(ViewProviderConnection::class, ['record' => $connection->getKey()])
->assertActionVisible('grant_admin_consent');
$instance = $component->instance();
if ($instance->getCachedHeaderActions() === []) {
$instance->cacheInteractsWithHeaderActions();
}
$headerActions = $instance->getCachedHeaderActions();
$primaryHeaderActions = collect($headerActions)
->reject(static fn ($action): bool => $action instanceof ActionGroup)
->map(static fn ($action): ?string => $action instanceof Action ? $action->getName() : null)
->filter()
->values()
->all();
$moreGroup = collect($headerActions)->first(static fn ($action): bool => $action instanceof ActionGroup);
$moreActionNames = collect($moreGroup?->getActions())
->map(static fn ($action): ?string => $action->getName())
->filter()
->values()
->all();
expect($primaryHeaderActions)->toEqual(['grant_admin_consent'])
->and($moreGroup)->toBeInstanceOf(ActionGroup::class)
->and($moreGroup?->getLabel())->toBe('More')
->and($moreActionNames)->toEqualCanonicalizing([
'edit',
'check_connection',
'inventory_sync',
'compliance_snapshot',
'set_default',
'enable_dedicated_override',
'rotate_dedicated_credential',
'delete_dedicated_credential',
'revert_to_platform',
'enable_connection',
'disable_connection',
]);
});
it('uses clickable rows without extra row actions on the alert deliveries list', function (): void { it('uses clickable rows without extra row actions on the alert deliveries list', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner'); [$user, $tenant] = createUserWithTenant(role: 'owner');
@ -2021,6 +2166,146 @@ function actionSurfaceSystemPanelContext(array $capabilities): PlatformUser
]); ]);
}); });
it('documents the spec 193 monitoring hierarchy inventory and explicit exception', function (): void {
$inventory = ActionSurfaceExemptions::spec193MonitoringSurfaceInventory();
$baselineExemptions = ActionSurfaceExemptions::baseline();
$remediationRequired = collect($inventory)
->filter(fn (array $surface): bool => $surface['classification'] === 'remediation_required')
->keys()
->values()
->all();
$calmReferences = collect($inventory)
->filter(fn (array $surface): bool => $surface['classification'] === 'compliant_no_op')
->keys()
->values()
->all();
expect(array_keys($inventory))->toEqualCanonicalizing([
FindingExceptionsQueue::class,
TenantlessOperationRunViewer::class,
Operations::class,
Alerts::class,
AuditLogPage::class,
ListAlertDeliveries::class,
EvidenceOverview::class,
BaselineCompareLanding::class,
BaselineCompareMatrix::class,
ReviewRegister::class,
TenantDiagnostics::class,
])
->and($baselineExemptions->hasClass(Alerts::class))->toBeFalse()
->and(method_exists(Alerts::class, 'actionSurfaceDeclaration'))->toBeTrue()
->and($remediationRequired)->toEqualCanonicalizing([
FindingExceptionsQueue::class,
TenantlessOperationRunViewer::class,
Operations::class,
])
->and($calmReferences)->toEqualCanonicalizing([
EvidenceOverview::class,
BaselineCompareLanding::class,
BaselineCompareMatrix::class,
ReviewRegister::class,
])
->and(ActionSurfaceExemptions::spec193MonitoringSurface(TenantDiagnostics::class)['classification'] ?? null)->toBe('special_type_acceptable')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(TenantDiagnostics::class)['exceptionReason'] ?? null)->toContain('diagnostic');
});
it('keeps spec 193 hierarchy work from expanding confirmation, reason capture, or compare-start semantics', function (): void {
[$approver, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');
$mountedActionFieldNames = static function (mixed $component): array {
$method = new \ReflectionMethod($component->instance(), 'getMountedActionForm');
$method->setAccessible(true);
$form = $method->invoke($component->instance());
return collect($form?->getFlatFields(withHidden: true) ?? [])
->map(static fn (mixed $field): ?string => method_exists($field, 'getName') ? $field->getName() : null)
->filter()
->values()
->all();
};
$finding = Finding::factory()->for($tenant)->create();
$exception = FindingException::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'finding_id' => (int) $finding->getKey(),
'requested_by_user_id' => (int) $approver->getKey(),
'owner_user_id' => (int) $approver->getKey(),
'status' => FindingException::STATUS_PENDING,
'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
'request_reason' => 'Guarded spec 193 review',
'requested_at' => now()->subDay(),
'review_due_at' => now()->addDay(),
'evidence_summary' => ['reference_count' => 0],
]);
$this->actingAs($approver);
setAdminPanelContext();
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
$approveComponent = Livewire::withQueryParams([
'exception' => (int) $exception->getKey(),
])
->actingAs($approver)
->test(FindingExceptionsQueue::class)
->assertActionExists('approve_selected_exception', function (Action $action): bool {
return $action->isConfirmationRequired();
})
->mountAction('approve_selected_exception');
expect($mountedActionFieldNames($approveComponent))->toBe([
'effective_from',
'expires_at',
'approval_reason',
]);
$rejectComponent = Livewire::withQueryParams([
'exception' => (int) $exception->getKey(),
])
->actingAs($approver)
->test(FindingExceptionsQueue::class)
->assertActionExists('reject_selected_exception', function (Action $action): bool {
return $action->isConfirmationRequired();
})
->mountAction('reject_selected_exception');
expect($mountedActionFieldNames($rejectComponent))->toBe([
'rejection_reason',
]);
$tenant->makeCurrent();
Filament::setTenant($tenant, true);
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'capture_mode' => \App\Support\Baselines\BaselineCaptureMode::FullContent->value,
]);
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
$profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);
BaselineTenantAssignment::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'baseline_profile_id' => (int) $profile->getKey(),
]);
Livewire::actingAs($approver)
->test(BaselineCompareLanding::class)
->assertActionExists('compareNow', function (Action $action): bool {
return $action->isConfirmationRequired()
&& $action->getModalDescription() === 'This will refresh content evidence on demand (redacted) before comparing the current tenant inventory against the assigned baseline snapshot.';
});
});
it('keeps spec 192 remediated pages out of the enterprise-detail layout rollout', function (): void { it('keeps spec 192 remediated pages out of the enterprise-detail layout rollout', function (): void {
foreach ([ foreach ([
\App\Filament\Resources\BaselineProfileResource::class, \App\Filament\Resources\BaselineProfileResource::class,

View File

@ -237,3 +237,11 @@ className: $className,
expect($result->hasIssues())->toBeFalse($result->formatForAssertion()); expect($result->hasIssues())->toBeFalse($result->formatForAssertion());
}); });
it('accepts the repository spec 193 monitoring inventory even when only inventory validation runs', function (): void {
$validator = ActionSurfaceValidator::withBaselineExemptions();
$result = $validator->validateComponents([]);
expect($result->hasIssues())->toBeFalse($result->formatForAssertion());
});

View File

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\BaselineCompareLanding;
use App\Filament\Pages\BaselineCompareMatrix;
use App\Filament\Pages\Monitoring\Alerts;
use App\Filament\Pages\Monitoring\AuditLog as AuditLogPage;
use App\Filament\Pages\Monitoring\EvidenceOverview;
use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Filament\Pages\Monitoring\Operations;
use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Filament\Pages\Reviews\ReviewRegister;
use App\Filament\Pages\TenantDiagnostics;
use App\Filament\Resources\AlertDeliveryResource\Pages\ListAlertDeliveries;
use App\Support\Ui\ActionSurface\ActionSurfaceExemptions;
use App\Support\Ui\ActionSurface\ActionSurfaceValidator;
it('keeps the spec 193 monitoring inventory complete and explicitly classified', function (): void {
$inventory = ActionSurfaceExemptions::spec193MonitoringSurfaceInventory();
expect(array_keys($inventory))->toEqualCanonicalizing([
FindingExceptionsQueue::class,
TenantlessOperationRunViewer::class,
Operations::class,
Alerts::class,
AuditLogPage::class,
ListAlertDeliveries::class,
EvidenceOverview::class,
BaselineCompareLanding::class,
BaselineCompareMatrix::class,
ReviewRegister::class,
TenantDiagnostics::class,
])
->and(ActionSurfaceExemptions::spec193MonitoringSurface(FindingExceptionsQueue::class)['classification'] ?? null)->toBe('remediation_required')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(FindingExceptionsQueue::class)['surfaceKind'] ?? null)->toBe('queue_workbench')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(FindingExceptionsQueue::class)['primaryInspectModel'] ?? null)->toBe('explicit_inspect_action')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(Alerts::class)['classification'] ?? null)->toBe('minor_alignment_only')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(EvidenceOverview::class)['classification'] ?? null)->toBe('compliant_no_op')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(TenantDiagnostics::class)['classification'] ?? null)->toBe('special_type_acceptable');
});
it('keeps tenant diagnostics as the only explicit spec 193 exception surface', function (): void {
$inventory = ActionSurfaceExemptions::spec193MonitoringSurfaceInventory();
$exceptionPages = collect($inventory)
->filter(fn (array $surface): bool => $surface['classification'] === 'special_type_acceptable')
->keys()
->values()
->all();
expect($exceptionPages)->toBe([
TenantDiagnostics::class,
])
->and(ActionSurfaceExemptions::spec193MonitoringSurface(TenantDiagnostics::class)['exceptionReason'] ?? null)->toContain('diagnostic')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(TenantDiagnostics::class)['surfaceKind'] ?? null)->toBe('diagnostic_exception')
->and(ActionSurfaceExemptions::spec193MonitoringSurface(TenantDiagnostics::class)['primaryInspectModel'] ?? null)->toBe('singleton_detail_surface')
->and(collect($inventory)
->except([TenantDiagnostics::class])
->every(fn (array $surface): bool => ($surface['exceptionReason'] ?? null) === null))->toBeTrue();
});
it('keeps the spec 193 monitoring inventory valid inside the action-surface validator', function (): void {
$result = ActionSurfaceValidator::withBaselineExemptions()->validateComponents([]);
expect($result->hasIssues())->toBeFalse($result->formatForAssertion());
});
it('keeps spec 193 monitoring surfaces out of record-page header layouts', function (): void {
foreach (array_keys(ActionSurfaceExemptions::spec193MonitoringSurfaceInventory()) as $className) {
$source = file_get_contents((string) (new \ReflectionClass($className))->getFileName()) ?: '';
expect($source)
->not->toContain('EnterpriseDetail')
->not->toContain('enterprise-detail/header');
}
});

View File

@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
it('keeps the spec 194 family inventory, surface bindings, and documented deviations explicit', function (): void {
$families = GovernanceActionCatalog::families();
$rules = GovernanceActionCatalog::rules();
$bindings = GovernanceActionCatalog::surfaceBindings();
expect(array_keys($families))->toEqualCanonicalizing([
'exception_decision',
'review_lifecycle',
'evidence_lifecycle',
'run_triage',
'finding_lifecycle',
'tenant_lifecycle',
])
->and(array_keys($rules))->toHaveCount(16)
->and($bindings)->not->toBeEmpty();
foreach ($bindings as $binding) {
$matchingRule = collect($rules)->first(
fn ($rule): bool => $rule->familyKey === $binding['familyKey']
&& in_array($binding['surfaceKey'], $rule->surfaceKeys, true),
);
expect($matchingRule)->not->toBeNull();
}
expect(GovernanceActionCatalog::documentedDeviations())->not->toBeEmpty();
});
it('keeps evidence and review surface bindings aligned to their canonical action names', function (): void {
$bindingsBySurface = collect(GovernanceActionCatalog::surfaceBindings())->groupBy('surfaceKey');
expect($bindingsBySurface->get('view_evidence_snapshot', collect())->pluck('actionName')->all())
->toEqualCanonicalizing(['refresh_evidence', 'expire_snapshot'])
->and($bindingsBySurface->get('view_tenant_review', collect())->pluck('actionName')->all())
->toContain('refresh_review', 'publish_review', 'archive_review');
});
it('keeps triage mutations out of the tenantless run viewer while the system run page owns them', function (): void {
$tenantlessViewer = file_get_contents(base_path('app/Filament/Pages/Operations/TenantlessOperationRunViewer.php'));
$systemViewRun = file_get_contents(base_path('app/Filament/System/Pages/Ops/ViewRun.php'));
expect($tenantlessViewer)->toBeString()
->and($systemViewRun)->toBeString()
->and($tenantlessViewer)->not->toContain("Action::make('retry')")
->and($tenantlessViewer)->not->toContain("Action::make('cancel')")
->and($tenantlessViewer)->not->toContain("Action::make('mark_investigated')")
->and($systemViewRun)->toContain("Action::make('retry')")
->and($systemViewRun)->toContain("Action::make('cancel')")
->and($systemViewRun)->toContain("Action::make('mark_investigated')");
});
it('keeps the governed surface files inside the catalog binding inventory', function (): void {
$boundFiles = collect(GovernanceActionCatalog::surfaceBindings())
->pluck('pageClass')
->unique()
->values()
->all();
expect($boundFiles)->toContain(
'App\\Filament\\Pages\\Monitoring\\FindingExceptionsQueue',
'App\\Filament\\Resources\\FindingExceptionResource\\Pages\\ViewFindingException',
'App\\Filament\\Resources\\EvidenceSnapshotResource\\Pages\\ViewEvidenceSnapshot',
'App\\Filament\\Resources\\TenantReviewResource\\Pages\\ViewTenantReview',
'App\\Filament\\System\\Pages\\Ops\\ViewRun',
'App\\Filament\\Resources\\FindingResource\\Pages\\ViewFinding',
'App\\Filament\\Resources\\TenantResource\\Pages\\ViewTenant',
'App\\Filament\\Resources\\TenantResource\\Pages\\EditTenant',
);
});

View File

@ -27,7 +27,7 @@
[$user, $tenant] = createUserWithTenant(role: 'owner'); [$user, $tenant] = createUserWithTenant(role: 'owner');
$finding = Finding::factory()->for($tenant)->permissionPosture()->resolved()->create(); $finding = Finding::factory()->for($tenant)->permissionPosture()->resolved()->create();
$finding = app(FindingWorkflowService::class)->reopen($finding, $tenant, $user); $finding = app(FindingWorkflowService::class)->reopen($finding, $tenant, $user, 'The finding recurred after a later scan.');
expect($finding->status)->toBe(Finding::STATUS_REOPENED) expect($finding->status)->toBe(Finding::STATUS_REOPENED)
->and($finding->reopened_at)->not->toBeNull() ->and($finding->reopened_at)->not->toBeNull()

View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\Monitoring\Alerts;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('keeps alerts as a quiet overview with downstream drilldown entry points', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->followingRedirects()
->get('/admin/alerts')
->assertOk()
->assertSee('Alert targets')
->assertSee('Alert rules')
->assertSee('Alert deliveries')
->assertDontSee('Focused review lane')
->assertDontSee('Follow-up lane');
});
it('surfaces origin context quietly on the alerts overview', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
Filament::setTenant(null, true);
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
setAdminPanelContext();
Livewire::withQueryParams([
'nav' => [
'source_surface' => 'backup_set.detail_section',
'canonical_route_name' => 'admin.alerts.overview',
'back_label' => 'Back to backup set',
'back_url' => '/admin/tenant/backup-sets/1',
],
])
->actingAs($user)
->test(Alerts::class)
->assertSee('Back to backup set')
->assertSee('/admin/tenant/backup-sets/1', false);
});

View File

@ -165,3 +165,39 @@
->assertDontSee('Close details') ->assertDontSee('Close details')
->assertDontSee('Open operation'); ->assertDontSee('Open operation');
}); });
it('surfaces origin context quietly when deep-linked to a selected audit event', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$audit = AuditLog::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'actor_email' => 'owner@example.com',
'actor_name' => 'Owner',
'actor_type' => 'human',
'action' => 'workspace.selected',
'status' => 'success',
'resource_type' => 'workspace',
'resource_id' => (string) $tenant->workspace_id,
'target_label' => 'Workspace 1',
'summary' => 'Workspace selected for Workspace 1',
'recorded_at' => now(),
]);
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
Filament::setTenant(null, true);
Livewire::withQueryParams([
'event' => (int) $audit->getKey(),
'nav' => [
'source_surface' => 'alerts.overview',
'canonical_route_name' => 'admin.monitoring.audit-log',
'back_label' => 'Back to alerts',
'back_url' => '/admin/alerts',
],
])
->actingAs($user)
->test(AuditLogPage::class)
->assertSet('selectedAuditLogId', (int) $audit->getKey())
->assertActionVisible('operate_hub_back_to_origin_audit_log');
});

View File

@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Models\Finding;
use App\Models\FindingException;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('renders a quiet monitoring state when no exception is selected', function (): void {
[$approver, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');
$finding = Finding::factory()->for($tenant)->create();
FindingException::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'finding_id' => (int) $finding->getKey(),
'requested_by_user_id' => (int) $approver->getKey(),
'owner_user_id' => (int) $approver->getKey(),
'status' => FindingException::STATUS_PENDING,
'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
'request_reason' => 'Queue hierarchy review lane',
'requested_at' => now()->subDay(),
'review_due_at' => now()->addDay(),
'evidence_summary' => ['reference_count' => 0],
]);
$this->actingAs($approver);
setAdminPanelContext();
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
Livewire::test(FindingExceptionsQueue::class)
->assertSee('Quiet monitoring mode')
->assertSee('Inspect an exception to enter the focused review lane.')
->assertDontSee('Focused review lane')
->assertActionHidden('approve_selected_exception')
->assertActionHidden('reject_selected_exception');
});
it('renders a focused review lane when a pending exception is selected', function (): void {
[$approver, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');
$finding = Finding::factory()->for($tenant)->create();
$exception = FindingException::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'finding_id' => (int) $finding->getKey(),
'requested_by_user_id' => (int) $approver->getKey(),
'owner_user_id' => (int) $approver->getKey(),
'status' => FindingException::STATUS_PENDING,
'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
'request_reason' => 'Focused review lane request',
'requested_at' => now()->subDay(),
'review_due_at' => now()->addDay(),
'evidence_summary' => ['reference_count' => 0],
]);
$this->actingAs($approver);
setAdminPanelContext();
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
Livewire::withQueryParams([
'exception' => (int) $exception->getKey(),
])
->test(FindingExceptionsQueue::class)
->assertSee('Focused review lane')
->assertSee('Decision lane')
->assertSee('Related drilldown')
->assertDontSee('Quiet monitoring mode')
->assertActionVisible('approve_selected_exception')
->assertActionVisible('reject_selected_exception')
->mountAction('approve_selected_exception')
->assertActionMounted('approve_selected_exception')
->callMountedAction()
->assertHasActionErrors(['approval_reason']);
Livewire::withQueryParams([
'exception' => (int) $exception->getKey(),
])
->test(FindingExceptionsQueue::class)
->mountAction('reject_selected_exception')
->assertActionMounted('reject_selected_exception')
->callMountedAction()
->assertHasActionErrors(['rejection_reason']);
});

View File

@ -202,6 +202,8 @@
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(OperationRunLinks::index($tenant, $context)) ->get(OperationRunLinks::index($tenant, $context))
->assertOk() ->assertOk()
->assertSee('Monitoring landing')
->assertSee('Return path')
->assertSee('Back to backup set') ->assertSee('Back to backup set')
->assertSee('/admin/tenant/backup-sets/1', false); ->assertSee('/admin/tenant/backup-sets/1', false);
}); });

View File

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('renders the operations landing as a quiet monitoring surface', function (): void {
$tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'inventory_sync',
]);
Filament::setTenant($tenant, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.index'))
->assertOk()
->assertSee('Monitoring landing')
->assertSee('Tabs, filters, and row inspection define the active work lane.')
->assertSee('Scope context')
->assertSee('Scope reset')
->assertSee('Inspect flow')
->assertSee('Show all tenants');
});
it('surfaces canonical return context separately from the operations work lane', function (): void {
$tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
$context = new CanonicalNavigationContext(
sourceSurface: 'backup_set.detail_section',
canonicalRouteName: 'admin.operations.index',
tenantId: (int) $tenant->getKey(),
backLinkLabel: 'Back to backup set',
backLinkUrl: '/admin/tenant/backup-sets/1',
);
Filament::setTenant($tenant, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(OperationRunLinks::index($tenant, $context))
->assertOk()
->assertSee('Monitoring landing')
->assertSee('Return path')
->assertSee('Back to backup set')
->assertSee('/admin/tenant/backup-sets/1', false)
->assertSee('Inspect flow');
});

View File

@ -37,6 +37,8 @@
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(OperationRunLinks::tenantlessView($run, $context)) ->get(OperationRunLinks::tenantlessView($run, $context))
->assertOk() ->assertOk()
->assertSee('Monitoring detail')
->assertSee('Related drilldown')
->assertSee('Back to backup set') ->assertSee('Back to backup set')
->assertSee(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant), false) ->assertSee(BackupSetResource::getUrl('view', ['record' => $backupSet], tenant: $tenant), false)
->assertSee('Related context') ->assertSee('Related context')

View File

@ -2,6 +2,9 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
@ -559,6 +562,117 @@
->assertActionVisible('operate_hub_back_to_origin_run_detail'); ->assertActionVisible('operate_hub_back_to_origin_run_detail');
}); });
it('renders the canonical tenantless viewer as a layered monitoring detail surface', function (): void {
$workspace = Workspace::factory()->create();
$user = User::factory()->create();
WorkspaceMembership::factory()->create([
'workspace_id' => (int) $workspace->getKey(),
'user_id' => (int) $user->getKey(),
'role' => 'owner',
]);
session()->forget(WorkspaceContext::SESSION_KEY);
$run = OperationRun::factory()->create([
'workspace_id' => (int) $workspace->getKey(),
'tenant_id' => null,
'type' => 'provider.connection.check',
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::Succeeded->value,
]);
$this->actingAs($user)
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertSuccessful()
->assertSee('Monitoring detail')
->assertSee('Navigation lane')
->assertSee('Utility lane')
->assertSee('Related drilldown')
->assertSee('Follow-up lane')
->assertSee('Refresh keeps the current run state accurate without changing scope.')
->assertSee('No run-specific follow-up is currently available.')
->assertDontSee('Resume capture');
});
it('surfaces resumable follow-up separately from navigation and drilldown lanes', function (): void {
$tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');
$run = OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'baseline_compare',
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::PartiallySucceeded->value,
'context' => [
'baseline_compare' => [
'resume_token' => 'resume-spec-193',
],
],
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertSuccessful()
->assertSee('Monitoring detail')
->assertSee('Follow-up lane')
->assertSee('Resume capture')
->assertSee('Resume capture only appears when this run supports additional evidence collection.')
->assertSee('Related drilldown');
});
it('keeps operations-list navigation out of the related drilldown lane', function (): void {
$tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
]);
$snapshot = BaselineSnapshot::factory()->complete()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
$run = OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'baseline_compare',
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::Succeeded->value,
'context' => [
'baseline_profile_id' => (int) $profile->getKey(),
'baseline_snapshot_id' => (int) $snapshot->getKey(),
],
]);
Filament::setTenant($tenant, true);
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
$this->actingAs($user);
Livewire::test(TenantlessOperationRunViewer::class, ['run' => $run])
->assertActionVisible('view_baseline_profile')
->assertActionVisible('view_snapshot')
->assertActionDoesNotExist('operations')
->assertActionDoesNotExist('open_operations');
$this
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertSuccessful()
->assertSee('Monitoring detail')
->assertSee('Open keeps secondary drilldowns grouped under one control: View baseline profile, View snapshot.');
});
it('renders shared polling markup for active tenantless runs', function (string $status, int $ageSeconds): void { it('renders shared polling markup for active tenantless runs', function (string $status, int $ageSeconds): void {
$workspace = Workspace::factory()->create(); $workspace = Workspace::factory()->create();
$user = User::factory()->create(); $user = User::factory()->create();

View File

@ -170,6 +170,37 @@
->assertDontSee('Show all operations'); ->assertDontSee('Show all operations');
})->group('ops-ux'); })->group('ops-ux');
it('renders shared scope and return copy as secondary monitoring context on operations surfaces', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$run = OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'policy.sync',
'status' => 'queued',
'outcome' => 'pending',
]);
$this->actingAs($user);
Filament::setTenant($tenant, true);
$this->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
])->get(route('admin.operations.index'))
->assertOk()
->assertSee('Monitoring landing')
->assertSee('Scope context')
->assertSee('Scope reset');
$this->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
])->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Monitoring detail')
->assertSee('Navigation lane')
->assertSee('Follow-up lane');
})->group('ops-ux');
it('returns 404 for non-member workspace access on /admin/operations', function (): void { it('returns 404 for non-member workspace access on /admin/operations', function (): void {
$user = User::factory()->create(); $user = User::factory()->create();
$workspace = Workspace::factory()->create(); $workspace = Workspace::factory()->create();

View File

@ -1,6 +1,7 @@
<?php <?php
use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections; use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections;
use App\Filament\Resources\ProviderConnectionResource\Pages\ViewProviderConnection;
use App\Jobs\ProviderComplianceSnapshotJob; use App\Jobs\ProviderComplianceSnapshotJob;
use App\Jobs\ProviderInventorySyncJob; use App\Jobs\ProviderInventorySyncJob;
use App\Models\OperationRun; use App\Models\OperationRun;
@ -64,6 +65,54 @@
Queue::assertPushed(ProviderInventorySyncJob::class, 1); Queue::assertPushed(ProviderInventorySyncJob::class, 1);
}); });
it('starts inventory sync from the provider connection detail page', function (): void {
Queue::fake();
$this->mock(GraphClientInterface::class, function ($mock): void {
$mock->shouldReceive('listPolicies')->never();
$mock->shouldReceive('getPolicy')->never();
$mock->shouldReceive('getOrganization')->never();
$mock->shouldReceive('applyPolicy')->never();
$mock->shouldReceive('getServicePrincipalPermissions')->never();
$mock->shouldReceive('request')->never();
});
[$user, $tenant] = createUserWithTenant(role: 'operator');
$this->actingAs($user);
$tenant->makeCurrent();
Filament::setTenant($tenant, true);
$connection = ProviderConnection::factory()->platform()->consentGranted()->create([
'tenant_id' => $tenant->getKey(),
'provider' => 'microsoft',
'entra_tenant_id' => fake()->uuid(),
'consent_status' => 'granted',
]);
Livewire::test(ViewProviderConnection::class, ['record' => $connection->getKey()])
->assertActionVisible('inventory_sync')
->callAction('inventory_sync');
$opRun = OperationRun::query()
->where('tenant_id', $tenant->getKey())
->where('type', 'inventory_sync')
->latest('id')
->first();
expect($opRun)->not->toBeNull();
expect($opRun?->context)->toMatchArray([
'provider' => 'microsoft',
'module' => 'inventory',
'provider_connection_id' => (int) $connection->getKey(),
'target_scope' => [
'entra_tenant_id' => $connection->entra_tenant_id,
],
]);
Queue::assertPushed(ProviderInventorySyncJob::class, 1);
});
it('dedupes compliance snapshot runs and does not call Graph during start', function (): void { it('dedupes compliance snapshot runs and does not call Graph during start', function (): void {
Queue::fake(); Queue::fake();

View File

@ -2,11 +2,16 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Models\Finding;
use App\Models\FindingException;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use Filament\Facades\Filament;
use Livewire\Livewire;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
it('returns 404 for non-members on representative action-surface route', function (): void { it('returns 404 for non-members on representative action-surface route', function (): void {
@ -38,3 +43,45 @@
->get(route('admin.operations.view', ['run' => (int) $runB->getKey()])) ->get(route('admin.operations.view', ['run' => (int) $runB->getKey()]))
->assertNotFound(); ->assertNotFound();
}); });
it('keeps queue approval and rejection actions behind the approval capability', function (): void {
[$approver, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');
$readonly = User::factory()->create();
createUserWithTenant(tenant: $tenant, user: $readonly, role: 'readonly', workspaceRole: 'readonly');
$finding = Finding::factory()->for($tenant)->create();
$exception = FindingException::query()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'finding_id' => (int) $finding->getKey(),
'requested_by_user_id' => (int) $approver->getKey(),
'owner_user_id' => (int) $approver->getKey(),
'status' => FindingException::STATUS_PENDING,
'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
'request_reason' => 'Authorization continuity test',
'requested_at' => now()->subDay(),
'review_due_at' => now()->addDay(),
'evidence_summary' => ['reference_count' => 0],
]);
$this->actingAs($approver);
Filament::setCurrentPanel('admin');
Filament::setTenant(null, true);
Filament::bootCurrentPanel();
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);
Livewire::withQueryParams([
'exception' => (int) $exception->getKey(),
])
->actingAs($approver)
->test(FindingExceptionsQueue::class)
->assertActionVisible('approve_selected_exception')
->assertActionVisible('reject_selected_exception');
$this->actingAs($readonly)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(FindingExceptionsQueue::getUrl(panel: 'admin'))
->assertForbidden();
});

View File

@ -40,6 +40,9 @@ function editTenantUiHeaderActions(Testable $component): array
&& $action->getTooltip() === 'You do not have permission to archive tenants.'; && $action->getTooltip() === 'You do not have permission to archive tenants.';
}) })
->mountAction('archive') ->mountAction('archive')
->setActionData([
'archive_reason' => 'Managers should not be able to archive tenants.',
])
->callMountedAction() ->callMountedAction()
->assertSuccessful(); ->assertSuccessful();
@ -67,6 +70,12 @@ function editTenantUiHeaderActions(Testable $component): array
->assertActionEnabled('archive') ->assertActionEnabled('archive')
->assertActionExists('archive', fn (Action $action): bool => $action->getLabel() === 'Archive' && $action->isConfirmationRequired()) ->assertActionExists('archive', fn (Action $action): bool => $action->getLabel() === 'Archive' && $action->isConfirmationRequired())
->mountAction('archive') ->mountAction('archive')
->assertActionMounted('archive')
->callMountedAction()
->assertHasActionErrors(['archive_reason'])
->setActionData([
'archive_reason' => 'This tenant is being archived from the edit page.',
])
->callMountedAction() ->callMountedAction()
->assertHasNoActionErrors(); ->assertHasNoActionErrors();

View File

@ -262,7 +262,7 @@
$auditLogger = app(WorkspaceAuditLogger::class); $auditLogger = app(WorkspaceAuditLogger::class);
TenantResource::restoreTenant($activeTenant, $auditLogger); TenantResource::restoreTenant($activeTenant, $auditLogger);
TenantResource::archiveTenant($onboardingTenant, $auditLogger); TenantResource::archiveTenant($onboardingTenant, $auditLogger, 'Trying to archive an onboarding tenant should be rejected.');
$activeTenant->refresh(); $activeTenant->refresh();
$onboardingTenant->refresh(); $onboardingTenant->refresh();

View File

@ -174,6 +174,8 @@
->test(ListTenants::class) ->test(ListTenants::class)
->assertTableActionVisible('archive', $tenant) ->assertTableActionVisible('archive', $tenant)
->assertTableActionEnabled('archive', $tenant) ->assertTableActionEnabled('archive', $tenant)
->assertTableActionVisible('syncTenant', $tenant)
->assertTableActionEnabled('syncTenant', $tenant)
->assertTableActionVisible('verify', $tenant) ->assertTableActionVisible('verify', $tenant)
->assertTableActionEnabled('verify', $tenant); ->assertTableActionEnabled('verify', $tenant);
@ -183,6 +185,8 @@
->test(ViewTenant::class, ['record' => $tenant->getRouteKey()]) ->test(ViewTenant::class, ['record' => $tenant->getRouteKey()])
->assertActionVisible('archive') ->assertActionVisible('archive')
->assertActionEnabled('archive') ->assertActionEnabled('archive')
->assertActionVisible('syncTenant')
->assertActionEnabled('syncTenant')
->assertActionVisible('verify') ->assertActionVisible('verify')
->assertActionEnabled('verify'); ->assertActionEnabled('verify');
}); });

View File

@ -9,10 +9,12 @@
use App\Support\OperationRunStatus; use App\Support\OperationRunStatus;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
uses(RefreshDatabase::class); uses(RefreshDatabase::class);
afterEach(function () { afterEach(function () {
Carbon::setTestNow();
CarbonImmutable::setTestNow(); CarbonImmutable::setTestNow();
}); });
@ -33,9 +35,13 @@
config()->set('tenantpilot.system_console.stuck_thresholds.queued_minutes', 10); config()->set('tenantpilot.system_console.stuck_thresholds.queued_minutes', 10);
config()->set('tenantpilot.system_console.stuck_thresholds.running_minutes', 20); config()->set('tenantpilot.system_console.stuck_thresholds.running_minutes', 20);
CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-02-27 10:00:00')); $referenceTime = CarbonImmutable::parse('2026-02-27 10:00:00');
Carbon::setTestNow($referenceTime);
CarbonImmutable::setTestNow($referenceTime);
$stuckQueued = OperationRun::factory()->create([ $stuckQueued = OperationRun::factory()->create([
'type' => 'inventory_sync',
'status' => OperationRunStatus::Queued->value, 'status' => OperationRunStatus::Queued->value,
'outcome' => OperationRunOutcome::Pending->value, 'outcome' => OperationRunOutcome::Pending->value,
'created_at' => now()->subMinutes(30), 'created_at' => now()->subMinutes(30),
@ -43,6 +49,7 @@
]); ]);
$stuckRunning = OperationRun::factory()->create([ $stuckRunning = OperationRun::factory()->create([
'type' => 'inventory_sync',
'status' => OperationRunStatus::Running->value, 'status' => OperationRunStatus::Running->value,
'outcome' => OperationRunOutcome::Pending->value, 'outcome' => OperationRunOutcome::Pending->value,
'created_at' => now()->subMinutes(25), 'created_at' => now()->subMinutes(25),
@ -50,6 +57,7 @@
]); ]);
$freshQueued = OperationRun::factory()->create([ $freshQueued = OperationRun::factory()->create([
'type' => 'inventory_sync',
'status' => OperationRunStatus::Queued->value, 'status' => OperationRunStatus::Queued->value,
'outcome' => OperationRunOutcome::Pending->value, 'outcome' => OperationRunOutcome::Pending->value,
'created_at' => now()->subMinutes(5), 'created_at' => now()->subMinutes(5),

View File

@ -218,9 +218,13 @@
->assertActionExists('go_to_runbooks', fn (Action $action): bool => $action->getLabel() === 'Go to runbooks' && $action->getUrl() === Runbooks::getUrl(panel: 'system')) ->assertActionExists('go_to_runbooks', fn (Action $action): bool => $action->getLabel() === 'Go to runbooks' && $action->getUrl() === Runbooks::getUrl(panel: 'system'))
->assertActionVisible('retry') ->assertActionVisible('retry')
->assertActionExists('retry', fn (Action $action): bool => $action->getLabel() === 'Retry' && $action->isConfirmationRequired()) ->assertActionExists('retry', fn (Action $action): bool => $action->getLabel() === 'Retry' && $action->isConfirmationRequired())
->assertActionHidden('cancel')
->assertActionVisible('mark_investigated') ->assertActionVisible('mark_investigated')
->assertActionExists('mark_investigated', fn (Action $action): bool => $action->getLabel() === 'Mark investigated' && $action->isConfirmationRequired()) ->assertActionExists('mark_investigated', fn (Action $action): bool => $action->getLabel() === 'Mark investigated' && $action->isConfirmationRequired())
->assertActionHidden('cancel'); ->mountAction('mark_investigated')
->assertActionMounted('mark_investigated')
->callMountedAction()
->assertHasActionErrors(['reason']);
expect($failedRunView->instance()->getTitle())->toBe('Operation #'.(int) $failedRun->getKey()); expect($failedRunView->instance()->getTitle())->toBe('Operation #'.(int) $failedRun->getKey());
@ -266,8 +270,19 @@
->assertActionHidden('retry') ->assertActionHidden('retry')
->assertActionVisible('cancel') ->assertActionVisible('cancel')
->assertActionExists('cancel', fn (Action $action): bool => $action->getLabel() === 'Cancel' && $action->isConfirmationRequired()) ->assertActionExists('cancel', fn (Action $action): bool => $action->getLabel() === 'Cancel' && $action->isConfirmationRequired())
->mountAction('cancel')
->assertActionMounted('cancel')
->callMountedAction()
->assertHasActionErrors(['reason']);
Livewire::test(ViewRun::class, [
'run' => $runningRun,
])
->assertActionVisible('cancel')
->assertActionVisible('mark_investigated') ->assertActionVisible('mark_investigated')
->callAction('cancel') ->callAction('cancel', data: [
'reason' => 'Stopping the in-flight run after operator triage.',
])
->assertHasNoActionErrors() ->assertHasNoActionErrors()
->assertNotified('Run cancelled'); ->assertNotified('Run cancelled');
@ -278,7 +293,8 @@
$runningRun->refresh(); $runningRun->refresh();
expect((string) $runningRun->status)->toBe(OperationRunStatus::Completed->value) expect((string) $runningRun->status)->toBe(OperationRunStatus::Completed->value)
->and((string) $runningRun->outcome)->toBe(OperationRunOutcome::Failed->value); ->and((string) $runningRun->outcome)->toBe(OperationRunOutcome::Failed->value)
->and(data_get($runningRun->context, 'triage.cancel_reason'))->toBe('Stopping the in-flight run after operator triage.');
}); });
it('keeps detail inspection and navigation available while hiding triage for view-only operators', function () { it('keeps detail inspection and navigation available while hiding triage for view-only operators', function () {

View File

@ -57,7 +57,7 @@
->assertActionEnabled('restore') ->assertActionEnabled('restore')
->assertActionExists('restore', fn (Action $action): bool => $action->getLabel() === 'Restore') ->assertActionExists('restore', fn (Action $action): bool => $action->getLabel() === 'Restore')
->assertActionHidden('archive') ->assertActionHidden('archive')
->assertActionHidden('related_onboarding'); ->assertActionDoesNotExist('related_onboarding');
}); });
it('keeps archived tenant detail inspectable for readonly members while blocking lifecycle mutation', function (): void { it('keeps archived tenant detail inspectable for readonly members while blocking lifecycle mutation', function (): void {
@ -72,7 +72,7 @@
->assertActionVisible('restore') ->assertActionVisible('restore')
->assertActionDisabled('restore') ->assertActionDisabled('restore')
->assertActionHidden('archive') ->assertActionHidden('archive')
->assertActionHidden('related_onboarding'); ->assertActionDoesNotExist('related_onboarding');
}); });
it('keeps archived tenant routes authoritative when another tenant is currently selected', function (): void { it('keeps archived tenant routes authoritative when another tenant is currently selected', function (): void {

View File

@ -1,8 +1,14 @@
<?php <?php
use App\Filament\Pages\TenantDiagnostics;
use App\Models\TenantMembership;
use App\Support\Rbac\UiTooltips;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class); uses(RefreshDatabase::class);
@ -22,3 +28,21 @@
->get("/admin/t/{$tenant->external_id}/diagnostics") ->get("/admin/t/{$tenant->external_id}/diagnostics")
->assertNotFound(); ->assertNotFound();
}); });
it('shows disabled repair affordances to readonly members when a defect exists', function () {
[$user, $tenant] = createUserWithTenant(role: 'readonly');
$this->actingAs($user);
Filament::setTenant($tenant, true);
TenantMembership::query()
->where('tenant_id', (int) $tenant->getKey())
->update(['role' => 'readonly']);
Livewire::test(TenantDiagnostics::class)
->assertActionVisible('bootstrapOwner')
->assertActionDisabled('bootstrapOwner')
->assertActionExists('bootstrapOwner', function (Action $action): bool {
return $action->getTooltip() === UiTooltips::INSUFFICIENT_PERMISSION;
});
});

View File

@ -42,7 +42,7 @@
$review = $reviewService->refresh($review, $user, $refreshSnapshot); $review = $reviewService->refresh($review, $user, $refreshSnapshot);
$review = $reviewService->compose($review->fresh()); $review = $reviewService->compose($review->fresh());
$published = $lifecycle->publish($review, $user); $published = $lifecycle->publish($review, $user, 'Publishing the current review pack.');
EvidenceSnapshot::query() EvidenceSnapshot::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('tenant_id', (int) $tenant->getKey())
@ -70,7 +70,7 @@
operationRunCount: 3, operationRunCount: 3,
)); ));
$lifecycle->archive($nextReview, $user); $lifecycle->archive($nextReview, $user, 'Replacing with a newer governance review.');
expect(AuditLog::query()->where('action', AuditActionId::TenantReviewCreated->value)->exists())->toBeTrue() expect(AuditLog::query()->where('action', AuditActionId::TenantReviewCreated->value)->exists())->toBeTrue()
->and(AuditLog::query()->where('action', AuditActionId::TenantReviewRefreshed->value)->exists())->toBeTrue() ->and(AuditLog::query()->where('action', AuditActionId::TenantReviewRefreshed->value)->exists())->toBeTrue()
@ -84,7 +84,19 @@
->latest('id') ->latest('id')
->first(); ->first();
$publishAudit = AuditLog::query()
->where('action', AuditActionId::TenantReviewPublished->value)
->latest('id')
->first();
$archiveAudit = AuditLog::query()
->where('action', AuditActionId::TenantReviewArchived->value)
->latest('id')
->first();
expect($exportAudit)->not->toBeNull() expect($exportAudit)->not->toBeNull()
->and($exportAudit?->resource_type)->toBe('tenant_review') ->and($exportAudit?->resource_type)->toBe('tenant_review')
->and(data_get($exportAudit?->metadata, 'review_pack_id'))->toBe((int) $pack->getKey()); ->and(data_get($exportAudit?->metadata, 'review_pack_id'))->toBe((int) $pack->getKey())
->and(data_get($publishAudit?->metadata, 'reason'))->toBe('Publishing the current review pack.')
->and(data_get($archiveAudit?->metadata, 'reason'))->toBe('Replacing with a newer governance review.');
}); });

View File

@ -11,6 +11,7 @@
$publishedReview = app(TenantReviewLifecycleService::class)->publish( $publishedReview = app(TenantReviewLifecycleService::class)->publish(
composeTenantReviewForTest($tenant, $user), composeTenantReviewForTest($tenant, $user),
$user, $user,
'Ready for the next review cycle.',
); );
EvidenceSnapshot::query() EvidenceSnapshot::query()

View File

@ -33,7 +33,7 @@
->and($truth->primaryLabel)->toBe('Publication blocked') ->and($truth->primaryLabel)->toBe('Publication blocked')
->and($truth->nextStepText())->toBe('Resolve the review blockers before publication'); ->and($truth->nextStepText())->toBe('Resolve the review blockers before publication');
expect(fn () => app(TenantReviewLifecycleService::class)->publish($review, $user)) expect(fn () => app(TenantReviewLifecycleService::class)->publish($review, $user, 'Ready for formal publication.'))
->toThrow(\InvalidArgumentException::class); ->toThrow(\InvalidArgumentException::class);
}); });
@ -58,7 +58,7 @@
], ],
); );
$published = app(TenantReviewLifecycleService::class)->publish($review, $user); $published = app(TenantReviewLifecycleService::class)->publish($review, $user, 'Ready for formal publication.');
$publishedAt = $published->published_at?->toIso8601String(); $publishedAt = $published->published_at?->toIso8601String();
expect($published->status)->toBe(TenantReviewStatus::Published->value) expect($published->status)->toBe(TenantReviewStatus::Published->value)
@ -67,7 +67,7 @@
$publishedTruth = app(ArtifactTruthPresenter::class)->forTenantReview($published); $publishedTruth = app(ArtifactTruthPresenter::class)->forTenantReview($published);
$archived = app(TenantReviewLifecycleService::class)->archive($published, $user); $archived = app(TenantReviewLifecycleService::class)->archive($published, $user, 'Superseded by newer review cycle.');
$archivedTruth = app(ArtifactTruthPresenter::class)->forTenantReview($archived); $archivedTruth = app(ArtifactTruthPresenter::class)->forTenantReview($archived);
expect($archived->status)->toBe(TenantReviewStatus::Archived->value) expect($archived->status)->toBe(TenantReviewStatus::Archived->value)

View File

@ -41,6 +41,8 @@
Livewire::actingAs($user) Livewire::actingAs($user)
->test(ReviewRegister::class) ->test(ReviewRegister::class)
->assertSee('Artifact truth') ->assertSee('Artifact truth')
->assertDontSee('Monitoring landing')
->assertDontSee('Navigation lane')
->assertCanSeeTableRecords([$reviewA, $reviewB]) ->assertCanSeeTableRecords([$reviewA, $reviewB])
->assertCanNotSeeTableRecords([$reviewC]) ->assertCanNotSeeTableRecords([$reviewC])
->filterTable('tenant_id', (string) $tenantB->getKey()) ->filterTable('tenant_id', (string) $tenantB->getKey())
@ -65,6 +67,42 @@
->assertSee('Clear filters'); ->assertSee('Clear filters');
}); });
it('clears the remembered tenant prefilter from the review register', function (): void {
$tenantA = Tenant::factory()->create(['name' => 'Alpha Tenant']);
[$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');
$tenantB = Tenant::factory()->create([
'workspace_id' => (int) $tenantA->workspace_id,
'name' => 'Beta Tenant',
]);
createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');
$reviewA = composeTenantReviewForTest($tenantA, $user);
$reviewB = composeTenantReviewForTest($tenantB, $user);
$this->actingAs($user);
setAdminPanelContext();
session()->put(WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);
session()->put(WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY, [
(string) $tenantA->workspace_id => (int) $tenantA->getKey(),
]);
$component = Livewire::actingAs($user)
->test(ReviewRegister::class)
->assertActionVisible('clear_filters')
->assertCanSeeTableRecords([$reviewA])
->assertCanNotSeeTableRecords([$reviewB]);
expect(app(WorkspaceContext::class)->lastTenantId())->toBe((int) $tenantA->getKey());
$component
->callAction('clear_filters')
->assertActionHidden('clear_filters')
->assertCanSeeTableRecords([$reviewA, $reviewB]);
expect(app(WorkspaceContext::class)->lastTenantId())->toBeNull();
});
it('keeps stale and partial review rows aligned with tenant review detail trust', function (): void { it('keeps stale and partial review rows aligned with tenant review detail trust', function (): void {
$staleTenant = Tenant::factory()->create(['name' => 'Stale Tenant']); $staleTenant = Tenant::factory()->create(['name' => 'Stale Tenant']);
[$user, $staleTenant] = createUserWithTenant(tenant: $staleTenant, role: 'owner'); [$user, $staleTenant] = createUserWithTenant(tenant: $staleTenant, role: 'owner');

Some files were not shown because too many files have changed in this diff Show More