Compare commits

..

2 Commits

Author SHA1 Message Date
bb72a54e84 Refactor: remove compare job legacy drift path (#235)
## Summary
- remove the dead legacy drift-computation path from `CompareBaselineToTenantJob` so the strategy-driven compare engine is the only execution path left in the orchestration file
- tighten compare guard and regression coverage around strategy selection, strategy execution context, findings, gaps, and no-drift outcomes
- fix the repo-wide suite blockers uncovered during validation by making the governance taxonomy registry test-double compatible and aligning the capture capability guard test with current unsupported-scope behavior
- add the Spec 205 planning artifacts and mark the implementation tasks complete

## Verification
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests --stop-on-failure`
  - result: `3659 passed, 8 skipped (21016 assertions)`
- browser smoke test passed on the Baseline Compare landing surface via the local smoke-login flow

## Notes
- no Filament resource, panel, global search, destructive action, or asset registration behavior was changed
- provider registration remains unchanged in `apps/platform/bootstrap/providers.php`
- the compare path remains strategy-driven and Livewire v4 / Filament v5 assumptions are unchanged

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #235
2026-04-14 21:54:37 +00:00
ad16eee591 Spec 204: harden platform core vocabulary (#234)
## Summary
- add the Spec 204 platform vocabulary foundation, including canonical glossary terms, registry ownership descriptors, canonical operation type and alias resolution, and explicit reason ownership and platform reason-family metadata
- harden platform-facing compare, snapshot, evidence, monitoring, review, and reporting surfaces so they prefer governed-subject and canonical operation semantics while preserving intentional Intune-owned terminology
- extend Spec 204 unit, feature, Filament, and architecture coverage and add the full spec artifacts, checklist, and completed task ledger

## Verification
- ran the focused recent-change Sail verification pack for the new glossary and reason-semantics work
- ran the full Spec 204 quickstart verification pack under Sail
- ran `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- ran an integrated-browser smoke pass covering tenant dashboard, operations, operation detail, baseline compare, evidence, reviews, review packs, provider connections, inventory items, backup schedules, onboarding, and the system dashboard/operations/failures/run-detail surfaces

## Notes
- provider registration is unchanged and remains in `bootstrap/providers.php`
- no new destructive actions or asset-registration changes are introduced by this branch

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #234
2026-04-14 06:09:42 +00:00
19 changed files with 1198 additions and 882 deletions

View File

@ -184,6 +184,8 @@ ## Active Technologies
- PostgreSQL via existing baseline snapshots, baseline snapshot items, `operation_runs`, findings, and baseline scope JSON; no new top-level tables planned (203-baseline-compare-strategy)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `GovernanceSubjectTaxonomyRegistry`, `BaselineScope`, `CompareStrategyRegistry`, `OperationCatalog`, `OperationRunType`, `ReasonTranslator`, `ReasonResolutionEnvelope`, `ProviderReasonTranslator`, and current Filament monitoring or review surfaces (204-platform-core-vocabulary-hardening)
- PostgreSQL via existing `operation_runs.type`, `operation_runs.context`, `baseline_profiles.scope_jsonb`, `baseline_snapshot_items`, findings, evidence payloads, and current config-backed registries; no new top-level tables planned (204-platform-core-vocabulary-hardening)
- PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BaselineCompareService`, `CompareBaselineToTenantJob`, `CompareStrategyRegistry`, `IntuneCompareStrategy`, `CurrentStateHashResolver`, and current finding lifecycle services (205-compare-job-cleanup)
- PostgreSQL via existing baseline snapshots, baseline snapshot items, inventory items, `operation_runs`, findings, and current run-context JSON; no new storage planned (205-compare-job-cleanup)
- PHP 8.4.15 (feat/005-bulk-operations)
@ -218,8 +220,8 @@ ## Code Style
PHP 8.4.15: Follow standard conventions
## Recent Changes
- 205-compare-job-cleanup: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BaselineCompareService`, `CompareBaselineToTenantJob`, `CompareStrategyRegistry`, `IntuneCompareStrategy`, `CurrentStateHashResolver`, and current finding lifecycle services
- 204-platform-core-vocabulary-hardening: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `GovernanceSubjectTaxonomyRegistry`, `BaselineScope`, `CompareStrategyRegistry`, `OperationCatalog`, `OperationRunType`, `ReasonTranslator`, `ReasonResolutionEnvelope`, `ProviderReasonTranslator`, and current Filament monitoring or review surfaces
- 203-baseline-compare-strategy: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BaselineCompareService`, `CompareBaselineToTenantJob`, `SubjectResolver`, `CurrentStateHashResolver`, `DriftHasher`, `BaselineCompareSummaryAssessor`, and finding lifecycle services
- 202-governance-subject-taxonomy: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4, Pest v4, Tailwind CSS v4, Laravel Sail, existing `BaselineScope`, `InventoryPolicyTypeMeta`, `BaselineSupportCapabilityGuard`, `BaselineCaptureService`, and `BaselineCompareService`
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->

View File

@ -12,7 +12,6 @@
use App\Models\Finding;
use App\Models\InventoryItem;
use App\Models\OperationRun;
use App\Models\PolicyVersion;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Workspace;
@ -21,19 +20,13 @@
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Baselines\BaselineSnapshotTruthResolver;
use App\Services\Baselines\CurrentStateHashResolver;
use App\Services\Baselines\Evidence\BaselinePolicyVersionResolver;
use App\Services\Baselines\Evidence\ContentEvidenceProvider;
use App\Services\Baselines\Evidence\EvidenceProvenance;
use App\Services\Baselines\Evidence\MetaEvidenceProvider;
use App\Services\Baselines\Evidence\ResolvedEvidence;
use App\Services\Drift\DriftHasher;
use App\Services\Drift\Normalizers\AssignmentsNormalizer;
use App\Services\Drift\Normalizers\ScopeTagsNormalizer;
use App\Services\Drift\Normalizers\SettingsNormalizer;
use App\Services\Findings\FindingSlaPolicy;
use App\Services\Findings\FindingWorkflowService;
use App\Services\Intune\AuditLogger;
use App\Services\Intune\IntuneRoleDefinitionNormalizer;
use App\Services\OperationRunService;
use App\Services\Settings\SettingsResolver;
use App\Support\Baselines\BaselineCaptureMode;
@ -76,11 +69,6 @@ class CompareBaselineToTenantJob implements ShouldQueue
public bool $failOnTimeout = true;
/**
* @var array<int, string>
*/
private array $baselineContentHashCache = [];
public ?OperationRun $operationRun = null;
public function __construct(
@ -825,7 +813,7 @@ private function rekeyResolvedEvidenceBySubjectKey(array $currentItems, array $r
* captured_versions?: array<string, array{
* policy_type: string,
* subject_external_id: string,
* version: PolicyVersion,
* version: \App\Models\PolicyVersion,
* observed_at: string,
* observed_operation_run_id: ?int
* }>
@ -855,7 +843,7 @@ private function resolveCapturedCurrentEvidenceByExternalId(array $phaseResult):
$observedOperationRunId = $capturedVersion['observed_operation_run_id'] ?? null;
$observedOperationRunId = is_numeric($observedOperationRunId) ? (int) $observedOperationRunId : null;
if (! $version instanceof PolicyVersion || $subjectExternalId === '' || ! is_string($key) || $key === '') {
if (! $version instanceof \App\Models\PolicyVersion || $subjectExternalId === '' || ! is_string($key) || $key === '') {
continue;
}
@ -870,6 +858,7 @@ private function resolveCapturedCurrentEvidenceByExternalId(array $phaseResult):
return $resolved;
}
private function completeWithCoverageWarning(
OperationRunService $operationRunService,
AuditLogger $auditLogger,
@ -1423,750 +1412,6 @@ private function truthfulTypesFromContext(array $context, BaselineScope $effecti
return $effectiveScope->allTypes();
}
/**
* Compare baseline items vs current inventory and produce drift results.
*
* @param array<string, array{subject_type: string, subject_external_id: string, subject_key: string, policy_type: string, baseline_hash: string, meta_jsonb: array<string, mixed>}> $baselineItems
* @param array<string, array{subject_external_id: string, subject_key: string, policy_type: string, meta_jsonb: array<string, mixed>}> $currentItems
* @param array<string, ResolvedEvidence|null> $resolvedCurrentEvidence
* @param array<string, string> $severityMapping
* @return array{
* drift: array<int, array{change_type: string, severity: string, evidence_fidelity: string, subject_type: string, subject_external_id: string, subject_key: string, policy_type: string, baseline_hash: string, current_hash: string, evidence: array<string, mixed>}>,
* evidence_gaps: array<string, int>,
* rbac_role_definitions: array{total_compared: int, unchanged: int, modified: int, missing: int, unexpected: int}
* }
*/
private function computeDrift(
Tenant $tenant,
int $baselineProfileId,
int $baselineSnapshotId,
int $compareOperationRunId,
int $inventorySyncRunId,
array $baselineItems,
array $currentItems,
array $resolvedCurrentEvidence,
array $severityMapping,
BaselinePolicyVersionResolver $baselinePolicyVersionResolver,
DriftHasher $hasher,
SettingsNormalizer $settingsNormalizer,
AssignmentsNormalizer $assignmentsNormalizer,
ScopeTagsNormalizer $scopeTagsNormalizer,
ContentEvidenceProvider $contentEvidenceProvider,
): array {
$drift = [];
$evidenceGaps = [];
$evidenceGapSubjects = [];
$rbacRoleDefinitionSummary = $this->emptyRbacRoleDefinitionSummary();
$roleDefinitionNormalizer = app(IntuneRoleDefinitionNormalizer::class);
$baselinePlaceholderProvenance = EvidenceProvenance::build(
fidelity: EvidenceProvenance::FidelityMeta,
source: EvidenceProvenance::SourceInventory,
observedAt: null,
observedOperationRunId: null,
);
$currentMissingProvenance = EvidenceProvenance::build(
fidelity: EvidenceProvenance::FidelityMeta,
source: EvidenceProvenance::SourceInventory,
observedAt: null,
observedOperationRunId: $inventorySyncRunId,
);
foreach ($baselineItems as $key => $baselineItem) {
$currentItem = $currentItems[$key] ?? null;
$policyType = (string) ($baselineItem['policy_type'] ?? '');
$subjectKey = (string) ($baselineItem['subject_key'] ?? '');
$isRbacRoleDefinition = $policyType === 'intuneRoleDefinition';
$baselineProvenance = $this->baselineProvenanceFromMetaJsonb($baselineItem['meta_jsonb'] ?? []);
$baselinePolicyVersionId = $this->resolveBaselinePolicyVersionId(
tenant: $tenant,
baselineItem: $baselineItem,
baselineProvenance: $baselineProvenance,
baselinePolicyVersionResolver: $baselinePolicyVersionResolver,
);
$baselineComparableHash = $this->effectiveBaselineHash(
tenant: $tenant,
baselineItem: $baselineItem,
baselinePolicyVersionId: $baselinePolicyVersionId,
contentEvidenceProvider: $contentEvidenceProvider,
);
if (! is_array($currentItem)) {
if ($isRbacRoleDefinition && $baselinePolicyVersionId === null) {
$evidenceGaps['missing_role_definition_baseline_version_reference'] = ($evidenceGaps['missing_role_definition_baseline_version_reference'] ?? 0) + 1;
$evidenceGapSubjects['missing_role_definition_baseline_version_reference'][] = $key;
continue;
}
$displayName = $baselineItem['meta_jsonb']['display_name'] ?? null;
$displayName = is_string($displayName) ? (string) $displayName : null;
$evidence = $this->buildDriftEvidenceContract(
changeType: 'missing_policy',
policyType: $policyType,
subjectKey: $subjectKey,
displayName: $displayName,
baselineHash: $baselineComparableHash,
currentHash: null,
baselineProvenance: $baselineProvenance,
currentProvenance: $currentMissingProvenance,
baselinePolicyVersionId: $baselinePolicyVersionId,
currentPolicyVersionId: null,
summaryKind: 'policy_snapshot',
baselineProfileId: $baselineProfileId,
baselineSnapshotId: $baselineSnapshotId,
compareOperationRunId: $compareOperationRunId,
inventorySyncRunId: $inventorySyncRunId,
);
if ($isRbacRoleDefinition) {
$evidence['summary']['kind'] = 'rbac_role_definition';
$evidence['rbac_role_definition'] = $this->buildRoleDefinitionEvidencePayload(
tenant: $tenant,
baselinePolicyVersionId: $baselinePolicyVersionId,
currentPolicyVersionId: null,
baselineMeta: is_array($baselineItem['meta_jsonb'] ?? null) ? $baselineItem['meta_jsonb'] : [],
currentMeta: [],
diffKind: 'missing',
);
}
if ($isRbacRoleDefinition) {
$rbacRoleDefinitionSummary['missing']++;
$rbacRoleDefinitionSummary['total_compared']++;
}
$drift[] = [
'change_type' => 'missing_policy',
'severity' => $isRbacRoleDefinition
? Finding::SEVERITY_HIGH
: $this->severityForChangeType($severityMapping, 'missing_policy'),
'subject_type' => $baselineItem['subject_type'],
'subject_external_id' => $baselineItem['subject_external_id'],
'subject_key' => $subjectKey,
'policy_type' => $policyType,
'evidence_fidelity' => (string) ($evidence['fidelity'] ?? EvidenceProvenance::FidelityMeta),
'baseline_hash' => $baselineComparableHash,
'current_hash' => '',
'evidence' => $evidence,
];
continue;
}
$currentEvidence = $resolvedCurrentEvidence[$key] ?? null;
if (! $currentEvidence instanceof ResolvedEvidence) {
$evidenceGaps['missing_current'] = ($evidenceGaps['missing_current'] ?? 0) + 1;
$evidenceGapSubjects['missing_current'][] = $key;
continue;
}
$currentPolicyVersionId = $this->currentPolicyVersionIdFromEvidence($currentEvidence);
if ($baselineComparableHash !== $currentEvidence->hash) {
$displayName = $currentItem['meta_jsonb']['display_name']
?? ($baselineItem['meta_jsonb']['display_name'] ?? null);
$displayName = is_string($displayName) ? (string) $displayName : null;
$roleDefinitionDiff = null;
if ($isRbacRoleDefinition) {
if ($baselinePolicyVersionId === null) {
$evidenceGaps['missing_role_definition_baseline_version_reference'] = ($evidenceGaps['missing_role_definition_baseline_version_reference'] ?? 0) + 1;
$evidenceGapSubjects['missing_role_definition_baseline_version_reference'][] = $key;
continue;
}
if ($currentPolicyVersionId === null) {
$evidenceGaps['missing_role_definition_current_version_reference'] = ($evidenceGaps['missing_role_definition_current_version_reference'] ?? 0) + 1;
$evidenceGapSubjects['missing_role_definition_current_version_reference'][] = $key;
continue;
}
$roleDefinitionDiff = $this->resolveRoleDefinitionDiff(
tenant: $tenant,
baselinePolicyVersionId: $baselinePolicyVersionId,
currentPolicyVersionId: $currentPolicyVersionId,
normalizer: $roleDefinitionNormalizer,
);
if ($roleDefinitionDiff === null) {
$evidenceGaps['missing_role_definition_compare_surface'] = ($evidenceGaps['missing_role_definition_compare_surface'] ?? 0) + 1;
$evidenceGapSubjects['missing_role_definition_compare_surface'][] = $key;
continue;
}
}
$summaryKind = $isRbacRoleDefinition
? 'rbac_role_definition'
: $this->selectSummaryKind(
tenant: $tenant,
policyType: $policyType,
baselinePolicyVersionId: $baselinePolicyVersionId,
currentPolicyVersionId: $currentPolicyVersionId,
hasher: $hasher,
settingsNormalizer: $settingsNormalizer,
assignmentsNormalizer: $assignmentsNormalizer,
scopeTagsNormalizer: $scopeTagsNormalizer,
);
$evidence = $this->buildDriftEvidenceContract(
changeType: 'different_version',
policyType: $policyType,
subjectKey: $subjectKey,
displayName: $displayName,
baselineHash: $baselineComparableHash,
currentHash: (string) $currentEvidence->hash,
baselineProvenance: $baselineProvenance,
currentProvenance: $currentEvidence->tenantProvenance(),
baselinePolicyVersionId: $baselinePolicyVersionId,
currentPolicyVersionId: $currentPolicyVersionId,
summaryKind: $summaryKind,
baselineProfileId: $baselineProfileId,
baselineSnapshotId: $baselineSnapshotId,
compareOperationRunId: $compareOperationRunId,
inventorySyncRunId: $inventorySyncRunId,
);
if ($isRbacRoleDefinition && is_array($roleDefinitionDiff)) {
$evidence['rbac_role_definition'] = $this->buildRoleDefinitionEvidencePayload(
tenant: $tenant,
baselinePolicyVersionId: $baselinePolicyVersionId,
currentPolicyVersionId: $currentPolicyVersionId,
baselineMeta: is_array($baselineItem['meta_jsonb'] ?? null) ? $baselineItem['meta_jsonb'] : [],
currentMeta: is_array($currentEvidence->meta ?? null) ? $currentEvidence->meta : (is_array($currentItem['meta_jsonb'] ?? null) ? $currentItem['meta_jsonb'] : []),
diffKind: (string) $roleDefinitionDiff['diff_kind'],
roleDefinitionDiff: $roleDefinitionDiff,
);
$rbacRoleDefinitionSummary['modified']++;
$rbacRoleDefinitionSummary['total_compared']++;
}
$drift[] = [
'change_type' => 'different_version',
'severity' => $isRbacRoleDefinition
? $this->severityForRoleDefinitionDiff($roleDefinitionDiff)
: $this->severityForChangeType($severityMapping, 'different_version'),
'subject_type' => $baselineItem['subject_type'],
'subject_external_id' => $currentItem['subject_external_id'],
'subject_key' => $subjectKey,
'policy_type' => $policyType,
'evidence_fidelity' => (string) ($evidence['fidelity'] ?? EvidenceProvenance::FidelityMeta),
'baseline_hash' => $baselineComparableHash,
'current_hash' => $currentEvidence->hash,
'evidence' => $evidence,
];
continue;
}
if ($isRbacRoleDefinition) {
$rbacRoleDefinitionSummary['unchanged']++;
$rbacRoleDefinitionSummary['total_compared']++;
}
}
foreach ($currentItems as $key => $currentItem) {
if (! array_key_exists($key, $baselineItems)) {
$currentEvidence = $resolvedCurrentEvidence[$key] ?? null;
if (! $currentEvidence instanceof ResolvedEvidence) {
$evidenceGaps['missing_current'] = ($evidenceGaps['missing_current'] ?? 0) + 1;
$evidenceGapSubjects['missing_current'][] = $key;
continue;
}
$policyType = (string) ($currentItem['policy_type'] ?? '');
$subjectKey = (string) ($currentItem['subject_key'] ?? '');
$isRbacRoleDefinition = $policyType === 'intuneRoleDefinition';
$displayName = $currentItem['meta_jsonb']['display_name'] ?? null;
$displayName = is_string($displayName) ? (string) $displayName : null;
$currentPolicyVersionId = $this->currentPolicyVersionIdFromEvidence($currentEvidence);
if ($isRbacRoleDefinition && $currentPolicyVersionId === null) {
$evidenceGaps['missing_role_definition_current_version_reference'] = ($evidenceGaps['missing_role_definition_current_version_reference'] ?? 0) + 1;
$evidenceGapSubjects['missing_role_definition_current_version_reference'][] = $key;
continue;
}
$evidence = $this->buildDriftEvidenceContract(
changeType: 'unexpected_policy',
policyType: $policyType,
subjectKey: $subjectKey,
displayName: $displayName,
baselineHash: null,
currentHash: (string) $currentEvidence->hash,
baselineProvenance: $baselinePlaceholderProvenance,
currentProvenance: $currentEvidence->tenantProvenance(),
baselinePolicyVersionId: null,
currentPolicyVersionId: $currentPolicyVersionId,
summaryKind: 'policy_snapshot',
baselineProfileId: $baselineProfileId,
baselineSnapshotId: $baselineSnapshotId,
compareOperationRunId: $compareOperationRunId,
inventorySyncRunId: $inventorySyncRunId,
);
if ($isRbacRoleDefinition) {
$evidence['summary']['kind'] = 'rbac_role_definition';
$evidence['rbac_role_definition'] = $this->buildRoleDefinitionEvidencePayload(
tenant: $tenant,
baselinePolicyVersionId: null,
currentPolicyVersionId: $currentPolicyVersionId,
baselineMeta: [],
currentMeta: is_array($currentEvidence->meta ?? null) ? $currentEvidence->meta : (is_array($currentItem['meta_jsonb'] ?? null) ? $currentItem['meta_jsonb'] : []),
diffKind: 'unexpected',
);
}
if ($isRbacRoleDefinition) {
$rbacRoleDefinitionSummary['unexpected']++;
$rbacRoleDefinitionSummary['total_compared']++;
}
$drift[] = [
'change_type' => 'unexpected_policy',
'severity' => $isRbacRoleDefinition
? Finding::SEVERITY_MEDIUM
: $this->severityForChangeType($severityMapping, 'unexpected_policy'),
'subject_type' => 'policy',
'subject_external_id' => $currentItem['subject_external_id'],
'subject_key' => $subjectKey,
'policy_type' => $policyType,
'evidence_fidelity' => (string) ($evidence['fidelity'] ?? EvidenceProvenance::FidelityMeta),
'baseline_hash' => '',
'current_hash' => $currentEvidence->hash,
'evidence' => $evidence,
];
}
}
return [
'drift' => $drift,
'evidence_gaps' => $evidenceGaps,
'evidence_gap_subjects' => $evidenceGapSubjects,
'rbac_role_definitions' => $rbacRoleDefinitionSummary,
];
}
/**
* @param array{subject_external_id: string, baseline_hash: string} $baselineItem
*/
private function effectiveBaselineHash(
Tenant $tenant,
array $baselineItem,
?int $baselinePolicyVersionId,
ContentEvidenceProvider $contentEvidenceProvider,
): string {
$storedHash = (string) ($baselineItem['baseline_hash'] ?? '');
if ($baselinePolicyVersionId === null) {
return $storedHash;
}
if (array_key_exists($baselinePolicyVersionId, $this->baselineContentHashCache)) {
return $this->baselineContentHashCache[$baselinePolicyVersionId];
}
$baselineVersion = PolicyVersion::query()
->where('tenant_id', (int) $tenant->getKey())
->find($baselinePolicyVersionId);
if (! $baselineVersion instanceof PolicyVersion) {
return $storedHash;
}
$hash = $contentEvidenceProvider->fromPolicyVersion(
version: $baselineVersion,
subjectExternalId: (string) ($baselineItem['subject_external_id'] ?? ''),
)->hash;
$this->baselineContentHashCache[$baselinePolicyVersionId] = $hash;
return $hash;
}
private function resolveBaselinePolicyVersionId(
Tenant $tenant,
array $baselineItem,
array $baselineProvenance,
BaselinePolicyVersionResolver $baselinePolicyVersionResolver,
): ?int {
$metaJsonb = is_array($baselineItem['meta_jsonb'] ?? null) ? $baselineItem['meta_jsonb'] : [];
$versionReferenceId = data_get($metaJsonb, 'version_reference.policy_version_id');
if (is_numeric($versionReferenceId)) {
return (int) $versionReferenceId;
}
$baselineFidelity = (string) ($baselineProvenance['fidelity'] ?? EvidenceProvenance::FidelityMeta);
$baselineSource = (string) ($baselineProvenance['source'] ?? EvidenceProvenance::SourceInventory);
if ($baselineFidelity !== EvidenceProvenance::FidelityContent || $baselineSource !== EvidenceProvenance::SourcePolicyVersion) {
return null;
}
$observedAt = $baselineProvenance['observed_at'] ?? null;
$observedAt = is_string($observedAt) ? trim($observedAt) : null;
if (! is_string($observedAt) || $observedAt === '') {
return null;
}
return $baselinePolicyVersionResolver->resolve(
tenant: $tenant,
policyType: (string) ($baselineItem['policy_type'] ?? ''),
subjectKey: (string) ($baselineItem['subject_key'] ?? ''),
observedAt: $observedAt,
);
}
private function currentPolicyVersionIdFromEvidence(ResolvedEvidence $evidence): ?int
{
$policyVersionId = $evidence->meta['policy_version_id'] ?? null;
return is_numeric($policyVersionId) ? (int) $policyVersionId : null;
}
private function selectSummaryKind(
Tenant $tenant,
string $policyType,
?int $baselinePolicyVersionId,
?int $currentPolicyVersionId,
DriftHasher $hasher,
SettingsNormalizer $settingsNormalizer,
AssignmentsNormalizer $assignmentsNormalizer,
ScopeTagsNormalizer $scopeTagsNormalizer,
): string {
if ($baselinePolicyVersionId === null || $currentPolicyVersionId === null) {
return 'policy_snapshot';
}
$baselineVersion = PolicyVersion::query()
->where('tenant_id', (int) $tenant->getKey())
->find($baselinePolicyVersionId);
$currentVersion = PolicyVersion::query()
->where('tenant_id', (int) $tenant->getKey())
->find($currentPolicyVersionId);
if (! $baselineVersion instanceof PolicyVersion || ! $currentVersion instanceof PolicyVersion) {
return 'policy_snapshot';
}
$platform = is_string($baselineVersion->platform ?? null)
? (string) $baselineVersion->platform
: (is_string($currentVersion->platform ?? null) ? (string) $currentVersion->platform : null);
$baselineSnapshot = is_array($baselineVersion->snapshot) ? $baselineVersion->snapshot : [];
$currentSnapshot = is_array($currentVersion->snapshot) ? $currentVersion->snapshot : [];
$baselineNormalized = $settingsNormalizer->normalizeForDiff(
snapshot: $baselineSnapshot,
policyType: $policyType,
platform: $platform,
);
$currentNormalized = $settingsNormalizer->normalizeForDiff(
snapshot: $currentSnapshot,
policyType: $policyType,
platform: $platform,
);
$baselineSnapshotHash = $hasher->hashNormalized([
'settings' => $baselineNormalized,
'secret_fingerprints' => $this->fingerprintBucket($baselineVersion, 'snapshot'),
]);
$currentSnapshotHash = $hasher->hashNormalized([
'settings' => $currentNormalized,
'secret_fingerprints' => $this->fingerprintBucket($currentVersion, 'snapshot'),
]);
if ($baselineSnapshotHash !== $currentSnapshotHash) {
return 'policy_snapshot';
}
$baselineAssignments = is_array($baselineVersion->assignments) ? $baselineVersion->assignments : [];
$currentAssignments = is_array($currentVersion->assignments) ? $currentVersion->assignments : [];
$baselineAssignmentsHash = $hasher->hashNormalized([
'assignments' => $assignmentsNormalizer->normalizeForDiff($baselineAssignments),
'secret_fingerprints' => $this->fingerprintBucket($baselineVersion, 'assignments'),
]);
$currentAssignmentsHash = $hasher->hashNormalized([
'assignments' => $assignmentsNormalizer->normalizeForDiff($currentAssignments),
'secret_fingerprints' => $this->fingerprintBucket($currentVersion, 'assignments'),
]);
if ($baselineAssignmentsHash !== $currentAssignmentsHash) {
return 'policy_assignments';
}
$baselineScopeTagIds = $scopeTagsNormalizer->normalizeIdsForHash($baselineVersion->scope_tags);
$currentScopeTagIds = $scopeTagsNormalizer->normalizeIdsForHash($currentVersion->scope_tags);
if ($baselineScopeTagIds === null || $currentScopeTagIds === null) {
return 'policy_snapshot';
}
$baselineScopeTagsHash = $hasher->hashNormalized([
'scope_tag_ids' => $baselineScopeTagIds,
'secret_fingerprints' => $this->fingerprintBucket($baselineVersion, 'scope_tags'),
]);
$currentScopeTagsHash = $hasher->hashNormalized([
'scope_tag_ids' => $currentScopeTagIds,
'secret_fingerprints' => $this->fingerprintBucket($currentVersion, 'scope_tags'),
]);
if ($baselineScopeTagsHash !== $currentScopeTagsHash) {
return 'policy_scope_tags';
}
return 'policy_snapshot';
}
/**
* @return array<string, string>
*/
private function fingerprintBucket(PolicyVersion $version, string $bucket): array
{
$secretFingerprints = is_array($version->secret_fingerprints) ? $version->secret_fingerprints : [];
$bucketFingerprints = $secretFingerprints[$bucket] ?? [];
return is_array($bucketFingerprints) ? $bucketFingerprints : [];
}
/**
* @param array{fidelity: string, source: string, observed_at: ?string, observed_operation_run_id: ?int} $baselineProvenance
* @param array<string, mixed> $currentProvenance
* @return array<string, mixed>
*/
private function buildDriftEvidenceContract(
string $changeType,
string $policyType,
string $subjectKey,
?string $displayName,
?string $baselineHash,
?string $currentHash,
array $baselineProvenance,
array $currentProvenance,
?int $baselinePolicyVersionId,
?int $currentPolicyVersionId,
string $summaryKind,
int $baselineProfileId,
int $baselineSnapshotId,
int $compareOperationRunId,
int $inventorySyncRunId,
): array {
$fidelity = $this->fidelityFromPolicyVersionRefs($baselinePolicyVersionId, $currentPolicyVersionId);
return [
'change_type' => $changeType,
'policy_type' => $policyType,
'subject_key' => $subjectKey,
'display_name' => $displayName,
'summary' => [
'kind' => $summaryKind,
],
'baseline' => [
'policy_version_id' => $baselinePolicyVersionId,
'hash' => $baselineHash,
'provenance' => $baselineProvenance,
],
'current' => [
'policy_version_id' => $currentPolicyVersionId,
'hash' => $currentHash,
'provenance' => $currentProvenance,
],
'fidelity' => $fidelity,
'provenance' => [
'baseline_profile_id' => $baselineProfileId,
'baseline_snapshot_id' => $baselineSnapshotId,
'compare_operation_run_id' => $compareOperationRunId,
'inventory_sync_run_id' => $inventorySyncRunId,
],
];
}
/**
* @param array<string, mixed> $baselineMeta
* @param array<string, mixed> $currentMeta
* @param array{
* baseline: array<string, mixed>,
* current: array<string, mixed>,
* changed_keys: list<string>,
* metadata_keys: list<string>,
* permission_keys: list<string>,
* diff_kind: string,
* diff_fingerprint: string
* }|null $roleDefinitionDiff
* @return array{
* diff_kind: string,
* diff_fingerprint: string,
* changed_keys: list<string>,
* metadata_keys: list<string>,
* permission_keys: list<string>,
* baseline: array{normalized: array<string, mixed>, is_built_in: mixed, role_permission_count: mixed},
* current: array{normalized: array<string, mixed>, is_built_in: mixed, role_permission_count: mixed}
* }
*/
private function buildRoleDefinitionEvidencePayload(
Tenant $tenant,
?int $baselinePolicyVersionId,
?int $currentPolicyVersionId,
array $baselineMeta,
array $currentMeta,
string $diffKind,
?array $roleDefinitionDiff = null,
): array {
$baselineVersion = $this->resolveRoleDefinitionVersion($tenant, $baselinePolicyVersionId);
$currentVersion = $this->resolveRoleDefinitionVersion($tenant, $currentPolicyVersionId);
$baselineNormalized = is_array($roleDefinitionDiff['baseline'] ?? null)
? $roleDefinitionDiff['baseline']
: $this->fallbackRoleDefinitionNormalized($baselineVersion, $baselineMeta);
$currentNormalized = is_array($roleDefinitionDiff['current'] ?? null)
? $roleDefinitionDiff['current']
: $this->fallbackRoleDefinitionNormalized($currentVersion, $currentMeta);
$changedKeys = is_array($roleDefinitionDiff['changed_keys'] ?? null)
? array_values(array_filter($roleDefinitionDiff['changed_keys'], 'is_string'))
: $this->roleDefinitionChangedKeys($baselineNormalized, $currentNormalized);
$metadataKeys = is_array($roleDefinitionDiff['metadata_keys'] ?? null)
? array_values(array_filter($roleDefinitionDiff['metadata_keys'], 'is_string'))
: array_values(array_diff($changedKeys, $this->roleDefinitionPermissionKeys($changedKeys)));
$permissionKeys = is_array($roleDefinitionDiff['permission_keys'] ?? null)
? array_values(array_filter($roleDefinitionDiff['permission_keys'], 'is_string'))
: $this->roleDefinitionPermissionKeys($changedKeys);
$resolvedDiffKind = is_string($roleDefinitionDiff['diff_kind'] ?? null)
? (string) $roleDefinitionDiff['diff_kind']
: $diffKind;
$diffFingerprint = is_string($roleDefinitionDiff['diff_fingerprint'] ?? null)
? (string) $roleDefinitionDiff['diff_fingerprint']
: hash(
'sha256',
json_encode([
'diff_kind' => $resolvedDiffKind,
'changed_keys' => $changedKeys,
'baseline' => $baselineNormalized,
'current' => $currentNormalized,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
);
return [
'diff_kind' => $resolvedDiffKind,
'diff_fingerprint' => $diffFingerprint,
'changed_keys' => $changedKeys,
'metadata_keys' => $metadataKeys,
'permission_keys' => $permissionKeys,
'baseline' => [
'normalized' => $baselineNormalized,
'is_built_in' => data_get($baselineMeta, 'rbac.is_built_in', data_get($baselineMeta, 'is_built_in')),
'role_permission_count' => data_get($baselineMeta, 'rbac.role_permission_count', data_get($baselineMeta, 'role_permission_count')),
],
'current' => [
'normalized' => $currentNormalized,
'is_built_in' => data_get($currentMeta, 'rbac.is_built_in', data_get($currentMeta, 'is_built_in')),
'role_permission_count' => data_get($currentMeta, 'rbac.role_permission_count', data_get($currentMeta, 'role_permission_count')),
],
];
}
private function resolveRoleDefinitionVersion(Tenant $tenant, ?int $policyVersionId): ?PolicyVersion
{
if ($policyVersionId === null) {
return null;
}
return PolicyVersion::query()
->where('tenant_id', (int) $tenant->getKey())
->find($policyVersionId);
}
/**
* @param array<string, mixed> $meta
* @return array<string, mixed>
*/
private function fallbackRoleDefinitionNormalized(?PolicyVersion $version, array $meta): array
{
if ($version instanceof PolicyVersion) {
return app(IntuneRoleDefinitionNormalizer::class)->buildEvidenceMap(
is_array($version->snapshot) ? $version->snapshot : [],
is_string($version->platform ?? null) ? (string) $version->platform : null,
);
}
$normalized = [];
$displayName = $meta['display_name'] ?? null;
if (is_string($displayName) && trim($displayName) !== '') {
$normalized['Role definition > Display name'] = trim($displayName);
}
$isBuiltIn = data_get($meta, 'rbac.is_built_in', data_get($meta, 'is_built_in'));
if (is_bool($isBuiltIn)) {
$normalized['Role definition > Role source'] = $isBuiltIn ? 'Built-in' : 'Custom';
}
$rolePermissionCount = data_get($meta, 'rbac.role_permission_count', data_get($meta, 'role_permission_count'));
if (is_numeric($rolePermissionCount)) {
$normalized['Role definition > Permission blocks'] = (int) $rolePermissionCount;
}
return $normalized;
}
/**
* @param array<string, mixed> $baselineNormalized
* @param array<string, mixed> $currentNormalized
* @return list<string>
*/
private function roleDefinitionChangedKeys(array $baselineNormalized, array $currentNormalized): array
{
$keys = array_values(array_unique(array_merge(array_keys($baselineNormalized), array_keys($currentNormalized))));
sort($keys, SORT_STRING);
return array_values(array_filter($keys, fn (string $key): bool => ($baselineNormalized[$key] ?? null) !== ($currentNormalized[$key] ?? null)));
}
/**
* @param list<string> $keys
* @return list<string>
*/
private function roleDefinitionPermissionKeys(array $keys): array
{
return array_values(array_filter(
$keys,
fn (string $key): bool => str_starts_with($key, 'Permission block ')
));
}
private function fidelityFromPolicyVersionRefs(?int $baselinePolicyVersionId, ?int $currentPolicyVersionId): string
{
if ($baselinePolicyVersionId !== null && $currentPolicyVersionId !== null) {
return 'content';
}
if ($baselinePolicyVersionId !== null || $currentPolicyVersionId !== null) {
return 'mixed';
}
return 'meta';
}
private function normalizeSubjectKey(
string $policyType,
?string $storedSubjectKey = null,
@ -2182,50 +1427,6 @@ private function normalizeSubjectKey(
return BaselineSubjectKey::forPolicy($policyType, $displayName, $subjectExternalId) ?? '';
}
/**
* @return array{
* baseline: array<string, mixed>,
* current: array<string, mixed>,
* changed_keys: list<string>,
* metadata_keys: list<string>,
* permission_keys: list<string>,
* diff_kind: string,
* diff_fingerprint: string
* }|null
*/
private function resolveRoleDefinitionDiff(
Tenant $tenant,
int $baselinePolicyVersionId,
int $currentPolicyVersionId,
IntuneRoleDefinitionNormalizer $normalizer,
): ?array {
$baselineVersion = $this->resolveRoleDefinitionVersion($tenant, $baselinePolicyVersionId);
$currentVersion = $this->resolveRoleDefinitionVersion($tenant, $currentPolicyVersionId);
if (! $baselineVersion instanceof PolicyVersion || ! $currentVersion instanceof PolicyVersion) {
return null;
}
return $normalizer->classifyDiff(
baselineSnapshot: is_array($baselineVersion->snapshot) ? $baselineVersion->snapshot : [],
currentSnapshot: is_array($currentVersion->snapshot) ? $currentVersion->snapshot : [],
platform: is_string($currentVersion->platform ?? null)
? (string) $currentVersion->platform
: (is_string($baselineVersion->platform ?? null) ? (string) $baselineVersion->platform : null),
);
}
/**
* @param array{diff_kind?: string}|null $roleDefinitionDiff
*/
private function severityForRoleDefinitionDiff(?array $roleDefinitionDiff): string
{
return match ($roleDefinitionDiff['diff_kind'] ?? null) {
'metadata_only' => Finding::SEVERITY_LOW,
default => Finding::SEVERITY_HIGH,
};
}
/**
* @return array{total_compared: int, unchanged: int, modified: int, missing: int, unexpected: int}
*/

View File

@ -6,7 +6,7 @@
use App\Support\Inventory\InventoryPolicyTypeMeta;
final class GovernanceSubjectTaxonomyRegistry
class GovernanceSubjectTaxonomyRegistry
{
/**
* @var array<string, list<string>>

View File

@ -138,6 +138,13 @@
$opService,
);
$compareRun->refresh();
expect(data_get($compareRun->context, 'baseline_compare.strategy.key'))->toBe('intune_policy')
->and(data_get($compareRun->context, 'baseline_compare.strategy.selection_state'))->toBe('supported')
->and(data_get($compareRun->context, 'baseline_compare.strategy.matched_scope_entries.0.domain_key'))->toBe('intune')
->and(data_get($compareRun->context, 'baseline_compare.strategy.execution_diagnostics.rbac_role_definitions.total_compared'))->toBe(0);
$finding = Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('subject_external_id', (string) $policy->external_id)

View File

@ -130,6 +130,9 @@
$run->refresh();
expect($run->status)->toBe('completed');
expect($run->outcome)->toBe('succeeded');
expect(data_get($run->context, 'baseline_compare.strategy.key'))->toBe('intune_policy')
->and(data_get($run->context, 'baseline_compare.strategy.selection_state'))->toBe('supported')
->and(data_get($run->context, 'baseline_compare.strategy.state_counts.drift'))->toBe(3);
$context = is_array($run->context) ? $run->context : [];
$countsByChangeType = $context['findings']['counts_by_change_type'] ?? null;

View File

@ -123,6 +123,8 @@
$run->refresh();
expect(data_get($run->context, 'baseline_compare.evidence_gaps.by_reason.policy_not_found'))->toBeNull()
->and(data_get($run->context, 'baseline_compare.strategy.key'))->toBe('intune_policy')
->and(data_get($run->context, 'baseline_compare.strategy.selection_state'))->toBe('supported')
->and(data_get($run->context, 'baseline_compare.evidence_gaps.by_reason.policy_record_missing'))->toBe(1)
->and(data_get($run->context, 'baseline_compare.evidence_gaps.by_reason.foundation_not_policy_backed'))->toBe(1);

View File

@ -85,7 +85,9 @@
);
$compareRun->refresh();
expect(data_get($compareRun->context, 'baseline_compare.subjects_total'))->toBe(0);
expect(data_get($compareRun->context, 'baseline_compare.subjects_total'))->toBe(0)
->and(data_get($compareRun->context, 'baseline_compare.strategy.key'))->toBe('intune_policy')
->and(data_get($compareRun->context, 'baseline_compare.strategy.selection_state'))->toBe('supported');
expect(data_get($compareRun->context, 'baseline_compare.reason_code'))->toBe(BaselineCompareReasonCode::NoSubjectsInScope->value);
});
@ -200,7 +202,10 @@
$compareRun->refresh();
expect(data_get($compareRun->context, 'baseline_compare.subjects_total'))->toBe(1);
expect(data_get($compareRun->context, 'baseline_compare.subjects_total'))->toBe(1)
->and(data_get($compareRun->context, 'baseline_compare.strategy.key'))->toBe('intune_policy')
->and(data_get($compareRun->context, 'baseline_compare.strategy.selection_state'))->toBe('supported')
->and(data_get($compareRun->context, 'baseline_compare.strategy.state_counts.no_drift'))->toBe(1);
expect(data_get($compareRun->context, 'result.findings_total'))->toBe(0);
expect(data_get($compareRun->context, 'baseline_compare.reason_code'))->toBe(BaselineCompareReasonCode::NoDriftDetected->value);
});

View File

@ -10,6 +10,8 @@
use App\Services\Baselines\BaselineCaptureService;
use App\Services\Baselines\BaselineCompareService;
use App\Support\Baselines\BaselineCaptureMode;
use App\Support\Baselines\BaselineReasonCodes;
use App\Support\Baselines\BaselineSupportCapabilityGuard;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
@ -85,7 +87,7 @@ function appendBrokenFoundationSupportConfig(): void
Bus::assertDispatched(CompareBaselineToTenantJob::class);
});
it('persists the same truthful scope capability decisions before dispatching capture work', function (): void {
it('blocks capture work when the scope still contains unsupported types, while preserving truthful capability context', function (): void {
Bus::fake();
appendBrokenFoundationSupportConfig();
@ -102,10 +104,13 @@ function appendBrokenFoundationSupportConfig(): void
$result = app(BaselineCaptureService::class)->startCapture($profile, $tenant, $user);
expect($result['ok'])->toBeTrue();
$scope = $profile->normalizedScope()->toEffectiveScopeContext(
app(BaselineSupportCapabilityGuard::class),
'capture',
);
$run = $result['run'];
$scope = data_get($run->context, 'effective_scope');
expect($result['ok'])->toBeFalse()
->and($result['reason_code'] ?? null)->toBe(BaselineReasonCodes::CAPTURE_UNSUPPORTED_SCOPE);
expect(data_get($scope, 'truthful_types'))->toBe(['deviceConfiguration', 'roleScopeTag'])
->and(data_get($scope, 'limited_types'))->toBe(['roleScopeTag'])
@ -117,5 +122,5 @@ function appendBrokenFoundationSupportConfig(): void
->and(data_get($scope, 'capabilities.brokenFoundation.support_mode'))->toBe('invalid_support_config')
->and(data_get($scope, 'capabilities.unknownFoundation.support_mode'))->toBeNull();
Bus::assertDispatched(CaptureBaselineSnapshotJob::class);
Bus::assertNotDispatched(CaptureBaselineSnapshotJob::class);
});

View File

@ -362,18 +362,11 @@ public function compare(
}
}
final class FakeGovernanceSubjectTaxonomyRegistry
final class FakeGovernanceSubjectTaxonomyRegistry extends GovernanceSubjectTaxonomyRegistry
{
private readonly GovernanceSubjectTaxonomyRegistry $inner;
public function __construct()
{
$this->inner = new GovernanceSubjectTaxonomyRegistry;
}
public function all(): array
{
return array_values(array_merge($this->inner->all(), [
return array_values(array_merge(parent::all(), [
new GovernanceSubjectType(
domainKey: GovernanceDomainKey::Entra,
subjectClass: GovernanceSubjectClass::Control,
@ -389,66 +382,4 @@ public function all(): array
),
]));
}
public function active(): array
{
return array_values(array_filter(
$this->all(),
static fn (GovernanceSubjectType $subjectType): bool => $subjectType->active,
));
}
public function activeLegacyBucketKeys(string $legacyBucket): array
{
$subjectTypes = array_filter(
$this->active(),
static fn (GovernanceSubjectType $subjectType): bool => $subjectType->legacyBucket === $legacyBucket,
);
$keys = array_map(
static fn (GovernanceSubjectType $subjectType): string => $subjectType->subjectTypeKey,
$subjectTypes,
);
sort($keys, SORT_STRING);
return array_values(array_unique($keys));
}
public function find(string $domainKey, string $subjectTypeKey): ?GovernanceSubjectType
{
foreach ($this->all() as $subjectType) {
if ($subjectType->domainKey->value !== trim($domainKey)) {
continue;
}
if ($subjectType->subjectTypeKey !== trim($subjectTypeKey)) {
continue;
}
return $subjectType;
}
return null;
}
public function isKnownDomain(string $domainKey): bool
{
return $this->inner->isKnownDomain($domainKey);
}
public function allowsSubjectClass(string $domainKey, string $subjectClass): bool
{
return $this->inner->allowsSubjectClass($domainKey, $subjectClass);
}
public function supportsFilters(string $domainKey, string $subjectClass): bool
{
return $this->inner->supportsFilters($domainKey, $subjectClass);
}
public function groupLabel(string $domainKey, string $subjectClass): string
{
return $this->inner->groupLabel($domainKey, $subjectClass);
}
}

View File

@ -6,6 +6,10 @@
$compareJob = file_get_contents(base_path('app/Jobs/CompareBaselineToTenantJob.php'));
expect($compareJob)->toBeString();
expect($compareJob)->toContain('CurrentStateHashResolver');
expect($compareJob)->toContain('compareStrategyRegistry->select(');
expect($compareJob)->toContain('compareStrategyRegistry->resolve(');
expect($compareJob)->toContain('$strategy->compare(');
expect($compareJob)->not->toContain('computeDrift(');
expect($compareJob)->not->toContain('->fingerprint(');
expect($compareJob)->not->toContain('::fingerprint(');

View File

@ -7,6 +7,24 @@
'PolicyNormalizer',
'VersionDiff',
'flattenForDiff',
'computeDrift(',
'effectiveBaselineHash(',
'resolveBaselinePolicyVersionId(',
'selectSummaryKind(',
'buildDriftEvidenceContract(',
'buildRoleDefinitionEvidencePayload(',
'resolveRoleDefinitionVersion(',
'fallbackRoleDefinitionNormalized(',
'roleDefinitionChangedKeys(',
'roleDefinitionPermissionKeys(',
'resolveRoleDefinitionDiff(',
'severityForRoleDefinitionDiff(',
'BaselinePolicyVersionResolver',
'DriftHasher',
'SettingsNormalizer',
'AssignmentsNormalizer',
'ScopeTagsNormalizer',
'IntuneRoleDefinitionNormalizer',
];
$captureForbiddenTokens = [
@ -20,6 +38,9 @@
$compareJob = file_get_contents(base_path('app/Jobs/CompareBaselineToTenantJob.php'));
expect($compareJob)->toBeString();
expect($compareJob)->toContain('CurrentStateHashResolver');
expect($compareJob)->toContain('compareStrategyRegistry->select(');
expect($compareJob)->toContain('compareStrategyRegistry->resolve(');
expect($compareJob)->toContain('$strategy->compare(');
foreach ($compareForbiddenTokens as $token) {
expect($compareJob)->not->toContain($token);

View File

@ -0,0 +1,35 @@
# Specification Quality Checklist: Compare Job Legacy Drift Path Cleanup
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-04-14
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- Validation passed on 2026-04-14 after the initial drafting pass.
- The feature is an internal cleanup, so user value is expressed through architectural honesty, review speed, and regression safety rather than a new operator-facing workflow.

View File

@ -0,0 +1,273 @@
openapi: 3.1.0
info:
title: Compare Job Legacy Drift Cleanup Internal Contract
version: 0.1.0
summary: Internal logical contract for the unchanged baseline compare start and execution path after legacy drift deletion
description: |
This contract is an internal planning artifact for Spec 205. No new HTTP
controllers or routes are introduced. The paths below identify logical
service, job, and guard boundaries that must remain true after the dead
pre-strategy drift path is removed from CompareBaselineToTenantJob.
x-logical-artifact: true
x-compare-job-cleanup-consumers:
- surface: baseline.compare.start
sourceFiles:
- apps/platform/app/Services/Baselines/BaselineCompareService.php
- apps/platform/tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php
mustRemainTrue:
- compare_start_remains_enqueue_only
- deterministic_strategy_selection_recorded_in_run_context
- no_legacy_compare_fallback_at_start
- surface: baseline.compare.execution
sourceFiles:
- apps/platform/app/Jobs/CompareBaselineToTenantJob.php
- apps/platform/app/Support/Baselines/Compare/CompareStrategyRegistry.php
- apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php
mustConsume:
- supported_strategy_selection
- strategy_compare_result
- normalized_strategy_subject_results
- no_legacy_compute_drift_fallback
- surface: baseline.compare.findings
sourceFiles:
- apps/platform/app/Jobs/CompareBaselineToTenantJob.php
mustRemainTrue:
- finding_lifecycle_unchanged
- summary_and_gap_counts_derived_from_strategy_results
- warning_outcomes_unchanged
- reason_translation_unchanged
- operation_run_completion_semantics_unchanged
- surface: baseline.compare.guard
sourceFiles:
- apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php
- apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php
mustEnforce:
- removed_legacy_methods_stay_absent
- orchestration_file_has_one_compare_engine
- surface: baseline.compare.run-guards
sourceFiles:
- apps/platform/tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php
- apps/platform/tests/Feature/Operations/BaselineOperationRunGuardTest.php
- apps/platform/tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php
- apps/platform/tests/Feature/OpsUx/SummaryCountsWhitelistTest.php
mustEnforce:
- baseline_compare_run_lifecycle_semantics_unchanged
- summary_count_keys_remain_whitelisted
- compare_run_context_updates_remain_valid
paths:
/internal/tenants/{tenant}/baseline-profiles/{profile}/compare:
post:
summary: Start baseline compare using the existing strategy-selected flow only
operationId: startBaselineCompareWithoutLegacyFallback
parameters:
- name: tenant
in: path
required: true
schema:
type: integer
- name: profile
in: path
required: true
schema:
type: integer
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CompareLaunchRequest'
responses:
'202':
description: Compare accepted and queued with the strategy-owned execution path only
content:
application/vnd.tenantpilot.baseline-compare-run+json:
schema:
$ref: '#/components/schemas/CompareLaunchEnvelope'
'422':
description: Existing unsupported or mixed-scope preconditions prevented compare from starting
'403':
description: Actor is in scope but lacks compare-start capability
'404':
description: Tenant or baseline profile is outside actor scope
/internal/operation-runs/{run}/baseline-compare/execute:
post:
summary: Execute baseline compare through strategy selection and strategy compare only
operationId: executeBaselineCompareJobWithoutLegacyFallback
parameters:
- name: run
in: path
required: true
schema:
type: integer
responses:
'200':
description: Existing compare run completed through the strategy-owned path with no legacy drift fallback
content:
application/vnd.tenantpilot.baseline-compare-execution+json:
schema:
$ref: '#/components/schemas/CompareExecutionEnvelope'
'409':
description: Existing snapshot, coverage, or strategy preconditions blocked execution
/internal/guards/baseline-compare/no-legacy-drift:
get:
summary: Static invariant proving the orchestration file no longer retains the pre-strategy drift implementation
operationId: assertNoLegacyBaselineCompareJobPath
responses:
'200':
description: Guard passes because the removed legacy methods are absent from the compare job
content:
application/vnd.tenantpilot.compare-job-guard+json:
schema:
$ref: '#/components/schemas/LegacyDriftGuardResult'
components:
schemas:
CompareLaunchRequest:
type: object
additionalProperties: false
required:
- baseline_snapshot_id
- effective_scope
properties:
baseline_snapshot_id:
type: integer
effective_scope:
type: object
additionalProperties: true
origin:
type: string
enum:
- tenant_profile
- compare_matrix
- other_existing_surface
SupportedStrategySelection:
type: object
additionalProperties: false
required:
- selection_state
- strategy_key
- operator_reason
properties:
selection_state:
type: string
enum:
- supported
strategy_key:
type: string
example: intune_policy
operator_reason:
type: string
diagnostics:
type: object
additionalProperties: true
CompareLaunchEnvelope:
type: object
additionalProperties: false
required:
- run_id
- operation_type
- execution_mode
- selected_strategy
- legacy_drift_path_present
properties:
run_id:
type: integer
operation_type:
type: string
enum:
- baseline_compare
execution_mode:
type: string
enum:
- queued
selected_strategy:
$ref: '#/components/schemas/SupportedStrategySelection'
legacy_drift_path_present:
type: boolean
const: false
CompareExecutionEnvelope:
type: object
additionalProperties: false
required:
- run_id
- compare_source
- selected_strategy_key
- no_legacy_compute_drift
- persisted_truths
properties:
run_id:
type: integer
compare_source:
type: string
enum:
- strategy_only
selected_strategy_key:
type: string
example: intune_policy
no_legacy_compute_drift:
type: boolean
const: true
persisted_truths:
type: array
items:
type: string
example:
- operation_runs
- findings
- baseline_compare.context
outputs_preserved:
type: object
additionalProperties: false
properties:
finding_lifecycle:
type: boolean
const: true
summary_counts:
type: boolean
const: true
gap_handling:
type: boolean
const: true
warning_outcomes:
type: boolean
const: true
reason_translation:
type: boolean
const: true
run_completion:
type: boolean
const: true
LegacyDriftGuardResult:
type: object
additionalProperties: false
required:
- status
- compare_job_path
- forbidden_method_names
properties:
status:
type: string
enum:
- pass
compare_job_path:
type: string
example: apps/platform/app/Jobs/CompareBaselineToTenantJob.php
forbidden_method_names:
type: array
items:
type: string
example:
- computeDrift
- effectiveBaselineHash
- resolveBaselinePolicyVersionId
- selectSummaryKind
- buildDriftEvidenceContract
- buildRoleDefinitionEvidencePayload
- resolveRoleDefinitionVersion
- fallbackRoleDefinitionNormalized
- roleDefinitionChangedKeys
- roleDefinitionPermissionKeys
- resolveRoleDefinitionDiff
- severityForRoleDefinitionDiff
invariant:
type: string
example: compare orchestration retains one live strategy-driven execution path

View File

@ -0,0 +1,131 @@
# Data Model: Compare Job Legacy Drift Path Cleanup
## Overview
This feature introduces no new top-level persisted entity and no new runtime or product-facing contract. It removes an obsolete implementation branch from `CompareBaselineToTenantJob` and preserves the existing persisted truths and compare contracts that already drive the live strategy-based compare flow. The OpenAPI document in `contracts/` is a planning-only logical artifact that records invariants for this cleanup; it does not define a new runtime integration surface.
## Existing Persisted Truth Reused Without Change
### Workspace-owned baseline truth
- `baseline_profiles`
- `baseline_snapshots`
- `baseline_snapshot_items`
- Canonical baseline scope payload already stored in profile and run context
These remain the baseline reference truth that compare reads.
### Tenant-owned current-state and operational truth
- `inventory_items`
- `operation_runs` for `baseline_compare`
- findings written by the baseline compare lifecycle
- existing run-context JSON such as `baseline_compare`, `findings`, and `result`
These remain the long-lived operational truths written or consumed by compare.
### Existing evidence inputs reused without change
- policy-version content evidence
- inventory meta evidence
- current-state hash resolution
- coverage and gap context already recorded in the compare run
Spec 205 changes none of these inputs; it only removes a dead alternate computation path.
## Existing Internal Contracts Preserved
### Compare orchestration path
The live orchestration path remains:
1. `CompareBaselineToTenantJob::handle()`
2. `CompareStrategyRegistry::select(...)`
3. `CompareStrategyRegistry::resolve(...)`
4. `strategy->compare(...)`
5. `normalizeStrategySubjectResults(...)`
6. finding upsert, summary aggregation, gap handling, and run completion
No new branch, fallback path, or second engine is introduced.
### CompareStrategySelection
Existing selection metadata remains unchanged and continues to be written into the compare run context.
| Field | Purpose | Change in Spec 205 |
|------|---------|--------------------|
| `selection_state` | Supported vs unsupported strategy state | unchanged |
| `strategy_key` | Active compare strategy family | unchanged |
| `diagnostics` | Secondary strategy selection detail | unchanged |
### CompareOrchestrationContext
Existing strategy input context remains unchanged.
| Field | Purpose | Change in Spec 205 |
|------|---------|--------------------|
| `workspace_id` | Workspace scope for compare run | unchanged |
| `tenant_id` | Tenant scope for compare run | unchanged |
| `baseline_profile_id` | Baseline profile reference | unchanged |
| `baseline_snapshot_id` | Snapshot reference | unchanged |
| `operation_run_id` | Run identity | unchanged |
| `normalized_scope` | Canonical scope payload | unchanged |
| `coverage_context` | Coverage and unsupported-type context | unchanged |
### CompareSubjectResult and CompareFindingCandidate
Existing per-subject compare results and finding projection contracts remain unchanged.
| Contract | Purpose | Change in Spec 205 |
|----------|---------|--------------------|
| `CompareSubjectResult` | Strategy-owned per-subject compare outcome | unchanged |
| `CompareFindingCandidate` | Strategy-neutral finding mutation payload | unchanged |
### OperationRun compare context
The compare run continues to record current strategy, evidence coverage, gap counts, fidelity, reason translation, and result summaries inside the existing context structure. Spec 205 does not add, remove, or rename run-context fields.
### Finding lifecycle output
Finding severity, change type, recurrence key, evidence fidelity, timestamps, reopen behavior, and auto-close behavior remain unchanged. Spec 205 only preserves the live path that already feeds these outputs.
## Deleted Internal Cluster
Current repository inspection confirms one dead implementation cluster anchored by `computeDrift()` inside `CompareBaselineToTenantJob`, plus exclusive helpers clustered beneath it. The current candidate delete set includes:
- `computeDrift()`
- `effectiveBaselineHash()`
- `resolveBaselinePolicyVersionId()`
- `selectSummaryKind()`
- `buildDriftEvidenceContract()`
- `buildRoleDefinitionEvidencePayload()`
- `resolveRoleDefinitionVersion()`
- `fallbackRoleDefinitionNormalized()`
- `roleDefinitionChangedKeys()`
- `roleDefinitionPermissionKeys()`
- `resolveRoleDefinitionDiff()`
- `severityForRoleDefinitionDiff()`
The final delete list is confirmed by call-graph inspection during implementation. Any method still used by the live orchestration path remains out of scope.
## Relationships
- One `baseline_compare` run selects one supported strategy.
- One selected strategy processes many compare subjects.
- One `CompareSubjectResult` may yield zero or one `CompareFindingCandidate`.
- Existing finding and summary writers consume the strategy result contracts directly.
- The legacy drift cluster is not part of any required runtime relationship after Spec 203 and is therefore removed.
## Validation Rules
1. `CompareBaselineToTenantJob::handle()` must not call `computeDrift()` or any helper used exclusively by that legacy path.
2. Compare execution must continue to run through strategy selection, strategy resolution, and `strategy->compare(...)`.
3. Existing `OperationRun` status, outcome, summary-count, and context semantics must remain unchanged.
4. Existing finding lifecycle behavior must remain driven by normalized strategy subject results.
5. No new persistence, contract, or state family may be introduced as part of the cleanup.
## State Transitions
No new state transition is introduced.
Existing compare run transitions such as queued -> running -> completed or blocked remain unchanged, and finding lifecycle transitions remain governed by the current writers and services.

View File

@ -0,0 +1,198 @@
# Implementation Plan: Compare Job Legacy Drift Path Cleanup
**Branch**: `205-compare-job-cleanup` | **Date**: 2026-04-14 | **Spec**: `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/205-compare-job-cleanup/spec.md`
**Input**: Feature specification from `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/205-compare-job-cleanup/spec.md`
**Note**: This plan treats Spec 205 as a mechanical closure cleanup. It removes only the dead pre-strategy drift-compute path from `CompareBaselineToTenantJob`, keeps the current strategy-driven compare execution unchanged, and uses focused regression plus guard coverage to prove no behavior drift.
## Summary
Delete `computeDrift()` and its exclusive helper cluster from `CompareBaselineToTenantJob`, preserve the existing `CompareStrategyRegistry` -> `IntuneCompareStrategy` execution path, remove dead imports and misleading internal descriptions that survive only because of the retained legacy block, and verify unchanged behavior through focused compare execution, finding, and guard tests.
## Technical Context
**Language/Version**: PHP 8.4.15
**Primary Dependencies**: Laravel 12, Filament v5, Livewire v4, Pest v4, Laravel Sail, existing `BaselineCompareService`, `CompareBaselineToTenantJob`, `CompareStrategyRegistry`, `IntuneCompareStrategy`, `CurrentStateHashResolver`, and current finding lifecycle services
**Storage**: PostgreSQL via existing baseline snapshots, baseline snapshot items, inventory items, `operation_runs`, findings, and current run-context JSON; no new storage planned
**Testing**: Pest feature and guard tests run through Laravel Sail, with focused compare execution and file-content guard coverage
**Target Platform**: Laravel web application under `apps/platform` with queue-backed compare execution in Sail/Docker
**Project Type**: web application in a monorepo (`apps/platform` plus `apps/website`)
**Performance Goals**: Preserve current compare start latency and compare job throughput, add no new remote calls or DB writes, and keep operator-facing compare and monitoring surfaces behaviorally unchanged
**Constraints**: No behavior change, no new abstraction or persistence, no operator-facing surface changes, no `OperationRun` lifecycle changes, and keep the PR mechanically small and reviewable
**Scale/Scope**: One queued compare job, one compare start service boundary, one active strategy registry, one active Intune strategy, existing finding and run writers, and a small focused regression slice
## Constitution Check
*GATE: Passed before Phase 0 research. Re-checked after Phase 1 design and still passing because the feature removes code without altering scope, auth, persistence, or UI contracts.*
| Principle | Pre-Research | Post-Design | Notes |
|-----------|--------------|-------------|-------|
| Inventory-first / snapshots-second | PASS | PASS | Compare still reads existing workspace baseline snapshots and inventory-backed current state; no new compare truth is introduced. |
| Read/write separation | PASS | PASS | Existing compare runs still write only current run, finding, and audit truth; the cleanup adds no new write path. |
| Graph contract path | PASS | PASS | No new Microsoft Graph path or contract is introduced. |
| Deterministic capabilities | PASS | PASS | Existing strategy selection and capability behavior remain unchanged because the registry and strategy classes stay intact. |
| Workspace + tenant isolation | PASS | PASS | No workspace, tenant, or route-scope behavior changes are planned. |
| RBAC-UX authorization semantics | PASS | PASS | No authorization rules, capability checks, or cross-plane behavior are changed. |
| Run observability / Ops-UX | PASS | PASS | Existing `baseline_compare` run creation, summary counts, and completion semantics remain authoritative and unchanged. |
| Data minimization | PASS | PASS | No new persisted diagnostics or helper truth is added; dead internal code is removed instead. |
| Proportionality / anti-bloat | PASS | PASS | The feature deletes an obsolete path and introduces no new structure. |
| No premature abstraction | PASS | PASS | No new factory, resolver, registry, strategy, or support layer is introduced. |
| Persisted truth / behavioral state | PASS | PASS | No new table, stored artifact, status family, or reason family is added. |
| UI semantics / few layers | PASS | PASS | No new presentation layer or surface behavior is introduced. |
| Filament v5 / Livewire v4 compliance | PASS | PASS | No Filament or Livewire API changes are part of this cleanup. |
| Provider registration location | PASS | PASS | No panel or provider change is required; Laravel 11+ provider registration remains in `bootstrap/providers.php`. |
| Global search hard rule | PASS | PASS | No searchable resource or search behavior is touched. |
| Destructive action safety | PASS | PASS | No destructive action is added or changed. |
| Asset strategy | PASS | PASS | No new assets are introduced and existing `filament:assets` deployment behavior remains unchanged. |
## Filament-Specific Compliance Notes
- **Livewire v4.0+ compliance**: Unchanged. The feature touches no Filament surface or Livewire component and does not introduce legacy APIs.
- **Provider registration location**: Unchanged. If any panel/provider review is needed later, Laravel 11+ still requires `bootstrap/providers.php`.
- **Global search**: No globally searchable resource is added or changed.
- **Destructive actions**: No destructive action is introduced; existing confirmation and authorization rules remain untouched.
- **Asset strategy**: No new panel or shared assets are required. Deployment handling of `cd apps/platform && php artisan filament:assets` remains unchanged.
- **Testing plan**: Focus on the required compare cleanup pack only: compare execution and findings regressions, gap and reason-code coverage, `Spec116OneEngineGuardTest`, `Spec118NoLegacyBaselineDriftGuardTest`, existing `OperationRun` and summary-count guards, and the enqueue-path matrix action regression. No new page, widget, relation manager, or action surface coverage is required.
## Phase 0 Research
Research outcomes are captured in `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/205-compare-job-cleanup/research.md`.
Key decisions:
- Treat the current `CompareStrategyRegistry` -> `IntuneCompareStrategy` execution path as the only supported compare engine.
- Delete the dead `computeDrift()` cluster rather than retaining it as deprecated or archived code.
- Preserve `CompareSubjectResult`, finding upsert, summary aggregation, gap handling, and run completion semantics exactly as they currently operate through the live strategy path.
- Use one focused compare pack covering execution fidelity, finding lifecycle, gap and reason outcomes, `OperationRun` lifecycle guards, summary-count guards, and the no-legacy orchestration guard as the minimum reliable regression slice.
- Keep the contract artifact logical and internal, documenting invariants of the unchanged execution boundary instead of inventing a new external API.
## Phase 1 Design
Design artifacts are created under `/Users/ahmeddarrazi/Documents/projects/TenantAtlas/specs/205-compare-job-cleanup/`:
- `research.md`: cleanup decisions, rationale, and rejected alternatives
- `data-model.md`: existing persisted truth and internal compare contracts preserved by the cleanup
- `contracts/compare-job-legacy-drift-cleanup.logical.openapi.yaml`: logical internal contract for the unchanged compare start and execution boundaries plus the no-legacy guard invariant
- `quickstart.md`: implementation and verification order for the cleanup
Design decisions:
- `CompareBaselineToTenantJob` remains the compare execution entry point, but only the live orchestration methods stay after cleanup.
- `CompareStrategyRegistry`, `IntuneCompareStrategy`, `CompareStrategySelection`, `CompareOrchestrationContext`, `CompareSubjectResult`, and `CompareFindingCandidate` remain reused unchanged.
- Existing persisted truth in baseline snapshots, inventory, findings, and `operation_runs` remains authoritative; no migration or compatibility layer is added.
- Guard coverage remains the explicit enforcement point preventing legacy drift computation from re-entering the orchestration file.
- Existing `OperationRun` lifecycle and summary-count guards remain part of the required verification surface because the cleanup still edits the compare executor.
- No route, UI, RBAC, or `OperationRun` design change is planned.
## Project Structure
### Documentation (this feature)
```text
specs/205-compare-job-cleanup/
├── plan.md
├── research.md
├── data-model.md
├── quickstart.md
├── spec.md
├── contracts/
│ └── compare-job-legacy-drift-cleanup.logical.openapi.yaml
└── checklists/
└── requirements.md
```
### Source Code (repository root)
```text
apps/platform/
├── app/
│ ├── Jobs/
│ │ └── CompareBaselineToTenantJob.php
│ ├── Services/
│ │ └── Baselines/
│ │ ├── BaselineCompareService.php
│ │ ├── CurrentStateHashResolver.php
│ │ └── Evidence/
│ └── Support/
│ └── Baselines/
│ └── Compare/
│ ├── CompareStrategyRegistry.php
│ ├── CompareStrategySelection.php
│ ├── CompareSubjectResult.php
│ ├── CompareFindingCandidate.php
│ └── IntuneCompareStrategy.php
└── tests/
├── Feature/
│ ├── BaselineDriftEngine/
│ │ └── FindingFidelityTest.php
│ ├── Baselines/
│ │ ├── BaselineCompareFindingsTest.php
│ │ ├── BaselineCompareGapClassificationTest.php
│ │ ├── BaselineCompareWhyNoFindingsReasonCodeTest.php
│ │ └── BaselineCompareMatrixCompareAllActionTest.php
│ └── Guards/
│ ├── Spec116OneEngineGuardTest.php
│ ├── Spec118NoLegacyBaselineDriftGuardTest.php
│ └── OperationLifecycleOpsUxGuardTest.php
│ ├── Operations/
│ │ └── BaselineOperationRunGuardTest.php
│ └── OpsUx/
│ ├── OperationSummaryKeysSpecTest.php
│ └── SummaryCountsWhitelistTest.php
```
**Structure Decision**: Keep the cleanup inside the existing compare orchestration file and current compare regression surfaces. No new namespace, support layer, or package structure is introduced.
## Complexity Tracking
No constitution exception or complexity justification is required. Spec 205 removes an obsolete implementation branch and introduces no new persistence, abstraction, state family, or semantic framework.
## Proportionality Review
Not triggered. This feature introduces no new enum or status family, DTO or presenter layer, persisted artifact, interface or registry, or cross-domain taxonomy.
## Implementation Strategy
### Phase A - Confirm dead call graph
- Confirm that `handle()` no longer reaches `computeDrift()` or its candidate helper cluster.
- Confirm that the live path still runs through strategy selection, strategy resolution, `strategy->compare(...)`, normalization, finding upsert, and run completion.
- Record the final helper delete list before editing to avoid removing shared orchestration methods.
### Phase B - Delete the legacy drift cluster
- Remove `computeDrift()` and every helper method used exclusively by that legacy path.
- Remove only the imports, comments, and internal descriptions that become dead because of the delete.
- Keep shared orchestration helpers such as evidence resolution, result normalization, summary aggregation, gap merging, and finding lifecycle methods untouched.
### Phase C - Preserve the live orchestration contract
- Leave `BaselineCompareService`, `CompareStrategyRegistry`, and `IntuneCompareStrategy` behavior unchanged unless a direct compile or test failure requires a minimal follow-up.
- Preserve the existing `baseline_compare` run context shape, summary count rules, gap handling, reason translation, and finding lifecycle semantics.
- Avoid any naming sweep, contract redesign, or opportunistic cleanup outside the dead cluster.
### Phase D - Guard and regression verification
- Keep or tighten the existing no-legacy guard so the removed path cannot silently re-enter the orchestration file.
- Run focused compare execution, gap and reason-code regression, and `OperationRun` lifecycle and summary-count guard tests to prove the delete is mechanically safe.
- Format the touched PHP files with Pint after the cleanup is implemented.
## Risk Assessment
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| A supposedly dead helper is still used by the live orchestration path | High | Medium | Confirm call sites before deletion and keep the initial regression pack focused on execution, findings, gap and reason outcomes, and run-lifecycle guards. |
| The cleanup grows into a broader refactor while the job file is open | Medium | Medium | Constrain edits to dead methods, direct import fallout, and guard or test changes required by the delete. |
| Existing guard tests are too weak or too token-specific to prevent reintroduction | Medium | Medium | Reuse `Spec118NoLegacyBaselineDriftGuardTest` and extend it with the removed method names only if the current assertions do not cover the dead-path cluster clearly enough. |
| A regression test depends on deleted internal structure rather than behavior | Medium | Low | Update such tests to assert live compare outcomes and orchestration invariants rather than private helper presence. |
## Test Strategy
- Run `tests/Feature/BaselineDriftEngine/FindingFidelityTest.php` as the primary execution and evidence-fidelity regression slice.
- Run `tests/Feature/Baselines/BaselineCompareFindingsTest.php` to protect finding generation, recurrence, summary counts, and run completion outcomes.
- Run `tests/Feature/Baselines/BaselineCompareGapClassificationTest.php` and `tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php` to protect gap handling, warning outcomes, and reason translation behavior.
- Run `tests/Feature/Guards/Spec116OneEngineGuardTest.php` to keep the one-engine orchestration invariant explicit while the dead fallback cluster is removed.
- Run `tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php`, `tests/Feature/Operations/BaselineOperationRunGuardTest.php`, `tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php`, and `tests/Feature/OpsUx/SummaryCountsWhitelistTest.php` to keep `OperationRun` lifecycle and summary-count guarantees intact.
- Run `tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php` to lock the orchestration boundary against legacy drift helper re-entry.
- Run `tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php` as the required enqueue-path regression slice for the focused cleanup pack.
- Run `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` after the code change.

View File

@ -0,0 +1,101 @@
# Quickstart: Compare Job Legacy Drift Path Cleanup
## Goal
Remove the obsolete pre-strategy drift-compute cluster from `CompareBaselineToTenantJob` while keeping the current strategy-driven compare workflow, finding lifecycle, and run semantics unchanged.
## Prerequisites
1. Work on branch `205-compare-job-cleanup`.
2. Ensure the platform containers are available:
```bash
cd apps/platform && ./vendor/bin/sail up -d
```
3. Keep Spec 203's strategy extraction artifacts available because the cleanup assumes that strategy-driven compare execution is already the live path.
## Recommended Implementation Order
### 1. Confirm the live call graph before editing
Verify the current live path and the candidate legacy cluster:
```bash
cd apps/platform && rg -n "compareStrategyRegistry->select|compareStrategyRegistry->resolve|strategy->compare" app/Jobs/CompareBaselineToTenantJob.php app/Services/Baselines/BaselineCompareService.php
cd apps/platform && rg -n "computeDrift|effectiveBaselineHash|resolveBaselinePolicyVersionId|selectSummaryKind|buildDriftEvidenceContract|buildRoleDefinitionEvidencePayload|resolveRoleDefinitionVersion|fallbackRoleDefinitionNormalized|roleDefinitionChangedKeys|roleDefinitionPermissionKeys|resolveRoleDefinitionDiff|severityForRoleDefinitionDiff" app/Jobs/CompareBaselineToTenantJob.php
```
If additional exclusive helpers are found adjacent to the dead cluster, add them to the delete list only after confirming they are not used by the live path.
### 2. Lock the current behavior with the focused regression slice
Run the minimum reliable compare pack before deleting anything:
```bash
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/BaselineDriftEngine/FindingFidelityTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareFindingsTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareGapClassificationTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/Spec116OneEngineGuardTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Operations/BaselineOperationRunGuardTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/OpsUx/SummaryCountsWhitelistTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php
```
Run the enqueue-path slice as part of the required focused pack:
```bash
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php
```
### 3. Delete the legacy drift cluster only
Remove:
- `computeDrift()`
- helper methods used exclusively by that path
- imports and internal descriptions that only exist because of those methods
Do not redesign `CompareStrategyRegistry`, `IntuneCompareStrategy`, run-context shapes, or finding lifecycle behavior while the job file is open.
### 4. Tighten or preserve the no-legacy guard
If the current guard does not explicitly block the removed helper names, extend it minimally so CI fails if the legacy drift cluster reappears in `CompareBaselineToTenantJob`.
### 5. Re-run the focused regression slice
After the delete, re-run the same focused pack:
```bash
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/BaselineDriftEngine/FindingFidelityTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareFindingsTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareGapClassificationTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/Spec116OneEngineGuardTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Operations/BaselineOperationRunGuardTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/OpsUx/SummaryCountsWhitelistTest.php
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php
```
Re-run the enqueue-path slice as part of the same focused pack:
```bash
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php
```
## Final Validation
1. Format touched PHP files:
```bash
cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent
```
2. Re-check that the live compare path still flows through strategy selection and `strategy->compare(...)`.
3. Confirm the compare run still completes with the same operator-visible outcome, gap and warning semantics, reason translation, and finding behavior as before.
4. Keep the PR limited to dead-path deletion, direct fallout cleanup, and the minimal regression or guard updates required by the delete.

View File

@ -0,0 +1,41 @@
# Research: Compare Job Legacy Drift Path Cleanup
## Decision 1: Treat the strategy-driven compare path as the only authoritative execution engine
- **Decision**: Use the existing `CompareStrategyRegistry` -> `IntuneCompareStrategy` path as the sole supported compare execution boundary.
- **Rationale**: Current code inspection shows `CompareBaselineToTenantJob::handle()` selecting a strategy, resolving it, and calling `strategy->compare(...)` before normalizing subject results and writing findings. No productive call path from `handle()` reaches the retained monolithic `computeDrift()` block.
- **Alternatives considered**:
- Keep the legacy block as a documented fallback. Rejected because it leaves the file structurally dishonest and suggests a second engine still exists.
- Add a feature flag between strategy and legacy execution. Rejected because there is no legitimate second execution mode left to preserve.
## Decision 2: Delete the dead drift cluster instead of archiving or deprecating it
- **Decision**: Remove `computeDrift()` and its exclusive helper cluster directly from `CompareBaselineToTenantJob`.
- **Rationale**: The retained cluster duplicates pre-strategy compare logic that has already been extracted into the active strategy implementation. Keeping it in place continues to mislead reviewers and inflates the orchestration file without operational value.
- **Alternatives considered**:
- Move the dead methods to a trait or archive class. Rejected because it preserves confusion and ownership cost without any runtime benefit.
- Leave the methods in place with a deprecation comment. Rejected because dead code still obscures the real call graph even when labeled.
## Decision 3: Preserve existing compare contracts, findings, and run semantics unchanged
- **Decision**: Keep `CompareStrategyRegistry`, `IntuneCompareStrategy`, `CompareStrategySelection`, `CompareSubjectResult`, `CompareFindingCandidate`, existing finding writers, and existing run context semantics unchanged.
- **Rationale**: Spec 205 is a closure cleanup, not a second strategy extraction spec. The safest path is deletion of dead code while leaving the live contracts and persisted truths untouched.
- **Alternatives considered**:
- Fold in additional compare refactors while editing the job. Rejected because that turns a narrow cleanup into a mixed review.
- Rename or reframe current compare contracts for symmetry. Rejected because it is unrelated to dead-path removal.
## Decision 4: Use a focused compare plus run-guard pack as the minimum regression slice
- **Decision**: Validate the cleanup with `FindingFidelityTest`, `BaselineCompareFindingsTest`, `BaselineCompareGapClassificationTest`, `BaselineCompareWhyNoFindingsReasonCodeTest`, `Spec116OneEngineGuardTest`, `OperationLifecycleOpsUxGuardTest`, `BaselineOperationRunGuardTest`, `OperationSummaryKeysSpecTest`, `SummaryCountsWhitelistTest`, `Spec118NoLegacyBaselineDriftGuardTest`, and `BaselineCompareMatrixCompareAllActionTest` as the required focused regression pack.
- **Rationale**: `FindingFidelityTest` exercises the compare execution path and evidence selection behavior, `BaselineCompareFindingsTest` protects finding lifecycle and summary outcomes, the gap and reason-code tests protect warning and reason semantics, `Spec116OneEngineGuardTest` keeps the one-engine orchestration invariant explicit, the `OperationRun` and summary-count guards protect lifecycle invariants, and the legacy guard keeps helper re-entry visible in CI. Together they provide high confidence for a mechanical delete without requiring a broad slow suite.
- **Alternatives considered**:
- Run the full baseline compare suite for every cleanup iteration. Rejected as optional rather than required for a small internal delete.
- Skip targeted tests and rely only on formatting or static inspection. Rejected as insufficient confidence.
## Decision 5: Keep the planning artifacts logical and invariant-focused
- **Decision**: Document the cleanup through a logical internal contract and a no-new-entity data model rather than inventing cleanup-specific services, APIs, or persistence.
- **Rationale**: The plan workflow still needs explicit design artifacts, but Spec 205 adds no new feature surface. The correct documentation shape is therefore an invariant record of the unchanged compare boundaries after dead-code deletion.
- **Alternatives considered**:
- Skip the contract artifact entirely because no new endpoint exists. Rejected because the planning workflow requires a contract deliverable.
- Invent a cleanup-specific service or endpoint in the design docs. Rejected because it would introduce fake architecture not warranted by the spec.

View File

@ -0,0 +1,162 @@
# Feature Specification: Compare Job Legacy Drift Path Cleanup
**Feature Branch**: `205-compare-job-cleanup`
**Created**: 2026-04-14
**Status**: Draft
**Input**: User description: "Compare Job Legacy Drift Path Cleanup"
- **Type**: Cleanup / closure hardening
- **Priority**: Medium
- **Depends on**: Spec 203 - Baseline Compare Engine Strategy Extraction
- **Related to**: Spec 202 - Governance Subject Taxonomy and Baseline Scope V2; Spec 204 - Platform Core Vocabulary Hardening
- **Recommended timing**: Immediate close-out before the next expansion-focused strand
- **Blocks**: No strategic work
- **Does not block**: Further platform work if completed as a short closure PR
## Spec Candidate Check *(mandatory - SPEC-GATE-001)*
- **Problem**: The baseline compare orchestration unit still retains an obsolete pre-strategy drift computation block that no longer reflects how compare execution actually works.
- **Today's failure**: Contributors and reviewers must spend time proving which compare path is live, while architecture audits still see false monolithic coupling that has already been structurally replaced.
- **User-visible improvement**: No operator workflow changes, but the codebase becomes more trustworthy, easier to audit, and faster to maintain because the live compare architecture is no longer obscured by dead logic.
- **Smallest enterprise-capable version**: Remove the dead legacy drift block and its exclusively related helpers, clean direct fallout such as unused dependencies and misleading internal descriptions, and confirm that the current strategy-driven compare behavior remains unchanged.
- **Explicit non-goals**: No new abstraction, no naming sweep, no evidence-contract redesign, no schema change, no UI change, no new strategy, and no opportunistic follow-up refactor.
- **Permanent complexity imported**: None beyond minimal regression coverage or comment cleanup needed to lock in the deletion.
- **Why now**: Specs 202, 203, and 204 already established the current architecture. Leaving the old drift block behind keeps the pre-expansion foundation structurally dishonest even though the behavioral migration is complete.
- **Why not local**: A narrower action than deletion would still leave the same dead-path ambiguity in place, so the architectural trust gap would remain.
- **Approval class**: Cleanup
- **Red flags triggered**: Scope-creep risk if broader naming or architecture work is mixed into the cleanup.
- **Score**: Nutzen: 2 | Dringlichkeit: 2 | Scope: 2 | Komplexitaet: 2 | Produktnaehe: 1 | Wiederverwendung: 1 | **Gesamt: 10/12**
- **Decision**: approve
## Spec Scope Fields *(mandatory)*
- **Scope**: workspace, tenant
- **Primary Routes**:
- No new or changed routes
- Existing verification anchors remain:
- `/admin/t/{tenant}/baseline-compare`
- `/admin/operations`
- `/admin/operations/{run}`
- **Data Ownership**:
- Existing tenant-owned compare runs, findings, summaries, and warnings remain authoritative.
- No new persistence, ownership boundary, or data shape is introduced.
- **RBAC**:
- Existing compare, monitoring, and tenant access rules remain unchanged.
- No new membership rule, capability, or operator-facing action is introduced.
- No destructive action behavior changes are included.
## Assumptions & Dependencies
- Spec 203 already made strategy-driven compare execution the authoritative live path for the baseline compare orchestration unit.
- The retained legacy drift block is not part of the productive call graph and can be removed without functional redesign.
- Any test or inspection logic that still depends on deleted internal helper structure is considered stale and may be narrowed to current observable behavior.
- Successful completion depends on focused regression coverage for strategy dispatch, compare execution, finding lifecycle behavior, summary computation, gap handling, warning handling, and run completion.
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Read the live compare architecture without dead-path noise (Priority: P1)
As a contributor reviewing baseline compare behavior, I want the orchestration unit to show only the active compare path so that I can understand current architecture without first disproving a retained legacy path.
**Why this priority**: This is the core value of the cleanup. If the dead path remains visible, the repository continues to teach the wrong architecture.
**Independent Test**: Inspect the orchestration unit after cleanup and confirm that only the active strategy-driven path remains while regression checks still pass.
**Acceptance Scenarios**:
1. **Given** the compare orchestration unit currently contains both live orchestration and retained legacy drift remnants, **When** a contributor reviews the file after cleanup, **Then** they can trace one active compare execution path without encountering a parallel legacy implementation.
2. **Given** a reviewer follows the productive compare call graph after cleanup, **When** they inspect the orchestration flow, **Then** the repository no longer suggests that the removed pre-strategy drift logic is still active.
---
### User Story 2 - Preserve current compare behavior while removing dead code (Priority: P1)
As a product maintainer, I want the dead-code removal to leave compare behavior unchanged so that the cleanup can merge as a safe closure PR rather than another hidden refactor.
**Why this priority**: The cleanup is only valuable if it preserves the current compare lifecycle and does not force a second architecture review.
**Independent Test**: Run focused automated regression checks for the current compare flow and confirm that expected outcomes remain unchanged after the delete.
**Acceptance Scenarios**:
1. **Given** existing baseline compare regression coverage, **When** the cleanup lands, **Then** strategy selection, compare execution, finding generation, summary computation, gap handling, warning handling, recurrence behavior, and run completion remain green.
2. **Given** a compare run that already uses the current strategy infrastructure, **When** it executes after cleanup, **Then** it produces the same class of persisted results and operator-observable outcomes as before.
---
### User Story 3 - Keep the review diff mechanically narrow (Priority: P2)
As a reviewer, I want the cleanup diff to stay limited to dead-path deletion and its direct fallout so that I can approve it quickly without re-reviewing unrelated architecture decisions.
**Why this priority**: The main delivery risk is not deletion itself, but that the cleanup grows into an opportunistic mixed refactor.
**Independent Test**: Inspect the resulting PR scope and confirm that it is limited to `CompareBaselineToTenantJob`, the focused compare guard and regression files that prove the delete is safe, and only direct blocker-driven follow-up in `BaselineCompareService` or `IntuneCompareStrategy` if the implementation explicitly justifies it.
**Acceptance Scenarios**:
1. **Given** nearby follow-up ideas exist, **When** the cleanup is implemented, **Then** the final diff touches `CompareBaselineToTenantJob`, the focused compare guard and regression files, and no other production file except a direct blocker-driven follow-up in `BaselineCompareService` or `IntuneCompareStrategy`.
2. **Given** adjacent imports, comments, or docblocks still imply the removed path exists, **When** the cleanup finishes, **Then** only those directly obsolete remnants are adjusted and no unrelated rename, schema, or UI work appears in the same PR.
### Edge Cases
- A seemingly legacy helper still has an indirect productive call site or compatibility responsibility.
- A regression test or inspection helper still asserts deleted internal structure instead of current compare behavior.
- Summary, warning, or finding behavior depends on normalization that must remain preserved through the active path even after the dead block is removed.
- Internal comments or docblocks still describe a fallback or alternate drift path that no longer exists.
## Requirements *(mandatory)*
**Constitution alignment (required):** This feature does not introduce a new external integration, new write pathway, or new long-running workflow. It removes dead internal compare logic from an existing execution unit and keeps existing tenant isolation, run observability, and audit behavior unchanged. Regression coverage must prove there is no behavior change.
**Constitution alignment (PROP-001 / ABSTR-001 / PERSIST-001 / STATE-001 / BLOAT-001):** The cleanup introduces no new persistence, abstraction, state family, or semantic layer. The narrowest correct implementation is deletion of the dead path and cleanup of its direct fallout.
**Constitution alignment (OPS-UX):** Existing run creation, lifecycle ownership, summary-count rules, and three-surface feedback behavior remain unchanged. Any touched regression coverage must continue to protect the current compare run lifecycle.
**Constitution alignment (RBAC-UX):** No authorization behavior changes are part of this feature. Existing workspace and tenant access rules, including current `404` and `403` behavior, remain untouched.
**Constitution alignment (OPS-EX-AUTH-001):** Not applicable.
**Constitution alignment (BADGE-001):** Not applicable; no status or badge semantics change.
**Constitution alignment (UI-FIL-001):** Not applicable; no Filament or Blade surface changes are introduced.
**Constitution alignment (UI-NAMING-001):** Operator-facing labels remain unchanged. Only misleading internal comments or docblocks may be corrected.
**Constitution alignment (DECIDE-001):** No new or changed operator-facing decision surface is introduced.
**Constitution alignment (UI-CONST-001 / UI-SURF-001 / ACTSURF-001 / UI-HARD-001 / UI-EX-001 / UI-REVIEW-001 / HDR-001):** No surface or action changes are in scope.
**Constitution alignment (ACTSURF-001 - action hierarchy):** Not applicable; no header, row, or bulk action structure changes are introduced.
**Constitution alignment (OPSURF-001):** Not applicable; no operator-facing surface is added or materially refactored.
**Constitution alignment (UI-SEM-001 / LAYER-001 / TEST-TRUTH-001):** The feature removes redundant legacy logic instead of adding a new interpretation layer. Tests stay focused on behavior and architectural truth rather than thin indirection.
**Constitution alignment (Filament Action Surfaces):** Not applicable.
**Constitution alignment (UX-001 - Layout & Information Architecture):** Not applicable.
### Functional Requirements
- **FR-205-001 Single active compare path**: The baseline compare orchestration unit MUST retain only the active strategy-driven compare execution path.
- **FR-205-002 Legacy drift removal**: The obsolete pre-strategy drift computation block retained in the orchestration unit MUST be removed.
- **FR-205-003 Helper cleanup**: Any helper method, local utility, or internal dependency used exclusively by the removed legacy path MUST also be removed.
- **FR-205-004 Truthful dependency surface**: After cleanup, imports, comments, and docblocks in the orchestration unit MUST reflect only currently active dependencies and behavior.
- **FR-205-005 No behavioral reshaping**: The cleanup MUST NOT change strategy selection, compare execution, finding generation, summary computation, gap handling, warning handling, recurrence behavior, reason handling, or run completion behavior.
- **FR-205-006 No speculative follow-up work**: The cleanup MUST NOT introduce new abstractions, naming generalizations, schema changes, UI changes, or unrelated refactors.
- **FR-205-007 Regression proof**: Automated regression coverage MUST demonstrate that the active strategy-driven compare path still executes correctly after the cleanup.
- **FR-205-008 Call-graph safety**: Before the cleanup is considered complete, the removed legacy path and its exclusive helpers MUST have no remaining productive call sites in the surrounding production code.
### Non-Functional Requirements
- **NFR-205-001 Reviewability**: The resulting change set MUST be limited to `CompareBaselineToTenantJob`, the focused compare guard and regression files needed to prove delete safety, and only direct blocker-driven follow-up in `BaselineCompareService` or `IntuneCompareStrategy` when explicitly justified.
- **NFR-205-002 Architectural honesty**: After cleanup, an architecture review of the compare orchestration unit MUST find one authoritative compare execution path rather than a retained parallel legacy implementation.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-205-001**: A contributor can inspect the compare orchestration unit and identify a single active compare execution path without needing to rule out a retained parallel legacy path.
- **SC-205-002**: Focused automated checks covering the current strategy-driven compare flow pass after the cleanup with no newly introduced failures.
- **SC-205-003**: Review of the cleanup diff shows touched files limited to `CompareBaselineToTenantJob`, the focused compare guard and regression files, and at most a direct blocker-driven follow-up in `BaselineCompareService` or `IntuneCompareStrategy`.
- **SC-205-004**: Post-cleanup architecture review no longer reports a retained pre-strategy drift computation block in the compare orchestration unit.

View File

@ -0,0 +1,194 @@
# Tasks: Compare Job Legacy Drift Path Cleanup
**Input**: Design documents from `/specs/205-compare-job-cleanup/`
**Prerequisites**: `plan.md`, `spec.md`, `research.md`, `data-model.md`, `contracts/compare-job-legacy-drift-cleanup.logical.openapi.yaml`, `quickstart.md`
**Tests**: Required. This cleanup changes runtime compare orchestration code in `CompareBaselineToTenantJob` and must keep the current strategy-driven compare path green through focused Pest regression and guard coverage.
**Operations**: Existing `baseline_compare` `OperationRun` behavior remains unchanged. No new run type, feedback surface, or monitoring path is introduced.
**RBAC**: No authorization change is in scope. Existing compare and monitoring permissions remain authoritative, and tasks must avoid introducing RBAC drift while touching the orchestration file.
**Operator Surfaces**: No operator-facing surface change is in scope. Existing tenant compare and monitoring routes remain verification anchors only.
**Filament UI Action Surfaces**: No Filament resource, page, relation manager, or action-hierarchy change is planned.
**Proportionality**: This spec removes dead code only and must not introduce new abstractions, persistence, or semantic layers.
**Organization**: Tasks are grouped by user story so the cleanup can be implemented and verified in narrow, reviewable increments. Recommended delivery order is `US1 -> US2 -> US3`, with `US1 + US2` forming the practical merge-ready slice.
## Phase 1: Setup (Shared Baseline)
**Purpose**: Capture the full required pre-cleanup regression baseline and inspect the active compare boundary before editing the orchestration file.
- [X] T001 [P] Capture the required pre-cleanup regression baseline by running `apps/platform/tests/Feature/BaselineDriftEngine/FindingFidelityTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareFindingsTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareGapClassificationTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php`, `apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php`, `apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php`, `apps/platform/tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php`, `apps/platform/tests/Feature/Operations/BaselineOperationRunGuardTest.php`, `apps/platform/tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php`, `apps/platform/tests/Feature/OpsUx/SummaryCountsWhitelistTest.php`, and `apps/platform/tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php`
- [X] T002 [P] Inspect the live compare dispatch and candidate legacy helper cluster in `apps/platform/app/Jobs/CompareBaselineToTenantJob.php` and `apps/platform/app/Services/Baselines/BaselineCompareService.php`
**Checkpoint**: The team has a known-good full focused baseline and a confirmed starting map of the live compare path.
---
## Phase 2: Foundational (Blocking Call-Graph Confirmation)
**Purpose**: Confirm the dead-vs-live method boundary so the cleanup deletes only unreachable logic.
**CRITICAL**: No user story work should begin until this phase is complete.
- [X] T003 [P] Map exclusive callers for `computeDrift()` and its adjacent helper cluster in `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`
- [X] T004 [P] Review `apps/platform/app/Support/Baselines/Compare/CompareStrategyRegistry.php` and `apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php` to confirm the live strategy contract needs no structural change for this cleanup
**Checkpoint**: The delete list is confirmed and the live strategy-owned path is explicitly out of scope for redesign.
---
## Phase 3: User Story 1 - Read the live compare architecture without dead-path noise (Priority: P1) MVP
**Goal**: Remove the retained monolithic drift-compute path so the compare job shows one real execution engine instead of a parallel historical implementation.
**Independent Test**: Inspect `apps/platform/app/Jobs/CompareBaselineToTenantJob.php` after cleanup and confirm that the live compare path still flows through strategy selection and `strategy->compare(...)`, while the legacy helper names are absent and the guard suite passes.
### Tests for User Story 1
> **NOTE**: Update these tests first and confirm they fail before implementation.
- [X] T005 [P] [US1] Extend legacy helper absence assertions in `apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php`
- [X] T006 [P] [US1] Reconfirm one-engine orchestration guard coverage in `apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php`
### Implementation for User Story 1
- [X] T007 [US1] Remove `computeDrift()` and its exclusive helper cluster from `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`
- [X] T008 [US1] Remove dead imports and stale fallback comments or docblocks left by the deleted cluster in `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`
- [X] T009 [US1] Re-run the guard coverage in `apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php` and `apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php` against `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`
**Checkpoint**: The compare job is structurally honest again and the guard suite blocks reintroduction of the deleted legacy path.
---
## Phase 4: User Story 2 - Preserve current compare behavior while removing dead code (Priority: P1)
**Goal**: Prove that the cleanup leaves strategy selection, compare execution, finding lifecycle behavior, summary computation, gap handling, warning handling, reason translation, and run completion unchanged.
**Independent Test**: Run the required focused regression slice and confirm that `FindingFidelityTest`, `BaselineCompareFindingsTest`, `BaselineCompareGapClassificationTest`, `BaselineCompareWhyNoFindingsReasonCodeTest`, `Spec116OneEngineGuardTest`, `Spec118NoLegacyBaselineDriftGuardTest`, `OperationLifecycleOpsUxGuardTest`, `BaselineOperationRunGuardTest`, `OperationSummaryKeysSpecTest`, `SummaryCountsWhitelistTest`, and the matrix enqueue-path check all remain green after the delete.
### Tests for User Story 2
> **NOTE**: Update these tests first and confirm they fail before implementation.
- [X] T010 [P] [US2] Tighten strategy-driven execution assertions in `apps/platform/tests/Feature/BaselineDriftEngine/FindingFidelityTest.php`
- [X] T011 [P] [US2] Tighten finding lifecycle, recurrence, and summary outcome assertions in `apps/platform/tests/Feature/Baselines/BaselineCompareFindingsTest.php`
- [X] T012 [P] [US2] Tighten gap classification, warning-outcome, and reason-code assertions in `apps/platform/tests/Feature/Baselines/BaselineCompareGapClassificationTest.php` and `apps/platform/tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php`
- [X] T013 [P] [US2] Reconfirm `OperationRun` lifecycle and summary-count guard coverage in `apps/platform/tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php`, `apps/platform/tests/Feature/Operations/BaselineOperationRunGuardTest.php`, `apps/platform/tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php`, and `apps/platform/tests/Feature/OpsUx/SummaryCountsWhitelistTest.php`
### Implementation for User Story 2
- [X] T014 [US2] Keep live compare behavior unchanged while reconciling any cleanup fallout in `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`; do not modify `apps/platform/app/Support/Baselines/Compare/CompareStrategyRegistry.php` or `apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php` unless a blocker proves the smallest direct fix is required
- [X] T015 [US2] Run the required focused regression slice in `apps/platform/tests/Feature/BaselineDriftEngine/FindingFidelityTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareFindingsTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareGapClassificationTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php`, `apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php`, `apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php`, `apps/platform/tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php`, `apps/platform/tests/Feature/Operations/BaselineOperationRunGuardTest.php`, `apps/platform/tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php`, `apps/platform/tests/Feature/OpsUx/SummaryCountsWhitelistTest.php`, and `apps/platform/tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php`
**Checkpoint**: The cleanup is behaviorally safe and the current compare lifecycle still works through the strategy-owned path.
---
## Phase 5: User Story 3 - Keep the review diff mechanically narrow (Priority: P2)
**Goal**: Keep the cleanup PR reviewable by limiting the touched area to dead-path deletion, direct fallout cleanup, and minimal regression updates.
**Independent Test**: Inspect the final changed-file set and confirm that it is limited to `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`, the focused compare guard and regression files, and only direct blocker-driven follow-up in `apps/platform/app/Services/Baselines/BaselineCompareService.php` or `apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php` if justified.
### Implementation for User Story 3
- [X] T016 [P] [US3] Audit the touched-file set and strip opportunistic edits outside `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`, `apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php`, `apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php`, `apps/platform/tests/Feature/BaselineDriftEngine/FindingFidelityTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareFindingsTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareGapClassificationTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php`, `apps/platform/tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php`, `apps/platform/tests/Feature/Operations/BaselineOperationRunGuardTest.php`, `apps/platform/tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php`, `apps/platform/tests/Feature/OpsUx/SummaryCountsWhitelistTest.php`, and `apps/platform/tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php`
- [X] T017 [P] [US3] Review `apps/platform/app/Services/Baselines/BaselineCompareService.php` and `apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php` to confirm they remain unchanged or carry only the smallest blocker-driven follow-up required by the cleanup
- [X] T018 [US3] Verify the final diff stays limited to `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`, the focused compare guard and regression files above including `apps/platform/tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php`, and only direct blocker-driven follow-up in `apps/platform/app/Services/Baselines/BaselineCompareService.php` or `apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php`
**Checkpoint**: The PR stays small, reviewable, and aligned with Spec 205 rather than drifting into a broader compare refactor.
---
## Phase 6: Polish & Cross-Cutting Concerns
**Purpose**: Apply formatting and rerun the final focused Sail pack before handing the cleanup over for review.
- [X] T019 Run `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` for touched PHP files centered on `apps/platform/app/Jobs/CompareBaselineToTenantJob.php`
- [X] T020 Run the final focused Sail pack from `specs/205-compare-job-cleanup/quickstart.md` covering `apps/platform/tests/Feature/BaselineDriftEngine/FindingFidelityTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareFindingsTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareGapClassificationTest.php`, `apps/platform/tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php`, `apps/platform/tests/Feature/Guards/OperationLifecycleOpsUxGuardTest.php`, `apps/platform/tests/Feature/Operations/BaselineOperationRunGuardTest.php`, `apps/platform/tests/Feature/OpsUx/OperationSummaryKeysSpecTest.php`, `apps/platform/tests/Feature/OpsUx/SummaryCountsWhitelistTest.php`, `apps/platform/tests/Feature/Guards/Spec116OneEngineGuardTest.php`, `apps/platform/tests/Feature/Guards/Spec118NoLegacyBaselineDriftGuardTest.php`, and `apps/platform/tests/Feature/Baselines/BaselineCompareMatrixCompareAllActionTest.php`
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies; can start immediately.
- **Foundational (Phase 2)**: Depends on Setup completion; blocks all user story work.
- **User Story 1 (Phase 3)**: Depends on Foundational completion.
- **User Story 2 (Phase 4)**: Depends on User Story 1 because behavior preservation is verified after the delete lands.
- **User Story 3 (Phase 5)**: Depends on User Story 1 and User Story 2 because scope review is only meaningful once the delete, gap and reason coverage, and run-guard updates exist.
- **Polish (Phase 6)**: Depends on all user stories being complete.
### User Story Dependencies
- **US1**: No dependency beyond Foundational.
- **US2**: Depends on US1 because the focused regression slice validates the actual cleanup result.
- **US3**: Depends on US1 and US2 because it is the final scope-control pass over the implemented cleanup.
### Within Each User Story
- Update or tighten the story's tests first and confirm they fail before implementation.
- Keep compare start orchestration in `apps/platform/app/Services/Baselines/BaselineCompareService.php` and live strategy behavior in `apps/platform/app/Support/Baselines/Compare/IntuneCompareStrategy.php` out of scope unless a blocker demands the smallest possible fix.
- Finish each story's focused verification before moving to the next story.
### Parallel Opportunities
- `T001` and `T002` can run in parallel.
- `T003` and `T004` can run in parallel.
- Within US1, `T005` and `T006` can run in parallel.
- Within US2, `T010`, `T011`, `T012`, and `T013` can run in parallel.
- Within US3, `T016` and `T017` can run in parallel.
---
## Parallel Example: User Story 1
```bash
# Parallel guard updates for US1
T005 Extend legacy helper absence assertions in Spec118NoLegacyBaselineDriftGuardTest.php
T006 Reconfirm one-engine orchestration guard coverage in Spec116OneEngineGuardTest.php
```
## Parallel Example: User Story 2
```bash
# Parallel regression tightening for US2
T010 Tighten strategy-driven execution assertions in FindingFidelityTest.php
T011 Tighten finding lifecycle and summary outcome assertions in BaselineCompareFindingsTest.php
T012 Tighten gap classification and reason-code assertions in BaselineCompareGapClassificationTest.php and BaselineCompareWhyNoFindingsReasonCodeTest.php
T013 Reconfirm OperationRun lifecycle and summary-count guard coverage in OperationLifecycleOpsUxGuardTest.php, BaselineOperationRunGuardTest.php, OperationSummaryKeysSpecTest.php, and SummaryCountsWhitelistTest.php
```
## Parallel Example: User Story 3
```bash
# Parallel scope review for US3
T016 Audit the touched-file set and strip opportunistic edits outside the focused cleanup files
T017 Review BaselineCompareService.php and IntuneCompareStrategy.php for blocker-only follow-up changes
```
---
## Implementation Strategy
### MVP First
1. Complete Setup and Foundational work.
2. Deliver US1 to remove the dead path and restore a single truthful compare engine in the orchestration file.
3. Immediately follow with US2 so the cleanup is merge-safe, not just structurally cleaner.
### Incremental Delivery
1. Finish US1 and confirm the guard suite blocks the deleted helper cluster.
2. Finish US2 and prove the live strategy-driven compare behavior remains unchanged.
3. Finish US3 to keep the cleanup PR mechanically narrow.
4. Finish with formatting and the final focused Sail pack from Phase 6.
### Parallel Team Strategy
1. One contributor handles Setup and Foundational call-graph confirmation.
2. After Foundation is green:
T005 and T006 can be prepared in parallel for US1.
T010, T011, T012, and T013 can be prepared in parallel for US2.
T016 and T017 can be prepared in parallel for US3 once the cleanup diff exists.
3. Merge back for the final diff review, formatting, and focused Sail verification.