spec: add tenant governance aggregate contract

This commit is contained in:
Ahmed Darrazi 2026-03-29 23:11:36 +02:00
parent 62c9b97d00
commit 705bd51659
10 changed files with 1397 additions and 4 deletions

View File

@ -114,6 +114,8 @@ ## Active Technologies
- PostgreSQL using existing `findings`, `finding_exceptions`, related decision tables, and existing DB-backed summary sources; no schema changes required (166-finding-governance-health) - PostgreSQL using existing `findings`, `finding_exceptions`, related decision tables, and existing DB-backed summary sources; no schema changes required (166-finding-governance-health)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `ArtifactTruthPresenter`, `OperationUxPresenter`, `RelatedNavigationResolver`, `AppServiceProvider`, `BadgeCatalog`, `BadgeRenderer`, and current Filament resource/page seams (167-derived-state-memoization) - PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `ArtifactTruthPresenter`, `OperationUxPresenter`, `RelatedNavigationResolver`, `AppServiceProvider`, `BadgeCatalog`, `BadgeRenderer`, and current Filament resource/page seams (167-derived-state-memoization)
- PostgreSQL unchanged; feature adds no persistence and relies on request-local in-memory state only (167-derived-state-memoization) - PostgreSQL unchanged; feature adds no persistence and relies on request-local in-memory state only (167-derived-state-memoization)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `BaselineCompareStats`, `BaselineCompareSummaryAssessor`, `BaselineCompareLanding`, `BaselineCompareNow`, `NeedsAttention`, `BaselineCompareCoverageBanner`, and `RequestScopedDerivedStateStore` from Spec 167 (168-tenant-governance-aggregate-contract)
- PostgreSQL unchanged; no new persistence, cache store, or durable summary artifac (168-tenant-governance-aggregate-contract)
- PHP 8.4.15 (feat/005-bulk-operations) - PHP 8.4.15 (feat/005-bulk-operations)
@ -133,8 +135,8 @@ ## Code Style
PHP 8.4.15: Follow standard conventions PHP 8.4.15: Follow standard conventions
## Recent Changes ## Recent Changes
- 168-tenant-governance-aggregate-contract: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, existing `BaselineCompareStats`, `BaselineCompareSummaryAssessor`, `BaselineCompareLanding`, `BaselineCompareNow`, `NeedsAttention`, `BaselineCompareCoverageBanner`, and `RequestScopedDerivedStateStore` from Spec 167
- 167-derived-state-memoization: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `ArtifactTruthPresenter`, `OperationUxPresenter`, `RelatedNavigationResolver`, `AppServiceProvider`, `BadgeCatalog`, `BadgeRenderer`, and current Filament resource/page seams - 167-derived-state-memoization: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `ArtifactTruthPresenter`, `OperationUxPresenter`, `RelatedNavigationResolver`, `AppServiceProvider`, `BadgeCatalog`, `BadgeRenderer`, and current Filament resource/page seams
- 166-finding-governance-health: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `Finding`, `FindingException`, `FindingRiskGovernanceResolver`, `BadgeCatalog`, `BadgeRenderer`, `FilterOptionCatalog`, and tenant dashboard widgets - 166-finding-governance-health: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, existing `Finding`, `FindingException`, `FindingRiskGovernanceResolver`, `BadgeCatalog`, `BadgeRenderer`, `FilterOptionCatalog`, and tenant dashboard widgets
- 165-baseline-summary-trust: Added PHP 8.4, Laravel 12, Blade, Filament v5, Livewire v4 + Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BaselineCompareStats`, `BaselineCompareExplanationRegistry`, `ReasonPresenter`, `BadgeCatalog` or `BadgeRenderer`, `UiEnforcement`, and `OperationRunLinks`
<!-- MANUAL ADDITIONS START --> <!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END --> <!-- MANUAL ADDITIONS END -->

View File

@ -238,9 +238,9 @@ ## Dependencies
## Follow-up Spec Candidates ## Follow-up Spec Candidates
- **Spec 167 — Finding Resolution Origin & Workflow Truth Foundation** if the current data model cannot stably distinguish workflow resolution from no-longer-observed truth on all required surfaces - **Finding Resolution Origin & Workflow Truth Foundation** if the current data model cannot stably distinguish workflow resolution from no-longer-observed truth on all required surfaces
- **Spec 168 — Exception Expiry Alerts & Governance Notifications** for proactive alerting around expiring or expired governance - **Exception Expiry Alerts & Governance Notifications** for proactive alerting around expiring or expired governance
- **Spec 169 — Finding Detail Workflow History & Reopen Context** for deeper recurrence, prior-resolution, and historical workflow storytelling - **Finding Detail Workflow History & Reopen Context** for deeper recurrence, prior-resolution, and historical workflow storytelling
## Definition of Done ## Definition of Done

View File

@ -0,0 +1,34 @@
# Specification Quality Checklist: Tenant Governance Aggregate Contract
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-03-28
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- Validation passed on first draft. The spec introduces one narrow derived aggregate contract, explicitly avoids new persistence and new state families, and keeps the work bounded to existing tenant-governance summary surfaces.

View File

@ -0,0 +1,335 @@
openapi: 3.1.0
info:
title: Tenant Governance Aggregate Internal Surface Contract
version: 0.1.0
summary: Internal logical contract for the shared tenant-governance summary aggregate
description: |
This contract is an internal planning artifact for Spec 168. It documents the
derived tenant-governance aggregate and the way tenant dashboard, banner, and
Baseline Compare landing surfaces consume it. The rendered routes still return
HTML. The structured schemas below describe the internal page and widget models
that must be derivable before rendering. This does not add a public HTTP API.
servers:
- url: /internal
x-governance-consumers:
- surface: tenant.dashboard.needs_attention
summarySource: tenant_governance_aggregate
accessPattern: widget_safe
guardScope:
- app/Filament/Widgets/Dashboard/NeedsAttention.php
requiredMarkers:
- 'TenantGovernanceAggregate'
- 'Needs Attention'
maxOccurrences:
- needle: 'Finding::query()'
max: 0
- surface: tenant.dashboard.baseline_governance
summarySource: tenant_governance_aggregate
accessPattern: widget_safe
guardScope:
- app/Filament/Widgets/Dashboard/BaselineCompareNow.php
requiredMarkers:
- 'TenantGovernanceAggregate'
- 'Baseline Governance'
- surface: tenant.banner.baseline_compare_coverage
summarySource: tenant_governance_aggregate
accessPattern: widget_safe
guardScope:
- app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php
requiredMarkers:
- 'TenantGovernanceAggregate'
- 'nextActionUrl'
- surface: tenant.page.baseline_compare_landing
summarySource: tenant_governance_aggregate
accessPattern: page_safe
guardScope:
- app/Filament/Pages/BaselineCompareLanding.php
requiredMarkers:
- 'TenantGovernanceAggregate'
- 'Compare now'
paths:
/tenants/{tenant}/governance-aggregate:
get:
summary: Resolve the derived tenant-governance aggregate for one tenant
operationId: resolveTenantGovernanceAggregate
parameters:
- name: tenant
in: path
required: true
schema:
type: string
description: Tenant route key or canonical tenant identifier for the current tenant scope.
- name: surface
in: query
required: false
schema:
$ref: '#/components/schemas/GovernanceSurface'
responses:
'200':
description: Aggregate resolved for the current tenant scope
content:
application/vnd.tenantpilot.tenant-governance-aggregate+json:
schema:
$ref: '#/components/schemas/TenantGovernanceAggregate'
'403':
description: Actor is in scope but lacks the capability required to view the target surface
'404':
description: Tenant is outside workspace or tenant entitlement scope
/admin/t/{tenant}:
get:
summary: Tenant dashboard governance summary surfaces
operationId: viewTenantDashboardGovernance
parameters:
- name: tenant
in: path
required: true
schema:
type: string
responses:
'200':
description: Rendered tenant dashboard with shared governance summary surfaces
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.tenant-dashboard-governance+json:
schema:
$ref: '#/components/schemas/TenantDashboardGovernanceBundle'
'403':
description: Actor is in scope but lacks the required tenant capability
'404':
description: Tenant is not visible in the current workspace or membership scope
/admin/t/{tenant}/baseline-compare-landing:
get:
summary: Baseline Compare landing governance summary and diagnostics split
operationId: viewBaselineCompareLandingGovernance
parameters:
- name: tenant
in: path
required: true
schema:
type: string
responses:
'200':
description: Rendered Baseline Compare landing page
content:
text/html:
schema:
type: string
application/vnd.tenantpilot.baseline-compare-landing-governance+json:
schema:
$ref: '#/components/schemas/BaselineCompareLandingGovernanceView'
'403':
description: Actor is in scope but lacks the required tenant capability
'404':
description: Tenant is not visible in the current workspace or membership scope
components:
schemas:
GovernanceSurface:
type: string
enum:
- dashboard_needs_attention
- dashboard_baseline_governance
- baseline_compare_landing
- coverage_banner
NextActionTarget:
type: string
enum:
- findings
- run
- landing
- none
GovernanceCounts:
type: object
additionalProperties: false
required:
- visibleDriftFindingsCount
- overdueOpenFindingsCount
- expiringGovernanceCount
- lapsedGovernanceCount
- activeNonNewFindingsCount
- highSeverityActiveFindingsCount
properties:
visibleDriftFindingsCount:
type: integer
minimum: 0
overdueOpenFindingsCount:
type: integer
minimum: 0
expiringGovernanceCount:
type: integer
minimum: 0
lapsedGovernanceCount:
type: integer
minimum: 0
activeNonNewFindingsCount:
type: integer
minimum: 0
highSeverityActiveFindingsCount:
type: integer
minimum: 0
NextActionIntent:
type: object
additionalProperties: false
required:
- label
- target
properties:
label:
type: string
target:
$ref: '#/components/schemas/NextActionTarget'
ComparePosture:
type: object
additionalProperties: false
required:
- compareState
- stateFamily
- tone
- headline
- positiveClaimAllowed
properties:
compareState:
type: string
enum:
- no_tenant
- no_assignment
- no_snapshot
- idle
- comparing
- failed
- ready
stateFamily:
type: string
enum:
- positive
- caution
- stale
- action_required
- in_progress
- unavailable
tone:
type: string
enum:
- success
- warning
- danger
- info
- gray
headline:
type: string
supportingMessage:
type:
- string
- 'null'
reasonCode:
type:
- string
- 'null'
lastComparedLabel:
type:
- string
- 'null'
positiveClaimAllowed:
type: boolean
TenantGovernanceAggregate:
type: object
additionalProperties: false
required:
- tenantId
- workspaceId
- posture
- counts
- nextAction
properties:
tenantId:
type: integer
workspaceId:
type: integer
profileName:
type:
- string
- 'null'
posture:
$ref: '#/components/schemas/ComparePosture'
counts:
$ref: '#/components/schemas/GovernanceCounts'
nextAction:
$ref: '#/components/schemas/NextActionIntent'
operationRunId:
type:
- integer
- 'null'
diagnosticsOwner:
type: string
enum:
- baseline_compare_stats
NeedsAttentionItem:
type: object
additionalProperties: false
required:
- title
- badge
- badgeColor
properties:
title:
type: string
body:
type:
- string
- 'null'
supportingMessage:
type:
- string
- 'null'
badge:
type: string
badgeColor:
type: string
nextStep:
type:
- string
- 'null'
TenantDashboardGovernanceBundle:
type: object
additionalProperties: false
required:
- aggregate
properties:
aggregate:
$ref: '#/components/schemas/TenantGovernanceAggregate'
needsAttentionItems:
type: array
items:
$ref: '#/components/schemas/NeedsAttentionItem'
baselineGovernanceCard:
type: object
additionalProperties: false
required:
- aggregate
properties:
aggregate:
$ref: '#/components/schemas/TenantGovernanceAggregate'
BaselineCompareLandingGovernanceView:
type: object
additionalProperties: false
required:
- aggregate
- diagnosticsPolicy
properties:
aggregate:
$ref: '#/components/schemas/TenantGovernanceAggregate'
diagnosticsPolicy:
type: object
additionalProperties: false
required:
- compareDiagnosticsRemainLocal
- evidenceGapDetailsRemainLocal
- compareActionUnchanged
properties:
compareDiagnosticsRemainLocal:
type: boolean
evidenceGapDetailsRemainLocal:
type: boolean
compareActionUnchanged:
type: boolean

View File

@ -0,0 +1,213 @@
# Phase 1 Data Model: Tenant Governance Aggregate Contract
## Overview
This feature does not add a database table or persisted summary artifact. It formalizes the existing persistent source truths that already drive tenant governance posture and adds one derived runtime contract plus request-scoped reuse rules for the shared summary family.
## Persistent Source Truths
### Tenant
**Purpose**: The tenant is the scope boundary for the aggregate and for every covered surface.
**Key fields**:
- `id`
- `workspace_id`
- `external_id`
**Validation rules**:
- Aggregate resolution is allowed only for one explicit tenant scope at a time.
- Workspace membership and tenant entitlement remain authoritative before any summary surface renders.
### BaselineTenantAssignment and BaselineProfile
**Purpose**: Define whether the tenant has an assigned baseline and which profile and snapshot chain determine compare availability.
**Key fields**:
- `baseline_tenant_assignments.tenant_id`
- `baseline_tenant_assignments.baseline_profile_id`
- `baseline_profiles.id`
- `baseline_profiles.name`
- `baseline_profiles.active_snapshot_id`
**Validation rules**:
- Missing assignment and missing snapshot remain derived availability states, not new persisted governance states.
### BaselineSnapshot
**Purpose**: Supplies consumable compare-snapshot truth for the assigned baseline profile.
**Key fields**:
- `id`
- `baseline_profile_id`
- lifecycle/completion fields already used by `BaselineSnapshotTruthResolver`
**Validation rules**:
- Snapshot usability remains governed by existing compare truth logic.
- The aggregate must not invent a second snapshot-availability rule set.
### OperationRun
**Purpose**: Supplies baseline-compare progress, completion, failure, and freshness context.
**Key fields**:
- `id`
- `tenant_id`
- `workspace_id`
- `type`
- `status`
- `outcome`
- `completed_at`
- `context`
**Validation rules**:
- Only existing baseline-compare runs influence compare posture in this slice.
- The aggregate does not introduce a new run type or a second operational state model.
### Finding and FindingException
**Purpose**: Supply overdue workflow state, visible drift pressure, and accepted-risk governance validity.
**Key fields**:
- `findings.tenant_id`
- `findings.status`
- `findings.severity`
- `findings.due_at`
- `finding_exceptions.current_validity_state`
**Validation rules**:
- Overdue, expiring, lapsed, active-non-new, and high-severity-active counts remain derived from current findings truth.
- The aggregate must not redefine accepted-risk validity semantics.
## Existing Runtime Source Objects
### BaselineCompareStats
**Purpose**: Existing query-backed compare truth object that already combines compare availability, diagnostics, and governance-attention counts for one tenant.
**Key fields consumed by this feature**:
- `state`
- `profileName`
- `operationRunId`
- `findingsCount`
- `lastComparedHuman`
- `lastComparedIso`
- `reasonCode`
- `overdueOpenFindingsCount`
- `expiringGovernanceCount`
- `lapsedGovernanceCount`
- `activeNonNewFindingsCount`
- `highSeverityActiveFindingsCount`
**Relationship to the new aggregate**:
- The aggregate is built from one `BaselineCompareStats` resolution.
- Landing diagnostics continue to read `BaselineCompareStats` directly.
### BaselineCompareSummaryAssessment
**Purpose**: Existing summary interpretation object that maps `BaselineCompareStats` to posture family, tone, headline, supporting message, and next-action target.
**Key fields consumed by this feature**:
- `stateFamily`
- `headline`
- `supportingMessage`
- `tone`
- `positiveClaimAllowed`
- `reasonCode`
- `nextActionTarget()`
- `nextActionLabel()`
**Relationship to the new aggregate**:
- The aggregate uses the summary assessment as its summary-semantics input.
- The feature must not fork a second state-family interpretation path.
## New Derived Runtime Entities
### TenantGovernanceAggregate
**Purpose**: One tenant-scoped operator summary contract that owns the shared posture, count family, and next-action intent for tenant-governance summary surfaces.
#### Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `tenant_id` | int | yes | Tenant scope for the aggregate |
| `workspace_id` | int | yes | Workspace scope for request-local reuse safety |
| `profile_name` | string nullable | no | Assigned baseline profile name when available |
| `compare_state` | string | yes | Existing compare availability or execution state from `BaselineCompareStats` |
| `state_family` | string | yes | Existing summary posture family from `BaselineCompareSummaryAssessment` |
| `tone` | string | yes | Existing tone family used by covered summary surfaces |
| `headline` | string | yes | Operator-facing summary headline |
| `supporting_message` | string nullable | no | Secondary operator-facing explanation |
| `reason_code` | string nullable | no | Summary reason code when available |
| `last_compared_label` | string nullable | no | Human-readable freshness label |
| `visible_drift_findings_count` | int | yes | Visible drift findings count from compare stats |
| `overdue_open_findings_count` | int | yes | Overdue open findings count |
| `expiring_governance_count` | int | yes | Accepted-risk governance nearing expiry |
| `lapsed_governance_count` | int | yes | Accepted-risk governance no longer valid |
| `active_non_new_findings_count` | int | yes | Active non-new findings pressure |
| `high_severity_active_findings_count` | int | yes | High-severity active findings pressure |
| `next_action_label` | string | yes | Stable operator-facing next-step label |
| `next_action_target` | enum(`findings`,`run`,`landing`,`none`) | yes | Stable next-action intent; surfaces map this to local URLs |
| `positive_claim_allowed` | bool | yes | Whether the current summary posture qualifies as a trustworthy all-clear |
| `stats` | `BaselineCompareStats` | yes | Embedded source truth used when a consumer also needs compare diagnostics |
| `summary_assessment` | `BaselineCompareSummaryAssessment` | yes | Embedded summary truth used by all covered surfaces |
#### Validation rules
- The aggregate must be built from exactly one `BaselineCompareStats` instance and exactly one `BaselineCompareSummaryAssessment` derived from that stats instance.
- Count fields must be copied from the same stats instance; surfaces must not recompute them locally.
- Final URLs, local badges, and layout-specific copy remain outside the aggregate.
### TenantGovernanceAggregateResolver
**Purpose**: Service seam that resolves one `TenantGovernanceAggregate` per tenant scope and handles request-local reuse.
#### Fields / Inputs
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `tenant` | `Tenant` nullable | yes | Target tenant; nullable only for explicit no-tenant handling paths |
| `workspace_id` | int nullable | no | Optional explicit scope input for guardable key composition |
| `surface_variant` | string | yes | Stable consumer variant used when request-local reuse or guard declarations need surface-specific context |
#### Validation rules
- The resolver must stay derived-only.
- Reuse must be request-local only.
- A no-tenant or wrong-tenant path must never reuse a previous tenants aggregate.
### DerivedStateFamily::TenantGovernanceAggregate
**Purpose**: Extends the existing Spec 167 request-scoped derived-state contract so the aggregate follows the same consumer-declaration and guard rules as other supported deterministic families.
#### Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `family` | enum value | yes | Stable family identifier for request-local aggregate reuse |
| `default_freshness_policy` | enum | yes | Expected to remain `invalidate_after_mutation` for landing refresh paths |
| `allows_negative_result_cache` | bool | yes | Aggregate resolution should be reusable for deterministic no-tenant or unavailable states only if the final key contract explicitly supports it |
## Consumer Mapping
| Consumer | Aggregate responsibility | Local responsibility |
|---|---|---|
| `NeedsAttention` | Overdue, expiring, lapsed, high-severity counts; baseline posture headline; next-action intent | Operations-in-progress count and widget-specific healthy fallback layout |
| `BaselineCompareNow` | Baseline posture family, headline, supporting message, next-action intent | Tenant-panel URL mapping for findings, run detail, and landing drill-down |
| `BaselineCompareCoverageBanner` | Banner visibility posture family, tone, headline, supporting message, next-action intent | Banner-specific show/hide threshold and local URL mapping |
| `BaselineCompareLanding` | Default-visible posture zone and next-action intent | Compare diagnostics, evidence-gap detail, duplicate-name detail, and existing `Compare now` action |
## Derived State Lifecycle
1. A covered tenant summary surface asks the resolver for the current tenant aggregate.
2. The resolver resolves or reuses one request-scoped aggregate for that tenant scope.
3. Covered surfaces read the same posture family, count family, and next-action intent from the shared aggregate.
4. If an in-request mutation or refresh path makes the current aggregate stale, the resolver uses explicit invalidation or fresh-resolution semantics.
5. The next request builds a new aggregate from current source truth.
## Migration Notes
- No schema migration is required.
- Existing `BaselineCompareStats` tests remain the low-level source-truth tests.
- If the implementation adds a new derived-state family, it must also extend the Spec 167 consumer-declaration contract and guard test.

View File

@ -0,0 +1,260 @@
# Implementation Plan: Tenant Governance Aggregate Contract
**Branch**: `168-tenant-governance-aggregate-contract` | **Date**: 2026-03-28 | **Spec**: `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/168-tenant-governance-aggregate-contract/spec.md`
**Input**: Feature specification from `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/168-tenant-governance-aggregate-contract/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/scripts/` for helper scripts.
## Summary
Introduce one explicit, derived, tenant-scoped governance aggregate that turns the existing compare posture and governance-attention counts into a single cross-surface contract. The first implementation slice will build the aggregate from `BaselineCompareStats` and its summary assessment, reuse the request-scoped derived-state infrastructure added in Spec 167, and align the tenant dashboard `Baseline Governance` card, tenant governance banner, and Baseline Compare landing around the same posture family and next-action intent while preserving existing landing action semantics and diagnostics hierarchy. A follow-on slice then moves `NeedsAttention` off its local findings-count ownership so the tenant dashboard can render both governance summary cards from one request-local contract without adding persistence or new mutation behavior.
## Technical Context
**Language/Version**: PHP 8.4.15
**Primary Dependencies**: Laravel 12, Filament v5, Livewire v4, Pest v4, existing `BaselineCompareStats`, `BaselineCompareSummaryAssessor`, `BaselineCompareLanding`, `BaselineCompareNow`, `NeedsAttention`, `BaselineCompareCoverageBanner`, and `RequestScopedDerivedStateStore` from Spec 167
**Storage**: PostgreSQL unchanged; no new persistence, cache store, or durable summary artifact
**Testing**: Pest 4 unit and feature tests, including Livewire component coverage and derived-state guard tests, run through Laravel Sail
**Target Platform**: Laravel monolith web application in Sail locally and containerized Linux deployment in staging/production
**Project Type**: web application
**Performance Goals**: One governance-aggregate resolution per request for the same tenant and summary scope; no duplicate aggregate-owned findings queries across the tenant dashboard render; covered summary surfaces keep DB-only render behavior and reuse one stable posture family
**Constraints**: Derived-only implementation, no new Graph calls, no cross-request cache, no new mutation surfaces, existing `Compare now` confirmation and authorization remain unchanged, diagnostics stay secondary, and no cross-tenant or cross-workspace summary leakage is allowed
**Scale/Scope**: One tenant at a time, with phased adoption across four tenant-facing summary consumers: MVP parity for `BaselineCompareNow`, `BaselineCompareCoverageBanner`, and `BaselineCompareLanding`, followed by `NeedsAttention` adoption for multi-card request stability
## Constitution Check
*GATE: Passed before Phase 0 research. Re-checked after Phase 1 design and still passing.*
| Principle | Pre-Research | Post-Design | Notes |
|-----------|--------------|-------------|-------|
| Inventory-first / snapshots-second | PASS | PASS | The aggregate is derived from current findings, exception validity, baseline assignment, snapshot availability, and compare-run truth; no new source-of-truth path is introduced. |
| Read/write separation | PASS | PASS | The feature changes read-time summary ownership only. Existing `Compare now` remains the only mutation-adjacent action and stays unchanged. |
| Graph contract path | N/A | N/A | No Graph calls, provider contracts, or `config/graph_contracts.php` changes are required. |
| Deterministic capabilities | PASS | PASS | Authorization and drill-down capability enforcement remain existing server-side checks; the aggregate is read-only and tenant-scoped. |
| Workspace + tenant isolation | PASS | PASS | The aggregate is resolved for one tenant at a time and must never outlive the current request or tenant context. |
| RBAC-UX authorization semantics | PASS | PASS | No new permissions, no role-string checks, and no change to 404-for-non-members / 403-for-in-scope-capability-denial semantics. |
| Run observability / Ops-UX | PASS | PASS | No new `OperationRun` type or feedback path. Existing baseline-compare run visibility remains the operational source. |
| Data minimization | PASS | PASS | No persistence is added; reuse remains request-local only. |
| Proportionality / no premature abstraction | PASS WITH JUSTIFIED ABSTRACTION | PASS WITH JUSTIFIED ABSTRACTION | One narrow runtime contract plus one resolver is justified because four surfaces already share the same summary family and `NeedsAttention` still re-queries data already owned elsewhere. |
| Persisted truth / behavioral state | PASS | PASS | No new tables, artifacts, reason-code families, or persisted statuses are introduced. |
| UI semantics / few layers | PASS | PASS | The aggregate stays below the existing surface layouts. It replaces split summary ownership instead of adding a second presentation framework. |
| Badge semantics (BADGE-001) | PASS | PASS | Existing summary tone and badge mapping stay authoritative; the aggregate supplies data, not ad hoc visual semantics. |
| Filament-native UI / Action Surface Contract | PASS | PASS | Widgets and landing page remain native Filament surfaces. No new row, bulk, or destructive actions are introduced. |
| Filament UX-001 | PASS | PASS | No create/edit/view layout redesign is proposed; only existing summary zones change data ownership. |
| Filament v5 / Livewire v4 compliance | PASS | PASS | The design remains inside the existing Filament v5 + Livewire v4 stack with no legacy API introduction. |
| Provider registration location | PASS | PASS | No panel or provider registration changes; Laravel 11+ registration remains in `bootstrap/providers.php`. |
| Global search hard rule | PASS | PASS | No globally searchable resource changes are proposed in this slice. |
| Destructive action safety | PASS | PASS | No new destructive actions are added. The existing Baseline Compare landing action remains `->action(...)->requiresConfirmation()` and capability-gated. |
| Asset strategy | PASS | PASS | No new assets or `filament:assets` deployment changes are required. |
| Testing truth (TEST-TRUTH-001) | PASS | PASS | The plan adds parity, memoization, and tenant-scope safety tests that protect operator-visible truth rather than thin adapters only. |
## Phase 0 Research
Research outcomes are captured in `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/168-tenant-governance-aggregate-contract/research.md`.
Key decisions:
- Build the new aggregate from `BaselineCompareStats` and `BaselineCompareSummaryAssessment` instead of creating a second query-backed summary path.
- Introduce one narrow `TenantGovernanceAggregate` runtime contract so summary ownership is explicit without moving landing-page diagnostics into a bloated new object.
- Reuse the existing request-scoped derived-state infrastructure from Spec 167 rather than adding widget-local or resource-local caches.
- Keep next-action intent inside the aggregate but leave final URLs and panel-specific drill-down mapping local to each surface.
- Let `BaselineCompareLanding` keep `BaselineCompareStats` for deep diagnostics while switching its default-visible posture zone to the shared aggregate.
- Protect the feature with focused parity, memoization, and guard tests instead of ad hoc performance scripts.
## Phase 1 Design
Design artifacts are created under `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/168-tenant-governance-aggregate-contract/`:
- `data-model.md`: persistent source truths plus the new derived tenant-governance runtime contract
- `contracts/tenant-governance-aggregate.openapi.yaml`: internal logical contract for resolving and consuming the aggregate on tenant summary surfaces
- `quickstart.md`: focused implementation and verification workflow
Design decisions:
- The shared contract is one derived runtime object, not a new persisted summary or reporting subsystem.
- `BaselineCompareStats` remains the heavy query-backed source for compare posture, findings counts, and landing diagnostics.
- The aggregate owns shared summary semantics only: posture family, count family, and next-action intent.
- Request-local reuse will extend the Spec 167 derived-state contract instead of introducing local static caches in widgets or pages.
- Consumer surfaces will adopt named helper seams so CI can guard against future reintroduction of local findings queries or direct duplicate aggregate resolution.
## Project Structure
### Documentation (this feature)
```text
specs/168-tenant-governance-aggregate-contract/
├── spec.md
├── plan.md
├── research.md
├── data-model.md
├── quickstart.md
├── contracts/
│ └── tenant-governance-aggregate.openapi.yaml
├── checklists/
│ └── requirements.md
└── tasks.md
```
### Source Code (repository root)
```text
app/
├── Filament/
│ ├── Pages/
│ │ ├── BaselineCompareLanding.php
│ │ └── TenantDashboard.php
│ └── Widgets/
│ ├── Dashboard/
│ │ ├── BaselineCompareNow.php
│ │ └── NeedsAttention.php
│ └── Tenant/
│ └── BaselineCompareCoverageBanner.php
├── Support/
│ ├── Baselines/
│ │ ├── BaselineCompareStats.php
│ │ ├── BaselineCompareSummaryAssessor.php
│ │ ├── BaselineCompareSummaryAssessment.php
│ │ ├── TenantGovernanceAggregate.php
│ │ └── TenantGovernanceAggregateResolver.php
│ └── Ui/
│ └── DerivedState/
│ └── DerivedStateFamily.php
tests/
├── Feature/
│ ├── Baselines/
│ │ ├── BaselineCompareStatsTest.php
│ │ ├── BaselineCompareSummaryAssessmentTest.php
│ │ └── TenantGovernanceAggregateResolverTest.php
│ ├── Filament/
│ │ ├── BaselineCompareSummaryConsistencyTest.php
│ │ ├── BaselineCompareNowWidgetTest.php
│ │ ├── BaselineCompareCoverageBannerTest.php
│ │ ├── BaselineCompareLandingAdminTenantParityTest.php
│ │ ├── BaselineCompareLandingDuplicateNamesBannerTest.php
│ │ ├── BaselineCompareLandingRbacLabelsTest.php
│ │ ├── BaselineCompareLandingStartSurfaceTest.php
│ │ ├── BaselineCompareLandingWhyNoFindingsTest.php
│ │ ├── NeedsAttentionWidgetTest.php
│ │ └── TenantGovernanceAggregateMemoizationTest.php
│ └── Guards/
│ └── DerivedStateConsumerAdoptionGuardTest.php
```
**Structure Decision**: Keep the existing Laravel monolith structure. Add one narrow runtime contract plus resolver under `app/Support/Baselines`, adopt it through the current Filament widgets and landing page, and extend the existing request-scoped derived-state infrastructure instead of creating new base directories or a broader presentation layer.
## Implementation Strategy
### Phase A — Introduce the Aggregate Contract and Resolver
**Goal**: Add one explicit tenant-governance runtime object and one resolver that derives it from existing compare truth.
| Step | File | Change |
|------|------|--------|
| A.1 | `app/Support/Baselines/TenantGovernanceAggregate.php` | Add the derived runtime contract that holds the shared summary posture, count family, and next-action intent for one tenant |
| A.2 | `app/Support/Baselines/TenantGovernanceAggregateResolver.php` | Add the resolver that derives the aggregate from `BaselineCompareStats` and `BaselineCompareSummaryAssessment` without adding persistence |
| A.3 | `app/Support/Baselines/BaselineCompareStats.php` | Expose the aggregate's count family from the existing source path and keep the landing diagnostics sourced from the same stats object |
### Phase B — Reuse the Existing Derived-State Infrastructure
**Goal**: Make repeated reads of the same tenant aggregate request-stable without adding ad hoc widget caches.
| Step | File | Change |
|------|------|--------|
| B.1 | `app/Support/Ui/DerivedState/DerivedStateFamily.php` | Add a dedicated family for tenant-governance aggregate reuse, unless the final implementation can reuse the existing family contract without ambiguity |
| B.2 | `app/Support/Baselines/TenantGovernanceAggregateResolver.php` and `specs/167-derived-state-memoization/contracts/request-scoped-derived-state.logical.openapi.yaml` | Route aggregate resolution through the existing request-scoped derived-state store and declare the supported first-slice consumer paths for the new family |
| B.3 | `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php` | Extend the allowed-family and guarded-consumer validation so first-slice summary surfaces cannot fall back to local caches or direct duplicate findings queries |
### Phase C — Adopt the First Shared Summary Surfaces
**Goal**: Make the tenant dashboard governance card, landing page, and tenant banner consume one shared semantic source before the second dashboard summary surface joins the contract.
| Step | File | Change |
|------|------|--------|
| C.1 | `app/Filament/Widgets/Dashboard/BaselineCompareNow.php` | Replace direct `BaselineCompareStats` summary reads with the aggregate while keeping local URL mapping for findings, run, and landing destinations |
| C.2 | `app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php` | Drive banner visibility, tone, and next-action intent from the same aggregate-backed posture family |
| C.3 | `app/Filament/Pages/BaselineCompareLanding.php` | Use the aggregate for the default-visible posture summary while preserving existing compare diagnostics, evidence-gap detail, and `Compare now` behavior |
| C.4 | `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, `tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php`, `tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php`, and `tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php` | Preserve unchanged compare-start authorization and confirmation semantics while proving diagnostics remain secondary to the aggregate-owned posture zone |
### Phase D — Align Next-Action Intent
**Goal**: Make the first shared summary surfaces point operators toward the same class of next step for the same tenant state.
| Step | File | Change |
|------|------|--------|
| D.1 | `app/Support/Baselines/TenantGovernanceAggregate.php` and `app/Support/Baselines/TenantGovernanceAggregateResolver.php` | Add next-action label and target ownership to the aggregate contract |
| D.2 | `app/Filament/Widgets/Dashboard/BaselineCompareNow.php`, `app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php`, and `app/Filament/Pages/BaselineCompareLanding.php` | Map shared next-action intent to local URLs and operator-facing labels without reintroducing local business rules |
| D.3 | `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, and `tests/Feature/Filament/BaselineCompareLandingAdminTenantParityTest.php` | Prove next-action parity for running, failed, unavailable, open-findings, overdue-without-new-drift, lapsed-without-new-drift, caution, and stale states |
### Phase E — Extend to `NeedsAttention` and Multi-Card Stability
**Goal**: Bring the second dashboard summary surface onto the same request-local contract and remove duplicate findings-count ownership.
| Step | File | Change |
|------|------|--------|
| E.1 | `app/Filament/Widgets/Dashboard/NeedsAttention.php` | Replace local `Finding::query()` ownership for overdue, expiring, lapsed, and high-severity summary counts with the shared aggregate and keep only local operations-in-progress logic |
| E.2 | `tests/Feature/Filament/NeedsAttentionWidgetTest.php`, `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php`, `specs/167-derived-state-memoization/contracts/request-scoped-derived-state.logical.openapi.yaml`, and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php` | Prove request-local reuse, no-tenant safety, tenant-switch safety, and extension of the guarded consumer contract to cover removal of hidden local findings-count ownership in `NeedsAttention` |
### Phase F — Regression Protection and Verification
**Goal**: Prove semantic consistency, request reuse, and tenant-scope safety.
| Step | File | Change |
|------|------|--------|
| F.1 | `tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php` | Add focused resolver coverage for the full FR-168-014 matrix: unavailable prerequisites, in-progress compare, failed compare, open findings requiring action, overdue-without-new-drift, lapsed-without-new-drift, caution, stale, and trustworthy all-clear |
| F.2 | `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, `tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php`, `tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php`, and `tests/Feature/Filament/NeedsAttentionWidgetTest.php` | Assert that covered surfaces share the same count family, posture family, diagnostics hierarchy, and next-action intent for seeded tenant states |
| F.3 | `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php` and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php` | Assert that one request stores one derived governance aggregate per tenant scope, no tenant state leaks, and no covered consumer reintroduces local findings-count ownership |
| F.4 | `vendor/bin/sail bin pint --dirty --format agent` and focused Pest runs | Apply formatting and run the smallest verification pack that covers stats, landing authorization and hierarchy, widgets, memoization, and the derived-state guard |
## Key Design Decisions
### D-001 — The new contract is summary-focused and derived from existing compare truth
The shared aggregate must not become a second diagnostics object. `BaselineCompareStats` already owns compare availability, findings counts, and low-level detail. The aggregate will summarize the operator-facing posture family built from that truth.
### D-002 — Request reuse must flow through Spec 167 infrastructure, not local caches
The repo already has `RequestScopedDerivedStateStore` and a guard model for supported families. This feature should extend that path instead of introducing widget-level static arrays or request-attribute caches.
### D-003 — Next-action intent belongs in the aggregate; final URLs stay local
The operator problem includes conflicting next steps, so the aggregate must own whether the next action is “findings”, “run”, “landing”, or “none”. Each surface will continue to map that intent to panel-specific URLs and capability-aware affordances.
### D-004 — Baseline Compare landing keeps diagnostics but loses summary re-ownership
The landing page remains the home for deep compare diagnostics and the compare-start action. It should stop being a separate semantic owner for the default-visible posture zone.
## Risk Assessment
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Aggregate and compare stats drift into parallel truths | High | Medium | Build the aggregate directly from one `BaselineCompareStats` resolution and keep diagnostics sourced from that same object |
| Request-scoped reuse omits tenant or route-sensitive inputs | High | Medium | Keep the aggregate user-agnostic, key it by workspace and tenant scope, and add tenant-switch / no-tenant regression tests |
| `NeedsAttention` keeps hidden local count ownership | High | Medium | Add consumer guard declarations plus tests that cover overdue, lapsed, and expiring states with zero new drift |
| Landing summary and dashboard summary stay semantically misaligned | Medium | Medium | Add cross-surface parity tests that assert one posture family and one next-action intent across dashboard, banner, and landing |
| The aggregate grows into a second presentation framework | Medium | Low | Limit it to summary posture, counts, and next-action intent; leave URLs, layout, and diagnostics local |
## Test Strategy
- Add focused resolver tests that cover the full FR-168-014 matrix: unavailable prerequisites, compare in progress, compare failed, open findings requiring action, overdue-without-new-drift, lapsed governance without new drift, cautionary limited-confidence results, stale results, and trustworthy all-clear results.
- Keep existing Baseline Compare stats and summary-assessment tests as the canonical low-level truth tests.
- Extend Filament widget and landing tests so covered surfaces assert the same headline family, tone, next-action label, preserved drill-down destination continuity, and diagnostics-secondary hierarchy for the same tenant state.
- Preserve existing `Compare now` confirmation, capability gating, and tenant-safe landing authorization behavior through explicit landing regression coverage.
- Add one request-scoped memoization test that renders a page with multiple consumers and proves a single stored governance aggregate exists for that tenant scope.
- Extend the Spec 167 consumer-adoption guard so the new family and consumer surfaces cannot regress back to local ad hoc caches or repeated findings-count queries.
- Preserve Livewire v4-compatible component tests and run the minimum focused Sail verification pack before implementation completion.
## Complexity Tracking
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| New derived runtime contract plus derived-state family | Four existing summary surfaces already share one operator posture family, and the repo already standardized request-local reuse for similar deterministic derived state | Per-widget hardening would preserve split semantic ownership and allow local findings queries or ad hoc caches to reappear |
## Proportionality Review
- **Current operator problem**: Tenant operators can already see overlapping dashboard cards, banners, and landing summaries that answer the same governance question through different logic paths, especially when no new drift exists but overdue or unhealthy governance still does.
- **Existing structure is insufficient because**: `BaselineCompareStats` already holds most of the needed truth, but no explicit summary contract owns the shared posture family. `NeedsAttention` still re-queries counts already derivable from compare stats, which keeps ownership split across surfaces.
- **Narrowest correct implementation**: Add one derived `TenantGovernanceAggregate` plus one resolver that builds from existing compare truth and reuses the existing request-scoped derived-state store.
- **Ownership cost created**: One new runtime DTO/resolver pair, one derived-state family declaration, one consumer guard extension, and a focused set of parity + memoization tests.
- **Alternative intentionally rejected**: Continuing to harden each widget or page independently was rejected because it would preserve multiple semantic owners and repeated queries. A persisted summary record or cross-request cache was rejected because the current-release need is request-time consistency only.
- **Release truth**: Current-release truth. The affected surfaces are already shipped and already overlap semantically.

View File

@ -0,0 +1,81 @@
# Quickstart: Tenant Governance Aggregate Contract
## Goal
Validate that one derived tenant-governance aggregate now drives the shared summary posture across the tenant dashboard, the tenant governance banner, and the Baseline Compare landing without adding persistence or reintroducing local findings-count ownership.
## Prerequisites
1. Start Sail.
2. Ensure a tenant exists with an assigned baseline profile and a consumable snapshot.
3. Seed compare-run scenarios for: no result yet, compare in progress, compare failed, trustworthy no-drift, stale no-drift, overdue findings without new drift, and lapsed governance without new drift.
4. Ensure the current user is a tenant member with access to the tenant dashboard and Baseline Compare landing.
## Implementation Validation Order
### 1. Run low-level compare and aggregate coverage
```bash
vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareStatsTest.php
vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareSummaryAssessmentTest.php
vendor/bin/sail artisan test --compact --filter=TenantGovernanceAggregate
```
Expected outcome:
- Existing compare truth still resolves the same availability and posture states.
- The new aggregate contract maps those states into one stable summary object without introducing a second query-backed truth path.
### 2. Run focused cross-surface parity coverage
```bash
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/NeedsAttentionWidgetTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareNowWidgetTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareCoverageBannerTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareLandingAdminTenantParityTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php
vendor/bin/sail artisan test --compact tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php
```
Expected outcome:
- `NeedsAttention`, `BaselineCompareNow`, `BaselineCompareCoverageBanner`, and the landing summary agree on posture family, headline, and next-action intent for the same tenant state.
- A tenant with zero visible drift but overdue or unhealthy governance still renders as action-needed on every covered surface.
- The landing keeps `Compare now` confirmation and capability gating unchanged, and diagnostics remain clearly secondary to the shared summary posture.
### 3. Run request-local reuse and guard coverage
```bash
vendor/bin/sail artisan test --compact --filter=TenantGovernanceAggregateMemoization
vendor/bin/sail artisan test --compact tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php
```
Expected outcome:
- One request stores one governance aggregate per tenant scope.
- Covered surfaces do not fall back to widget-local ad hoc caches or repeated local findings queries.
### 4. Format touched implementation files
```bash
vendor/bin/sail bin pint --dirty --format agent
```
Expected outcome:
- All touched implementation files conform to the repos Pint rules.
## Manual Smoke Check
1. Open `/admin/t/{tenant}` for a tenant with lapsed governance and no new drift findings.
2. Confirm the dashboard `Needs Attention` widget and `Baseline Governance` card both show action-needed posture.
3. Open `/admin/t/{tenant}/baseline-compare-landing` and confirm the landing summary agrees with the dashboard posture while still showing deeper diagnostics below.
4. Use a tenant with a trustworthy no-drift result and confirm the banner hides, the dashboard falls back to healthy checks, and the landing summary presents the same all-clear posture.
5. Use a tenant with a queued or running compare and confirm dashboard, banner, and landing all present progress-aware follow-up instead of stale “all clear” messaging.
6. Switch from one tenant to another and confirm the second tenant does not reuse the first tenants summary posture.
## Non-Goals For This Slice
- No database migration.
- No new Graph call or provider-contract work.
- No new assets or Filament panel registration change.
- No new mutation surface beyond the existing `Compare now` action, which remains unchanged.

View File

@ -0,0 +1,49 @@
# Phase 0 Research: Tenant Governance Aggregate Contract
## Decision: Build the shared contract from `BaselineCompareStats` and its summary assessment instead of creating a second query-backed summary path
**Rationale**: `BaselineCompareStats::forTenant()` already resolves baseline assignment, consumable snapshot availability, latest compare-run posture, findings visibility counts, and the governance-attention count family that this spec needs. `NeedsAttention` is the main surface still re-querying overdue, expiring, lapsed, and high-severity finding counts locally even though those values are already derivable from compare stats. Building the aggregate from `BaselineCompareStats` keeps one query-backed truth and avoids a second summary service that would drift.
**Alternatives considered**:
- Create a new persisted tenant-governance summary record: rejected because the current-release problem is request-time consistency, not independent lifecycle or historical reporting truth.
- Create a new query service that bypasses `BaselineCompareStats`: rejected because it would duplicate compare availability and attention logic that already exists.
## Decision: Introduce one narrow `TenantGovernanceAggregate` runtime contract instead of continuing to treat `BaselineCompareStats` as an implicit shared summary
**Rationale**: `BaselineCompareStats` is a broad compare-detail object that also carries diagnostics and landing-specific support data. The operator problem is narrower: multiple surfaces need one shared summary posture, count family, and next-action intent. A dedicated aggregate keeps that summary ownership explicit while allowing the landing page to keep deeper diagnostics in `BaselineCompareStats`.
**Alternatives considered**:
- Use `BaselineCompareStats` directly everywhere with no new contract: rejected because it would leave summary ownership implicit and make it easier for widgets to keep local business rules.
- Move every compare diagnostic into the new aggregate: rejected because it would bloat a summary contract into a second detail model.
## Decision: Reuse the existing request-scoped derived-state infrastructure from Spec 167
**Rationale**: The repo already binds `RequestScopedDerivedStateStore` in the Laravel container and uses it for request-local reuse of `ArtifactTruthPresenter`, `OperationUxPresenter`, and `RelatedNavigationResolver`. This feature needs the same boundary: one request-local derived result per deterministic question, explicit invalidation rules, and a guard path that prevents local ad hoc caches from coming back.
**Alternatives considered**:
- Add a static cache inside `NeedsAttention`, `BaselineCompareNow`, or `BaselineCompareCoverageBanner`: rejected because Spec 167 explicitly moved the codebase away from that pattern.
- Use `Cache::remember()` or another cross-request store: rejected because the spec requires request-local reuse only and stale cross-request posture would be harder to reason about.
## Decision: Keep next-action intent inside the aggregate, but keep final URLs and panel-specific drill-down mapping local to surfaces
**Rationale**: The semantic drift problem is not only conflicting counts; it is also conflicting operator follow-up. The aggregate must therefore answer the stable business question “what is the next action target category for this tenant state?” while leaving local surfaces free to map that answer to tenant-panel URLs, run links, or findings links appropriate to their context.
**Alternatives considered**:
- Store absolute URLs inside the aggregate: rejected because final URLs remain panel-aware and surface-local, and capability-gated destinations should stay local to the consuming surface.
- Leave next-action computation local to every widget or page: rejected because next-action drift is part of the problem this spec is supposed to solve.
## Decision: Keep `BaselineCompareLanding` as the home for diagnostics, but move its default-visible posture semantics onto the aggregate
**Rationale**: The spec explicitly distinguishes default-visible operator posture from diagnostics-only information. `BaselineCompareLanding` should still own evidence gaps, duplicate-name diagnostics, detailed compare context, and the existing `Compare now` action. What changes is that its primary posture zone should no longer be another local semantic owner.
**Alternatives considered**:
- Leave the landing page fully outside the aggregate: rejected because the landing page is one of the authoritative summary surfaces listed in the spec.
- Collapse the landing page into a pure aggregate view: rejected because operators still need compare diagnostics there.
## Decision: Protect the feature with parity, memoization, and guard tests rather than ad hoc performance scripts
**Rationale**: The highest-risk regressions are semantic drift, hidden local re-queries, and request-scope leakage. Focused Pest tests can assert those business truths directly, and the derived-state adoption guard can stop future surfaces from quietly reintroducing local caches or unsupported family access patterns.
**Alternatives considered**:
- Rely only on query counting or manual profiling: rejected because it would miss operator-visible drift and consumer-adoption regressions.
- Treat this as a pure unit-test problem: rejected because the spec is about cross-surface agreement and request behavior, which requires feature-level coverage too.

View File

@ -0,0 +1,202 @@
# Feature Specification: Tenant Governance Aggregate Contract
**Feature Branch**: `168-tenant-governance-aggregate-contract`
**Created**: 2026-03-28
**Status**: Draft
**Input**: User description: "Spec 168 — Tenant Governance Aggregate Contract"
## Spec Scope Fields *(mandatory)*
- **Scope**: tenant
- **Primary Routes**:
- `/admin/t/{tenant}` as the tenant dashboard where Baseline Governance and Needs Attention currently surface overlapping governance posture
- `/admin/t/{tenant}/baseline-compare-landing` as the tenant baseline-compare hub that owns compare posture, next action, and supporting diagnostics
- tenant-context governance banners and summary cards that surface baseline posture or governance attention inside the tenant panel
- **Data Ownership**:
- Tenant-owned: findings, finding-exception validity, overdue workflow state, and tenant-scoped compare-run visibility that together describe the tenant's current governance attention posture
- Workspace-owned but tenant-resolved: baseline assignment, baseline profile, effective baseline snapshot availability, and workspace-level prerequisites that shape tenant compare posture
- This feature introduces no new persisted tenant-governance record; the shared aggregate remains derived for one tenant at a time
- **RBAC**:
- Existing workspace membership and tenant entitlement remain required for every surface that consumes the aggregate
- Existing tenant inspection capabilities remain the gate for opening findings, baseline compare detail, and other drill-down destinations reached from the aggregate
- Existing compare-start authorization and confirmation rules remain unchanged for the Baseline Compare landing action
## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)*
| Surface | Primary Persona | Surface Type | Primary Operator Question | Default-visible Information | Diagnostics-only Information | Status Dimensions Used | Mutation Scope | Primary Actions | Dangerous Actions |
|---|---|---|---|---|---|---|---|---|---|
| Tenant dashboard `Needs Attention` | Tenant operator | Summary widget | What needs action right now across governance and baseline posture? | Overdue findings, lapsed governance, expiring governance, high-severity active findings, baseline-posture summary | Deep reason codes, raw compare diagnostics, low-level evidence gaps, run internals | governance attention, due urgency, compare posture, severity urgency | Read-only summary with drill-down navigation | Review dashboard attention items, open related destination | None |
| Tenant dashboard `Baseline Governance` card | Tenant operator | Summary card | Can I trust the latest baseline posture, and what should I do next? | Aggregate headline, supporting message, next action, visible drift count, high-severity count, last compared label | Deep coverage details, duplicate-name stats, evidence-gap drill-down, run diagnostics | compare freshness, compare outcome, governance attention, trustworthiness | Read-only summary with drill-down navigation | Open findings, open run, open Baseline Compare | None |
| Baseline Compare landing | Tenant operator | Landing page | What is the tenant's current baseline governance posture, and should I compare now or investigate detail? | Aggregate posture, assignment or snapshot availability, findings attention, next action, compare availability | Coverage detail, evidence-gap detail, duplicate-name diagnostics, low-level run reason detail | compare availability, compare freshness, compare outcome, governance attention, coverage limits | Existing compare action unchanged; page state itself is read-focused | Review posture, open findings, start `Compare now`, open run detail | No new dangerous action; existing `Compare now` remains confirmation-gated and capability-gated |
| Tenant governance banner | Tenant operator | Inline warning banner | Is there a governance or compare limitation I should not miss on this screen? | Shared aggregate headline, supporting message, next action intent, warning tone | Full compare diagnostics and detailed count breakdowns | compare caution or stale state, governance attention, next action intent | Read-only summary with drill-down navigation | Follow next action to findings, run detail, or Baseline Compare | None |
## Proportionality Review *(mandatory when structural complexity is introduced)*
- **New source of truth?**: No. Findings, exception validity, baseline assignment, snapshot availability, and compare-run truth remain the source data.
- **New persisted entity/table/artifact?**: No. The aggregate is derived and request-scoped.
- **New abstraction?**: Yes. This feature introduces one explicit tenant-scoped aggregate contract for governance summary state that multiple surfaces share.
- **New enum/state/reason family?**: No. Existing compare posture, governance validity, and attention semantics remain the source vocabulary.
- **New cross-domain UI framework/taxonomy?**: No. The work consolidates one summary family; it does not create a new presentation framework.
- **Current operator problem**: Operators can see overlapping tenant-governance cards and pages that recompute similar facts independently, which makes counts, headlines, and next-action guidance harder to trust and more expensive to keep aligned.
- **Existing structure is insufficient because**: The current structure lets baseline compare posture live in one shared path while overdue, expiring, and lapsed governance attention can still be owned locally by individual widgets or banners. That fragmentation means no single contract is accountable for the tenant's shared governance summary.
- **Narrowest correct implementation**: Introduce one derived tenant-scoped governance aggregate that absorbs the overlapping summary facts already reused across landing, dashboard, and banner surfaces, while leaving presentation mapping local to each surface.
- **Ownership cost**: The codebase takes on one explicit shared contract plus cross-surface regression tests and request-reuse guarantees, but removes duplicated query ownership and semantic drift from each consuming surface.
- **Alternative intentionally rejected**: Continuing to harden each widget or page independently was rejected because it preserves duplicate ownership. Adding a persisted summary record or cross-request cache was rejected because current-release needs do not require a new durable truth source.
- **Release truth**: Current-release truth. The overlap already exists on shipped tenant-governance surfaces and is growing with ongoing governance work.
## User Scenarios & Testing *(mandatory)*
### User Story 1 - One Tenant, One Governance Posture (Priority: P1)
As a tenant operator, I want the dashboard, banner, and baseline-compare landing to agree on what needs action, so that I do not have to reconcile conflicting counts or messages before deciding what to do next.
**Why this priority**: Trust in the product's governance posture depends on cross-surface consistency. Conflicting summary signals create operator hesitation and support debt.
**Independent Test**: Can be fully tested by seeding one tenant with baseline-compare posture and governance-attention states, then rendering at least three covered surfaces and verifying that the same tenant state produces the same underlying counts, posture family, and next-action intent.
**Acceptance Scenarios**:
1. **Given** a tenant has no visible drift findings but has lapsed accepted-risk governance, **When** an authorized operator opens the dashboard and the baseline-compare landing, **Then** both surfaces present the tenant as needing attention rather than as an all-clear.
2. **Given** a tenant has overdue open findings and expiring governance, **When** multiple tenant-governance surfaces render in the same session, **Then** they expose consistent overdue and governance-attention meaning for that tenant.
3. **Given** a tenant has a trustworthy compare result with no findings and no governance-attention conditions, **When** the operator opens covered summary surfaces, **Then** those surfaces consistently present a healthy posture rather than mixed healthy and warning states.
---
### User Story 2 - Consistent Next Action Across Summary Surfaces (Priority: P1)
As a tenant operator, I want each governance summary surface to point me toward the same next step for the same tenant state, so that I can act quickly without guessing which surface is authoritative.
**Why this priority**: A shared aggregate is only useful if it produces not just aligned counts, but aligned operator action.
**Independent Test**: Can be fully tested by exercising compare-in-progress, failed-compare, overdue-findings, and governance-lapsed scenarios and verifying that each covered surface routes the operator toward the same class of next action for the same state.
**Acceptance Scenarios**:
1. **Given** a baseline compare is currently running, **When** the operator opens the dashboard card, banner, and landing page, **Then** each surface points to progress-aware follow-up instead of mixing stale completion guidance with active-run guidance.
2. **Given** a tenant needs attention because overdue or lapsed governance states remain, **When** the operator opens any aggregate-consuming summary surface, **Then** the primary follow-up action remains aligned with reviewing findings rather than presenting unrelated compare guidance.
3. **Given** a tenant lacks a usable baseline compare result because no assignment or no snapshot is available, **When** summary surfaces render, **Then** they consistently communicate availability or prerequisite guidance instead of one surface appearing healthy while another appears unavailable.
---
### User Story 3 - Stable Multi-Card Tenant Summary (Priority: P2)
As a tenant operator, I want a page that shows multiple governance cards to stay stable for my current tenant, so that repeated summary cards do not disagree or flicker between different tenant-governance interpretations.
**Why this priority**: The immediate product problem is not only semantic drift over time but duplicate ownership inside one page render.
**Independent Test**: Can be fully tested by rendering a tenant page that includes more than one aggregate-consuming governance surface and verifying that the same tenant request produces one stable posture family and one stable set of governance-attention counts.
**Acceptance Scenarios**:
1. **Given** a tenant dashboard renders both a governance card and a needs-attention summary, **When** the page loads, **Then** both surfaces reflect the same tenant posture and compatible next-step guidance.
2. **Given** the operator switches from one tenant to another, **When** the new tenant page renders, **Then** the summary state resets to the new tenant and does not reuse the previous tenant's governance posture.
3. **Given** no tenant is selected, **When** a tenant-governance surface is reached indirectly, **Then** it shows the appropriate empty or unavailable state and does not leak another tenant's summary.
### Edge Cases
- A tenant has zero open drift findings, but overdue findings, expiring governance, or lapsed governance still exist; all aggregate-consuming attention surfaces must continue to present action-needed posture.
- A tenant has baseline assignment but no consumable snapshot or no completed compare result yet; covered surfaces must stay consistent about availability and prerequisites.
- A compare run is queued or running while older compare-derived counts still exist; summary surfaces must present progress-aware posture instead of mixing active-run and completed-run claims.
- A single request renders multiple governance summary surfaces for one tenant; the request must not produce contradictory counts or posture labels because different surfaces recomputed the same attention family separately.
- A tenant switch or no-tenant context occurs between requests; request-local reuse must not carry governance summary state across tenant boundaries.
- A surface still needs local diagnostics beyond the shared aggregate; those diagnostics must remain secondary and must not redefine the shared attention semantics.
## Requirements *(mandatory)*
**Constitution alignment (required):** This feature introduces no new Microsoft Graph contract, no new long-running job type, and no new persisted artifact. It consolidates existing tenant-governance summary truth from current compare posture, findings attention, and governance validity into one shared derived contract. Existing compare operations and Monitoring observability remain unchanged.
**Constitution alignment (PROP-001 / ABSTR-001 / PERSIST-001 / STATE-001 / BLOAT-001):** This feature introduces one narrow abstraction: a shared tenant-governance aggregate contract. It does so because existing tenant surfaces already duplicate overlapping summary state and a narrower per-surface hardening would preserve split ownership. The contract remains derived, current-release, and intentionally avoids new persistence, new state families, or a cross-domain semantic framework.
**Constitution alignment (OPS-UX):** No new `OperationRun` type is introduced. Existing baseline-compare runs remain the only operational execution path involved, and their queued, running, failed, or completed visibility remains governed by the existing Ops-UX contract.
**Constitution alignment (RBAC-UX):** The feature stays entirely in the tenant/admin plane on tenant-context surfaces. It does not introduce new authorization behavior. Non-members remain deny-as-not-found, in-scope members without the required capability remain forbidden for existing compare-start or drill-down actions, and shared aggregate reuse must remain tenant-scoped so no cross-tenant summary leakage is possible.
**Constitution alignment (OPS-EX-AUTH-001):** Not applicable. No authentication flow is changed.
**Constitution alignment (BADGE-001):** Existing centralized badge and tone semantics for findings severity, governance validity, and compare posture remain the semantic source. This feature may make those semantics appear on more than one surface through the aggregate, but it must not introduce ad hoc per-surface status vocabularies.
**Constitution alignment (UI-FIL-001):** The feature reuses native Filament widgets, sections, links, and badges already present on the dashboard, landing page, and banner surfaces. It should consolidate the shared semantic source rather than introducing page-local markup or a new local visual language for warning states.
**Constitution alignment (UI-NAMING-001):** Operator-facing terms remain baseline governance, needs attention, baseline compare, compare now, and open findings. The feature must preserve the same domain vocabulary across dashboard cards, landing copy, banner messaging, and drill-down affordances so operators do not see one surface talk about attention while another describes the same state as healthy posture.
**Constitution alignment (OPSURF-001):** This feature materially refactors operator-facing summary surfaces. Default-visible information must remain operator-first: posture, urgency, and next action appear first, while diagnostics remain secondary. Mutation scope remains unchanged: read-only summary surfaces stay read-only, and the existing `Compare now` action continues to communicate its existing compare execution scope.
**Constitution alignment (UI-SEM-001 / LAYER-001 / TEST-TRUTH-001):** A shared aggregate is justified because direct per-surface mapping has already produced redundant truth and semantic drift. The aggregate must replace duplicate per-surface summary ownership rather than layering yet another presenter or wrapper on top of it. Tests must assert business truth across surfaces and request scope, not only thin adapter wiring.
**Constitution alignment (Filament Action Surfaces):** This feature modifies Filament pages and widgets in the tenant panel. The Action Surface Contract remains satisfied because the summary surfaces are read-only and the only existing mutation surface involved, Baseline Compare landing, keeps explicit confirmation and capability gating for compare start. UI-FIL-001 is satisfied because no exception to native Filament summary or action primitives is required.
**Constitution alignment (UX-001 — Layout & Information Architecture):** The feature does not add new create or edit screens. It changes summary and landing semantics on existing tenant surfaces. The landing page must keep operator posture and next-action messaging above diagnostics, and widgets or banners must keep attention content concise, explicit, and drill-down oriented rather than becoming diagnostic walls.
### Functional Requirements
- **FR-168-001**: The system MUST provide one tenant-scoped governance aggregate for the currently selected tenant that combines the summary state already shared across tenant governance cards, banners, and baseline-compare summary surfaces.
- **FR-168-002**: The tenant-governance aggregate MUST include, at minimum, compare availability or progress state, compare outcome or freshness posture, compare trust-limiting signals relevant to summary posture, visible drift findings count, overdue open findings count, expiring governance count, lapsed governance count, active non-new findings count, and high-severity active findings count.
- **FR-168-003**: At least three existing tenant-facing summary surfaces MUST consume the same tenant-governance aggregate contract.
- **FR-168-004**: Aggregate-consuming surfaces MUST treat the shared aggregate as the semantic owner for overdue findings, expiring governance, lapsed governance, and tenant-level baseline posture, and MUST NOT define conflicting local business rules for those states.
- **FR-168-005**: Aggregate-consuming surfaces MAY keep local layout, wording emphasis, and navigation affordances appropriate to their context, but they MUST preserve the same underlying posture family, counts, and next-action intent for the same tenant state.
- **FR-168-006**: A tenant with zero visible drift findings but any overdue open findings, expiring governance, or lapsed governance MUST still render as needing attention on every aggregate-consuming attention surface.
- **FR-168-007**: A tenant with no baseline assignment, no usable snapshot, no current compare result, an in-progress compare, a failed compare, a stale compare result, or a trustworthy all-clear result MUST resolve to one consistent tenant-governance posture across all aggregate-consuming surfaces.
- **FR-168-008**: Repeated reads of the same tenant-governance aggregate during one request MUST reuse the same derived result instead of recomputing aggregate-owned counts separately for each consuming surface.
- **FR-168-009**: Request-local aggregate reuse MUST remain scoped to the current tenant context and MUST NOT leak summary state across tenants, workspaces, or no-tenant states.
- **FR-168-010**: The initial implementation MUST remain derived-only and MUST NOT require a new persisted summary record, a new cross-request cache, or a new dashboard setup step.
- **FR-168-011**: Existing compare-start actions, findings drill-downs, and baseline-compare navigation destinations MUST remain available, and this feature MUST NOT broaden or weaken their existing RBAC and confirmation behavior.
- **FR-168-012**: If a covered surface needs diagnostics beyond the shared aggregate, those diagnostics MUST remain secondary and MUST NOT redefine the shared attention semantics already owned by the aggregate.
- **FR-168-013**: The feature MUST stay bounded to one tenant at a time and MUST NOT expand this aggregate into cross-tenant portfolio posture, new governance workflow semantics, or a full dashboard redesign.
- **FR-168-014**: Regression coverage MUST verify semantic consistency across aggregate-consuming surfaces for at least these tenant states: unavailable prerequisites, compare in progress, compare failed, open findings requiring action, overdue findings without new drift, lapsed governance without new drift, caution or stale compare posture, and trustworthy all-clear.
- **FR-168-015**: Regression coverage MUST verify that a single page render containing multiple aggregate-consuming surfaces does not re-own overdue, expiring, or lapsed counts in parallel and remains stable for the current tenant context.
## UI Action Matrix *(mandatory when Filament is changed)*
| Surface | Location | Header Actions | Inspect Affordance (List/Table) | Row Actions (max 2 visible) | Bulk Actions (grouped) | Empty-State CTA(s) | View Header Actions | Create/Edit Save+Cancel | Audit log? | Notes / Exemptions |
|---|---|---|---|---|---|---|---|---|---|---|
| Baseline Compare landing | `app/Filament/Pages/BaselineCompareLanding.php` | Existing `Compare now` action remains in the header | Not a record list surface | None | None | Existing prerequisite and unavailable messaging remains | `Compare now` only | N/A | Existing compare start remains observable through `OperationRun`; no new audit surface added here | This spec changes posture ownership and copy consistency, not the action inventory |
| Tenant dashboard `Needs Attention` widget | `app/Filament/Widgets/Dashboard/NeedsAttention.php` | None | N/A | None | None | Healthy state remains a read-only reassurance surface | N/A | N/A | No | Read-only summary widget; covered because it currently owns overlapping attention counts |
| Tenant dashboard `Baseline Governance` card | `app/Filament/Widgets/Dashboard/BaselineCompareNow.php` | None | N/A | None | None | Existing no-assignment state remains a read-only empty state | N/A | N/A | No | Read-only summary card; next-action links remain navigation only |
| Tenant governance banner | `app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php` | None | N/A | None | None | Banner simply hides when not relevant | N/A | N/A | No | Read-only warning banner; included because it must consume the shared aggregate family |
### Key Entities *(include if feature involves data)*
- **Tenant governance aggregate**: A derived tenant-scoped summary that combines compare posture, governance-attention counts, and next-action intent for operator-facing summary surfaces.
- **Baseline compare posture**: The tenant's current compare availability, freshness, outcome, and trustworthiness summary.
- **Governance attention summary**: The tenant's actionable counts for overdue findings, expiring governance, lapsed governance, and other active finding pressure that should influence summary posture.
- **Aggregate-consuming surface**: Any tenant-facing card, widget, banner, or landing summary that reads the shared aggregate and applies only local presentation mapping.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-168-001**: In seeded regression coverage, at least three tenant-governance summary surfaces display identical overdue, expiring, and lapsed-governance counts for the same tenant in 100% of tested scenarios.
- **SC-168-002**: In seeded regression coverage, tenants with zero visible drift findings but overdue or unhealthy governance still render as action-needed on every tested aggregate-consuming attention surface.
- **SC-168-003**: In operator acceptance review, a tenant operator can determine the current governance posture and next action from either the dashboard or baseline-compare landing within 10 seconds.
- **SC-168-004**: In regression coverage, a single page that renders multiple aggregate-consuming surfaces for one tenant shows no contradictory posture family, tone, or next-action combination within the same load.
- **SC-168-005**: The feature ships without requiring any new setup step, scheduled refresh step, or durable summary artifact for operators to see the shared tenant-governance posture.
## Assumptions
- Existing findings workflow truth, finding-exception validity truth, and baseline-compare posture truth remain sufficient to derive the shared tenant-governance aggregate.
- Existing tenant dashboard and baseline-compare surfaces remain in place; this spec consolidates their summary contract rather than replacing the whole tenant-governance UI.
- Existing tenant-entitlement and compare-start authorization rules remain correct and do not need separate RBAC redesign in this slice.
## Non-Goals
- Building a cross-tenant portfolio governance aggregate or workspace-wide control tower summary for this data family
- Introducing a new persisted summary table, cache artifact, or reporting export just to support shared summary posture
- Redefining findings workflow semantics, exception validity semantics, or compare reason-code semantics
- Redesigning the entire tenant dashboard or baseline-compare landing beyond the shared-governance summary family
## Dependencies
- Existing baseline assignment, snapshot availability, and compare-run truth
- Existing findings and finding-exception governance-attention derivation
- Existing tenant dashboard widgets, baseline-compare landing surface, and tenant governance banner surfaces
- Existing tenant-context RBAC and drill-down destinations for findings and operation runs
## Definition of Done
Spec 168 is complete when:
- one tenant-scoped governance aggregate owns the overlapping summary family used by at least three tenant-facing governance surfaces,
- dashboard, landing, and banner-style surfaces no longer contradict one another about overdue, expiring, lapsed, or compare-posture state for the same tenant,
- request-local reuse of the aggregate is testable and tenant-safe,
- no new persisted summary truth or cross-request cache is required,
- and the covered surfaces remain operator-first while keeping local presentation responsibility separate from shared business semantics.

View File

@ -0,0 +1,217 @@
# Tasks: Tenant Governance Aggregate Contract
**Input**: Design documents from `/specs/168-tenant-governance-aggregate-contract/`
**Prerequisites**: `plan.md` (required), `spec.md` (required for user stories), `research.md`, `data-model.md`, `contracts/`, `quickstart.md`
**Tests**: Tests are REQUIRED for this feature. Use Pest coverage in `tests/Feature/Baselines/BaselineCompareStatsTest.php`, `tests/Feature/Baselines/BaselineCompareSummaryAssessmentTest.php`, `tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php`, `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingAdminTenantParityTest.php`, `tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, `tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php`, `tests/Feature/Filament/NeedsAttentionWidgetTest.php`, `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php`, and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php`.
**Operations**: This feature does not create a new `OperationRun` type or change run lifecycle ownership. Existing baseline-compare runs remain the only execution surface involved, and all work here is read-time summary consolidation.
**RBAC**: Existing tenant-context membership, entitlement, and 404 vs 403 semantics remain unchanged. Tasks must preserve current tenant-safe drill-down behavior and ensure request-local reuse never leaks summary state across tenants, workspaces, or no-tenant states.
**Operator Surfaces**: The tenant dashboard `Baseline Governance` card, tenant dashboard `Needs Attention` widget, tenant governance banner, and Baseline Compare landing must keep operator-first posture, urgency, and next-step guidance above diagnostics.
**Filament UI Action Surfaces**: No new action inventories are added. The existing Baseline Compare landing `Compare now` action remains confirmation-gated and capability-gated, and all other affected surfaces remain navigation-only summaries.
**Filament UI UX-001**: No new create, edit, or view layouts are introduced. Existing widget, banner, and landing layouts remain intact while shared summary ownership is refactored.
**Badges**: Existing compare-posture, severity, and governance-validity semantics must remain sourced from shared badge semantics; no new page-local mappings are introduced.
**Organization**: Tasks are grouped by user story so each story can be implemented and verified as an independent increment after the shared aggregate contract is in place.
## Phase 1: Setup (Shared Aggregate Scaffolding)
**Purpose**: Create the narrow runtime and test scaffolding required for the tenant-governance aggregate.
- [X] T001 [P] Create the aggregate runtime scaffolding in `app/Support/Baselines/TenantGovernanceAggregate.php` and `app/Support/Baselines/TenantGovernanceAggregateResolver.php`
- [X] T002 [P] Create the focused regression scaffolding in `tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php` and `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php`
---
## Phase 2: Foundational (Blocking Aggregate Contract)
**Purpose**: Build the shared aggregate runtime and request-scoped family contract that all user stories depend on.
**⚠️ CRITICAL**: No user story work should begin until this phase is complete.
- [X] T003 [P] Extend source-truth regression coverage for aggregate input counts and summary assessment mapping in `tests/Feature/Baselines/BaselineCompareStatsTest.php` and `tests/Feature/Baselines/BaselineCompareSummaryAssessmentTest.php`
- [X] T004 Implement the derived tenant summary contract fields in `app/Support/Baselines/TenantGovernanceAggregate.php`
- [X] T005 Implement aggregate resolution and request-scoped reuse from `BaselineCompareStats` and `BaselineCompareSummaryAssessment` in `app/Support/Baselines/TenantGovernanceAggregateResolver.php` and `app/Support/Baselines/BaselineCompareStats.php`
- [X] T006 [P] Declare the governance aggregate derived-state family, extend the first-slice supported consumer contract, and update the guard in `app/Support/Ui/DerivedState/DerivedStateFamily.php`, `specs/167-derived-state-memoization/contracts/request-scoped-derived-state.logical.openapi.yaml`, and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php`
**Checkpoint**: The tenant-governance aggregate exists as one derived request-local contract that later surface work can consume.
---
## Phase 3: User Story 1 - One Tenant, One Governance Posture (Priority: P1)
**Goal**: Make the dashboard governance card, tenant banner, and Baseline Compare landing agree on posture family and governance-attention counts for the same tenant.
**Independent Test**: Seed one tenant with unavailable prerequisites, compare in progress, compare failed, open findings requiring action, overdue without new drift, lapsed governance without new drift, caution, stale results, and trustworthy all-clear states, then verify the dashboard governance card, banner, and landing summary resolve the same posture family and count family while keeping landing diagnostics secondary.
### Tests for User Story 1
- [X] T007 [P] [US1] Add aggregate scenario coverage for unavailable, in-progress, failed, open-findings action-required, overdue-without-new-drift, lapsed-without-new-drift, caution, stale, and trustworthy-all-clear states in `tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php`
- [X] T008 [P] [US1] Extend cross-surface posture and count parity assertions for the full FR-168-014 state matrix, landing diagnostics-secondary hierarchy, and unchanged compare-start authorization and confirmation semantics in `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, `tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php`, `tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php`, and `tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php`
### Implementation for User Story 1
- [X] T009 [US1] Route the tenant dashboard `Baseline Governance` summary card through the shared aggregate in `app/Filament/Widgets/Dashboard/BaselineCompareNow.php`
- [X] T010 [US1] Drive the tenant governance banner from the shared aggregate in `app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php`
- [X] T011 [US1] Replace the Baseline Compare landing default-visible posture summary with the shared aggregate while keeping diagnostics on `BaselineCompareStats`, preserving existing `Compare now` confirmation and capability semantics, and keeping diagnostics secondary in `app/Filament/Pages/BaselineCompareLanding.php`
- [X] T012 [US1] Keep aggregate posture, tone, and supporting-message semantics aligned to existing compare-summary rules in `app/Support/Baselines/BaselineCompareSummaryAssessor.php` and `app/Support/Baselines/BaselineCompareSummaryAssessment.php`
- [X] T013 [US1] Run the focused posture parity pack in `tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php`, `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, `tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php`, `tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php`, and `tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php`
**Checkpoint**: Three tenant-facing summary surfaces now share one governance posture and count contract for the same tenant state.
---
## Phase 4: User Story 2 - Consistent Next Action Across Summary Surfaces (Priority: P1)
**Goal**: Make every covered summary surface point operators toward the same class of next step for the same tenant state.
**Independent Test**: Seed running-compare, failed-compare, unavailable-prerequisite, open-findings requiring action, overdue-without-new-drift, lapsed-governance without new drift, caution, and stale scenarios, then verify the dashboard governance card, banner, and landing summary expose the same next-action intent and matching operator-facing labels.
### Tests for User Story 2
- [X] T014 [P] [US2] Add next-action intent regressions for running, failed, unavailable, open-findings action-required, overdue-without-new-drift, lapsed-without-new-drift, caution, and stale scenarios in `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, and `tests/Feature/Filament/BaselineCompareLandingAdminTenantParityTest.php`
- [X] T015 [P] [US2] Add dashboard governance card and banner next-step assertions, including preserved findings drill-down and open-landing navigation availability, in `tests/Feature/Filament/BaselineCompareNowWidgetTest.php` and `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`
### Implementation for User Story 2
- [X] T016 [US2] Add next-action label and target ownership to the aggregate contract in `app/Support/Baselines/TenantGovernanceAggregate.php` and `app/Support/Baselines/TenantGovernanceAggregateResolver.php`
- [X] T017 [US2] Map shared next-action intent to findings, run, and landing destinations in `app/Filament/Widgets/Dashboard/BaselineCompareNow.php`
- [X] T018 [US2] Align banner and landing next-action presentation to the shared intent in `app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php` and `app/Filament/Pages/BaselineCompareLanding.php`
- [X] T019 [US2] Run the focused next-action pack in `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, and `tests/Feature/Filament/BaselineCompareLandingAdminTenantParityTest.php`
**Checkpoint**: Covered summary surfaces no longer disagree about whether the operator should inspect findings, watch a run, open the landing page, or take no action.
---
## Phase 5: User Story 3 - Stable Multi-Card Tenant Summary (Priority: P2)
**Goal**: Keep multiple governance cards on the same tenant page stable by reusing one request-local aggregate and removing duplicate local findings-count ownership.
**Independent Test**: Render the tenant dashboard with both `Needs Attention` and `Baseline Governance` visible, verify both surfaces stay consistent for the same tenant in one request, then switch tenants or remove tenant context and verify no stale summary leaks.
### Tests for User Story 3
- [X] T020 [P] [US3] Add request-local reuse, tenant-switch, and no-tenant safety coverage in `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php`
- [X] T021 [P] [US3] Extend multi-card dashboard stability and no-local-requery coverage in `tests/Feature/Filament/NeedsAttentionWidgetTest.php` and `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`
### Implementation for User Story 3
- [X] T022 [US3] Harden tenant-switch, workspace-scope, and no-tenant key behavior for the second dashboard summary consumer in `app/Support/Ui/DerivedState/DerivedStateFamily.php` and `app/Support/Baselines/TenantGovernanceAggregateResolver.php`
- [X] T023 [US3] Replace local overdue, expiring, lapsed, and high-severity findings ownership with the shared aggregate in `app/Filament/Widgets/Dashboard/NeedsAttention.php`
- [X] T024 [US3] Extend governance aggregate consumer declarations and no-local-requery guard coverage to include `NeedsAttention` in `specs/167-derived-state-memoization/contracts/request-scoped-derived-state.logical.openapi.yaml` and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php`
- [X] T025 [US3] Run the focused memoization and guard pack in `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php`, `tests/Feature/Filament/NeedsAttentionWidgetTest.php`, and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php`
**Checkpoint**: The tenant dashboard can render multiple governance summary surfaces in one request without contradictory counts, posture drift, or tenant leakage.
---
## Phase 6: Polish & Cross-Cutting Concerns
**Purpose**: Final copy alignment, formatting, and focused verification across all stories.
- [X] T026 [P] Align operator-facing copy and next-step labels in `app/Filament/Widgets/Dashboard/BaselineCompareNow.php`, `app/Filament/Widgets/Dashboard/NeedsAttention.php`, `app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php`, and `app/Filament/Pages/BaselineCompareLanding.php`
- [X] T027 Run formatting for touched implementation files with `vendor/bin/sail bin pint --dirty --format agent` using `specs/168-tenant-governance-aggregate-contract/quickstart.md`
- [X] T028 Run the final focused verification pack from `specs/168-tenant-governance-aggregate-contract/quickstart.md` against `tests/Feature/Baselines/BaselineCompareStatsTest.php`, `tests/Feature/Baselines/BaselineCompareSummaryAssessmentTest.php`, `tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php`, `tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php`, `tests/Feature/Filament/BaselineCompareNowWidgetTest.php`, `tests/Feature/Filament/BaselineCompareCoverageBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingAdminTenantParityTest.php`, `tests/Feature/Filament/BaselineCompareLandingDuplicateNamesBannerTest.php`, `tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php`, `tests/Feature/Filament/BaselineCompareLandingStartSurfaceTest.php`, `tests/Feature/Filament/BaselineCompareLandingWhyNoFindingsTest.php`, `tests/Feature/Filament/NeedsAttentionWidgetTest.php`, `tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php`, and `tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php`
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: Starts immediately and creates the narrow aggregate runtime and test scaffolding.
- **Foundational (Phase 2)**: Depends on Setup and blocks all user stories until the aggregate contract and request-scoped family are in place.
- **User Story 1 (Phase 3)**: Starts after Foundational and delivers the MVP shared-posture slice across three surfaces.
- **User Story 2 (Phase 4)**: Starts after User Story 1 because it refines the same summary surfaces with explicit next-action intent.
- **User Story 3 (Phase 5)**: Starts after User Story 2 because it adopts the second dashboard summary surface only after shared next-action semantics and first-slice parity are settled.
- **Polish (Phase 6)**: Starts after all desired user stories are complete and ends with focused verification.
### User Story Dependencies
- **User Story 1 (P1)**: Depends only on the aggregate contract and request-scoped family from Phase 2.
- **User Story 2 (P1)**: Depends on User Story 1 because the same summary surfaces must already read the shared aggregate before their next-action mapping can be aligned.
- **User Story 3 (P2)**: Depends on the aggregate contract from Phase 2 plus the settled shared posture and next-action semantics from User Stories 1 and 2 before the second dashboard consumer joins the shared contract.
### Within Each User Story
- Story tests should be written before or alongside the relevant implementation tasks and must fail before the story is considered complete.
- Aggregate contract changes should land before surface adoption in the same story.
- Surface refactors should land before the focused story-level regression run.
### Parallel Opportunities
- `T001` and `T002` can run in parallel during Setup.
- `T003` and `T006` can run in parallel during Foundational work.
- `T007` and `T008` can run in parallel for User Story 1.
- `T014` and `T015` can run in parallel for User Story 2.
- `T020` and `T021` can run in parallel for User Story 3.
- After `T022`, `T023` and `T024` can run in parallel because they change different files.
---
## Parallel Example: User Story 1
```bash
# User Story 1 tests in parallel:
Task: T007 tests/Feature/Baselines/TenantGovernanceAggregateResolverTest.php
Task: T008 tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php
# User Story 1 surface adoption split after aggregate semantics are fixed:
Task: T009 app/Filament/Widgets/Dashboard/BaselineCompareNow.php
Task: T010 app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php
```
## Parallel Example: User Story 2
```bash
# User Story 2 tests in parallel:
Task: T014 tests/Feature/Filament/BaselineCompareSummaryConsistencyTest.php
Task: T015 tests/Feature/Filament/BaselineCompareNowWidgetTest.php
# User Story 2 implementation split after next-action ownership lands:
Task: T017 app/Filament/Widgets/Dashboard/BaselineCompareNow.php
Task: T018 app/Filament/Widgets/Tenant/BaselineCompareCoverageBanner.php and app/Filament/Pages/BaselineCompareLanding.php
```
## Parallel Example: User Story 3
```bash
# User Story 3 tests in parallel:
Task: T020 tests/Feature/Filament/TenantGovernanceAggregateMemoizationTest.php
Task: T021 tests/Feature/Filament/NeedsAttentionWidgetTest.php
# User Story 3 implementation split after request-scoped keying is settled:
Task: T023 app/Filament/Widgets/Dashboard/NeedsAttention.php
Task: T024 tests/Feature/Guards/DerivedStateConsumerAdoptionGuardTest.php and specs/167-derived-state-memoization/contracts/request-scoped-derived-state.logical.openapi.yaml
```
---
## Implementation Strategy
### MVP First
1. Complete Phase 1: Setup.
2. Complete Phase 2: Foundational.
3. Complete Phase 3: User Story 1.
4. Validate that the dashboard governance card, tenant banner, and landing summary now share one posture and count contract.
### Incremental Delivery
1. Add User Story 2 to align next-action guidance once shared posture parity is proven.
2. Add User Story 3 to bring the second dashboard card onto the same contract and lock in request-local stability.
3. Finish with copy alignment, formatting, and the focused verification pack.
### Parallel Team Strategy
1. One developer can complete Phase 1 and Phase 2 while another prepares the story tests.
2. After User Story 1 lands, one developer can handle User Story 2 next-action adoption while another prepares User Story 3 memoization and guard coverage.
3. Rejoin for Phase 6 to run Pint and the focused verification pack.
---
## Notes
- `[P]` tasks target different files with no direct dependency on unfinished code in the same phase.
- `[US1]`, `[US2]`, and `[US3]` labels map tasks directly to the feature specification user stories.
- The suggested MVP scope is Phase 1 through Phase 3 only.
- No task in this plan introduces new persistence, a new Graph contract, a new Filament panel/provider registration, or a new destructive action.