<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/jsonm/php/runtime/autoload.php';

require_once __DIR__ . '/support/Support.php';
require_once __DIR__ . '/support/Richtext.php';
require_once __DIR__ . '/security/PublicInteractionTokenService.php';
require_once __DIR__ . '/mic/MicElementResolverInterface.php';
require_once __DIR__ . '/mic/MicElementSearchable.php';
require_once __DIR__ . '/mic/MicElementRegistry.php';
require_once __DIR__ . '/mic/SearchTextExtractor.php';
require_once __DIR__ . '/media/PublicMediaRenditionService.php';
require_once __DIR__ . '/performance/PublicPageCache.php';
require_once __DIR__ . '/performance/PublicPageCacheWarmer.php';
require_once __DIR__ . '/performance/PublicPageCacheWarmCoordinator.php';
require_once __DIR__ . '/performance/PublicRenderProfiler.php';
require_once __DIR__ . '/release/ReleaseMetadata.php';
require_once __DIR__ . '/database/Database.php';
require_once __DIR__ . '/database/MigrationRunner.php';
require_once __DIR__ . '/database/MigrationOperationsService.php';
require_once __DIR__ . '/license/LicenseStatus.php';
require_once __DIR__ . '/license/LicenseClient.php';
require_once __DIR__ . '/license/EntitlementSnapshot.php';
require_once __DIR__ . '/license/LicenseRepository.php';
require_once __DIR__ . '/license/LicenseAuditRepository.php';
require_once __DIR__ . '/license/LicenseActivationService.php';
require_once __DIR__ . '/license/EntitlementGate.php';
require_once __DIR__ . '/license/EntitlementPresentationPolicy.php';
require_once __DIR__ . '/license/DesignLibraryEntitlementPolicy.php';
require_once __DIR__ . '/license/MarketplaceCatalogClient.php';
require_once __DIR__ . '/license/ModuleEntitlementRepository.php';
require_once __DIR__ . '/license/ModuleLicenseManagerService.php';
require_once __DIR__ . '/update/UpdatePackageResult.php';
require_once __DIR__ . '/update/UpdateManifest.php';
require_once __DIR__ . '/update/OperatorStateUpdateBoundary.php';
require_once __DIR__ . '/update/OperatorStateSnapshot.php';
require_once __DIR__ . '/update/MarketplaceKeyResolver.php';
require_once __DIR__ . '/update/MarketplaceEnvelope.php';
require_once __DIR__ . '/update/MarketplaceEnvelopeVerifier.php';
require_once __DIR__ . '/update/UpdatePackageValidator.php';
require_once __DIR__ . '/update/UpdateAuditRepository.php';
require_once __DIR__ . '/update/ModulePackageInstallLedger.php';
require_once __DIR__ . '/update/UpdateApplicationService.php';
require_once __DIR__ . '/update/VersionComparator.php';
require_once __DIR__ . '/update/EntitlementBoundaryIntegrityService.php';
require_once __DIR__ . '/update/RemoteUpdateClient.php';
require_once __DIR__ . '/update/RemoteModulePackageClient.php';
require_once __DIR__ . '/update/RemoteUpdateManifestValidator.php';
require_once __DIR__ . '/update/UpdateSettingsRepository.php';
require_once __DIR__ . '/update/UpdateStateRepository.php';
require_once __DIR__ . '/update/RemoteUpdateCheckService.php';
require_once __DIR__ . '/update/RemoteUpdateApplyService.php';
require_once __DIR__ . '/modules/ModuleRegistry.php';
require_once __DIR__ . '/modules/ModuleLoader.php';
require_once dirname(__DIR__) . '/modules/content/ContentRepository.php';
require_once dirname(__DIR__) . '/modules/content/pages/PageRoleService.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/TemplateInstantiationService.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/BundleBootstrapService.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/DisabledPageRedirectsRepository.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/RedirectFallbackValidator.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/BundleImpactAnalysisService.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/BundleDisableService.php';
require_once dirname(__DIR__) . '/modules/content/instantiation/BundleEnableService.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicRenderPresentation.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicComponentDataResolver.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicHeroImagePolicy.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicCriticalResourceResolver.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicNavigationRenderer.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicHeaderContextResolver.php';
require_once dirname(__DIR__) . '/modules/content/public/PublicHeadMetadataResolver.php';
require_once dirname(__DIR__) . '/modules/content/public/PageRoleResolver.php';
require_once dirname(__DIR__) . '/modules/content/seo/MyronSeoFieldResolver.php';
require_once dirname(__DIR__) . '/modules/content/seo/MyronJsonLdEncoder.php';
require_once dirname(__DIR__) . '/modules/content/seo/MyronJsonLdGenerator.php';
require_once dirname(__DIR__) . '/modules/content/seo/MyronJsonLdService.php';
require_once dirname(__DIR__) . '/modules/content/seo/MyronSeoPanelService.php';
require_once dirname(__DIR__) . '/modules/content/seo/MyronOgImageValidator.php';
require_once dirname(__DIR__) . '/modules/content/seo/SitemapGenerator.php';
require_once dirname(__DIR__) . '/modules/content/seo/LlmsTxtGenerator.php';
require_once dirname(__DIR__) . '/modules/content/seo/RobotsTxtGenerator.php';
require_once dirname(__DIR__) . '/modules/content/seo/HtmlToMarkdownConverter.php';
require_once dirname(__DIR__) . '/modules/content/seo/MarkdownToHtmlConverter.php';
require_once dirname(__DIR__) . '/modules/content/seo/MarkdownFrontMatterBuilder.php';
require_once dirname(__DIR__) . '/modules/content/seo/MarkdownExtractor.php';
require_once dirname(__DIR__) . '/modules/content/public/SectionRenderContext.php';
require_once dirname(__DIR__) . '/modules/content/public/SectionContract.php';
require_once dirname(__DIR__) . '/modules/content/public/SectionRenderer.php';
require_once dirname(__DIR__) . '/modules/content/public/CallableSectionRenderer.php';
require_once dirname(__DIR__) . '/modules/content/public/SectionRendererRegistry.php';
require_once dirname(__DIR__) . '/modules/content/public/DefinitionTemplateRenderer.php';
require_once dirname(__DIR__) . '/modules/content/public/PublishedPageHtmlAssembler.php';
require_once dirname(__DIR__) . '/modules/content/preview/TemplateContentResolver.php';
require_once dirname(__DIR__) . '/modules/content/preview/TemplatePreviewFactory.php';
require_once dirname(__DIR__) . '/modules/content/editor/SectionContentSchemaService.php';
require_once dirname(__DIR__) . '/modules/content/editor/EditorSurfaceReadModel.php';
require_once dirname(__DIR__) . '/modules/content/editor/PageContractService.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableRepository.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableService.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableResolver.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormRepository.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormSubmissionRepository.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormNotificationFailureRepository.php';
require_once dirname(__DIR__) . '/modules/content/mics/FormSubmissionHelpers.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormSpamCounter.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormNotificationBody.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormNotificationDispatcher.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormService.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormResolver.php';
require_once dirname(__DIR__) . '/modules/content/comments/BlogCommentRepository.php';
require_once dirname(__DIR__) . '/modules/content/comments/BlogCommentSettingsRepository.php';
require_once dirname(__DIR__) . '/modules/content/comments/BlogCommentModerationEventRepository.php';
require_once dirname(__DIR__) . '/modules/content/comments/BlogCommentNotificationDispatcher.php';
require_once dirname(__DIR__) . '/modules/content/comments/BlogCommentService.php';
require_once dirname(__DIR__) . '/modules/content/migration/SectionContentMigrationReport.php';
require_once dirname(__DIR__) . '/modules/content/migration/SectionContentMigrationService.php';
require_once dirname(__DIR__) . '/modules/search/SearchIndexService.php';
require_once dirname(__DIR__) . '/modules/search/PublicSearchRequestService.php';
require_once dirname(__DIR__) . '/modules/search/SearchIndexer.php';
require_once dirname(__DIR__) . '/modules/quality/QualityRuleRegistry.php';
require_once dirname(__DIR__) . '/modules/quality/QualityReportService.php';
require_once dirname(__DIR__) . '/modules/design/TokenReferenceService.php';
require_once dirname(__DIR__) . '/modules/design/CustomCssRepository.php';
require_once dirname(__DIR__) . '/modules/design/SectionVariantRepository.php';
require_once dirname(__DIR__) . '/modules/design/TokenPatchRepository.php';
require_once dirname(__DIR__) . '/modules/design/TokenControlRenderer.php';
require_once dirname(__DIR__) . '/modules/design/DefinitionFontHeadRenderer.php';
require_once dirname(__DIR__) . '/modules/design/catalog/MyronMotionProfileCatalog.php';
require_once dirname(__DIR__) . '/modules/design/catalog/MyronSceneCatalog.php';
require_once dirname(__DIR__) . '/modules/design/catalog/MyronCreativeLibraryCatalog.php';
require_once __DIR__ . '/api/Action.php';
require_once __DIR__ . '/api/Scopes.php';
require_once __DIR__ . '/api/AuthMethodRegistry.php';
require_once __DIR__ . '/api/Authorization.php';
require_once __DIR__ . '/api/ActionRegistry.php';
require_once __DIR__ . '/api/ActionDispatcher.php';
require_once __DIR__ . '/api/RegistryAudit.php';
require_once __DIR__ . '/api/JsonContentEnvelope.php';
require_once __DIR__ . '/mcp/OAuthMetadataService.php';
require_once __DIR__ . '/mcp/OperatingContract.php';
require_once __DIR__ . '/mcp/OAuthClientRepository.php';
require_once __DIR__ . '/mcp/OAuthTokenService.php';
require_once __DIR__ . '/mcp/ConnectorAuthAdapter.php';
require_once dirname(__DIR__) . '/api/actions/administration/BundleImpactPreviewAction.php';
require_once dirname(__DIR__) . '/api/actions/administration/BundleDisableAction.php';
require_once dirname(__DIR__) . '/api/actions/administration/BundleEnableAction.php';
require_once dirname(__DIR__) . '/api/actions/administration/BundleRecentEventsAction.php';
require_once dirname(__DIR__) . '/api/actions/administration/DeleteRedirectAction.php';
require_once dirname(__DIR__) . '/api/actions/administration/InstallModulePackageAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTypesListAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableListAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableReadAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableCreateAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableUpdateAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicTableDeleteAction.php';
require_once dirname(__DIR__) . '/modules/content/mics/MicFormActions.php';
require_once __DIR__ . '/extensions/ExtensionManifest.php';
require_once __DIR__ . '/extensions/ExtensionScopeGrantRepository.php';
require_once __DIR__ . '/extensions/ExtensionMigrationRunner.php';
require_once __DIR__ . '/extensions/MyronExtensionSDK.php';
require_once __DIR__ . '/extensions/MarketplaceExtensionPackageClient.php';
require_once __DIR__ . '/extensions/MarketplaceExtensionInstallService.php';
require_once __DIR__ . '/extensions/ExtensionLoader.php';
require_once __DIR__ . '/definitions/DefinitionsPath.php';
require_once __DIR__ . '/definitions/DefinitionsAuditService.php';
require_once dirname(__DIR__) . '/modules/design/registry/NavigationDesignSettingsRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/NavigationDesignRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/NavigationHeaderOverrideRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/FooterDesignSettingsRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/FooterDesignRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/FooterVariantOverrideRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/RailDesignRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/TemplateChromeAssignmentRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/FooterVariantCompositionService.php';
require_once dirname(__DIR__) . '/modules/design/registry/FooterZoneContentSchemaService.php';
require_once dirname(__DIR__) . '/modules/design/registry/FooterContentSeedService.php';
require_once dirname(__DIR__) . '/modules/design/registry/ComponentRegistryRepository.php';
require_once dirname(__DIR__) . '/modules/design/registry/ComponentRegistryIngestionService.php';
require_once dirname(__DIR__) . '/modules/design/preview/ComponentPreviewCatalog.php';
require_once dirname(__DIR__) . '/modules/design/preview/ComponentPreviewRenderer.php';
require_once dirname(__DIR__) . '/modules/design/preview/PrimitiveRenderer.php';
require_once dirname(__DIR__) . '/modules/design/preview/PrimitiveExplorerService.php';
require_once dirname(__DIR__) . '/modules/content/definitions/TemplateDefinitionRepository.php';
require_once dirname(__DIR__) . '/modules/content/sections/SectionBridgeRepository.php';
require_once dirname(__DIR__) . '/modules/content/sections/SectionComponentDefaultsRepository.php';
require_once dirname(__DIR__) . '/modules/content/sections/SectionContentDefaultsRepository.php';
require_once dirname(__DIR__) . '/modules/content/sections/CustomSectionTemplateRepository.php';
require_once dirname(__DIR__) . '/modules/content/sections/CustomSectionTemplateActionService.php';
require_once dirname(__DIR__) . '/modules/content/sections/SectionRegistryRepository.php';
require_once dirname(__DIR__) . '/modules/content/sections/SectionUsageService.php';
require_once dirname(__DIR__) . '/modules/content/usage/LiveSectionInventoryReadModel.php';
require_once dirname(__DIR__) . '/modules/content/usage/CurrentSiteUsageReadModel.php';
require_once dirname(__DIR__) . '/modules/content/definitions/TemplateDefinitionIngestionService.php';
require_once dirname(__DIR__) . '/modules/content/site_types/SiteTypeRegistryRepository.php';
require_once dirname(__DIR__) . '/modules/content/site_types/SiteTypeIngestionService.php';
require_once dirname(__DIR__) . '/modules/content/site_types/BundleActivationRepository.php';
require_once dirname(__DIR__) . '/modules/forms/BranchingFormService.php';
require_once dirname(__DIR__) . '/modules/integrations/WebhookDeliveryService.php';
require_once dirname(__DIR__) . '/modules/analytics/CapiEmitter.php';
require_once dirname(__DIR__) . '/modules/analytics/AnalyticsSessionHashService.php';
require_once dirname(__DIR__) . '/modules/analytics/UserAgentClassifier.php';
require_once dirname(__DIR__) . '/modules/analytics/SiteAnalyticsRepository.php';
require_once dirname(__DIR__) . '/modules/verification/VerificationEngine.php';
require_once dirname(__DIR__) . '/modules/dashboard/DashboardReadModel.php';
require_once dirname(__DIR__) . '/modules/dashboard/TipsFeedRepository.php';
require_once dirname(__DIR__) . '/modules/dashboard/TipsFeedService.php';
require_once dirname(__DIR__) . '/modules/dashboard/DashboardNotesRepository.php';
require_once dirname(__DIR__) . '/modules/dashboard/DashboardLinksRepository.php';
require_once dirname(__DIR__) . '/modules/dashboard/DashboardMessagesRepository.php';
require_once dirname(__DIR__) . '/modules/site/SiteSettingsRepository.php';
require_once dirname(__DIR__) . '/modules/site/SiteTypeStageGateService.php';
require_once dirname(__DIR__) . '/modules/site/SiteSetupSelectionService.php';
require_once dirname(__DIR__) . '/modules/site/SiteSetupDefaultReplacementService.php';
require_once dirname(__DIR__) . '/modules/site/OnboardingStateRepository.php';
require_once dirname(__DIR__) . '/modules/site/SiteResetService.php';
require_once dirname(__DIR__) . '/modules/site/snapshot/SiteSnapshotEnvelope.php';
require_once dirname(__DIR__) . '/modules/site/snapshot/SiteSnapshotValidationResult.php';
require_once dirname(__DIR__) . '/modules/site/snapshot/SiteSnapshotImportAuditRepository.php';
require_once dirname(__DIR__) . '/modules/site/snapshot/SiteSnapshotExportService.php';
require_once dirname(__DIR__) . '/modules/site/snapshot/SiteSnapshotImportService.php';
require_once dirname(__DIR__) . '/modules/identity/AuthRepository.php';
require_once dirname(__DIR__) . '/modules/files/FileRepository.php';
require_once dirname(__DIR__) . '/modules/files/AssetUploadRequestHandler.php';
require_once dirname(__DIR__) . '/modules/files/VideoAssetRepository.php';
require_once dirname(__DIR__) . '/modules/files/MediaAccessibilityAttachmentRepository.php';
require_once dirname(__DIR__) . '/modules/files/MediaAccessibilityActionService.php';
require_once dirname(__DIR__) . '/modules/files/AssetPickerView.php';
require_once dirname(__DIR__) . '/modules/files/AssetUploadView.php';
require_once dirname(__DIR__) . '/modules/files/DocumentTemplateRepository.php';
require_once dirname(__DIR__) . '/modules/identity/MailSettingsRepository.php';
require_once dirname(__DIR__) . '/modules/identity/NotificationEmailsRepository.php';
require_once dirname(__DIR__) . '/modules/identity/NotificationEmailsService.php';
require_once dirname(__DIR__) . '/modules/identity/FormNotificationFailureService.php';
require_once dirname(__DIR__) . '/modules/identity/NotificationEmailActions.php';
require_once __DIR__ . '/mail/MailTransportInterface.php';
require_once __DIR__ . '/mail/MailEnvelope.php';
require_once __DIR__ . '/mail/MailDispatchResult.php';
require_once __DIR__ . '/mail/MailTransportRegistry.php';
require_once __DIR__ . '/mail/MyronSmtpTransport.php';
require_once __DIR__ . '/mail/Mailer.php';
require_once dirname(__DIR__) . '/modules/identity/MailTestService.php';
require_once dirname(__DIR__) . '/modules/identity/PasswordResetService.php';
require_once __DIR__ . '/shell/FlashNotifications.php';
require_once __DIR__ . '/helpers/component_guard.php';
require_once __DIR__ . '/shell/AdminShell.php';
require_once __DIR__ . '/shell/PublicShell.php';
require_once __DIR__ . '/routing/AppFrontController.php';

MyronEnv::load(dirname(__DIR__, 2) . '/.env');
myronPublicRenderProfiler()->mark('bootstrap_loaded');

function myronProjectRoot(): string
{
    return dirname(__DIR__, 2);
}

function myronAppRoot(): string
{
    return dirname(__DIR__);
}

function myronModuleRegistry(): MyronModuleRegistry
{
    static $registry = null;

    if ($registry instanceof MyronModuleRegistry) {
        return $registry;
    }

    $registry = new MyronModuleRegistry();
    return $registry;
}

function myronLoadModuleSubstrate(): void
{
    static $loaded = false;

    if ($loaded) {
        return;
    }

    $loaded = true;
    MyronModuleLoader::load(myronModuleRegistry(), myronAppRoot());
}

function myronModulePresent(string $slug): bool
{
    myronLoadModuleSubstrate();
    return myronModuleRegistry()->isPresent($slug);
}

myronLoadModuleSubstrate();

if (myronShouldAutoMigrateDatabase()) {
    $myronModuleMigrationReport = MyronMigrationRunner::migrateWithReport(myronDatabase());
    if (($myronModuleMigrationReport['pending'] ?? []) === []) {
        myronModulePackageInstallLedger()->reconcileBootstrapMigrations(myronModuleRegistry()->presentModules());
    }
    myronPublicRenderProfiler()->mark('module_migrations_converged');
}

function myronDatabase(): PDO
{
    static $pdo = null;

    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $config = MyronDatabaseConfig::fromEnvironment(myronAppRoot());
    $database = new MyronDatabase($config);
    $pdo = $database->connect();
    if (myronShouldAutoMigrateDatabase()) {
        MyronMigrationRunner::migrate($pdo);
        myronPublicRenderProfiler()->mark('database_migrated');
    }

    return $pdo;
}

function myronContentRepository(): MyronContentRepository
{
    static $repository = null;

    if ($repository instanceof MyronContentRepository) {
        return $repository;
    }

    $repository = new MyronContentRepository(myronDatabase());
    if (myronShouldAutoSeedContent()) {
        $repository->ensureSeedData();
        myronPublicRenderProfiler()->mark('content_seed_checked');
    }

    return $repository;
}

function myronMicTableRepository(): MicTableRepository
{
    static $repository = null;
    if ($repository instanceof MicTableRepository) {
        return $repository;
    }
    $repository = new MicTableRepository(myronDatabase());
    return $repository;
}

function myronMicTableService(): MicTableService
{
    static $service = null;
    if ($service instanceof MicTableService) {
        return $service;
    }
    $service = new MicTableService(myronMicTableRepository());
    return $service;
}

function myronMicFormRepository(): MicFormRepository
{
    static $repository = null;
    if ($repository instanceof MicFormRepository) {
        return $repository;
    }
    $repository = new MicFormRepository(myronDatabase());
    return $repository;
}

function myronMicFormSubmissionRepository(): MicFormSubmissionRepository
{
    static $repository = null;
    if ($repository instanceof MicFormSubmissionRepository) {
        return $repository;
    }
    $repository = new MicFormSubmissionRepository(myronDatabase());
    return $repository;
}

function myronMicFormNotificationFailureRepository(): MicFormNotificationFailureRepository
{
    static $repository = null;
    if ($repository instanceof MicFormNotificationFailureRepository) {
        return $repository;
    }
    $repository = new MicFormNotificationFailureRepository(myronDatabase());
    return $repository;
}

function myronMicFormService(): MicFormService
{
    static $service = null;
    if ($service instanceof MicFormService) {
        return $service;
    }
    $service = new MicFormService(myronMicFormRepository(), myronMicFormSubmissionRepository());
    return $service;
}

function myronBlogCommentRepository(): BlogCommentRepository
{
    static $repository = null;
    if ($repository instanceof BlogCommentRepository) {
        return $repository;
    }
    $repository = new BlogCommentRepository(myronDatabase());
    return $repository;
}

function myronBlogCommentSettingsRepository(): BlogCommentSettingsRepository
{
    static $repository = null;
    if ($repository instanceof BlogCommentSettingsRepository) {
        return $repository;
    }
    $repository = new BlogCommentSettingsRepository(myronDatabase());
    return $repository;
}

function myronBlogCommentModerationEventRepository(): BlogCommentModerationEventRepository
{
    static $repository = null;
    if ($repository instanceof BlogCommentModerationEventRepository) {
        return $repository;
    }
    $repository = new BlogCommentModerationEventRepository(myronDatabase());
    return $repository;
}

function myronBlogCommentService(): BlogCommentService
{
    static $service = null;
    if ($service instanceof BlogCommentService) {
        return $service;
    }
    $service = new BlogCommentService(
        myronBlogCommentRepository(),
        myronBlogCommentSettingsRepository(),
        myronBlogCommentModerationEventRepository()
    );
    return $service;
}

function myronBlogCommentNotificationDispatcher(): BlogCommentNotificationDispatcher
{
    static $dispatcher = null;
    if ($dispatcher instanceof BlogCommentNotificationDispatcher) {
        return $dispatcher;
    }
    $dispatcher = new BlogCommentNotificationDispatcher(
        myronBlogCommentSettingsRepository(),
        myronNotificationEmailsRepository(),
        myronMailSettingsRepository(),
        myronContentRepository(),
        myronBlogCommentModerationEventRepository()
    );
    return $dispatcher;
}

function myronMicFormSpamCounter(): MicFormSpamCounter
{
    static $counter = null;
    if ($counter instanceof MicFormSpamCounter) {
        return $counter;
    }
    $counter = new MicFormSpamCounter();
    return $counter;
}

function myronBootstrapCoreMicTypes(): void
{
    static $booted = false;
    if ($booted) {
        return;
    }
    $booted = true;
    myronMicElementRegistry()->registerCore('table', new MicTableResolver(myronMicTableRepository()));
    myronMicElementRegistry()->registerCore('form', new MicFormResolver(myronMicFormRepository()));
}

function myronLicenseRepository(): MyronLicenseRepository
{
    static $repository = null;

    if ($repository instanceof MyronLicenseRepository) {
        return $repository;
    }

    $repository = new MyronLicenseRepository(myronDatabase());
    return $repository;
}

function myronLicenseAuditRepository(): MyronLicenseAuditRepository
{
    static $repository = null;

    if ($repository instanceof MyronLicenseAuditRepository) {
        return $repository;
    }

    $repository = new MyronLicenseAuditRepository(myronDatabase());
    return $repository;
}

function myronLicenseActivationService(): MyronLicenseActivationService
{
    static $service = null;

    if ($service instanceof MyronLicenseActivationService) {
        return $service;
    }

    $service = new MyronLicenseActivationService(
        MyronLicenseClient::fromEnvironment(),
        myronLicenseRepository(),
        myronLicenseAuditRepository()
    );
    return $service;
}

function myronModuleEntitlementRepository(): MyronModuleEntitlementRepository
{
    static $repository = null;

    if ($repository instanceof MyronModuleEntitlementRepository) {
        return $repository;
    }

    $repository = new MyronModuleEntitlementRepository(myronLicenseRepository());
    return $repository;
}

function myronModuleLicenseManagerService(): MyronModuleLicenseManagerService
{
    static $service = null;

    if ($service instanceof MyronModuleLicenseManagerService) {
        return $service;
    }

    $service = new MyronModuleLicenseManagerService(
        myronModuleEntitlementRepository(),
        myronLicenseAuditRepository(),
        myronLicenseActivationService(),
        myronRemoteModulePackageClient()
    );
    return $service;
}

function myronEntitlementGate(): MyronEntitlementGate
{
    static $gate = null;

    if ($gate instanceof MyronEntitlementGate) {
        return $gate;
    }

    $gate = new MyronEntitlementGate(myronLicenseRepository());
    return $gate;
}

function myronEntitlementPresentationPolicy(): MyronEntitlementPresentationPolicy
{
    static $policy = null;

    if ($policy instanceof MyronEntitlementPresentationPolicy) {
        return $policy;
    }

    $policy = new MyronEntitlementPresentationPolicy(myronEntitlementGate());
    return $policy;
}

function myronDesignLibraryEntitlementPolicy(): MyronDesignLibraryEntitlementPolicy
{
    static $policy = null;

    if ($policy instanceof MyronDesignLibraryEntitlementPolicy) {
        return $policy;
    }

    $policy = new MyronDesignLibraryEntitlementPolicy(
        myronEntitlementPresentationPolicy(),
        myronSiteTypeRegistryRepository(),
        myronTemplateDefinitionRepository(),
    );
    return $policy;
}

function myronPublicHeadMetadataResolver(): MyronPublicHeadMetadataResolver
{
    static $resolver = null;

    if ($resolver instanceof MyronPublicHeadMetadataResolver) {
        return $resolver;
    }

    $resolver = new MyronPublicHeadMetadataResolver();
    return $resolver;
}

function myronDefinitionFontHeadRenderer(): MyronDefinitionFontHeadRenderer
{
    static $renderer = null;
    if ($renderer instanceof MyronDefinitionFontHeadRenderer) {
        return $renderer;
    }

    $renderer = new MyronDefinitionFontHeadRenderer();
    return $renderer;
}

/**
 * @param list<string> $definitionUrls
 */
function myronRenderDefinitionFontHeadTags(array $definitionUrls = []): string
{
    return myronDefinitionFontHeadRenderer()->render($definitionUrls);
}

function myronPageRoleResolver(): MyronPageRoleResolver
{
    static $resolver = null;
    if ($resolver instanceof MyronPageRoleResolver) {
        return $resolver;
    }
    $resolver = new MyronPageRoleResolver(myronContentRepository());
    return $resolver;
}

function myronPublicSearchRequestService(): MyronPublicSearchRequestService
{
    static $service = null;
    if ($service instanceof MyronPublicSearchRequestService) {
        return $service;
    }
    $service = new MyronPublicSearchRequestService(myronSearchIndex());
    return $service;
}

function myronSeoFieldResolver(): MyronSeoFieldResolver
{
    return new MyronSeoFieldResolver(myronSiteSettings());
}

function myronJsonLdService(): MyronJsonLdService
{
    static $service = null;

    if ($service instanceof MyronJsonLdService) {
        return $service;
    }

    $resolver = new MyronSeoFieldResolver(myronSiteSettings());
    $service = new MyronJsonLdService(
        new MyronJsonLdGenerator($resolver),
        new MyronJsonLdEncoder()
    );
    return $service;
}

function myronSeoPanelService(): MyronSeoPanelService
{
    return new MyronSeoPanelService(myronSeoFieldResolver(), myronJsonLdService());
}

function myronHtmlToMarkdownConverter(): MyronHtmlToMarkdownConverter
{
    static $converter = null;

    if ($converter instanceof MyronHtmlToMarkdownConverter) {
        return $converter;
    }

    $converter = new MyronHtmlToMarkdownConverter();
    return $converter;
}

function myronMarkdownToHtmlConverter(): MyronMarkdownToHtmlConverter
{
    static $converter = null;

    if ($converter instanceof MyronMarkdownToHtmlConverter) {
        return $converter;
    }

    $converter = new MyronMarkdownToHtmlConverter();
    return $converter;
}

function myronMarkdownFrontMatterBuilder(): MyronMarkdownFrontMatterBuilder
{
    static $builder = null;

    if ($builder instanceof MyronMarkdownFrontMatterBuilder) {
        return $builder;
    }

    $builder = new MyronMarkdownFrontMatterBuilder();
    return $builder;
}

function myronMarkdownExtractor(): MyronMarkdownExtractor
{
    static $extractor = null;

    if ($extractor instanceof MyronMarkdownExtractor) {
        return $extractor;
    }

    $extractor = new MyronMarkdownExtractor(myronHtmlToMarkdownConverter(), myronMarkdownFrontMatterBuilder());
    return $extractor;
}

function myronOgImageValidator(): MyronOgImageValidator
{
    static $validator = null;

    if ($validator instanceof MyronOgImageValidator) {
        return $validator;
    }

    $validator = new MyronOgImageValidator();
    return $validator;
}

function myronSitemapGenerator(): MyronSitemapGenerator
{
    return new MyronSitemapGenerator(myronContentRepository());
}

function myronLlmsTxtGenerator(): MyronLlmsTxtGenerator
{
    return new MyronLlmsTxtGenerator(myronContentRepository(), myronSiteSettings());
}

function myronRobotsTxtGenerator(): MyronRobotsTxtGenerator
{
    return new MyronRobotsTxtGenerator(myronSiteSettings());
}

function myronTokenReferenceService(): MyronTokenReferenceService
{
    static $service = null;

    if ($service instanceof MyronTokenReferenceService) {
        return $service;
    }

    $service = new MyronTokenReferenceService();
    return $service;
}

function myronCustomCssRepository(): MyronCustomCssRepository
{
    static $repository = null;

    if ($repository instanceof MyronCustomCssRepository) {
        return $repository;
    }

    $repository = new MyronCustomCssRepository(myronDatabase());
    return $repository;
}

function myronSectionVariantRepository(): MyronSectionVariantRepository
{
    static $repository = null;

    if ($repository instanceof MyronSectionVariantRepository) {
        return $repository;
    }

    $repository = new MyronSectionVariantRepository(myronDatabase(), myronContentRepository());
    return $repository;
}

function myronMotionProfileCatalog(): MyronMotionProfileCatalog
{
    static $catalog = null;
    if ($catalog instanceof MyronMotionProfileCatalog) {
        return $catalog;
    }
    $catalog = new MyronMotionProfileCatalog();
    return $catalog;
}

function myronSceneCatalog(): MyronSceneCatalog
{
    static $catalog = null;
    if ($catalog instanceof MyronSceneCatalog) {
        return $catalog;
    }
    $catalog = new MyronSceneCatalog();
    return $catalog;
}

function myronCreativeLibraryCatalog(): MyronCreativeLibraryCatalog
{
    static $catalog = null;
    if ($catalog instanceof MyronCreativeLibraryCatalog) {
        return $catalog;
    }
    $catalog = new MyronCreativeLibraryCatalog(myronMotionProfileCatalog(), myronSceneCatalog());
    return $catalog;
}

function myronTokenPatchRepository(): MyronTokenPatchRepository
{
    static $repository = null;

    if ($repository instanceof MyronTokenPatchRepository) {
        return $repository;
    }

    $repository = new MyronTokenPatchRepository(
        myronDatabase(),
        myronAppRoot() . '/assets/runtime/css/runtime-token-overrides.css'
    );
    return $repository;
}

function myronAssetUploadRequestHandler(): MyronAssetUploadRequestHandler
{
    static $handler = null;

    if ($handler instanceof MyronAssetUploadRequestHandler) {
        return $handler;
    }

    $handler = new MyronAssetUploadRequestHandler(myronFileRepository());
    return $handler;
}

function myronTokenControlRenderer(): MyronTokenControlRenderer
{
    static $renderer = null;

    if ($renderer instanceof MyronTokenControlRenderer) {
        return $renderer;
    }

    $renderer = new MyronTokenControlRenderer();
    return $renderer;
}

function myronDefinitionsPath(): MyronDefinitionsPath
{
    static $path = null;

    if ($path instanceof MyronDefinitionsPath) {
        return $path;
    }

    $path = new MyronDefinitionsPath(myronProjectRoot());
    return $path;
}

function myronEnsureDefinitionsRuntimeSeeded(): void
{
    static $seeded = false;

    if ($seeded) {
        return;
    }

    myronSeedDefinitionsRuntime();
    $seeded = true;
}

function myronReseedDefinitionsRuntime(): void
{
    myronSeedDefinitionsRuntime();
}

function myronSeedDefinitionsRuntime(): void
{
    $pdo = myronDatabase();
    $definitionsPath = myronDefinitionsPath();

    $componentRepository = new MyronComponentRegistryRepository($pdo);
    $templateRepository = new MyronTemplateDefinitionRepository($pdo);
    $sectionBridgeRepository = new MyronSectionBridgeRepository($pdo);
    $sectionRepository = new MyronSectionRegistryRepository($pdo, $sectionBridgeRepository);
    $siteTypeRepository = new MyronSiteTypeRegistryRepository($pdo);

    $componentIngestion = new MyronComponentRegistryIngestionService($definitionsPath, $componentRepository);
    $sectionRepository->ensureSeeded();
    $templateIngestion = new MyronTemplateDefinitionIngestionService($definitionsPath, $templateRepository, $componentRepository, $sectionRepository);
    $siteTypeIngestion = new MyronSiteTypeIngestionService($definitionsPath, $siteTypeRepository);

    $componentIngestion->seedFromDefinitions();
    $templateIngestion->seedFromDefinitions();
    $siteTypeIngestion->seedFromDefinitions();
}

function myronComponentRegistryRepository(): MyronComponentRegistryRepository
{
    static $repository = null;

    if ($repository instanceof MyronComponentRegistryRepository) {
        return $repository;
    }

    myronEnsureDefinitionsRuntimeSeeded();
    $repository = new MyronComponentRegistryRepository(myronDatabase());

    return $repository;
}

function myronTemplateDefinitionRepository(): MyronTemplateDefinitionRepository
{
    static $repository = null;

    if ($repository instanceof MyronTemplateDefinitionRepository) {
        return $repository;
    }

    myronEnsureDefinitionsRuntimeSeeded();
    $repository = new MyronTemplateDefinitionRepository(myronDatabase());

    return $repository;
}

function myronSectionRegistryRepository(): MyronSectionRegistryRepository
{
    static $repository = null;

    if ($repository instanceof MyronSectionRegistryRepository) {
        return $repository;
    }

    myronEnsureDefinitionsRuntimeSeeded();
    $repository = new MyronSectionRegistryRepository(
        myronDatabase(),
        myronSectionBridgeRepository(),
        myronCustomSectionTemplateRepository(),
    );
    $repository->ensureSeeded();

    return $repository;
}

function myronCustomSectionTemplateRepository(): MyronCustomSectionTemplateRepository
{
    static $repository = null;

    if ($repository instanceof MyronCustomSectionTemplateRepository) {
        return $repository;
    }

    $repository = new MyronCustomSectionTemplateRepository(myronDatabase());
    return $repository;
}

function myronCustomSectionTemplateActionService(): MyronCustomSectionTemplateActionService
{
    static $service = null;

    if ($service instanceof MyronCustomSectionTemplateActionService) {
        return $service;
    }

    $service = new MyronCustomSectionTemplateActionService(
        myronDatabase(),
        myronCustomSectionTemplateRepository(),
        myronComponentRegistryRepository(),
        myronPrimitiveRenderer(),
    );
    return $service;
}

function myronSectionBridgeRepository(): MyronSectionBridgeRepository
{
    static $repository = null;

    if ($repository instanceof MyronSectionBridgeRepository) {
        return $repository;
    }

    $repository = new MyronSectionBridgeRepository(myronDatabase());

    return $repository;
}

function myronSectionComponentDefaultsRepository(): MyronSectionComponentDefaultsRepository
{
    static $repository = null;

    if ($repository instanceof MyronSectionComponentDefaultsRepository) {
        return $repository;
    }

    $repository = new MyronSectionComponentDefaultsRepository(myronDatabase());

    return $repository;
}

function myronSectionContentDefaultsRepository(): MyronSectionContentDefaultsRepository
{
    static $repository = null;

    if ($repository instanceof MyronSectionContentDefaultsRepository) {
        return $repository;
    }

    $repository = new MyronSectionContentDefaultsRepository(myronDatabase());

    return $repository;
}

function myronSectionUsageService(): MyronSectionUsageService
{
    static $service = null;

    if ($service instanceof MyronSectionUsageService) {
        return $service;
    }

    $service = new MyronSectionUsageService(
        myronSectionRegistryRepository(),
        myronTemplateDefinitionRepository(),
    );

    return $service;
}

function myronLiveSectionInventoryReadModel(): MyronLiveSectionInventoryReadModel
{
    static $model = null;

    if ($model instanceof MyronLiveSectionInventoryReadModel) {
        return $model;
    }

    $model = new MyronLiveSectionInventoryReadModel(
        myronContentRepository(),
        myronSectionRegistryRepository(),
        myronSectionComponentDefaultsRepository(),
        myronSectionContentDefaultsRepository(),
    );

    return $model;
}

function myronCurrentSiteUsageReadModel(): MyronCurrentSiteUsageReadModel
{
    static $model = null;

    if ($model instanceof MyronCurrentSiteUsageReadModel) {
        return $model;
    }

    $model = new MyronCurrentSiteUsageReadModel(
        myronContentRepository(),
        myronSectionRegistryRepository(),
        myronLiveSectionInventoryReadModel(),
    );

    return $model;
}

function myronSectionContentMigrationService(): MyronSectionContentMigrationService
{
    static $service = null;

    if ($service instanceof MyronSectionContentMigrationService) {
        return $service;
    }

    $service = new MyronSectionContentMigrationService();
    return $service;
}

function myronSiteTypeRegistryRepository(): MyronSiteTypeRegistryRepository
{
    static $repository = null;

    if ($repository instanceof MyronSiteTypeRegistryRepository) {
        return $repository;
    }

    myronEnsureDefinitionsRuntimeSeeded();
    $repository = new MyronSiteTypeRegistryRepository(myronDatabase());

    return $repository;
}

function myronBundleActivationRepository(): MyronBundleActivationRepository
{
    static $repository = null;

    if ($repository instanceof MyronBundleActivationRepository) {
        return $repository;
    }

    myronEnsureDefinitionsRuntimeSeeded();
    $repository = new MyronBundleActivationRepository(myronDatabase(), myronSiteTypeRegistryRepository());

    return $repository;
}

function myronDisabledPageRedirectsRepository(): DisabledPageRedirectsRepository
{
    static $repository = null;

    if ($repository instanceof DisabledPageRedirectsRepository) {
        return $repository;
    }

    $repository = new DisabledPageRedirectsRepository(myronDatabase());
    return $repository;
}

function myronRedirectFallbackValidator(): MyronRedirectFallbackValidator
{
    static $validator = null;

    if ($validator instanceof MyronRedirectFallbackValidator) {
        return $validator;
    }

    $validator = new MyronRedirectFallbackValidator(myronDatabase(), myronDisabledPageRedirectsRepository());
    return $validator;
}

function myronBundleImpactAnalysisService(): MyronBundleImpactAnalysisService
{
    static $service = null;

    if ($service instanceof MyronBundleImpactAnalysisService) {
        return $service;
    }

    $service = new MyronBundleImpactAnalysisService(
        myronDatabase(),
        myronSiteTypeRegistryRepository(),
        myronBundleActivationRepository()
    );
    return $service;
}

function myronBundleDisableService(): MyronBundleDisableService
{
    static $service = null;

    if ($service instanceof MyronBundleDisableService) {
        return $service;
    }

    $service = new MyronBundleDisableService(
        myronDatabase(),
        myronSiteTypeRegistryRepository(),
        myronBundleActivationRepository(),
        myronBundleImpactAnalysisService(),
        myronDisabledPageRedirectsRepository(),
        myronRedirectFallbackValidator()
    );
    return $service;
}

function myronBundleEnableService(): MyronBundleEnableService
{
    static $service = null;

    if ($service instanceof MyronBundleEnableService) {
        return $service;
    }

    $service = new MyronBundleEnableService(
        myronDatabase(),
        myronSiteTypeRegistryRepository(),
        myronBundleActivationRepository(),
        myronDisabledPageRedirectsRepository()
    );
    return $service;
}

function myronTemplateInstantiationService(): MyronTemplateInstantiationService
{
    static $service = null;

    if ($service instanceof MyronTemplateInstantiationService) {
        return $service;
    }

    $service = new MyronTemplateInstantiationService(
        myronDatabase(),
        myronContentRepository(),
    );

    return $service;
}

function myronBundleBootstrapService(): MyronBundleBootstrapService
{
    static $service = null;

    if ($service instanceof MyronBundleBootstrapService) {
        return $service;
    }

    $service = new MyronBundleBootstrapService(
        myronDatabase(),
        myronContentRepository(),
        myronTemplateDefinitionRepository(),
        myronSiteTypeRegistryRepository(),
        myronBundleActivationRepository(),
        myronTemplateInstantiationService(),
        myronSiteSetupSelectionService(),
    );

    return $service;
}

function myronDefinitionTemplateRenderer(): MyronDefinitionTemplateRenderer
{
    static $renderer = null;

    if ($renderer instanceof MyronDefinitionTemplateRenderer) {
        return $renderer;
    }

    $sectionRenderers = new MyronSectionRendererRegistry();
    $renderer = new MyronDefinitionTemplateRenderer(null, myronPublicComponentDataResolver(), $sectionRenderers);
    myronModuleRegistry()->initializeSectionRenderers($sectionRenderers);
    return $renderer;
}

function myronPublishedPageHtmlAssembler(): MyronPublishedPageHtmlAssembler
{
    static $assembler = null;

    if ($assembler instanceof MyronPublishedPageHtmlAssembler) {
        return $assembler;
    }

    $assembler = new MyronPublishedPageHtmlAssembler();
    return $assembler;
}

function myronPublicCriticalResourceResolver(): MyronPublicCriticalResourceResolver
{
    static $resolver = null;

    if ($resolver instanceof MyronPublicCriticalResourceResolver) {
        return $resolver;
    }

    $resolver = new MyronPublicCriticalResourceResolver();
    return $resolver;
}

function myronPublicComponentDataResolver(): MyronPublicComponentDataResolver
{
    static $resolver = null;

    if ($resolver instanceof MyronPublicComponentDataResolver) {
        return $resolver;
    }

    $resolver = new MyronPublicComponentDataResolver(myronDatabase());
    return $resolver;
}

function myronPublicNavigationRenderer(): MyronPublicNavigationRenderer
{
    static $renderer = null;

    if ($renderer instanceof MyronPublicNavigationRenderer) {
        return $renderer;
    }

    $renderer = new MyronPublicNavigationRenderer();
    return $renderer;
}

function myronNavigationDesignSettingsRepository(): MyronNavigationDesignSettingsRepository
{
    static $repository = null;

    if ($repository instanceof MyronNavigationDesignSettingsRepository) {
        return $repository;
    }

    $repository = new MyronNavigationDesignSettingsRepository(myronDatabase());
    return $repository;
}

function myronNavigationDesignRepository(): MyronNavigationDesignRepository
{
    static $repository = null;

    if ($repository instanceof MyronNavigationDesignRepository) {
        return $repository;
    }

    $repository = new MyronNavigationDesignRepository(myronDatabase());
    return $repository;
}

function myronNavigationHeaderOverrideRepository(): MyronNavigationHeaderOverrideRepository
{
    static $repository = null;

    if ($repository instanceof MyronNavigationHeaderOverrideRepository) {
        return $repository;
    }

    $repository = new MyronNavigationHeaderOverrideRepository(myronDatabase());
    return $repository;
}

function myronFooterDesignSettingsRepository(): MyronFooterDesignSettingsRepository
{
    static $repository = null;

    if ($repository instanceof MyronFooterDesignSettingsRepository) {
        return $repository;
    }

    $repository = new MyronFooterDesignSettingsRepository(myronDatabase());
    return $repository;
}

function myronFooterDesignRepository(): MyronFooterDesignRepository
{
    static $repository = null;

    if ($repository instanceof MyronFooterDesignRepository) {
        return $repository;
    }

    $repository = new MyronFooterDesignRepository(myronDatabase());
    return $repository;
}

function myronFooterZoneContentSchemaService(): MyronFooterZoneContentSchemaService
{
    static $service = null;

    if ($service instanceof MyronFooterZoneContentSchemaService) {
        return $service;
    }

    $service = new MyronFooterZoneContentSchemaService();
    return $service;
}

function myronFooterContentSeedService(): MyronFooterContentSeedService
{
    static $service = null;

    if ($service instanceof MyronFooterContentSeedService) {
        return $service;
    }

    $service = new MyronFooterContentSeedService();
    return $service;
}

function myronFooterVariantCompositionService(): MyronFooterVariantCompositionService
{
    static $service = null;

    if ($service instanceof MyronFooterVariantCompositionService) {
        return $service;
    }

    $service = new MyronFooterVariantCompositionService();
    return $service;
}

function myronFooterVariantOverrideRepository(): MyronFooterVariantOverrideRepository
{
    static $repository = null;

    if ($repository instanceof MyronFooterVariantOverrideRepository) {
        return $repository;
    }

    $repository = new MyronFooterVariantOverrideRepository(myronDatabase());
    return $repository;
}

function myronRailDesignRepository(): MyronRailDesignRepository
{
    static $repository = null;

    if ($repository instanceof MyronRailDesignRepository) {
        return $repository;
    }

    $repository = new MyronRailDesignRepository(myronDatabase());
    return $repository;
}

function myronTemplateChromeAssignmentRepository(): MyronTemplateChromeAssignmentRepository
{
    static $repository = null;

    if ($repository instanceof MyronTemplateChromeAssignmentRepository) {
        return $repository;
    }

    $repository = new MyronTemplateChromeAssignmentRepository(myronDatabase());
    return $repository;
}

function myronPublicHeaderContextResolver(): MyronPublicHeaderContextResolver
{
    static $resolver = null;

    if ($resolver instanceof MyronPublicHeaderContextResolver) {
        return $resolver;
    }

    $resolver = new MyronPublicHeaderContextResolver(
        myronContentRepository(),
        myronNavigationDesignRepository(),
        myronTemplateChromeAssignmentRepository(),
        myronBundleActivationRepository(),
        myronFileRepository(),
    );
    return $resolver;
}

function myronTemplatePreviewFactory(): MyronTemplatePreviewFactory
{
    static $factory = null;

    if ($factory instanceof MyronTemplatePreviewFactory) {
        return $factory;
    }

    $factory = new MyronTemplatePreviewFactory(myronTemplateContentResolver());
    return $factory;
}

function myronTemplateContentResolver(): MyronTemplateContentResolver
{
    static $resolver = null;

    if ($resolver instanceof MyronTemplateContentResolver) {
        return $resolver;
    }

    $resolver = new MyronTemplateContentResolver(
        myronTemplateDefinitionRepository(),
        myronContentRepository(),
        myronTemplateInstantiationService(),
    );

    return $resolver;
}

function myronEditorSurfaceReadModel(): MyronEditorSurfaceReadModel
{
    static $model = null;

    if ($model instanceof MyronEditorSurfaceReadModel) {
        return $model;
    }

    $model = new MyronEditorSurfaceReadModel(
        myronContentRepository(),
        myronTemplateDefinitionRepository(),
        myronSectionRegistryRepository(),
        myronSectionContentSchemaService(),
        myronTemplateContentResolver(),
    );

    return $model;
}

function myronPageContractService(): MyronPageContractService
{
    static $service = null;

    if ($service instanceof MyronPageContractService) {
        return $service;
    }

    $service = new MyronPageContractService(
        myronContentRepository(),
        myronEditorSurfaceReadModel(),
        myronFileRepository(),
    );

    return $service;
}

function myronSectionContentSchemaService(): MyronSectionContentSchemaService
{
    static $service = null;

    if ($service instanceof MyronSectionContentSchemaService) {
        return $service;
    }

    $service = new MyronSectionContentSchemaService(myronDefinitionTemplateRenderer()->sectionRendererRegistry());
    return $service;
}

function myronComponentPreviewRenderer(): MyronComponentPreviewRenderer
{
    static $renderer = null;

    if ($renderer instanceof MyronComponentPreviewRenderer) {
        return $renderer;
    }

    $renderer = new MyronComponentPreviewRenderer();
    return $renderer;
}

function myronPrimitiveRenderer(): MyronPrimitiveRenderer
{
    static $renderer = null;

    if ($renderer instanceof MyronPrimitiveRenderer) {
        return $renderer;
    }

    $renderer = new MyronPrimitiveRenderer(myronDefinitionTemplateRenderer());
    return $renderer;
}

function myronPrimitiveExplorerService(): MyronPrimitiveExplorerService
{
    static $service = null;

    if ($service instanceof MyronPrimitiveExplorerService) {
        return $service;
    }

    $service = new MyronPrimitiveExplorerService(
        myronTemplateDefinitionRepository(),
        myronComponentRegistryRepository(),
    );
    return $service;
}

function myronComponentPreviewCatalog(): MyronComponentPreviewCatalog
{
    static $catalog = null;

    if ($catalog instanceof MyronComponentPreviewCatalog) {
        return $catalog;
    }

    $catalog = new MyronComponentPreviewCatalog();
    return $catalog;
}

function myronQualityReportService(): MyronQualityReportService
{
    static $service = null;

    if ($service instanceof MyronQualityReportService) {
        return $service;
    }

    $service = new MyronQualityReportService(myronDatabase());
    return $service;
}

function myronAuthRepository(): MyronAuthRepository
{
    static $repository = null;

    if ($repository instanceof MyronAuthRepository) {
        return $repository;
    }

    $repository = new MyronAuthRepository(myronDatabase());
    $repository->ensureSeedData();

    return $repository;
}

function myronMailSettingsRepository(): MyronMailSettingsRepository
{
    static $repository = null;

    if ($repository instanceof MyronMailSettingsRepository) {
        return $repository;
    }

    $repository = new MyronMailSettingsRepository(myronDatabase());
    return $repository;
}

function myronMailTransportRegistry(): MailTransportRegistry
{
    static $registry = null;
    if ($registry instanceof MailTransportRegistry) {
        return $registry;
    }
    $registry = new MailTransportRegistry();
    $registry->registerCore('smtp', new MyronSmtpTransport(myronMailSettingsRepository()));
    return $registry;
}

function myronNotificationEmailsRepository(): NotificationEmailsRepository
{
    static $repository = null;
    if ($repository instanceof NotificationEmailsRepository) {
        return $repository;
    }
    $repository = new NotificationEmailsRepository(myronDatabase());
    return $repository;
}

function myronNotificationEmailsService(): NotificationEmailsService
{
    static $service = null;
    if ($service instanceof NotificationEmailsService) {
        return $service;
    }
    $service = new NotificationEmailsService(
        myronNotificationEmailsRepository(),
        myronMicFormRepository(),
        myronMailSettingsRepository()
    );
    return $service;
}

function myronMicFormNotificationDispatcher(): MicFormNotificationDispatcher
{
    static $dispatcher = null;
    if ($dispatcher instanceof MicFormNotificationDispatcher) {
        return $dispatcher;
    }
    $dispatcher = new MicFormNotificationDispatcher(
        myronMicFormRepository(),
        myronMicFormSubmissionRepository(),
        myronMicFormNotificationFailureRepository(),
        myronNotificationEmailsRepository(),
        myronMailSettingsRepository(),
        new MicFormNotificationBody()
    );
    return $dispatcher;
}

function myronFormNotificationFailureService(): FormNotificationFailureService
{
    static $service = null;
    if ($service instanceof FormNotificationFailureService) {
        return $service;
    }
    $service = new FormNotificationFailureService(
        myronMicFormNotificationFailureRepository(),
        myronMicFormNotificationDispatcher()
    );
    return $service;
}

function myronFileRepository(): MyronFileRepository
{
    static $repository = null;

    if ($repository instanceof MyronFileRepository) {
        return $repository;
    }

    $repository = new MyronFileRepository(myronDatabase());
    return $repository;
}

function myronVideoAssetRepository(): MyronVideoAssetRepository
{
    static $repository = null;

    if ($repository instanceof MyronVideoAssetRepository) {
        return $repository;
    }

    $repository = new MyronVideoAssetRepository(myronDatabase(), myronFileRepository());
    return $repository;
}

function myronMediaAccessibilityAttachmentRepository(): MyronMediaAccessibilityAttachmentRepository
{
    static $repository = null;

    if ($repository instanceof MyronMediaAccessibilityAttachmentRepository) {
        return $repository;
    }

    $repository = new MyronMediaAccessibilityAttachmentRepository(myronDatabase(), myronFileRepository());
    return $repository;
}

function myronDocumentTemplateRepository(): MyronDocumentTemplateRepository
{
    static $repository = null;

    if ($repository instanceof MyronDocumentTemplateRepository) {
        return $repository;
    }

    $repository = new MyronDocumentTemplateRepository(myronDatabase(), myronFileRepository());
    return $repository;
}

function myronPasswordResetService(): MyronPasswordResetService
{
    static $service = null;

    if ($service instanceof MyronPasswordResetService) {
        return $service;
    }

    $service = new MyronPasswordResetService(
        myronDatabase(),
        myronAuthRepository(),
        myronMailSettingsRepository(),
        new MyronMailer(),
    );

    return $service;
}

function myronBranchingFormService(): MyronBranchingFormService
{
    static $service = null;

    if ($service instanceof MyronBranchingFormService) {
        return $service;
    }

    $service = new MyronBranchingFormService();
    return $service;
}

function myronAnalyticsSessionHashService(): MyronAnalyticsSessionHashService
{
    static $service = null;

    if ($service instanceof MyronAnalyticsSessionHashService) {
        return $service;
    }

    $service = new MyronAnalyticsSessionHashService(myronDatabase());
    return $service;
}

function myronUserAgentClassifier(): MyronUserAgentClassifier
{
    static $classifier = null;

    if ($classifier instanceof MyronUserAgentClassifier) {
        return $classifier;
    }

    $classifier = new MyronUserAgentClassifier();
    return $classifier;
}

function myronSiteAnalyticsRepository(): MyronSiteAnalyticsRepository
{
    static $repository = null;

    if ($repository instanceof MyronSiteAnalyticsRepository) {
        return $repository;
    }

    $repository = new MyronSiteAnalyticsRepository(myronDatabase());
    return $repository;
}

function myronVerificationStorageDir(): string
{
    return rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'myron-verification';
}

function myronVerificationSettingsRepository(): MyronVerificationSettingsRepository
{
    static $repository = null;

    if ($repository instanceof MyronVerificationSettingsRepository) {
        return $repository;
    }

    $repository = new MyronVerificationSettingsRepository(myronDatabase());
    return $repository;
}

function myronVerificationLogRepository(): MyronVerificationLogRepository
{
    static $repository = null;

    if ($repository instanceof MyronVerificationLogRepository) {
        return $repository;
    }

    $repository = new MyronVerificationLogRepository(myronDatabase());
    return $repository;
}

function myronVerificationChallengeStore(): MyronVerificationChallengeStore
{
    static $store = null;

    if ($store instanceof MyronVerificationChallengeStore) {
        return $store;
    }

    $store = new MyronVerificationChallengeStore(myronVerificationStorageDir());
    return $store;
}

function myronVerificationEngine(): MyronVerificationEngine
{
    static $engine = null;

    if ($engine instanceof MyronVerificationEngine) {
        return $engine;
    }

    $storageDir = myronVerificationStorageDir();
    $engine = new MyronVerificationEngine(
        myronVerificationSettingsRepository(),
        new MyronNativeVerificationProvider(
            new MyronVerificationRateLimiter($storageDir),
            myronVerificationChallengeStore(),
        ),
        new MyronTurnstileVerificationProvider(),
        myronVerificationLogRepository(),
    );
    return $engine;
}

function myronMailTestService(): MyronMailTestService
{
    static $service = null;

    if ($service instanceof MyronMailTestService) {
        return $service;
    }

    $service = new MyronMailTestService(
        myronMailSettingsRepository(),
        new MyronMailer(),
    );

    return $service;
}

function myronSiteSettingsRepository(): MyronSiteSettingsRepository
{
    static $repository = null;

    if ($repository instanceof MyronSiteSettingsRepository) {
        return $repository;
    }

    $repository = new MyronSiteSettingsRepository(
        myronDatabase(),
        myronFileRepository(),
    );

    return $repository;
}

function myronDashboardReadModel(): MyronDashboardReadModel
{
    static $model = null;

    if ($model instanceof MyronDashboardReadModel) {
        return $model;
    }

    $model = new MyronDashboardReadModel(
        myronContentRepository(),
        myronFileRepository(),
        myronAuthRepository(),
        myronLicenseRepository(),
        myronMailSettingsRepository(),
        myronAiIntegrationRepository(),
        myronAuditLogRepository(),
        myronSiteSettingsRepository(),
        myronComponentRegistryRepository(),
        myronSectionRegistryRepository(),
        myronTemplateDefinitionRepository(),
        myronTokenPatchRepository(),
        myronCurrentSiteUsageReadModel(),
    );

    return $model;
}

function myronDashboardTipsFeedRepository(): MyronDashboardTipsFeedRepository
{
    static $repository = null;

    if ($repository instanceof MyronDashboardTipsFeedRepository) {
        return $repository;
    }

    $repository = new MyronDashboardTipsFeedRepository(myronDatabase());
    return $repository;
}

function myronDashboardTipsFeedService(): MyronDashboardTipsFeedService
{
    static $service = null;

    if ($service instanceof MyronDashboardTipsFeedService) {
        return $service;
    }

    $service = new MyronDashboardTipsFeedService(myronDashboardTipsFeedRepository());
    return $service;
}

function myronDashboardNotesRepository(): MyronDashboardNotesRepository
{
    static $repository = null;

    if ($repository instanceof MyronDashboardNotesRepository) {
        return $repository;
    }

    $repository = new MyronDashboardNotesRepository(myronDatabase());
    return $repository;
}

function myronDashboardLinksRepository(): MyronDashboardLinksRepository
{
    static $repository = null;

    if ($repository instanceof MyronDashboardLinksRepository) {
        return $repository;
    }

    $repository = new MyronDashboardLinksRepository(myronDatabase());
    return $repository;
}

function myronDashboardMessagesRepository(): MyronDashboardMessagesRepository
{
    static $repository = null;

    if ($repository instanceof MyronDashboardMessagesRepository) {
        return $repository;
    }

    $repository = new MyronDashboardMessagesRepository(myronDatabase());
    return $repository;
}

function myronOnboardingStateRepository(): MyronOnboardingStateRepository
{
    static $repository = null;

    if ($repository instanceof MyronOnboardingStateRepository) {
        return $repository;
    }

    $repository = new MyronOnboardingStateRepository(
        myronDatabase(),
        myronSiteTypeRegistryRepository(),
        myronBundleActivationRepository(),
        null,
        null,
        myronSiteSetupSelectionService(),
    );

    return $repository;
}

function myronSiteSetupSelectionService(): MyronSiteSetupSelectionService
{
    static $service = null;

    if ($service instanceof MyronSiteSetupSelectionService) {
        return $service;
    }

    $service = new MyronSiteSetupSelectionService(
        myronDatabase(),
        myronSiteTypeRegistryRepository(),
        myronTemplateDefinitionRepository(),
        myronEntitlementPresentationPolicy(),
    );

    return $service;
}

function myronSiteTypeStageGateService(?int $currentStage = null): MyronSiteTypeStageGateService
{
    if ($currentStage !== null) {
        return new MyronSiteTypeStageGateService($currentStage);
    }

    static $service = null;

    if ($service instanceof MyronSiteTypeStageGateService) {
        return $service;
    }

    $configured = getenv('MYRON_FOUNDATION_STAGE');
    $stage = is_string($configured) && trim($configured) !== '' ? (int) $configured : 5;
    $service = new MyronSiteTypeStageGateService($stage);
    return $service;
}

function myronSiteResetService(): MyronSiteResetService
{
    return new MyronSiteResetService(
        myronDatabase(),
        myronContentRepository(),
        myronOnboardingStateRepository(),
        myronBundleActivationRepository(),
        myronFileRepository(),
        myronSiteSettingsRepository(),
        new DesignSystemRegistry(),
    );
}

function myronSiteSetupDefaultReplacementService(): MyronSiteSetupDefaultReplacementService
{
    return new MyronSiteSetupDefaultReplacementService(
        myronDatabase(),
        myronSiteTypeRegistryRepository(),
        myronSiteSetupSelectionService(),
        myronFooterDesignRepository(),
    );
}

function myronUpdatePackageValidator(): MyronUpdatePackageValidator
{
    return new MyronUpdatePackageValidator();
}

function myronModulePackageInstallLedger(): MyronModulePackageInstallLedger
{
    return new MyronModulePackageInstallLedger(myronAppRoot());
}

function myronMigrationOperationsService(): MyronMigrationOperationsService
{
    return new MyronMigrationOperationsService(
        myronDatabase(),
        myronModulePackageInstallLedger(),
        myronModuleRegistry(),
    );
}

function myronEntitlementBoundaryIntegrityService(): MyronEntitlementBoundaryIntegrityService
{
    return new MyronEntitlementBoundaryIntegrityService(myronProjectRoot());
}

function myronApplicationUpdateAuditRepository(): MyronUpdateAuditRepository
{
    return new MyronUpdateAuditRepository(myronDatabase());
}

function myronApplicationUpdateService(): MyronUpdateApplicationService
{
    return new MyronUpdateApplicationService(
        myronProjectRoot(),
        myronAppRoot(),
        myronUpdatePackageValidator(),
        myronApplicationUpdateAuditRepository(),
    );
}

function myronVersionComparator(): MyronVersionComparator
{
    return new MyronVersionComparator();
}

function myronRemoteUpdateSettingsRepository(): MyronUpdateSettingsRepository
{
    return new MyronUpdateSettingsRepository(myronDatabase());
}

function myronRemoteUpdateStateRepository(): MyronUpdateStateRepository
{
    return new MyronUpdateStateRepository(myronDatabase());
}

function myronRemoteUpdateCheckService(?MyronRemoteUpdateClient $client = null): MyronRemoteUpdateCheckService
{
    $versionComparator = myronVersionComparator();

    return new MyronRemoteUpdateCheckService(
        myronRemoteUpdateSettingsRepository(),
        myronRemoteUpdateStateRepository(),
        $client ?? new MyronRemoteUpdateClient(),
        new MyronRemoteUpdateManifestValidator($versionComparator),
        $versionComparator,
        myronLicenseRepository(),
    );
}

function myronRemoteModulePackageClient(?MyronRemoteUpdateClient $client = null): MyronRemoteModulePackageClient
{
    return new MyronRemoteModulePackageClient(
        $client ?? new MyronRemoteUpdateClient(),
        myronLicenseRepository(),
        myronEntitlementBoundaryIntegrityService(),
        myronAppRoot(),
    );
}

function myronRemoteUpdateApplyService(): MyronRemoteUpdateApplyService
{
    return new MyronRemoteUpdateApplyService(
        myronAppRoot(),
        myronRemoteUpdateStateRepository(),
        myronApplicationUpdateService(),
    );
}

/**
 * @return array<string, mixed>
 */
function myronRemoteUpdateNoticeContext(): array
{
    try {
        $stateRepository = myronRemoteUpdateStateRepository();
        $state = $stateRepository->get();
        $available = is_array($state['available_update'] ?? null) ? $state['available_update'] : null;
        if (!$stateRepository->hasVisibleAvailableUpdate() || $available === null) {
            return [
                'available' => false,
                'href' => myronBuildAdminUrl('administration.siteSetup') . '#application-update-title',
                'label' => 'No application update notification',
            ];
        }

        $version = (string) ($available['latestVersion'] ?? '');
        return [
            'available' => true,
            'version' => $version,
            'href' => myronBuildAdminUrl('administration.siteSetup') . '#application-update-title',
            'label' => 'MyronCMS ' . $version . ' update available',
        ];
    } catch (Throwable) {
        return [
            'available' => false,
            'href' => myronBuildAdminUrl('administration.siteSetup') . '#application-update-title',
            'label' => 'No application update notification',
        ];
    }
}

/**
 * @param array<string, mixed> $currentUser
 * @return array{unread_messages:int,system_items:list<array<string,string>>,has_notifications:bool}
 */
function myronUserNotificationContext(array $currentUser): array
{
    $userId = (string) ($currentUser['id'] ?? '');
    $unreadMessages = $userId !== '' ? myronDashboardMessagesRepository()->countUnread($userId) : 0;
    $systemItems = [];

    $updateNotice = myronRemoteUpdateNoticeContext();
    if (!empty($updateNotice['available'])) {
        $systemItems[] = [
            'type' => 'update',
            'title' => (string) ($updateNotice['label'] ?? 'MyronCMS update available'),
            'href' => (string) ($updateNotice['href'] ?? myronBuildAdminUrl('administration.siteSetup') . '#application-update-title'),
        ];
    }

    if (myronUserCanAccessAdministration($currentUser)) {
        try {
            foreach (myronDashboardTipsFeedRepository()->listTipsForContext('administration', 5) as $tip) {
                if (empty($tip['isSecurity'])) {
                    continue;
                }

                $href = trim((string) ($tip['url'] ?? ''));
                if ($href === '') {
                    continue;
                }

                $systemItems[] = [
                    'type' => 'security',
                    'title' => (string) ($tip['title'] ?? 'Security advisory'),
                    'href' => $href,
                ];
            }
        } catch (Throwable) {
            // Notification chrome must remain available even if feed cache data is absent.
        }
    }

    return [
        'unread_messages' => $unreadMessages,
        'system_items' => $systemItems,
        'has_notifications' => $unreadMessages > 0 || $systemItems !== [],
    ];
}

function myronRemoteUpdateCheckOnAdminLogin(): void
{
    try {
        $settings = myronRemoteUpdateSettingsRepository()->get();
        if (!empty($settings['check_on_admin_login'])) {
            myronRemoteUpdateCheckService()->checkIfStale();
        }
    } catch (Throwable) {
        // Update checks must never block authentication.
    }
}

function myronSiteSettings(): array
{
    if (isset($GLOBALS['myron_site_settings_cache']) && is_array($GLOBALS['myron_site_settings_cache'])) {
        return $GLOBALS['myron_site_settings_cache'];
    }

    $GLOBALS['myron_site_settings_cache'] = myronSiteSettingsRepository()->getSettings();
    return $GLOBALS['myron_site_settings_cache'];
}

function myronRefreshSiteSettingsCache(): array
{
    $GLOBALS['myron_site_settings_cache'] = myronSiteSettingsRepository()->getSettings();
    return $GLOBALS['myron_site_settings_cache'];
}

function myronSiteTitle(): string
{
    return trim((string) (myronSiteSettings()['site_title'] ?? 'MyronCMS')) ?: 'MyronCMS';
}

function myronSiteLanguage(): string
{
    $language = trim((string) (myronSiteSettings()['site_language'] ?? 'en-US'));
    return $language === '' ? 'en-US' : $language;
}

function myronSiteTimezone(): string
{
    $timezone = trim((string) (myronSiteSettings()['timezone'] ?? 'UTC'));
    return $timezone === '' ? 'UTC' : $timezone;
}

function myronSiteDateFormat(): string
{
    $format = trim((string) (myronSiteSettings()['date_format'] ?? 'F j, Y'));
    return $format === '' ? 'F j, Y' : $format;
}

function myronSiteTimeFormat(): string
{
    $format = trim((string) (myronSiteSettings()['time_format'] ?? 'g:i a'));
    return $format === '' ? 'g:i a' : $format;
}

function myronAnalyticsEnabled(): bool
{
    return (bool) (myronSiteSettings()['analytics_enabled'] ?? true);
}

function myronAnalyticsRetentionDays(): int
{
    $days = (int) (myronSiteSettings()['analytics_retention_days'] ?? 90);
    return in_array($days, [30, 90, 180, 365], true) ? $days : 90;
}

function myronAnalyticsHeadScript(): string
{
    return trim((string) (myronSiteSettings()['analytics_head_script'] ?? ''));
}

function myronVerificationEnabled(): bool
{
    return (bool) (myronVerificationSettingsRepository()->getSettings()['verification_enabled'] ?? true);
}

function myronVerificationSecretAvailable(): bool
{
    return trim((string) (getenv('MYRON_APP_KEY') ?: '')) !== '';
}

function myronVerificationSecret(): string
{
    $secret = trim((string) (getenv('MYRON_APP_KEY') ?: ''));
    return $secret !== '' ? $secret : 'myroncms-missing-app-key';
}

function myronVerificationSignPassive(string $formKey, int $issuedAt, string $nonce): string
{
    return hash_hmac('sha256', implode('|', [$formKey, (string) $issuedAt, $nonce]), myronVerificationSecret());
}

function myronVerificationClientIp(): string
{
    $forwarded = trim((string) ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? ''));
    if ($forwarded !== '') {
        $parts = array_map('trim', explode(',', $forwarded));
        if (($parts[0] ?? '') !== '') {
            return (string) $parts[0];
        }
    }
    return trim((string) ($_SERVER['REMOTE_ADDR'] ?? ''));
}

function myronVerificationRender(string $formKey): string
{
    $settings = myronVerificationSettingsRepository()->getSettings();
    if (empty($settings['verification_enabled'])) {
        return '';
    }

    $formKey = substr(trim($formKey), 0, 120) ?: 'default';
    $issuedAt = time();
    $nonce = bin2hex(random_bytes(16));
    $signature = myronVerificationSignPassive($formKey, $issuedAt, $nonce);
    $html = [];
    $html[] = '<div class="myron-verification" data-myron-verification-form>';
    $html[] = '<input type="text" name="myron_company" value="" tabindex="-1" autocomplete="off" aria-hidden="true" class="myron-verification__hp">';
    $html[] = '<input type="hidden" name="myron_verification_form" value="' . myronEscape($formKey) . '">';
    $html[] = '<input type="hidden" name="myron_verification_issued_at" value="' . $issuedAt . '">';
    $html[] = '<input type="hidden" name="myron_verification_nonce" value="' . myronEscape($nonce) . '">';
    $html[] = '<input type="hidden" name="myron_verification_signature" value="' . myronEscape($signature) . '">';
    $html[] = '<input type="hidden" name="myron_verification_js" value="" data-myron-verification-js>';
    $html[] = '<input type="hidden" name="myron_verification_interactions" value="0" data-myron-verification-interactions>';

    if ((string) ($settings['verification_provider'] ?? 'native') === 'turnstile' && trim((string) ($settings['verification_turnstile_site_key'] ?? '')) !== '') {
        $html[] = '<div class="cf-turnstile" data-sitekey="' . myronEscape((string) $settings['verification_turnstile_site_key']) . '"></div>';
    } elseif (!empty($settings['verification_challenge_enabled'])) {
        $challenge = myronVerificationChallengeStore()->issue($formKey);
        $html[] = '<fieldset class="myron-verification__challenge">';
        $html[] = '<legend>Verification</legend>';
        $html[] = '<p>' . myronEscape((string) ($challenge['question'] ?? 'Choose the correct answer.')) . '</p>';
        $html[] = '<input type="hidden" name="myron_challenge_id" value="' . myronEscape((string) ($challenge['id'] ?? '')) . '">';
        $html[] = '<input type="hidden" name="myron_challenge_signature" value="' . myronEscape((string) ($challenge['signature'] ?? '')) . '">';
        foreach ((array) ($challenge['options'] ?? []) as $value => $label) {
            $id = 'myron-v-' . preg_replace('/[^A-Za-z0-9_-]+/', '-', $formKey) . '-' . preg_replace('/[^A-Za-z0-9_-]+/', '-', (string) $value);
            $html[] = '<label class="myron-verification__choice" for="' . myronEscape($id) . '"><input id="' . myronEscape($id) . '" type="radio" name="myron_challenge_answer" value="' . myronEscape((string) $value) . '" required> <span>' . myronEscape((string) $label) . '</span></label>';
        }
        $html[] = '</fieldset>';
    }
    $html[] = '</div>';

    return implode("\n", $html);
}

function myronVerificationVerify(string $formKey, array $input): MyronVerificationResult
{
    return myronVerificationEngine()->verify(
        $formKey,
        $input,
        myronVerificationClientIp(),
        trim((string) ($_SERVER['HTTP_USER_AGENT'] ?? '')),
    );
}

function myronSiteFaviconUrl(): ?string
{
    $url = myronSiteSettings()['favicon_url'] ?? null;
    return is_string($url) && $url !== '' ? $url : null;
}

function myronSiteLogoLightUrl(): string
{
    return trim((string) (myronSiteSettings()['site_logo_light_url'] ?? ''));
}

function myronSiteLogoDarkUrl(): string
{
    return trim((string) (myronSiteSettings()['site_logo_dark_url'] ?? ''));
}

function myronSiteLogoAlt(): string
{
    return trim((string) (myronSiteSettings()['site_logo_alt'] ?? ''));
}

function myronComposeDocumentTitle(string $contextTitle): string
{
    $siteTitle = myronSiteTitle();
    $context = trim($contextTitle);
    if ($context === '' || $context === $siteTitle) {
        return $siteTitle;
    }

    return $context . ' · ' . $siteTitle;
}

function myronRenderSiteFaviconLink(): string
{
    $faviconUrl = myronSiteFaviconUrl();
    if ($faviconUrl === null) {
        return '';
    }

    return '<link rel="icon" href="' . myronEscape($faviconUrl) . '">';
}

function myronHasUsers(): bool
{
    return myronAuthRepository()->hasUsers();
}

function myronCurrentUser(): ?array
{
    static $cachedUser = null;
    static $resolvedUserId = null;

    $userId = myronAuthenticatedUserId();
    if ($userId === null) {
        $cachedUser = null;
        $resolvedUserId = null;
        return null;
    }

    if ($resolvedUserId === $userId && is_array($cachedUser)) {
        return $cachedUser;
    }

    $user = myronAuthRepository()->findUserById($userId);
    if ($user === null) {
        myronClearAuthenticatedUser();
        $cachedUser = null;
        $resolvedUserId = null;
        return null;
    }

    $cachedUser = $user;
    $resolvedUserId = $userId;
    return $cachedUser;
}

function myronLoginUser(string $userId): void
{
    myronSetAuthenticatedUserId($userId);
}

function myronLogoutUser(): void
{
    myronClearAuthenticatedUser();
}

function myronRequireAuthenticatedUser(): array
{
    $user = myronCurrentUser();
    if (is_array($user)) {
        return $user;
    }

    $requestUri = (string) ($_SERVER['REQUEST_URI'] ?? myronBuildAdminUrl('content.pages'));
    myronRedirect(myronBuildAdminUrl('auth.login') . '?next=' . rawurlencode(myronSanitizeAdminNext($requestUri)));
}

/**
 * @param list<string> $roleKeys
 */
function myronRequireRole(array $roleKeys): array
{
    $user = myronRequireAuthenticatedUser();
    if (myronUserMatchesRoleTerms($user, $roleKeys)) {
        return $user;
    }

    myronRenderForbidden('Your current role does not have access to this surface.');
}

function myronUserCanAccessDesign(array $user): bool
{
    return myronUserCanAccessContext($user, 'design');
}

function myronUserCanAccessContent(array $user): bool
{
    return myronUserCanAccessContext($user, 'content');
}

function myronUserCanAccessAdministration(array $user): bool
{
    return myronUserCanAccessContext($user, 'administration');
}

function myronUserCanManageDesign(array $user): bool
{
    return myronUserHoldsScope($user, MyronApiScopes::DESIGN_WRITE);
}

function myronUserCanManageContent(array $user): bool
{
    return myronUserHoldsScope($user, MyronApiScopes::CONTENT_WRITE);
}

/**
 * @return list<string>
 */
function myronUserGrantedScopes(array $user): array
{
    if (class_exists('MyronAuthRepository')) {
        return MyronAuthRepository::normalizeGrantedScopes($user['granted_scopes'] ?? $user['granted_scopes_json'] ?? []);
    }

    $raw = $user['granted_scopes'] ?? $user['granted_scopes_json'] ?? [];
    if (is_string($raw)) {
        $decoded = json_decode($raw, true);
        $raw = is_array($decoded) ? $decoded : [];
    }
    if (!is_array($raw)) {
        return [];
    }
    return array_values(array_unique(array_map('strval', $raw)));
}

function myronUserHoldsScope(array $user, string $scope): bool
{
    return MyronApiScopes::covers(myronUserGrantedScopes($user), $scope);
}

function myronUserCanAccessContext(array $user, string $context): bool
{
    $scopes = myronUserGrantedScopes($user);
    return match ($context) {
        'design' => MyronApiScopes::covers($scopes, MyronApiScopes::DESIGN_READ)
            || MyronApiScopes::covers($scopes, MyronApiScopes::DESIGN_WRITE),
        'content' => MyronApiScopes::covers($scopes, MyronApiScopes::CONTENT_READ)
            || MyronApiScopes::covers($scopes, MyronApiScopes::CONTENT_WRITE),
        'administration' => MyronApiScopes::covers($scopes, MyronApiScopes::ADMINISTRATION_READ)
            || MyronApiScopes::covers($scopes, MyronApiScopes::ADMINISTRATION_WRITE)
            || MyronApiScopes::covers($scopes, MyronApiScopes::ADMINISTRATION_DESTRUCTIVE),
        default => false,
    };
}

function myronActionCallerContextForUser(array $user): MyronActionCallerContext
{
    return new MyronActionCallerContext(
        callerType: 'human-session',
        callerId: (string) ($user['id'] ?? ''),
        heldScopes: myronUserGrantedScopes($user)
    );
}

function myronRequireDesignAccess(bool $write = false): array
{
    $user = myronRequireAuthenticatedUser();
    if ($write ? myronUserCanManageDesign($user) : myronUserCanAccessDesign($user)) {
        return $user;
    }

    myronRenderForbidden('Your current access does not permit this Design surface.');
}

function myronRequireContentAccess(bool $write = false): array
{
    $user = myronRequireAuthenticatedUser();
    if ($write ? myronUserCanManageContent($user) : myronUserCanAccessContent($user)) {
        return $user;
    }

    myronRenderForbidden('Your current access does not permit this Content surface.');
}

function myronRequireAdministrationAccess(): array
{
    $user = myronRequireAuthenticatedUser();
    if (myronUserCanAccessAdministration($user)) {
        return $user;
    }

    myronRenderForbidden('Your current access does not permit this Administration surface.');
}

function myronRenderForbidden(string $message): never
{
    http_response_code(403);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="' . myronEscape(myronSiteLanguage()) . '"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>' . myronEscape(myronComposeDocumentTitle('Forbidden')) . '</title>' . myronRenderSiteFaviconLink() . '</head><body><h1>Forbidden</h1><p>' . myronEscape($message) . '</p></body></html>';
    exit;
}

/**
 * APO-180 Card 6 — pre-existing install seed application bootstrap hook.
 *
 * Called at the end of bootstrap. Idempotent: short-circuits via
 * MyronFooterContentSeedService::needsBackfill() (one cheap DB read on the
 * default footer row); after a successful backfill, subsequent calls return
 * fast. Only runs when there is a primary active site-type bundle (a fresh
 * install with no bundle activated produces a no-op).
 *
 * Operator-edit protection: the underlying backfill performs field-level
 * fallthrough — only currently-empty zones/fields get the seed; operator-set
 * fields are preserved.
 */
function myronApplyFooterContentBackfillIfNeeded(): int
{
    static $cachedResult = null;
    if ($cachedResult !== null) {
        return $cachedResult;
    }
    try {
        $seedService = myronFooterContentSeedService();
        $footerRepo  = myronFooterDesignRepository();
        $composition = myronFooterVariantCompositionService();
        if (!$seedService->needsBackfill($footerRepo, $composition)) {
            $cachedResult = 0;
            return 0;
        }
        $primaryBundleId = myronBundleActivationRepository()->getPrimaryBundleId();
        if ($primaryBundleId === null || trim($primaryBundleId) === '') {
            $cachedResult = 0;
            return 0;
        }
        $cachedResult = $seedService->backfillEmptyZonesForActiveSiteType(
            (string) $primaryBundleId,
            $footerRepo,
            $composition,
            ''
        );
        return $cachedResult;
    } catch (Throwable) {
        $cachedResult = 0;
        return 0;
    }
}

myronApplyFooterContentBackfillIfNeeded();

/**
 * APO-186 — AI-native API substrate service locators.
 *
 * Each locator returns a singleton bound to the request lifecycle. The
 * registry holds all registered MyronAction instances; the dispatcher uses
 * the registry + the authorization gate to route /api/v1/... requests.
 *
 * Action registration happens after the locators are defined (see the
 * registration block at the end of this file).
 */
function myronApiAuthorization(): MyronApiAuthorization
{
    static $instance = null;
    if ($instance instanceof MyronApiAuthorization) {
        return $instance;
    }
    $token  = (string) (getenv('MYRON_AI_DEV_BEARER_TOKEN') ?: '');
    $scopes = MyronApiScopes::parseList((string) (getenv('MYRON_AI_DEV_BEARER_SCOPES') ?: ''));
    if ($scopes === [] && $token !== '') {
        // If a token is set but no scope list, default to all six base scopes
        // so the dev token works out-of-the-box for local validation.
        $scopes = MyronApiScopes::ALL_BASE;
    }
    $isProduction = strtolower((string) (getenv('MYRON_RUNTIME_MODE') ?: 'development')) === 'production';
    $instance = new MyronApiAuthorization(
        $token,
        $scopes,
        myronAiIntegrationRepository(),
        $isProduction,
        array_merge([myronMcpConnectorAuthAdapter()], myronModuleRegistry()->authMethods())
    );
    return $instance;
}

function myronMcpOAuthMetadataService(): MyronMcpOAuthMetadataService
{
    static $instance = null;
    if ($instance instanceof MyronMcpOAuthMetadataService) {
        return $instance;
    }
    $instance = new MyronMcpOAuthMetadataService();
    return $instance;
}

function myronMcpProtectedResourceMetadataUrl(): string
{
    return myronMcpOAuthMetadataService()->protectedResourceMetadataUrl();
}

function myronMcpOAuthClientRepository(): MyronMcpOAuthClientRepository
{
    static $instance = null;
    if ($instance instanceof MyronMcpOAuthClientRepository) {
        return $instance;
    }
    $instance = new MyronMcpOAuthClientRepository(myronDatabase());
    return $instance;
}

function myronMcpOAuthTokenService(): MyronMcpOAuthTokenService
{
    static $instance = null;
    if ($instance instanceof MyronMcpOAuthTokenService) {
        return $instance;
    }
    $instance = new MyronMcpOAuthTokenService(
        myronMcpOAuthClientRepository(),
        myronAiIntegrationRepository(),
        myronMcpOAuthMetadataService()
    );
    return $instance;
}

function myronAiConnectionRevocationService(): MyronAiConnectionRevocationService
{
    static $instance = null;
    if ($instance instanceof MyronAiConnectionRevocationService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/administration/AiConnectionRevocationService.php';
    $instance = new MyronAiConnectionRevocationService(
        myronAiIntegrationRepository(),
        myronMcpOAuthClientRepository(),
    );
    return $instance;
}

function myronMcpConnectorAuthAdapter(): MyronMcpConnectorAuthAdapter
{
    static $instance = null;
    if ($instance instanceof MyronMcpConnectorAuthAdapter) {
        return $instance;
    }
    $instance = new MyronMcpConnectorAuthAdapter(myronMcpOAuthTokenService(), myronAiIntegrationRepository());
    return $instance;
}

function myronSendMcpOAuthNoStoreHeaders(): void
{
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
}

/**
 * APO-197 Card 1 — AI integration repository locator.
 */
function myronAiIntegrationRepository(): MyronAiIntegrationRepository
{
    static $instance = null;
    if ($instance instanceof MyronAiIntegrationRepository) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/identity/AiIntegration.php';
    $instance = new MyronAiIntegrationRepository(myronDatabase());
    return $instance;
}

/**
 * APO-197 Card 2 — Audit log repository locator.
 */
function myronAuditLogRepository(): MyronAuditLogRepository
{
    static $instance = null;
    if ($instance instanceof MyronAuditLogRepository) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/audit/AuditEvent.php';
    $instance = new MyronAuditLogRepository(myronDatabase(), new MyronAuditSanitiser());
    return $instance;
}

function myronActionRegistry(): MyronActionRegistry
{
    static $instance = null;
    if ($instance instanceof MyronActionRegistry) {
        return $instance;
    }
    $instance = new MyronActionRegistry();
    return $instance;
}

function myronExtensionScopeGrantRepository(): MyronExtensionScopeGrantRepository
{
    static $instance = null;
    if ($instance instanceof MyronExtensionScopeGrantRepository) {
        return $instance;
    }
    $instance = new MyronExtensionScopeGrantRepository(myronDatabase());
    return $instance;
}

function myronExtensionMigrationRunner(): MyronExtensionMigrationRunner
{
    static $instance = null;
    if ($instance instanceof MyronExtensionMigrationRunner) {
        return $instance;
    }
    $instance = new MyronExtensionMigrationRunner();
    return $instance;
}

function myronExtensionLoader(): MyronExtensionLoader
{
    static $instance = null;
    if ($instance instanceof MyronExtensionLoader) {
        return $instance;
    }
    $instance = new MyronExtensionLoader(
        myronAppRoot() . '/extensions',
        myronDatabase(),
        myronActionRegistry(),
        myronExtensionScopeGrantRepository(),
        myronExtensionMigrationRunner()
    );
    return $instance;
}

function myronMarketplaceExtensionPackageClient(): MyronMarketplaceExtensionPackageClient
{
    static $instance = null;
    if ($instance instanceof MyronMarketplaceExtensionPackageClient) {
        return $instance;
    }

    $instance = new MyronMarketplaceExtensionPackageClient();
    return $instance;
}

function myronMarketplaceExtensionInstallService(): MyronMarketplaceExtensionInstallService
{
    static $instance = null;
    if ($instance instanceof MyronMarketplaceExtensionInstallService) {
        return $instance;
    }

    $instance = new MyronMarketplaceExtensionInstallService(
        myronAppRoot(),
        myronMarketplaceExtensionPackageClient(),
        myronApplicationUpdateService()
    );
    return $instance;
}

function myronActionDispatcher(): MyronActionDispatcher
{
    static $instance = null;
    if ($instance instanceof MyronActionDispatcher) {
        return $instance;
    }
    $instance = new MyronActionDispatcher(
        myronActionRegistry(),
        myronApiAuthorization(),
        myronAuditLogRepository(),
        myronRateLimiter()
    );
    return $instance;
}

/**
 * APO-198 — MCP server adapter locator.
 */
function myronMcpServer(): MyronMcpServer
{
    static $instance = null;
    if ($instance instanceof MyronMcpServer) {
        return $instance;
    }
    require_once __DIR__ . '/mcp/Server.php';
    $instance = new MyronMcpServer(
        myronActionRegistry(),
        myronApiAuthorization(),
        myronActionDispatcher(),
        myronSystemSnapshotService(),
        myronCompatibilityDocumentService()
    );
    return $instance;
}

/**
 * APO-198 Card 6 — MCP CORS policy locator.
 */
function myronMcpCorsPolicy(): MyronMcpCorsPolicy
{
    static $instance = null;
    if ($instance instanceof MyronMcpCorsPolicy) {
        return $instance;
    }
    require_once __DIR__ . '/api/CorsPolicy.php';
    $allowed = [];
    if (function_exists('myronSiteSettingsGet')) {
        $settings = myronSiteSettingsGet();
        $list = $settings['mcp_cors_allowlist'] ?? '';
        if (is_string($list) && $list !== '') {
            $decoded = json_decode($list, true);
            if (is_array($decoded)) {
                $allowed = array_values(array_filter(array_map('strval', $decoded), static fn ($s) => $s !== ''));
            }
        }
    }
    $instance = new MyronMcpCorsPolicy($allowed);
    return $instance;
}

/**
 * APO-197 Card 8 — Rate limiter locator.
 */
function myronRateLimiter(): MyronRateLimiter
{
    static $instance = null;
    if ($instance instanceof MyronRateLimiter) {
        return $instance;
    }
    require_once __DIR__ . '/api/RateLimiter.php';
    $instance = new MyronRateLimiter(myronAuditLogRepository(), myronAiIntegrationRepository());
    return $instance;
}

function myronRegistryAudit(): MyronRegistryAudit
{
    static $instance = null;
    if ($instance instanceof MyronRegistryAudit) {
        return $instance;
    }
    $appRoot = dirname(__DIR__);
    $instance = new MyronRegistryAudit(
        adminRoutesDir:    $appRoot . '/admin/routes',
        registry:          myronActionRegistry(),
        backlogReportPath: $appRoot . '/tests/reports/ai-native-registry-backlog.json',
    );
    return $instance;
}

/**
 * APO-193 — System snapshot composer service locator.
 *
 * The composer invokes every registered MyronAction with snapshotInclude:true
 * and slots the result under the action's declared snapshotKey. Used by the
 * compatibility-document endpoints (APO-193 Card 3) and by the MCP
 * resources/read handler (APO-198) to compose the live install state document.
 */
function myronSystemSnapshotService(): MyronSystemSnapshotService
{
    static $instance = null;
    if ($instance instanceof MyronSystemSnapshotService) {
        return $instance;
    }
    require_once __DIR__ . '/api/SystemSnapshotService.php';
    $instance = new MyronSystemSnapshotService(myronActionRegistry());
    return $instance;
}

function myronUploadSessionService(): MyronUploadSessionService
{
    static $instance = null;
    if ($instance instanceof MyronUploadSessionService) {
        return $instance;
    }
    require_once __DIR__ . '/api/UploadSessionService.php';
    $instance = new MyronUploadSessionService(dirname(__DIR__) . '/tmp/uploads/sessions');
    return $instance;
}

/**
 * APO-186 — Action service locator + registration.
 *
 * MyronFooterDesignActionService extracts the business logic for footer
 * design actions so both the admin form path and the /api/v1 path call
 * the same code. Foundation only ships setDefault() as the worked example;
 * APO-187 Pass A continues the extraction for the rest of the verb set.
 */
function myronFooterDesignActionService(): MyronFooterDesignActionService
{
    static $instance = null;
    if ($instance instanceof MyronFooterDesignActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/registry/FooterDesignActionService.php';
    $instance = new MyronFooterDesignActionService(
        myronFooterDesignRepository(),
        myronDesignLibraryEntitlementPolicy(),
    );
    return $instance;
}

/**
 * APO-195 Card 1 — Pages action service locator.
 */
function myronPagesActionService(): MyronPagesActionService
{
    static $instance = null;
    if ($instance instanceof MyronPagesActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/content/pages/PagesActionService.php';
    $instance = new MyronPagesActionService(myronContentRepository(), myronPageRoleService());
    return $instance;
}

function myronPageRoleService(): MyronPageRoleService
{
    static $instance = null;
    if ($instance instanceof MyronPageRoleService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/content/pages/PageRoleService.php';
    $instance = new MyronPageRoleService(myronDatabase());
    return $instance;
}

/**
 * APO-196 — Pass C Administration + Identity service locators.
 */
function myronSiteSettingsActionService(): MyronSiteSettingsActionService
{
    static $instance = null;
    if ($instance instanceof MyronSiteSettingsActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/site/SiteSettingsActionService.php';
    $instance = new MyronSiteSettingsActionService(myronSiteSettingsRepository());
    return $instance;
}

function myronMailActionService(): MyronMailActionService
{
    static $instance = null;
    if ($instance instanceof MyronMailActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/identity/MailActionService.php';
    $instance = new MyronMailActionService(myronMailSettingsRepository(), myronMailTestService());
    return $instance;
}

function myronSiteSetupActionService(): MyronSiteSetupActionService
{
    static $instance = null;
    if ($instance instanceof MyronSiteSetupActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/administration/SiteSetupActionService.php';
    $instance = new MyronSiteSetupActionService(myronOnboardingStateRepository());
    return $instance;
}

function myronSiteSnapshotImportAuditRepository(): MyronSiteSnapshotImportAuditRepository
{
    static $instance = null;
    if ($instance instanceof MyronSiteSnapshotImportAuditRepository) {
        return $instance;
    }
    $instance = new MyronSiteSnapshotImportAuditRepository(myronDatabase());
    return $instance;
}

function myronSiteSnapshotExportService(): MyronSiteSnapshotExportService
{
    static $instance = null;
    if ($instance instanceof MyronSiteSnapshotExportService) {
        return $instance;
    }
    $instance = new MyronSiteSnapshotExportService(myronDatabase());
    return $instance;
}

function myronSiteSnapshotImportService(): MyronSiteSnapshotImportService
{
    static $instance = null;
    if ($instance instanceof MyronSiteSnapshotImportService) {
        return $instance;
    }
    $instance = new MyronSiteSnapshotImportService(myronDatabase(), myronSiteSnapshotImportAuditRepository());
    return $instance;
}

function myronIdentityActionService(): MyronIdentityActionService
{
    static $instance = null;
    if ($instance instanceof MyronIdentityActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/identity/IdentityActionService.php';
    $instance = new MyronIdentityActionService(myronAuthRepository());
    return $instance;
}

/**
 * APO-195 Card 4 — Menu action service locator.
 */
function myronMenuActionService(): MyronMenuActionService
{
    static $instance = null;
    if ($instance instanceof MyronMenuActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/content/MenuActionService.php';
    $instance = new MyronMenuActionService(myronContentRepository());
    return $instance;
}

/**
 * APO-195 Card 3 — Category action service locator.
 */
function myronCategoryActionService(): MyronCategoryActionService
{
    static $instance = null;
    if ($instance instanceof MyronCategoryActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/content/CategoryActionService.php';
    $instance = new MyronCategoryActionService(myronContentRepository());
    return $instance;
}

/**
 * APO-195 Card 2 — Section Edit action service locator.
 */
function myronSectionEditActionService(): MyronSectionEditActionService
{
    static $instance = null;
    if ($instance instanceof MyronSectionEditActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/content/SectionEditActionService.php';
    $instance = new MyronSectionEditActionService(
        myronContentRepository(),
        myronTemplateDefinitionRepository(),
        myronSectionRegistryRepository(),
        myronSectionVariantRepository(),
        myronComponentRegistryRepository(),
        myronSectionContentSchemaService(),
    );
    return $instance;
}

/**
 * APO-194 Card 6 — Definitions (Design Systems) action service locator.
 * Wraps the JSONM DesignSystemRegistry. All actions registered with this
 * service are exposeToMcp:false — install-level system management.
 */
function myronDefinitionsActionService(): MyronDefinitionsActionService
{
    static $instance = null;
    if ($instance instanceof MyronDefinitionsActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/DefinitionsActionService.php';
    // DesignSystemRegistry is loaded by the app-local JSONM runtime autoloader.
    $registry = new \DesignSystemRegistry();
    if (method_exists($registry, 'ensureStorage')) {
        $registry->ensureStorage();
    }
    // APO-205-011 Fix B — inject the onboarding state repo so the service
    // writes back onboarding_state.applied_design_system_id after a successful
    // registry apply. This is the canonical reciprocal-telemetry hook.
    $instance = new MyronDefinitionsActionService($registry, myronOnboardingStateRepository());
    return $instance;
}

/**
 * APO-194 Card 5 — Template Chrome action service locator.
 */
function myronTemplateChromeActionService(): MyronTemplateChromeActionService
{
    static $instance = null;
    if ($instance instanceof MyronTemplateChromeActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/registry/TemplateChromeActionService.php';
    $instance = new MyronTemplateChromeActionService(myronTemplateChromeAssignmentRepository());
    return $instance;
}

function myronRailDesignActionService(): MyronRailDesignActionService
{
    static $instance = null;
    if ($instance instanceof MyronRailDesignActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/registry/RailDesignActionService.php';
    $instance = new MyronRailDesignActionService(myronRailDesignRepository());
    return $instance;
}

/**
 * APO-194 Card 4 — Files action service locator (with JSON-content envelope).
 */
function myronFilesActionService(): MyronFilesActionService
{
    static $instance = null;
    if ($instance instanceof MyronFilesActionService) {
        return $instance;
    }
    require_once __DIR__ . '/api/JsonContentEnvelope.php';
    require_once dirname(__DIR__) . '/modules/files/FilesActionService.php';
    $instance = new MyronFilesActionService(
        myronFileRepository(),
        myronAiIntegrationRepository(),
        myronAuthRepository()
    );
    return $instance;
}

/**
 * APO-194 Card 4 — Video Asset action service locator (reuses Files service).
 */
function myronVideoAssetActionService(): MyronVideoAssetActionService
{
    static $instance = null;
    if ($instance instanceof MyronVideoAssetActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/files/VideoAssetActionService.php';
    $instance = new MyronVideoAssetActionService(myronVideoAssetRepository(), myronFilesActionService());
    return $instance;
}

function myronMediaAccessibilityActionService(): MyronMediaAccessibilityActionService
{
    static $instance = null;
    if ($instance instanceof MyronMediaAccessibilityActionService) {
        return $instance;
    }
    $instance = new MyronMediaAccessibilityActionService(
        myronFileRepository(),
        myronVideoAssetRepository(),
        myronFilesActionService(),
        myronMediaAccessibilityAttachmentRepository(),
    );
    return $instance;
}

/**
 * APO-194 Card 3 — Document Template action service locator.
 */
function myronDocumentTemplateActionService(): MyronDocumentTemplateActionService
{
    static $instance = null;
    if ($instance instanceof MyronDocumentTemplateActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/files/DocumentTemplateActionService.php';
    $instance = new MyronDocumentTemplateActionService(myronDocumentTemplateRepository());
    return $instance;
}

/**
 * APO-194 Card 2 — Template Duplication action service locator.
 *
 * The schema resolver is bound to a substrate-equivalent of the admin
 * route's local closure: given a template definition (from the
 * MyronTemplateDefinitionRepository), produce the runtime schema map by
 * delegating to the TemplateInstantiationService.
 */
function myronTemplateDuplicationActionService(): MyronTemplateDuplicationActionService
{
    static $instance = null;
    if ($instance instanceof MyronTemplateDuplicationActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/registry/TemplateDuplicationActionService.php';
    $schemaResolver = static function (array $definition): array {
        $runtime = myronTemplateInstantiationService()->instantiateTemplate($definition);
        $schema  = is_array($runtime['template_schema'] ?? null) ? $runtime['template_schema'] : [];
        if ($schema === []) {
            $schema = $definition;
        }
        return $schema;
    };
    $instance = new MyronTemplateDuplicationActionService(myronDatabase(), $schemaResolver);
    return $instance;
}

/**
 * APO-194 Card 1 — Navigation Version action service locator.
 */
function myronNavigationVersionActionService(): MyronNavigationVersionActionService
{
    static $instance = null;
    if ($instance instanceof MyronNavigationVersionActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/registry/NavigationVersionActionService.php';
    $instance = new MyronNavigationVersionActionService(myronNavigationDesignRepository());
    return $instance;
}

/**
 * APO-193 Card 8 — Section Defaults action service locator.
 */
function myronSectionDefaultsActionService(): MyronSectionDefaultsActionService
{
    static $instance = null;
    if ($instance instanceof MyronSectionDefaultsActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/SectionDefaultsActionService.php';
    $instance = new MyronSectionDefaultsActionService(
        myronSectionComponentDefaultsRepository(),
        myronSectionContentDefaultsRepository(),
        myronSectionRegistryRepository(),
    );
    return $instance;
}

/**
 * APO-193 Card 8 — Layout action service locator.
 */
function myronLayoutActionService(): MyronLayoutActionService
{
    static $instance = null;
    if ($instance instanceof MyronLayoutActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/LayoutActionService.php';
    // DesignSystemRegistry is loaded by the app-local JSONM runtime autoloader.
    $registry = new \DesignSystemRegistry();
    if (method_exists($registry, 'ensureStorage')) {
        $registry->ensureStorage();
    }
    $instance = new MyronLayoutActionService($registry);
    return $instance;
}

/**
 * APO-193 Card 7 — Section Variant action service locator.
 */
function myronSectionVariantActionService(): MyronSectionVariantActionService
{
    static $instance = null;
    if ($instance instanceof MyronSectionVariantActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/SectionVariantActionService.php';
    $instance = new MyronSectionVariantActionService(myronSectionVariantRepository());
    return $instance;
}

/**
 * APO-193 Card 6 — Custom CSS action service locator.
 */
function myronCustomCssActionService(): MyronCustomCssActionService
{
    static $instance = null;
    if ($instance instanceof MyronCustomCssActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/CustomCssActionService.php';
    $instance = new MyronCustomCssActionService(
        myronCustomCssRepository(),
        myronAiIntegrationRepository(),
        myronAuthRepository()
    );
    return $instance;
}

/**
 * APO-193 Card 5 — Token Patch action service locator.
 */
function myronTokenPatchActionService(): MyronTokenPatchActionService
{
    static $instance = null;
    if ($instance instanceof MyronTokenPatchActionService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/design/TokenPatchActionService.php';
    $instance = new MyronTokenPatchActionService(myronTokenPatchRepository());
    return $instance;
}

/**
 * APO-193 — Compatibility document composer service locator.
 */
function myronCompatibilityDocumentService(): MyronCompatibilityDocumentService
{
    static $instance = null;
    if ($instance instanceof MyronCompatibilityDocumentService) {
        return $instance;
    }
    require_once dirname(__DIR__) . '/modules/system/CompatibilityDocumentService.php';
    $instance = new MyronCompatibilityDocumentService(
        myronSystemSnapshotService(),
        myronSiteTypeRegistryRepository(),
        myronFooterDesignRepository(),
        myronBundleActivationRepository(),
    );
    return $instance;
}

/**
 * APO-186 — Register all MyronAction implementations with the registry.
 *
 * Adding a new action: require the file here, then ->register() it. The
 * registry audit (Card 7) cross-references the registered actions against
 * the static-analysis grep of admin POST handlers; un-registered actions
 * appear in app/tests/reports/ai-native-registry-backlog.json.
 */
(static function (): void {
    $registry = myronActionRegistry();
    $apiDir = dirname(__DIR__) . '/api/actions';

    // System
    require_once $apiDir . '/system/GetManifestAction.php';
    require_once $apiDir . '/system/GetCompatibilityDocumentDefaultAction.php';
    require_once $apiDir . '/system/GetAuditLogAction.php';
    require_once $apiDir . '/administration/GetCompatibilityDocumentConfiguredAction.php';

    // Design — APO-186 Foundation
    require_once $apiDir . '/design/SetFooterDefaultAction.php';
    require_once $apiDir . '/design/ActivateCreativeLibraryNavStyleAction.php';
    require_once $apiDir . '/design/ClearCreativeLibraryNavStyleAction.php';
    require_once $apiDir . '/design/ActivateCreativeLibraryButtonStyleAction.php';
    require_once $apiDir . '/design/ClearCreativeLibraryButtonStyleAction.php';

    // Design — APO-193 Pass A1 (Footer mutations)
    require_once $apiDir . '/design/ActivateFooterAction.php';
    require_once $apiDir . '/design/DeactivateFooterAction.php';
    require_once $apiDir . '/design/ApplyFooterRecommendationAction.php';
    require_once $apiDir . '/design/DismissFooterRecommendationAction.php';
    require_once $apiDir . '/design/ApplyFooterZoneDefaultsAction.php';
    require_once $apiDir . '/design/UpdateFooterConfigurationAction.php';

    // Design — APO-193 Pass A1 (Token Patches)
    require_once $apiDir . '/design/SaveTokenPatchAction.php';
    require_once $apiDir . '/design/ClearTokenPatchAction.php';
    require_once $apiDir . '/design/ClearAllTokenPatchesAction.php';
    require_once $apiDir . '/design/ClearOrphanTokenPatchesAction.php';

    // Design — APO-193 Pass A1 (Custom CSS)
    require_once $apiDir . '/design/SaveSiteCustomCssAction.php';
    require_once $apiDir . '/design/GetCustomInteractionsAction.php';
    require_once $apiDir . '/design/SaveCustomInteractionsAction.php';
    require_once $apiDir . '/design/UploadCustomInteractionLibraryAction.php';
    require_once $apiDir . '/design/DeleteCustomInteractionLibraryAction.php';
    require_once $apiDir . '/design/SaveCustomInteractionFontsAction.php';
    require_once $apiDir . '/design/UploadCustomInteractionFontAction.php';
    require_once $apiDir . '/design/DeleteCustomInteractionFontAction.php';

    // Design — APO-193 Pass A1 (Section Variants)
    require_once $apiDir . '/design/CreateSectionVariantAction.php';
    require_once $apiDir . '/design/UpdateSectionVariantAction.php';
    require_once $apiDir . '/design/DeleteSectionVariantAction.php';

    // Design — APO-193 Pass A1 (Section Defaults + Layout)
    require_once $apiDir . '/design/UpdateSectionDefaultsAction.php';
    require_once $apiDir . '/design/UpdateLayoutAction.php';

    // Design — APO-337 Core Blog rails
    require_once $apiDir . '/design/SetRailDefaultAction.php';
    require_once $apiDir . '/design/UpdateRailDefaultsAction.php';
    require_once $apiDir . '/design/UpdateTemplateRailAssignmentAction.php';

    // Design — APO-231 (Custom Section Templates)
    require_once $apiDir . '/design/CreateCustomSectionTemplateAction.php';
    require_once $apiDir . '/design/GetCustomSectionTemplateAction.php';
    require_once $apiDir . '/design/UpdateCustomSectionTemplateAction.php';
    require_once $apiDir . '/design/DeleteCustomSectionTemplateAction.php';

    // Design — APO-194 Pass A2 (Navigation Versions — 7 actions)
    require_once $apiDir . '/design/CreateNavigationVersionAction.php';
    require_once $apiDir . '/design/UpdateNavigationVersionAction.php';
    require_once $apiDir . '/design/ActivateNavigationVersionAction.php';
    require_once $apiDir . '/design/DeactivateNavigationVersionAction.php';
    require_once $apiDir . '/design/SetNavigationDefaultAction.php';
    require_once $apiDir . '/design/DuplicateNavigationVersionAction.php';
    require_once $apiDir . '/design/DeleteNavigationVersionAction.php';

    // Design — APO-194 Pass A2 (Site Type Studio mutations)
    require_once $apiDir . '/design/DuplicateTemplateAction.php';
    require_once $apiDir . '/design/CreateCustomSiteTemplateAction.php';
    require_once $apiDir . '/design/RegisterCustomSiteTemplateAsPageTemplateAction.php';
    require_once $apiDir . '/design/DeleteCustomSiteTemplateAction.php';

    // Design — APO-194 Pass A2 (Document Templates)
    require_once $apiDir . '/design/CreateDocumentTemplateAction.php';
    require_once $apiDir . '/design/UpdateDocumentTemplateAction.php';
    require_once $apiDir . '/design/DeactivateDocumentTemplateAction.php';

    // Files — APO-194 Pass A2 (JSON-content envelope substrate)
    require_once $apiDir . '/files/UploadFileAction.php';
    require_once $apiDir . '/files/UploadMultipartFileAction.php';
    require_once $apiDir . '/files/CreateFileUploadSessionAction.php';
    require_once $apiDir . '/files/AppendFileUploadChunkAction.php';
    require_once $apiDir . '/files/CommitFileUploadSessionAction.php';
    require_once $apiDir . '/files/AbortFileUploadSessionAction.php';
    require_once $apiDir . '/files/UpdateFileAction.php';
    require_once $apiDir . '/files/ReplaceFileContentAction.php';
    require_once $apiDir . '/files/DeleteFileAction.php';
    require_once $apiDir . '/files/CreateVideoAssetAction.php';
    require_once $apiDir . '/files/UpdateVideoAssetAction.php';
    require_once $apiDir . '/files/AddVideoRenditionAction.php';
    require_once $apiDir . '/files/DeleteVideoAssetAction.php';
    require_once $apiDir . '/files/UploadVideoCaptionsAction.php';
    require_once $apiDir . '/files/DeleteVideoCaptionsAction.php';
    require_once $apiDir . '/files/UploadAudioTranscriptAction.php';
    require_once $apiDir . '/files/DeleteAudioTranscriptAction.php';

    // Design — APO-194 Pass A2 (Template Chrome Assignments)
    require_once $apiDir . '/design/AssignTemplateChromeAction.php';
    require_once $apiDir . '/design/ResetTemplateChromeAction.php';

    // Design — APO-194 Pass A2 (Definitions ingestion — all exposeToMcp:false)
    require_once $apiDir . '/design/SaveCurrentDefinitionAction.php';
    require_once $apiDir . '/design/ApplyStoredDefinitionAction.php';
    require_once $apiDir . '/design/ApplyDefinitionAction.php';
    require_once $apiDir . '/design/ResetBaselineDefinitionAction.php';
    require_once $apiDir . '/design/RemoveStoredDefinitionAction.php';
    require_once $apiDir . '/design/RemoveSystemArchetypeAction.php';
    require_once $apiDir . '/design/ImportDefinitionAction.php';

    // Content — APO-195 Pass B (Pages)
    require_once $apiDir . '/content/CreatePageAction.php';
    require_once $apiDir . '/content/UpdatePageAction.php';
    require_once $apiDir . '/content/SavePageSeoAction.php';
    require_once $apiDir . '/content/DownloadPageMarkupAction.php';
    require_once $apiDir . '/content/DownloadPageMarkdownAction.php';
    require_once $apiDir . '/content/ValidateOgImageAction.php';
    require_once $apiDir . '/content/PublishPageAction.php';
    require_once $apiDir . '/content/UnpublishPageAction.php';
    require_once $apiDir . '/content/DeletePageAction.php';
    require_once $apiDir . '/content/UpdatePageSectionContentAction.php';
    require_once $apiDir . '/content/SetPageBodyMarkdownAction.php';
    require_once $apiDir . '/content/SetPageCategoriesAction.php';
    require_once $apiDir . '/content/GetPageCategoriesAction.php';
    require_once $apiDir . '/content/SetPageAuthorAction.php';
    require_once $apiDir . '/content/GetPageAuthorAction.php';
    require_once $apiDir . '/content/SetPageNavVisibilityAction.php';
    require_once $apiDir . '/content/AssignPageRoleAction.php';
    require_once $apiDir . '/content/ClearPageRoleAction.php';

    // Content — APO-195 Pass B (Section edits on template drafts)
    require_once $apiDir . '/content/CreateRuntimeDraftAction.php';
    require_once $apiDir . '/content/InsertSectionAction.php';
    require_once $apiDir . '/content/MoveSectionAction.php';
    require_once $apiDir . '/content/DuplicateTemplateSectionAction.php';
    require_once $apiDir . '/content/RemoveTemplateSectionAction.php';
    require_once $apiDir . '/content/ReorderTemplateSectionsAction.php';
    require_once $apiDir . '/content/UpdateSectionEditabilityAction.php';
    require_once $apiDir . '/content/UpdateSectionDesignAction.php';
    require_once $apiDir . '/content/UpdateTemplateSectionContentAction.php';
    require_once $apiDir . '/content/SaveSectionAsVariantAction.php';
    require_once $apiDir . '/content/ApplySectionVariantToTemplateAction.php';

    // Content — APO-195 Pass B (Categories)
    require_once $apiDir . '/content/CreateCategoryAction.php';
    require_once $apiDir . '/content/UpdateCategoryAction.php';
    require_once $apiDir . '/content/ArchiveCategoryAction.php';
    require_once $apiDir . '/content/ReactivateCategoryAction.php';

    // Content — APO-195 Pass B (Menus)
    require_once $apiDir . '/content/CreateMenuAction.php';
    require_once $apiDir . '/content/SaveMenuPlacementsAction.php';
    require_once $apiDir . '/content/AddPageToMenuAction.php';
    require_once $apiDir . '/content/RemoveMenuItemAction.php';
    require_once $apiDir . '/content/MoveMenuItemAction.php';

    // Administration — APO-196 Pass C (Site Settings, Mail, Site Setup, Updates, Identity)
    require_once $apiDir . '/administration/SaveSiteSettingsAction.php';
    require_once $apiDir . '/administration/SaveSeoSettingsAction.php';
    require_once $apiDir . '/administration/SaveMailSettingsAction.php';
    require_once $apiDir . '/administration/SendTestMailAction.php';
    require_once $apiDir . '/administration/SaveSiteSetupAction.php';
    require_once $apiDir . '/administration/ResetSiteBaselineAction.php';
    require_once $apiDir . '/administration/ApplyApplicationUpdateAction.php';
    require_once $apiDir . '/administration/ApplyRemoteApplicationUpdateAction.php';
    require_once $apiDir . '/administration/CheckRemoteApplicationUpdateAction.php';
    require_once $apiDir . '/administration/SaveRemoteUpdateManifestUrlAction.php';
    require_once $apiDir . '/administration/DismissRemoteApplicationUpdateAction.php';
    require_once $apiDir . '/administration/UpdateProfileAction.php';
    require_once $apiDir . '/administration/UpdatePasswordAction.php';
    require_once $apiDir . '/administration/UpdateUserScopesAction.php';
    require_once $apiDir . '/administration/UpdateUserRoleAction.php';
    require_once $apiDir . '/administration/SaveRegistrationSettingsAction.php';
    // Administration reads
    require_once $apiDir . '/administration/GetSiteSettingsAction.php';
    require_once $apiDir . '/administration/GetMailConfigAction.php';
    require_once $apiDir . '/administration/ListMailTransportsAction.php';
    require_once $apiDir . '/administration/GetSiteSetupStateAction.php';
    require_once $apiDir . '/administration/ListUsersAction.php';
    require_once $apiDir . '/administration/ReadUserAction.php';
    require_once $apiDir . '/administration/ListRolesAction.php';
    require_once $apiDir . '/administration/GetRegistrationSettingsAction.php';
    require_once $apiDir . '/administration/GetUpdateStatusAction.php';
    require_once $apiDir . '/administration/GetMigrationStatusAction.php';
    require_once $apiDir . '/administration/ApplyPendingMigrationsAction.php';
    require_once $apiDir . '/administration/ExportSiteSnapshotAction.php';
    require_once $apiDir . '/administration/ImportSiteSnapshotAction.php';
    require_once $apiDir . '/administration/GetVerificationSettingsAction.php';
    require_once $apiDir . '/administration/UpdateVerificationSettingsAction.php';
    require_once $apiDir . '/administration/RefreshLicenseAction.php';
    require_once $apiDir . '/administration/RemoveLicenseAction.php';
    require_once $apiDir . '/administration/ListModuleLicensesAction.php';
    require_once $apiDir . '/administration/RedeemModuleLicenseAction.php';
    require_once $apiDir . '/administration/GetModuleEntitlementAction.php';
    require_once $apiDir . '/administration/RefreshModuleEntitlementsAction.php';

    // Analytics — APO-225 native privacy-first site analytics
    require_once $apiDir . '/analytics/GetAnalyticsSummaryAction.php';
    require_once $apiDir . '/analytics/GetTopPagesAction.php';
    require_once $apiDir . '/analytics/GetTrafficSourcesAction.php';

    // Administration — APO-197 AI Connection management (all exposeToMcp:false)
    require_once $apiDir . '/administration/CreateAiConnectionAction.php';
    require_once $apiDir . '/administration/UpdateAiConnectionAction.php';
    require_once $apiDir . '/administration/RevokeAiConnectionAction.php';
    require_once $apiDir . '/administration/RotateAiConnectionAction.php';

    // Content — APO-195 Pass B (Reads)
    require_once $apiDir . '/content/ListPagesAction.php';
    require_once $apiDir . '/content/GetPageAction.php';
    require_once $apiDir . '/content/GetPageContractAction.php';
    require_once $apiDir . '/content/ListPagesForManagerAction.php';
    require_once $apiDir . '/content/ListCategoriesAction.php';
    require_once $apiDir . '/content/ListPageCategoriesWithUsageAction.php';
    require_once $apiDir . '/content/ListMenusAction.php';
    require_once $apiDir . '/content/ListMenuPlacementsAction.php';
    require_once $apiDir . '/content/SaveCommentSettingsAction.php';
    // Content — APO-269 Site Search Foundation
    require_once $apiDir . '/search/SearchContentAction.php';
    require_once $apiDir . '/search/RebuildSearchIndexAction.php';

    // Pass A2 Reads (13 endpoints)
    require_once $apiDir . '/design/ListNavigationVersionsAction.php';
    require_once $apiDir . '/design/GetNavigationVersionAction.php';
    require_once $apiDir . '/design/GetNavigationDefaultAction.php';
    require_once $apiDir . '/design/ListTemplatesAction.php';
    require_once $apiDir . '/design/GetTemplateAction.php';
    require_once $apiDir . '/design/ListDocumentTemplatesAction.php';
    require_once $apiDir . '/design/GetDocumentTemplateAction.php';
    require_once $apiDir . '/design/GetTemplateChromeAction.php';
    require_once $apiDir . '/design/ListDefinitionsAction.php';
    require_once $apiDir . '/design/ExportCurrentDefinitionAction.php';
    require_once $apiDir . '/files/ListFilesAction.php';
    require_once $apiDir . '/files/GetFileAction.php';
    require_once $apiDir . '/files/ListVideoAssetsAction.php';
    require_once $apiDir . '/files/GetVideoAssetAction.php';

    // Design — APO-193 Pass A1 (Reads — 12 GET endpoints)
    require_once $apiDir . '/design/ListFootersAction.php';
    require_once $apiDir . '/design/GetFooterAction.php';
    require_once $apiDir . '/design/GetFooterDefaultAction.php';
    require_once $apiDir . '/design/ListTokenPatchesAction.php';
    require_once $apiDir . '/design/GetSiteCustomCssAction.php';
    require_once $apiDir . '/design/GetSiteCustomCssChunkAction.php';
    require_once $apiDir . '/design/CreateSiteCustomCssUploadSessionAction.php';
    require_once $apiDir . '/design/AppendSiteCustomCssUploadChunkAction.php';
    require_once $apiDir . '/design/CommitSiteCustomCssUploadSessionAction.php';
    require_once $apiDir . '/design/GetCustomJsChunkAction.php';
    require_once $apiDir . '/design/CreateCustomJsUploadSessionAction.php';
    require_once $apiDir . '/design/AppendCustomJsUploadChunkAction.php';
    require_once $apiDir . '/design/CommitCustomJsUploadSessionAction.php';
    require_once $apiDir . '/design/ListSectionVariantsAction.php';
    require_once $apiDir . '/design/GetSectionVariantAction.php';
    require_once $apiDir . '/design/GetLayoutSettingsAction.php';
    require_once $apiDir . '/design/ListSectionDefaultsAction.php';
    require_once $apiDir . '/design/ListComponentsAction.php';
    require_once $apiDir . '/design/GetComponentAction.php';
    require_once $apiDir . '/design/ListSectionsAction.php';

    // Shared dependency for the layout read action — same DesignSystemRegistry
    // instance the layout-mutation service uses. App-local JSONM runtime loaded.
    $sharedLayoutRegistry = new \DesignSystemRegistry();
    if (method_exists($sharedLayoutRegistry, 'ensureStorage')) {
        $sharedLayoutRegistry->ensureStorage();
    }

    $footerService             = myronFooterDesignActionService();
    $tokenPatchService         = myronTokenPatchActionService();
    $customCssService          = myronCustomCssActionService();
    $variantService            = myronSectionVariantActionService();
    $sectionDefaultsService    = myronSectionDefaultsActionService();
    $customSectionService      = myronCustomSectionTemplateActionService();
    $layoutService             = myronLayoutActionService();
    $railService               = myronRailDesignActionService();
    $navVersionService         = myronNavigationVersionActionService();
    $templateDupService        = myronTemplateDuplicationActionService();
    $docTemplateService        = myronDocumentTemplateActionService();
    $filesActionService        = myronFilesActionService();
    $videoActionService        = myronVideoAssetActionService();
    $mediaAccessibilityService = myronMediaAccessibilityActionService();
    $chromeService             = myronTemplateChromeActionService();
    $definitionsService        = myronDefinitionsActionService();
    $uploadSessionService      = myronUploadSessionService();
    $footerRepo                = myronFooterDesignRepository();
    $tokenPatchRepo            = myronTokenPatchRepository();
    $customCssRepo             = myronCustomCssRepository();
    $variantRepo               = myronSectionVariantRepository();
    $componentRepo             = myronComponentRegistryRepository();
    $sectionRegistryRepo       = myronSectionRegistryRepository();
    $componentDefaultsRepo     = myronSectionComponentDefaultsRepository();
    $contentDefaultsRepo       = myronSectionContentDefaultsRepository();

    $registry->register(new MyronGetManifestAction($registry));
    $registry->register(new MyronGetCompatibilityDocumentDefaultAction(myronCompatibilityDocumentService()));
    $registry->register(new MyronGetCompatibilityDocumentConfiguredAction(myronCompatibilityDocumentService()));
    $registry->register(new MyronGetAuditLogAction(myronAuditLogRepository()));
    $registry->register(new MyronSetFooterDefaultAction($footerService));
    $registry->register(new MyronActivateCreativeLibraryNavStyleAction(myronSiteSettingsRepository(), myronCreativeLibraryCatalog()));
    $registry->register(new MyronClearCreativeLibraryNavStyleAction(myronSiteSettingsRepository()));
    $registry->register(new MyronActivateCreativeLibraryButtonStyleAction(myronSiteSettingsRepository(), myronCreativeLibraryCatalog()));
    $registry->register(new MyronClearCreativeLibraryButtonStyleAction(myronSiteSettingsRepository()));
    $registry->register(new MyronActivateFooterAction($footerService));
    $registry->register(new MyronDeactivateFooterAction($footerService));
    $registry->register(new MyronApplyFooterRecommendationAction($footerService));
    $registry->register(new MyronDismissFooterRecommendationAction($footerService));
    $registry->register(new MyronApplyFooterZoneDefaultsAction($footerService));
    $registry->register(new MyronUpdateFooterConfigurationAction($footerService));
    $registry->register(new MyronSaveTokenPatchAction($tokenPatchService));
    $registry->register(new MyronClearTokenPatchAction($tokenPatchService));
    $registry->register(new MyronClearAllTokenPatchesAction($tokenPatchService));
    $registry->register(new MyronClearOrphanTokenPatchesAction($tokenPatchService));
    $registry->register(new MyronSaveSiteCustomCssAction($customCssService));
    $registry->register(new MyronSaveCustomInteractionsAction($customCssService));
    $registry->register(new MyronCreateSiteCustomCssUploadSessionAction($uploadSessionService));
    $registry->register(new MyronAppendSiteCustomCssUploadChunkAction($uploadSessionService));
    $registry->register(new MyronCommitSiteCustomCssUploadSessionAction($uploadSessionService, $customCssService));
    $registry->register(new MyronCreateCustomJsUploadSessionAction($uploadSessionService));
    $registry->register(new MyronAppendCustomJsUploadChunkAction($uploadSessionService));
    $registry->register(new MyronCommitCustomJsUploadSessionAction($uploadSessionService, $customCssService, $customCssRepo));
    $registry->register(new MyronUploadCustomInteractionLibraryAction($customCssService));
    $registry->register(new MyronDeleteCustomInteractionLibraryAction($customCssService));
    $registry->register(new MyronSaveCustomInteractionFontsAction($customCssService));
    $registry->register(new MyronUploadCustomInteractionFontAction($customCssService));
    $registry->register(new MyronDeleteCustomInteractionFontAction($customCssService));
    $registry->register(new MyronCreateSectionVariantAction($variantService));
    $registry->register(new MyronUpdateSectionVariantAction($variantService));
    $registry->register(new MyronDeleteSectionVariantAction($variantService));
    $registry->register(new MyronUpdateSectionDefaultsAction($sectionDefaultsService));
    $registry->register(new MyronCreateCustomSectionTemplateAction($customSectionService));
    $registry->register(new MyronGetCustomSectionTemplateAction($customSectionService));
    $registry->register(new MyronUpdateCustomSectionTemplateAction($customSectionService));
    $registry->register(new MyronDeleteCustomSectionTemplateAction($customSectionService));
    $registry->register(new MyronUpdateLayoutAction($layoutService));
    $registry->register(new MyronSetRailDefaultAction($railService));
    $registry->register(new MyronUpdateRailDefaultsAction($railService));
    $registry->register(new MyronUpdateTemplateRailAssignmentAction($railService));

    // Reads
    $registry->register(new MyronListFootersAction($footerRepo));
    $registry->register(new MyronGetFooterAction($footerRepo));
    $registry->register(new MyronGetFooterDefaultAction($footerRepo));
    $registry->register(new MyronListTokenPatchesAction($tokenPatchRepo));
    $registry->register(new MyronGetSiteCustomCssAction($customCssRepo));
    $registry->register(new MyronGetSiteCustomCssChunkAction($customCssRepo));
    $registry->register(new MyronGetCustomInteractionsAction($customCssRepo));
    $registry->register(new MyronGetCustomJsChunkAction($customCssRepo));
    $registry->register(new MyronListSectionVariantsAction($variantRepo));
    $registry->register(new MyronGetSectionVariantAction($variantRepo));
    $registry->register(new MyronGetLayoutSettingsAction($sharedLayoutRegistry));
    $registry->register(new MyronListSectionDefaultsAction($componentDefaultsRepo, $contentDefaultsRepo));
    $registry->register(new MyronListComponentsAction($componentRepo));
    $registry->register(new MyronGetComponentAction($componentRepo));
    $registry->register(new MyronListSectionsAction($sectionRegistryRepo));

    // Pass A2 — Navigation Version mutations
    $registry->register(new MyronCreateNavigationVersionAction($navVersionService));
    $registry->register(new MyronUpdateNavigationVersionAction($navVersionService));
    $registry->register(new MyronActivateNavigationVersionAction($navVersionService));
    $registry->register(new MyronDeactivateNavigationVersionAction($navVersionService));
    $registry->register(new MyronSetNavigationDefaultAction($navVersionService));
    $registry->register(new MyronDuplicateNavigationVersionAction($navVersionService));
    $registry->register(new MyronDeleteNavigationVersionAction($navVersionService));
    $registry->register(new MyronDuplicateTemplateAction($templateDupService, myronTemplateDefinitionRepository()));
    $registry->register(new MyronCreateCustomSiteTemplateAction($templateDupService));
    $registry->register(new MyronRegisterCustomSiteTemplateAsPageTemplateAction($templateDupService));
    $registry->register(new MyronDeleteCustomSiteTemplateAction($templateDupService));
    $registry->register(new MyronCreateDocumentTemplateAction($docTemplateService));
    $registry->register(new MyronUpdateDocumentTemplateAction($docTemplateService));
    $registry->register(new MyronDeactivateDocumentTemplateAction($docTemplateService));
    // Files (APO-194 Card 4)
    $registry->register(new MyronUploadFileAction($filesActionService));
    $registry->register(new MyronUploadMultipartFileAction($filesActionService));
    $registry->register(new MyronCreateFileUploadSessionAction($uploadSessionService));
    $registry->register(new MyronAppendFileUploadChunkAction($uploadSessionService));
    $registry->register(new MyronCommitFileUploadSessionAction($uploadSessionService, $filesActionService));
    $registry->register(new MyronAbortFileUploadSessionAction($uploadSessionService));
    $registry->register(new MyronUpdateFileAction($filesActionService));
    $registry->register(new MyronReplaceFileContentAction($filesActionService));
    $registry->register(new MyronDeleteFileAction($filesActionService));
    $registry->register(new MyronCreateVideoAssetAction($videoActionService));
    $registry->register(new MyronUpdateVideoAssetAction($videoActionService));
    $registry->register(new MyronAddVideoRenditionAction($videoActionService));
    $registry->register(new MyronDeleteVideoAssetAction($videoActionService));
    $registry->register(new MyronUploadVideoCaptionsAction($mediaAccessibilityService));
    $registry->register(new MyronDeleteVideoCaptionsAction($mediaAccessibilityService));
    $registry->register(new MyronUploadAudioTranscriptAction($mediaAccessibilityService));
    $registry->register(new MyronDeleteAudioTranscriptAction($mediaAccessibilityService));
    // Template chrome (APO-194 Card 5)
    $registry->register(new MyronAssignTemplateChromeAction($chromeService));
    $registry->register(new MyronResetTemplateChromeAction($chromeService));
    // Definitions (APO-194 Card 6 — exposeToMcp:false; install-level system management)
    $registry->register(new MyronSaveCurrentDefinitionAction($definitionsService));
    $registry->register(new MyronApplyStoredDefinitionAction($definitionsService));
    $registry->register(new MyronApplyDefinitionAction($definitionsService));
    $registry->register(new MyronResetBaselineDefinitionAction($definitionsService));
    $registry->register(new MyronRemoveStoredDefinitionAction($definitionsService));
    $registry->register(new MyronRemoveSystemArchetypeAction($definitionsService));
    $registry->register(new MyronImportDefinitionAction($definitionsService));

    // Pass A2 read endpoints (snapshotInclude tags drive snapshot composer)
    $navRepo                   = myronNavigationDesignRepository();
    $templateDefRepo           = myronTemplateDefinitionRepository();
    $docTemplateRepo           = myronDocumentTemplateRepository();
    $fileRepoForReads          = myronFileRepository();
    $videoRepoForReads         = myronVideoAssetRepository();
    $chromeAssignmentRepo      = myronTemplateChromeAssignmentRepository();

    $registry->register(new MyronListNavigationVersionsAction($navRepo));
    $registry->register(new MyronGetNavigationVersionAction($navRepo));
    $registry->register(new MyronGetNavigationDefaultAction($navRepo));
    $registry->register(new MyronListTemplatesAction($templateDefRepo));
    $registry->register(new MyronGetTemplateAction($templateDefRepo, myronContentRepository()));
    $registry->register(new MyronListDocumentTemplatesAction($docTemplateRepo));
    $registry->register(new MyronGetDocumentTemplateAction($docTemplateRepo));
    $registry->register(new MyronGetTemplateChromeAction($chromeAssignmentRepo));
    $registry->register(new MyronListDefinitionsAction($definitionsService));
    $registry->register(new MyronExportCurrentDefinitionAction($definitionsService));
    $registry->register(new MyronListFilesAction($fileRepoForReads));
    $registry->register(new MyronGetFileAction($fileRepoForReads));
    $registry->register(new MyronListVideoAssetsAction($videoRepoForReads));
    $registry->register(new MyronGetVideoAssetAction($videoRepoForReads));

    // Content (APO-195 Card 1) — Pages mutations
    $pagesService = myronPagesActionService();
    $pageContractService = myronPageContractService();
    $registry->register(new MyronCreatePageAction($pagesService));
    $registry->register(new MyronUpdatePageAction($pagesService));
    $registry->register(new MyronSavePageSeoAction($pagesService));
    $registry->register(new MyronDownloadPageMarkupAction(myronContentRepository()));
    $registry->register(new MyronDownloadPageMarkdownAction(myronContentRepository(), myronMarkdownExtractor()));
    $registry->register(new MyronValidateOgImageAction(myronOgImageValidator()));
    $registry->register(new MyronPublishPageAction($pagesService));
    $registry->register(new MyronUnpublishPageAction($pagesService));
    $registry->register(new MyronDeletePageAction($pagesService));
    $registry->register(new MyronUpdatePageSectionContentAction($pageContractService));
    $registry->register(new MyronSetPageBodyMarkdownAction($pageContractService));
    $registry->register(new MyronSetPageCategoriesAction($pagesService));
    $registry->register(new MyronGetPageCategoriesAction($pagesService));
    $registry->register(new MyronSetPageAuthorAction($pagesService));
    $registry->register(new MyronGetPageAuthorAction($pagesService));
    $registry->register(new MyronSetPageNavVisibilityAction($pagesService));
    $registry->register(new MyronAssignPageRoleAction($pagesService));
    $registry->register(new MyronClearPageRoleAction($pagesService));

    // Content (APO-195 Card 2) — Section edits on template drafts
    $sectionEditService = myronSectionEditActionService();
    $registry->register(new MyronCreateRuntimeDraftAction($sectionEditService));
    $registry->register(new MyronInsertSectionAction($sectionEditService));
    $registry->register(new MyronMoveSectionAction($sectionEditService));
    $registry->register(new MyronDuplicateTemplateSectionAction($sectionEditService));
    $registry->register(new MyronRemoveTemplateSectionAction($sectionEditService));
    $registry->register(new MyronReorderTemplateSectionsAction($sectionEditService));
    $registry->register(new MyronUpdateSectionEditabilityAction($sectionEditService));
    $registry->register(new MyronUpdateSectionDesignAction($sectionEditService));
    $registry->register(new MyronUpdateTemplateSectionContentAction($sectionEditService));
    $registry->register(new MyronSaveSectionAsVariantAction($sectionEditService));
    $registry->register(new MyronApplySectionVariantToTemplateAction($sectionEditService));

    // Content (APO-195 Card 3) — Categories
    $categoryService = myronCategoryActionService();
    $registry->register(new MyronCreateCategoryAction($categoryService));
    $registry->register(new MyronUpdateCategoryAction($categoryService));
    $registry->register(new MyronArchiveCategoryAction($categoryService));
    $registry->register(new MyronReactivateCategoryAction($categoryService));

    // Content (APO-195 Card 4) — Menus
    $menuService = myronMenuActionService();
    $registry->register(new MyronCreateMenuAction($menuService));
    $registry->register(new MyronSaveMenuPlacementsAction($menuService));
    $registry->register(new MyronAddPageToMenuAction($menuService));
    $registry->register(new MyronRemoveMenuItemAction($menuService));
    $registry->register(new MyronMoveMenuItemAction($menuService));

    // Content reads (APO-195 Card 7)
    $contentRepo = myronContentRepository();
    myronBootstrapCoreMicTypes();
    $micTableService = myronMicTableService();
    $registry->register(new MicTypesListAction(myronMicElementRegistry()));
    $registry->register(new MicTableListAction($micTableService));
    $registry->register(new MicTableReadAction($micTableService));
    $registry->register(new MicTableCreateAction($micTableService));
    $registry->register(new MicTableUpdateAction($micTableService));
    $registry->register(new MicTableDeleteAction($micTableService));
    $micFormService = myronMicFormService();
    $registry->register(new MicFormListAction($micFormService));
    $registry->register(new MicFormReadAction($micFormService));
    $registry->register(new MicFormCreateAction($micFormService));
    $registry->register(new MicFormUpdateAction($micFormService));
    $registry->register(new MicFormDeleteAction($micFormService));
    $registry->register(new MicFormDuplicateAction($micFormService));
    $registry->register(new MicFormSubmissionListAction($micFormService));
    $registry->register(new MicFormSubmissionReadAction($micFormService));
    $registry->register(new MicFormSubmissionDeleteAction($micFormService));
    $registry->register(new MyronListPagesAction($contentRepo));
    $registry->register(new MyronGetPageAction($contentRepo));
    $registry->register(new MyronGetPageContractAction($pageContractService));
    $registry->register(new MyronListPagesForManagerAction($contentRepo));
    $registry->register(new MyronListCategoriesAction($contentRepo));
    $registry->register(new MyronListPageCategoriesWithUsageAction($contentRepo));
    $registry->register(new MyronListMenusAction($contentRepo));
    $registry->register(new MyronListMenuPlacementsAction($contentRepo));
    $registry->register(new MyronSaveCommentSettingsAction(myronBlogCommentService()));
    // APO-269 Site Search Foundation
    $registry->register(new MyronSearchContentAction(myronSearchIndex()));
    $registry->register(new MyronRebuildSearchIndexAction(myronDatabase(), myronSearchIndexer()));

    // Administration (APO-196 Pass C)
    $siteSettingsService = myronSiteSettingsActionService();
    $mailService         = myronMailActionService();
    $siteSetupService    = myronSiteSetupActionService();
    $identityService     = myronIdentityActionService();
    $siteSettingsRepo    = myronSiteSettingsRepository();
    $verificationSettingsRepo = myronVerificationSettingsRepository();
    $mailSettingsRepo    = myronMailSettingsRepository();
    $onboardingRepo      = myronOnboardingStateRepository();
    $authRepo            = myronAuthRepository();

    // Mutations
    $registry->register(new MyronSaveSiteSettingsAction($siteSettingsService));
    $registry->register(new MyronSaveSeoSettingsAction($siteSettingsService));
    $registry->register(new MyronSaveMailSettingsAction($mailService));
    $registry->register(new MyronSendTestMailAction($mailService));
    $registry->register(new MyronSaveSiteSetupAction($siteSetupService));
    $registry->register(new MyronBundleDisableAction(myronBundleDisableService()));
    $registry->register(new MyronBundleEnableAction(myronBundleEnableService()));
    $registry->register(new MyronDeleteRedirectAction(myronDisabledPageRedirectsRepository()));
    $registry->register(new MyronResetSiteBaselineAction($siteSetupService));
    $registry->register(new MyronApplyApplicationUpdateAction($siteSetupService));
    $registry->register(new MyronApplyRemoteApplicationUpdateAction($siteSetupService));
    $registry->register(new MyronCheckRemoteApplicationUpdateAction($siteSetupService));
    $registry->register(new MyronSaveRemoteUpdateManifestUrlAction($siteSetupService));
    $registry->register(new MyronDismissRemoteApplicationUpdateAction($siteSetupService));
    $registry->register(new MyronUpdateProfileAction($identityService));
    $registry->register(new MyronUpdatePasswordAction($identityService));
    $registry->register(new MyronUpdateUserScopesAction($identityService));
    $registry->register(new MyronUpdateUserRoleAction($identityService));
    $registry->register(new MyronSaveRegistrationSettingsAction($identityService));
    // Reads
    $registry->register(new MyronGetSiteSettingsAction($siteSettingsRepo));
    $registry->register(new MyronGetMailConfigAction($mailSettingsRepo));
    $registry->register(new MyronListMailTransportsAction(myronMailTransportRegistry()));
    $notificationEmailService = myronNotificationEmailsService();
    $registry->register(new NotificationEmailsListAction($notificationEmailService));
    $registry->register(new NotificationEmailsCreateAction($notificationEmailService));
    $registry->register(new NotificationEmailsResendVerificationAction($notificationEmailService));
    $registry->register(new NotificationEmailsDeleteAction($notificationEmailService));
    $registry->register(new NotificationEmailsSetDefaultAction($notificationEmailService));
    $registry->register(new NotificationEmailsVerifyAction($notificationEmailService));
    $registry->register(new MyronGetSiteSetupStateAction($onboardingRepo));
    $registry->register(new MyronBundleImpactPreviewAction(myronBundleImpactAnalysisService()));
    $registry->register(new MyronBundleRecentEventsAction(myronDatabase(), myronSiteTypeRegistryRepository()));
    $registry->register(new MyronListUsersAction($authRepo));
    $registry->register(new MyronListRolesAction());
    $registry->register(new MyronGetRegistrationSettingsAction($authRepo));
    $registry->register(new MyronReadUserAction($authRepo));
    $registry->register(new MyronGetUpdateStatusAction());
    $registry->register(new MyronGetMigrationStatusAction(myronMigrationOperationsService()));
    $registry->register(new MyronApplyPendingMigrationsAction(myronMigrationOperationsService()));
    $registry->register(new MyronExportSiteSnapshotAction(myronSiteSnapshotExportService()));
    $registry->register(new MyronImportSiteSnapshotAction(myronSiteSnapshotImportService()));
    $registry->register(new MyronGetVerificationSettingsAction($verificationSettingsRepo));
    $registry->register(new MyronUpdateVerificationSettingsAction($verificationSettingsRepo));
    $registry->register(new MyronRefreshLicenseAction(myronLicenseActivationService()));
    $registry->register(new MyronRemoveLicenseAction(myronLicenseActivationService()));
    $registry->register(new MyronListModuleLicensesAction(myronModuleLicenseManagerService()));
    $registry->register(new MyronRedeemModuleLicenseAction(myronModuleLicenseManagerService()));
    $registry->register(new MyronInstallModulePackageAction(myronModuleLicenseManagerService()));
    $registry->register(new MyronGetModuleEntitlementAction(myronModuleLicenseManagerService()));
    $registry->register(new MyronRefreshModuleEntitlementsAction(myronModuleLicenseManagerService()));

    $analyticsRepo = myronSiteAnalyticsRepository();
    $registry->register(new MyronGetAnalyticsSummaryAction($analyticsRepo));
    $registry->register(new MyronGetTopPagesAction($analyticsRepo));
    $registry->register(new MyronGetTrafficSourcesAction($analyticsRepo));

    // AI Connections management (APO-197) — all exposeToMcp:false
    $aiIntegrationRepo = myronAiIntegrationRepository();
    $registry->register(new MyronCreateAiConnectionAction($aiIntegrationRepo));
    $registry->register(new MyronUpdateAiConnectionAction($aiIntegrationRepo));
    $registry->register(new MyronRevokeAiConnectionAction(myronAiConnectionRevocationService()));
    $registry->register(new MyronRotateAiConnectionAction($aiIntegrationRepo));

    myronModuleRegistry()->initializeActions($registry);
})();

myronExtensionLoader()->boot();
