Compare commits

...

10 Commits

Author SHA1 Message Date
2f45ff5a84 feat: add portfolio triage review state tracking (#220)
## Summary
- add tenant triage review-state persistence, fingerprinting, resolver logic, service layer, and migration for current affected-set tracking
- surface review-state and affected-set progress across tenant registry, tenant dashboard arrival continuity, and workspace overview
- extend RBAC, audit/badge support, specs, and test coverage for portfolio triage review-state workflows
- suppress expected hidden-page background transport failures in the global unhandled rejection logger while keeping visible-page failures logged

## Validation
- targeted Pest coverage added for tenant registry, workspace overview, arrival context, RBAC authorization, badges, fingerprinting, resolver behavior, and logger asset behavior
- code formatted with `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`

## Notes
- full suite was not re-run in this final step
- branch includes the spec artifacts under `specs/189-portfolio-triage-review-state/`

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #220
2026-04-10 21:35:17 +00:00
1655cc481e Spec 188: canonical provider connection state cleanup (#219)
## Summary
- migrate provider connections to the canonical three-dimension state model: lifecycle via `is_enabled`, consent via `consent_status`, and verification via `verification_status`
- remove legacy provider status and health badge paths, update admin and system directory surfaces, and align onboarding, consent callback, verification, resolver, and mutation flows with the new model
- add the Spec 188 artifact set, schema migrations, guard coverage, and expanded provider-state tests across admin, system, onboarding, verification, and rendering paths

## Verification
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Auth/SystemPanelAuthTest.php tests/Feature/Filament/TenantGlobalSearchLifecycleScopeTest.php tests/Feature/ProviderConnections/ProviderConnectionEnableDisableTest.php tests/Feature/ProviderConnections/ProviderConnectionTruthCleanupSpec179Test.php`
- integrated browser smoke: validated admin provider list/detail/edit, tenant provider summary, system directory tenant detail, provider-connection search exclusion, and cleaned up the temporary smoke record afterward

## Filament / implementation notes
- Livewire v4.0+ compliance: preserved; this change targets Filament v5 on Livewire v4 and does not introduce older APIs
- Provider registration location: unchanged; Laravel 11+ panel providers remain registered in `bootstrap/providers.php`
- Globally searchable resources: `ProviderConnectionResource` remains intentionally excluded from global search; tenant global search remains enabled and continues to resolve to view pages
- Destructive actions: no new destructive action surface was introduced without confirmation or authorization; existing capability checks continue to gate provider mutations
- Asset strategy: unchanged; no new Filament assets were added, so deploy behavior for `php artisan filament:assets` remains unchanged
- Testing plan covered: system auth, tenant global search, provider lifecycle enable/disable behavior, and provider truth cleanup cutover behavior

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #219
2026-04-10 11:22:56 +00:00
28e62bd22c feat: preserve portfolio triage arrival context (#218)
## Summary
- preserve portfolio triage arrival context from workspace overview and tenant registry drill-throughs
- add a tenant dashboard continuity widget plus bounded arrival token and resolver support
- add focused Pest coverage for arrival routing, return flow, RBAC degradation, and request-local performance
- include the Spec 187 spec, plan, research, data model, quickstart, contract, and tasks artifacts

## Validation
- integrated browser smoke: workspace overview -> tenant dashboard arrival -> backup sets CTA
- integrated browser smoke: tenant registry triage -> tenant dashboard arrival -> return to tenant triage
- branch includes focused automated test coverage for the new arrival-context surfaces

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #218
2026-04-09 21:38:31 +00:00
9fbd3e5ec7 Spec 186: implement tenant registry recovery triage (#217)
## Summary
- turn the tenant registry into a workspace-scoped recovery triage surface with backup posture and recovery evidence columns
- preserve workspace overview backup and recovery drilldown intent by routing multi-tenant cases into filtered tenant registry slices
- add the Spec 186 planning artifacts, focused regression coverage, and shared triage presentation helpers

## Testing
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Filament/TenantRegistryRecoveryTriageTest.php tests/Feature/Filament/WorkspaceOverviewSummaryMetricsTest.php tests/Feature/Filament/WorkspaceOverviewDrilldownContinuityTest.php tests/Feature/Filament/TenantResourceIndexIsWorkspaceScopedTest.php tests/Feature/Filament/WorkspaceOverviewAuthorizationTest.php tests/Feature/Guards/ActionSurfaceContractTest.php tests/Feature/Guards/FilamentTableStandardsGuardTest.php`

## Notes
- no schema change
- no new persisted recovery truth
- branch includes the full Spec 186 spec, plan, research, data model, contract, quickstart, and tasks artifacts

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #217
2026-04-09 19:20:48 +00:00
53e799fea7 Spec 185: workspace recovery posture visibility (#216)
## Summary
- add Spec 185 workspace recovery posture visibility artifacts under `specs/185-workspace-recovery-posture-visibility`
- promote tenant backup health and recovery evidence onto the workspace overview with separate metrics, attention ordering, calmness coverage, and tenant-dashboard drill-throughs
- batch visible-tenant backup/recovery derivation to keep the workspace overview query-bounded
- align follow-up fixes from the authoritative suite rerun, including dashboard truth-alignment fixtures, canonical backup schedule tenant context, guard-path cleanup, smoke-fixture credential removal, and robust theme asset manifest handling

## Testing
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Unit/Filament/PanelThemeAssetTest.php tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php`
- focused regression pack for the previously failing cases passed
- full suite JUnit run passed: `3401` tests, `18849` assertions, `0` failures, `0` errors, `8` skips

## Notes
- no new schema or persisted workspace recovery model
- no provider-registration changes; Filament/Livewire stack remains on Filament v5 and Livewire v4
- no new destructive actions or global search changes

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #216
2026-04-09 12:57:19 +00:00
f1a73490e4 feat: finalize dashboard recovery honesty (#215)
## Summary
- add a dedicated Recovery Readiness dashboard widget for backup posture and recovery evidence
- group Needs Attention items by domain and elevate the recovery call-to-action
- align restore-run and recovery posture tests with the extracted widget and continuity flows
- include the related spec artifacts for 184-dashboard-recovery-honesty

## Verification
- `cd /Users/ahmeddarrazi/Documents/projects/TenantAtlas/apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `cd /Users/ahmeddarrazi/Documents/projects/TenantAtlas/apps/platform && ./vendor/bin/sail artisan test --compact --filter="DashboardKpisWidget|DashboardRecoveryPosture|TenantDashboardDbOnly|TenantpilotSeedBackupHealthBrowserFixtureCommand|NeedsAttentionWidget"`
- browser smoke verified on the calm, unvalidated, and weakened dashboard states

## Notes
- Livewire v4.0+ compliant with Filament v5
- no panel provider changes; Laravel 11+ provider registration remains in `bootstrap/providers.php`
- Recovery Readiness stays within the existing tenant dashboard asset strategy; no new Filament asset registration required

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #215
2026-04-08 23:21:36 +00:00
03b1beb616 feat: implement workspace foundation website app (#214)
## Summary
- add the first multi-app workspace foundation with a new standalone Astro website under `apps/website`
- introduce repo-root pnpm workspace orchestration and migrate the platform Node workflow from npm assumptions to pnpm
- update root docs, editor or agent guidance, and workspace-focused smoke tests for the new platform plus website command model
- add Spec 183 artifacts for spec, plan, research, contracts, quickstart, checklist, and tasks

## Verification
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/WorkspaceFoundation`
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `corepack pnpm build:website`
- integrated-browser smoke: verified `http://localhost/up`, `http://localhost/admin/login`, and `http://localhost:4321/` including website anchor navigation and combined root dev flow

## Notes
- branch: `183-website-workspace-foundation`
- commit: `6d41618d`
- root command model now covers `dev:platform`, `dev:website`, `dev`, `build:platform`, and `build:website`
- website port override documentation is included in the command contract, quickstart, and README

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #214
2026-04-08 12:20:31 +00:00
ce0615a9c1 Spec 182: relocate Laravel platform to apps/platform (#213)
## Summary
- move the Laravel application into `apps/platform` and keep the repository root for orchestration, docs, and tooling
- update the local command model, Sail/Docker wiring, runtime paths, and ignore rules around the new platform location
- add relocation quickstart/contracts plus focused smoke coverage for bootstrap, command model, routes, and runtime behavior

## Validation
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/PlatformRelocation`
- integrated browser smoke validated `/up`, `/`, `/admin`, `/admin/choose-workspace`, and tenant route semantics for `200`, `403`, and `404`

## Remaining Rollout Checks
- validate Dokploy build context and working-directory assumptions against the new `apps/platform` layout
- confirm web, queue, and scheduler processes all start from the expected working directory in staging/production
- verify no legacy volume mounts or asset-publish paths still point at the old root-level `public/` or `storage/` locations

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #213
2026-04-08 08:40:47 +00:00
6f8eb28ca2 feat: add tenant backup health signals (#212)
## Summary
- add the Spec 180 tenant backup-health resolver and value objects to derive absent, stale, degraded, healthy, and schedule-follow-up posture from existing backup and schedule truth
- surface backup posture and reason-driven drillthroughs in the tenant dashboard and preserve continuity on backup-set and backup-schedule destinations
- add deterministic local/testing browser-fixture seeding plus a local fixture-login helper for the blocked drillthrough `403` scenario, along with the related spec artifacts and focused regression coverage

## Testing
- `vendor/bin/sail artisan test --compact tests/Feature/Auth/BackupHealthBrowserFixtureLoginTest.php tests/Feature/Console/TenantpilotSeedBackupHealthBrowserFixtureCommandTest.php`
- `vendor/bin/sail artisan test --compact tests/Unit/Support/BackupHealth/TenantBackupHealthResolverTest.php tests/Feature/Filament/DashboardKpisWidgetTest.php tests/Feature/Filament/NeedsAttentionWidgetTest.php tests/Feature/Filament/TenantDashboardTruthAlignmentTest.php tests/Feature/Filament/TenantDashboardTenantScopeTest.php tests/Feature/Filament/TenantDashboardDbOnlyTest.php tests/Feature/Filament/BackupSetListContinuityTest.php tests/Feature/Filament/BackupSetEnterpriseDetailPageTest.php tests/Feature/BackupScheduling/BackupScheduleLifecycleTest.php tests/Feature/Auth/BackupHealthBrowserFixtureLoginTest.php tests/Feature/Console/TenantpilotSeedBackupHealthBrowserFixtureCommandTest.php`

## Notes
- Filament v5 / Livewire v4 compliant; no panel-provider change was needed, so `bootstrap/providers.php` remains unchanged
- no new globally searchable resource was introduced, so global-search behavior is unchanged
- no new destructive action was added; existing destructive actions and confirmation behavior remain unchanged
- no new asset registration was added; the existing deploy-time `php artisan filament:assets` step remains sufficient
- the local fixture login helper route is limited to `local` and `testing` environments
- the focused and broader Spec 180 packs are green; the full suite was not rerun after these changes

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #212
2026-04-07 21:35:58 +00:00
e840007127 feat: add backup quality truth surfaces (#211)
## Summary
- add a shared backup-quality resolver and summary model for backup sets, backup items, policy versions, and restore selection
- surface backup-quality truth across Filament backup-set, policy-version, and restore-wizard entry points
- add focused Pest coverage and the full Spec Kit artifact set for spec 176

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

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #211
2026-04-07 11:39:40 +00:00
2523 changed files with 37180 additions and 6653 deletions

View File

@ -1,7 +1,12 @@
node_modules/ node_modules/
apps/platform/node_modules/
apps/website/node_modules/
apps/website/.astro/
apps/website/dist/
dist/ dist/
build/ build/
vendor/ vendor/
apps/platform/vendor/
coverage/ coverage/
.git/ .git/
.DS_Store .DS_Store
@ -18,12 +23,19 @@ Dockerfile*
*.tmp *.tmp
*.swp *.swp
public/build/ public/build/
apps/platform/public/build/
public/hot/ public/hot/
apps/platform/public/hot/
public/storage/ public/storage/
apps/platform/public/storage/
storage/framework/ storage/framework/
apps/platform/storage/framework/
storage/logs/ storage/logs/
apps/platform/storage/logs/
storage/debugbar/ storage/debugbar/
apps/platform/storage/debugbar/
storage/*.key storage/*.key
apps/platform/storage/*.key
/references/ /references/
.idea/ .idea/
.vscode/ .vscode/

View File

@ -2,6 +2,14 @@ # TenantAtlas Development Guidelines
Auto-generated from all feature plans. Last updated: 2025-12-22 Auto-generated from all feature plans. Last updated: 2025-12-22
## Relocation override
- The authoritative Laravel application root is `apps/platform`.
- Human-facing commands should use `cd apps/platform && ...`.
- Repo-root tooling may delegate via `./scripts/platform-sail` when it cannot set a nested working directory.
- Repo-root JavaScript orchestration uses `corepack pnpm install`, `corepack pnpm dev:platform`, `corepack pnpm dev:website`, `corepack pnpm dev`, `corepack pnpm build:website`, and `corepack pnpm build:platform`.
- `apps/website` is a standalone Astro app, not a second Laravel runtime, so Boost MCP remains platform-only.
- If any generated technology note below conflicts with the current repo, trust `apps/platform/composer.json`, `apps/platform/package.json`, and the live Laravel application metadata over stale generated entries.
## Active Technologies ## Active Technologies
- PHP 8.4.15 + Laravel 12, Filament v4, Livewire v3 (feat/005-bulk-operations) - PHP 8.4.15 + Laravel 12, Filament v4, Livewire v3 (feat/005-bulk-operations)
- PostgreSQL (app), SQLite in-memory (tests) (feat/005-bulk-operations) - PostgreSQL (app), SQLite in-memory (tests) (feat/005-bulk-operations)
@ -137,27 +145,62 @@ ## Active Technologies
- PostgreSQL unchanged; existing `operation_runs` JSONB-backed `context`, `summary_counts`, and `failure_summary`; no schema change (178-ops-truth-alignment) - PostgreSQL unchanged; existing `operation_runs` JSONB-backed `context`, `summary_counts`, and `failure_summary`; no schema change (178-ops-truth-alignment)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers (181-restore-safety-integrity) - PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers (181-restore-safety-integrity)
- PostgreSQL with existing `restore_runs` and `operation_runs` records plus JSON or array-backed `metadata`, `preview`, `results`, and `context`; no schema change planned (181-restore-safety-integrity) - PostgreSQL with existing `restore_runs` and `operation_runs` records plus JSON or array-backed `metadata`, `preview`, `results`, and `context`; no schema change planned (181-restore-safety-integrity)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BackupSetResource`, `BackupItemsRelationManager`, `PolicyVersionResource`, `RestoreRunResource`, `CreateRestoreRun`, `AssignmentBackupService`, `VersionService`, `PolicySnapshotService`, `RestoreRiskChecker`, `BadgeRenderer`, `PolicySnapshotModeBadge`, `EnterpriseDetailBuilder`, and existing RBAC helpers (176-backup-quality-truth)
- PostgreSQL with existing tenant-owned `backup_sets`, `backup_items`, `policy_versions`, and restore wizard input state; JSON-backed `metadata`, `snapshot`, `assignments`, and `scope_tags`; no schema change planned (176-backup-quality-truth)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `DashboardKpis`, `NeedsAttention`, `BackupSetResource`, `BackupScheduleResource`, `BackupQualityResolver`, `BackupQualitySummary`, `ScheduleTimeService`, shared badge infrastructure, and existing RBAC helpers (180-tenant-backup-health)
- PostgreSQL with existing tenant-owned `backup_sets`, `backup_items`, and `backup_schedules` records plus existing JSON-backed backup metadata; no schema change planned (180-tenant-backup-health)
- PHP 8.4.15, Laravel 12, Blade, Livewire v4, Filament v5.2.x, Tailwind CSS v4, Vite 7 + `laravel/framework`, `filament/filament`, `livewire/livewire`, `laravel/sail`, `laravel-vite-plugin`, `tailwindcss`, `vite`, `pestphp/pest`, `drizzle-kit`, PostgreSQL, Redis, Docker Compose (182-platform-relocation)
- PostgreSQL, Redis, filesystem storage under the Laravel app `storage/` tree, plus existing Vite build artifacts in `public/build`; no new database persistence planned (182-platform-relocation)
- PHP 8.4.15 and Laravel 12 for `apps/platform`; Node.js 20+ with pnpm 10 workspace tooling; Astro v6 for `apps/website`; Bash and Docker Compose for root orchestration + `laravel/framework`, `filament/filament`, `livewire/livewire`, `laravel/sail`, `vite`, `tailwindcss`, `pnpm` workspaces, Astro, existing `./scripts/platform-sail` wrapper, repo-root Docker Compose (183-website-workspace-foundation)
- Existing PostgreSQL, Redis, and filesystem storage for `apps/platform`; static build artifacts for `apps/website`; repository-managed workspace manifests and docs; no new database persistence (183-website-workspace-foundation)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5 widgets and resources, Livewire v4, Pest v4, existing `TenantDashboard`, `DashboardKpis`, `NeedsAttention`, `TenantBackupHealthResolver`, `TenantBackupHealthAssessment`, `RestoreRunResource`, `RestoreSafetyResolver`, `RestoreResultAttention`, `OperationRunLinks`, and existing RBAC helpers (184-dashboard-recovery-honesty)
- PostgreSQL with existing tenant-owned `backup_sets`, `restore_runs`, and linked `operation_runs`; no schema change planned (184-dashboard-recovery-honesty)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `WorkspaceOverviewBuilder`, `WorkspaceSummaryStats`, `WorkspaceNeedsAttention`, `TenantBackupHealthResolver`, `TenantBackupHealthAssessment`, `RestoreSafetyResolver`, tenant dashboard widgets, `WorkspaceCapabilityResolver`, `CapabilityResolver`, and the current workspace overview Blade surfaces (185-workspace-recovery-posture-visibility)
- PostgreSQL unchanged; no schema change, new cache table, or persisted workspace recovery artifact is planned (185-workspace-recovery-posture-visibility)
- PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5 resources and table filters, Livewire v4 `ListRecords`, Pest v4, Laravel Sail, existing `TenantResource`, `ListTenants`, `WorkspaceOverviewBuilder`, `TenantBackupHealthResolver`, `TenantBackupHealthAssessment`, `RestoreSafetyResolver`, `RecoveryReadiness`, and shared badge infrastructure (186-tenant-registry-recovery-triage)
- PostgreSQL with existing tenant-owned `tenants`, `backup_sets`, `backup_items`, `restore_runs`, `policies`, and membership records; no schema change planned (186-tenant-registry-recovery-triage)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `WorkspaceOverviewBuilder`, `TenantResource`, `TenantDashboard`, `CanonicalAdminTenantFilterState`, `TenantBackupHealthAssessment`, `RestoreSafetyResolver`, and continuity-aware backup or restore list pages (187-portfolio-triage-arrival-context)
- PostgreSQL unchanged; no new tables, caches, or durable workflow artifacts (187-portfolio-triage-arrival-context)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `ProviderConnection` model, `ProviderConnectionResolver`, `ProviderConnectionStateProjector`, `ProviderConnectionMutationService`, `ProviderConnectionHealthCheckJob`, `StartVerification`, `ProviderConnectionResource`, `TenantResource`, system directory pages, `BadgeCatalog`, `BadgeRenderer`, and shared provider-state Blade entries (188-provider-connection-state-cleanup)
- PostgreSQL with one narrow schema addition (`is_enabled`) followed by final removal of legacy `status` and `health_status` columns and their indexes (188-provider-connection-state-cleanup)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `WorkspaceOverviewBuilder`, `TenantResource`, `TenantDashboard`, `PortfolioArrivalContext`, `TenantBackupHealthResolver`, `RestoreSafetyResolver`, `BadgeCatalog`, `UiEnforcement`, and `AuditRecorder` patterns (189-portfolio-triage-review-state)
- PostgreSQL via Laravel Eloquent with one new table `tenant_triage_reviews` and no new external caches or background stores (189-portfolio-triage-review-state)
- PHP 8.4.15 (feat/005-bulk-operations) - PHP 8.4.15 (feat/005-bulk-operations)
## Project Structure ## Project Structure
```text ```text
src/ apps/
tests/ platform/
website/
docs/
specs/
scripts/
``` ```
## Commands ## Commands
# Add commands for PHP 8.4.15 - Root workspace:
- `corepack pnpm install`
- `corepack pnpm dev:platform`
- `corepack pnpm dev:website`
- `corepack pnpm dev`
- `corepack pnpm build:website`
- `corepack pnpm build:platform`
- Platform app:
- `cd apps/platform && ./vendor/bin/sail up -d`
- `cd apps/platform && ./vendor/bin/sail pnpm dev`
- `cd apps/platform && ./vendor/bin/sail pnpm build`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact`
## Code Style ## Code Style
PHP 8.4.15: Follow standard conventions PHP 8.4.15: Follow standard conventions
## Recent Changes ## Recent Changes
- 181-restore-safety-integrity: Added PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `RestoreRunResource`, `RestoreService`, `RestoreRiskChecker`, `RestoreDiffGenerator`, `OperationRunResource`, `TenantlessOperationRunViewer`, shared badge infrastructure, and existing RBAC or write-gate helpers - 189-portfolio-triage-review-state: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `WorkspaceOverviewBuilder`, `TenantResource`, `TenantDashboard`, `PortfolioArrivalContext`, `TenantBackupHealthResolver`, `RestoreSafetyResolver`, `BadgeCatalog`, `UiEnforcement`, and `AuditRecorder` patterns
- 178-ops-truth-alignment: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `OperationRun`, `OperationLifecyclePolicy`, `OperationRunFreshnessState`, `OperationUxPresenter`, `OperationRunLinks`, `ActiveRuns`, `StuckRunClassifier`, `WorkspaceOverviewBuilder`, dashboard widgets, workspace widgets, and system ops pages - 188-provider-connection-state-cleanup: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `ProviderConnection` model, `ProviderConnectionResolver`, `ProviderConnectionStateProjector`, `ProviderConnectionMutationService`, `ProviderConnectionHealthCheckJob`, `StartVerification`, `ProviderConnectionResource`, `TenantResource`, system directory pages, `BadgeCatalog`, `BadgeRenderer`, and shared provider-state Blade entries
- 177-inventory-coverage-truth: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `InventoryItem`, `OperationRun`, `InventoryCoverage`, `InventoryPolicyTypeMeta`, `CoverageCapabilitiesResolver`, `InventoryKpiHeader`, `InventoryCoverage` page, and `OperationRunResource` enterprise-detail stack - 187-portfolio-triage-arrival-context: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `WorkspaceOverviewBuilder`, `TenantResource`, `TenantDashboard`, `CanonicalAdminTenantFilterState`, `TenantBackupHealthAssessment`, `RestoreSafetyResolver`, and continuity-aware backup or restore list pages
<!-- MANUAL ADDITIONS START --> <!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END --> <!-- MANUAL ADDITIONS END -->

View File

@ -40,7 +40,7 @@ ## 3) Panel setup defaults
- Assets policy: - Assets policy:
- Panel-only assets: register via panel config. - Panel-only assets: register via panel config.
- Shared/plugin assets: register via `FilamentAsset::register()`. - Shared/plugin assets: register via `FilamentAsset::register()`.
- Deployment must include `php artisan filament:assets`. - Deployment must include `cd apps/platform && php artisan filament:assets`.
Sources: Sources:
- https://filamentphp.com/docs/5.x/panel-configuration - https://filamentphp.com/docs/5.x/panel-configuration
@ -254,7 +254,7 @@ ## Testing
- Source: https://filamentphp.com/docs/5.x/testing/testing-actions — “Testing actions” - Source: https://filamentphp.com/docs/5.x/testing/testing-actions — “Testing actions”
## Deployment / Ops ## Deployment / Ops
- [ ] `php artisan filament:assets` is included in the deployment process when using registered assets. - [ ] `cd apps/platform && php artisan filament:assets` is included in the deployment process when using registered assets.
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade” - Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade”
=== foundation rules === === foundation rules ===
@ -291,8 +291,12 @@ ## Application Structure & Architecture
- Stick to existing directory structure; don't create new base folders without approval. - Stick to existing directory structure; don't create new base folders without approval.
- Do not change the application's dependencies without approval. - Do not change the application's dependencies without approval.
## Workspace Commands
- Repo-root JavaScript orchestration now uses `corepack pnpm install`, `corepack pnpm dev:platform`, `corepack pnpm dev:website`, `corepack pnpm dev`, `corepack pnpm build:website`, and `corepack pnpm build:platform`.
- `apps/website` is a standalone Astro app, not a second Laravel runtime, so Boost MCP remains platform-only.
## Frontend Bundling ## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `vendor/bin/sail npm run build`, `vendor/bin/sail npm run dev`, or `vendor/bin/sail composer run dev`. Ask them. - If the user doesn't see a platform frontend change reflected in the UI, it could mean they need to run `cd apps/platform && ./vendor/bin/sail pnpm build`, `cd apps/platform && ./vendor/bin/sail pnpm dev`, or `cd apps/platform && ./vendor/bin/sail composer run dev`. Ask them.
## Replies ## Replies
- Be concise in your explanations - focus on what's important rather than explaining obvious details. - Be concise in your explanations - focus on what's important rather than explaining obvious details.
@ -372,28 +376,29 @@ ## Enums
## Laravel Sail ## Laravel Sail
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail. - This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
- Start services using `vendor/bin/sail up -d` and stop them with `vendor/bin/sail stop`. - The canonical application working directory is `apps/platform`. Repo-root launchers such as MCP or VS Code tasks may use `./scripts/platform-sail`, but that helper is compatibility-only.
- Open the application in the browser by running `vendor/bin/sail open`. - Start services using `cd apps/platform && ./vendor/bin/sail up -d` and stop them with `cd apps/platform && ./vendor/bin/sail stop`.
- Always prefix PHP, Artisan, Composer, and Node commands with `vendor/bin/sail`. Examples: - Open the application in the browser by running `cd apps/platform && ./vendor/bin/sail open`.
- Run Artisan Commands: `vendor/bin/sail artisan migrate` - Always prefix PHP, Artisan, Composer, and Node commands with `cd apps/platform && ./vendor/bin/sail`. Examples:
- Install Composer packages: `vendor/bin/sail composer install` - Run Artisan Commands: `cd apps/platform && ./vendor/bin/sail artisan migrate`
- Execute Node commands: `vendor/bin/sail npm run dev` - Install Composer packages: `cd apps/platform && ./vendor/bin/sail composer install`
- Execute PHP scripts: `vendor/bin/sail php [script]` - Execute Node commands: `cd apps/platform && ./vendor/bin/sail pnpm dev`
- View all available Sail commands by running `vendor/bin/sail` without arguments. - Execute PHP scripts: `cd apps/platform && ./vendor/bin/sail php [script]`
- View all available Sail commands by running `cd apps/platform && ./vendor/bin/sail` without arguments.
=== tests rules === === tests rules ===
## Test Enforcement ## Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. - Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `vendor/bin/sail artisan test --compact` with a specific filename or filter. - Run the minimum number of tests needed to ensure code quality and speed. Use `cd apps/platform && ./vendor/bin/sail artisan test --compact` with a specific filename or filter.
=== laravel/core rules === === laravel/core rules ===
## Do Things the Laravel Way ## Do Things the Laravel Way
- Use `vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. - Use `cd apps/platform && ./vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `vendor/bin/sail artisan make:class`. - If you're creating a generic PHP class, use `cd apps/platform && ./vendor/bin/sail artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
### Database ### Database
@ -404,7 +409,7 @@ ### Database
- Use Laravel's query builder for very complex database operations. - Use Laravel's query builder for very complex database operations.
### Model Creation ### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `vendor/bin/sail artisan make:model`. - When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `cd apps/platform && ./vendor/bin/sail artisan make:model`.
### APIs & Eloquent Resources ### APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention. - For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
@ -428,10 +433,10 @@ ### Configuration
### Testing ### Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`. - Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. - When creating tests, make use of `cd apps/platform && ./vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
### Vite Error ### Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `vendor/bin/sail npm run build` or ask the user to run `vendor/bin/sail npm run dev` or `vendor/bin/sail composer run dev`. - If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `cd apps/platform && ./vendor/bin/sail pnpm build` or ask the user to run `cd apps/platform && ./vendor/bin/sail pnpm dev` or `cd apps/platform && ./vendor/bin/sail composer run dev`.
=== laravel/v12 rules === === laravel/v12 rules ===
@ -460,7 +465,7 @@ ### Models
## Livewire ## Livewire
- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests. - Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests.
- Use the `vendor/bin/sail artisan make:livewire [Posts\CreatePost]` Artisan command to create new components. - Use the `cd apps/platform && ./vendor/bin/sail artisan make:livewire [Posts\CreatePost]` Artisan command to create new components.
- State should live on the server, with the UI reflecting it. - State should live on the server, with the UI reflecting it.
- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions. - All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions.
@ -504,8 +509,8 @@ ## Testing Livewire
## Laravel Pint Code Formatter ## Laravel Pint Code Formatter
- You must run `vendor/bin/sail bin pint --dirty` before finalizing changes to ensure your code matches the project's expected style. - You must run `cd apps/platform && ./vendor/bin/sail bin pint --dirty` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/sail bin pint --test`, simply run `vendor/bin/sail bin pint` to fix any formatting issues. - Do not run `cd apps/platform && ./vendor/bin/sail bin pint --test`, simply run `cd apps/platform && ./vendor/bin/sail bin pint` to fix any formatting issues.
=== pest/core rules === === pest/core rules ===
@ -514,7 +519,7 @@ ### Testing
- If you need to verify a feature is working, write or update a Unit / Feature test. - If you need to verify a feature is working, write or update a Unit / Feature test.
### Pest Tests ### Pest Tests
- All tests must be written using Pest. Use `vendor/bin/sail artisan make:test --pest {name}`. - All tests must be written using Pest. Use `cd apps/platform && ./vendor/bin/sail artisan make:test --pest {name}`.
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application. - You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
- Tests should test all of the happy paths, failure paths, and weird paths. - Tests should test all of the happy paths, failure paths, and weird paths.
- Tests live in the `tests/Feature` and `tests/Unit` directories. - Tests live in the `tests/Feature` and `tests/Unit` directories.
@ -527,9 +532,9 @@ ### Pest Tests
### Running Tests ### Running Tests
- Run the minimal number of tests using an appropriate filter before finalizing code edits. - Run the minimal number of tests using an appropriate filter before finalizing code edits.
- To run all tests: `vendor/bin/sail artisan test --compact`. - To run all tests: `cd apps/platform && ./vendor/bin/sail artisan test --compact`.
- To run all tests in a file: `vendor/bin/sail artisan test --compact tests/Feature/ExampleTest.php`. - To run all tests in a file: `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/ExampleTest.php`.
- To filter on a particular test name: `vendor/bin/sail artisan test --compact --filter=testName` (recommended after making a change to a related file). - To filter on a particular test name: `cd apps/platform && ./vendor/bin/sail artisan test --compact --filter=testName` (recommended after making a change to a related file).
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing. - When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
### Pest Assertions ### Pest Assertions

19
.gitignore vendored
View File

@ -15,19 +15,34 @@
/.zed /.zed
/auth.json /auth.json
/node_modules /node_modules
/apps/platform/node_modules
/apps/website/node_modules
/.pnpm-store
/apps/website/.astro
dist/ dist/
build/ build/
coverage/ coverage/
/public/build /public/build
/apps/platform/public/build
/apps/website/dist
/public/hot /public/hot
/apps/platform/public/hot
/public/storage /public/storage
/apps/platform/public/storage
/storage/*.key /storage/*.key
/apps/platform/storage/*.key
/storage/pail /storage/pail
/apps/platform/storage/pail
/storage/framework /storage/framework
/apps/platform/storage/framework
/storage/logs /storage/logs
/apps/platform/storage/logs
/storage/debugbar /storage/debugbar
/apps/platform/storage/debugbar
/vendor /vendor
/apps/platform/vendor
/bootstrap/cache /bootstrap/cache
/apps/platform/bootstrap/cache
Homestead.json Homestead.json
Homestead.yaml Homestead.yaml
Thumbs.db Thumbs.db
@ -35,3 +50,7 @@ Thumbs.db
/tests/Browser/Screenshots /tests/Browser/Screenshots
*.tmp *.tmp
*.swp *.swp
/apps/platform/.env
/apps/platform/.env.*
/apps/website/.env
/apps/website/.env.*

View File

@ -1,8 +1,14 @@
dist/ dist/
build/ build/
public/build/ public/build/
apps/platform/public/build/
node_modules/ node_modules/
apps/platform/node_modules/
apps/website/node_modules/
apps/website/.astro/
apps/website/dist/
vendor/ vendor/
apps/platform/vendor/
*.log *.log
.env .env
.env.* .env.*

View File

@ -2,12 +2,22 @@ node_modules/
dist/ dist/
build/ build/
public/build/ public/build/
apps/platform/public/build/
public/hot/ public/hot/
apps/platform/public/hot/
public/storage/ public/storage/
apps/platform/public/storage/
coverage/ coverage/
vendor/ vendor/
apps/platform/vendor/
apps/platform/node_modules/
apps/website/node_modules/
apps/website/.astro/
apps/website/dist/
storage/ storage/
apps/platform/storage/
bootstrap/cache/ bootstrap/cache/
apps/platform/bootstrap/cache/
package-lock.json package-lock.json
yarn.lock yarn.lock
pnpm-lock.yaml pnpm-lock.yaml

View File

@ -109,6 +109,15 @@ ### Mandatory Bloat Check for New Specs (BLOAT-001)
6. Is this current-release truth or future-release preparation? 6. Is this current-release truth or future-release preparation?
- Specs that cannot answer these questions clearly MUST NOT merge. - Specs that cannot answer these questions clearly MUST NOT merge.
### Spec Candidate Gate (SPEC-GATE-001)
- Every new spec candidate MUST pass the Spec Approval Rubric (`.specify/memory/spec-approval-rubric.md`) before progressing beyond Draft status.
- The spec MUST include a filled-out "Spec Candidate Check" section answering the 5 mandatory questions (operator workflow, trust/safety, smallest version, permanent complexity, why now).
- The spec MUST be classified into exactly one approval class: Core Enterprise, Workflow Compression, Cleanup, or Defer.
- The spec MUST include a scored evaluation (6 dimensions, 02 each). Specs scoring below 7/12 MUST NOT be approved without explicit scope reduction.
- If two or more red flags from the rubric are triggered, the spec MUST include an explicit defense justifying why it should proceed.
- Specs classified as "Defer" or scoring 03 MUST NOT be implemented.
- This gate applies to all spec-creating agents (speckit.specify, speckit.plan) and manual spec creation alike.
### Default Bias (BIAS-001) ### Default Bias (BIAS-001)
- Default codebase bias is: derive before persist, map before frameworkize, localize before generalize, simplify before extend, replace before layer, explicit before generic, and present directly before interpreting recursively. - Default codebase bias is: derive before persist, map before frameworkize, localize before generalize, simplify before extend, replace before layer, explicit before generic, and present directly before interpreting recursively.

View File

@ -0,0 +1,236 @@
# TenantPilot Spec Approval Rubric (Anti-Overengineering Guardrails)
## Leitsatz
> Kein neuer Layer ohne klaren Operatorgewinn, und kein neuer Spec nur für interne semantische Schönheit.
Ein neuer Spec ist nur dann stark genug, wenn er **sichtbar mehr Produktwahrheit oder Operator-Wirkung** erzeugt als er dauerhafte Systemkomplexität importiert.
Jeder Spec muss zwei Dinge gleichzeitig beweisen:
1. Welches echte Problem wird gelöst?
2. Warum ist diese Lösung die kleinste enterprise-taugliche Form?
Wenn der Spec nur interne Eleganz, feinere Semantik oder mehr Konsistenz bringt, aber keinen klaren Workflow-, Trust- oder Audit-Gewinn, dann ist er **verdächtig**.
---
## 5 Pflichtfragen vor jeder Freigabe
Ein Spec darf nur weiterverfolgt werden, wenn diese 5 Fragen sauber beantwortet sind.
### A. Welcher konkrete Operator-Workflow wird besser?
Nicht abstrakt „Konsistenz verbessern", sondern konkret: welcher Nutzer, auf welcher Fläche, in welchem Schritt, mit welchem heutigen Schmerz, und was danach schneller, sicherer oder ehrlicher wird.
Wenn kein klarer Vorher/Nachher-Workflow benennbar ist → Spec ist zu abstrakt.
### B. Welche falsche oder gefährliche Produktaussage wird verhindert?
Legitime Antworten:
- Falscher „alles okay"-Eindruck
- Irreführende Recovery-Claims
- Unsaubere Ownership
- Fehlende nächste Aktion
- Fehlende Audit-Nachvollziehbarkeit
- Tenant/Workspace Leakage
- RBAC-Missverständnisse
Wenn ein Spec weder Workflow noch Trust verbessert → kaum zu rechtfertigen.
### C. Was ist die kleinste brauchbare Version?
Explizit benennen:
- Was ist die v1-Minimalversion?
- Welche Teile sind bewusst nicht enthalten?
- Welche Generalisierung wird absichtlich verschoben?
Wenn v1 wie ein Framework, eine Plattform oder eine universelle Taxonomie klingt → zu groß.
### D. Welche dauerhafte Komplexität entsteht?
Nicht nur Implementierungsaufwand, sondern Dauerfolgen:
- Neue Models / Tables?
- Neue Enums / Statusachsen?
- Neue UI-Semantik?
- Neue cross-surface Contracts?
- Neue Tests, die dauerhaft gepflegt werden müssen?
- Neue Begriffe, die jeder verstehen muss?
Wenn die Liste lang ist → Produktgewinn muss entsprechend hoch sein.
### E. Warum jetzt?
Legitime Gründe:
- Blockiert Kernworkflow
- Verhindert gefährliche Fehlinterpretation
- Ist Voraussetzung für unmittelbar folgende Hauptdomäne
- Beseitigt echten systemischen Widerspruch
- Wird bereits von mehreren Flächen schmerzhaft benötigt
Schwache Gründe:
- „wäre sauberer"
- „brauchen wir später bestimmt"
- „passt gut zur Architektur"
- „macht das Modell vollständiger"
---
## 4 Spec-Klassen
Jeden Kandidaten zwingend in genau eine Klasse einordnen.
### Klasse 1 — Core Enterprise Spec
Mindestens eins muss stimmen:
- Schützt echte System-/Tenant-/RBAC-Korrektheit
- Verhindert falsche Governance-/Recovery-/Audit-Aussagen
- Schließt klaren Workflow-Gap
- Beseitigt cross-surface Widerspruch mit realem Operator-Schaden
- Ist echte Voraussetzung für eine wichtige Produktfunktion
Dürfen Komplexität einführen, aber nur gezielt.
### Klasse 2 — Workflow Compression Spec
Gut, wenn sie:
- Klickpfade verkürzen
- Kontextverlust senken
- Return-/Drilldown-Kontinuität verbessern
- Triage-/Review-/Run-Bearbeitung beschleunigen
Nützlich, aber klein halten.
### Klasse 3 — Cleanup / Consolidation
- Vereinfachung, Zusammenführung, Entkopplung
- Entfernen von Legacy / Duplikaten
- Reduktion unnötiger Schichten
Explizit erwünscht als Gegengewicht zu Wachstum.
### Klasse 4 — Premature / Defer
Wenn der Kandidat hauptsächlich bringt:
- Neue Semantik, Frameworks, Taxonomien
- Generalisierung für künftige Fälle
- Infrastruktur ohne breite aktuelle Nutzung
→ Nicht freigeben. Verschieben oder brutal einkürzen.
---
## Rote Flaggen
Wenn **zwei oder mehr** zutreffen → Spec muss aktiv verteidigt werden.
| # | Rote Flagge | Prüffrage |
|---|---|---|
| 1 | **Neue Achsen** — neues Truth-Modell, Statusdimension, Taxonomie, Bewertungsachse | Braucht der Operator das wirklich, oder nur das Modell? |
| 2 | **Neue Meta-Infrastruktur** — Presenter, Resolver, Catalog, Matrix, Registry, Builder, Policy-Layer | Sehr hoher Beweiswert nötig. |
| 3 | **Viele Flächen, wenig Nutzerwert** — 6 Flächen „harmonisiert", kein klarer Nutzerflow besser | Architektur um ihrer selbst willen? |
| 4 | **Klingt nach Foundation** — foundation, framework, generalized, reusable, future-proof, canonical semantics | Fast immer erklärungsbedürftig. |
| 5 | **Mehr Begriffe als Outcomes** — lange semantische Erklärung, Nutzerverbesserung kaum in einem Satz | Verdächtig. |
| 6 | **Mehrere Mikrospecs für eine Domäne** — foundation + semantics + presentation + hardening + integration | Zu fein zerlegt. |
---
## Grüne Flaggen
- Löst klar beobachtbaren Operator-Schmerz
- Verbessert echte Entscheidungssituation
- Verhindert konkrete Fehlinterpretation
- Reduziert Navigation oder Denkaufwand
- Vereinfacht bereits existierende Komplexität
- Führt wenig neue Begriffe ein
- Hat klare Nicht-Ziele
- Ist in einer Sitzung gut erklärbar
- Braucht keine neue Meta-Schicht
- Macht mehrere Flächen einfacher statt abstrakter
---
## Bewertungsraster (02 pro Dimension)
| Dimension | 0 | 1 | 2 |
|---|---|---|---|
| **Nutzen** | unklar | lokal nützlich | klarer Workflow-/Trust-/Audit-Gewinn |
| **Dringlichkeit** | kann warten | sinnvoll bald | blockiert oder schützt Wichtiges jetzt |
| **Scope-Disziplin** | wirkt wie Framework/Plattform | etwas breit | klar begrenzte v1 |
| **Komplexitätslast** | hohe dauerhafte Last | mittel | niedrig / gut beherrschbar |
| **Produktnähe** | vor allem intern/architektonisch | gemischt | direkt spürbar für Operatoren |
| **Wiederverwendung belegt** | hypothetisch | wahrscheinlich | bereits an mehreren echten Stellen nötig |
### Auswertung
| Score | Entscheidung |
|---|---|
| **1012** | Freigabefähig |
| **79** | Nur freigeben wenn Scope enger gezogen wird |
| **46** | Verschieben oder zu Cleanup/Micro-Follow-up downgraden |
| **03** | Nicht freigeben |
---
## TenantPilot-spezifische Regeln
### Regel A — Keine neue semantische Achse ohne UI-Beweis
Wo wird sie sichtbar? Warum reichen bestehende Achsen nicht? Welche Fehlentscheidung bleibt ohne sie bestehen?
### Regel B — Keine neue Support-/Presentation-Schicht ohne ≥ 3 echte Verbraucher
Registry, Resolver, Catalog, Presenter, Matrix, Explanation-Layer → nur mit mindestens drei echten (nicht künstlich erzeugten) Verbrauchern. Sonst lokal lösen.
### Regel C — Keine Spec-Aufspaltung unterhalb Operator-Domäne
Wenn ein Thema nicht eigenständig als Operator-Problem beschrieben werden kann → kein eigener Spec.
### Regel D — Jeder neue Status braucht eine echte Folgehandlung
Neue Status/Outcome nur erlaubt wenn sie etwas Konkretes ändern: andere nächste Aktion, anderes Routing, andere Audit-Bedeutung, andere Workflow-Behandlung.
### Regel E — Consolidation ist ein legitimer Spec-Typ
Zusammenführen von Semantik, Reduktion von Komplexität, Entfernen von Parallelmodellen, Vereinfachung von Navigation/Resolvern, Rückbau unnötiger Zwischenlayer — aktiv Platz geben.
---
## Freigabe-Template (Pflichtabschnitt in spec.md)
```markdown
## Spec Candidate Check
- **Problem**: [Konkreter Operator-Schmerz oder Trust-Gap heute]
- **Today's failure**: [Welche Fehlentscheidung / Verlangsamung / irreführende Produktaussage passiert aktuell?]
- **User-visible improvement**: [Was wird konkret schneller, sicherer oder ehrlicher?]
- **Smallest enterprise-capable version**: [Kleinste Version die das Problem sauber löst]
- **Explicit non-goals**: [Was wird bewusst nicht modelliert/generalisiert/frameworkisiert?]
- **Permanent complexity imported**: [Neue Models, Status, Enums, Services, Support-Layer, Tests, UI-Konzepte, Begriffe]
- **Why now**: [Warum jetzt wichtiger als später?]
- **Why not local**: [Warum reicht keine lokale, schmale Lösung?]
- **Approval class**: [Core Enterprise / Workflow Compression / Cleanup / Defer]
- **Red flags triggered**: [Welche roten Flaggen treffen zu?]
- **Score**: [Nutzen: _ | Dringlichkeit: _ | Scope: _ | Komplexität: _ | Produktnähe: _ | Wiederverwendung: _ | **Gesamt: _/12**]
- **Decision**: [approve / shrink / merge / defer / reject]
```
---
## Erlaubt vs. Verdächtig (Schnellreferenz)
| Erlaubt | Verdächtig |
|---|---|
| Echte Workflow-Specs | Neue truth sub-axes |
| Governance-/Finding-/Review-Bearbeitbarkeit | Neue explanation frameworks |
| Trust-/Audit-/RBAC-Härtung | Neue presentation taxonomies |
| Portfolio-Operator-Durchsatzverbesserungen | Neue generalized support layers |
| Consolidation-Specs | Mikro-Specs für bereits stark zerlegte Domänen |

View File

@ -5,6 +5,24 @@ # Feature Specification: [FEATURE NAME]
**Status**: Draft **Status**: Draft
**Input**: User description: "$ARGUMENTS" **Input**: User description: "$ARGUMENTS"
## Spec Candidate Check *(mandatory — SPEC-GATE-001)*
<!-- This section MUST be completed before the spec progresses beyond Draft.
See .specify/memory/spec-approval-rubric.md for the full rubric. -->
- **Problem**: [Konkreter Operator-Schmerz oder Trust-Gap heute]
- **Today's failure**: [Welche Fehlentscheidung / Verlangsamung / irreführende Produktaussage passiert aktuell?]
- **User-visible improvement**: [Was wird konkret schneller, sicherer oder ehrlicher?]
- **Smallest enterprise-capable version**: [Kleinste Version die das Problem sauber löst]
- **Explicit non-goals**: [Was wird bewusst nicht modelliert/generalisiert/frameworkisiert?]
- **Permanent complexity imported**: [Neue Models, Status, Enums, Services, Support-Layer, Tests, UI-Konzepte, Begriffe]
- **Why now**: [Warum jetzt wichtiger als später?]
- **Why not local**: [Warum reicht keine lokale, schmale Lösung?]
- **Approval class**: [Core Enterprise / Workflow Compression / Cleanup / Defer]
- **Red flags triggered**: [Welche roten Flaggen treffen zu? Wenn ≥ 2: explizite Verteidigung nötig]
- **Score**: [Nutzen: _ | Dringlichkeit: _ | Scope: _ | Komplexität: _ | Produktnähe: _ | Wiederverwendung: _ | **Gesamt: _/12**]
- **Decision**: [approve / shrink / merge / defer / reject]
## Spec Scope Fields *(mandatory)* ## Spec Scope Fields *(mandatory)*
- **Scope**: [workspace | tenant | canonical-view] - **Scope**: [workspace | tenant | canonical-view]

View File

@ -318,12 +318,13 @@ ## Security
## Commands ## Commands
### Sail (preferred locally) ### Sail (preferred locally)
- `./vendor/bin/sail up -d` - `cd apps/platform && ./vendor/bin/sail up -d`
- `./vendor/bin/sail down` - `cd apps/platform && ./vendor/bin/sail down`
- `./vendor/bin/sail composer install` - `cd apps/platform && ./vendor/bin/sail composer install`
- `./vendor/bin/sail artisan migrate` - `cd apps/platform && ./vendor/bin/sail artisan migrate`
- `./vendor/bin/sail artisan test` - `cd apps/platform && ./vendor/bin/sail artisan test`
- `./vendor/bin/sail artisan` (general) - `cd apps/platform && ./vendor/bin/sail artisan` (general)
- Root helper for tooling only: `./scripts/platform-sail ...`
### Drizzle (local DB tooling, if configured) ### Drizzle (local DB tooling, if configured)
- Use only for local/dev workflows. - Use only for local/dev workflows.
@ -335,10 +336,10 @@ ### Drizzle (local DB tooling, if configured)
(Agents should confirm the exact script names in `package.json` before suggesting them.) (Agents should confirm the exact script names in `package.json` before suggesting them.)
### Non-Docker fallback (only if needed) ### Non-Docker fallback (only if needed)
- `composer install` - `cd apps/platform && composer install`
- `php artisan serve` - `cd apps/platform && php artisan serve`
- `php artisan migrate` - `cd apps/platform && php artisan migrate`
- `php artisan test` - `cd apps/platform && php artisan test`
### Frontend/assets/tooling (if present) ### Frontend/assets/tooling (if present)
- `pnpm install` - `pnpm install`
@ -352,11 +353,11 @@ ## Where to look first
- `.specify/` - `.specify/`
- `AGENTS.md` - `AGENTS.md`
- `README.md` - `README.md`
- `app/` - `apps/platform/app/`
- `database/` - `apps/platform/database/`
- `routes/` - `apps/platform/routes/`
- `resources/` - `apps/platform/resources/`
- `config/` - `apps/platform/config/`
--- ---
@ -433,7 +434,7 @@ ## 3) Panel setup defaults
- Assets policy: - Assets policy:
- Panel-only assets: register via panel config. - Panel-only assets: register via panel config.
- Shared/plugin assets: register via `FilamentAsset::register()`. - Shared/plugin assets: register via `FilamentAsset::register()`.
- Deployment must include `php artisan filament:assets`. - Deployment must include `cd apps/platform && php artisan filament:assets`.
Sources: Sources:
- https://filamentphp.com/docs/5.x/panel-configuration - https://filamentphp.com/docs/5.x/panel-configuration
@ -670,7 +671,7 @@ ## Testing
## Deployment / Ops ## Deployment / Ops
- [ ] `php artisan filament:assets` is included in the deployment process when using registered assets. - [ ] `cd apps/platform && php artisan filament:assets` is included in the deployment process when using registered assets.
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade” - Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade”
=== foundation rules === === foundation rules ===
@ -720,7 +721,9 @@ ## Application Structure & Architecture
## Frontend Bundling ## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `vendor/bin/sail npm run build`, `vendor/bin/sail npm run dev`, or `vendor/bin/sail composer run dev`. Ask them. - Repo-root JavaScript orchestration now uses `corepack pnpm install`, `corepack pnpm dev:platform`, `corepack pnpm dev:website`, `corepack pnpm dev`, `corepack pnpm build:website`, and `corepack pnpm build:platform`.
- `apps/website` is a standalone Astro app, not a second Laravel runtime, so Boost MCP remains platform-only.
- If the user doesn't see a platform frontend change reflected in the UI, it could mean they need to run `cd apps/platform && ./vendor/bin/sail pnpm build`, `cd apps/platform && ./vendor/bin/sail pnpm dev`, or `cd apps/platform && ./vendor/bin/sail composer run dev`. Ask them.
## Documentation Files ## Documentation Files
@ -812,28 +815,28 @@ ## PHPDoc Blocks
# Laravel Sail # Laravel Sail
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail. - This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
- Start services using `vendor/bin/sail up -d` and stop them with `vendor/bin/sail stop`. - Start services using `cd apps/platform && ./vendor/bin/sail up -d` and stop them with `cd apps/platform && ./vendor/bin/sail stop`.
- Open the application in the browser by running `vendor/bin/sail open`. - Open the application in the browser by running `cd apps/platform && ./vendor/bin/sail open`.
- Always prefix PHP, Artisan, Composer, and Node commands with `vendor/bin/sail`. Examples: - Always prefix PHP, Artisan, Composer, and Node commands with `cd apps/platform && ./vendor/bin/sail`. Examples:
- Run Artisan Commands: `vendor/bin/sail artisan migrate` - Run Artisan Commands: `cd apps/platform && ./vendor/bin/sail artisan migrate`
- Install Composer packages: `vendor/bin/sail composer install` - Install Composer packages: `cd apps/platform && ./vendor/bin/sail composer install`
- Execute Node commands: `vendor/bin/sail npm run dev` - Execute Node commands: `cd apps/platform && ./vendor/bin/sail pnpm dev`
- Execute PHP scripts: `vendor/bin/sail php [script]` - Execute PHP scripts: `cd apps/platform && ./vendor/bin/sail php [script]`
- View all available Sail commands by running `vendor/bin/sail` without arguments. - View all available Sail commands by running `cd apps/platform && ./vendor/bin/sail` without arguments.
=== tests rules === === tests rules ===
# Test Enforcement # Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. - Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `vendor/bin/sail artisan test --compact` with a specific filename or filter. - Run the minimum number of tests needed to ensure code quality and speed. Use `cd apps/platform && ./vendor/bin/sail artisan test --compact` with a specific filename or filter.
=== laravel/core rules === === laravel/core rules ===
# Do Things the Laravel Way # Do Things the Laravel Way
- Use `vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. - Use `cd apps/platform && ./vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `vendor/bin/sail artisan make:class`. - If you're creating a generic PHP class, use `cd apps/platform && ./vendor/bin/sail artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
## Database ## Database
@ -846,7 +849,7 @@ ## Database
### Model Creation ### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `vendor/bin/sail artisan make:model`. - When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `cd apps/platform && ./vendor/bin/sail artisan make:model`.
### APIs & Eloquent Resources ### APIs & Eloquent Resources
@ -877,11 +880,11 @@ ## Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`. - Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. - When creating tests, make use of `cd apps/platform && ./vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
## Vite Error ## Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `vendor/bin/sail npm run build` or ask the user to run `vendor/bin/sail npm run dev` or `vendor/bin/sail composer run dev`. - If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `cd apps/platform && ./vendor/bin/sail pnpm build` or ask the user to run `cd apps/platform && ./vendor/bin/sail pnpm dev` or `cd apps/platform && ./vendor/bin/sail composer run dev`.
=== laravel/v12 rules === === laravel/v12 rules ===
@ -912,15 +915,15 @@ ### Models
# Laravel Pint Code Formatter # Laravel Pint Code Formatter
- You must run `vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style. - You must run `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/sail bin pint --test --format agent`, simply run `vendor/bin/sail bin pint --format agent` to fix any formatting issues. - Do not run `cd apps/platform && ./vendor/bin/sail bin pint --test --format agent`, simply run `cd apps/platform && ./vendor/bin/sail bin pint --format agent` to fix any formatting issues.
=== pest/core rules === === pest/core rules ===
## Pest ## Pest
- This project uses Pest for testing. Create tests: `vendor/bin/sail artisan make:test --pest {name}`. - This project uses Pest for testing. Create tests: `cd apps/platform && ./vendor/bin/sail artisan make:test --pest {name}`.
- Run tests: `vendor/bin/sail artisan test --compact` or filter: `vendor/bin/sail artisan test --compact --filter=testName`. - Run tests: `cd apps/platform && ./vendor/bin/sail artisan test --compact` or filter: `cd apps/platform && ./vendor/bin/sail artisan test --compact --filter=testName`.
- Do NOT delete tests without approval. - Do NOT delete tests without approval.
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples. - CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples.
- IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task. - IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task.

View File

@ -156,12 +156,13 @@ ## Security
## Commands ## Commands
### Sail (preferred locally) ### Sail (preferred locally)
- `./vendor/bin/sail up -d` - `cd apps/platform && ./vendor/bin/sail up -d`
- `./vendor/bin/sail down` - `cd apps/platform && ./vendor/bin/sail down`
- `./vendor/bin/sail composer install` - `cd apps/platform && ./vendor/bin/sail composer install`
- `./vendor/bin/sail artisan migrate` - `cd apps/platform && ./vendor/bin/sail artisan migrate`
- `./vendor/bin/sail artisan test` - `cd apps/platform && ./vendor/bin/sail artisan test`
- `./vendor/bin/sail artisan` (general) - `cd apps/platform && ./vendor/bin/sail artisan` (general)
- Root helper for tooling only: `./scripts/platform-sail ...`
### Drizzle (local DB tooling, if configured) ### Drizzle (local DB tooling, if configured)
- Use only for local/dev workflows. - Use only for local/dev workflows.
@ -173,10 +174,10 @@ ### Drizzle (local DB tooling, if configured)
(Agents should confirm the exact script names in `package.json` before suggesting them.) (Agents should confirm the exact script names in `package.json` before suggesting them.)
### Non-Docker fallback (only if needed) ### Non-Docker fallback (only if needed)
- `composer install` - `cd apps/platform && composer install`
- `php artisan serve` - `cd apps/platform && php artisan serve`
- `php artisan migrate` - `cd apps/platform && php artisan migrate`
- `php artisan test` - `cd apps/platform && php artisan test`
### Frontend/assets/tooling (if present) ### Frontend/assets/tooling (if present)
- `pnpm install` - `pnpm install`
@ -190,11 +191,11 @@ ## Where to look first
- `.specify/` - `.specify/`
- `AGENTS.md` - `AGENTS.md`
- `README.md` - `README.md`
- `app/` - `apps/platform/app/`
- `database/` - `apps/platform/database/`
- `routes/` - `apps/platform/routes/`
- `resources/` - `apps/platform/resources/`
- `config/` - `apps/platform/config/`
--- ---
@ -271,7 +272,7 @@ ## 3) Panel setup defaults
- Assets policy: - Assets policy:
- Panel-only assets: register via panel config. - Panel-only assets: register via panel config.
- Shared/plugin assets: register via `FilamentAsset::register()`. - Shared/plugin assets: register via `FilamentAsset::register()`.
- Deployment must include `php artisan filament:assets`. - Deployment must include `cd apps/platform && php artisan filament:assets`.
Sources: Sources:
- https://filamentphp.com/docs/5.x/panel-configuration - https://filamentphp.com/docs/5.x/panel-configuration
@ -508,7 +509,7 @@ ## Testing
## Deployment / Ops ## Deployment / Ops
- [ ] `php artisan filament:assets` is included in the deployment process when using registered assets. - [ ] `cd apps/platform && php artisan filament:assets` is included in the deployment process when using registered assets.
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade” - Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade”
=== foundation rules === === foundation rules ===
@ -558,7 +559,9 @@ ## Application Structure & Architecture
## Frontend Bundling ## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `vendor/bin/sail npm run build`, `vendor/bin/sail npm run dev`, or `vendor/bin/sail composer run dev`. Ask them. - Repo-root JavaScript orchestration now uses `corepack pnpm install`, `corepack pnpm dev:platform`, `corepack pnpm dev:website`, `corepack pnpm dev`, `corepack pnpm build:website`, and `corepack pnpm build:platform`.
- `apps/website` is a standalone Astro app, not a second Laravel runtime, so Boost MCP remains platform-only.
- If the user doesn't see a platform frontend change reflected in the UI, it could mean they need to run `cd apps/platform && ./vendor/bin/sail pnpm build`, `cd apps/platform && ./vendor/bin/sail pnpm dev`, or `cd apps/platform && ./vendor/bin/sail composer run dev`. Ask them.
## Documentation Files ## Documentation Files
@ -650,28 +653,28 @@ ## PHPDoc Blocks
# Laravel Sail # Laravel Sail
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail. - This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
- Start services using `vendor/bin/sail up -d` and stop them with `vendor/bin/sail stop`. - Start services using `cd apps/platform && ./vendor/bin/sail up -d` and stop them with `cd apps/platform && ./vendor/bin/sail stop`.
- Open the application in the browser by running `vendor/bin/sail open`. - Open the application in the browser by running `cd apps/platform && ./vendor/bin/sail open`.
- Always prefix PHP, Artisan, Composer, and Node commands with `vendor/bin/sail`. Examples: - Always prefix PHP, Artisan, Composer, and Node commands with `cd apps/platform && ./vendor/bin/sail`. Examples:
- Run Artisan Commands: `vendor/bin/sail artisan migrate` - Run Artisan Commands: `cd apps/platform && ./vendor/bin/sail artisan migrate`
- Install Composer packages: `vendor/bin/sail composer install` - Install Composer packages: `cd apps/platform && ./vendor/bin/sail composer install`
- Execute Node commands: `vendor/bin/sail npm run dev` - Execute Node commands: `cd apps/platform && ./vendor/bin/sail pnpm dev`
- Execute PHP scripts: `vendor/bin/sail php [script]` - Execute PHP scripts: `cd apps/platform && ./vendor/bin/sail php [script]`
- View all available Sail commands by running `vendor/bin/sail` without arguments. - View all available Sail commands by running `cd apps/platform && ./vendor/bin/sail` without arguments.
=== tests rules === === tests rules ===
# Test Enforcement # Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass. - Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `vendor/bin/sail artisan test --compact` with a specific filename or filter. - Run the minimum number of tests needed to ensure code quality and speed. Use `cd apps/platform && ./vendor/bin/sail artisan test --compact` with a specific filename or filter.
=== laravel/core rules === === laravel/core rules ===
# Do Things the Laravel Way # Do Things the Laravel Way
- Use `vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. - Use `cd apps/platform && ./vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `vendor/bin/sail artisan make:class`. - If you're creating a generic PHP class, use `cd apps/platform && ./vendor/bin/sail artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
## Database ## Database
@ -684,7 +687,7 @@ ## Database
### Model Creation ### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `vendor/bin/sail artisan make:model`. - When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `cd apps/platform && ./vendor/bin/sail artisan make:model`.
### APIs & Eloquent Resources ### APIs & Eloquent Resources
@ -715,11 +718,11 @@ ## Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`. - Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. - When creating tests, make use of `cd apps/platform && ./vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
## Vite Error ## Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `vendor/bin/sail npm run build` or ask the user to run `vendor/bin/sail npm run dev` or `vendor/bin/sail composer run dev`. - If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `cd apps/platform && ./vendor/bin/sail pnpm build` or ask the user to run `cd apps/platform && ./vendor/bin/sail pnpm dev` or `cd apps/platform && ./vendor/bin/sail composer run dev`.
=== laravel/v12 rules === === laravel/v12 rules ===
@ -750,15 +753,15 @@ ### Models
# Laravel Pint Code Formatter # Laravel Pint Code Formatter
- You must run `vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style. - You must run `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/sail bin pint --test --format agent`, simply run `vendor/bin/sail bin pint --format agent` to fix any formatting issues. - Do not run `cd apps/platform && ./vendor/bin/sail bin pint --test --format agent`, simply run `cd apps/platform && ./vendor/bin/sail bin pint --format agent` to fix any formatting issues.
=== pest/core rules === === pest/core rules ===
## Pest ## Pest
- This project uses Pest for testing. Create tests: `vendor/bin/sail artisan make:test --pest {name}`. - This project uses Pest for testing. Create tests: `cd apps/platform && ./vendor/bin/sail artisan make:test --pest {name}`.
- Run tests: `vendor/bin/sail artisan test --compact` or filter: `vendor/bin/sail artisan test --compact --filter=testName`. - Run tests: `cd apps/platform && ./vendor/bin/sail artisan test --compact` or filter: `cd apps/platform && ./vendor/bin/sail artisan test --compact --filter=testName`.
- Do NOT delete tests without approval. - Do NOT delete tests without approval.
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples. - CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples.
- IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task. - IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task.

134
README.md
View File

@ -1,19 +1,50 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p> # TenantPilot Workspace
<p align="center"> TenantPilot is an Intune management platform built around a stable Laravel application in
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a> `apps/platform` and, starting with Spec 183, a standalone public Astro website in
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a> `apps/website`. The repository root is now the official JavaScript workspace entry point and
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a> orchestrates app-local commands without becoming a runtime itself.
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## TenantPilot setup ## Multi-App Topology
- `apps/platform`: the Laravel 12 + Filament v5 + Livewire v4 product runtime
- `apps/website`: the Astro v6 public website runtime
- repo root: workspace manifests, documentation, scripts, editor tooling, and `docker-compose.yml`
- `./scripts/platform-sail`: platform-only compatibility helper for tooling that cannot set `cwd`
## Official Root Commands
- Install workspace-managed JavaScript dependencies: `corepack pnpm install`
- Start the platform stack: `corepack pnpm dev:platform`
- Start the website dev server: `corepack pnpm dev:website`
- Start platform + website together: `corepack pnpm dev`
- Build the website: `corepack pnpm build:website`
- Build platform frontend assets: `corepack pnpm build:platform`
## App-Local Commands
### Platform
- Install PHP dependencies: `cd apps/platform && composer install`
- Start Sail: `cd apps/platform && ./vendor/bin/sail up -d`
- Generate the app key: `cd apps/platform && ./vendor/bin/sail artisan key:generate`
- Run migrations and seeders: `cd apps/platform && ./vendor/bin/sail artisan migrate --seed`
- Run frontend watch/build inside Sail: `cd apps/platform && ./vendor/bin/sail pnpm dev` or `cd apps/platform && ./vendor/bin/sail pnpm build`
- Run tests: `cd apps/platform && ./vendor/bin/sail artisan test --compact`
### Website
- Start the dev server: `cd apps/website && pnpm dev`
- Build the static site: `cd apps/website && pnpm build`
## Port Overrides
- Platform HTTP and Vite ports: set `APP_PORT` and or `VITE_PORT` before `corepack pnpm dev:platform` or `cd apps/platform && ./vendor/bin/sail up -d`
- Website dev server port: set `WEBSITE_PORT` before `corepack pnpm dev:website` or pass `--port <port>` to `cd apps/website && pnpm dev`
- Parallel local development keeps both apps isolated, even when one or both ports are overridden
## Platform Setup Notes
- Local dev (Sail-first):
- Start stack: `./vendor/bin/sail up -d`
- Init DB: `./vendor/bin/sail artisan migrate --seed`
- Tests: `./vendor/bin/sail artisan test`
- Policy sync: `./vendor/bin/sail artisan intune:sync-policies`
- Filament admin: `/admin` (seed user `test@example.com`, set password via factory or `artisan tinker`). - Filament admin: `/admin` (seed user `test@example.com`, set password via factory or `artisan tinker`).
- Microsoft Graph (Intune) env vars: - Microsoft Graph (Intune) env vars:
- `GRAPH_TENANT_ID` - `GRAPH_TENANT_ID`
@ -25,10 +56,17 @@ ## TenantPilot setup
- **Missing permissions?** Scope tags will show as "Unknown (ID: X)" - add `DeviceManagementRBAC.Read.All` - **Missing permissions?** Scope tags will show as "Unknown (ID: X)" - add `DeviceManagementRBAC.Read.All`
- Deployment (Dokploy, staging → production): - Deployment (Dokploy, staging → production):
- Containerized deploy; ensure Postgres + Redis are provisioned (see `docker-compose.yml` for local baseline). - Containerized deploy; ensure Postgres + Redis are provisioned (see `docker-compose.yml` for local baseline).
- Run application commands from `apps/platform`, including `php artisan filament:assets`.
- Run migrations on staging first, validate backup/restore flows, then promote to production. - Run migrations on staging first, validate backup/restore flows, then promote to production.
- Ensure queue workers are running for jobs (e.g., policy sync) after deploy. - Ensure queue workers are running for jobs (e.g., policy sync) after deploy.
- Keep secrets/env in Dokploy, never in code. - Keep secrets/env in Dokploy, never in code.
## Platform relocation rollout notes
- Open branches that still touch legacy root app paths should merge `dev` first, then remap file moves from `app/`, `bootstrap/`, `config/`, `database/`, `lang/`, `public/`, `resources/`, `routes/`, `storage/`, and `tests/` into `apps/platform/...`.
- Keep using merge-based catch-up on shared feature branches; do not rebase long-lived shared branches just to absorb the relocation.
- VS Code tasks expose the official root workspace commands, while MCP launchers remain platform-only and delegate through `./scripts/platform-sail`.
## Bulk operations (Feature 005) ## Bulk operations (Feature 005)
- Bulk actions are available in Filament resource tables (Policies, Policy Versions, Backup Sets, Restore Runs). - Bulk actions are available in Filament resource tables (Policies, Policy Versions, Backup Sets, Restore Runs).
@ -39,8 +77,23 @@ ### Troubleshooting
- **Progress stuck on “Queued…”** usually means the queue worker is not running (or not processing the queue you expect). - **Progress stuck on “Queued…”** usually means the queue worker is not running (or not processing the queue you expect).
- Prefer using the Sail/Docker worker (see `docker-compose.yml`) rather than starting an additional local `php artisan queue:work`. - Prefer using the Sail/Docker worker (see `docker-compose.yml`) rather than starting an additional local `php artisan queue:work`.
- Check worker status/logs: `./vendor/bin/sail ps` and `./vendor/bin/sail logs -f queue`. - Check worker status/logs: `cd apps/platform && ./vendor/bin/sail ps` and `cd apps/platform && ./vendor/bin/sail logs -f queue`.
- **Exit code 137** for `queue:work` typically means the process was killed (often OOM). Increase Docker memory/limits or run the worker inside the container. - **Exit code 137** for `queue:work` typically means the process was killed (often OOM). Increase Docker memory/limits or run the worker inside the container.
- **Moved app but old commands still fail** usually means the command is still being run from repo root. Switch to `cd apps/platform && ...` or use `./scripts/platform-sail ...` only for tooling that cannot set `cwd`.
## Rollback checklist
1. Revert the relocation commit or merge on your feature branch instead of hard-resetting shared history.
2. Preserve any local app env overrides before switching commits: `cp apps/platform/.env /tmp/tenantatlas.platform.env.backup` if needed.
3. Stop local containers and clean generated artifacts: `cd apps/platform && ./vendor/bin/sail down -v`, then remove `apps/platform/vendor`, `apps/platform/node_modules`, `apps/platform/public/build`, and `apps/platform/public/hot` if they need a clean rebuild.
4. After rollback, restore the matching env file for the restored topology and rerun the documented setup flow for that commit.
5. Notify owners of open feature branches that the topology changed so they can remap outstanding work before the next merge from `dev`.
## Deployment unknowns
- Dokploy build context for a repo-root compose file plus an app-root Laravel runtime still needs staging confirmation.
- Production web, queue, and scheduler working directories must be verified explicitly after the move; do not assume repo root and app root behave interchangeably.
- Any Dokploy volume mounts or storage persistence paths that previously targeted repo-root `storage/` must be reviewed against `apps/platform/storage/`.
### Configuration ### Configuration
@ -64,7 +117,7 @@ ## Graph Contract Registry & Drift Guard
- Sanitizes `$select`/`$expand` to allowed fields; logs warnings on trim. - Sanitizes `$select`/`$expand` to allowed fields; logs warnings on trim.
- Derived @odata.type values within the family are accepted for preview/restore routing. - Derived @odata.type values within the family are accepted for preview/restore routing.
- Capability fallback: on 400s related to select/expand, retries without those clauses and surfaces warnings. - Capability fallback: on 400s related to select/expand, retries without those clauses and surfaces warnings.
- Drift check: `php artisan graph:contract:check [--tenant=]` runs lightweight probes against contract endpoints to detect capability/shape issues; useful in staging/CI (prod optional). - Drift check: `cd apps/platform && php artisan graph:contract:check [--tenant=]` runs lightweight probes against contract endpoints to detect capability/shape issues; useful in staging/CI (prod optional).
- If Graph returns capability errors, TenantPilot downgrades safely, records warnings/audit entries, and avoids breaking preview/restore flows. - If Graph returns capability errors, TenantPilot downgrades safely, records warnings/audit entries, and avoids breaking preview/restore flows.
## Policy Settings Display ## Policy Settings Display
@ -89,54 +142,3 @@ ## Policy JSON Viewer (Feature 002)
- Scrollable container with max height to prevent page overflow - Scrollable container with max height to prevent page overflow
- **Usage**: See `specs/002-filament-json/quickstart.md` for detailed examples and configuration - **Usage**: See `specs/002-filament-json/quickstart.md` for detailed examples and configuration
- **Performance**: Optimized for payloads up to 1 MB; auto-collapse improves initial render for large snapshots - **Performance**: Optimized for payloads up to 1 MB; auto-collapse improves initial render for large snapshots
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

View File

@ -1,17 +0,0 @@
<?php
namespace App\Filament\Resources\RestoreRunResource\Pages;
use App\Filament\Resources\RestoreRunResource;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Database\Eloquent\Model;
class ViewRestoreRun extends ViewRecord
{
protected static string $resource = RestoreRunResource::class;
protected function resolveRecord(int|string $key): Model
{
return RestoreRunResource::resolveScopedRecordOrFail($key);
}
}

View File

@ -1,66 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\TenantResource\Pages;
use App\Filament\Resources\TenantResource;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Onboarding\OnboardingDraftResolver;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListTenants extends ListRecords
{
protected static string $resource = TenantResource::class;
protected function getHeaderActions(): array
{
return [
$this->makeOnboardingEntryAction()
->visible(fn (): bool => $this->getTableRecords()->count() > 0),
];
}
protected function getTableEmptyStateActions(): array
{
return [
$this->makeOnboardingEntryAction(),
];
}
private function makeOnboardingEntryAction(): Actions\Action
{
$descriptor = TenantResource::tenantActionPolicy()->onboardingEntryDescriptor($this->accessibleResumableDraftCount());
return Actions\Action::make('add_tenant')
->label($descriptor->label)
->icon($descriptor->icon)
->url(route('admin.onboarding'));
}
private function accessibleResumableDraftCount(): int
{
$user = auth()->user();
if (! $user instanceof User) {
return 0;
}
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
if (! is_int($workspaceId)) {
return 0;
}
$workspace = Workspace::query()->whereKey($workspaceId)->first();
if (! $workspace instanceof Workspace) {
return 0;
}
return app(OnboardingDraftResolver::class)->resumableDraftsFor($user, $workspace)->count();
}
}

View File

@ -1,254 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Widgets\Dashboard;
use App\Filament\Pages\BaselineCompareLanding;
use App\Filament\Resources\FindingResource;
use App\Models\FindingException;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Support\Auth\Capabilities;
use App\Support\Baselines\TenantGovernanceAggregate;
use App\Support\Baselines\TenantGovernanceAggregateResolver;
use App\Support\OperationRunLinks;
use App\Support\OpsUx\ActiveRuns;
use App\Support\Rbac\UiTooltips;
use Filament\Facades\Filament;
use Filament\Widgets\Widget;
class NeedsAttention extends Widget
{
protected string $view = 'filament.widgets.dashboard.needs-attention';
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
$tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) {
return [
'pollingInterval' => null,
'items' => [],
'healthyChecks' => [],
];
}
$tenantId = (int) $tenant->getKey();
$aggregate = $this->governanceAggregate($tenant);
$compareAssessment = $aggregate->summaryAssessment;
$items = [];
$overdueOpenCount = $aggregate->overdueOpenFindingsCount;
$lapsedGovernanceCount = $aggregate->lapsedGovernanceCount;
$expiringGovernanceCount = $aggregate->expiringGovernanceCount;
$highSeverityCount = $aggregate->highSeverityActiveFindingsCount;
$staleActiveOperationsCount = (int) OperationRun::query()
->where('tenant_id', $tenantId)
->activeStaleAttention()
->count();
$terminalFollowUpOperationsCount = (int) OperationRun::query()
->where('tenant_id', $tenantId)
->terminalFollowUp()
->count();
$activeRuns = (int) OperationRun::query()
->where('tenant_id', $tenantId)
->healthyActive()
->count();
if ($lapsedGovernanceCount > 0) {
$items[] = [
'key' => 'lapsed_governance',
'title' => 'Lapsed accepted-risk governance',
'body' => "{$lapsedGovernanceCount} accepted-risk finding(s) no longer have valid supporting governance.",
'badge' => 'Governance',
'badgeColor' => 'danger',
...$this->findingsAction(
$tenant,
'Open findings',
[
'tab' => 'risk_accepted',
'governance_validity' => FindingException::VALIDITY_MISSING_SUPPORT,
],
),
];
}
if ($overdueOpenCount > 0) {
$items[] = [
'key' => 'overdue_findings',
'title' => 'Overdue findings',
'body' => "{$overdueOpenCount} open finding(s) are overdue and still need workflow follow-up.",
'badge' => 'Findings',
'badgeColor' => 'danger',
...$this->findingsAction(
$tenant,
'Open findings',
['tab' => 'overdue'],
),
];
}
if ($expiringGovernanceCount > 0) {
$items[] = [
'key' => 'expiring_governance',
'title' => 'Expiring accepted-risk governance',
'body' => "{$expiringGovernanceCount} accepted-risk finding(s) need governance review soon.",
'badge' => 'Governance',
'badgeColor' => 'warning',
...$this->findingsAction(
$tenant,
'Open findings',
[
'tab' => 'risk_accepted',
'governance_validity' => FindingException::VALIDITY_EXPIRING,
],
),
];
}
if ($highSeverityCount > 0) {
$items[] = [
'key' => 'high_severity_active_findings',
'title' => 'High severity active findings',
'body' => "{$highSeverityCount} high or critical finding(s) are still active.",
'badge' => 'Findings',
'badgeColor' => 'danger',
...$this->findingsAction(
$tenant,
'Open findings',
[
'tab' => 'needs_action',
'high_severity' => 1,
],
),
];
}
if ($compareAssessment->stateFamily !== 'positive') {
$items[] = [
'key' => 'baseline_compare_posture',
'title' => 'Baseline compare posture',
'body' => $compareAssessment->headline,
'supportingMessage' => $compareAssessment->supportingMessage,
'badge' => 'Baseline',
'badgeColor' => $compareAssessment->tone,
'actionLabel' => 'Open Baseline Compare',
'actionUrl' => BaselineCompareLanding::getUrl(panel: 'tenant', tenant: $tenant),
];
}
if ($staleActiveOperationsCount > 0) {
$items[] = [
'key' => 'operations_stale_attention',
'title' => 'Active operations look stale',
'body' => "{$staleActiveOperationsCount} run(s) are still marked active but are past the lifecycle window.",
'badge' => 'Operations',
'badgeColor' => 'warning',
'actionLabel' => 'Open stale operations',
'actionUrl' => OperationRunLinks::index(
$tenant,
activeTab: OperationRun::PROBLEM_CLASS_ACTIVE_STALE_ATTENTION,
problemClass: OperationRun::PROBLEM_CLASS_ACTIVE_STALE_ATTENTION,
),
];
}
if ($terminalFollowUpOperationsCount > 0) {
$items[] = [
'key' => 'operations_terminal_follow_up',
'title' => 'Terminal operations need follow-up',
'body' => "{$terminalFollowUpOperationsCount} run(s) finished blocked, partially, failed, or were automatically reconciled.",
'badge' => 'Operations',
'badgeColor' => 'danger',
'actionLabel' => 'Open terminal follow-up',
'actionUrl' => OperationRunLinks::index(
$tenant,
activeTab: OperationRun::PROBLEM_CLASS_TERMINAL_FOLLOW_UP,
problemClass: OperationRun::PROBLEM_CLASS_TERMINAL_FOLLOW_UP,
),
];
}
$healthyChecks = [];
if ($items === []) {
$healthyChecks = [
[
'title' => 'Baseline compare looks trustworthy',
'body' => $aggregate->headline,
],
[
'title' => 'No overdue findings',
'body' => 'No open findings are currently overdue for this tenant.',
],
[
'title' => 'Accepted-risk governance is healthy',
'body' => 'No accepted-risk findings currently need governance follow-up.',
],
[
'title' => 'No high severity active findings',
'body' => 'No high severity findings are currently open for this tenant.',
],
$activeRuns > 0
? [
'title' => 'Operations are active',
'body' => "{$activeRuns} run(s) are active, but nothing currently needs follow-up.",
]
: [
'title' => 'No active operations',
'body' => 'Nothing is currently running for this tenant.',
],
];
}
return [
'pollingInterval' => ActiveRuns::pollingIntervalForTenant($tenant),
'items' => $items,
'healthyChecks' => $healthyChecks,
];
}
/**
* @param array<string, mixed> $parameters
* @return array<string, mixed>
*/
private function findingsAction(Tenant $tenant, string $label, array $parameters): array
{
$url = $this->canOpenFindings($tenant)
? FindingResource::getUrl('index', $parameters, panel: 'tenant', tenant: $tenant)
: null;
return [
'actionLabel' => $label,
'actionUrl' => $url,
'actionDisabled' => $url === null,
'helperText' => $url === null ? UiTooltips::INSUFFICIENT_PERMISSION : null,
];
}
private function canOpenFindings(Tenant $tenant): bool
{
$user = auth()->user();
return $user instanceof User
&& $user->canAccessTenant($tenant)
&& $user->can(Capabilities::TENANT_FINDINGS_VIEW, $tenant);
}
private function governanceAggregate(Tenant $tenant): TenantGovernanceAggregate
{
/** @var TenantGovernanceAggregateResolver $resolver */
$resolver = app(TenantGovernanceAggregateResolver::class);
/** @var TenantGovernanceAggregate $aggregate */
$aggregate = $resolver->forTenant($tenant);
return $aggregate;
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace App\Support\Badges\Domains;
use App\Support\Badges\BadgeCatalog;
use App\Support\Badges\BadgeMapper;
use App\Support\Badges\BadgeSpec;
final class ProviderConnectionHealthBadge implements BadgeMapper
{
public function spec(mixed $value): BadgeSpec
{
$state = BadgeCatalog::normalizeProviderConnectionHealth($value);
return match ($state) {
'ok' => new BadgeSpec('OK', 'success', 'heroicon-m-check-circle'),
'degraded' => new BadgeSpec('Degraded', 'warning', 'heroicon-m-exclamation-triangle'),
'down' => new BadgeSpec('Down', 'danger', 'heroicon-m-x-circle'),
'unknown' => new BadgeSpec('Unknown', 'gray', 'heroicon-m-question-mark-circle'),
default => BadgeSpec::unknown(),
};
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace App\Support\Badges\Domains;
use App\Support\Badges\BadgeCatalog;
use App\Support\Badges\BadgeMapper;
use App\Support\Badges\BadgeSpec;
final class ProviderConnectionStatusBadge implements BadgeMapper
{
public function spec(mixed $value): BadgeSpec
{
$state = BadgeCatalog::normalizeProviderConnectionStatus($value);
return match ($state) {
'connected' => new BadgeSpec('Connected', 'success', 'heroicon-m-check-circle'),
'needs_consent' => new BadgeSpec('Needs consent', 'warning', 'heroicon-m-exclamation-triangle'),
'error' => new BadgeSpec('Error', 'danger', 'heroicon-m-x-circle'),
'disabled' => new BadgeSpec('Disabled', 'gray', 'heroicon-m-minus-circle'),
default => BadgeSpec::unknown(),
};
}
}

View File

@ -3,6 +3,8 @@ APP_ENV=local
APP_KEY= APP_KEY=
APP_DEBUG=true APP_DEBUG=true
APP_URL=http://localhost APP_URL=http://localhost
SAIL_FILES=../../docker-compose.yml
TENANTATLAS_REPO_ROOT=../..
APP_LOCALE=en APP_LOCALE=en
APP_FALLBACK_LOCALE=en APP_FALLBACK_LOCALE=en
@ -21,11 +23,12 @@ LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug LOG_LEVEL=debug
DB_CONNECTION=pgsql DB_CONNECTION=pgsql
DB_HOST=127.0.0.1 DB_HOST=pgsql
DB_PORT=5432 DB_PORT=5432
FORWARD_DB_PORT=55432
DB_DATABASE=tenantatlas DB_DATABASE=tenantatlas
DB_USERNAME=root DB_USERNAME=root
DB_PASSWORD= DB_PASSWORD=postgres
SESSION_DRIVER=database SESSION_DRIVER=database
SESSION_LIFETIME=120 SESSION_LIFETIME=120
@ -43,7 +46,7 @@ CACHE_STORE=database
MEMCACHED_HOST=127.0.0.1 MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1 REDIS_HOST=redis
REDIS_PASSWORD=null REDIS_PASSWORD=null
REDIS_PORT=6379 REDIS_PORT=6379

View File

@ -10,7 +10,6 @@
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
use App\Services\Providers\ProviderConnectionClassificationResult; use App\Services\Providers\ProviderConnectionClassificationResult;
use App\Services\Providers\ProviderConnectionClassifier; use App\Services\Providers\ProviderConnectionClassifier;
use App\Services\Providers\ProviderConnectionStateProjector;
use App\Support\Providers\ProviderConnectionType; use App\Support\Providers\ProviderConnectionType;
use App\Support\Providers\ProviderCredentialKind; use App\Support\Providers\ProviderCredentialKind;
use App\Support\Providers\ProviderCredentialSource; use App\Support\Providers\ProviderCredentialSource;
@ -29,10 +28,8 @@ class ClassifyProviderConnections extends Command
protected $description = 'Classify legacy provider connections into platform, dedicated, or review-required outcomes.'; protected $description = 'Classify legacy provider connections into platform, dedicated, or review-required outcomes.';
public function handle( public function handle(ProviderConnectionClassifier $classifier): int
ProviderConnectionClassifier $classifier, {
ProviderConnectionStateProjector $stateProjector,
): int {
$query = $this->query(); $query = $this->query();
$write = (bool) $this->option('write'); $write = (bool) $this->option('write');
$chunkSize = max(1, (int) $this->option('chunk')); $chunkSize = max(1, (int) $this->option('chunk'));
@ -62,7 +59,6 @@ public function handle(
->orderBy('id') ->orderBy('id')
->chunkById($chunkSize, function ($connections) use ( ->chunkById($chunkSize, function ($connections) use (
$classifier, $classifier,
$stateProjector,
$write, $write,
$tenantCounts, $tenantCounts,
&$startedTenants, &$startedTenants,
@ -101,7 +97,7 @@ public function handle(
$startedTenants[$tenantKey] = true; $startedTenants[$tenantKey] = true;
} }
$connection = $this->applyClassification($connection, $result, $stateProjector); $connection = $this->applyClassification($connection, $result);
$this->auditApplied($tenant, $connection, $result); $this->auditApplied($tenant, $connection, $result);
$appliedCount++; $appliedCount++;
} }
@ -146,11 +142,10 @@ private function query(): Builder
private function applyClassification( private function applyClassification(
ProviderConnection $connection, ProviderConnection $connection,
ProviderConnectionClassificationResult $result, ProviderConnectionClassificationResult $result,
ProviderConnectionStateProjector $stateProjector,
): ProviderConnection { ): ProviderConnection {
DB::transaction(function () use ($connection, $result, $stateProjector): void { DB::transaction(function () use ($connection, $result): void {
$connection->forceFill( $connection->forceFill(
$connection->classificationProjection($result, $stateProjector) $connection->classificationProjection($result)
)->save(); )->save();
$credential = $connection->credential; $credential = $connection->credential;

View File

@ -0,0 +1,190 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\Tenant;
use App\Models\TenantMembership;
use App\Models\User;
use App\Models\UserTenantPreference;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
class SeedBackupHealthBrowserFixture extends Command
{
protected $signature = 'tenantpilot:backup-health:seed-browser-fixture {--force-refresh : Rebuild the fixture backup basis even if it already exists}';
protected $description = 'Seed a local/testing browser fixture for the Spec 180 blocked backup drill-through scenario.';
public function handle(): int
{
if (! app()->environment(['local', 'testing'])) {
$this->error('This fixture command is limited to local and testing environments.');
return self::FAILURE;
}
$fixture = config('tenantpilot.backup_health.browser_smoke_fixture');
if (! is_array($fixture)) {
$this->error('The backup-health browser smoke fixture is not configured.');
return self::FAILURE;
}
$workspaceConfig = is_array($fixture['workspace'] ?? null) ? $fixture['workspace'] : [];
$userConfig = is_array($fixture['user'] ?? null) ? $fixture['user'] : [];
$scenarioConfig = is_array($fixture['blocked_drillthrough'] ?? null) ? $fixture['blocked_drillthrough'] : [];
$tenantRouteKey = (string) ($scenarioConfig['tenant_id'] ?? $scenarioConfig['tenant_external_id'] ?? '18000000-0000-4000-8000-000000000180');
$workspace = Workspace::query()->updateOrCreate(
['slug' => (string) ($workspaceConfig['slug'] ?? 'spec-180-backup-health-smoke')],
['name' => (string) ($workspaceConfig['name'] ?? 'Spec 180 Backup Health Smoke')],
);
$password = (string) ($userConfig['password'] ?? 'password');
$user = User::query()->updateOrCreate(
['email' => (string) ($userConfig['email'] ?? 'smoke-requester+180@tenantpilot.local')],
[
'name' => (string) ($userConfig['name'] ?? 'Spec 180 Requester'),
'password' => Hash::make($password),
'email_verified_at' => now(),
],
);
$tenant = Tenant::query()->updateOrCreate(
['external_id' => $tenantRouteKey],
[
'workspace_id' => (int) $workspace->getKey(),
'name' => (string) ($scenarioConfig['tenant_name'] ?? 'Spec 180 Blocked Backup Tenant'),
'tenant_id' => $tenantRouteKey,
'app_certificate_thumbprint' => null,
'app_status' => 'ok',
'app_notes' => null,
'status' => Tenant::STATUS_ACTIVE,
'environment' => 'dev',
'is_current' => false,
'metadata' => ['fixture' => 'spec-180-browser-smoke'],
'rbac_status' => 'ok',
'rbac_last_checked_at' => now(),
],
);
WorkspaceMembership::query()->updateOrCreate(
['workspace_id' => (int) $workspace->getKey(), 'user_id' => (int) $user->getKey()],
['role' => 'owner'],
);
TenantMembership::query()->updateOrCreate(
['tenant_id' => (int) $tenant->getKey(), 'user_id' => (int) $user->getKey()],
['role' => 'owner', 'source' => 'manual', 'source_ref' => 'spec-180-browser-smoke'],
);
if (Schema::hasColumn('users', 'last_workspace_id')) {
$user->forceFill(['last_workspace_id' => (int) $workspace->getKey()])->save();
}
if (Schema::hasTable('user_tenant_preferences')) {
UserTenantPreference::query()->updateOrCreate(
['user_id' => (int) $user->getKey(), 'tenant_id' => (int) $tenant->getKey()],
['last_used_at' => now()],
);
}
$policy = Policy::query()->updateOrCreate(
[
'tenant_id' => (int) $tenant->getKey(),
'external_id' => (string) ($scenarioConfig['policy_external_id'] ?? 'spec-180-rbac-stale-policy'),
'policy_type' => (string) ($scenarioConfig['policy_type'] ?? 'settingsCatalogPolicy'),
],
[
'display_name' => (string) ($scenarioConfig['policy_name'] ?? 'Spec 180 RBAC Smoke Policy'),
'platform' => 'windows',
'last_synced_at' => now(),
'metadata' => ['fixture' => 'spec-180-browser-smoke'],
],
);
$backupSet = BackupSet::withTrashed()->firstOrNew([
'tenant_id' => (int) $tenant->getKey(),
'name' => (string) ($scenarioConfig['backup_set_name'] ?? 'Spec 180 Blocked Stale Backup'),
]);
$backupSet->forceFill([
'created_by' => (string) $user->email,
'status' => 'completed',
'item_count' => 1,
'completed_at' => now()->subHours(max(25, (int) ($scenarioConfig['stale_age_hours'] ?? 48))),
'metadata' => ['fixture' => 'spec-180-browser-smoke'],
'deleted_at' => null,
])->save();
if (method_exists($backupSet, 'trashed') && $backupSet->trashed()) {
$backupSet->restore();
}
$backupItem = BackupItem::withTrashed()->firstOrNew([
'backup_set_id' => (int) $backupSet->getKey(),
'policy_identifier' => (string) ($scenarioConfig['policy_external_id'] ?? 'spec-180-rbac-stale-policy'),
'policy_type' => (string) ($scenarioConfig['policy_type'] ?? 'settingsCatalogPolicy'),
]);
$backupItem->forceFill([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'platform' => 'windows',
'captured_at' => $backupSet->completed_at,
'payload' => [
'id' => (string) ($scenarioConfig['policy_external_id'] ?? 'spec-180-rbac-stale-policy'),
'name' => (string) ($scenarioConfig['policy_name'] ?? 'Spec 180 RBAC Smoke Policy'),
],
'metadata' => [
'policy_name' => (string) ($scenarioConfig['policy_name'] ?? 'Spec 180 RBAC Smoke Policy'),
'fixture' => 'spec-180-browser-smoke',
],
'assignments' => [],
'deleted_at' => null,
])->save();
if (method_exists($backupItem, 'trashed') && $backupItem->trashed()) {
$backupItem->restore();
}
if ((bool) $this->option('force-refresh')) {
$backupSet->forceFill([
'completed_at' => now()->subHours(max(25, (int) ($scenarioConfig['stale_age_hours'] ?? 48))),
])->save();
$backupItem->forceFill([
'captured_at' => $backupSet->completed_at,
])->save();
}
$this->table(
['Fixture', 'Value'],
[
['Workspace', (string) $workspace->name],
['User email', (string) $user->email],
['User password', $password],
['Tenant', (string) $tenant->name],
['Tenant external id', (string) $tenant->external_id],
['Dashboard URL', "/admin/t/{$tenant->external_id}"],
['Fixture login URL', route('admin.local.backup-health-browser-fixture-login', absolute: false)],
['Blocked route', "/admin/t/{$tenant->external_id}/backup-sets"],
['Locally denied capability', 'tenant.view'],
],
);
$this->info('The dashboard remains visible for this fixture user, while backup drill-through routes stay forbidden via a local/testing-only capability deny seam.');
return self::SUCCESS;
}
}

View File

@ -4,11 +4,13 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use App\Filament\Widgets\Tenant\TenantTriageArrivalContinuity;
use App\Filament\Widgets\Dashboard\BaselineCompareNow; use App\Filament\Widgets\Dashboard\BaselineCompareNow;
use App\Filament\Widgets\Dashboard\DashboardKpis; use App\Filament\Widgets\Dashboard\DashboardKpis;
use App\Filament\Widgets\Dashboard\NeedsAttention; use App\Filament\Widgets\Dashboard\NeedsAttention;
use App\Filament\Widgets\Dashboard\RecentDriftFindings; use App\Filament\Widgets\Dashboard\RecentDriftFindings;
use App\Filament\Widgets\Dashboard\RecentOperations; use App\Filament\Widgets\Dashboard\RecentOperations;
use App\Filament\Widgets\Dashboard\RecoveryReadiness;
use Filament\Pages\Dashboard; use Filament\Pages\Dashboard;
use Filament\Widgets\Widget; use Filament\Widgets\Widget;
use Filament\Widgets\WidgetConfiguration; use Filament\Widgets\WidgetConfiguration;
@ -30,6 +32,8 @@ public static function getUrl(array $parameters = [], bool $isAbsolute = true, ?
public function getWidgets(): array public function getWidgets(): array
{ {
return [ return [
TenantTriageArrivalContinuity::class,
RecoveryReadiness::class,
DashboardKpis::class, DashboardKpis::class,
NeedsAttention::class, NeedsAttention::class,
BaselineCompareNow::class, BaselineCompareNow::class,

View File

@ -30,7 +30,6 @@
use App\Services\Onboarding\OnboardingLifecycleService; use App\Services\Onboarding\OnboardingLifecycleService;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Providers\ProviderConnectionMutationService; use App\Services\Providers\ProviderConnectionMutationService;
use App\Services\Providers\ProviderConnectionStateProjector;
use App\Services\Providers\ProviderOperationRegistry; use App\Services\Providers\ProviderOperationRegistry;
use App\Services\Providers\ProviderOperationStartGate; use App\Services\Providers\ProviderOperationStartGate;
use App\Services\Tenants\TenantOperabilityService; use App\Services\Tenants\TenantOperabilityService;
@ -2535,12 +2534,6 @@ public function createProviderConnection(array $data): void
/** @var ProviderConnection $connection */ /** @var ProviderConnection $connection */
$connection = DB::transaction(function () use ($tenant, $displayName, $clientId, $clientSecret, $makeDefault, $usesDedicatedCredential, &$wasExistingConnection, &$previousConnectionType): ProviderConnection { $connection = DB::transaction(function () use ($tenant, $displayName, $clientId, $clientSecret, $makeDefault, $usesDedicatedCredential, &$wasExistingConnection, &$previousConnectionType): ProviderConnection {
$projectedState = app(ProviderConnectionStateProjector::class)->project(
connectionType: ProviderConnectionType::Platform,
consentStatus: ProviderConsentStatus::Required,
verificationStatus: ProviderVerificationStatus::Unknown,
);
$connection = ProviderConnection::query() $connection = ProviderConnection::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('tenant_id', (int) $tenant->getKey())
->where('provider', 'microsoft') ->where('provider', 'microsoft')
@ -2554,15 +2547,14 @@ public function createProviderConnection(array $data): void
'provider' => 'microsoft', 'provider' => 'microsoft',
'entra_tenant_id' => (string) $tenant->tenant_id, 'entra_tenant_id' => (string) $tenant->tenant_id,
'display_name' => $displayName, 'display_name' => $displayName,
'is_enabled' => true,
'connection_type' => ProviderConnectionType::Platform->value, 'connection_type' => ProviderConnectionType::Platform->value,
'status' => $projectedState['status'],
'consent_status' => ProviderConsentStatus::Required->value, 'consent_status' => ProviderConsentStatus::Required->value,
'consent_granted_at' => null, 'consent_granted_at' => null,
'consent_last_checked_at' => null, 'consent_last_checked_at' => null,
'consent_error_code' => null, 'consent_error_code' => null,
'consent_error_message' => null, 'consent_error_message' => null,
'verification_status' => ProviderVerificationStatus::Unknown->value, 'verification_status' => ProviderVerificationStatus::Unknown->value,
'health_status' => $projectedState['health_status'],
'migration_review_required' => false, 'migration_review_required' => false,
'migration_reviewed_at' => null, 'migration_reviewed_at' => null,
'last_error_reason_code' => ProviderReasonCodes::ProviderConsentMissing, 'last_error_reason_code' => ProviderReasonCodes::ProviderConsentMissing,

View File

@ -395,6 +395,7 @@ public static function table(Table $table): Table
return $nextRun->format('M j, Y H:i:s'); return $nextRun->format('M j, Y H:i:s');
} }
}) })
->description(fn (BackupSchedule $record): ?string => static::scheduleFollowUpDescription($record))
->sortable(), ->sortable(),
]) ])
->filters([ ->filters([
@ -1149,4 +1150,31 @@ protected static function dayOfWeekOptions(): array
7 => 'Sunday', 7 => 'Sunday',
]; ];
} }
protected static function scheduleFollowUpDescription(BackupSchedule $record): ?string
{
if (! $record->is_enabled || $record->trashed()) {
return null;
}
$graceCutoff = now('UTC')->subMinutes(max(1, (int) config('tenantpilot.backup_health.schedule_overdue_grace_minutes', 30)));
$lastRunStatus = strtolower(trim((string) $record->last_run_status));
$isOverdue = $record->next_run_at?->lessThan($graceCutoff) ?? false;
$neverSuccessful = $record->last_run_at === null
&& ($isOverdue || ($record->created_at?->lessThan($graceCutoff) ?? false));
if ($neverSuccessful) {
return 'No successful run has been recorded yet.';
}
if ($isOverdue) {
return 'This schedule looks overdue.';
}
if (in_array($lastRunStatus, ['failed', 'partial', 'skipped', 'canceled'], true)) {
return 'The last run needs follow-up.';
}
return null;
}
} }

View File

@ -3,7 +3,11 @@
namespace App\Filament\Resources\BackupScheduleResource\Pages; namespace App\Filament\Resources\BackupScheduleResource\Pages;
use App\Filament\Resources\BackupScheduleResource; use App\Filament\Resources\BackupScheduleResource;
use App\Models\Tenant;
use App\Support\BackupHealth\TenantBackupHealthAssessment;
use App\Support\BackupHealth\TenantBackupHealthResolver;
use App\Support\Filament\CanonicalAdminTenantFilterState; use App\Support\Filament\CanonicalAdminTenantFilterState;
use Filament\Facades\Filament;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
@ -64,4 +68,23 @@ private function syncCanonicalAdminTenantFilterState(): void
tenantFilterName: null, tenantFilterName: null,
); );
} }
public function getSubheading(): ?string
{
if (request()->string('backup_health_reason')->toString() !== TenantBackupHealthAssessment::REASON_SCHEDULE_FOLLOW_UP) {
return null;
}
$tenant = BackupScheduleResource::panelTenantContext();
if ($tenant === null) {
return 'One or more enabled schedules need follow-up.';
}
/** @var TenantBackupHealthResolver $resolver */
$resolver = app(TenantBackupHealthResolver::class);
$summary = $resolver->assess($tenant)->scheduleFollowUp->summaryMessage;
return $summary ?? 'One or more enabled schedules need follow-up.';
}
} }

View File

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

View File

@ -3,6 +3,7 @@
namespace App\Filament\Resources\BackupSetResource\Pages; namespace App\Filament\Resources\BackupSetResource\Pages;
use App\Filament\Resources\BackupSetResource; use App\Filament\Resources\BackupSetResource;
use App\Support\BackupHealth\TenantBackupHealthAssessment;
use App\Support\Filament\CanonicalAdminTenantFilterState; use App\Support\Filament\CanonicalAdminTenantFilterState;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
@ -40,4 +41,14 @@ protected function getTableEmptyStateActions(): array
BackupSetResource::makeCreateAction(), BackupSetResource::makeCreateAction(),
]; ];
} }
public function getSubheading(): ?string
{
return match (request()->string('backup_health_reason')->toString()) {
TenantBackupHealthAssessment::REASON_NO_BACKUP_BASIS => 'No usable completed backup basis is currently available for this tenant.',
TenantBackupHealthAssessment::REASON_LATEST_BACKUP_STALE => 'The latest backup detail is no longer available, so this view stays on the backup-set list.',
TenantBackupHealthAssessment::REASON_LATEST_BACKUP_DEGRADED => 'The latest backup detail is no longer available, so this view stays on the backup-set list.',
default => null,
};
}
} }

View File

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

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