/// @defgroup SrcRoot "SrcRoot"
/// @{
/// @brief Canonical backend package root for application, scripts, and tests.
/// @}
void SrcRoot(void);

/// @defgroup src_api "src.api"
/// @{
/// @brief Backend API package root.
/// @}
void src_api(void);

/// @defgroup AuthApi "AuthApi"
/// @{
/// @brief Authentication API endpoints.
/// @invariant All auth endpoints must return consistent error codes.
/// @post FastAPI app instance with auth routes registered.
/// @pre Python environment and dependencies installed; database available.
/// @}
void AuthApi(void);

/// @defgroup login_for_access_token "login_for_access_token"
/// @{
/// @brief Authenticates a user and returns a JWT access token.
/// @post Returns a Token object on success.
/// @pre form_data contains username and password.
/// @}
void login_for_access_token(void);

/// @defgroup read_users_me "read_users_me"
/// @{
/// @brief Retrieves the profile of the currently authenticated user.
/// @post Returns the current user's data.
/// @pre Valid JWT token provided.
/// @}
void read_users_me(void);

/// @defgroup logout "logout"
/// @{
/// @brief Logs out the current user (placeholder for session revocation).
/// @post Returns success message.
/// @pre Valid JWT token provided.
/// @}
void logout(void);

/// @defgroup login_adfs "login_adfs"
/// @{
/// @brief Initiates the ADFS OIDC login flow.
/// @post Redirects the user to ADFS.
/// @}
void login_adfs(void);

/// @defgroup auth_callback_adfs "auth_callback_adfs"
/// @{
/// @brief Handles the callback from ADFS after successful authentication.
/// @post Provisions user JIT and returns session token.
/// @}
void auth_callback_adfs(void);

/// @defgroup ApiRoutesModule "ApiRoutesModule"
/// @{
/// @brief Provide lazy route module loading to avoid heavyweight imports during tests.
/// @invariant Only names listed in __all__ are importable via __getattr__.
/// @post Route modules are lazily loadable via __getattr__
/// @pre FastAPI app initialized, route modules available in package
/// @}
void ApiRoutesModule(void);

/// @defgroup Route_Group_Contracts "Route_Group_Contracts"
/// @{
/// @brief Declare the canonical route-module registry used by lazy imports and app router inclusion.
/// @}
void Route_Group_Contracts(void);

/// @defgroup ApiRoutesGetAttr "ApiRoutesGetAttr"
/// @{
/// @brief Lazily import route module by attribute name.
/// @post Returns imported submodule or raises AttributeError.
/// @pre name is module candidate exposed in __all__.
/// @}
void ApiRoutesGetAttr(void);

/// @defgroup RoutesTestsConftest "RoutesTestsConftest"
/// @{
/// @brief Shared low-fidelity test doubles for API route test modules.
/// @}
void RoutesTestsConftest(void);

/// @defgroup AssistantApiTests "AssistantApiTests"
/// @{
/// @brief Validate assistant API endpoint logic via direct async handler invocation.
/// @invariant Every test clears assistant in-memory state before execution.
/// @}
void AssistantApiTests(void);

/// @defgroup _dataset_review_session "_dataset_review_session"
/// @{
/// @brief Build minimal owned dataset-review session fixture for assistant scoped routing tests.
/// @}
void _dataset_review_session(void);

/// @defgroup _await_none "_await_none"
/// @{
/// @brief Async helper returning None for planner fallback tests.
/// @}
void _await_none(void);

/// @defgroup test_unknown_command_returns_needs_clarification "test_unknown_command_returns_needs_clarification"
/// @{
/// @brief Unknown command should return clarification state and unknown intent.
/// @}
void test_unknown_command_returns_needs_clarification(void);

/// @defgroup test_capabilities_question_returns_successful_help "test_capabilities_question_returns_successful_help"
/// @{
/// @brief Capability query should return deterministic help response.
/// @}
void test_capabilities_question_returns_successful_help(void);

/// @defgroup test_assistant_message_request_accepts_dataset_review_session_binding "test_assistant_message_request_accepts_dataset_review_session_binding"
/// @{
/// @brief Assistant request schema should accept active dataset review session binding for scoped orchestration.
/// @}
void test_assistant_message_request_accepts_dataset_review_session_binding(void);

/// @defgroup test_dataset_review_scoped_message_uses_masked_filter_context "test_dataset_review_scoped_message_uses_masked_filter_context"
/// @{
/// @brief Session-scoped assistant context should mask imported-filter raw values before assistant-visible metadata is persisted.
/// @}
void test_dataset_review_scoped_message_uses_masked_filter_context(void);

/// @defgroup test_dataset_review_scoped_command_returns_confirmation_for_mapping_approval "test_dataset_review_scoped_command_returns_confirmation_for_mapping_approval"
/// @{
/// @brief Session-scoped assistant commands should route dataset-review mapping approvals into confirmation workflow with bound session metadata.
/// @}
void test_dataset_review_scoped_command_returns_confirmation_for_mapping_approval(void);

/// @defgroup test_dataset_review_scoped_command_routes_field_semantics_update "test_dataset_review_scoped_command_routes_field_semantics_update"
/// @{
/// @brief Session-scoped assistant commands should route semantic field updates through explicit confirmation metadata.
/// @}
void test_dataset_review_scoped_command_routes_field_semantics_update(void);

/// @defgroup TestAssistantAuthz "TestAssistantAuthz"
/// @{
/// @brief Verify assistant confirmation ownership, expiration, and deny behavior for restricted users.
/// @invariant Security-sensitive flows fail closed for unauthorized actors.
/// @}
void TestAssistantAuthz(void);

/// @defgroup _run_async "_run_async"
/// @{
/// @brief Execute async endpoint handler in synchronous test context.
/// @post Returns coroutine result or raises propagated exception.
/// @pre coroutine is awaitable endpoint invocation.
/// @}
void _run_async(void);

/// @defgroup _FakeTask "_FakeTask"
/// @{
/// @brief Lightweight task model used for assistant authz tests.
/// @post Returns task with provided id, status, and user_id accessible as attributes.
/// @pre task_id is non-empty string.
/// @}
void _FakeTask(void);

/// @defgroup _FakeConfigManager "_FakeConfigManager"
/// @{
/// @brief Provide deterministic environment aliases required by intent parsing.
/// @invariant get_config() is absent; only get_environments() is emulated. Safe only for routes that do not invoke get_config() on the injected ConfigManager — verify against assistant.py route handler code before adding new test cases that use this fake.
/// @post get_environments() returns two deterministic SimpleNamespace stubs with id/name.
/// @pre No external config or DB state is required.
/// @}
void _FakeConfigManager(void);

/// @defgroup _other_admin_user "_other_admin_user"
/// @{
/// @brief Build second admin principal fixture for ownership tests.
/// @post Returns alternate admin-like user stub.
/// @pre Ownership mismatch scenario needs distinct authenticated actor.
/// @}
void _other_admin_user(void);

/// @defgroup _limited_user "_limited_user"
/// @{
/// @brief Build limited principal without required assistant execution privileges.
/// @post Returns restricted user stub.
/// @pre Permission denial scenario needs non-admin actor.
/// @}
void _limited_user(void);

/// @defgroup _FakeDb "_FakeDb"
/// @{
/// @brief In-memory DB session double constrained to assistant message/confirmation/audit persistence paths.
/// @invariant query/add/merge are intentionally narrow and must not claim full SQLAlchemy Session semantics.
/// @}
void _FakeDb(void);

/// @defgroup _clear_assistant_state "_clear_assistant_state"
/// @{
/// @brief Reset assistant process-local state between test cases.
/// @post Assistant in-memory state dictionaries are cleared.
/// @pre Assistant globals may contain state from prior tests.
/// @}
void _clear_assistant_state(void);

/// @defgroup test_confirmation_owner_mismatch_returns_403 "test_confirmation_owner_mismatch_returns_403"
/// @{
/// @brief Confirm endpoint should reject requests from user that does not own the confirmation token.
/// @post Second actor receives 403 on confirm operation.
/// @pre Confirmation token is created by first admin actor.
/// @}
void test_confirmation_owner_mismatch_returns_403(void);

/// @defgroup test_expired_confirmation_cannot_be_confirmed "test_expired_confirmation_cannot_be_confirmed"
/// @{
/// @brief Expired confirmation token should be rejected and not create task.
/// @post Confirm endpoint raises 400 and no task is created.
/// @pre Confirmation token exists and is manually expired before confirm request.
/// @}
void test_expired_confirmation_cannot_be_confirmed(void);

/// @defgroup test_limited_user_cannot_launch_restricted_operation "test_limited_user_cannot_launch_restricted_operation"
/// @{
/// @brief Limited user should receive denied state for privileged operation.
/// @post Assistant returns denied state and does not execute operation.
/// @pre Restricted user attempts dangerous deploy command.
/// @}
void test_limited_user_cannot_launch_restricted_operation(void);

/// @defgroup TestCleanReleaseApi "TestCleanReleaseApi"
/// @{
/// @brief Contract tests for clean release checks and reports endpoints.
/// @invariant API returns deterministic payload shapes for checks and reports.
/// @}
void TestCleanReleaseApi(void);

/// @defgroup test_start_check_and_get_status_contract "test_start_check_and_get_status_contract"
/// @{
/// @brief Validate checks start endpoint returns expected identifiers and status endpoint reflects the same run.
/// @}
void test_start_check_and_get_status_contract(void);

/// @defgroup test_get_report_not_found_returns_404 "test_get_report_not_found_returns_404"
/// @{
/// @brief Validate reports endpoint returns 404 for an unknown report identifier.
/// @}
void test_get_report_not_found_returns_404(void);

/// @defgroup test_get_report_success "test_get_report_success"
/// @{
/// @brief Validate reports endpoint returns persisted report payload for an existing report identifier.
/// @}
void test_get_report_success(void);

/// @defgroup test_prepare_candidate_api_success "test_prepare_candidate_api_success"
/// @{
/// @brief Validate candidate preparation endpoint returns prepared status and manifest identifier on valid input.
/// @}
void test_prepare_candidate_api_success(void);

/// @defgroup TestCleanReleaseLegacyCompat "TestCleanReleaseLegacyCompat"
/// @{
/// @brief Compatibility tests for legacy clean-release API paths retained during v2 migration.
/// @}
void TestCleanReleaseLegacyCompat(void);

/// @defgroup _seed_legacy_repo "_seed_legacy_repo"
/// @{
/// @brief Seed in-memory repository with minimum trusted data for legacy endpoint contracts.
/// @post Candidate, policy, registry and manifest are available for legacy checks flow.
/// @pre Repository is empty.
/// @}
void _seed_legacy_repo(void);

/// @defgroup test_legacy_prepare_endpoint_still_available "test_legacy_prepare_endpoint_still_available"
/// @{
/// @brief Verify legacy prepare endpoint remains reachable and returns a status payload.
/// @}
void test_legacy_prepare_endpoint_still_available(void);

/// @defgroup test_legacy_checks_endpoints_still_available "test_legacy_checks_endpoints_still_available"
/// @{
/// @brief Verify legacy checks start/status endpoints remain available during v2 transition.
/// @}
void test_legacy_checks_endpoints_still_available(void);

/// @defgroup TestCleanReleaseSourcePolicy "TestCleanReleaseSourcePolicy"
/// @{
/// @brief Validate API behavior for source isolation violations in clean release preparation.
/// @invariant External endpoints must produce blocking violation entries.
/// @}
void TestCleanReleaseSourcePolicy(void);

/// @defgroup _repo_with_seed_data "_repo_with_seed_data"
/// @{
/// @brief Seed repository with candidate, registry, and active policy for source isolation test flow.
/// @}
void _repo_with_seed_data(void);

/// @defgroup test_prepare_candidate_blocks_external_source "test_prepare_candidate_blocks_external_source"
/// @{
/// @brief Verify candidate preparation is blocked when at least one source host is external to the trusted registry.
/// @}
void test_prepare_candidate_blocks_external_source(void);

/// @defgroup CleanReleaseV2ApiTests "CleanReleaseV2ApiTests"
/// @{
/// @brief API contract tests for redesigned clean release endpoints.
/// @}
void CleanReleaseV2ApiTests(void);

/// @defgroup test_candidate_registration_contract "test_candidate_registration_contract"
/// @{
/// @brief Validate candidate registration endpoint creates a draft candidate with expected identifier contract.
/// @}
void test_candidate_registration_contract(void);

/// @defgroup test_artifact_import_contract "test_artifact_import_contract"
/// @{
/// @brief Validate artifact import endpoint accepts candidate artifacts and returns success status payload.
/// @}
void test_artifact_import_contract(void);

/// @defgroup test_manifest_build_contract "test_manifest_build_contract"
/// @{
/// @brief Validate manifest build endpoint produces manifest payload linked to the target candidate.
/// @}
void test_manifest_build_contract(void);

/// @defgroup CleanReleaseV2ReleaseApiTests "CleanReleaseV2ReleaseApiTests"
/// @{
/// @brief API contract test scaffolding for clean release approval and publication endpoints.
/// @}
void CleanReleaseV2ReleaseApiTests(void);

/// @defgroup _seed_candidate_and_passed_report "_seed_candidate_and_passed_report"
/// @{
/// @brief Seed repository with approvable candidate and passed report for release endpoint contracts.
/// @}
void _seed_candidate_and_passed_report(void);

/// @defgroup test_release_approve_and_publish_revoke_contract "test_release_approve_and_publish_revoke_contract"
/// @{
/// @brief Verify approve, publish, and revoke endpoints preserve expected release lifecycle contract.
/// @}
void test_release_approve_and_publish_revoke_contract(void);

/// @defgroup test_release_reject_contract "test_release_reject_contract"
/// @{
/// @brief Verify reject endpoint returns successful rejection decision payload.
/// @}
void test_release_reject_contract(void);

/// @defgroup DashboardsApiTests "DashboardsApiTests"
/// @{
/// @brief Unit tests for dashboards API endpoints.
/// @}
void DashboardsApiTests(void);

/// @defgroup test_get_dashboards_success "test_get_dashboards_success"
/// @{
/// @brief Validate dashboards listing returns a populated response that satisfies the schema contract.
/// @post Response matches DashboardsResponse schema
/// @pre env_id exists
/// @test GET /api/dashboards returns 200 and valid schema
/// @}
void test_get_dashboards_success(void);

/// @defgroup test_get_dashboards_with_search "test_get_dashboards_with_search"
/// @{
/// @brief Validate dashboards listing applies the search filter and returns only matching rows.
/// @post Filtered result count must match search
/// @pre search parameter provided
/// @test GET /api/dashboards filters by search term
/// @}
void test_get_dashboards_with_search(void);

/// @defgroup test_get_dashboards_empty "test_get_dashboards_empty"
/// @{
/// @brief Validate dashboards listing returns an empty payload for an environment without dashboards.
/// @}
void test_get_dashboards_empty(void);

/// @defgroup test_get_dashboards_superset_failure "test_get_dashboards_superset_failure"
/// @{
/// @brief Validate dashboards listing surfaces a 503 contract when Superset access fails.
/// @}
void test_get_dashboards_superset_failure(void);

/// @defgroup test_get_dashboards_env_not_found "test_get_dashboards_env_not_found"
/// @{
/// @brief Validate dashboards listing returns 404 when the requested environment does not exist.
/// @post Returns 404 error
/// @pre env_id does not exist
/// @test GET /api/dashboards returns 404 if env_id missing
/// @}
void test_get_dashboards_env_not_found(void);

/// @defgroup test_get_dashboards_invalid_pagination "test_get_dashboards_invalid_pagination"
/// @{
/// @brief Validate dashboards listing rejects invalid pagination parameters with 400 responses.
/// @post Returns 400 error
/// @pre page < 1 or page_size > 100
/// @test GET /api/dashboards returns 400 for invalid page/page_size
/// @}
void test_get_dashboards_invalid_pagination(void);

/// @defgroup test_get_dashboard_detail_success "test_get_dashboard_detail_success"
/// @{
/// @brief Validate dashboard detail returns charts and datasets for an existing dashboard.
/// @test GET /api/dashboards/{id} returns dashboard detail with charts and datasets
/// @}
void test_get_dashboard_detail_success(void);

/// @defgroup test_get_dashboard_detail_env_not_found "test_get_dashboard_detail_env_not_found"
/// @{
/// @brief Validate dashboard detail returns 404 when the requested environment is missing.
/// @test GET /api/dashboards/{id} returns 404 for missing environment
/// @}
void test_get_dashboard_detail_env_not_found(void);

/// @defgroup test_migrate_dashboards_success "test_migrate_dashboards_success"
/// @{
/// @brief Validate dashboard migration request creates an async task and returns its identifier.
/// @post Returns task_id and create_task was called
/// @POST/@SIDE_EFFECT: create_task was called
/// @pre Valid source_env_id, target_env_id, dashboard_ids
/// @test POST /api/dashboards/migrate creates migration task
/// @}
void test_migrate_dashboards_success(void);

/// @defgroup test_migrate_dashboards_no_ids "test_migrate_dashboards_no_ids"
/// @{
/// @brief Validate dashboard migration rejects empty dashboard identifier lists.
/// @post Returns 400 error
/// @pre dashboard_ids is empty
/// @test POST /api/dashboards/migrate returns 400 for empty dashboard_ids
/// @}
void test_migrate_dashboards_no_ids(void);

/// @defgroup test_migrate_dashboards_env_not_found "test_migrate_dashboards_env_not_found"
/// @{
/// @brief Validate migration creation returns 404 when the source environment cannot be resolved.
/// @pre source_env_id and target_env_id are valid environment IDs
/// @}
void test_migrate_dashboards_env_not_found(void);

/// @defgroup test_backup_dashboards_success "test_backup_dashboards_success"
/// @{
/// @brief Validate dashboard backup request creates an async backup task and returns its identifier.
/// @post Returns task_id and create_task was called
/// @POST/@SIDE_EFFECT: create_task was called
/// @pre Valid env_id, dashboard_ids
/// @test POST /api/dashboards/backup creates backup task
/// @}
void test_backup_dashboards_success(void);

/// @defgroup test_backup_dashboards_env_not_found "test_backup_dashboards_env_not_found"
/// @{
/// @brief Validate backup task creation returns 404 when the target environment is missing.
/// @pre env_id is a valid environment ID
/// @}
void test_backup_dashboards_env_not_found(void);

/// @defgroup test_get_database_mappings_success "test_get_database_mappings_success"
/// @{
/// @brief Validate database mapping suggestions are returned for valid source and target environments.
/// @post Returns list of database mappings
/// @pre Valid source_env_id, target_env_id
/// @test GET /api/dashboards/db-mappings returns mapping suggestions
/// @}
void test_get_database_mappings_success(void);

/// @defgroup test_get_database_mappings_env_not_found "test_get_database_mappings_env_not_found"
/// @{
/// @brief Validate database mapping suggestions return 404 when either environment is missing.
/// @pre source_env_id and target_env_id are valid environment IDs
/// @}
void test_get_database_mappings_env_not_found(void);

/// @defgroup test_get_dashboard_tasks_history_filters_success "test_get_dashboard_tasks_history_filters_success"
/// @{
/// @brief Validate dashboard task history returns only related backup and LLM tasks.
/// @test GET /api/dashboards/{id}/tasks returns backup and llm tasks for dashboard
/// @}
void test_get_dashboard_tasks_history_filters_success(void);

/// @defgroup test_get_dashboard_thumbnail_success "test_get_dashboard_thumbnail_success"
/// @{
/// @brief Validate dashboard thumbnail endpoint proxies image bytes and content type from Superset.
/// @test GET /api/dashboards/{id}/thumbnail proxies image bytes from Superset
/// @}
void test_get_dashboard_thumbnail_success(void);

/// @defgroup _build_profile_preference_stub "_build_profile_preference_stub"
/// @{
/// @brief Creates profile preference payload stub for dashboards filter contract tests.
/// @post Returns object compatible with ProfileService.get_my_preference contract.
/// @pre username can be empty; enabled indicates profile-default toggle state.
/// @}
void _build_profile_preference_stub(void);

/// @defgroup _matches_actor_case_insensitive "_matches_actor_case_insensitive"
/// @{
/// @brief Applies trim + case-insensitive owners OR modified_by matching used by route contract tests.
/// @post Returns True when bound username matches any owner or modified_by.
/// @pre owners can be None or list-like values.
/// @}
void _matches_actor_case_insensitive(void);

/// @defgroup test_get_dashboards_profile_filter_contract_owners_or_modified_by "test_get_dashboards_profile_filter_contract_owners_or_modified_by"
/// @{
/// @brief Validate profile-default filtering matches owner and modifier aliases using normalized Superset actor values.
/// @post Response includes only matching dashboards and effective_profile_filter metadata.
/// @pre Current user has enabled profile-default preference and bound username.
/// @test GET /api/dashboards applies profile-default filter with owners OR modified_by trim+case-insensitive semantics.
/// @}
void test_get_dashboards_profile_filter_contract_owners_or_modified_by(void);

/// @defgroup test_get_dashboards_override_show_all_contract "test_get_dashboards_override_show_all_contract"
/// @{
/// @brief Validate override_show_all bypasses profile-default filtering without changing dashboard list semantics.
/// @post Response remains unfiltered and effective_profile_filter.applied is false.
/// @pre Profile-default preference exists but override_show_all=true query is provided.
/// @test GET /api/dashboards honors override_show_all and disables profile-default filter for current page.
/// @}
void test_get_dashboards_override_show_all_contract(void);

/// @defgroup test_get_dashboards_profile_filter_no_match_results_contract "test_get_dashboards_profile_filter_no_match_results_contract"
/// @{
/// @brief Validate profile-default filtering returns an empty dashboard page when no actor aliases match the bound user.
/// @post Response total is 0 with deterministic pagination and active effective_profile_filter metadata.
/// @pre Profile-default preference is enabled with bound username and all dashboards are non-matching.
/// @test GET /api/dashboards returns empty result set when profile-default filter is active and no dashboard actors match.
/// @}
void test_get_dashboards_profile_filter_no_match_results_contract(void);

/// @defgroup test_get_dashboards_page_context_other_disables_profile_default "test_get_dashboards_page_context_other_disables_profile_default"
/// @{
/// @brief Validate non-dashboard page contexts suppress profile-default filtering and preserve unfiltered results.
/// @post Response remains unfiltered and metadata reflects source_page=other.
/// @pre Profile-default preference exists but page_context=other query is provided.
/// @test GET /api/dashboards does not auto-apply profile-default filter outside dashboards_main page context.
/// @}
void test_get_dashboards_page_context_other_disables_profile_default(void);

/// @defgroup test_get_dashboards_profile_filter_matches_display_alias_without_detail_fanout "test_get_dashboards_profile_filter_matches_display_alias_without_detail_fanout"
/// @{
/// @brief Validate profile-default filtering reuses resolved Superset display aliases without triggering per-dashboard detail fanout.
/// @post Route matches by alias (`Superset Admin`) and does not call `SupersetClient.get_dashboard` in list filter path.
/// @pre Profile-default filter is active, bound username is `admin`, dashboard actors contain display labels.
/// @test GET /api/dashboards resolves Superset display-name alias once and filters without per-dashboard detail calls.
/// @}
void test_get_dashboards_profile_filter_matches_display_alias_without_detail_fanout(void);

/// @defgroup test_get_dashboards_profile_filter_matches_owner_object_payload_contract "test_get_dashboards_profile_filter_matches_owner_object_payload_contract"
/// @{
/// @brief Validate profile-default filtering accepts owner object payloads once aliases resolve to the bound Superset username.
/// @post Response keeps dashboards where owner object resolves to bound username alias.
/// @pre Profile-default preference is enabled and owners list contains dict payloads.
/// @test GET /api/dashboards profile-default filter matches Superset owner object payloads.
/// @}
void test_get_dashboards_profile_filter_matches_owner_object_payload_contract(void);

/// @defgroup DatasetReviewApiTests "DatasetReviewApiTests"
/// @{
/// @brief Verify backend US1 dataset review lifecycle, export, parsing, and dictionary-resolution contracts.
/// @}
void DatasetReviewApiTests(void);

/// @defgroup _make_user "_make_user"
/// @{
/// @}
void _make_user(void);

/// @defgroup _make_config_manager "_make_config_manager"
/// @{
/// @}
void _make_config_manager(void);

/// @defgroup _make_session "_make_session"
/// @{
/// @}
void _make_session(void);

/// @defgroup _make_us2_session "_make_us2_session"
/// @{
/// @}
void _make_us2_session(void);

/// @defgroup _make_us3_session "_make_us3_session"
/// @{
/// @}
void _make_us3_session(void);

/// @defgroup _make_preview_ready_session "_make_preview_ready_session"
/// @{
/// @}
void _make_preview_ready_session(void);

/// @defgroup dataset_review_api_dependencies "dataset_review_api_dependencies"
/// @{
/// @}
void dataset_review_api_dependencies(void);

/// @defgroup test_parse_superset_link_dashboard_partial_recovery "test_parse_superset_link_dashboard_partial_recovery"
/// @{
/// @brief Verify dashboard links recover dataset context and preserve explicit partial-recovery markers.
/// @}
void test_parse_superset_link_dashboard_partial_recovery(void);

/// @defgroup test_parse_superset_link_dashboard_slug_recovery "test_parse_superset_link_dashboard_slug_recovery"
/// @{
/// @brief Verify dashboard slug links resolve through dashboard detail endpoints and recover dataset context.
/// @}
void test_parse_superset_link_dashboard_slug_recovery(void);

/// @defgroup test_parse_superset_link_dashboard_permalink_partial_recovery "test_parse_superset_link_dashboard_permalink_partial_recovery"
/// @{
/// @brief Verify dashboard permalink links no longer fail parsing and preserve permalink filter state for partial recovery.
/// @}
void test_parse_superset_link_dashboard_permalink_partial_recovery(void);

/// @defgroup test_parse_superset_link_dashboard_permalink_recovers_dataset_from_nested_dashboard_state "test_parse_superset_link_dashboard_permalink_recovers_dataset_from_nested_dashboard_state"
/// @{
/// @brief Verify permalink state with nested dashboard id recovers dataset binding and keeps imported filters.
/// @}
void test_parse_superset_link_dashboard_permalink_recovers_dataset_from_nested_dashboard_state(void);

/// @defgroup test_resolve_from_dictionary_prefers_exact_match "test_resolve_from_dictionary_prefers_exact_match"
/// @{
/// @brief Verify trusted dictionary exact matches outrank fuzzy candidates and unresolved fields stay explicit.
/// @}
void test_resolve_from_dictionary_prefers_exact_match(void);

/// @defgroup test_orchestrator_start_session_preserves_partial_recovery "test_orchestrator_start_session_preserves_partial_recovery"
/// @{
/// @brief Verify session start persists usable recovery-required state when Superset intake is partial.
/// @}
void test_orchestrator_start_session_preserves_partial_recovery(void);

/// @defgroup test_orchestrator_start_session_bootstraps_recovery_state "test_orchestrator_start_session_bootstraps_recovery_state"
/// @{
/// @brief Verify session start persists recovered filters, template variables, and initial execution mappings for review workspace bootstrap.
/// @}
void test_orchestrator_start_session_bootstraps_recovery_state(void);

/// @defgroup test_start_session_endpoint_returns_created_summary "test_start_session_endpoint_returns_created_summary"
/// @{
/// @brief Verify POST session lifecycle endpoint returns a persisted ownership-scoped summary.
/// @}
void test_start_session_endpoint_returns_created_summary(void);

/// @defgroup test_get_session_detail_export_and_lifecycle_endpoints "test_get_session_detail_export_and_lifecycle_endpoints"
/// @{
/// @brief Verify lifecycle get/patch/delete plus documentation and validation exports remain ownership-scoped and usable.
/// @}
void test_get_session_detail_export_and_lifecycle_endpoints(void);

/// @defgroup test_get_clarification_state_returns_empty_payload_when_session_has_no_record "test_get_clarification_state_returns_empty_payload_when_session_has_no_record"
/// @{
/// @brief Clarification state endpoint should return a non-blocking empty payload when the session has no clarification aggregate yet.
/// @}
void test_get_clarification_state_returns_empty_payload_when_session_has_no_record(void);

/// @defgroup test_us2_clarification_endpoints_persist_answer_and_feedback "test_us2_clarification_endpoints_persist_answer_and_feedback"
/// @{
/// @brief Clarification endpoints should expose one current question, persist the answer before advancement, and store feedback on the answer audit record.
/// @}
void test_us2_clarification_endpoints_persist_answer_and_feedback(void);

/// @defgroup test_us2_field_semantic_override_lock_unlock_and_feedback "test_us2_field_semantic_override_lock_unlock_and_feedback"
/// @{
/// @brief Semantic field endpoints should apply manual overrides with lock/provenance invariants and persist feedback independently.
/// @}
void test_us2_field_semantic_override_lock_unlock_and_feedback(void);

/// @defgroup test_us3_mapping_patch_approval_preview_and_launch_endpoints "test_us3_mapping_patch_approval_preview_and_launch_endpoints"
/// @{
/// @brief US3 execution endpoints should persist manual overrides, preserve explicit approval semantics, return contract-shaped preview truth, and expose audited launch handoff.
/// @}
void test_us3_mapping_patch_approval_preview_and_launch_endpoints(void);

/// @defgroup test_us3_preview_response_propagates_refreshed_session_version_for_launch_follow_up "test_us3_preview_response_propagates_refreshed_session_version_for_launch_follow_up"
/// @{
/// @brief Preview response should expose the refreshed session version so the normal preview-then-launch UI flow can satisfy optimistic locking without a forced full reload.
/// @}
void test_us3_preview_response_propagates_refreshed_session_version_for_launch_follow_up(void);

/// @defgroup test_us3_preview_endpoint_returns_failed_preview_without_false_dashboard_not_found_contract_drift "test_us3_preview_endpoint_returns_failed_preview_without_false_dashboard_not_found_contract_drift"
/// @{
/// @brief Preview endpoint should preserve API contract and surface generic upstream preview failures without fabricating dashboard-not-found semantics for non-dashboard 404s.
/// @}
void test_us3_preview_endpoint_returns_failed_preview_without_false_dashboard_not_found_contract_drift(void);

/// @defgroup test_mutation_endpoints_surface_session_version_conflict_payload "test_mutation_endpoints_surface_session_version_conflict_payload"
/// @{
/// @brief Dataset review mutation endpoints should return deterministic 409 conflict semantics when optimistic-lock versions are stale.
/// @}
void test_mutation_endpoints_surface_session_version_conflict_payload(void);

/// @defgroup test_update_session_surfaces_commit_time_session_version_conflict_payload "test_update_session_surfaces_commit_time_session_version_conflict_payload"
/// @{
/// @brief Session lifecycle mutation should return deterministic 409 conflict semantics when commit-time optimistic locking rejects a stale write.
/// @}
void test_update_session_surfaces_commit_time_session_version_conflict_payload(void);

/// @defgroup test_execution_snapshot_includes_recovered_imported_filters_without_template_mapping "test_execution_snapshot_includes_recovered_imported_filters_without_template_mapping"
/// @{
/// @brief Recovered imported filters with values should flow into preview filter context even when no template variable mapping exists.
/// @}
void test_execution_snapshot_includes_recovered_imported_filters_without_template_mapping(void);

/// @defgroup test_execution_snapshot_preserves_mapped_template_variables_and_filter_context "test_execution_snapshot_preserves_mapped_template_variables_and_filter_context"
/// @{
/// @brief Mapped template variables should still populate template params while contributing their effective filter context.
/// @}
void test_execution_snapshot_preserves_mapped_template_variables_and_filter_context(void);

/// @defgroup test_execution_snapshot_skips_partial_imported_filters_without_values "test_execution_snapshot_skips_partial_imported_filters_without_values"
/// @{
/// @brief Partial imported filters without raw or normalized values must not emit bogus active preview filters.
/// @}
void test_execution_snapshot_skips_partial_imported_filters_without_values(void);

/// @defgroup test_us3_launch_endpoint_requires_launch_permission "test_us3_launch_endpoint_requires_launch_permission"
/// @{
/// @brief Launch endpoint should enforce the contract RBAC permission instead of the generic session-manage permission.
/// @}
void test_us3_launch_endpoint_requires_launch_permission(void);

/// @defgroup test_semantic_source_version_propagation_preserves_locked_fields "test_semantic_source_version_propagation_preserves_locked_fields"
/// @{
/// @brief Updated semantic source versions should mark unlocked fields reviewable while preserving locked manual values.
/// @}
void test_semantic_source_version_propagation_preserves_locked_fields(void);

/// @defgroup DatasetsApiTests "DatasetsApiTests"
/// @{
/// @brief Unit tests for datasets API endpoints.
/// @invariant Endpoint contracts remain stable for success and validation failure paths.
/// @}
void DatasetsApiTests(void);

/// @defgroup test_get_datasets_success "test_get_datasets_success"
/// @{
/// @brief Validate successful datasets listing contract for an existing environment.
/// @post Response matches DatasetsResponse schema
/// @pre env_id exists
/// @test GET /api/datasets returns 200 and valid schema
/// @}
void test_get_datasets_success(void);

/// @defgroup test_get_datasets_env_not_found "test_get_datasets_env_not_found"
/// @{
/// @brief Validate datasets listing returns 404 when the requested environment does not exist.
/// @post Returns 404 error
/// @pre env_id does not exist
/// @test GET /api/datasets returns 404 if env_id missing
/// @}
void test_get_datasets_env_not_found(void);

/// @defgroup test_get_datasets_invalid_pagination "test_get_datasets_invalid_pagination"
/// @{
/// @brief Validate datasets listing rejects invalid pagination parameters with 400 responses.
/// @post Returns 400 error
/// @pre page < 1 or page_size > 100
/// @test GET /api/datasets returns 400 for invalid page/page_size
/// @}
void test_get_datasets_invalid_pagination(void);

/// @defgroup test_map_columns_success "test_map_columns_success"
/// @{
/// @brief Validate map-columns request creates an async mapping task and returns its identifier.
/// @post Returns task_id
/// @pre Valid env_id, dataset_ids, source_type (sqllab)
/// @test POST /api/datasets/map-columns creates mapping task
/// @}
void test_map_columns_success(void);

/// @defgroup test_map_columns_invalid_source_type "test_map_columns_invalid_source_type"
/// @{
/// @brief Validate map-columns rejects unsupported source types with a 400 contract response.
/// @post Returns 400 error
/// @pre source_type is not 'sqllab' or 'xlsx'
/// @test POST /api/datasets/map-columns returns 400 for invalid source_type
/// @}
void test_map_columns_invalid_source_type(void);

/// @defgroup test_generate_docs_success "test_generate_docs_success"
/// @{
/// @brief Validate generate-docs request creates an async documentation task and returns its identifier.
/// @post Returns task_id
/// @pre Valid env_id, dataset_ids, llm_provider
/// @test POST /api/datasets/generate-docs creates doc generation task
/// @}
void test_generate_docs_success(void);

/// @defgroup test_map_columns_empty_ids "test_map_columns_empty_ids"
/// @{
/// @brief Validate map-columns rejects empty dataset identifier lists.
/// @post Returns 400 error
/// @pre dataset_ids is empty
/// @test POST /api/datasets/map-columns returns 400 for empty dataset_ids
/// @}
void test_map_columns_empty_ids(void);

/// @defgroup test_map_columns_missing_database_id "test_map_columns_missing_database_id"
/// @{
/// @brief Validate map-columns rejects sqllab source without database_id.
/// @post Returns 400 error
/// @test POST /api/datasets/map-columns returns 400 for sqllab without database_id
/// @}
void test_map_columns_missing_database_id(void);

/// @defgroup test_generate_docs_empty_ids "test_generate_docs_empty_ids"
/// @{
/// @brief Validate generate-docs rejects empty dataset identifier lists.
/// @post Returns 400 error
/// @pre dataset_ids is empty
/// @test POST /api/datasets/generate-docs returns 400 for empty dataset_ids
/// @}
void test_generate_docs_empty_ids(void);

/// @defgroup test_generate_docs_env_not_found "test_generate_docs_env_not_found"
/// @{
/// @brief Validate generate-docs returns 404 when the requested environment cannot be resolved.
/// @post Returns 404 error
/// @pre env_id does not exist
/// @test POST /api/datasets/generate-docs returns 404 for missing env
/// @}
void test_generate_docs_env_not_found(void);

/// @defgroup test_get_datasets_superset_failure "test_get_datasets_superset_failure"
/// @{
/// @brief Validate datasets listing surfaces a 503 contract when Superset access fails.
/// @post Returns 503 with stable error detail when upstream dataset fetch fails.
/// @}
void test_get_datasets_superset_failure(void);

/// @defgroup TestGitApi "TestGitApi"
/// @{
/// @brief API tests for Git configurations and repository operations.
/// @}
void TestGitApi(void);

/// @defgroup DbMock "DbMock"
/// @{
/// @brief In-memory session double for git route tests with minimal query/filter persistence semantics.
/// @invariant Supports only the SQLAlchemy-like operations exercised by this test module.
/// @}
void DbMock(void);

/// @defgroup test_get_git_configs_masks_pat "test_get_git_configs_masks_pat"
/// @{
/// @brief Validate listing git configs masks stored PAT values in API-facing responses.
/// @}
void test_get_git_configs_masks_pat(void);

/// @defgroup test_create_git_config_persists_config "test_create_git_config_persists_config"
/// @{
/// @brief Validate creating git config persists supplied server attributes in backing session.
/// @}
void test_create_git_config_persists_config(void);

/// @defgroup test_update_git_config_modifies_record "test_update_git_config_modifies_record"
/// @{
/// @brief Validate updating git config modifies mutable fields while preserving masked PAT semantics.
/// @}
void test_update_git_config_modifies_record(void);

/// @defgroup SingleConfigDbMock "SingleConfigDbMock"
/// @{
/// @}
void SingleConfigDbMock(void);

/// @defgroup test_update_git_config_raises_404_if_not_found "test_update_git_config_raises_404_if_not_found"
/// @{
/// @brief Validate updating non-existent git config raises HTTP 404 contract response.
/// @}
void test_update_git_config_raises_404_if_not_found(void);

/// @defgroup test_delete_git_config_removes_record "test_delete_git_config_removes_record"
/// @{
/// @brief Validate deleting existing git config removes record and returns success payload.
/// @}
void test_delete_git_config_removes_record(void);

/// @defgroup test_test_git_config_validates_connection_successfully "test_test_git_config_validates_connection_successfully"
/// @{
/// @brief Validate test-connection endpoint returns success when provider connectivity check passes.
/// @}
void test_test_git_config_validates_connection_successfully(void);

/// @defgroup MockGitService "MockGitService"
/// @{
/// @}
void MockGitService(void);

/// @defgroup test_test_git_config_fails_validation "test_test_git_config_fails_validation"
/// @{
/// @brief Validate test-connection endpoint raises HTTP 400 when provider connectivity check fails.
/// @}
void test_test_git_config_fails_validation(void);

/// @defgroup test_list_gitea_repositories_returns_payload "test_list_gitea_repositories_returns_payload"
/// @{
/// @brief Validate gitea repositories endpoint returns normalized list for GITEA provider configs.
/// @}
void test_list_gitea_repositories_returns_payload(void);

/// @defgroup test_list_gitea_repositories_rejects_non_gitea "test_list_gitea_repositories_rejects_non_gitea"
/// @{
/// @brief Validate gitea repositories endpoint rejects non-GITEA providers with HTTP 400.
/// @}
void test_list_gitea_repositories_rejects_non_gitea(void);

/// @defgroup test_create_remote_repository_creates_provider_repo "test_create_remote_repository_creates_provider_repo"
/// @{
/// @brief Validate remote repository creation endpoint maps provider response into normalized payload.
/// @}
void test_create_remote_repository_creates_provider_repo(void);

/// @defgroup test_init_repository_initializes_and_saves_binding "test_init_repository_initializes_and_saves_binding"
/// @{
/// @brief Validate repository initialization endpoint creates local repo and persists dashboard binding.
/// @}
void test_init_repository_initializes_and_saves_binding(void);

/// @defgroup TestGitStatusRoute "TestGitStatusRoute"
/// @{
/// @brief Validate status endpoint behavior for missing and error repository states.
/// @}
void TestGitStatusRoute(void);

/// @defgroup test_get_repository_status_returns_no_repo_payload_for_missing_repo "test_get_repository_status_returns_no_repo_payload_for_missing_repo"
/// @{
/// @brief Ensure missing local repository is represented as NO_REPO payload instead of an API error.
/// @post Route returns a deterministic NO_REPO status payload.
/// @pre GitService.get_status raises HTTPException(404).
/// @}
void test_get_repository_status_returns_no_repo_payload_for_missing_repo(void);

/// @defgroup test_get_repository_status_propagates_non_404_http_exception "test_get_repository_status_propagates_non_404_http_exception"
/// @{
/// @brief Ensure HTTP exceptions other than 404 are not masked.
/// @post Raised exception preserves original status and detail.
/// @pre GitService.get_status raises HTTPException with non-404 status.
/// @}
void test_get_repository_status_propagates_non_404_http_exception(void);

/// @defgroup test_get_repository_diff_propagates_http_exception "test_get_repository_diff_propagates_http_exception"
/// @{
/// @brief Ensure diff endpoint preserves domain HTTP errors from GitService.
/// @post Endpoint raises same HTTPException values.
/// @pre GitService.get_diff raises HTTPException.
/// @}
void test_get_repository_diff_propagates_http_exception(void);

/// @defgroup test_get_history_wraps_unexpected_error_as_500 "test_get_history_wraps_unexpected_error_as_500"
/// @{
/// @brief Ensure non-HTTP exceptions in history endpoint become deterministic 500 errors.
/// @post Endpoint returns HTTPException with status 500 and route context.
/// @pre GitService.get_commit_history raises ValueError.
/// @}
void test_get_history_wraps_unexpected_error_as_500(void);

/// @defgroup test_commit_changes_wraps_unexpected_error_as_500 "test_commit_changes_wraps_unexpected_error_as_500"
/// @{
/// @brief Ensure commit endpoint does not leak unexpected errors as 400.
/// @post Endpoint raises HTTPException(500) with route context.
/// @pre GitService.commit_changes raises RuntimeError.
/// @}
void test_commit_changes_wraps_unexpected_error_as_500(void);

/// @defgroup test_get_repository_status_batch_returns_mixed_statuses "test_get_repository_status_batch_returns_mixed_statuses"
/// @{
/// @brief Ensure batch endpoint returns per-dashboard statuses in one response.
/// @post Returned map includes resolved status for each requested dashboard ID.
/// @pre Some repositories are missing and some are initialized.
/// @}
void test_get_repository_status_batch_returns_mixed_statuses(void);

/// @defgroup test_get_repository_status_batch_marks_item_as_error_on_service_failure "test_get_repository_status_batch_marks_item_as_error_on_service_failure"
/// @{
/// @brief Ensure batch endpoint marks failed items as ERROR without failing entire request.
/// @post Failed dashboard status is marked as ERROR.
/// @pre GitService raises non-HTTP exception for one dashboard.
/// @}
void test_get_repository_status_batch_marks_item_as_error_on_service_failure(void);

/// @defgroup test_get_repository_status_batch_deduplicates_and_truncates_ids "test_get_repository_status_batch_deduplicates_and_truncates_ids"
/// @{
/// @brief Ensure batch endpoint protects server from oversized payloads.
/// @post Result contains unique IDs up to configured cap.
/// @pre request includes duplicate IDs and more than MAX_REPOSITORY_STATUS_BATCH entries.
/// @}
void test_get_repository_status_batch_deduplicates_and_truncates_ids(void);

/// @defgroup test_commit_changes_applies_profile_identity_before_commit "test_commit_changes_applies_profile_identity_before_commit"
/// @{
/// @brief Ensure commit route configures repository identity from profile preferences before commit call.
/// @post git_service.configure_identity receives resolved identity and commit proceeds.
/// @pre Profile preference contains git_username/git_email for current user.
/// @}
void test_commit_changes_applies_profile_identity_before_commit(void);

/// @defgroup test_pull_changes_applies_profile_identity_before_pull "test_pull_changes_applies_profile_identity_before_pull"
/// @{
/// @brief Ensure pull route configures repository identity from profile preferences before pull call.
/// @post git_service.configure_identity receives resolved identity and pull proceeds.
/// @pre Profile preference contains git_username/git_email for current user.
/// @}
void test_pull_changes_applies_profile_identity_before_pull(void);

/// @defgroup test_get_merge_status_returns_service_payload "test_get_merge_status_returns_service_payload"
/// @{
/// @brief Ensure merge status route returns service payload as-is.
/// @post Route response contains has_unfinished_merge=True.
/// @pre git_service.get_merge_status returns unfinished merge payload.
/// @}
void test_get_merge_status_returns_service_payload(void);

/// @defgroup test_resolve_merge_conflicts_passes_resolution_items_to_service "test_resolve_merge_conflicts_passes_resolution_items_to_service"
/// @{
/// @brief Ensure merge resolve route forwards parsed resolutions to service.
/// @post Service receives normalized list and route returns resolved files.
/// @pre resolve_data has one file strategy.
/// @}
void test_resolve_merge_conflicts_passes_resolution_items_to_service(void);

/// @defgroup test_abort_merge_calls_service_and_returns_result "test_abort_merge_calls_service_and_returns_result"
/// @{
/// @brief Ensure abort route delegates to service.
/// @post Route returns aborted status.
/// @pre Service abort_merge returns aborted status.
/// @}
void test_abort_merge_calls_service_and_returns_result(void);

/// @defgroup test_continue_merge_passes_message_and_returns_commit "test_continue_merge_passes_message_and_returns_commit"
/// @{
/// @brief Ensure continue route passes commit message to service.
/// @post Route returns committed status and hash.
/// @pre continue_data.message is provided.
/// @}
void test_continue_merge_passes_message_and_returns_commit(void);

/// @defgroup TestMigrationRoutes "TestMigrationRoutes"
/// @{
/// @brief Unit tests for migration API route handlers.
/// @}
void TestMigrationRoutes(void);

/// @defgroup _mock_env "_mock_env"
/// @{
/// @}
void _mock_env(void);

/// @defgroup _make_sync_config_manager "_make_sync_config_manager"
/// @{
/// @}
void _make_sync_config_manager(void);

/// @defgroup TestProfileApi "TestProfileApi"
/// @{
/// @brief Verifies profile API route contracts for preference read/update and Superset account lookup.
/// @}
void TestProfileApi(void);

/// @defgroup mock_profile_route_dependencies "mock_profile_route_dependencies"
/// @{
/// @brief Provides deterministic dependency overrides for profile route tests.
/// @post Dependencies are overridden for current test and restored afterward.
/// @pre App instance is initialized.
/// @}
void mock_profile_route_dependencies(void);

/// @defgroup profile_route_deps_fixture "profile_route_deps_fixture"
/// @{
/// @brief Pytest fixture wrapper for profile route dependency overrides.
/// @post Yields overridden dependencies and clears overrides after test.
/// @pre None.
/// @}
void profile_route_deps_fixture(void);

/// @defgroup _build_preference_response "_build_preference_response"
/// @{
/// @brief Builds stable profile preference response payload for route tests.
/// @post Returns ProfilePreferenceResponse object with deterministic timestamps.
/// @pre user_id is provided.
/// @}
void _build_preference_response(void);

/// @defgroup test_get_profile_preferences_returns_self_payload "test_get_profile_preferences_returns_self_payload"
/// @{
/// @brief Verifies GET /api/profile/preferences returns stable self-scoped payload.
/// @post Response status is 200 and payload contains current user preference.
/// @pre Authenticated user context is available.
/// @}
void test_get_profile_preferences_returns_self_payload(void);

/// @defgroup test_patch_profile_preferences_success "test_patch_profile_preferences_success"
/// @{
/// @brief Verifies PATCH /api/profile/preferences persists valid payload through route mapping.
/// @post Response status is 200 with saved preference payload.
/// @pre Valid request payload and authenticated user.
/// @}
void test_patch_profile_preferences_success(void);

/// @defgroup test_patch_profile_preferences_validation_error "test_patch_profile_preferences_validation_error"
/// @{
/// @brief Verifies route maps domain validation failure to HTTP 422 with actionable details.
/// @post Response status is 422 and includes validation messages.
/// @pre Service raises ProfileValidationError.
/// @}
void test_patch_profile_preferences_validation_error(void);

/// @defgroup test_patch_profile_preferences_cross_user_denied "test_patch_profile_preferences_cross_user_denied"
/// @{
/// @brief Verifies route maps domain authorization guard failure to HTTP 403.
/// @post Response status is 403 with denial message.
/// @pre Service raises ProfileAuthorizationError.
/// @}
void test_patch_profile_preferences_cross_user_denied(void);

/// @defgroup test_lookup_superset_accounts_success "test_lookup_superset_accounts_success"
/// @{
/// @brief Verifies lookup route returns success payload with normalized candidates.
/// @post Response status is 200 and items list is returned.
/// @pre Valid environment_id and service success response.
/// @}
void test_lookup_superset_accounts_success(void);

/// @defgroup test_lookup_superset_accounts_env_not_found "test_lookup_superset_accounts_env_not_found"
/// @{
/// @brief Verifies lookup route maps missing environment to HTTP 404.
/// @post Response status is 404 with explicit message.
/// @pre Service raises EnvironmentNotFoundError.
/// @}
void test_lookup_superset_accounts_env_not_found(void);

/// @defgroup TestReportsApi "TestReportsApi"
/// @{
/// @brief Contract tests for GET /api/reports defaults, pagination, and filtering behavior.
/// @invariant API response contract contains {items,total,page,page_size,has_next,applied_filters}.
/// @}
void TestReportsApi(void);

/// @defgroup _make_task "_make_task"
/// @{
/// @brief Build Task fixture with controlled timestamps/status for reports list/detail normalization.
/// @}
void _make_task(void);

/// @defgroup test_get_reports_default_pagination_contract "test_get_reports_default_pagination_contract"
/// @{
/// @brief Validate reports list endpoint default pagination and contract keys for mixed task statuses.
/// @}
void test_get_reports_default_pagination_contract(void);

/// @defgroup test_get_reports_filter_and_pagination "test_get_reports_filter_and_pagination"
/// @{
/// @brief Validate reports list endpoint applies task-type/status filters and pagination boundaries.
/// @}
void test_get_reports_filter_and_pagination(void);

/// @defgroup test_get_reports_handles_mixed_naive_and_aware_datetimes "test_get_reports_handles_mixed_naive_and_aware_datetimes"
/// @{
/// @brief Validate reports sorting remains stable when task timestamps mix naive and timezone-aware datetimes.
/// @}
void test_get_reports_handles_mixed_naive_and_aware_datetimes(void);

/// @defgroup test_get_reports_invalid_filter_returns_400 "test_get_reports_invalid_filter_returns_400"
/// @{
/// @brief Validate reports list endpoint rejects unsupported task type filters with HTTP 400.
/// @}
void test_get_reports_invalid_filter_returns_400(void);

/// @defgroup TestReportsDetailApi "TestReportsDetailApi"
/// @{
/// @brief Contract tests for GET /api/reports/{report_id} detail endpoint behavior.
/// @invariant Detail endpoint tests must keep deterministic assertions for success and not-found contracts.
/// @}
void TestReportsDetailApi(void);

/// @defgroup test_get_report_detail_success "test_get_report_detail_success"
/// @{
/// @brief Validate report detail endpoint returns report body with diagnostics and next actions for existing task.
/// @}
void test_get_report_detail_success(void);

/// @defgroup test_get_report_detail_not_found "test_get_report_detail_not_found"
/// @{
/// @brief Validate report detail endpoint returns 404 when requested report identifier is absent.
/// @}
void test_get_report_detail_not_found(void);

/// @defgroup TestReportsOpenapiConformance "TestReportsOpenapiConformance"
/// @{
/// @brief Validate implemented reports payload shape against OpenAPI-required top-level contract fields.
/// @invariant List and detail payloads include required contract keys.
/// @}
void TestReportsOpenapiConformance(void);

/// @defgroup _FakeTaskManager "_FakeTaskManager"
/// @{
/// @brief Minimal task-manager fake exposing static task list for OpenAPI conformance checks.
/// @invariant get_all_tasks returns seeded tasks unchanged.
/// @}
void _FakeTaskManager(void);

/// @defgroup _admin_user "_admin_user"
/// @{
/// @brief Provide admin principal fixture required by reports routes in conformance tests.
/// @}
void _admin_user(void);

/// @defgroup _task "_task"
/// @{
/// @brief Construct deterministic task fixture consumed by reports list/detail payload assertions.
/// @}
void _task(void);

/// @defgroup test_reports_list_openapi_required_keys "test_reports_list_openapi_required_keys"
/// @{
/// @brief Verify reports list endpoint includes all required OpenAPI top-level keys.
/// @}
void test_reports_list_openapi_required_keys(void);

/// @defgroup test_reports_detail_openapi_required_keys "test_reports_detail_openapi_required_keys"
/// @{
/// @brief Verify reports detail endpoint returns payload containing the report object key.
/// @}
void test_reports_detail_openapi_required_keys(void);

/// @defgroup test_tasks_logs_module "test_tasks_logs_module"
/// @{
/// @brief Contract testing for task logs API endpoints.
/// @}
void test_tasks_logs_module(void);

/// @defgroup test_get_task_logs_success "test_get_task_logs_success"
/// @{
/// @brief Validate task logs endpoint returns filtered logs for an existing task.
/// @}
void test_get_task_logs_success(void);

/// @defgroup test_get_task_logs_not_found "test_get_task_logs_not_found"
/// @{
/// @brief Validate task logs endpoint returns 404 when the task identifier is missing.
/// @}
void test_get_task_logs_not_found(void);

/// @defgroup test_get_task_logs_invalid_limit "test_get_task_logs_invalid_limit"
/// @{
/// @brief Validate task logs endpoint enforces query validation for limit lower bound.
/// @}
void test_get_task_logs_invalid_limit(void);

/// @defgroup test_get_task_log_stats_success "test_get_task_log_stats_success"
/// @{
/// @brief Validate log stats endpoint returns success payload for an existing task.
/// @}
void test_get_task_log_stats_success(void);

/// @defgroup AdminApi "AdminApi"
/// @{
/// @brief Admin API endpoints for user and role management.
/// @invariant All endpoints in this module require 'Admin' role or 'admin' scope.
/// @}
void AdminApi(void);

/// @defgroup list_users "list_users"
/// @{
/// @brief Lists all registered users.
/// @post Returns a list of UserSchema objects.
/// @pre Current user has 'Admin' role.
/// @}
void list_users(void);

/// @defgroup create_user "create_user"
/// @{
/// @brief Creates a new local user.
/// @post New user is created in the database.
/// @pre Current user has 'Admin' role.
/// @}
void create_user(void);

/// @defgroup update_user "update_user"
/// @{
/// @brief Updates an existing user.
/// @post User record is updated in the database.
/// @pre Current user has 'Admin' role.
/// @}
void update_user(void);

/// @defgroup delete_user "delete_user"
/// @{
/// @brief Deletes a user.
/// @post User record is removed from the database.
/// @pre Current user has 'Admin' role.
/// @}
void delete_user(void);

/// @defgroup list_roles "list_roles"
/// @{
/// @brief Lists all available roles.
/// @}
void list_roles(void);

/// @defgroup create_role "create_role"
/// @{
/// @brief Creates a new system role with associated permissions.
/// @post New Role record is created in auth.db.
/// @pre Role name must be unique.
/// @}
void create_role(void);

/// @defgroup update_role "update_role"
/// @{
/// @brief Updates an existing role's metadata and permissions.
/// @post Role record is updated in auth.db.
/// @pre role_id must be a valid existing role UUID.
/// @}
void update_role(void);

/// @defgroup delete_role "delete_role"
/// @{
/// @brief Removes a role from the system.
/// @post Role record is removed from auth.db.
/// @pre role_id must be a valid existing role UUID.
/// @}
void delete_role(void);

/// @defgroup list_ad_mappings "list_ad_mappings"
/// @{
/// @brief Lists all AD Group to Role mappings.
/// @}
void list_ad_mappings(void);

/// @defgroup create_ad_mapping "create_ad_mapping"
/// @{
/// @brief Creates a new AD Group mapping.
/// @}
void create_ad_mapping(void);

/// @defgroup AdminApiKeyRoutes "AdminApiKeyRoutes"
/// @{
/// @brief Admin API endpoints for API key management — list, generate (one-time reveal), and revoke.
/// @invariant DELETE /api/admin/api-keys/{id} soft-deletes (active=False), preserves row for audit.
/// @}
void AdminApiKeyRoutes(void);

/// @defgroup ApiKeyCreateRequest "ApiKeyCreateRequest"
/// @{
/// @}
void ApiKeyCreateRequest(void);

/// @defgroup ApiKeyCreateResponse "ApiKeyCreateResponse"
/// @{
/// @}
void ApiKeyCreateResponse(void);

/// @defgroup ApiKeyListItem "ApiKeyListItem"
/// @{
/// @}
void ApiKeyListItem(void);

/// @defgroup ApiKeyRevokeResponse "ApiKeyRevokeResponse"
/// @{
/// @}
void ApiKeyRevokeResponse(void);

/// @defgroup list_api_keys "list_api_keys"
/// @{
/// @brief List all API keys — NEVER returns key_hash or raw_key.
/// @post Returns list of ApiKeyListItem without sensitive fields.
/// @pre Requires admin:settings WRITE permission.
/// @}
void list_api_keys(void);

/// @defgroup create_api_key "create_api_key"
/// @{
/// @brief Generate a new API key — returns raw key ONCE, never stored or retrievable again.
/// @post Creates APIKey row with SHA-256 hash. Returns raw key in response.
/// @pre Requires admin:settings WRITE permission. name is required, at least one permission.
/// @}
void create_api_key(void);

/// @defgroup revoke_api_key "revoke_api_key"
/// @{
/// @brief Revoke an API key by setting active=False. Preserves row for audit.
/// @post Sets active=False on the key. Returns 404 if already revoked or not found.
/// @pre Requires admin:settings WRITE permission.
/// @}
void revoke_api_key(void);

/// @defgroup AssistantAdminRoutes "AssistantAdminRoutes"
/// @{
/// @brief FastAPI route handlers for assistant admin operations — conversation listing, deletion, history, audit.
/// @invariant Audit endpoint requires tasks:READ permission.
/// @}
void AssistantAdminRoutes(void);

/// @defgroup list_conversations "list_conversations"
/// @{
/// @brief Return paginated conversation list for current user with archived flag and last message preview.
/// @post Conversations are grouped by conversation_id sorted by latest activity descending.
/// @pre Authenticated user context and valid pagination params.
/// @}
void list_conversations(void);

/// @defgroup delete_conversation "delete_conversation"
/// @{
/// @brief Soft-delete or hard-delete a conversation and clear its in-memory trace.
/// @post Conversation records are removed from DB and CONVERSATIONS cache.
/// @pre conversation_id belongs to current_user.
/// @}
void delete_conversation(void);

/// @defgroup get_history "get_history"
/// @{
/// @brief Retrieve paginated assistant conversation history for current user.
/// @post Returns persistent messages and mirrored in-memory snapshot for diagnostics.
/// @pre Authenticated user is available and page params are valid.
/// @}
void get_history(void);

/// @defgroup get_assistant_audit "get_assistant_audit"
/// @{
/// @brief Return assistant audit decisions for current user from persistent and in-memory stores.
/// @post Audit payload is returned in reverse chronological order from DB.
/// @pre User has tasks:READ permission.
/// @}
void get_assistant_audit(void);

/// @defgroup AssistantCommandParser "AssistantCommandParser"
/// @{
/// @brief Deterministic RU/EN command text parser that converts user messages into intent payloads.
/// @invariant Every return path includes domain, operation, entities, confidence, risk_level, requires_confirmation.
/// @}
void AssistantCommandParser(void);

/// @defgroup _parse_command "_parse_command"
/// @{
/// @brief Deterministically parse RU/EN command text into intent payload.
/// @invariant every return path includes domain, operation, entities, confidence, risk_level, requires_confirmation.
/// @post Returns intent dict with domain/operation/entities/confidence/risk fields.
/// @pre message contains raw user text and config manager resolves environments.
/// @}
void _parse_command(void);

/// @defgroup AssistantDatasetReview "AssistantDatasetReview"
/// @{
/// @brief Dataset review context loading and intent planning for the assistant API.
/// @invariant Dataset review operations are always scoped to the owner's session.
/// @}
void AssistantDatasetReview(void);

/// @defgroup _serialize_dataset_review_context "_serialize_dataset_review_context"
/// @{
/// @brief Build assistant-safe dataset-review context snapshot with masked imported-filter payloads for session-scoped assistant routing.
/// @post Returns a serializable dictionary containing the complete review context.
/// @pre session_id is a valid active review session identifier.
/// @}
void _serialize_dataset_review_context(void);

/// @defgroup _load_dataset_review_context "_load_dataset_review_context"
/// @{
/// @brief Load owner-scoped dataset-review context for assistant planning and grounded response generation.
/// @post Returns a loaded context object with session data and findings.
/// @pre session_id is a valid active review session identifier.
/// @}
void _load_dataset_review_context(void);

/// @defgroup _extract_dataset_review_target "_extract_dataset_review_target"
/// @{
/// @brief Extract structured dataset-review focus target hints embedded in assistant prompts.
/// @}
void _extract_dataset_review_target(void);

/// @defgroup _match_dataset_review_field "_match_dataset_review_field"
/// @{
/// @brief Resolve one semantic field from assistant-visible context by id or user-visible label.
/// @}
void _match_dataset_review_field(void);

/// @defgroup _extract_quoted_segment "_extract_quoted_segment"
/// @{
/// @brief Extract one quoted assistant command segment after a label token.
/// @}
void _extract_quoted_segment(void);

/// @defgroup _plan_dataset_review_intent "_plan_dataset_review_intent"
/// @{
/// @brief Parse session-scoped dataset-review assistant commands before falling back to generic assistant tool routing.
/// @}
void _plan_dataset_review_intent(void);

/// @defgroup AssistantDatasetReviewDispatch "AssistantDatasetReviewDispatch"
/// @{
/// @brief Dispatch and confirmation handling for dataset-review assistant intents.
/// @invariant Dataset review dispatch requires valid session version for write operations.
/// @}
void AssistantDatasetReviewDispatch(void);

/// @defgroup _dataset_review_conflict_http_exception "_dataset_review_conflict_http_exception"
/// @{
/// @brief Convert dataset-review optimistic-lock conflicts into shared 409 assistant semantics.
/// @}
void _dataset_review_conflict_http_exception(void);

/// @defgroup _dispatch_dataset_review_intent "_dispatch_dataset_review_intent"
/// @{
/// @brief Route confirmed dataset-review assistant intents through existing backend dataset-review APIs and orchestration boundaries.
/// @post Returns a structured response with planned actions and confirmations.
/// @pre context contains valid session data and user intent.
/// @}
void _dispatch_dataset_review_intent(void);

/// @defgroup AssistantDispatch "AssistantDispatch"
/// @{
/// @brief Intent dispatch engine, confirmation summary, and clarification text for the assistant API.
/// @invariant Unsupported operations are rejected via HTTPException(400).
/// @}
void AssistantDispatch(void);

/// @defgroup _clarification_text_for_intent "_clarification_text_for_intent"
/// @{
/// @brief Convert technical missing-parameter errors into user-facing clarification prompts.
/// @post Returned text is human-readable and actionable for target operation.
/// @pre state was classified as needs_clarification for current intent/error combination.
/// @}
void _clarification_text_for_intent(void);

/// @defgroup _async_confirmation_summary "_async_confirmation_summary"
/// @{
/// @brief Build human-readable confirmation prompt for an intent before execution.
/// @post Returns a formatted summary string suitable for display to the user.
/// @pre actions is a non-empty list of planned review actions.
/// @}
void _async_confirmation_summary(void);

/// @defgroup _dispatch_intent "_dispatch_intent"
/// @{
/// @brief Execute parsed assistant intent via existing task/plugin/git services.
/// @invariant unsupported operations are rejected via HTTPException(400).
/// @post Returns response text, optional task id, and UI actions for follow-up.
/// @pre intent operation is known and actor permissions are validated per operation.
/// @}
void _dispatch_intent(void);

/// @defgroup AssistantHistory "AssistantHistory"
/// @{
/// @brief Conversation history, audit trail, and confirmation persistence helpers for the assistant API.
/// @invariant Failed persistence attempts always rollback before returning.
/// @}
void AssistantHistory(void);

/// @defgroup _append_history "_append_history"
/// @{
/// @brief Append conversation message to in-memory history buffer.
/// @invariant every appended entry includes generated message_id and created_at timestamp.
/// @post Message entry is appended to CONVERSATIONS key list.
/// @pre user_id and conversation_id identify target conversation bucket.
/// @}
void _append_history(void);

/// @defgroup _persist_message "_persist_message"
/// @{
/// @brief Persist assistant/user message record to database.
/// @invariant failed persistence attempts always rollback before returning.
/// @post Message row is committed or persistence failure is logged.
/// @pre db session is writable and message payload is serializable.
/// @}
void _persist_message(void);

/// @defgroup _audit "_audit"
/// @{
/// @brief Append in-memory audit record for assistant decision trace.
/// @invariant persisted in-memory audit entry always contains created_at in ISO format.
/// @post ASSISTANT_AUDIT list for user contains new timestamped entry.
/// @pre payload describes decision/outcome fields.
/// @}
void _audit(void);

/// @defgroup _persist_audit "_persist_audit"
/// @{
/// @brief Persist structured assistant audit payload in database.
/// @post Audit row is committed or failure is logged with rollback.
/// @pre db session is writable and payload is JSON-serializable.
/// @}
void _persist_audit(void);

/// @defgroup _persist_confirmation "_persist_confirmation"
/// @{
/// @brief Persist confirmation token record to database.
/// @post Confirmation row exists in persistent storage.
/// @pre record contains id/user/intent/dispatch/expiry fields.
/// @}
void _persist_confirmation(void);

/// @defgroup _update_confirmation_state "_update_confirmation_state"
/// @{
/// @brief Update persistent confirmation token lifecycle state.
/// @post State and consumed_at fields are updated when applicable.
/// @pre confirmation_id references existing row.
/// @}
void _update_confirmation_state(void);

/// @defgroup _load_confirmation_from_db "_load_confirmation_from_db"
/// @{
/// @brief Load confirmation token from database into in-memory model.
/// @post Returns ConfirmationRecord when found, otherwise None.
/// @pre confirmation_id may or may not exist in storage.
/// @}
void _load_confirmation_from_db(void);

/// @defgroup _ensure_conversation "_ensure_conversation"
/// @{
/// @brief Resolve active conversation id in memory or create a new one.
/// @post Returns stable conversation id and updates USER_ACTIVE_CONVERSATION.
/// @pre user_id identifies current actor.
/// @}
void _ensure_conversation(void);

/// @defgroup _resolve_or_create_conversation "_resolve_or_create_conversation"
/// @{
/// @brief Resolve active conversation using explicit id, memory cache, or persisted history.
/// @post Returns conversation id and updates USER_ACTIVE_CONVERSATION cache.
/// @pre user_id and db session are available.
/// @}
void _resolve_or_create_conversation(void);

/// @defgroup _cleanup_history_ttl "_cleanup_history_ttl"
/// @{
/// @brief Enforce assistant message retention window by deleting expired rows and in-memory records.
/// @post Messages older than ASSISTANT_MESSAGE_TTL_DAYS are removed from persistence and memory mirrors.
/// @pre db session is available and user_id references current actor scope.
/// @}
void _cleanup_history_ttl(void);

/// @defgroup _is_conversation_archived "_is_conversation_archived"
/// @{
/// @brief Determine archived state for a conversation based on last update timestamp.
/// @post Returns True when conversation inactivity exceeds archive threshold.
/// @pre updated_at can be null for empty conversations.
/// @}
void _is_conversation_archived(void);

/// @defgroup _coerce_query_bool "_coerce_query_bool"
/// @{
/// @brief Normalize bool-like query values for compatibility in direct handler invocations/tests.
/// @post Returns deterministic boolean flag.
/// @pre value may be bool, string, or FastAPI Query metadata object.
/// @}
void _coerce_query_bool(void);

/// @defgroup AssistantLlmPlanner "AssistantLlmPlanner"
/// @{
/// @brief LLM-based intent planning, tool catalog construction, and authorization for the assistant API.
/// @invariant Tool catalog is filtered by user permissions before being sent to LLM.
/// @post LLM tool catalog filtered and returned
/// @pre Assistant routes initialized, user authenticated
/// @}
void AssistantLlmPlanner(void);

/// @defgroup _check_any_permission "_check_any_permission"
/// @{
/// @brief Validate user against alternative permission checks (logical OR).
/// @post Returns on first successful permission; raises 403-like HTTPException otherwise.
/// @pre checks list contains resource-action tuples.
/// @}
void _check_any_permission(void);

/// @defgroup _has_any_permission "_has_any_permission"
/// @{
/// @brief Check whether user has at least one permission tuple from the provided list.
/// @post Returns True when at least one permission check passes.
/// @pre current_user and checks list are valid.
/// @}
void _has_any_permission(void);

/// @defgroup _build_tool_catalog "_build_tool_catalog"
/// @{
/// @brief Build current-user tool catalog for LLM planner with operation contracts and defaults.
/// @post Returns list of executable tools filtered by permission and runtime availability.
/// @pre current_user is authenticated; config/db are available.
/// @}
void _build_tool_catalog(void);

/// @defgroup _coerce_intent_entities "_coerce_intent_entities"
/// @{
/// @brief Normalize intent entity value types from LLM output to route-compatible values.
/// @post Returned intent has numeric ids coerced where possible and string values stripped.
/// @pre intent contains entities dict or missing entities.
/// @}
void _coerce_intent_entities(void);

/// @defgroup AssistantLlmPlannerIntent "AssistantLlmPlannerIntent"
/// @{
/// @brief LLM-based intent planning and authorization for the assistant API — separated from tool catalog.
/// @invariant Production deployments always require confirmation.
/// @post Intent planning registered with confirmation gate
/// @pre Assistant routes initialized, user authenticated
/// @}
void AssistantLlmPlannerIntent(void);

/// @defgroup _plan_intent_with_llm "_plan_intent_with_llm"
/// @{
/// @brief Use active LLM provider to select best tool/operation from dynamic catalog.
/// @post Returns normalized intent dict when planning succeeds; otherwise None.
/// @pre tools list contains allowed operations for current user.
/// @}
void _plan_intent_with_llm(void);

/// @defgroup _authorize_intent "_authorize_intent"
/// @{
/// @brief Validate user permissions for parsed intent before confirmation/dispatch.
/// @post Returns if authorized; raises HTTPException(403) when denied.
/// @pre intent.operation is present for known assistant command domains.
/// @}
void _authorize_intent(void);

/// @defgroup AssistantResolvers "AssistantResolvers"
/// @{
/// @brief Environment, dashboard, provider, and task resolution utilities for the assistant API.
/// @invariant Resolution functions never raise; they return None on failure.
/// @}
void AssistantResolvers(void);

/// @defgroup _extract_id "_extract_id"
/// @{
/// @brief Extract first regex match group from text by ordered pattern list.
/// @post Returns first matched token or None.
/// @pre patterns contain at least one capture group.
/// @}
void _extract_id(void);

/// @defgroup _resolve_env_id "_resolve_env_id"
/// @{
/// @brief Resolve environment identifier/name token to canonical environment id.
/// @post Returns matched environment id or None.
/// @pre config_manager provides environment list.
/// @}
void _resolve_env_id(void);

/// @defgroup _is_production_env "_is_production_env"
/// @{
/// @brief Determine whether environment token resolves to production-like target.
/// @post Returns True for production/prod synonyms, else False.
/// @pre config_manager provides environments or token text is provided.
/// @}
void _is_production_env(void);

/// @defgroup _resolve_provider_id "_resolve_provider_id"
/// @{
/// @brief Resolve provider token to provider id with active/default fallback.
/// @post Returns provider id or None when no providers configured.
/// @pre db session can load provider list through LLMProviderService.
/// @}
void _resolve_provider_id(void);

/// @defgroup _get_default_environment_id "_get_default_environment_id"
/// @{
/// @brief Resolve default environment id from settings or first configured environment.
/// @post Returns default environment id or None when environment list is empty.
/// @pre config_manager returns environments list.
/// @}
void _get_default_environment_id(void);

/// @defgroup _resolve_dashboard_id_by_ref "_resolve_dashboard_id_by_ref"
/// @{
/// @brief Resolve dashboard id by title or slug reference in selected environment.
/// @post Returns dashboard id when uniquely matched, otherwise None.
/// @pre dashboard_ref is a non-empty string-like token.
/// @}
void _resolve_dashboard_id_by_ref(void);

/// @defgroup _resolve_dashboard_id_entity "_resolve_dashboard_id_entity"
/// @{
/// @brief Resolve dashboard id from intent entities using numeric id or dashboard_ref fallback.
/// @post Returns resolved dashboard id or None when ambiguous/unresolvable.
/// @pre entities may contain dashboard_id as int/str and optional dashboard_ref.
/// @}
void _resolve_dashboard_id_entity(void);

/// @defgroup _get_environment_name_by_id "_get_environment_name_by_id"
/// @{
/// @brief Resolve human-readable environment name by id.
/// @post Returns matching environment name or fallback id.
/// @pre environment id may be None.
/// @}
void _get_environment_name_by_id(void);

/// @defgroup _extract_result_deep_links "_extract_result_deep_links"
/// @{
/// @brief Build deep-link actions to verify task result from assistant chat.
/// @post Returns zero or more assistant actions for dashboard open/diff.
/// @pre task object is available.
/// @}
void _extract_result_deep_links(void);

/// @defgroup _build_task_observability_summary "_build_task_observability_summary"
/// @{
/// @brief Build compact textual summary for completed tasks to reduce "black box" effect.
/// @post Returns non-empty summary line for known task types or empty string fallback.
/// @pre task may contain plugin-specific result payload.
/// @}
void _build_task_observability_summary(void);

/// @defgroup AssistantRoutes "AssistantRoutes"
/// @{
/// @brief FastAPI route handlers for the assistant API — message sending, confirmation, conversation management.
/// @invariant Risky operations are never executed without valid confirmation token.
/// @}
void AssistantRoutes(void);

/// @defgroup send_message "send_message"
/// @{
/// @brief Parse assistant command, enforce safety gates, and dispatch executable intent.
/// @invariant non-safe operations are gated with confirmation before execution from this endpoint.
/// @post Response state is one of clarification/confirmation/started/success/denied/failed.
/// @pre Authenticated user is available and message text is non-empty.
/// @}
void send_message(void);

/// @defgroup confirm_operation "confirm_operation"
/// @{
/// @brief Execute previously requested risky operation after explicit user confirmation.
/// @post Confirmation state becomes consumed and operation result is persisted in history.
/// @pre confirmation_id exists, belongs to current user, is pending, and not expired.
/// @}
void confirm_operation(void);

/// @defgroup cancel_operation "cancel_operation"
/// @{
/// @brief Cancel pending risky operation and mark confirmation token as cancelled.
/// @post Confirmation becomes cancelled and cannot be executed anymore.
/// @pre confirmation_id exists, belongs to current user, and is still pending.
/// @}
void cancel_operation(void);

/// @defgroup AssistantSchemas "AssistantSchemas"
/// @{
/// @brief Pydantic models, in-memory stores, and permission mappings for the assistant API.
/// @invariant In-memory stores are module-level singletons shared across the assistant package.
/// @}
void AssistantSchemas(void);

/// @defgroup AssistantMessageRequest "AssistantMessageRequest"
/// @{
/// @brief Input payload for assistant message endpoint.
/// @invariant message is always non-empty and no longer than 4000 characters.
/// @post Request object provides message text and optional conversation binding.
/// @pre message length is within accepted bounds.
/// @}
void AssistantMessageRequest(void);

/// @defgroup AssistantAction "AssistantAction"
/// @{
/// @brief UI action descriptor returned with assistant responses.
/// @invariant type and label are required for every UI action.
/// @post Action can be rendered as button on frontend.
/// @pre type and label are provided by orchestration logic.
/// @}
void AssistantAction(void);

/// @defgroup AssistantMessageResponse "AssistantMessageResponse"
/// @{
/// @brief Output payload contract for assistant interaction endpoints.
/// @invariant created_at and state are always present in endpoint responses.
/// @post Payload may include task_id/confirmation_id/actions for UI follow-up.
/// @pre Response includes deterministic state and text.
/// @}
void AssistantMessageResponse(void);

/// @defgroup ConfirmationRecord "ConfirmationRecord"
/// @{
/// @brief In-memory confirmation token model for risky operation dispatch.
/// @invariant state defaults to "pending" and expires_at bounds confirmation validity.
/// @post Record tracks lifecycle state and expiry timestamp.
/// @pre intent/dispatch/user_id are populated at confirmation request time.
/// @}
void ConfirmationRecord(void);

/// @defgroup CONVERSATIONS "CONVERSATIONS"
/// @{
/// @brief In-memory conversation history store: {(user_id, conversation_id) -> [message_records]}
/// @}
void CONVERSATIONS(void);

/// @defgroup ASSISTANT_AUDIT "ASSISTANT_AUDIT"
/// @{
/// @brief In-memory assistant audit trail: {user_id -> [audit_records]}. Volatile — lost on restart.
/// @}
void ASSISTANT_AUDIT(void);

/// @defgroup CleanReleaseApi "CleanReleaseApi"
/// @{
/// @brief Expose clean release endpoints for candidate preparation and subsequent compliance flow.
/// @invariant API never reports prepared status if preparation errors are present.
/// @post Candidate preparation, manifest, and compliance routes expose deterministic API payloads without reporting prepared state on failed preparation.
/// @pre Clean release repository and preparation service dependencies are configured for the current request scope.
/// @}
void CleanReleaseApi(void);

/// @defgroup PrepareCandidateRequest "PrepareCandidateRequest"
/// @{
/// @brief Request schema for candidate preparation endpoint.
/// @}
void PrepareCandidateRequest(void);

/// @defgroup StartCheckRequest "StartCheckRequest"
/// @{
/// @brief Request schema for clean compliance check run startup.
/// @}
void StartCheckRequest(void);

/// @defgroup RegisterCandidateRequest "RegisterCandidateRequest"
/// @{
/// @brief Request schema for candidate registration endpoint.
/// @}
void RegisterCandidateRequest(void);

/// @defgroup ImportArtifactsRequest "ImportArtifactsRequest"
/// @{
/// @brief Request schema for candidate artifact import endpoint.
/// @}
void ImportArtifactsRequest(void);

/// @defgroup BuildManifestRequest "BuildManifestRequest"
/// @{
/// @brief Request schema for manifest build endpoint.
/// @}
void BuildManifestRequest(void);

/// @defgroup CreateComplianceRunRequest "CreateComplianceRunRequest"
/// @{
/// @brief Request schema for compliance run creation with optional manifest pinning.
/// @}
void CreateComplianceRunRequest(void);

/// @defgroup register_candidate_v2_endpoint "register_candidate_v2_endpoint"
/// @{
/// @brief Register a clean-release candidate for headless lifecycle.
/// @post Candidate is persisted in DRAFT status.
/// @pre Candidate identifier is unique.
/// @}
void register_candidate_v2_endpoint(void);

/// @defgroup import_candidate_artifacts_v2_endpoint "import_candidate_artifacts_v2_endpoint"
/// @{
/// @brief Import candidate artifacts in headless flow.
/// @post Artifacts are persisted and candidate advances to PREPARED if it was DRAFT.
/// @pre Candidate exists and artifacts array is non-empty.
/// @}
void import_candidate_artifacts_v2_endpoint(void);

/// @defgroup build_candidate_manifest_v2_endpoint "build_candidate_manifest_v2_endpoint"
/// @{
/// @brief Build immutable manifest snapshot for prepared candidate.
/// @post Returns created ManifestDTO with incremented version.
/// @pre Candidate exists and has imported artifacts.
/// @}
void build_candidate_manifest_v2_endpoint(void);

/// @defgroup get_candidate_overview_v2_endpoint "get_candidate_overview_v2_endpoint"
/// @{
/// @brief Return expanded candidate overview DTO for headless lifecycle visibility.
/// @post Returns CandidateOverviewDTO built from the same repository state used by headless US1 endpoints.
/// @pre Candidate exists.
/// @}
void get_candidate_overview_v2_endpoint(void);

/// @defgroup prepare_candidate_endpoint "prepare_candidate_endpoint"
/// @{
/// @brief Prepare candidate with policy evaluation and deterministic manifest generation.
/// @post Returns preparation result including manifest reference and violations.
/// @pre Candidate and active policy exist in repository.
/// @}
void prepare_candidate_endpoint(void);

/// @defgroup start_check "start_check"
/// @{
/// @brief Start and finalize a clean compliance check run and persist report artifacts.
/// @post Returns accepted payload with check_run_id and started_at.
/// @pre Active policy and candidate exist.
/// @}
void start_check(void);

/// @defgroup get_check_status "get_check_status"
/// @{
/// @brief Return terminal/intermediate status payload for a check run.
/// @post Deterministic payload shape includes checks and violations arrays.
/// @pre check_run_id references an existing run.
/// @}
void get_check_status(void);

/// @defgroup get_report "get_report"
/// @{
/// @brief Return persisted compliance report by report_id.
/// @post Returns serialized report object.
/// @pre report_id references an existing report.
/// @}
void get_report(void);

/// @defgroup CleanReleaseV2Api "CleanReleaseV2Api"
/// @{
/// @brief Redesigned clean release API for headless candidate lifecycle.
/// @post Candidate registration, approval, publication, and revocation routes are registered without behavior changes.
/// @pre Clean release repository dependency is available for candidate lifecycle endpoints.
/// @}
void CleanReleaseV2Api(void);

/// @defgroup ApprovalRequest "ApprovalRequest"
/// @{
/// @brief Schema for approval request payload.
/// @}
void ApprovalRequest(void);

/// @defgroup PublishRequest "PublishRequest"
/// @{
/// @brief Schema for publication request payload.
/// @}
void PublishRequest(void);

/// @defgroup RevokeRequest "RevokeRequest"
/// @{
/// @brief Schema for revocation request payload.
/// @}
void RevokeRequest(void);

/// @defgroup register_candidate "register_candidate"
/// @{
/// @brief Register a new release candidate.
/// @post Candidate is saved in repository.
/// @pre Payload contains required fields (id, version, source_snapshot_ref, created_by).
/// @}
void register_candidate(void);

/// @defgroup import_artifacts "import_artifacts"
/// @{
/// @brief Associate artifacts with a release candidate.
/// @post Artifacts are processed (placeholder).
/// @pre Candidate exists.
/// @}
void import_artifacts(void);

/// @defgroup build_manifest "build_manifest"
/// @{
/// @brief Generate distribution manifest for a candidate.
/// @post Manifest is created and saved.
/// @pre Candidate exists.
/// @}
void build_manifest(void);

/// @defgroup approve_candidate_endpoint "approve_candidate_endpoint"
/// @{
/// @brief Endpoint to record candidate approval.
/// @}
void approve_candidate_endpoint(void);

/// @defgroup reject_candidate_endpoint "reject_candidate_endpoint"
/// @{
/// @brief Endpoint to record candidate rejection.
/// @}
void reject_candidate_endpoint(void);

/// @defgroup publish_candidate_endpoint "publish_candidate_endpoint"
/// @{
/// @brief Endpoint to publish an approved candidate.
/// @}
void publish_candidate_endpoint(void);

/// @defgroup revoke_publication_endpoint "revoke_publication_endpoint"
/// @{
/// @brief Endpoint to revoke a previous publication.
/// @}
void revoke_publication_endpoint(void);

/// @defgroup DashboardsApi "DashboardsApi"
/// @{
/// @brief API endpoints for the Dashboard Hub - listing dashboards with Git and task status
/// @invariant All dashboard responses include git_status and last_task metadata
/// @post Dashboard responses are projected into DashboardsResponse DTO.
/// @pre Valid environment configurations exist in ConfigManager.
/// @}
void DashboardsApi(void);

/// @defgroup DashboardActionRoutes "DashboardActionRoutes"
/// @{
/// @brief Dashboard action route handlers — migrate, backup.
/// @}
void DashboardActionRoutes(void);

/// @defgroup migrate_dashboards "migrate_dashboards"
/// @{
/// @brief Trigger bulk migration of dashboards from source to target environment
/// @post Task is created and queued for execution
/// @pre dashboard_ids is a non-empty list
/// @}
void migrate_dashboards(void);

/// @defgroup backup_dashboards "backup_dashboards"
/// @{
/// @brief Trigger bulk backup of dashboards with optional cron schedule
/// @post If schedule is provided, a scheduled task is created
/// @pre dashboard_ids is a non-empty list
/// @}
void backup_dashboards(void);

/// @defgroup DashboardDetailRoutes "DashboardDetailRoutes"
/// @{
/// @brief Dashboard detail, db-mappings, task history, thumbnail route handlers.
/// @}
void DashboardDetailRoutes(void);

/// @defgroup get_database_mappings "get_database_mappings"
/// @{
/// @brief Get database mapping suggestions between source and target environments
/// @post Returns list of suggested database mappings with confidence scores
/// @pre source_env_id and target_env_id are valid environment IDs
/// @}
void get_database_mappings(void);

/// @defgroup get_dashboard_detail "get_dashboard_detail"
/// @{
/// @brief Fetch detailed dashboard info with related charts and datasets
/// @post Returns dashboard detail payload for overview page
/// @pre env_id must be valid and dashboard ref (slug or id) must exist
/// @}
void get_dashboard_detail(void);

/// @defgroup get_dashboard_tasks_history "get_dashboard_tasks_history"
/// @{
/// @brief Returns history of backup and LLM validation tasks for a dashboard.
/// @post Response contains sorted task history (newest first).
/// @pre dashboard ref (slug or id) is valid.
/// @}
void get_dashboard_tasks_history(void);

/// @defgroup get_dashboard_thumbnail "get_dashboard_thumbnail"
/// @{
/// @brief Proxies Superset dashboard thumbnail with cache support.
/// @post Returns image bytes or 202 when thumbnail is being prepared by Superset.
/// @pre env_id must exist.
/// @}
void get_dashboard_thumbnail(void);

/// @defgroup DashboardHelpers "DashboardHelpers"
/// @{
/// @brief Basic helper functions for dashboard route handlers — slug resolution, filter normalization.
/// @}
void DashboardHelpers(void);

/// @defgroup _find_dashboard_id_by_slug "_find_dashboard_id_by_slug"
/// @{
/// @brief Resolve dashboard numeric ID by slug using Superset list endpoint.
/// @post Returns dashboard ID when found, otherwise None.
/// @pre `dashboard_slug` is non-empty.
/// @}
void _find_dashboard_id_by_slug(void);

/// @defgroup _resolve_dashboard_id_from_ref "_resolve_dashboard_id_from_ref"
/// @{
/// @brief Resolve dashboard ID from slug-first reference with numeric fallback.
/// @post Returns a valid dashboard ID or raises HTTPException(404).
/// @pre `dashboard_ref` is provided in route path.
/// @}
void _resolve_dashboard_id_from_ref(void);

/// @defgroup _find_dashboard_id_by_slug_async "_find_dashboard_id_by_slug_async"
/// @{
/// @brief Resolve dashboard numeric ID by slug using async Superset list endpoint.
/// @post Returns dashboard ID when found, otherwise None.
/// @pre dashboard_slug is non-empty.
/// @}
void _find_dashboard_id_by_slug_async(void);

/// @defgroup _resolve_dashboard_id_from_ref_async "_resolve_dashboard_id_from_ref_async"
/// @{
/// @brief Resolve dashboard ID from slug-first reference using async Superset client.
/// @post Returns valid dashboard ID or raises HTTPException(404).
/// @pre dashboard_ref is provided in route path.
/// @}
void _resolve_dashboard_id_from_ref_async(void);

/// @defgroup _normalize_filter_values "_normalize_filter_values"
/// @{
/// @brief Normalize query filter values to lower-cased non-empty tokens.
/// @post Returns trimmed normalized list preserving input order.
/// @pre values may be None or list of strings.
/// @}
void _normalize_filter_values(void);

/// @defgroup _dashboard_git_filter_value "_dashboard_git_filter_value"
/// @{
/// @brief Build comparable git status token for dashboards filtering.
/// @post Returns one of ok|diff|no_repo|error|pending.
/// @pre dashboard payload may contain git_status or None.
/// @}
void _dashboard_git_filter_value(void);

/// @defgroup DashboardListingRoutes "DashboardListingRoutes"
/// @{
/// @brief Dashboard listing route handler for Dashboard Hub.
/// @}
void DashboardListingRoutes(void);

/// @defgroup get_dashboards "get_dashboards"
/// @{
/// @brief Fetch list of dashboards from a specific environment with Git status and last task status
/// @post Response includes effective profile filter metadata for main dashboards page context
/// @pre page_size must be between 1 and 100 if provided
/// @}
void get_dashboards(void);

/// @defgroup DashboardProjection "DashboardProjection"
/// @{
/// @brief Dashboard response projection and profile-filter helpers for Dashboard Hub routes.
/// @}
void DashboardProjection(void);

/// @defgroup _normalize_actor_alias_token "_normalize_actor_alias_token"
/// @{
/// @brief Normalize actor alias token to comparable trim+lower text.
/// @}
void _normalize_actor_alias_token(void);

/// @defgroup _normalize_owner_display_token "_normalize_owner_display_token"
/// @{
/// @brief Project owner payload value into stable display string for API response contracts.
/// @}
void _normalize_owner_display_token(void);

/// @defgroup _normalize_dashboard_owner_values "_normalize_dashboard_owner_values"
/// @{
/// @brief Normalize dashboard owners payload to optional list of display strings.
/// @}
void _normalize_dashboard_owner_values(void);

/// @defgroup _project_dashboard_response_items "_project_dashboard_response_items"
/// @{
/// @brief Project dashboard payloads to response-contract-safe shape.
/// @}
void _project_dashboard_response_items(void);

/// @defgroup _get_profile_filter_binding "_get_profile_filter_binding"
/// @{
/// @brief Resolve dashboard profile-filter binding through current or legacy profile service contracts.
/// @}
void _get_profile_filter_binding(void);

/// @defgroup _resolve_profile_actor_aliases "_resolve_profile_actor_aliases"
/// @{
/// @brief Resolve stable actor aliases for profile filtering without per-dashboard detail fan-out.
/// @}
void _resolve_profile_actor_aliases(void);

/// @defgroup _matches_dashboard_actor_aliases "_matches_dashboard_actor_aliases"
/// @{
/// @brief Apply profile actor matching against multiple aliases (username + optional display name).
/// @}
void _matches_dashboard_actor_aliases(void);

/// @defgroup _task_matches_dashboard "_task_matches_dashboard"
/// @{
/// @brief Checks whether task params are tied to a specific dashboard and environment.
/// @}
void _task_matches_dashboard(void);

/// @defgroup DashboardsRouter "DashboardsRouter"
/// @{
/// @brief Single APIRouter instance for all dashboard endpoints.
/// @}
void DashboardsRouter(void);

/// @defgroup DashboardSchemas "DashboardSchemas"
/// @{
/// @brief DTO classes for the Dashboard Hub API.
/// @}
void DashboardSchemas(void);

/// @defgroup GitStatus "GitStatus"
/// @{
/// @brief DTO for dashboard Git synchronization status.
/// @}
void GitStatus(void);

/// @defgroup DashboardItem "DashboardItem"
/// @{
/// @brief DTO representing a single dashboard with projected metadata.
/// @}
void DashboardItem(void);

/// @defgroup EffectiveProfileFilter "EffectiveProfileFilter"
/// @{
/// @brief Metadata about applied profile filters for UI context.
/// @}
void EffectiveProfileFilter(void);

/// @defgroup DashboardsResponse "DashboardsResponse"
/// @{
/// @brief Envelope DTO for paginated dashboards list.
/// @}
void DashboardsResponse(void);

/// @defgroup DashboardChartItem "DashboardChartItem"
/// @{
/// @brief DTO for a chart linked to a dashboard.
/// @}
void DashboardChartItem(void);

/// @defgroup DashboardDatasetItem "DashboardDatasetItem"
/// @{
/// @brief DTO for a dataset associated with a dashboard.
/// @}
void DashboardDatasetItem(void);

/// @defgroup DashboardDetailResponse "DashboardDetailResponse"
/// @{
/// @brief Detailed dashboard metadata including children.
/// @}
void DashboardDetailResponse(void);

/// @defgroup DashboardTaskHistoryItem "DashboardTaskHistoryItem"
/// @{
/// @brief Individual history record entry.
/// @}
void DashboardTaskHistoryItem(void);

/// @defgroup DashboardTaskHistoryResponse "DashboardTaskHistoryResponse"
/// @{
/// @brief Collection DTO for task history.
/// @}
void DashboardTaskHistoryResponse(void);

/// @defgroup DatabaseMapping "DatabaseMapping"
/// @{
/// @brief DTO for cross-environment database ID mapping.
/// @}
void DatabaseMapping(void);

/// @defgroup DatabaseMappingsResponse "DatabaseMappingsResponse"
/// @{
/// @brief Wrapper for database mappings.
/// @}
void DatabaseMappingsResponse(void);

/// @defgroup MigrateRequest "MigrateRequest"
/// @{
/// @brief DTO for dashboard migration requests.
/// @}
void MigrateRequest(void);

/// @defgroup BackupRequest "BackupRequest"
/// @{
/// @brief DTO for dashboard backup requests.
/// @}
void BackupRequest(void);

/// @defgroup DatasetReviewDependencies "DatasetReviewDependencies"
/// @{
/// @brief Dependency injection, serialization helpers, and feature-flag guards for dataset review endpoints.
/// @}
void DatasetReviewDependencies(void);

/// @defgroup StartSessionRequest "StartSessionRequest"
/// @{
/// @brief Request DTO for starting one dataset review session.
/// @}
void StartSessionRequest(void);

/// @defgroup UpdateSessionRequest "UpdateSessionRequest"
/// @{
/// @brief Request DTO for lifecycle state updates on an existing session.
/// @}
void UpdateSessionRequest(void);

/// @defgroup SessionCollectionResponse "SessionCollectionResponse"
/// @{
/// @brief Paginated session collection response.
/// @}
void SessionCollectionResponse(void);

/// @defgroup ExportArtifactResponse "ExportArtifactResponse"
/// @{
/// @brief Inline export response for documentation or validation outputs.
/// @}
void ExportArtifactResponse(void);

/// @defgroup FieldSemanticUpdateRequest "FieldSemanticUpdateRequest"
/// @{
/// @brief Request DTO for field-level semantic candidate acceptance or manual override.
/// @}
void FieldSemanticUpdateRequest(void);

/// @defgroup FeedbackRequest "FeedbackRequest"
/// @{
/// @brief Request DTO for thumbs up/down feedback.
/// @}
void FeedbackRequest(void);

/// @defgroup ClarificationAnswerRequest "ClarificationAnswerRequest"
/// @{
/// @brief Request DTO for submitting one clarification answer.
/// @}
void ClarificationAnswerRequest(void);

/// @defgroup ClarificationSessionSummaryResponse "ClarificationSessionSummaryResponse"
/// @{
/// @brief Summary DTO for current clarification session state.
/// @}
void ClarificationSessionSummaryResponse(void);

/// @defgroup ClarificationStateResponse "ClarificationStateResponse"
/// @{
/// @brief Response DTO for current clarification state and active question payload.
/// @}
void ClarificationStateResponse(void);

/// @defgroup ClarificationAnswerResultResponse "ClarificationAnswerResultResponse"
/// @{
/// @brief Response DTO for one clarification answer mutation result.
/// @}
void ClarificationAnswerResultResponse(void);

/// @defgroup FeedbackResponse "FeedbackResponse"
/// @{
/// @brief Minimal response DTO for persisted AI feedback actions.
/// @}
void FeedbackResponse(void);

/// @defgroup ApproveMappingRequest "ApproveMappingRequest"
/// @{
/// @brief Optional request DTO for explicit mapping approval audit notes.
/// @}
void ApproveMappingRequest(void);

/// @defgroup BatchApproveSemanticItemRequest "BatchApproveSemanticItemRequest"
/// @{
/// @brief Request DTO for one batch semantic-approval item.
/// @}
void BatchApproveSemanticItemRequest(void);

/// @defgroup BatchApproveSemanticRequest "BatchApproveSemanticRequest"
/// @{
/// @brief Request DTO for explicit batch semantic approvals.
/// @}
void BatchApproveSemanticRequest(void);

/// @defgroup BatchApproveMappingRequest "BatchApproveMappingRequest"
/// @{
/// @brief Request DTO for explicit batch mapping approvals.
/// @}
void BatchApproveMappingRequest(void);

/// @defgroup PreviewEnqueueResultResponse "PreviewEnqueueResultResponse"
/// @{
/// @brief Async preview trigger response exposing only enqueue state.
/// @}
void PreviewEnqueueResultResponse(void);

/// @defgroup MappingCollectionResponse "MappingCollectionResponse"
/// @{
/// @brief Wrapper for execution mapping list responses.
/// @}
void MappingCollectionResponse(void);

/// @defgroup UpdateExecutionMappingRequest "UpdateExecutionMappingRequest"
/// @{
/// @brief Request DTO for one manual execution-mapping override update.
/// @}
void UpdateExecutionMappingRequest(void);

/// @defgroup LaunchDatasetResponse "LaunchDatasetResponse"
/// @{
/// @brief Launch result exposing audited run context and SQL Lab redirect target.
/// @}
void LaunchDatasetResponse(void);

/// @defgroup _require_auto_review_flag "_require_auto_review_flag"
/// @{
/// @brief Guard US1 dataset review endpoints behind the configured feature flag.
/// @}
void _require_auto_review_flag(void);

/// @defgroup _require_clarification_flag "_require_clarification_flag"
/// @{
/// @brief Guard clarification-specific US2 endpoints behind the configured feature flag.
/// @}
void _require_clarification_flag(void);

/// @defgroup _require_execution_flag "_require_execution_flag"
/// @{
/// @brief Guard US3 execution endpoints behind the configured feature flag.
/// @}
void _require_execution_flag(void);

/// @defgroup _get_repository "_get_repository"
/// @{
/// @brief Build repository dependency.
/// @}
void _get_repository(void);

/// @defgroup _get_orchestrator "_get_orchestrator"
/// @{
/// @brief Build orchestrator dependency.
/// @}
void _get_orchestrator(void);

/// @defgroup _get_clarification_engine "_get_clarification_engine"
/// @{
/// @brief Build clarification engine dependency.
/// @}
void _get_clarification_engine(void);

/// @defgroup _serialize_session_summary "_serialize_session_summary"
/// @{
/// @brief Map session aggregate into stable API summary DTO.
/// @}
void _serialize_session_summary(void);

/// @defgroup _serialize_session_detail "_serialize_session_detail"
/// @{
/// @brief Map session aggregate into stable API detail DTO.
/// @}
void _serialize_session_detail(void);

/// @defgroup _require_session_version_header "_require_session_version_header"
/// @{
/// @brief Read the optimistic-lock session version header.
/// @}
void _require_session_version_header(void);

/// @defgroup _build_session_version_conflict_http_exception "_build_session_version_conflict_http_exception"
/// @{
/// @brief Normalize optimistic-lock conflict errors into HTTP 409 responses.
/// @}
void _build_session_version_conflict_http_exception(void);

/// @defgroup _enforce_session_version "_enforce_session_version"
/// @{
/// @brief Convert repository optimistic-lock conflicts into deterministic HTTP 409 responses.
/// @}
void _enforce_session_version(void);

/// @defgroup _get_owned_session_or_404 "_get_owned_session_or_404"
/// @{
/// @brief Resolve one session for current user or collaborator scope, returning 404 when inaccessible.
/// @}
void _get_owned_session_or_404(void);

/// @defgroup _require_owner_mutation_scope "_require_owner_mutation_scope"
/// @{
/// @brief Enforce owner-only mutation scope.
/// @}
void _require_owner_mutation_scope(void);

/// @defgroup _prepare_owned_session_mutation "_prepare_owned_session_mutation"
/// @{
/// @brief Resolve owner-scoped mutation session and enforce optimistic-lock version.
/// @}
void _prepare_owned_session_mutation(void);

/// @defgroup _commit_owned_session_mutation "_commit_owned_session_mutation"
/// @{
/// @brief Centralize session version bumping and commit semantics.
/// @}
void _commit_owned_session_mutation(void);

/// @defgroup _record_session_event "_record_session_event"
/// @{
/// @brief Persist one explicit audit event for an owned mutation endpoint.
/// @}
void _record_session_event(void);

/// @defgroup _serialize_semantic_field "_serialize_semantic_field"
/// @{
/// @brief Map one semantic field into stable DTO.
/// @}
void _serialize_semantic_field(void);

/// @defgroup _serialize_execution_mapping "_serialize_execution_mapping"
/// @{
/// @brief Map one execution mapping into stable DTO.
/// @}
void _serialize_execution_mapping(void);

/// @defgroup _serialize_preview "_serialize_preview"
/// @{
/// @brief Map one preview into stable DTO.
/// @}
void _serialize_preview(void);

/// @defgroup _serialize_run_context "_serialize_run_context"
/// @{
/// @brief Map one run context into stable DTO.
/// @}
void _serialize_run_context(void);

/// @defgroup _serialize_clarification_question_payload "_serialize_clarification_question_payload"
/// @{
/// @brief Convert clarification engine payload into API DTO.
/// @}
void _serialize_clarification_question_payload(void);

/// @defgroup _serialize_clarification_state "_serialize_clarification_state"
/// @{
/// @brief Convert clarification engine state into API response.
/// @}
void _serialize_clarification_state(void);

/// @defgroup _serialize_empty_clarification_state "_serialize_empty_clarification_state"
/// @{
/// @brief Return empty clarification payload.
/// @}
void _serialize_empty_clarification_state(void);

/// @defgroup _get_latest_clarification_session_or_404 "_get_latest_clarification_session_or_404"
/// @{
/// @brief Resolve the latest clarification aggregate or raise.
/// @}
void _get_latest_clarification_session_or_404(void);

/// @defgroup _get_owned_mapping_or_404 "_get_owned_mapping_or_404"
/// @{
/// @brief Resolve one execution mapping inside one owned session.
/// @}
void _get_owned_mapping_or_404(void);

/// @defgroup _get_owned_field_or_404 "_get_owned_field_or_404"
/// @{
/// @brief Resolve a semantic field inside one owned session.
/// @}
void _get_owned_field_or_404(void);

/// @defgroup _map_candidate_provenance "_map_candidate_provenance"
/// @{
/// @brief Translate accepted semantic candidate type into stable field provenance.
/// @}
void _map_candidate_provenance(void);

/// @defgroup _resolve_candidate_source_version "_resolve_candidate_source_version"
/// @{
/// @brief Resolve the semantic source version for one accepted candidate.
/// @}
void _resolve_candidate_source_version(void);

/// @defgroup _update_semantic_field_state "_update_semantic_field_state"
/// @{
/// @brief Apply field-level semantic manual override or candidate acceptance.
/// @post Manual overrides always set manual provenance plus lock.
/// @}
void _update_semantic_field_state(void);

/// @defgroup _build_sql_lab_redirect_url "_build_sql_lab_redirect_url"
/// @{
/// @brief Build SQL Lab redirect URL.
/// @}
void _build_sql_lab_redirect_url(void);

/// @defgroup _build_documentation_export "_build_documentation_export"
/// @{
/// @brief Produce session documentation export content.
/// @}
void _build_documentation_export(void);

/// @defgroup _build_validation_export "_build_validation_export"
/// @{
/// @brief Produce validation-focused export content.
/// @}
void _build_validation_export(void);

/// @defgroup DatasetReviewRoutes "DatasetReviewRoutes"
/// @{
/// @brief Persist thumbs up/down feedback for clarification question/answer content.
/// @}
void DatasetReviewRoutes(void);

/// @defgroup list_sessions "list_sessions"
/// @{
/// @brief List resumable dataset review sessions for the current user.
/// @}
void list_sessions(void);

/// @defgroup start_session "start_session"
/// @{
/// @brief Start a new dataset review session from a Superset link or dataset selection.
/// @}
void start_session(void);

/// @defgroup get_session_detail "get_session_detail"
/// @{
/// @brief Return the full accessible dataset review session aggregate.
/// @}
void get_session_detail(void);

/// @defgroup update_session "update_session"
/// @{
/// @brief Update resumable lifecycle status for an owned session.
/// @}
void update_session(void);

/// @defgroup delete_session "delete_session"
/// @{
/// @brief Archive or hard-delete a session owned by the current user.
/// @}
void delete_session(void);

/// @defgroup export_documentation "export_documentation"
/// @{
/// @brief Export documentation output for the current session.
/// @}
void export_documentation(void);

/// @defgroup export_validation "export_validation"
/// @{
/// @brief Export validation findings for the current session.
/// @}
void export_validation(void);

/// @defgroup get_clarification_state "get_clarification_state"
/// @{
/// @brief Return the current clarification session summary and active question payload.
/// @}
void get_clarification_state(void);

/// @defgroup resume_clarification "resume_clarification"
/// @{
/// @brief Resume clarification mode on the highest-priority unresolved question.
/// @}
void resume_clarification(void);

/// @defgroup record_clarification_answer "record_clarification_answer"
/// @{
/// @brief Persist one clarification answer before advancing the active pointer.
/// @}
void record_clarification_answer(void);

/// @defgroup update_field_semantic "update_field_semantic"
/// @{
/// @brief Apply one field-level semantic candidate decision or manual override.
/// @}
void update_field_semantic(void);

/// @defgroup lock_field_semantic "lock_field_semantic"
/// @{
/// @brief Lock one semantic field against later automatic overwrite.
/// @}
void lock_field_semantic(void);

/// @defgroup unlock_field_semantic "unlock_field_semantic"
/// @{
/// @brief Unlock one semantic field so later automated candidate application may replace it.
/// @}
void unlock_field_semantic(void);

/// @defgroup approve_batch_semantic_fields "approve_batch_semantic_fields"
/// @{
/// @brief Approve multiple semantic candidate decisions in one batch.
/// @}
void approve_batch_semantic_fields(void);

/// @defgroup list_execution_mappings "list_execution_mappings"
/// @{
/// @brief Return the current mapping-review set for one accessible session.
/// @}
void list_execution_mappings(void);

/// @defgroup update_execution_mapping "update_execution_mapping"
/// @{
/// @brief Persist one owner-authorized execution-mapping effective value override.
/// @}
void update_execution_mapping(void);

/// @defgroup approve_execution_mapping "approve_execution_mapping"
/// @{
/// @brief Explicitly approve a warning-sensitive mapping transformation.
/// @}
void approve_execution_mapping(void);

/// @defgroup approve_batch_execution_mappings "approve_batch_execution_mappings"
/// @{
/// @brief Approve multiple warning-sensitive execution mappings in one batch.
/// @}
void approve_batch_execution_mappings(void);

/// @defgroup trigger_preview_generation "trigger_preview_generation"
/// @{
/// @brief Trigger Superset-side preview compilation for the current owned execution context.
/// @}
void trigger_preview_generation(void);

/// @defgroup launch_dataset "launch_dataset"
/// @{
/// @brief Execute the current owned session launch handoff and return audited SQL Lab run context.
/// @}
void launch_dataset(void);

/// @defgroup record_field_feedback "record_field_feedback"
/// @{
/// @brief Persist thumbs up/down feedback for AI-assisted semantic field content.
/// @}
void record_field_feedback(void);

/// @defgroup record_clarification_feedback "record_clarification_feedback"
/// @{
/// @brief Persist thumbs up/down feedback for clarification question/answer content.
/// @}
void record_clarification_feedback(void);

/// @defgroup DatasetsApi "DatasetsApi"
/// @{
/// @brief API endpoints for the Dataset Hub - listing datasets with mapping progress
/// @invariant All dataset responses include last_task metadata
/// @post Returns dataset metadata with mapping status.
/// @pre SupersetClient is available; env_id is valid.
/// @}
void DatasetsApi(void);

/// @defgroup MappedFields "MappedFields"
/// @{
/// @brief DTO for dataset mapping progress statistics
/// @}
void MappedFields(void);

/// @defgroup LastTask "LastTask"
/// @{
/// @brief DTO for the most recent task associated with a dataset
/// @}
void LastTask(void);

/// @defgroup DatasetItem "DatasetItem"
/// @{
/// @brief Summary DTO for a dataset in the hub listing
/// @}
void DatasetItem(void);

/// @defgroup LinkedDashboard "LinkedDashboard"
/// @{
/// @brief DTO for a dashboard linked to a dataset
/// @}
void LinkedDashboard(void);

/// @defgroup DatasetColumn "DatasetColumn"
/// @{
/// @brief DTO for a single dataset column's metadata
/// @}
void DatasetColumn(void);

/// @defgroup MetricItem "MetricItem"
/// @{
/// @brief Pydantic DTO for a dataset metric — carries Superset metric metadata.
/// @}
void MetricItem(void);

/// @defgroup DatasetDetailResponse "DatasetDetailResponse"
/// @{
/// @brief Detailed DTO for a dataset including columns, linked dashboards, and metrics.
/// @}
void DatasetDetailResponse(void);

/// @defgroup StatsCounts "StatsCounts"
/// @{
/// @brief Aggregate statistics for the Stats Bar — computed from full dataset list.
/// @}
void StatsCounts(void);

/// @defgroup DatasetsResponse "DatasetsResponse"
/// @{
/// @brief Paginated response DTO for dataset listings with stats.
/// @}
void DatasetsResponse(void);

/// @defgroup TaskResponse "TaskResponse"
/// @{
/// @brief Response DTO containing a task ID for tracking
/// @}
void TaskResponse(void);

/// @defgroup ColumnDescriptionUpdate "ColumnDescriptionUpdate"
/// @{
/// @brief Request DTO for inline-edit of a column description.
/// @}
void ColumnDescriptionUpdate(void);

/// @defgroup MetricDescriptionUpdate "MetricDescriptionUpdate"
/// @{
/// @brief Request DTO for inline-edit of a metric description.
/// @}
void MetricDescriptionUpdate(void);

/// @defgroup get_dataset_ids "get_dataset_ids"
/// @{
/// @brief Fetch list of all dataset IDs from a specific environment (without pagination)
/// @post Returns a list of all dataset IDs
/// @pre env_id must be a valid environment ID
/// @}
void get_dataset_ids(void);

/// @defgroup get_datasets "get_datasets"
/// @{
/// @brief Fetch list of datasets from a specific environment with mapping progress and stats.
/// @post Response includes pagination metadata (page, page_size, total, total_pages) and stats object.
/// @pre page_size must be between 1 and 100 if provided
/// @}
void get_datasets(void);

/// @defgroup MapColumnsRequest "MapColumnsRequest"
/// @{
/// @brief Request DTO for initiating column mapping
/// @}
void MapColumnsRequest(void);

/// @defgroup map_columns "map_columns"
/// @{
/// @brief Trigger bulk column mapping for datasets
/// @post Task is created and queued for execution
/// @pre dataset_ids is a non-empty list
/// @}
void map_columns(void);

/// @defgroup GenerateDocsRequest "GenerateDocsRequest"
/// @{
/// @brief Request DTO for initiating documentation generation
/// @}
void GenerateDocsRequest(void);

/// @defgroup generate_docs "generate_docs"
/// @{
/// @brief Trigger bulk documentation generation for datasets
/// @post Task is created and queued for execution
/// @pre dataset_ids is a non-empty list
/// @}
void generate_docs(void);

/// @defgroup get_dataset_detail "get_dataset_detail"
/// @{
/// @brief Get detailed dataset information including columns and linked dashboards
/// @post Returns detailed dataset info with columns and linked dashboards
/// @pre dataset_id is a valid dataset ID
/// @}
void get_dataset_detail(void);

/// @defgroup _strip_html_tags "_strip_html_tags"
/// @{
/// @brief Detect and strip HTML tags from a text string. Uses simple regex <[^>]*>.
/// @}
void _strip_html_tags(void);

/// @defgroup update_column_description "update_column_description"
/// @{
/// @brief Save description for a single dataset column. Internal: GET full dataset from Superset, modify one column's description, PUT back.
/// @post Column description in Superset is updated. Response confirms success.
/// @pre dataset_id and column_id must exist in the target environment.
/// @}
void update_column_description(void);

/// @defgroup update_metric_description "update_metric_description"
/// @{
/// @brief Save description for a single dataset metric. Mirror of update_column_description for metrics.
/// @post Metric description in Superset is updated.
/// @pre dataset_id and metric_id must exist in the target environment.
/// @}
void update_metric_description(void);

/// @defgroup EnvironmentsApi "EnvironmentsApi"
/// @{
/// @brief API endpoints for listing environments and their databases.
/// @invariant Environment IDs must exist in the configuration.
/// @}
void EnvironmentsApi(void);

/// @defgroup _normalize_superset_env_url "_normalize_superset_env_url"
/// @{
/// @brief Canonicalize Superset environment URL to base host/path without trailing /api/v1.
/// @post Returns normalized base URL.
/// @pre raw_url can be empty.
/// @}
void _normalize_superset_env_url(void);

/// @defgroup ScheduleSchema "ScheduleSchema"
/// @{
/// @}
void ScheduleSchema(void);

/// @defgroup EnvironmentResponse "EnvironmentResponse"
/// @{
/// @}
void EnvironmentResponse(void);

/// @defgroup DatabaseResponse "DatabaseResponse"
/// @{
/// @}
void DatabaseResponse(void);

/// @defgroup update_environment_schedule "update_environment_schedule"
/// @{
/// @brief Update backup schedule for an environment.
/// @post Backup schedule updated and scheduler reloaded.
/// @pre Environment id exists, schedule is valid ScheduleSchema.
/// @}
void update_environment_schedule(void);

/// @defgroup get_environment_databases "get_environment_databases"
/// @{
/// @brief Fetch the list of databases from a specific environment.
/// @post Returns a list of database summaries from the environment.
/// @pre Environment id exists.
/// @}
void get_environment_databases(void);

/// @defgroup GitPackage "GitPackage"
/// @{
/// @brief Package root for decomposed git routes. Re-exports all public symbols from submodules.
/// @invariant git_service and os are module-level attributes for test monkeypatch compatibility.
/// @post Git API package exported
/// @pre Git service initialized
/// @}
void GitPackage(void);

/// @defgroup GitConfigRoutes "GitConfigRoutes"
/// @{
/// @brief FastAPI endpoints for Git server configuration CRUD and connection testing.
/// @}
void GitConfigRoutes(void);

/// @defgroup get_git_configs "get_git_configs"
/// @{
/// @brief List all configured Git servers.
/// @}
void get_git_configs(void);

/// @defgroup create_git_config "create_git_config"
/// @{
/// @brief Register a new Git server configuration.
/// @}
void create_git_config(void);

/// @defgroup update_git_config "update_git_config"
/// @{
/// @brief Update an existing Git server configuration.
/// @}
void update_git_config(void);

/// @defgroup delete_git_config "delete_git_config"
/// @{
/// @brief Remove a Git server configuration.
/// @}
void delete_git_config(void);

/// @defgroup test_git_config "test_git_config"
/// @{
/// @brief Validate connection to a Git server using provided credentials.
/// @}
void test_git_config(void);

/// @defgroup GitDeps "GitDeps"
/// @{
/// @brief Shared dependency wiring for monkeypatch-safe git_service access and constants.
/// @invariant get_git_service() resolves from sys.modules at call time so test monkeypatching
/// @}
void GitDeps(void);

/// @defgroup GitEnvironmentRoutes "GitEnvironmentRoutes"
/// @{
/// @brief FastAPI endpoint for listing deployment environments.
/// @}
void GitEnvironmentRoutes(void);

/// @defgroup GitGiteaRoutes "GitGiteaRoutes"
/// @{
/// @brief FastAPI endpoints for Gitea-specific repository operations.
/// @}
void GitGiteaRoutes(void);

/// @defgroup list_gitea_repositories "list_gitea_repositories"
/// @{
/// @brief List repositories in Gitea for a saved Gitea config.
/// @}
void list_gitea_repositories(void);

/// @defgroup create_gitea_repository "create_gitea_repository"
/// @{
/// @brief Create a repository in Gitea for a saved Gitea config.
/// @}
void create_gitea_repository(void);

/// @defgroup delete_gitea_repository "delete_gitea_repository"
/// @{
/// @brief Delete repository in Gitea for a saved Gitea config.
/// @}
void delete_gitea_repository(void);

/// @defgroup create_remote_repository "create_remote_repository"
/// @{
/// @brief Create repository on remote Git server using selected provider config.
/// @}
void create_remote_repository(void);

/// @defgroup GitHelpers "GitHelpers"
/// @{
/// @brief Shared helper functions for Git route modules.
/// @}
void GitHelpers(void);

/// @defgroup _build_no_repo_status_payload "_build_no_repo_status_payload"
/// @{
/// @brief Build a consistent status payload for dashboards without initialized repositories.
/// @post Returns a stable payload compatible with frontend repository status parsing.
/// @}
void _build_no_repo_status_payload(void);

/// @defgroup _handle_unexpected_git_route_error "_handle_unexpected_git_route_error"
/// @{
/// @brief Convert unexpected route-level exceptions to stable 500 API responses.
/// @post Raises HTTPException(500) with route-specific context.
/// @pre `error` is a non-HTTPException instance.
/// @}
void _handle_unexpected_git_route_error(void);

/// @defgroup _resolve_repository_status "_resolve_repository_status"
/// @{
/// @brief Resolve repository status for one dashboard with graceful NO_REPO semantics.
/// @post Returns standard status payload or `NO_REPO` payload when repository path is absent.
/// @pre `dashboard_id` is a valid integer.
/// @}
void _resolve_repository_status(void);

/// @defgroup _get_git_config_or_404 "_get_git_config_or_404"
/// @{
/// @brief Resolve GitServerConfig by id or raise 404.
/// @}
void _get_git_config_or_404(void);

/// @defgroup _resolve_repo_key_from_ref "_resolve_repo_key_from_ref"
/// @{
/// @brief Resolve repository folder key with slug-first strategy and deterministic fallback.
/// @}
void _resolve_repo_key_from_ref(void);

/// @defgroup _sanitize_optional_identity_value "_sanitize_optional_identity_value"
/// @{
/// @brief Normalize optional identity value into trimmed string or None.
/// @}
void _sanitize_optional_identity_value(void);

/// @defgroup _resolve_current_user_git_identity "_resolve_current_user_git_identity"
/// @{
/// @brief Resolve configured Git username/email from current user's profile preferences.
/// @}
void _resolve_current_user_git_identity(void);

/// @defgroup _apply_git_identity_from_profile "_apply_git_identity_from_profile"
/// @{
/// @brief Apply user-scoped Git identity to repository-local config before write/pull operations.
/// @}
void _apply_git_identity_from_profile(void);

/// @defgroup GitMergeRoutes "GitMergeRoutes"
/// @{
/// @brief FastAPI endpoints for merge operations (status, conflicts, resolve, abort, continue).
/// @}
void GitMergeRoutes(void);

/// @defgroup get_merge_status "get_merge_status"
/// @{
/// @brief Return unfinished-merge status for repository (web-only recovery support).
/// @}
void get_merge_status(void);

/// @defgroup get_merge_conflicts "get_merge_conflicts"
/// @{
/// @brief Return conflicted files with mine/theirs previews for web conflict resolver.
/// @}
void get_merge_conflicts(void);

/// @defgroup resolve_merge_conflicts "resolve_merge_conflicts"
/// @{
/// @brief Apply mine/theirs/manual conflict resolutions from WebUI and stage files.
/// @}
void resolve_merge_conflicts(void);

/// @defgroup abort_merge "abort_merge"
/// @{
/// @brief Abort unfinished merge from WebUI flow.
/// @}
void abort_merge(void);

/// @defgroup continue_merge "continue_merge"
/// @{
/// @brief Finalize unfinished merge from WebUI flow.
/// @}
void continue_merge(void);

/// @defgroup GitRepoLifecycleRoutes "GitRepoLifecycleRoutes"
/// @{
/// @brief FastAPI endpoints for Git lifecycle operations (sync, promote, deploy).
/// @}
void GitRepoLifecycleRoutes(void);

/// @defgroup sync_dashboard "sync_dashboard"
/// @{
/// @brief Sync dashboard state from Superset to Git using the GitPlugin.
/// @}
void sync_dashboard(void);

/// @defgroup promote_dashboard "promote_dashboard"
/// @{
/// @brief Promote changes between branches via MR or direct merge.
/// @}
void promote_dashboard(void);

/// @defgroup deploy_dashboard "deploy_dashboard"
/// @{
/// @brief Deploy dashboard from Git to a target environment.
/// @}
void deploy_dashboard(void);

/// @defgroup GitRepoOperationsRoutes "GitRepoOperationsRoutes"
/// @{
/// @brief FastAPI endpoints for Git repository operations (commit, push, pull, status, diff, history).
/// @}
void GitRepoOperationsRoutes(void);

/// @defgroup commit_changes "commit_changes"
/// @{
/// @brief Stage and commit changes in the dashboard's repository.
/// @}
void commit_changes(void);

/// @defgroup push_changes "push_changes"
/// @{
/// @brief Push local commits to the remote repository.
/// @}
void push_changes(void);

/// @defgroup pull_changes "pull_changes"
/// @{
/// @brief Pull changes from the remote repository.
/// @}
void pull_changes(void);

/// @defgroup get_repository_status "get_repository_status"
/// @{
/// @brief Get current Git status for a dashboard repository.
/// @}
void get_repository_status(void);

/// @defgroup get_repository_status_batch "get_repository_status_batch"
/// @{
/// @brief Get Git statuses for multiple dashboard repositories in one request.
/// @}
void get_repository_status_batch(void);

/// @defgroup get_repository_diff "get_repository_diff"
/// @{
/// @brief Get Git diff for a dashboard repository.
/// @}
void get_repository_diff(void);

/// @defgroup generate_commit_message "generate_commit_message"
/// @{
/// @brief Generate a suggested commit message using LLM.
/// @}
void generate_commit_message(void);

/// @defgroup GitRepoRoutes "GitRepoRoutes"
/// @{
/// @brief FastAPI endpoints for core Git repository operations (init, binding, branches, checkout).
/// @}
void GitRepoRoutes(void);

/// @defgroup init_repository "init_repository"
/// @{
/// @brief Link a dashboard to a Git repository and perform initial clone/init.
/// @}
void init_repository(void);

/// @defgroup get_repository_binding "get_repository_binding"
/// @{
/// @brief Return repository binding with provider metadata for selected dashboard.
/// @}
void get_repository_binding(void);

/// @defgroup delete_repository "delete_repository"
/// @{
/// @brief Delete local repository workspace and DB binding for selected dashboard.
/// @}
void delete_repository(void);

/// @defgroup get_branches "get_branches"
/// @{
/// @brief List all branches for a dashboard's repository.
/// @}
void get_branches(void);

/// @defgroup create_branch "create_branch"
/// @{
/// @brief Create a new branch in the dashboard's repository.
/// @}
void create_branch(void);

/// @defgroup checkout_branch "checkout_branch"
/// @{
/// @brief Switch the dashboard's repository to a specific branch.
/// @}
void checkout_branch(void);

/// @defgroup GitRouter "GitRouter"
/// @{
/// @brief Shared APIRouter for all Git route modules.
/// @}
void GitRouter(void);

/// @defgroup GitSchemas "GitSchemas"
/// @{
/// @brief Defines Pydantic models for the Git integration API layer.
/// @invariant All schemas must be compatible with the FastAPI router.
/// @}
void GitSchemas(void);

/// @defgroup GitServerConfigBase "GitServerConfigBase"
/// @{
/// @brief Base schema for Git server configuration attributes.
/// @}
void GitServerConfigBase(void);

/// @defgroup GitServerConfigUpdate "GitServerConfigUpdate"
/// @{
/// @brief Schema for updating an existing Git server configuration.
/// @}
void GitServerConfigUpdate(void);

/// @defgroup GitServerConfigCreate "GitServerConfigCreate"
/// @{
/// @brief Schema for creating a new Git server configuration.
/// @}
void GitServerConfigCreate(void);

/// @defgroup GitServerConfigSchema "GitServerConfigSchema"
/// @{
/// @brief Schema for representing a Git server configuration with metadata.
/// @}
void GitServerConfigSchema(void);

/// @defgroup GitRepositorySchema "GitRepositorySchema"
/// @{
/// @brief Schema for tracking a local Git repository linked to a dashboard.
/// @}
void GitRepositorySchema(void);

/// @defgroup BranchSchema "BranchSchema"
/// @{
/// @brief Schema for representing a Git branch metadata.
/// @}
void BranchSchema(void);

/// @defgroup CommitSchema "CommitSchema"
/// @{
/// @brief Schema for representing Git commit details.
/// @}
void CommitSchema(void);

/// @defgroup BranchCreate "BranchCreate"
/// @{
/// @brief Schema for branch creation requests.
/// @}
void BranchCreate(void);

/// @defgroup BranchCheckout "BranchCheckout"
/// @{
/// @brief Schema for branch checkout requests.
/// @}
void BranchCheckout(void);

/// @defgroup CommitCreate "CommitCreate"
/// @{
/// @brief Schema for staging and committing changes.
/// @}
void CommitCreate(void);

/// @defgroup ConflictResolution "ConflictResolution"
/// @{
/// @brief Schema for resolving merge conflicts.
/// @}
void ConflictResolution(void);

/// @defgroup MergeStatusSchema "MergeStatusSchema"
/// @{
/// @brief Schema representing unfinished merge status for repository.
/// @}
void MergeStatusSchema(void);

/// @defgroup MergeConflictFileSchema "MergeConflictFileSchema"
/// @{
/// @brief Schema describing one conflicted file with optional side snapshots.
/// @}
void MergeConflictFileSchema(void);

/// @defgroup MergeResolveRequest "MergeResolveRequest"
/// @{
/// @brief Request schema for resolving one or multiple merge conflicts.
/// @}
void MergeResolveRequest(void);

/// @defgroup MergeContinueRequest "MergeContinueRequest"
/// @{
/// @brief Request schema for finishing merge with optional explicit commit message.
/// @}
void MergeContinueRequest(void);

/// @defgroup DeploymentEnvironmentSchema "DeploymentEnvironmentSchema"
/// @{
/// @brief Schema for representing a target deployment environment.
/// @}
void DeploymentEnvironmentSchema(void);

/// @defgroup DeployRequest "DeployRequest"
/// @{
/// @brief Schema for dashboard deployment requests.
/// @}
void DeployRequest(void);

/// @defgroup RepoInitRequest "RepoInitRequest"
/// @{
/// @brief Schema for repository initialization requests.
/// @}
void RepoInitRequest(void);

/// @defgroup RepositoryBindingSchema "RepositoryBindingSchema"
/// @{
/// @brief Schema describing repository-to-config binding and provider metadata.
/// @}
void RepositoryBindingSchema(void);

/// @defgroup RepoStatusBatchRequest "RepoStatusBatchRequest"
/// @{
/// @brief Schema for requesting repository statuses for multiple dashboards in a single call.
/// @}
void RepoStatusBatchRequest(void);

/// @defgroup RepoStatusBatchResponse "RepoStatusBatchResponse"
/// @{
/// @brief Schema for returning repository statuses keyed by dashboard ID.
/// @}
void RepoStatusBatchResponse(void);

/// @defgroup GiteaRepoSchema "GiteaRepoSchema"
/// @{
/// @brief Schema describing a Gitea repository.
/// @}
void GiteaRepoSchema(void);

/// @defgroup GiteaRepoCreateRequest "GiteaRepoCreateRequest"
/// @{
/// @brief Request schema for creating a Gitea repository.
/// @}
void GiteaRepoCreateRequest(void);

/// @defgroup RemoteRepoSchema "RemoteRepoSchema"
/// @{
/// @brief Provider-agnostic remote repository payload.
/// @}
void RemoteRepoSchema(void);

/// @defgroup RemoteRepoCreateRequest "RemoteRepoCreateRequest"
/// @{
/// @brief Provider-agnostic repository creation request.
/// @}
void RemoteRepoCreateRequest(void);

/// @defgroup PromoteRequest "PromoteRequest"
/// @{
/// @brief Request schema for branch promotion workflow.
/// @}
void PromoteRequest(void);

/// @defgroup PromoteResponse "PromoteResponse"
/// @{
/// @brief Response schema for promotion operation result.
/// @}
void PromoteResponse(void);

/// @defgroup health_router "health_router"
/// @{
/// @brief API endpoints for dashboard health monitoring and status aggregation.
/// @}
void health_router(void);

/// @defgroup get_health_summary "get_health_summary"
/// @{
/// @brief Get aggregated health status for all dashboards.
/// @post Returns HealthSummaryResponse.
/// @pre Caller has read permission for dashboard health view.
/// @}
void get_health_summary(void);

/// @defgroup delete_health_report "delete_health_report"
/// @{
/// @brief Delete one persisted dashboard validation report from health summary.
/// @post Validation record is removed; linked task/logs are cleaned when available.
/// @pre Caller has write permission for tasks/report maintenance.
/// @}
void delete_health_report(void);

/// @defgroup LlmRoutes "LlmRoutes"
/// @{
/// @brief API routes for LLM provider configuration and management.
/// @}
void LlmRoutes(void);

/// @defgroup FetchModelsRequest "FetchModelsRequest"
/// @{
/// @brief Pydantic request model for the fetch-models endpoint.
/// @}
void FetchModelsRequest(void);

/// @defgroup router "router"
/// @{
/// @brief APIRouter instance for LLM routes.
/// @}
void router(void);

/// @defgroup _is_valid_runtime_api_key "_is_valid_runtime_api_key"
/// @{
/// @brief Validate decrypted runtime API key presence/shape.
/// @post Returns True only for non-placeholder key.
/// @pre value can be None.
/// @}
void _is_valid_runtime_api_key(void);

/// @defgroup get_providers "get_providers"
/// @{
/// @brief Retrieve all LLM provider configurations.
/// @post Returns list of LLMProviderConfig.
/// @pre User is authenticated.
/// @}
void get_providers(void);

/// @defgroup fetch_models "fetch_models"
/// @{
/// @brief Fetch available models from an LLM provider by base_url+provider_type, or by provider_id.
/// @post Returns a list of available model IDs.
/// @pre User is authenticated. Either provider_id or base_url+provider_type must be provided.
/// @}
void fetch_models(void);

/// @defgroup get_llm_status "get_llm_status"
/// @{
/// @brief Returns whether LLM runtime is configured for dashboard validation.
/// @post configured=true only when an active provider with valid decrypted key exists.
/// @pre User is authenticated.
/// @}
void get_llm_status(void);

/// @defgroup create_provider "create_provider"
/// @{
/// @brief Create a new LLM provider configuration.
/// @post Returns the created LLMProviderConfig.
/// @pre User is authenticated and has admin permissions.
/// @}
void create_provider(void);

/// @defgroup update_provider "update_provider"
/// @{
/// @brief Update an existing LLM provider configuration.
/// @post Returns the updated LLMProviderConfig.
/// @pre User is authenticated and has admin permissions.
/// @}
void update_provider(void);

/// @defgroup delete_provider "delete_provider"
/// @{
/// @brief Delete an LLM provider configuration.
/// @post Returns success status.
/// @pre User is authenticated and has admin permissions.
/// @}
void delete_provider(void);

/// @defgroup test_connection "test_connection"
/// @{
/// @brief Test connection to an LLM provider.
/// @post Returns success status and message.
/// @pre User is authenticated.
/// @}
void test_connection(void);

/// @defgroup test_provider_config "test_provider_config"
/// @{
/// @brief Test connection with a provided configuration (not yet saved).
/// @post Returns success status and message.
/// @pre User is authenticated.
/// @}
void test_provider_config(void);

/// @defgroup MaintenanceRoutesPackage "MaintenanceRoutesPackage"
/// @{
/// @brief Maintenance Banner API route package.
/// @}
void MaintenanceRoutesPackage(void);

/// @defgroup MaintenanceRouter "MaintenanceRouter"
/// @{
/// @brief FastAPI APIRouter for the Maintenance Banner endpoints.
/// @}
void MaintenanceRouter(void);

/// @defgroup MaintenanceRoutesModule "MaintenanceRoutesModule"
/// @{
/// @brief Route handler stubs for all 7 Maintenance Banner API endpoints with RBAC guards per FR-015.
/// @invariant RBAC enforced per FR-015 matrix via has_permission() dependency.
/// @}
void MaintenanceRoutesModule(void);

/// @defgroup list_dashboard_banners "list_dashboard_banners"
/// @{
/// @brief Get per-dashboard banner state for the Dashboard Hub indicator.
/// @}
void list_dashboard_banners(void);

/// @defgroup list_events "list_events"
/// @{
/// @brief Get active and completed maintenance event lists with affected dashboard counts.
/// @}
void list_events(void);

/// @defgroup start_maintenance "start_maintenance"
/// @{
/// @brief Start a maintenance event. Validates input, creates event, dispatches TaskManager task.
/// @}
void start_maintenance(void);

/// @defgroup end_maintenance "end_maintenance"
/// @{
/// @brief End a specific maintenance event by ID. Removes banners from affected dashboards.
/// @}
void end_maintenance(void);

/// @defgroup end_all_maintenance "end_all_maintenance"
/// @{
/// @brief End all active maintenance events. Removes all banners from all dashboards.
/// @}
void end_all_maintenance(void);

/// @defgroup get_maintenance_settings "get_maintenance_settings"
/// @{
/// @brief Get current maintenance settings configuration.
/// @}
void get_maintenance_settings(void);

/// @defgroup update_maintenance_settings "update_maintenance_settings"
/// @{
/// @brief Update maintenance settings. All fields optional for partial update.
/// @}
void update_maintenance_settings(void);

/// @defgroup MaintenanceSchemasModule "MaintenanceSchemasModule"
/// @{
/// @brief Pydantic models for Maintenance Banner API: request/response schemas per data-model.md.
/// @invariant All response schemas use the standard envelope shape: { status, data, error, meta }
/// @}
void MaintenanceSchemasModule(void);

/// @defgroup MaintenanceStartRequest "MaintenanceStartRequest"
/// @{
/// @brief POST /api/maintenance/start request body with environment scoping.
/// @}
void MaintenanceStartRequest(void);

/// @defgroup MaintenanceSettingsUpdate "MaintenanceSettingsUpdate"
/// @{
/// @brief PUT /api/maintenance/settings request body — all fields optional for partial update.
/// @}
void MaintenanceSettingsUpdate(void);

/// @defgroup MaintenanceStartResponse "MaintenanceStartResponse"
/// @{
/// @brief Response for /api/maintenance/start — always 202 with task_id.
/// @}
void MaintenanceStartResponse(void);

/// @defgroup MaintenanceDashboardResult "MaintenanceDashboardResult"
/// @{
/// @brief Describes a single dashboard affected by a maintenance operation.
/// @}
void MaintenanceDashboardResult(void);

/// @defgroup MaintenanceFailedDashboard "MaintenanceFailedDashboard"
/// @{
/// @brief Describes a dashboard that failed during banner apply/removal.
/// @}
void MaintenanceFailedDashboard(void);

/// @defgroup MaintenanceTaskResult "MaintenanceTaskResult"
/// @{
/// @brief Result payload for a completed maintenance start task.
/// @}
void MaintenanceTaskResult(void);

/// @defgroup MaintenanceEndResponse "MaintenanceEndResponse"
/// @{
/// @brief Response for /api/maintenance/{id}/end and /api/maintenance/end-all — always 202 with task_id.
/// @}
void MaintenanceEndResponse(void);

/// @defgroup MaintenanceEndTaskResult "MaintenanceEndTaskResult"
/// @{
/// @brief Result payload for a completed end maintenance task.
/// @}
void MaintenanceEndTaskResult(void);

/// @defgroup MaintenanceEndAllTaskResult "MaintenanceEndAllTaskResult"
/// @{
/// @brief Result payload for a completed end-all maintenance task.
/// @}
void MaintenanceEndAllTaskResult(void);

/// @defgroup MaintenanceSettingsResponse "MaintenanceSettingsResponse"
/// @{
/// @brief Response for GET /api/maintenance/settings.
/// @}
void MaintenanceSettingsResponse(void);

/// @defgroup MaintenanceEventItem "MaintenanceEventItem"
/// @{
/// @brief Single maintenance event summary for GET /api/maintenance/events.
/// @}
void MaintenanceEventItem(void);

/// @defgroup MaintenanceEventListResponse "MaintenanceEventListResponse"
/// @{
/// @brief Response for GET /api/maintenance/events.
/// @}
void MaintenanceEventListResponse(void);

/// @defgroup MaintenanceDashboardBannerState "MaintenanceDashboardBannerState"
/// @{
/// @brief Per-dashboard banner state for GET /api/maintenance/dashboard-banners.
/// @}
void MaintenanceDashboardBannerState(void);

/// @defgroup MaintenanceAlreadyActiveResponse "MaintenanceAlreadyActiveResponse"
/// @{
/// @brief Response for duplicate /start call — idempotency hit.
/// @}
void MaintenanceAlreadyActiveResponse(void);

/// @defgroup MappingsApi "MappingsApi"
/// @{
/// @brief API endpoints for managing database mappings and getting suggestions.
/// @}
void MappingsApi(void);

/// @defgroup MappingCreate "MappingCreate"
/// @{
/// @}
void MappingCreate(void);

/// @defgroup MappingResponse "MappingResponse"
/// @{
/// @}
void MappingResponse(void);

/// @defgroup SuggestRequest "SuggestRequest"
/// @{
/// @}
void SuggestRequest(void);

/// @defgroup get_mappings "get_mappings"
/// @{
/// @brief List all saved database mappings.
/// @post Returns filtered list of DatabaseMapping records.
/// @pre db session is injected.
/// @}
void get_mappings(void);

/// @defgroup create_mapping "create_mapping"
/// @{
/// @brief Create or update a database mapping.
/// @post DatabaseMapping created or updated in database.
/// @pre mapping is valid MappingCreate, db session is injected.
/// @}
void create_mapping(void);

/// @defgroup suggest_mappings_api "suggest_mappings_api"
/// @{
/// @brief Get suggested mappings based on fuzzy matching.
/// @post Returns mapping suggestions.
/// @pre request is valid SuggestRequest, config_manager is injected.
/// @}
void suggest_mappings_api(void);

/// @defgroup MigrationApi "MigrationApi"
/// @{
/// @brief HTTP contract layer for migration orchestration, settings, dry-run, and mapping sync endpoints.
/// @invariant Migration endpoints never execute with invalid environment references and always return explicit HTTP errors on guard failures.
/// @post Migration tasks are enqueued or dry-run results are computed and returned.
/// @pre Backend core services initialized and Database session available.
/// @}
void MigrationApi(void);

/// @defgroup execute_migration "execute_migration"
/// @{
/// @brief Validate migration selection and enqueue asynchronous migration task execution.
/// @invariant Migration task dispatch never occurs before source and target environment ids pass guard validation.
/// @post Returns {"task_id": str, "message": str} when task creation succeeds; emits HTTP_400/HTTP_500 on failure.
/// @pre DashboardSelection payload is valid and both source/target environments exist.
/// @}
void execute_migration(void);

/// @defgroup dry_run_migration "dry_run_migration"
/// @{
/// @brief Build pre-flight migration diff and risk summary without mutating target systems.
/// @invariant Dry-run flow remains read-only and rejects identical source/target environments before service execution.
/// @post Returns deterministic dry-run payload; emits HTTP_400 for guard violations and HTTP_500 for orchestrator value errors.
/// @pre DashboardSelection is valid, source and target environments exist, differ, and selected_ids is non-empty.
/// @}
void dry_run_migration(void);

/// @defgroup get_migration_settings "get_migration_settings"
/// @{
/// @brief Read and return configured migration synchronization cron expression.
/// @post Returns {"cron": str} reflecting current persisted settings value.
/// @pre Configuration store is available and requester has READ permission.
/// @}
void get_migration_settings(void);

/// @defgroup update_migration_settings "update_migration_settings"
/// @{
/// @brief Validate and persist migration synchronization cron expression update.
/// @post Returns {"cron": str, "status": "updated"} and persists updated cron value.
/// @pre Payload includes "cron" key and requester has WRITE permission.
/// @}
void update_migration_settings(void);

/// @defgroup get_resource_mappings "get_resource_mappings"
/// @{
/// @brief Fetch synchronized resource mappings with optional filters and pagination for migration mappings view.
/// @post Returns {"items": [...], "total": int} where items reflect applied filters and pagination.
/// @pre skip>=0, 1<=limit<=500, DB session is active, requester has READ permission.
/// @}
void get_resource_mappings(void);

/// @defgroup trigger_sync_now "trigger_sync_now"
/// @{
/// @brief Trigger immediate ID synchronization for every configured environment.
/// @post Returns sync summary with synced/failed counts after attempting all environments.
/// @pre At least one environment is configured and requester has EXECUTE permission.
/// @}
void trigger_sync_now(void);

/// @defgroup PluginsRouter "PluginsRouter"
/// @{
/// @brief Defines the FastAPI router for plugin-related endpoints, allowing clients to list available plugins.
/// @}
void PluginsRouter(void);

/// @defgroup list_plugins "list_plugins"
/// @{
/// @brief Retrieve a list of all available plugins.
/// @post Returns a list of PluginConfig objects.
/// @pre plugin_loader is injected via Depends.
/// @}
void list_plugins(void);

/// @defgroup ProfileApiModule "ProfileApiModule"
/// @{
/// @brief Exposes self-scoped profile preference endpoints and environment-based Superset account lookup.
/// @invariant Endpoints are self-scoped and never mutate another user preference.
/// @post Profile endpoints registered
/// @pre Auth middleware configured, database session available
/// @}
void ProfileApiModule(void);

/// @defgroup _get_profile_service "_get_profile_service"
/// @{
/// @brief Build profile service for current request scope.
/// @post Returns a ready ProfileService instance.
/// @pre db session and config manager are available.
/// @}
void _get_profile_service(void);

/// @defgroup get_preferences "get_preferences"
/// @{
/// @brief Get authenticated user's dashboard filter preference.
/// @post Returns preference payload for current user only.
/// @pre Valid JWT and authenticated user context.
/// @}
void get_preferences(void);

/// @defgroup update_preferences "update_preferences"
/// @{
/// @brief Update authenticated user's dashboard filter preference.
/// @post Persists normalized preference for current user or raises validation/authorization errors.
/// @pre Valid JWT and valid request payload.
/// @}
void update_preferences(void);

/// @defgroup lookup_superset_accounts "lookup_superset_accounts"
/// @{
/// @brief Lookup Superset account candidates in selected environment.
/// @post Returns success or degraded lookup payload with stable shape.
/// @pre Valid JWT, authenticated context, and environment_id query parameter.
/// @}
void lookup_superset_accounts(void);

/// @defgroup ReportsRouter "ReportsRouter"
/// @{
/// @brief FastAPI router for unified task report list and detail retrieval endpoints.
/// @invariant Endpoints are read-only and do not trigger long-running tasks.
/// @post Router is configured and endpoints are ready for registration.
/// @pre Reports service and dependencies are initialized.
/// @}
void ReportsRouter(void);

/// @defgroup _parse_csv_enum_list "_parse_csv_enum_list"
/// @{
/// @brief Parse comma-separated query value into enum list.
/// @post Returns enum list or raises HTTP 400 with deterministic machine-readable payload.
/// @pre raw may be None/empty or comma-separated values.
/// @}
void _parse_csv_enum_list(void);

/// @defgroup list_reports "list_reports"
/// @{
/// @brief Return paginated unified reports list.
/// @post deterministic error payload for invalid filters.
/// @pre authenticated/authorized request and validated query params.
/// @}
void list_reports(void);

/// @defgroup get_report_detail "get_report_detail"
/// @{
/// @brief Return one normalized report detail with diagnostics and next actions.
/// @post returns normalized detail envelope or 404 when report is not found.
/// @pre authenticated/authorized request and existing report_id.
/// @}
void get_report_detail(void);

/// @defgroup SettingsRouter "SettingsRouter"
/// @{
/// @brief Provides API endpoints for managing application settings and Superset environments.
/// @invariant All settings changes must be persisted via ConfigManager.
/// @post Settings are read or written via ConfigManager.
/// @pre ConfigManager is initialized and accessible.
/// @}
void SettingsRouter(void);

/// @defgroup LoggingConfigResponse "LoggingConfigResponse"
/// @{
/// @brief Response model for logging configuration with current task log level.
/// @}
void LoggingConfigResponse(void);

/// @defgroup _validate_superset_connection_fast "_validate_superset_connection_fast"
/// @{
/// @brief Run lightweight Superset connectivity validation without full pagination scan.
/// @post Raises on auth/API failures; returns None on success.
/// @pre env contains valid URL and credentials.
/// @}
void _validate_superset_connection_fast(void);

/// @defgroup get_settings "get_settings"
/// @{
/// @brief Retrieves all application settings.
/// @post Returns masked AppConfig.
/// @pre Config manager is available.
/// @}
void get_settings(void);

/// @defgroup get_features "get_features"
/// @{
/// @brief Public endpoint returning feature flags for frontend sidebar filtering.
/// @post Returns dict with dataset_review and health_monitor booleans.
/// @pre Config manager is available.
/// @}
void get_features(void);

/// @defgroup get_storage_settings "get_storage_settings"
/// @{
/// @brief Retrieves storage-specific settings.
/// @}
void get_storage_settings(void);

/// @defgroup update_storage_settings "update_storage_settings"
/// @{
/// @brief Updates storage-specific settings.
/// @post Storage settings are updated and saved.
/// @}
void update_storage_settings(void);

/// @defgroup test_environment_connection "test_environment_connection"
/// @{
/// @brief Tests the connection to a Superset environment.
/// @post Returns success or error status.
/// @pre ID is provided.
/// @}
void test_environment_connection(void);

/// @defgroup get_logging_config "get_logging_config"
/// @{
/// @brief Retrieves current logging configuration.
/// @post Returns logging configuration.
/// @pre Config manager is available.
/// @}
void get_logging_config(void);

/// @defgroup update_logging_config "update_logging_config"
/// @{
/// @brief Updates logging configuration.
/// @post Logging configuration is updated and saved.
/// @pre New logging config is provided.
/// @}
void update_logging_config(void);

/// @defgroup ConsolidatedSettingsResponse "ConsolidatedSettingsResponse"
/// @{
/// @brief Response model for consolidated application settings.
/// @}
void ConsolidatedSettingsResponse(void);

/// @defgroup get_consolidated_settings "get_consolidated_settings"
/// @{
/// @brief Retrieves all settings categories in a single call.
/// @post Returns consolidated settings, provider metadata, and persisted notification payload in one stable response.
/// @pre Config manager is available and the caller holds admin settings read permission.
/// @}
void get_consolidated_settings(void);

/// @defgroup update_consolidated_settings "update_consolidated_settings"
/// @{
/// @brief Bulk update application settings from the consolidated view.
/// @post Settings are updated and saved via ConfigManager.
/// @pre User has admin permissions, config is valid.
/// @}
void update_consolidated_settings(void);

/// @defgroup get_validation_policies "get_validation_policies"
/// @{
/// @brief Lists all validation policies.
/// @}
void get_validation_policies(void);

/// @defgroup create_validation_policy "create_validation_policy"
/// @{
/// @brief Creates a new validation policy.
/// @}
void create_validation_policy(void);

/// @defgroup update_validation_policy "update_validation_policy"
/// @{
/// @brief Updates an existing validation policy.
/// @}
void update_validation_policy(void);

/// @defgroup delete_validation_policy "delete_validation_policy"
/// @{
/// @brief Deletes a validation policy.
/// @}
void delete_validation_policy(void);

/// @defgroup get_translation_schedules "get_translation_schedules"
/// @{
/// @brief Lists all translation schedules joined with translation job names.
/// @}
void get_translation_schedules(void);

/// @defgroup storage_routes "storage_routes"
/// @{
/// @brief API endpoints for file storage management (backups and repositories).
/// @invariant All paths must be validated against path traversal.
/// @}
void storage_routes(void);

/// @defgroup list_files "list_files"
/// @{
/// @brief List all files and directories in the storage system.
/// @post Returns a list of StoredFile objects.
/// @pre None.
/// @}
void list_files(void);

/// @defgroup delete_file "delete_file"
/// @{
/// @brief Delete a specific file or directory.
/// @post Item is removed from storage.
/// @pre category must be a valid FileCategory.
/// @}
void delete_file(void);

/// @defgroup download_file "download_file"
/// @{
/// @brief Retrieve a file for download.
/// @post Returns a FileResponse.
/// @pre category must be a valid FileCategory.
/// @}
void download_file(void);

/// @defgroup get_file_by_path "get_file_by_path"
/// @{
/// @brief Retrieve a file by validated absolute/relative path under storage root.
/// @post Returns a FileResponse for existing files.
/// @pre path must resolve under configured storage root.
/// @}
void get_file_by_path(void);

/// @defgroup TasksRouter "TasksRouter"
/// @{
/// @brief Defines the FastAPI router for task-related endpoints, allowing clients to create, list, and get the status of tasks.
/// @}
void TasksRouter(void);

/// @defgroup resume_task "resume_task"
/// @{
/// @brief Resume a task that is awaiting input (e.g., passwords).
/// @post Task resumes execution with provided input.
/// @pre task must be in AWAITING_INPUT status.
/// @}
void resume_task(void);

/// @defgroup TranslateRoutes "TranslateRoutes"
/// @{
/// @brief API routes for LLM-based SQL/dashboard translation management including terminology dictionary CRUD and import.
/// @post Translation job, run, dictionary, correction, preview, and schedule CRUD operations are executed.
/// @pre API server is running, user is authenticated, database is accessible.
/// @}
void TranslateRoutes(void);

/// @defgroup TranslateCorrectionRoutesModule "TranslateCorrectionRoutesModule"
/// @{
/// @brief Term correction submission endpoints.
/// @}
void TranslateCorrectionRoutesModule(void);

/// @defgroup submit_correction "submit_correction"
/// @{
/// @brief Submit a term correction from a run result review.
/// @post Correction applied with conflict detection.
/// @pre User has translate.dictionary.edit permission.
/// @}
void submit_correction(void);

/// @defgroup submit_bulk_corrections "submit_bulk_corrections"
/// @{
/// @brief Submit multiple term corrections atomically.
/// @post All corrections applied or none with conflict list.
/// @pre User has translate.dictionary.edit permission.
/// @}
void submit_bulk_corrections(void);

/// @defgroup TranslateDictionaryRoutesModule "TranslateDictionaryRoutesModule"
/// @{
/// @brief Terminology Dictionary CRUD, entries management, and import routes.
/// @}
void TranslateDictionaryRoutesModule(void);

/// @defgroup list_dictionaries "list_dictionaries"
/// @{
/// @brief List all terminology dictionaries.
/// @post Returns list of dictionaries with total count.
/// @pre User has translate.dictionary.view permission.
/// @}
void list_dictionaries(void);

/// @defgroup get_dictionary "get_dictionary"
/// @{
/// @brief Get a single terminology dictionary by ID.
/// @post Returns the dictionary with entry_count.
/// @pre User has translate.dictionary.view permission.
/// @}
void get_dictionary(void);

/// @defgroup create_dictionary "create_dictionary"
/// @{
/// @brief Create a new terminology dictionary.
/// @post Returns the created dictionary.
/// @pre User has translate.dictionary.create permission.
/// @}
void create_dictionary(void);

/// @defgroup update_dictionary "update_dictionary"
/// @{
/// @brief Update an existing terminology dictionary.
/// @post Returns the updated dictionary.
/// @pre User has translate.dictionary.edit permission.
/// @}
void update_dictionary(void);

/// @defgroup delete_dictionary "delete_dictionary"
/// @{
/// @brief Delete a terminology dictionary, blocked if attached to active/scheduled jobs.
/// @post Dictionary is deleted.
/// @pre User has translate.dictionary.delete permission.
/// @}
void delete_dictionary(void);

/// @defgroup list_dictionary_entries "list_dictionary_entries"
/// @{
/// @brief List entries for a dictionary, optionally filtered by language pair.
/// @post Returns paginated list of entries with language pair fields.
/// @pre User has translate.dictionary.view permission.
/// @}
void list_dictionary_entries(void);

/// @defgroup add_dictionary_entry "add_dictionary_entry"
/// @{
/// @brief Add a new entry to a dictionary.
/// @post Entry is created.
/// @pre User has translate.dictionary.edit permission.
/// @}
void add_dictionary_entry(void);

/// @defgroup edit_dictionary_entry "edit_dictionary_entry"
/// @{
/// @brief Update an existing dictionary entry.
/// @post Entry is updated.
/// @pre User has translate.dictionary.edit permission.
/// @}
void edit_dictionary_entry(void);

/// @defgroup delete_dictionary_entry "delete_dictionary_entry"
/// @{
/// @brief Delete a dictionary entry.
/// @post Entry is deleted.
/// @pre User has translate.dictionary.edit permission.
/// @}
void delete_dictionary_entry(void);

/// @defgroup import_dictionary_entries "import_dictionary_entries"
/// @{
/// @brief Import entries into a terminology dictionary from CSV/TSV content.
/// @post Entries are imported per conflict mode.
/// @pre User has translate.dictionary.edit permission.
/// @}
void import_dictionary_entries(void);

/// @defgroup TranslateHelpersModule "TranslateHelpersModule"
/// @{
/// @brief Shared helper functions for translate route handlers.
/// @}
void TranslateHelpersModule(void);

/// @defgroup _run_to_response "_run_to_response"
/// @{
/// @brief Convert TranslationRun ORM to response dict.
/// @}
void _run_to_response(void);

/// @defgroup _dict_to_response "_dict_to_response"
/// @{
/// @brief Convert a TerminologyDictionary ORM model to a response dict with computed entry_count.
/// @}
void _dict_to_response(void);

/// @defgroup _get_dictionary_entry_counts "_get_dictionary_entry_counts"
/// @{
/// @brief Get entry counts for a list of dictionary IDs.
/// @}
void _get_dictionary_entry_counts(void);

/// @defgroup TranslateJobRoutesModule "TranslateJobRoutesModule"
/// @{
/// @brief Translation Job CRUD and datasource column routes.
/// @}
void TranslateJobRoutesModule(void);

/// @defgroup list_jobs "list_jobs"
/// @{
/// @brief List all translation jobs.
/// @post Returns list of translation jobs.
/// @pre User has translate.job.view permission.
/// @}
void list_jobs(void);

/// @defgroup get_job "get_job"
/// @{
/// @brief Get a single translation job by ID.
/// @post Returns the translation job.
/// @pre User has translate.job.view permission.
/// @}
void get_job(void);

/// @defgroup create_job "create_job"
/// @{
/// @brief Create a new translation job.
/// @post Returns the created translation job.
/// @pre User has translate.job.create permission.
/// @}
void create_job(void);

/// @defgroup update_job "update_job"
/// @{
/// @brief Update an existing translation job.
/// @post Returns the updated translation job.
/// @pre User has translate.job.edit permission.
/// @}
void update_job(void);

/// @defgroup delete_job "delete_job"
/// @{
/// @brief Delete a translation job.
/// @post Job is deleted.
/// @pre User has translate.job.delete permission.
/// @}
void delete_job(void);

/// @defgroup duplicate_job "duplicate_job"
/// @{
/// @brief Duplicate a translation job.
/// @post Returns the duplicated job with status DRAFT.
/// @pre User has translate.job.create permission.
/// @}
void duplicate_job(void);

/// @defgroup get_datasource_columns "get_datasource_columns"
/// @{
/// @brief Get column metadata and database dialect for a Superset datasource.
/// @post Returns column list with metadata and database_dialect.
/// @pre User has translate.job.view permission.
/// @}
void get_datasource_columns(void);

/// @defgroup check_target_schema "check_target_schema"
/// @{
/// @brief Проверяет схему целевой таблицы: какие колонки ожидаются, какие есть, каких не хватает.
/// @}
void check_target_schema(void);

/// @defgroup TranslateMetricsRoutesModule "TranslateMetricsRoutesModule"
/// @{
/// @brief Translation Metrics endpoints.
/// @}
void TranslateMetricsRoutesModule(void);

/// @defgroup get_metrics "get_metrics"
/// @{
/// @brief Get translation metrics, optionally filtered by job.
/// @post Returns metrics data.
/// @pre User has translate.metrics.view permission.
/// @}
void get_metrics(void);

/// @defgroup get_job_metrics "get_job_metrics"
/// @{
/// @brief Get aggregated metrics for a specific job.
/// @post Returns metrics dict.
/// @pre User has translate.metrics.view permission.
/// @}
void get_job_metrics(void);

/// @defgroup TranslatePreviewRoutesModule "TranslatePreviewRoutesModule"
/// @{
/// @brief Translation Preview session management routes.
/// @}
void TranslatePreviewRoutesModule(void);

/// @defgroup preview_translation "preview_translation"
/// @{
/// @brief Preview a translation before applying it.
/// @post Returns a preview session with records and cost estimation.
/// @pre User has translate.job.execute permission.
/// @}
void preview_translation(void);

/// @defgroup update_preview_row "update_preview_row"
/// @{
/// @brief Approve, edit, or reject a preview row (optionally per language).
/// @post Preview row status is updated.
/// @pre User has translate.job.execute permission.
/// @}
void update_preview_row(void);

/// @defgroup accept_preview_session "accept_preview_session"
/// @{
/// @brief Accept a preview session, marking it as the quality gate for full execution.
/// @post Preview session is marked as APPLIED; full execution can proceed.
/// @pre User has translate.job.execute permission. Job has an ACTIVE preview session.
/// @}
void accept_preview_session(void);

/// @defgroup apply_preview "apply_preview"
/// @{
/// @brief Apply a preview session (alias for accept when accepting at session level).
/// @post Preview is applied.
/// @pre User has translate.job.execute permission.
/// @}
void apply_preview(void);

/// @defgroup get_preview_records "get_preview_records"
/// @{
/// @brief Get records for a preview session.
/// @post Returns list of preview records.
/// @pre User has translate.job.view permission.
/// @}
void get_preview_records(void);

/// @defgroup TranslateRouterModule "TranslateRouterModule"
/// @{
/// @brief APIRouter instance for translate routes.
/// @}
void TranslateRouterModule(void);

/// @defgroup translate_router "translate_router"
/// @{
/// @brief APIRouter instance for all translate sub-routes.
/// @}
void translate_router(void);

/// @defgroup TranslateRunListRoutesModule "TranslateRunListRoutesModule"
/// @{
/// @brief Translation Run listing, detail, and CSV download routes (cross-job).
/// @}
void TranslateRunListRoutesModule(void);

/// @defgroup download_skipped_csv "download_skipped_csv"
/// @{
/// @brief Download a CSV of skipped translation records from a run.
/// @post Returns CSV file of skipped records.
/// @pre User has translate.job.view permission.
/// @}
void download_skipped_csv(void);

/// @defgroup TranslateRunRoutesModule "TranslateRunRoutesModule"
/// @{
/// @brief Translation Run execution, history, status, records and batches routes.
/// @}
void TranslateRunRoutesModule(void);

/// @defgroup run_translation "run_translation"
/// @{
/// @brief Execute a translation job (trigger a run).
/// @post Returns the created translation run.
/// @pre User has translate.job.execute permission.
/// @}
void run_translation(void);

/// @defgroup retry_run "retry_run"
/// @{
/// @brief Retry failed batches in a translation run.
/// @post Returns the updated translation run.
/// @pre User has translate.job.execute permission.
/// @}
void retry_run(void);

/// @defgroup retry_insert "retry_insert"
/// @{
/// @brief Retry the SQL insert phase for a completed run.
/// @post Returns the updated run.
/// @pre User has translate.job.execute permission.
/// @}
void retry_insert(void);

/// @defgroup cancel_run "cancel_run"
/// @{
/// @brief Cancel a running translation.
/// @post Run is cancelled.
/// @pre User has translate.job.execute permission.
/// @}
void cancel_run(void);

/// @defgroup get_run_history "get_run_history"
/// @{
/// @brief Get run history for a translation job.
/// @post Returns list of runs.
/// @pre User has translate.history.view permission.
/// @}
void get_run_history(void);

/// @defgroup get_run_status "get_run_status"
/// @{
/// @brief Get status and statistics for a translation run.
/// @post Returns run details with statistics.
/// @pre User has translate.history.view permission.
/// @}
void get_run_status(void);

/// @defgroup get_run_records "get_run_records"
/// @{
/// @brief Get paginated records for a translation run.
/// @post Returns paginated records.
/// @pre User has translate.history.view permission.
/// @}
void get_run_records(void);

/// @defgroup get_batches "get_batches"
/// @{
/// @brief Get batches for a translation run.
/// @post Returns list of batches.
/// @pre User has translate.job.view permission.
/// @}
void get_batches(void);

/// @defgroup override_detected_language "override_detected_language"
/// @{
/// @brief Manually override the detected source language for a specific translation language entry.
/// @post TranslationLanguage.source_language_detected is updated; language_overridden is set to True.
/// @pre User has translate.job.execute permission. Run, record, and language entry exist.
/// @}
void override_detected_language(void);

/// @defgroup inline_edit_translation "inline_edit_translation"
/// @{
/// @brief Apply an inline correction to a translated value on a completed run result.
/// @post TranslationLanguage.final_value and user_edit are updated. Optional dictionary submission.
/// @pre User has translate.job.execute permission. Run, record, and language entry exist.
/// @}
void inline_edit_translation(void);

/// @defgroup bulk_find_replace "bulk_find_replace"
/// @{
/// @brief Perform bulk find-and-replace on translated values within a run.
/// @post If preview=false, matching translations are updated. Optional dictionary submission.
/// @pre User has translate.job.execute permission. Run exists.
/// @}
void bulk_find_replace(void);

/// @defgroup TranslateScheduleRoutesModule "TranslateScheduleRoutesModule"
/// @{
/// @brief Translation Schedule management routes.
/// @}
void TranslateScheduleRoutesModule(void);

/// @defgroup get_schedule "get_schedule"
/// @{
/// @brief Get the schedule for a translation job.
/// @post Returns the schedule configuration.
/// @pre User has translate.schedule.view permission.
/// @}
void get_schedule(void);

/// @defgroup set_schedule "set_schedule"
/// @{
/// @brief Set or update the schedule for a translation job.
/// @post Schedule is created or updated.
/// @pre User has translate.schedule.manage permission.
/// @}
void set_schedule(void);

/// @defgroup enable_schedule "enable_schedule"
/// @{
/// @brief Enable a schedule for a translation job.
/// @post Schedule is enabled.
/// @pre User has translate.schedule.manage permission.
/// @}
void enable_schedule(void);

/// @defgroup disable_schedule "disable_schedule"
/// @{
/// @brief Disable a schedule for a translation job.
/// @post Schedule is disabled.
/// @pre User has translate.schedule.manage permission.
/// @}
void disable_schedule(void);

/// @defgroup delete_schedule "delete_schedule"
/// @{
/// @brief Delete the schedule for a translation job.
/// @post Schedule is removed.
/// @pre User has translate.schedule.manage permission.
/// @}
void delete_schedule(void);

/// @defgroup get_next_executions "get_next_executions"
/// @{
/// @brief Preview next N executions for a job's schedule.
/// @post Returns next execution times.
/// @pre User has translate.schedule.view permission.
/// @}
void get_next_executions(void);

/// @defgroup ValidationRoutes "ValidationRoutes"
/// @{
/// @brief API routes for validation task management and run history.
/// @}
void ValidationRoutes(void);

/// @defgroup _get_task_service "_get_task_service"
/// @{
/// @}
void _get_task_service(void);

/// @defgroup _get_run_service "_get_run_service"
/// @{
/// @}
void _get_run_service(void);

/// @defgroup list_tasks "list_tasks"
/// @{
/// @}
void list_tasks(void);

/// @defgroup update_task "update_task"
/// @{
/// @}
void update_task(void);

/// @defgroup delete_task "delete_task"
/// @{
/// @}
void delete_task(void);

/// @defgroup trigger_run "trigger_run"
/// @{
/// @}
void trigger_run(void);

/// @defgroup list_runs "list_runs"
/// @{
/// @}
void list_runs(void);

/// @defgroup get_run_detail "get_run_detail"
/// @{
/// @}
void get_run_detail(void);

/// @defgroup delete_run "delete_run"
/// @{
/// @}
void delete_run(void);

/// @defgroup ValidationApiTests "ValidationApiTests"
/// @{
/// @brief Unit tests for validation task CRUD and run history API endpoints.
/// @invariant provider_id must reference a multimodal LLM provider for creation
/// @}
void ValidationApiTests(void);

/// @defgroup test_list_tasks_success "test_list_tasks_success"
/// @{
/// @brief GET /validation/tasks returns paginated task list with filters.
/// @}
void test_list_tasks_success(void);

/// @defgroup test_list_tasks_pagination "test_list_tasks_pagination"
/// @{
/// @brief Pagination query params are validated: page >= 1, page_size 1-100.
/// @}
void test_list_tasks_pagination(void);

/// @defgroup test_list_tasks_service_error "test_list_tasks_service_error"
/// @{
/// @brief Service ValueError becomes 400 on list_tasks.
/// @}
void test_list_tasks_service_error(void);

/// @defgroup test_create_task_success "test_create_task_success"
/// @{
/// @brief POST /validation/tasks with valid payload returns 201.
/// @}
void test_create_task_success(void);

/// @defgroup test_create_task_missing_fields "test_create_task_missing_fields"
/// @{
/// @brief POST with missing required fields returns 422.
/// @}
void test_create_task_missing_fields(void);

/// @defgroup test_create_task_invalid_provider "test_create_task_invalid_provider"
/// @{
/// @brief POST with non-multimodal provider returns 422.
/// @}
void test_create_task_invalid_provider(void);

/// @defgroup test_get_task_success "test_get_task_success"
/// @{
/// @brief GET /validation/tasks/{id} returns task with recent_runs.
/// @}
void test_get_task_success(void);

/// @defgroup test_get_task_not_found "test_get_task_not_found"
/// @{
/// @brief GET for nonexistent task returns 404.
/// @}
void test_get_task_not_found(void);

/// @defgroup test_update_task_success "test_update_task_success"
/// @{
/// @brief PUT /validation/tasks/{id} updates task and returns updated object.
/// @}
void test_update_task_success(void);

/// @defgroup test_update_task_not_found "test_update_task_not_found"
/// @{
/// @brief PUT for nonexistent task returns 404.
/// @}
void test_update_task_not_found(void);

/// @defgroup test_delete_task_success "test_delete_task_success"
/// @{
/// @brief DELETE /validation/tasks/{id} returns 204.
/// @}
void test_delete_task_success(void);

/// @defgroup test_delete_task_not_found "test_delete_task_not_found"
/// @{
/// @brief DELETE for nonexistent task returns 404.
/// @}
void test_delete_task_not_found(void);

/// @defgroup test_delete_task_with_runs_flag "test_delete_task_with_runs_flag"
/// @{
/// @brief DELETE with delete_runs=true passes query param to service.
/// @}
void test_delete_task_with_runs_flag(void);

/// @defgroup test_trigger_run_success "test_trigger_run_success"
/// @{
/// @brief POST /validation/tasks/{id}/run spawns a validation task.
/// @}
void test_trigger_run_success(void);

/// @defgroup test_trigger_run_not_found "test_trigger_run_not_found"
/// @{
/// @brief POST for nonexistent task returns 422.
/// @}
void test_trigger_run_not_found(void);

/// @defgroup test_trigger_run_no_dashboards "test_trigger_run_no_dashboards"
/// @{
/// @brief Trigger fails with 422 when task has no dashboard IDs.
/// @}
void test_trigger_run_no_dashboards(void);

/// @defgroup test_list_runs_success "test_list_runs_success"
/// @{
/// @brief GET /validation/runs returns paginated run list.
/// @}
void test_list_runs_success(void);

/// @defgroup test_list_runs_filters "test_list_runs_filters"
/// @{
/// @brief All 6 filter query params are accepted and forwarded to service.
/// @}
void test_list_runs_filters(void);

/// @defgroup test_list_runs_pagination "test_list_runs_pagination"
/// @{
/// @brief Pagination boundary checks on runs list.
/// @}
void test_list_runs_pagination(void);

/// @defgroup test_list_runs_invalid_status "test_list_runs_invalid_status"
/// @{
/// @brief Status is a free string; any value passes through to service.
/// @}
void test_list_runs_invalid_status(void);

/// @defgroup test_get_run_detail_success "test_get_run_detail_success"
/// @{
/// @brief GET /validation/runs/{id} returns full detail with issues and raw_response.
/// @}
void test_get_run_detail_success(void);

/// @defgroup test_get_run_detail_not_found "test_get_run_detail_not_found"
/// @{
/// @brief GET for nonexistent run returns 404.
/// @}
void test_get_run_detail_not_found(void);

/// @defgroup test_delete_run_success "test_delete_run_success"
/// @{
/// @brief DELETE /validation/runs/{id} returns 204.
/// @}
void test_delete_run_success(void);

/// @defgroup test_delete_run_not_found "test_delete_run_not_found"
/// @{
/// @brief DELETE for nonexistent run returns 404.
/// @}
void test_delete_run_not_found(void);

/// @defgroup test_endpoints_require_authentication "test_endpoints_require_authentication"
/// @{
/// @brief Without current_user dependency, all 9 endpoints return 401.
/// @}
void test_endpoints_require_authentication(void);

/// @defgroup test_permission_denied_non_admin "test_permission_denied_non_admin"
/// @{
/// @brief A non-admin user without validation.* permissions receives 403.
/// @}
void test_permission_denied_non_admin(void);

/// @defgroup test_permission_denied_all_actions "test_permission_denied_all_actions"
/// @{
/// @brief Each action (VIEW, CREATE, EDIT, DELETE, EXECUTE) denied for non-admin.
/// @}
void test_permission_denied_all_actions(void);

/// @defgroup test_delete_task_runs_default_false "test_delete_task_runs_default_false"
/// @{
/// @brief delete_runs query param defaults to False.
/// @}
void test_delete_task_runs_default_false(void);

/// @defgroup AppModule "AppModule"
/// @{
/// @brief The main entry point for the FastAPI application.
/// @invariant All WebSocket connections must be properly cleaned up on disconnect.
/// @post FastAPI app instance is created, middleware configured, and routes registered.
/// @pre Python environment and dependencies installed; configuration database available.
/// @}
void AppModule(void);

/// @defgroup FastAPI_App "FastAPI_App"
/// @{
/// @brief Canonical FastAPI application instance for route, middleware, and websocket registration.
/// @}
void FastAPI_App(void);

/// @defgroup ensure_initial_admin_user "ensure_initial_admin_user"
/// @{
/// @brief Ensures initial admin user exists when bootstrap env flags are enabled.
/// @}
void ensure_initial_admin_user(void);

/// @defgroup startup_event "startup_event"
/// @{
/// @brief Handles application startup tasks, such as starting the scheduler.
/// @post Scheduler is started.
/// @pre None.
/// @}
void startup_event(void);

/// @defgroup shutdown_event "shutdown_event"
/// @{
/// @brief Handles application shutdown tasks, such as stopping the scheduler.
/// @post Scheduler is stopped.
/// @pre None.
/// @}
void shutdown_event(void);

/// @defgroup app_middleware "app_middleware"
/// @{
/// @brief Configure application-wide middleware (Session, CORS).
/// @}
void app_middleware(void);

/// @defgroup network_error_handler "network_error_handler"
/// @{
/// @brief Global exception handler for NetworkError.
/// @post Returns 503 HTTP Exception.
/// @pre request is a FastAPI Request object.
/// @}
void network_error_handler(void);

/// @defgroup log_requests "log_requests"
/// @{
/// @brief Middleware to log incoming HTTP requests and their response status.
/// @post Logs request and response details.
/// @pre request is a FastAPI Request object.
/// @}
void log_requests(void);

/// @defgroup API_Routes "API_Routes"
/// @{
/// @brief Register all FastAPI route groups exposed by the application entrypoint.
/// @}
void API_Routes(void);

/// @defgroup api_include_routers "api.include_routers"
/// @{
/// @brief Registers all API routers with the FastAPI application.
/// @}
void api_include_routers(void);

/// @defgroup websocket_endpoint "websocket_endpoint"
/// @{
/// @brief Provides a WebSocket endpoint for real-time log streaming of a task with server-side filtering.
/// @invariant Every accepted WebSocket subscription is unsubscribed exactly once even when streaming fails or the client disconnects.
/// @post WebSocket connection is managed and logs are streamed until disconnect.
/// @pre task_id must be a valid task ID.
/// @}
void websocket_endpoint(void);

/// @defgroup dataset_websocket_endpoint "dataset_websocket_endpoint"
/// @{
/// @brief WebSocket endpoint for dataset.updated events — auto-refresh on task completion.
/// @post WebSocket streams dataset.updated events until disconnect.
/// @pre env_id must reference a known environment.
/// @}
void dataset_websocket_endpoint(void);

/// @defgroup StaticFiles "StaticFiles"
/// @{
/// @brief Mounts the frontend build directory to serve static assets.
/// @}
void StaticFiles(void);

/// @defgroup serve_spa "serve_spa"
/// @{
/// @brief Serves the SPA frontend for any path not matched by API routes.
/// @post Returns the requested file or index.html.
/// @pre frontend_path exists.
/// @}
void serve_spa(void);

/// @defgroup read_root "read_root"
/// @{
/// @brief A simple root endpoint to confirm that the API is running when frontend is missing.
/// @post Returns a JSON message indicating API status.
/// @pre None.
/// @}
void read_root(void);

/// @defgroup src_core "src.core"
/// @{
/// @brief Backend core services and infrastructure package root.
/// @}
void src_core(void);

/// @defgroup TestConfigManagerCompat "TestConfigManagerCompat"
/// @{
/// @brief Verifies ConfigManager compatibility wrappers preserve legacy payload sections.
/// @}
void TestConfigManagerCompat(void);

/// @defgroup test_get_payload_preserves_legacy_sections "test_get_payload_preserves_legacy_sections"
/// @{
/// @brief Ensure get_payload merges typed config into raw payload without dropping legacy sections.
/// @}
void test_get_payload_preserves_legacy_sections(void);

/// @defgroup test_save_config_accepts_raw_payload_and_keeps_extras "test_save_config_accepts_raw_payload_and_keeps_extras"
/// @{
/// @brief Ensure save_config accepts raw dict payload, refreshes typed config, and preserves extra sections.
/// @}
void test_save_config_accepts_raw_payload_and_keeps_extras(void);

/// @defgroup test_save_config_syncs_environment_records_for_fk_backed_flows "test_save_config_syncs_environment_records_for_fk_backed_flows"
/// @{
/// @brief Ensure saving config mirrors typed environments into relational records required by FK-backed session persistence.
/// @}
void test_save_config_syncs_environment_records_for_fk_backed_flows(void);

/// @defgroup _FakeQuery "_FakeQuery"
/// @{
/// @brief Minimal query stub returning hardcoded existing environment record list for sync tests.
/// @invariant all() always returns [existing_record]; no parameterization or filtering.
/// @}
void _FakeQuery(void);

/// @defgroup _FakeSession "_FakeSession"
/// @{
/// @brief Minimal SQLAlchemy session stub that captures add/delete calls for environment sync assertions.
/// @invariant query() always returns _FakeQuery; no real DB interaction.
/// @}
void _FakeSession(void);

/// @defgroup test_save_config_syncs_deletions_to_persistence "test_save_config_syncs_deletions_to_persistence"
/// @{
/// @brief Ensure stale environment records are deleted during save (in _delete_stale_environment_records)
/// @}
void test_save_config_syncs_deletions_to_persistence(void);

/// @defgroup _FakeQueryDel "_FakeQueryDel"
/// @{
/// @brief Minimal query stub for deletion test.
/// @}
void _FakeQueryDel(void);

/// @defgroup _FakeSessionDel "_FakeSessionDel"
/// @{
/// @brief Minimal session stub that captures add/delete for deletion assertions.
/// @}
void _FakeSessionDel(void);

/// @defgroup test_load_config_syncs_environment_records_from_existing_db_payload "test_load_config_syncs_environment_records_from_existing_db_payload"
/// @{
/// @brief Ensure loading an existing DB-backed config also mirrors environment rows required by FK-backed runtime flows.
/// @}
void test_load_config_syncs_environment_records_from_existing_db_payload(void);

/// @defgroup NativeFilterExtractionTests "NativeFilterExtractionTests"
/// @{
/// @brief Verify native filter extraction from permalinks and native_filters_key URLs.
/// @}
void NativeFilterExtractionTests(void);

/// @defgroup test_extract_native_filters_from_permalink "test_extract_native_filters_from_permalink"
/// @{
/// @brief Extract native filters from a permalink key.
/// @}
void test_extract_native_filters_from_permalink(void);

/// @defgroup test_extract_native_filters_from_permalink_direct_response "test_extract_native_filters_from_permalink_direct_response"
/// @{
/// @brief Handle permalink response without result wrapper.
/// @}
void test_extract_native_filters_from_permalink_direct_response(void);

/// @defgroup test_extract_native_filters_from_key "test_extract_native_filters_from_key"
/// @{
/// @brief Extract native filters from a native_filters_key.
/// @}
void test_extract_native_filters_from_key(void);

/// @defgroup test_extract_native_filters_from_key_single_filter "test_extract_native_filters_from_key_single_filter"
/// @{
/// @brief Handle single filter format in native filter state.
/// @}
void test_extract_native_filters_from_key_single_filter(void);

/// @defgroup test_extract_native_filters_from_key_dict_value "test_extract_native_filters_from_key_dict_value"
/// @{
/// @brief Handle filter state value as dict instead of JSON string.
/// @}
void test_extract_native_filters_from_key_dict_value(void);

/// @defgroup test_parse_dashboard_url_for_filters_permalink "test_parse_dashboard_url_for_filters_permalink"
/// @{
/// @brief Parse permalink URL format.
/// @}
void test_parse_dashboard_url_for_filters_permalink(void);

/// @defgroup test_parse_dashboard_url_for_filters_native_key "test_parse_dashboard_url_for_filters_native_key"
/// @{
/// @brief Parse native_filters_key URL format with numeric dashboard ID.
/// @}
void test_parse_dashboard_url_for_filters_native_key(void);

/// @defgroup test_parse_dashboard_url_for_filters_native_key_slug "test_parse_dashboard_url_for_filters_native_key_slug"
/// @{
/// @brief Parse native_filters_key URL format when dashboard reference is a slug, not a numeric ID.
/// @}
void test_parse_dashboard_url_for_filters_native_key_slug(void);

/// @defgroup test_parse_dashboard_url_for_filters_native_key_slug_resolution_fails "test_parse_dashboard_url_for_filters_native_key_slug_resolution_fails"
/// @{
/// @brief Gracefully handle slug resolution failure for native_filters_key URL.
/// @}
void test_parse_dashboard_url_for_filters_native_key_slug_resolution_fails(void);

/// @defgroup test_parse_dashboard_url_for_filters_native_filters_direct "test_parse_dashboard_url_for_filters_native_filters_direct"
/// @{
/// @brief Parse native_filters direct query param.
/// @}
void test_parse_dashboard_url_for_filters_native_filters_direct(void);

/// @defgroup test_parse_dashboard_url_for_filters_no_filters "test_parse_dashboard_url_for_filters_no_filters"
/// @{
/// @brief Return empty result when no filters present.
/// @}
void test_parse_dashboard_url_for_filters_no_filters(void);

/// @defgroup test_extra_form_data_merge "test_extra_form_data_merge"
/// @{
/// @brief Test ExtraFormDataMerge correctly merges dictionaries.
/// @}
void test_extra_form_data_merge(void);

/// @defgroup test_filter_state_model "test_filter_state_model"
/// @{
/// @brief Test FilterState Pydantic model.
/// @}
void test_filter_state_model(void);

/// @defgroup test_parsed_native_filters_model "test_parsed_native_filters_model"
/// @{
/// @brief Test ParsedNativeFilters Pydantic model.
/// @}
void test_parsed_native_filters_model(void);

/// @defgroup test_parsed_native_filters_empty "test_parsed_native_filters_empty"
/// @{
/// @brief Test ParsedNativeFilters with no filters.
/// @}
void test_parsed_native_filters_empty(void);

/// @defgroup test_native_filter_data_mask_model "test_native_filter_data_mask_model"
/// @{
/// @brief Test NativeFilterDataMask model.
/// @}
void test_native_filter_data_mask_model(void);

/// @defgroup test_recover_imported_filters_reconciles_raw_native_filter_ids_to_metadata_names "test_recover_imported_filters_reconciles_raw_native_filter_ids_to_metadata_names"
/// @{
/// @brief Reconcile raw native filter ids from state to canonical metadata filter names.
/// @}
void test_recover_imported_filters_reconciles_raw_native_filter_ids_to_metadata_names(void);

/// @defgroup test_recover_imported_filters_collapses_state_and_metadata_duplicates_into_one_canonical_filter "test_recover_imported_filters_collapses_state_and_metadata_duplicates_into_one_canonical_filter"
/// @{
/// @brief Collapse raw-id state entries and metadata entries into one canonical filter.
/// @}
void test_recover_imported_filters_collapses_state_and_metadata_duplicates_into_one_canonical_filter(void);

/// @defgroup test_recover_imported_filters_preserves_unmatched_raw_native_filter_ids "test_recover_imported_filters_preserves_unmatched_raw_native_filter_ids"
/// @{
/// @brief Preserve unmatched raw native filter ids as fallback diagnostics when metadata mapping is unavailable.
/// @}
void test_recover_imported_filters_preserves_unmatched_raw_native_filter_ids(void);

/// @defgroup test_extract_imported_filters_preserves_clause_level_native_filter_payload_for_preview "test_extract_imported_filters_preserves_clause_level_native_filter_payload_for_preview"
/// @{
/// @brief Recovered native filter state should preserve exact Superset clause payload and time extras for preview compilation.
/// @}
void test_extract_imported_filters_preserves_clause_level_native_filter_payload_for_preview(void);

/// @defgroup test_sanitize_imported_filter_for_assistant_masks_sensitive_raw_values "test_sanitize_imported_filter_for_assistant_masks_sensitive_raw_values"
/// @{
/// @brief Assistant-facing imported-filter payload should redact likely PII while preserving structure metadata.
/// @}
void test_sanitize_imported_filter_for_assistant_masks_sensitive_raw_values(void);

/// @defgroup SupersetPreviewPipelineTests "SupersetPreviewPipelineTests"
/// @{
/// @brief Verify explicit chart-data preview compilation and ensure non-dashboard 404 errors remain generic across sync and async clients.
/// @}
void SupersetPreviewPipelineTests(void);

/// @defgroup _make_environment "_make_environment"
/// @{
/// @}
void _make_environment(void);

/// @defgroup _make_requests_http_error "_make_requests_http_error"
/// @{
/// @}
void _make_requests_http_error(void);

/// @defgroup _make_httpx_status_error "_make_httpx_status_error"
/// @{
/// @}
void _make_httpx_status_error(void);

/// @defgroup test_compile_dataset_preview_prefers_legacy_explore_form_data_strategy "test_compile_dataset_preview_prefers_legacy_explore_form_data_strategy"
/// @{
/// @brief Superset preview compilation should prefer the legacy form_data transport inferred from browser traffic before falling back to chart-data.
/// @}
void test_compile_dataset_preview_prefers_legacy_explore_form_data_strategy(void);

/// @defgroup test_compile_dataset_preview_falls_back_to_chart_data_after_legacy_failures "test_compile_dataset_preview_falls_back_to_chart_data_after_legacy_failures"
/// @{
/// @brief Superset preview compilation should fall back to chart-data when legacy form_data strategies are rejected.
/// @}
void test_compile_dataset_preview_falls_back_to_chart_data_after_legacy_failures(void);

/// @defgroup test_build_dataset_preview_query_context_places_recovered_filters_in_chart_style_form_data "test_build_dataset_preview_query_context_places_recovered_filters_in_chart_style_form_data"
/// @{
/// @brief Preview query context should mirror chart-style filter transport so recovered native filters reach Superset compilation.
/// @}
void test_build_dataset_preview_query_context_places_recovered_filters_in_chart_style_form_data(void);

/// @defgroup test_build_dataset_preview_query_context_merges_dataset_template_params_and_preserves_user_values "test_build_dataset_preview_query_context_merges_dataset_template_params_and_preserves_user_values"
/// @{
/// @brief Preview query context should merge dataset template params for parity with real dataset definitions while preserving explicit session overrides.
/// @}
void test_build_dataset_preview_query_context_merges_dataset_template_params_and_preserves_user_values(void);

/// @defgroup test_build_dataset_preview_query_context_preserves_time_range_from_native_filter_payload "test_build_dataset_preview_query_context_preserves_time_range_from_native_filter_payload"
/// @{
/// @brief Preview query context should preserve time-range native filter extras even when dataset defaults differ.
/// @}
void test_build_dataset_preview_query_context_preserves_time_range_from_native_filter_payload(void);

/// @defgroup test_build_dataset_preview_legacy_form_data_preserves_native_filter_clauses "test_build_dataset_preview_legacy_form_data_preserves_native_filter_clauses"
/// @{
/// @brief Legacy preview form_data should preserve recovered native filter clauses in browser-style fields without duplicating datasource for QueryObjectFactory.
/// @}
void test_build_dataset_preview_legacy_form_data_preserves_native_filter_clauses(void);

/// @defgroup test_sync_network_404_mapping_keeps_non_dashboard_endpoints_generic "test_sync_network_404_mapping_keeps_non_dashboard_endpoints_generic"
/// @{
/// @brief Sync network client should reserve dashboard-not-found translation for dashboard endpoints only.
/// @}
void test_sync_network_404_mapping_keeps_non_dashboard_endpoints_generic(void);

/// @defgroup test_sync_network_404_mapping_translates_dashboard_endpoints "test_sync_network_404_mapping_translates_dashboard_endpoints"
/// @{
/// @brief Sync network client should still translate dashboard endpoint 404 responses into dashboard-not-found errors.
/// @}
void test_sync_network_404_mapping_translates_dashboard_endpoints(void);

/// @defgroup test_async_network_404_mapping_keeps_non_dashboard_endpoints_generic "test_async_network_404_mapping_keeps_non_dashboard_endpoints_generic"
/// @{
/// @brief Async network client should reserve dashboard-not-found translation for dashboard endpoints only.
/// @}
void test_async_network_404_mapping_keeps_non_dashboard_endpoints_generic(void);

/// @defgroup test_async_network_404_mapping_translates_dashboard_endpoints "test_async_network_404_mapping_translates_dashboard_endpoints"
/// @{
/// @brief Async network client should still translate dashboard endpoint 404 responses into dashboard-not-found errors.
/// @}
void test_async_network_404_mapping_translates_dashboard_endpoints(void);

/// @defgroup TestSupersetProfileLookup "TestSupersetProfileLookup"
/// @{
/// @brief Verifies Superset profile lookup adapter payload normalization and fallback error precedence.
/// @}
void TestSupersetProfileLookup(void);

/// @defgroup _RecordingNetworkClient "_RecordingNetworkClient"
/// @{
/// @brief Records request payloads and returns scripted responses for deterministic adapter tests.
/// @invariant Each request consumes one scripted response in call order and persists call metadata.
/// @}
void _RecordingNetworkClient(void);

/// @defgroup test_get_users_page_sends_lowercase_order_direction "test_get_users_page_sends_lowercase_order_direction"
/// @{
/// @brief Ensures adapter sends lowercase order_direction compatible with Superset rison schema.
/// @post First request query payload contains order_direction='asc' for asc sort.
/// @pre Adapter is initialized with recording network client.
/// @}
void test_get_users_page_sends_lowercase_order_direction(void);

/// @defgroup test_get_users_page_preserves_primary_schema_error_over_fallback_auth_error "test_get_users_page_preserves_primary_schema_error_over_fallback_auth_error"
/// @{
/// @brief Ensures fallback auth error does not mask primary schema/query failure.
/// @post Raised exception remains primary SupersetAPIError (non-auth) to preserve root cause.
/// @pre Primary endpoint fails with SupersetAPIError and fallback fails with AuthenticationError.
/// @}
void test_get_users_page_preserves_primary_schema_error_over_fallback_auth_error(void);

/// @defgroup test_get_users_page_uses_fallback_endpoint_when_primary_fails "test_get_users_page_uses_fallback_endpoint_when_primary_fails"
/// @{
/// @brief Verifies adapter retries second users endpoint and succeeds when fallback is healthy.
/// @post Result status is success and both endpoints were attempted in order.
/// @pre Primary endpoint fails; fallback returns valid users payload.
/// @}
void test_get_users_page_uses_fallback_endpoint_when_primary_fails(void);

/// @defgroup test_throttled_scheduler "test_throttled_scheduler"
/// @{
/// @brief Unit tests for ThrottledSchedulerConfigurator distribution logic.
/// @}
void test_throttled_scheduler(void);

/// @defgroup test_calculate_schedule_even_distribution "test_calculate_schedule_even_distribution"
/// @{
/// @brief Validate even spacing across a two-hour scheduling window for three tasks.
/// @}
void test_calculate_schedule_even_distribution(void);

/// @defgroup test_calculate_schedule_midnight_crossing "test_calculate_schedule_midnight_crossing"
/// @{
/// @brief Validate scheduler correctly rolls timestamps into the next day across midnight.
/// @}
void test_calculate_schedule_midnight_crossing(void);

/// @defgroup test_calculate_schedule_single_task "test_calculate_schedule_single_task"
/// @{
/// @brief Validate single-task schedule returns only the window start timestamp.
/// @}
void test_calculate_schedule_single_task(void);

/// @defgroup test_calculate_schedule_empty_list "test_calculate_schedule_empty_list"
/// @{
/// @brief Validate empty dashboard list produces an empty schedule.
/// @}
void test_calculate_schedule_empty_list(void);

/// @defgroup test_calculate_schedule_zero_window "test_calculate_schedule_zero_window"
/// @{
/// @brief Validate zero-length window schedules all tasks at identical start timestamp.
/// @}
void test_calculate_schedule_zero_window(void);

/// @defgroup test_calculate_schedule_very_small_window "test_calculate_schedule_very_small_window"
/// @{
/// @brief Validate sub-second interpolation when task count exceeds near-zero window granularity.
/// @}
void test_calculate_schedule_very_small_window(void);

/// @defgroup AsyncSupersetClientModule "AsyncSupersetClientModule"
/// @{
/// @brief Parse a Superset dashboard URL and extract native filter state asynchronously.
/// @}
void AsyncSupersetClientModule(void);

/// @defgroup AsyncSupersetClient "AsyncSupersetClient"
/// @{
/// @brief Async sibling of SupersetClient for dashboard read paths.
/// @}
void AsyncSupersetClient(void);

/// @defgroup AsyncSupersetClientInit "AsyncSupersetClientInit"
/// @{
/// @brief Initialize async Superset client with AsyncAPIClient transport.
/// @post Client uses async network transport and inherited projection helpers.
/// @pre env is valid Environment instance.
/// @}
void AsyncSupersetClientInit(void);

/// @defgroup AsyncSupersetClientClose "AsyncSupersetClientClose"
/// @{
/// @brief Close async transport resources.
/// @post Underlying AsyncAPIClient is closed.
/// @}
void AsyncSupersetClientClose(void);

/// @defgroup get_dashboards_page_async "get_dashboards_page_async"
/// @{
/// @brief Fetch one dashboards page asynchronously.
/// @post Returns total count and page result list.
/// @}
void get_dashboards_page_async(void);

/// @defgroup get_dashboard_async "get_dashboard_async"
/// @{
/// @brief Fetch one dashboard payload asynchronously.
/// @post Returns raw dashboard payload from Superset API.
/// @}
void get_dashboard_async(void);

/// @defgroup get_chart_async "get_chart_async"
/// @{
/// @brief Fetch one chart payload asynchronously.
/// @post Returns raw chart payload from Superset API.
/// @}
void get_chart_async(void);

/// @defgroup get_dashboard_detail_async "get_dashboard_detail_async"
/// @{
/// @brief Fetch dashboard detail asynchronously with concurrent charts/datasets requests.
/// @post Returns dashboard detail payload for overview page.
/// @}
void get_dashboard_detail_async(void);

/// @defgroup get_dashboard_permalink_state_async "get_dashboard_permalink_state_async"
/// @{
/// @brief Fetch stored dashboard permalink state asynchronously.
/// @post Returns dashboard permalink state payload from Superset API.
/// @}
void get_dashboard_permalink_state_async(void);

/// @defgroup get_native_filter_state_async "get_native_filter_state_async"
/// @{
/// @brief Fetch stored native filter state asynchronously.
/// @post Returns native filter state payload from Superset API.
/// @}
void get_native_filter_state_async(void);

/// @defgroup extract_native_filters_from_permalink_async "extract_native_filters_from_permalink_async"
/// @{
/// @brief Extract native filters dataMask from a permalink key asynchronously.
/// @post Returns extracted dataMask with filter states.
/// @}
void extract_native_filters_from_permalink_async(void);

/// @defgroup extract_native_filters_from_key_async "extract_native_filters_from_key_async"
/// @{
/// @brief Extract native filters from a native_filters_key URL parameter asynchronously.
/// @post Returns extracted filter state with extraFormData.
/// @}
void extract_native_filters_from_key_async(void);

/// @defgroup parse_dashboard_url_for_filters_async "parse_dashboard_url_for_filters_async"
/// @{
/// @brief Parse a Superset dashboard URL and extract native filter state asynchronously.
/// @post Returns extracted filter state or empty dict if no filters found.
/// @}
void parse_dashboard_url_for_filters_async(void);

/// @defgroup AuthPackage "AuthPackage"
/// @{
/// @brief Authentication and authorization package root.
/// @}
void AuthPackage(void);

/// @defgroup test_auth "test_auth"
/// @{
/// @brief Unit tests for authentication module
/// @}
void test_auth(void);

/// @defgroup test_create_user "test_create_user"
/// @{
/// @brief Verifies that a persisted user can be retrieved with intact credential hash.
/// @}
void test_create_user(void);

/// @defgroup test_authenticate_user "test_authenticate_user"
/// @{
/// @brief Validates authentication outcomes for valid, wrong-password, and unknown-user cases.
/// @}
void test_authenticate_user(void);

/// @defgroup test_create_session "test_create_session"
/// @{
/// @brief Ensures session creation returns bearer token payload fields.
/// @}
void test_create_session(void);

/// @defgroup test_role_permission_association "test_role_permission_association"
/// @{
/// @brief Confirms role-permission many-to-many assignments persist and reload correctly.
/// @}
void test_role_permission_association(void);

/// @defgroup test_user_role_association "test_user_role_association"
/// @{
/// @brief Confirms user-role assignment persists and is queryable from repository reads.
/// @}
void test_user_role_association(void);

/// @defgroup test_ad_group_mapping "test_ad_group_mapping"
/// @{
/// @brief Verifies AD group mapping rows persist and reference the expected role.
/// @}
void test_ad_group_mapping(void);

/// @defgroup test_authenticate_user_updates_last_login "test_authenticate_user_updates_last_login"
/// @{
/// @brief Verifies successful authentication updates last_login audit field.
/// @}
void test_authenticate_user_updates_last_login(void);

/// @defgroup test_authenticate_inactive_user "test_authenticate_inactive_user"
/// @{
/// @brief Verifies inactive accounts are rejected during password authentication.
/// @}
void test_authenticate_inactive_user(void);

/// @defgroup test_verify_password_empty_hash "test_verify_password_empty_hash"
/// @{
/// @brief Verifies password verification safely rejects empty or null password hashes.
/// @}
void test_verify_password_empty_hash(void);

/// @defgroup test_provision_adfs_user_new "test_provision_adfs_user_new"
/// @{
/// @brief Verifies JIT provisioning creates a new ADFS user and maps group-derived roles.
/// @}
void test_provision_adfs_user_new(void);

/// @defgroup test_provision_adfs_user_existing "test_provision_adfs_user_existing"
/// @{
/// @brief Verifies JIT provisioning reuses existing ADFS user and refreshes role assignments.
/// @}
void test_provision_adfs_user_existing(void);

/// @defgroup APIKeyUtilities "APIKeyUtilities"
/// @{
/// @brief API key generation and hashing utilities for service-to-service authentication.
/// @invariant hash_api_key() produces SHA-256 hex digest for lookup and storage.
/// @}
void APIKeyUtilities(void);

/// @defgroup generate_api_key "generate_api_key"
/// @{
/// @brief Generate a new API key in ssk_ format with SHA-256 hash.
/// @post Returns (raw_key, prefix, key_hash) — raw_key shown ONCE to caller, never stored.
/// @}
void generate_api_key(void);

/// @defgroup hash_api_key "hash_api_key"
/// @{
/// @brief Hash an API key string to SHA-256 hex digest for lookup.
/// @post Returns 64-character hex digest.
/// @pre raw_key is a non-empty string.
/// @}
void hash_api_key(void);

/// @defgroup AuthConfigModule "AuthConfigModule"
/// @{
/// @brief Centralized configuration for authentication and authorization.
/// @invariant All sensitive configuration must be loaded from environment; no hardcoded secrets.
/// @}
void AuthConfigModule(void);

/// @defgroup AuthConfig "AuthConfig"
/// @{
/// @brief Holds authentication-related settings.
/// @post Returns a configuration object with validated settings.
/// @pre Environment variables may be provided via .env file.
/// @}
void AuthConfig(void);

/// @defgroup auth_config "auth_config"
/// @{
/// @brief Singleton instance of AuthConfig.
/// @}
void auth_config(void);

/// @defgroup AuthJwtModule "AuthJwtModule"
/// @{
/// @brief JWT token generation and validation logic.
/// @invariant Tokens must include expiration time and user identifier.
/// @post Token encode/decode functions exported
/// @pre JWT secret configured in environment
/// @}
void AuthJwtModule(void);

/// @defgroup create_access_token "create_access_token"
/// @{
/// @brief Generates a new JWT access token.
/// @post Returns a signed JWT string.
/// @pre data dict contains 'sub' (user_id) and optional 'scopes' (roles).
/// @}
void create_access_token(void);

/// @defgroup decode_token "decode_token"
/// @{
/// @brief Decodes and validates a JWT token.
/// @post Returns the decoded payload if valid.
/// @pre token is a signed JWT string.
/// @}
void decode_token(void);

/// @defgroup AuthLoggerModule "AuthLoggerModule"
/// @{
/// @brief Structured auth logging module for audit trail generation.
/// @invariant Must not log sensitive data like passwords or full tokens.
/// @post Audit logging functions exported
/// @pre Auth module initialized
/// @}
void AuthLoggerModule(void);

/// @defgroup log_security_event "log_security_event"
/// @{
/// @brief Logs a security-related event for audit trails.
/// @post Security event is written to the application log.
/// @pre event_type and username are strings.
/// @}
void log_security_event(void);

/// @defgroup AuthOauthModule "AuthOauthModule"
/// @{
/// @brief ADFS OIDC configuration and client using Authlib.
/// @invariant Must use secure OIDC flows.
/// @}
void AuthOauthModule(void);

/// @defgroup oauth "oauth"
/// @{
/// @brief Global Authlib OAuth registry.
/// @}
void oauth(void);

/// @defgroup register_adfs "register_adfs"
/// @{
/// @brief Registers the ADFS OIDC client.
/// @post ADFS client is registered in oauth registry.
/// @pre ADFS configuration is provided in auth_config.
/// @}
void register_adfs(void);

/// @defgroup is_adfs_configured "is_adfs_configured"
/// @{
/// @brief Checks if ADFS is properly configured.
/// @post Returns True if ADFS client is registered, False otherwise.
/// @pre None.
/// @}
void is_adfs_configured(void);

/// @defgroup AuthRepositoryModule "AuthRepositoryModule"
/// @{
/// @brief Data access layer for authentication and user preference entities.
/// @invariant All database read/write operations must execute via the injected SQLAlchemy session boundary.
/// @post Provides valid access to identity data.
/// @pre Database connection is active.
/// @}
void AuthRepositoryModule(void);

/// @defgroup AuthRepository "AuthRepository"
/// @{
/// @brief Provides low-level CRUD operations for identity and authorization records.
/// @post Entity instances returned safely.
/// @pre Database session is bound.
/// @}
void AuthRepository(void);

/// @defgroup get_user_by_id "get_user_by_id"
/// @{
/// @brief Retrieve user by UUID.
/// @post Returns User object if found, else None.
/// @pre user_id is a valid UUID string.
/// @}
void get_user_by_id(void);

/// @defgroup get_user_by_username "get_user_by_username"
/// @{
/// @brief Retrieve user by username.
/// @post Returns User object if found, else None.
/// @pre username is a non-empty string.
/// @}
void get_user_by_username(void);

/// @defgroup get_role_by_id "get_role_by_id"
/// @{
/// @brief Retrieve role by UUID with permissions preloaded.
/// @}
void get_role_by_id(void);

/// @defgroup get_role_by_name "get_role_by_name"
/// @{
/// @brief Retrieve role by unique name.
/// @}
void get_role_by_name(void);

/// @defgroup get_permission_by_id "get_permission_by_id"
/// @{
/// @brief Retrieve permission by UUID.
/// @}
void get_permission_by_id(void);

/// @defgroup get_permission_by_resource_action "get_permission_by_resource_action"
/// @{
/// @brief Retrieve permission by resource and action tuple.
/// @}
void get_permission_by_resource_action(void);

/// @defgroup list_permissions "list_permissions"
/// @{
/// @brief List all system permissions.
/// @}
void list_permissions(void);

/// @defgroup get_user_dashboard_preference "get_user_dashboard_preference"
/// @{
/// @brief Retrieve dashboard filters/preferences for a user.
/// @}
void get_user_dashboard_preference(void);

/// @defgroup get_roles_by_ad_groups "get_roles_by_ad_groups"
/// @{
/// @brief Retrieve roles that match a list of AD group names.
/// @post Returns a list of Role objects mapped to the provided AD groups.
/// @pre groups is a list of strings representing AD group identifiers.
/// @}
void get_roles_by_ad_groups(void);

/// @defgroup AuthSecurityModule "AuthSecurityModule"
/// @{
/// @brief Utility for password hashing and verification using Passlib.
/// @invariant Uses bcrypt for hashing with standard work factor.
/// @}
void AuthSecurityModule(void);

/// @defgroup verify_password "verify_password"
/// @{
/// @brief Verifies a plain password against a hashed password.
/// @post Returns True if password matches, False otherwise.
/// @pre plain_password is a string, hashed_password is a bcrypt hash.
/// @}
void verify_password(void);

/// @defgroup get_password_hash "get_password_hash"
/// @{
/// @brief Generates a bcrypt hash for a plain password.
/// @post Returns a secure bcrypt hash string.
/// @pre password is a string.
/// @}
void get_password_hash(void);

/// @defgroup ConfigManager "ConfigManager"
/// @{
/// @brief Manages application configuration persistence in DB with one-time migration from legacy JSON.
/// @invariant Configuration must always be representable by AppConfig and persisted under global record id.
/// @post Configuration is loaded into memory and logger is configured.
/// @pre Database schema for AppConfigRecord must be initialized.
/// @}
void ConfigManager(void);

/// @defgroup _apply_features_from_env "_apply_features_from_env"
/// @{
/// @brief Read FEATURES__* env vars and apply them to a GlobalSettings features config.
/// @}
void _apply_features_from_env(void);

/// @defgroup _default_config "_default_config"
/// @{
/// @brief Build default application configuration fallback.
/// @}
void _default_config(void);

/// @defgroup _sync_raw_payload_from_config "_sync_raw_payload_from_config"
/// @{
/// @brief Merge typed AppConfig state into raw payload while preserving unsupported legacy sections.
/// @}
void _sync_raw_payload_from_config(void);

/// @defgroup _load_from_legacy_file "_load_from_legacy_file"
/// @{
/// @brief Load legacy JSON configuration for migration fallback path.
/// @}
void _load_from_legacy_file(void);

/// @defgroup _get_record "_get_record"
/// @{
/// @brief Resolve global configuration record from DB.
/// @}
void _get_record(void);

/// @defgroup _load_config "_load_config"
/// @{
/// @brief Load configuration from DB or perform one-time migration from legacy JSON.
/// @}
void _load_config(void);

/// @defgroup _sync_environment_records "_sync_environment_records"
/// @{
/// @brief Mirror configured environments into the relational environments table used by FK-backed domain models.
/// @}
void _sync_environment_records(void);

/// @defgroup _delete_stale_environment_records "_delete_stale_environment_records"
/// @{
/// @brief Remove persisted environment records that are no longer in the configured environments.
/// @post Stale Environment rows are deleted via the session (caller must commit).
/// @pre _sync_environment_records must already have run so the query returns a current view.
/// @}
void _delete_stale_environment_records(void);

/// @defgroup _save_config_to_db "_save_config_to_db"
/// @{
/// @brief Persist provided AppConfig into the global DB configuration record.
/// @}
void _save_config_to_db(void);

/// @defgroup save "save"
/// @{
/// @brief Persist current in-memory configuration state.
/// @}
void save(void);

/// @defgroup get_config "get_config"
/// @{
/// @brief Return current in-memory configuration snapshot.
/// @}
void get_config(void);

/// @defgroup get_payload "get_payload"
/// @{
/// @brief Return full persisted payload including sections outside typed AppConfig schema.
/// @}
void get_payload(void);

/// @defgroup save_config "save_config"
/// @{
/// @brief Persist configuration provided either as typed AppConfig or raw payload dict.
/// @}
void save_config(void);

/// @defgroup update_global_settings "update_global_settings"
/// @{
/// @brief Replace global settings and persist the resulting configuration.
/// @}
void update_global_settings(void);

/// @defgroup validate_path "validate_path"
/// @{
/// @brief Validate that path exists and is writable, creating it when absent.
/// @}
void validate_path(void);

/// @defgroup get_environments "get_environments"
/// @{
/// @brief Return all configured environments.
/// @}
void get_environments(void);

/// @defgroup has_environments "has_environments"
/// @{
/// @brief Check whether at least one environment exists in configuration.
/// @}
void has_environments(void);

/// @defgroup get_environment "get_environment"
/// @{
/// @brief Resolve a configured environment by identifier.
/// @}
void get_environment(void);

/// @defgroup add_environment "add_environment"
/// @{
/// @brief Upsert environment by id into configuration and persist.
/// @}
void add_environment(void);

/// @defgroup update_environment "update_environment"
/// @{
/// @brief Update existing environment by id and preserve masked password placeholder behavior.
/// @}
void update_environment(void);

/// @defgroup delete_environment "delete_environment"
/// @{
/// @brief Delete environment by id and persist when deletion occurs.
/// @}
void delete_environment(void);

/// @defgroup ConfigModels "ConfigModels"
/// @{
/// @brief Defines the data models for application configuration using Pydantic.
/// @}
void ConfigModels(void);

/// @defgroup CoreContracts "CoreContracts"
/// @{
/// @brief Contract for core configuration models — Pydantic BaseModel subclasses with scheduler config.
/// @}
void CoreContracts(void);

/// @defgroup ConnectionContracts "ConnectionContracts"
/// @{
/// @brief Contract for database/environment connection configuration models.
/// @}
void ConnectionContracts(void);

/// @defgroup Schedule "Schedule"
/// @{
/// @brief Represents a backup schedule configuration.
/// @}
void Schedule(void);

/// @defgroup Environment "Environment"
/// @{
/// @brief Represents a Superset environment configuration.
/// @}
void Environment(void);

/// @defgroup LoggingConfig "LoggingConfig"
/// @{
/// @brief Defines the configuration for the application's logging system.
/// @}
void LoggingConfig(void);

/// @defgroup CleanReleaseConfig "CleanReleaseConfig"
/// @{
/// @brief Configuration for clean release compliance subsystem.
/// @}
void CleanReleaseConfig(void);

/// @defgroup FeaturesConfig "FeaturesConfig"
/// @{
/// @brief Top-level feature flags that toggle entire project features on/off.
/// @}
void FeaturesConfig(void);

/// @defgroup GlobalSettings "GlobalSettings"
/// @{
/// @brief Represents global application settings.
/// @}
void GlobalSettings(void);

/// @defgroup AppConfig "AppConfig"
/// @{
/// @brief The root configuration model containing all application settings.
/// @}
void AppConfig(void);

/// @defgroup CotLoggerModule "CotLoggerModule"
/// @{
/// @brief Structured JSON logger implementing the molecular CoT (Chain-of-Thought) logging protocol.
/// @}
void CotLoggerModule(void);

/// @defgroup cot_trace_context "cot_trace_context"
/// @{
/// @brief ContextVars for trace ID and span ID propagation across async boundaries.
/// @}
void cot_trace_context(void);

/// @defgroup cot_logger_instance "cot_logger_instance"
/// @{
/// @brief Dedicated Python logger for all CoT (molecular) log output.
/// @}
void cot_logger_instance(void);

/// @defgroup seed_trace_id "seed_trace_id"
/// @{
/// @brief Generate a new UUID4 trace_id, set it in ContextVar, and return it.
/// @}
void seed_trace_id(void);

/// @defgroup set_trace_id "set_trace_id"
/// @{
/// @brief Set an explicit trace_id into the ContextVar (e.g. from an incoming header).
/// @}
void set_trace_id(void);

/// @defgroup get_trace_id "get_trace_id"
/// @{
/// @brief Get the current trace_id from ContextVar.
/// @}
void get_trace_id(void);

/// @defgroup push_span "push_span"
/// @{
/// @brief Set a new span_id in ContextVar and return the previous span_id for later restoration.
/// @}
void push_span(void);

/// @defgroup pop_span "pop_span"
/// @{
/// @brief Restore a previous span_id into the ContextVar.
/// @}
void pop_span(void);

/// @defgroup cot_log_function "cot_log_function"
/// @{
/// @brief Core structured logging function that emits a single-line JSON record.
/// @}
void cot_log_function(void);

/// @defgroup MarkerLogger "MarkerLogger"
/// @{
/// @brief Thin proxy class providing .reason(), .reflect(), .explore() convenience methods.
/// @}
void MarkerLogger(void);

/// @defgroup MarkerLogger___init__ "MarkerLogger.__init__"
/// @{
/// @brief Store the module/component name used as the 'src' field in all log calls.
/// @}
void MarkerLogger___init__(void);

/// @defgroup MarkerLogger_reason "MarkerLogger.reason"
/// @{
/// @brief Log a REASON marker — strict deduction, core logic.
/// @}
void MarkerLogger_reason(void);

/// @defgroup MarkerLogger_reflect "MarkerLogger.reflect"
/// @{
/// @brief Log a REFLECT marker — self-check, structural validation.
/// @}
void MarkerLogger_reflect(void);

/// @defgroup MarkerLogger_explore "MarkerLogger.explore"
/// @{
/// @brief Log an EXPLORE marker — searching, alternatives, violated assumptions.
/// @}
void MarkerLogger_explore(void);

/// @defgroup DatabaseModule "DatabaseModule"
/// @{
/// @brief Configures database connection and session management (PostgreSQL-first).
/// @invariant A single engine instance is used for the entire application.
/// @}
void DatabaseModule(void);

/// @defgroup BASE_DIR "BASE_DIR"
/// @{
/// @brief Base directory for the backend.
/// @}
void BASE_DIR(void);

/// @defgroup DATABASE_URL "DATABASE_URL"
/// @{
/// @brief URL for the main application database. Read from env; dev fallback only.
/// @}
void DATABASE_URL(void);

/// @defgroup TASKS_DATABASE_URL "TASKS_DATABASE_URL"
/// @{
/// @brief URL for the tasks execution database.
/// @}
void TASKS_DATABASE_URL(void);

/// @defgroup AUTH_DATABASE_URL "AUTH_DATABASE_URL"
/// @{
/// @brief URL for the authentication database.
/// @}
void AUTH_DATABASE_URL(void);

/// @defgroup engine "engine"
/// @{
/// @brief SQLAlchemy engine for mappings database.
/// @}
void engine(void);

/// @defgroup tasks_engine "tasks_engine"
/// @{
/// @brief SQLAlchemy engine for tasks database.
/// @}
void tasks_engine(void);

/// @defgroup auth_engine "auth_engine"
/// @{
/// @brief SQLAlchemy engine for authentication database.
/// @}
void auth_engine(void);

/// @defgroup SessionLocal "SessionLocal"
/// @{
/// @brief A session factory for the main mappings database.
/// @pre engine is initialized.
/// @}
void SessionLocal(void);

/// @defgroup TasksSessionLocal "TasksSessionLocal"
/// @{
/// @brief A session factory for the tasks execution database.
/// @pre tasks_engine is initialized.
/// @}
void TasksSessionLocal(void);

/// @defgroup AuthSessionLocal "AuthSessionLocal"
/// @{
/// @brief A session factory for the authentication database.
/// @pre auth_engine is initialized.
/// @}
void AuthSessionLocal(void);

/// @defgroup _ensure_user_dashboard_preferences_columns "_ensure_user_dashboard_preferences_columns"
/// @{
/// @brief Applies additive schema upgrades for user_dashboard_preferences table.
/// @post Missing columns are added without data loss.
/// @pre bind_engine points to application database where profile table is stored.
/// @}
void _ensure_user_dashboard_preferences_columns(void);

/// @defgroup _ensure_user_dashboard_preferences_health_columns "_ensure_user_dashboard_preferences_health_columns"
/// @{
/// @brief Applies additive schema upgrades for user_dashboard_preferences table (health fields).
/// @}
void _ensure_user_dashboard_preferences_health_columns(void);

/// @defgroup _ensure_llm_validation_results_columns "_ensure_llm_validation_results_columns"
/// @{
/// @brief Applies additive schema upgrades for llm_validation_results table.
/// @}
void _ensure_llm_validation_results_columns(void);

/// @defgroup _ensure_git_server_configs_columns "_ensure_git_server_configs_columns"
/// @{
/// @brief Applies additive schema upgrades for git_server_configs table.
/// @post Missing columns are added without data loss.
/// @pre bind_engine points to application database.
/// @}
void _ensure_git_server_configs_columns(void);

/// @defgroup _ensure_auth_users_columns "_ensure_auth_users_columns"
/// @{
/// @brief Applies additive schema upgrades for auth users table.
/// @post Missing columns are added without data loss.
/// @pre bind_engine points to authentication database.
/// @}
void _ensure_auth_users_columns(void);

/// @defgroup _ensure_filter_source_enum_values "_ensure_filter_source_enum_values"
/// @{
/// @brief Adds missing FilterSource enum values to the PostgreSQL native filtersource type.
/// @post New enum values are available without data loss.
/// @pre bind_engine points to application database with imported_filters table.
/// @}
void _ensure_filter_source_enum_values(void);

/// @defgroup _ensure_dataset_review_session_columns "_ensure_dataset_review_session_columns"
/// @{
/// @brief Apply additive schema upgrades for dataset review persistence required by optimistic-lock and recovery metadata semantics.
/// @post Missing additive columns across legacy dataset review tables are created without removing existing data.
/// @pre bind_engine points to the application database where dataset review tables are stored.
/// @}
void _ensure_dataset_review_session_columns(void);

/// @defgroup _ensure_translation_schedules_columns "_ensure_translation_schedules_columns"
/// @{
/// @brief Applies additive schema upgrades for translation_schedules table.
/// @post Missing columns are added without data loss.
/// @pre bind_engine points to application database.
/// @}
void _ensure_translation_schedules_columns(void);

/// @defgroup _ensure_dictionary_entries_columns "_ensure_dictionary_entries_columns"
/// @{
/// @brief Additive migration for dictionary_entries origin tracking columns.
/// @}
void _ensure_dictionary_entries_columns(void);

/// @defgroup init_db "init_db"
/// @{
/// @brief Initializes the database by creating all tables.
/// @post Database tables created in all databases.
/// @pre engine, tasks_engine and auth_engine are initialized.
/// @}
void init_db(void);

/// @defgroup get_db "get_db"
/// @{
/// @brief Dependency for getting a database session.
/// @post Session is closed after use.
/// @pre SessionLocal is initialized.
/// @}
void get_db(void);

/// @defgroup get_tasks_db "get_tasks_db"
/// @{
/// @brief Dependency for getting a tasks database session.
/// @post Session is closed after use.
/// @pre TasksSessionLocal is initialized.
/// @}
void get_tasks_db(void);

/// @defgroup get_auth_db "get_auth_db"
/// @{
/// @brief Dependency for getting an authentication database session.
/// @post Session is closed after use.
/// @pre AuthSessionLocal is initialized.
/// @}
void get_auth_db(void);

/// @defgroup EncryptionKeyModule "EncryptionKeyModule"
/// @{
/// @brief Resolve and persist the Fernet encryption key required by runtime services.
/// @invariant Runtime key resolution never falls back to an ephemeral secret.
/// @post A valid Fernet key is available to runtime services via ENCRYPTION_KEY.
/// @pre Runtime environment can read process variables and target .env path is writable when key generation is required.
/// @}
void EncryptionKeyModule(void);

/// @defgroup ensure_encryption_key "ensure_encryption_key"
/// @{
/// @brief Ensure backend runtime has a persistent valid Fernet key.
/// @post Returns a valid Fernet key and guarantees it is present in process environment.
/// @pre env_file_path points to a writable backend .env file or ENCRYPTION_KEY exists in process environment.
/// @}
void ensure_encryption_key(void);

/// @defgroup LoggerModule "LoggerModule"
/// @{
/// @brief Application logging system with CotJsonFormatter producing molecular CoT JSON output.
/// @invariant CotJsonFormatter.format() always returns valid single-line JSON string.
/// @post All log output is single-line JSON with ts, level, trace_id, src, marker, intent, payload, error, span_id.
/// @pre Python 3.7+ with cot_logger ContextVars available.
/// @}
void LoggerModule(void);

/// @defgroup CotJsonFormatter "CotJsonFormatter"
/// @{
/// @brief JSON formatter implementing the molecular CoT logging protocol. Outputs single-line JSON with ts, level, trace_id, src, marker, intent, payload, error, span_id.
/// @}
void CotJsonFormatter(void);

/// @defgroup CotJsonFormatter_format "CotJsonFormatter.format"
/// @{
/// @brief Format a LogRecord into a single-line CoT JSON string with molecular CoT protocol fields.
/// @invariant Output is always valid single-line JSON.
/// @}
void CotJsonFormatter_format(void);

/// @defgroup BeliefFormatter "BeliefFormatter"
/// @{
/// @brief Legacy formatter that adds belief state prefixes to log messages. Deprecated in favor of CotJsonFormatter.
/// @}
void BeliefFormatter(void);

/// @defgroup LogEntry "LogEntry"
/// @{
/// @brief A Pydantic model representing a single, structured log entry.
/// @}
void LogEntry(void);

/// @defgroup belief_scope "belief_scope"
/// @{
/// @brief Context manager for Molecular CoT structured logging. Uses cot_logger.log() for JSON output.
/// @post Thread-local belief state is updated; REASON/REFLECT/EXPLORE markers emitted via structured JSON logger.
/// @pre anchor_id must be provided.
/// @}
void belief_scope(void);

/// @defgroup configure_logger "configure_logger"
/// @{
/// @brief Configures the main logger and the CoT logger with CotJsonFormatter, file handlers, and global flags.
/// @post Logger levels, handlers, formatters, belief state flag, and task log level are updated.
/// @pre config is a valid LoggingConfig instance.
/// @}
void configure_logger(void);

/// @defgroup get_task_log_level "get_task_log_level"
/// @{
/// @brief Returns the current task log level filter.
/// @}
void get_task_log_level(void);

/// @defgroup should_log_task_level "should_log_task_level"
/// @{
/// @brief Checks if a log level should be recorded based on task_log_level setting.
/// @}
void should_log_task_level(void);

/// @defgroup Logger "Logger"
/// @{
/// @brief The global application logger instance configured with CotJsonFormatter, console handler, and WebSocketLogHandler.
/// @}
void Logger(void);

/// @defgroup believed "believed"
/// @{
/// @brief A decorator that wraps a function in a belief scope.
/// @}
void believed(void);

/// @defgroup explore "explore"
/// @{
/// @brief Logs an EXPLORE marker (WARNING level) with structured extra data for CotJsonFormatter.
/// @}
void explore(void);

/// @defgroup reason "reason"
/// @{
/// @brief Logs a REASON marker (DEBUG level) with structured extra data for CotJsonFormatter.
/// @}
void reason(void);

/// @defgroup reflect "reflect"
/// @{
/// @brief Logs a REFLECT marker (DEBUG level) with structured extra data for CotJsonFormatter.
/// @}
void reflect(void);

/// @defgroup test_logger "test_logger"
/// @{
/// @brief Unit tests for logger module
/// @}
void test_logger(void);

/// @defgroup test_belief_scope_logs_reason_reflect_at_debug "test_belief_scope_logs_reason_reflect_at_debug"
/// @{
/// @brief Test that belief_scope generates [REASON] and [REFLECT] logs at DEBUG level.
/// @post Logs are verified to contain REASON and REFLECT markers at DEBUG level.
/// @pre belief_scope is available. caplog fixture is used. Logger configured to DEBUG.
/// @}
void test_belief_scope_logs_reason_reflect_at_debug(void);

/// @defgroup test_belief_scope_error_handling "test_belief_scope_error_handling"
/// @{
/// @brief Test that belief_scope logs EXPLORE on exception.
/// @post Logs are verified to contain EXPLORE marker.
/// @pre belief_scope is available. caplog fixture is used. Logger configured to DEBUG.
/// @}
void test_belief_scope_error_handling(void);

/// @defgroup test_belief_scope_success_reflect "test_belief_scope_success_reflect"
/// @{
/// @brief Test that belief_scope logs REFLECT on success.
/// @post Logs are verified to contain REFLECT marker.
/// @pre belief_scope is available. caplog fixture is used. Logger configured to DEBUG.
/// @}
void test_belief_scope_success_reflect(void);

/// @defgroup test_belief_scope_not_visible_at_info "test_belief_scope_not_visible_at_info"
/// @{
/// @brief Test that belief_scope REFLECT logs are NOT visible at INFO level.
/// @post REASON is visible at INFO (uses info()); REFLECT is not (uses debug()).
/// @pre belief_scope is available. caplog fixture is used.
/// @}
void test_belief_scope_not_visible_at_info(void);

/// @defgroup test_task_log_level_default "test_task_log_level_default"
/// @{
/// @brief Test that default task log level is INFO.
/// @post Default level is INFO.
/// @pre None.
/// @}
void test_task_log_level_default(void);

/// @defgroup test_should_log_task_level "test_should_log_task_level"
/// @{
/// @brief Test that should_log_task_level correctly filters log levels.
/// @post Filtering works correctly for all level combinations.
/// @pre None.
/// @}
void test_should_log_task_level(void);

/// @defgroup test_configure_logger_task_log_level "test_configure_logger_task_log_level"
/// @{
/// @brief Test that configure_logger updates task_log_level.
/// @post task_log_level is updated correctly.
/// @pre LoggingConfig is available.
/// @}
void test_configure_logger_task_log_level(void);

/// @defgroup test_enable_belief_state_flag "test_enable_belief_state_flag"
/// @{
/// @brief Test that enable_belief_state flag controls belief_scope logging.
/// @post belief_scope explicit REASON logs are controlled by the flag; REFLECT always logged.
/// @pre LoggingConfig is available. caplog fixture is used.
/// @}
void test_enable_belief_state_flag(void);

/// @defgroup test_belief_scope_missing_anchor "test_belief_scope_missing_anchor"
/// @{
/// @brief Test @PRE condition: anchor_id must be provided
/// @}
void test_belief_scope_missing_anchor(void);

/// @defgroup test_configure_logger_post_conditions "test_configure_logger_post_conditions"
/// @{
/// @brief Test @POST condition: Logger level, handlers, belief state flag, and task log level are updated.
/// @}
void test_configure_logger_post_conditions(void);

/// @defgroup IdMappingServiceModule "IdMappingServiceModule"
/// @{
/// @brief Service for tracking and synchronizing Superset Resource IDs (UUID <-> Integer ID)
/// @invariant sync_environment must handle remote API failures gracefully.
/// @post Mapping synchronization and lookup APIs are available for environment-scoped UUID-to-integer resolution.
/// @pre Database session is valid and Superset client factory returns authenticated clients for requested environments.
/// @}
void IdMappingServiceModule(void);

/// @defgroup IdMappingService "IdMappingService"
/// @{
/// @brief Service handling the cataloging and retrieval of remote Superset Integer IDs.
/// @invariant self.db remains the authoritative session for all mapping operations.
/// @post Service instance provides scheduler control and environment-scoped mapping synchronization APIs.
/// @pre db_session is an active SQLAlchemy Session bound to mapping tables.
/// @}
void IdMappingService(void);

/// @defgroup start_scheduler "start_scheduler"
/// @{
/// @brief Starts the background scheduler with a given cron string.
/// @param superset_client_factory - Function to get a client for an environment.
/// @}
void start_scheduler(void);

/// @defgroup sync_environment "sync_environment"
/// @{
/// @brief Fully synchronizes mapping for a specific environment.
/// @param superset_client - Instance capable of hitting the Superset API.
/// @post ResourceMapping records for the environment are created or updated.
/// @pre environment_id exists in the database.
/// @}
void sync_environment(void);

/// @defgroup get_remote_id "get_remote_id"
/// @{
/// @brief Retrieves the remote integer ID for a given universal UUID.
/// @param uuid (str)
/// @return Optional[int]
/// @}
void get_remote_id(void);

/// @defgroup get_remote_ids_batch "get_remote_ids_batch"
/// @{
/// @brief Retrieves remote integer IDs for a list of universal UUIDs efficiently.
/// @param uuids (List[str])
/// @return Dict[str, int] - Mapping of UUID -> Integer ID
/// @}
void get_remote_ids_batch(void);

/// @defgroup middleware_package "middleware_package"
/// @{
/// @brief FastAPI/Starlette middleware package for request-level context and tracing.
/// @}
void middleware_package(void);

/// @defgroup TraceContextMiddlewareModule "TraceContextMiddlewareModule"
/// @{
/// @brief FastAPI/Starlette middleware that seeds a trace_id for every incoming HTTP request.
/// @}
void TraceContextMiddlewareModule(void);

/// @defgroup TraceContextMiddleware "TraceContextMiddleware"
/// @{
/// @brief Starlette BaseHTTPMiddleware that seeds a trace_id per request.
/// @}
void TraceContextMiddleware(void);

/// @defgroup TraceContextMiddleware___init__ "TraceContextMiddleware.__init__"
/// @{
/// @brief Standard BaseHTTPMiddleware initialiser.
/// @}
void TraceContextMiddleware___init__(void);

/// @defgroup TraceContextMiddleware_dispatch "TraceContextMiddleware.dispatch"
/// @{
/// @brief Dispatch handler that seeds trace_id before passing to the next middleware.
/// @}
void TraceContextMiddleware_dispatch(void);

/// @defgroup MigrationPackage "MigrationPackage"
/// @{
/// @}
void MigrationPackage(void);

/// @defgroup MigrationArchiveParserModule "MigrationArchiveParserModule"
/// @{
/// @brief Parse Superset export ZIP archives into normalized object catalogs for diffing.
/// @invariant Parsing is read-only and never mutates archive files.
/// @post Parsed migration archive returned
/// @pre Archive file path is valid and readable
/// @}
void MigrationArchiveParserModule(void);

/// @defgroup MigrationArchiveParser "MigrationArchiveParser"
/// @{
/// @brief Extract normalized dashboards/charts/datasets metadata from ZIP archives.
/// @}
void MigrationArchiveParser(void);

/// @defgroup extract_objects_from_zip "extract_objects_from_zip"
/// @{
/// @brief Extract object catalogs from Superset archive.
/// @post Returns object lists grouped by resource type.
/// @pre zip_path points to a valid readable ZIP.
/// @return Dict[str, List[Dict[str, Any]]]
/// @}
void extract_objects_from_zip(void);

/// @defgroup _collect_yaml_objects "_collect_yaml_objects"
/// @{
/// @brief Read and normalize YAML manifests for one object type.
/// @post Returns only valid normalized objects.
/// @pre object_type is one of dashboards/charts/datasets.
/// @}
void _collect_yaml_objects(void);

/// @defgroup _normalize_object_payload "_normalize_object_payload"
/// @{
/// @brief Convert raw YAML payload to stable diff signature shape.
/// @post Returns normalized descriptor with `uuid`, `title`, and `signature`.
/// @pre payload is parsed YAML mapping.
/// @}
void _normalize_object_payload(void);

/// @defgroup MigrationDryRunOrchestratorModule "MigrationDryRunOrchestratorModule"
/// @{
/// @brief Compute pre-flight migration diff and risk scoring without apply.
/// @invariant Dry run is informative only and must not mutate target environment.
/// @post Dry-run diff returned without mutation
/// @pre Source and target environments configured
/// @}
void MigrationDryRunOrchestratorModule(void);

/// @defgroup MigrationDryRunService "MigrationDryRunService"
/// @{
/// @brief Build deterministic diff/risk payload for migration pre-flight.
/// @}
void MigrationDryRunService(void);

/// @defgroup run "run"
/// @{
/// @brief Execute full dry-run computation for selected dashboards.
/// @post Returns JSON-serializable pre-flight payload with summary, diff and risk.
/// @pre source/target clients are authenticated and selection validated by caller.
/// @}
void run(void);

/// @defgroup _load_db_mapping "_load_db_mapping"
/// @{
/// @brief Resolve UUID mapping for optional DB config replacement.
/// @}
void _load_db_mapping(void);

/// @defgroup _accumulate_objects "_accumulate_objects"
/// @{
/// @brief Merge extracted resources by UUID to avoid duplicates.
/// @}
void _accumulate_objects(void);

/// @defgroup _index_by_uuid "_index_by_uuid"
/// @{
/// @brief Build UUID-index map for normalized resources.
/// @}
void _index_by_uuid(void);

/// @defgroup _build_object_diff "_build_object_diff"
/// @{
/// @brief Compute create/update/delete buckets by UUID+signature.
/// @}
void _build_object_diff(void);

/// @defgroup _build_target_signatures "_build_target_signatures"
/// @{
/// @brief Pull target metadata and normalize it into comparable signatures.
/// @}
void _build_target_signatures(void);

/// @defgroup _build_risks "_build_risks"
/// @{
/// @brief Build risk items for missing datasource, broken refs, overwrite, owner mismatch.
/// @}
void _build_risks(void);

/// @defgroup RiskAssessorModule "RiskAssessorModule"
/// @{
/// @brief Compute deterministic migration risk items and aggregate score for dry-run reporting.
/// @invariant Risk scoring must remain bounded to [0,100] and preserve severity-to-weight mapping.
/// @post Risk scoring output preserves item list and provides bounded score with derived level.
/// @pre Risk assessor functions receive normalized migration object collections from dry-run orchestration.
/// @}
void RiskAssessorModule(void);

/// @defgroup index_by_uuid "index_by_uuid"
/// @{
/// @brief Build UUID-index from normalized objects.
/// @post Returns mapping keyed by string uuid; only truthy uuid values are included.
/// @pre Input list items are dict-like payloads potentially containing "uuid".
/// @}
void index_by_uuid(void);

/// @defgroup extract_owner_identifiers "extract_owner_identifiers"
/// @{
/// @brief Normalize owner payloads for stable comparison.
/// @post Returns sorted unique owner identifiers as strings.
/// @pre Owners may be list payload, scalar values, or None.
/// @}
void extract_owner_identifiers(void);

/// @defgroup build_risks "build_risks"
/// @{
/// @brief Build risk list from computed diffs and target catalog state.
/// @post Returns list of deterministic risk items derived from overwrite, missing datasource, reference, and owner mismatch checks.
/// @pre target_client is authenticated/usable for database list retrieval.
/// @}
void build_risks(void);

/// @defgroup score_risks "score_risks"
/// @{
/// @brief Aggregate risk list into score and level.
/// @post Returns dict with score in [0,100], derived level, and original items.
/// @pre risk_items contains optional severity fields expected in {high,medium,low} or defaults to low weight.
/// @}
void score_risks(void);

/// @defgroup MigrationEngineModule "MigrationEngineModule"
/// @{
/// @brief Transforms Superset export ZIP archives while preserving archive integrity and patching mapped identifiers.
/// @invariant ZIP structure and non-targeted metadata must remain valid after transformation.
/// @post Migration engine contracts preserve ZIP integrity while exposing transformation entrypoints for import pipelines.
/// @pre Input archives are readable Superset exports and optional mapping collaborators expose remote id lookup APIs.
/// @}
void MigrationEngineModule(void);

/// @defgroup MigrationEngine "MigrationEngine"
/// @{
/// @brief Engine for transforming Superset export ZIPs.
/// @}
void MigrationEngine(void);

/// @defgroup transform_zip "transform_zip"
/// @{
/// @brief Extracts ZIP, replaces database UUIDs in YAMLs, patches cross-filters, and re-packages.
/// @param fix_cross_filters (bool) - Whether to patch dashboard json_metadata.
/// @post Returns True only when extraction, transformation, and packaging complete without exception.
/// @pre zip_path points to a readable ZIP; output_path parent is writable; db_mapping keys/values are UUID strings.
/// @return bool - True if successful.
/// @}
void transform_zip(void);

/// @defgroup _transform_yaml "_transform_yaml"
/// @{
/// @brief Replaces database_uuid in a single YAML file.
/// @param db_mapping (Dict[str, str]) - UUID mapping dictionary.
/// @post database_uuid is replaced in-place only when source UUID is present in db_mapping.
/// @pre file_path exists, is readable YAML, and db_mapping contains source->target UUID pairs.
/// @}
void _transform_yaml(void);

/// @defgroup _extract_chart_uuids_from_archive "_extract_chart_uuids_from_archive"
/// @{
/// @brief Scans extracted chart YAML files and builds a source chart ID to UUID lookup map.
/// @param temp_dir (Path) - Root dir of unpacked archive.
/// @post Returns a best-effort Dict[int, str] containing only parseable chart id/uuid pairs.
/// @pre temp_dir exists and points to extracted archive root with optional chart YAML resources.
/// @return Dict[int, str] - Mapping of source Integer ID to UUID.
/// @}
void _extract_chart_uuids_from_archive(void);

/// @defgroup _patch_dashboard_metadata "_patch_dashboard_metadata"
/// @{
/// @brief Rewrites dashboard json_metadata chart/dataset integer identifiers using target environment mappings.
/// @param source_map (Dict[int, str])
/// @post json_metadata is re-serialized with mapped integer IDs when remote mappings are available; otherwise file remains unchanged.
/// @pre file_path points to dashboard YAML with json_metadata; target_env_id is non-empty; source_map contains source id->uuid.
/// @}
void _patch_dashboard_metadata(void);

/// @defgroup PluginBase "PluginBase"
/// @{
/// @brief PluginLoader scans for subclasses of PluginBase.
/// @invariant All plugins MUST inherit from this class.
/// @}
void PluginBase(void);

/// @defgroup id "id"
/// @{
/// @brief Returns the unique identifier for the plugin.
/// @post Returns string ID.
/// @pre Plugin instance exists.
/// @return str - Plugin ID.
/// @}
void id(void);

/// @defgroup name "name"
/// @{
/// @brief Returns the human-readable name of the plugin.
/// @post Returns string name.
/// @pre Plugin instance exists.
/// @return str - Plugin name.
/// @}
void name(void);

/// @defgroup description "description"
/// @{
/// @brief Returns a brief description of the plugin.
/// @post Returns string description.
/// @pre Plugin instance exists.
/// @return str - Plugin description.
/// @}
void description(void);

/// @defgroup version "version"
/// @{
/// @brief Returns the version of the plugin.
/// @post Returns string version.
/// @pre Plugin instance exists.
/// @return str - Plugin version.
/// @}
void version(void);

/// @defgroup required_permission "required_permission"
/// @{
/// @brief Returns the required permission string to execute this plugin.
/// @post Returns string permission.
/// @pre Plugin instance exists.
/// @return str - Required permission (e.g., "plugin:backup:execute").
/// @}
void required_permission(void);

/// @defgroup ui_route "ui_route"
/// @{
/// @brief Returns the frontend route for the plugin's UI, if applicable.
/// @post Returns string route or None.
/// @pre Plugin instance exists.
/// @return Optional[str] - Frontend route.
/// @}
void ui_route(void);

/// @defgroup get_schema "get_schema"
/// @{
/// @brief Returns the JSON schema for the plugin's input parameters.
/// @post Returns dict schema.
/// @pre Plugin instance exists.
/// @return Dict[str, Any] - JSON schema.
/// @}
void get_schema(void);

/// @defgroup execute "execute"
/// @{
/// @brief Executes the plugin's core logic.
/// @param params (Dict[str, Any]) - Validated input parameters.
/// @post Plugin execution is completed.
/// @pre params must be a dictionary.
/// @}
void execute(void);

/// @defgroup PluginConfig "PluginConfig"
/// @{
/// @brief Validated PluginConfig exposed to API layer.
/// @}
void PluginConfig(void);

/// @defgroup PluginLoader "PluginLoader"
/// @{
/// @brief Discovers and manages available PluginBase implementations.
/// @}
void PluginLoader(void);

/// @defgroup _load_plugins "_load_plugins"
/// @{
/// @brief Scans the plugin directory and loads all valid plugins.
/// @post _load_module is called for each .py file.
/// @pre plugin_dir exists or can be created.
/// @}
void _load_plugins(void);

/// @defgroup _load_module "_load_module"
/// @{
/// @brief Loads a single Python module and discovers PluginBase implementations.
/// @param file_path (str) - The path to the module file.
/// @post Plugin classes are instantiated and registered.
/// @pre module_name and file_path are valid.
/// @}
void _load_module(void);

/// @defgroup _register_plugin "_register_plugin"
/// @{
/// @brief Registers a PluginBase instance and its configuration.
/// @param plugin_instance (PluginBase) - The plugin instance to register.
/// @post Plugin is added to _plugins and _plugin_configs.
/// @pre plugin_instance is a valid implementation of PluginBase.
/// @}
void _register_plugin(void);

/// @defgroup get_plugin "get_plugin"
/// @{
/// @brief Retrieves a loaded plugin instance by its ID.
/// @param plugin_id (str) - The unique identifier of the plugin.
/// @post Returns plugin instance or None.
/// @pre plugin_id is a string.
/// @return Optional[PluginBase] - The plugin instance if found, otherwise None.
/// @}
void get_plugin(void);

/// @defgroup get_all_plugin_configs "get_all_plugin_configs"
/// @{
/// @brief Returns a list of all registered plugin configurations.
/// @post Returns list of all PluginConfig objects.
/// @pre None.
/// @return List[PluginConfig] - A list of plugin configurations.
/// @}
void get_all_plugin_configs(void);

/// @defgroup has_plugin "has_plugin"
/// @{
/// @brief Checks if a plugin with the given ID is registered.
/// @param plugin_id (str) - The unique identifier of the plugin.
/// @post Returns True if plugin exists.
/// @pre plugin_id is a string.
/// @return bool - True if the plugin is registered, False otherwise.
/// @}
void has_plugin(void);

/// @defgroup SchedulerModule "SchedulerModule"
/// @{
/// @brief Manages scheduled tasks using APScheduler.
/// @}
void SchedulerModule(void);

/// @defgroup SchedulerService "SchedulerService"
/// @{
/// @brief Provides a service to manage scheduled backup tasks.
/// @}
void SchedulerService(void);

/// @defgroup start "start"
/// @{
/// @brief Starts the background scheduler and loads initial schedules.
/// @post Scheduler is running and schedules are loaded.
/// @pre Scheduler should be initialized.
/// @}
void start(void);

/// @defgroup stop "stop"
/// @{
/// @brief Stops the background scheduler.
/// @post Scheduler is shut down.
/// @pre Scheduler should be running.
/// @}
void stop(void);

/// @defgroup load_schedules "load_schedules"
/// @{
/// @brief Load backup and active translation schedules from config and DB, re-registering all jobs.
/// @post All enabled backup jobs and active translation schedules are re-registered in APScheduler.
/// @pre config_manager must have valid configuration; database is accessible.
/// @}
void load_schedules(void);

/// @defgroup add_backup_job "add_backup_job"
/// @{
/// @brief Adds a scheduled backup job for an environment.
/// @param cron_expression (str) - The cron expression for the schedule.
/// @post A new job is added to the scheduler or replaced if it already exists.
/// @pre env_id and cron_expression must be valid strings.
/// @}
void add_backup_job(void);

/// @defgroup add_translation_job "add_translation_job"
/// @{
/// @brief Register a translation schedule with APScheduler.
/// @post A new APScheduler job is registered or replaced if it already exists.
/// @pre schedule_id, job_id, and cron_expression are valid strings.
/// @}
void add_translation_job(void);

/// @defgroup remove_translation_job "remove_translation_job"
/// @{
/// @brief Remove a translation schedule from APScheduler.
/// @post The APScheduler job is removed if it exists; silently ignored otherwise.
/// @pre schedule_id is a valid string.
/// @}
void remove_translation_job(void);

/// @defgroup _trigger_backup "_trigger_backup"
/// @{
/// @brief Triggered by the scheduler to start a backup task.
/// @param env_id (str) - The ID of the environment.
/// @post A new backup task is created in the task manager if not already running.
/// @pre env_id must be a valid environment ID.
/// @}
void _trigger_backup(void);

/// @defgroup add_validation_job "add_validation_job"
/// @{
/// @brief Register a validation policy schedule with APScheduler.
/// @post A new APScheduler job is registered or replaced if it already exists.
/// @pre policy_id and cron_expression are valid strings.
/// @}
void add_validation_job(void);

/// @defgroup remove_validation_job "remove_validation_job"
/// @{
/// @brief Remove a validation policy schedule from APScheduler.
/// @post The APScheduler job is removed if it exists; silently ignored otherwise.
/// @pre policy_id is a valid string.
/// @}
void remove_validation_job(void);

/// @defgroup reload_validation_policy "reload_validation_policy"
/// @{
/// @brief Reload a single validation policy schedule — calls remove then add.
/// @post Old job is removed; new job is registered if policy is active and has schedule_days.
/// @pre policy_id is a valid ValidationPolicy id with schedule data in DB.
/// @}
void reload_validation_policy(void);

/// @defgroup _trigger_validation "_trigger_validation"
/// @{
/// @brief APScheduler job handler — triggers validation runs for a policy.
/// @post A validation task is spawned via TaskManager for each dashboard in the policy.
/// @pre policy_id is a valid ValidationPolicy id with dashboard_ids.
/// @}
void _trigger_validation(void);

/// @defgroup ThrottledSchedulerConfigurator "ThrottledSchedulerConfigurator"
/// @{
/// @brief Distributes validation tasks evenly within an execution window.
/// @invariant Returned schedule size always matches number of dashboard IDs.
/// @post Produces deterministic per-dashboard run timestamps within the configured window.
/// @pre Validation policies provide a finite dashboard list and a valid execution window.
/// @}
void ThrottledSchedulerConfigurator(void);

/// @defgroup calculate_schedule "calculate_schedule"
/// @{
/// @brief Calculates execution times for N tasks within a window.
/// @invariant Tasks are distributed with near-even spacing.
/// @post Returns List[EXT:Python:datetime] of scheduled times.
/// @pre window_start, window_end (time), dashboard_ids (List), current_date (date).
/// @}
void calculate_schedule(void);

/// @defgroup SupersetClientModule "SupersetClientModule"
/// @{
/// @brief Предоставляет высокоуровневый клиент для взаимодействия с Superset REST API, инкапсулируя логику запросов, обработку ошибок и пагинацию.
/// @invariant All network operations must use the internal APIClient instance.
/// @}
void SupersetClientModule(void);

/// @defgroup SupersetClient "SupersetClient"
/// @{
/// @brief Класс-обёртка над Superset REST API, предоставляющий методы для работы с дашбордами и датасетами.
/// @}
void SupersetClient(void);

/// @defgroup SupersetClientBase "SupersetClientBase"
/// @{
/// @brief Base class for SupersetClient providing initialization, authentication, pagination, and import/export helpers.
/// @}
void SupersetClientBase(void);

/// @defgroup SupersetClientInit "SupersetClientInit"
/// @{
/// @brief Инициализирует клиент, проверяет конфигурацию и создает сетевой клиент.
/// @}
void SupersetClientInit(void);

/// @defgroup SupersetClientAuthenticate "SupersetClientAuthenticate"
/// @{
/// @brief Authenticates the client using the configured credentials.
/// @}
void SupersetClientAuthenticate(void);

/// @defgroup SupersetClientHeaders "SupersetClientHeaders"
/// @{
/// @brief Возвращает базовые HTTP-заголовки, используемые сетевым клиентом.
/// @}
void SupersetClientHeaders(void);

/// @defgroup SupersetClientValidateQueryParams "SupersetClientValidateQueryParams"
/// @{
/// @brief Ensures query parameters have default page and page_size.
/// @}
void SupersetClientValidateQueryParams(void);

/// @defgroup SupersetClientFetchTotalObjectCount "SupersetClientFetchTotalObjectCount"
/// @{
/// @brief Fetches the total number of items for a given endpoint.
/// @}
void SupersetClientFetchTotalObjectCount(void);

/// @defgroup SupersetClientFetchAllPages "SupersetClientFetchAllPages"
/// @{
/// @brief Iterates through all pages to collect all data items.
/// @}
void SupersetClientFetchAllPages(void);

/// @defgroup SupersetClientDoImport "SupersetClientDoImport"
/// @{
/// @brief Performs the actual multipart upload for import.
/// @}
void SupersetClientDoImport(void);

/// @defgroup SupersetClientValidateExportResponse "SupersetClientValidateExportResponse"
/// @{
/// @brief Validates that the export response is a non-empty ZIP archive.
/// @}
void SupersetClientValidateExportResponse(void);

/// @defgroup SupersetClientResolveExportFilename "SupersetClientResolveExportFilename"
/// @{
/// @brief Determines the filename for an exported dashboard.
/// @}
void SupersetClientResolveExportFilename(void);

/// @defgroup SupersetClientValidateImportFile "SupersetClientValidateImportFile"
/// @{
/// @brief Validates that the file to be imported is a valid ZIP with metadata.yaml.
/// @}
void SupersetClientValidateImportFile(void);

/// @defgroup SupersetClientResolveTargetIdForDelete "SupersetClientResolveTargetIdForDelete"
/// @{
/// @brief Resolves a dashboard ID from either an ID or a slug.
/// @}
void SupersetClientResolveTargetIdForDelete(void);

/// @defgroup SupersetClientGetAllResources "SupersetClientGetAllResources"
/// @{
/// @brief Fetches all resources of a given type with id, uuid, and name columns.
/// @}
void SupersetClientGetAllResources(void);

/// @defgroup SupersetChartsMixin "SupersetChartsMixin"
/// @{
/// @brief Chart domain mixin for SupersetClient — list, get, extract IDs from layout.
/// @}
void SupersetChartsMixin(void);

/// @defgroup SupersetClientGetChart "SupersetClientGetChart"
/// @{
/// @brief Fetches a single chart by ID.
/// @}
void SupersetClientGetChart(void);

/// @defgroup SupersetClientGetCharts "SupersetClientGetCharts"
/// @{
/// @brief Fetches all charts with pagination support.
/// @}
void SupersetClientGetCharts(void);

/// @defgroup SupersetClientExtractChartIdsFromLayout "SupersetClientExtractChartIdsFromLayout"
/// @{
/// @brief Traverses dashboard layout metadata and extracts chart IDs from common keys.
/// @}
void SupersetClientExtractChartIdsFromLayout(void);

/// @defgroup SupersetDashboardsCrudMixin "SupersetDashboardsCrudMixin"
/// @{
/// @brief Dashboard CRUD mixin for SupersetClient — detail, export, import, delete.
/// @}
void SupersetDashboardsCrudMixin(void);

/// @defgroup SupersetClientGetDashboardDetail "SupersetClientGetDashboardDetail"
/// @{
/// @brief Fetches detailed dashboard information including related charts and datasets.
/// @}
void SupersetClientGetDashboardDetail(void);

/// @defgroup extract_dataset_id_from_form_data "extract_dataset_id_from_form_data"
/// @{
/// @}
void extract_dataset_id_from_form_data(void);

/// @defgroup SupersetClientExportDashboard "SupersetClientExportDashboard"
/// @{
/// @brief Экспортирует дашборд в виде ZIP-архива.
/// @}
void SupersetClientExportDashboard(void);

/// @defgroup SupersetClientImportDashboard "SupersetClientImportDashboard"
/// @{
/// @brief Импортирует дашборд из ZIP-файла.
/// @}
void SupersetClientImportDashboard(void);

/// @defgroup SupersetClientDeleteDashboard "SupersetClientDeleteDashboard"
/// @{
/// @brief Удаляет дашборд по его ID или slug.
/// @}
void SupersetClientDeleteDashboard(void);

/// @defgroup SupersetDashboardsFiltersMixin "SupersetDashboardsFiltersMixin"
/// @{
/// @brief Dashboard native filter extraction mixin for SupersetClient.
/// @}
void SupersetDashboardsFiltersMixin(void);

/// @defgroup SupersetClientGetDashboard "SupersetClientGetDashboard"
/// @{
/// @brief Fetches a single dashboard by ID or slug.
/// @}
void SupersetClientGetDashboard(void);

/// @defgroup SupersetClientGetDashboardPermalinkState "SupersetClientGetDashboardPermalinkState"
/// @{
/// @brief Fetches stored dashboard permalink state by permalink key.
/// @}
void SupersetClientGetDashboardPermalinkState(void);

/// @defgroup SupersetClientGetNativeFilterState "SupersetClientGetNativeFilterState"
/// @{
/// @brief Fetches stored native filter state by filter state key.
/// @}
void SupersetClientGetNativeFilterState(void);

/// @defgroup SupersetClientExtractNativeFiltersFromPermalink "SupersetClientExtractNativeFiltersFromPermalink"
/// @{
/// @brief Extract native filters dataMask from a permalink key.
/// @}
void SupersetClientExtractNativeFiltersFromPermalink(void);

/// @defgroup SupersetClientExtractNativeFiltersFromKey "SupersetClientExtractNativeFiltersFromKey"
/// @{
/// @brief Extract native filters from a native_filters_key URL parameter.
/// @}
void SupersetClientExtractNativeFiltersFromKey(void);

/// @defgroup SupersetClientParseDashboardUrlForFilters "SupersetClientParseDashboardUrlForFilters"
/// @{
/// @brief Parse a Superset dashboard URL and extract native filter state if present.
/// @}
void SupersetClientParseDashboardUrlForFilters(void);

/// @defgroup SupersetDashboardsListMixin "SupersetDashboardsListMixin"
/// @{
/// @brief Dashboard listing mixin for SupersetClient — paginated list, summary projection.
/// @}
void SupersetDashboardsListMixin(void);

/// @defgroup SupersetClientGetDashboards "SupersetClientGetDashboards"
/// @{
/// @brief Получает полный список дашбордов, автоматически обрабатывая пагинацию.
/// @}
void SupersetClientGetDashboards(void);

/// @defgroup SupersetClientGetDashboardsPage "SupersetClientGetDashboardsPage"
/// @{
/// @brief Fetches a single dashboards page from Superset without iterating all pages.
/// @}
void SupersetClientGetDashboardsPage(void);

/// @defgroup SupersetClientGetDashboardsSummary "SupersetClientGetDashboardsSummary"
/// @{
/// @brief Fetches dashboard metadata optimized for the grid.
/// @}
void SupersetClientGetDashboardsSummary(void);

/// @defgroup SupersetClientGetDashboardsSummaryPage "SupersetClientGetDashboardsSummaryPage"
/// @{
/// @brief Fetches one page of dashboard metadata optimized for the grid.
/// @}
void SupersetClientGetDashboardsSummaryPage(void);

/// @defgroup SupersetDashboardsWriteMixin "SupersetDashboardsWriteMixin"
/// @{
/// @brief Dashboard write mixin for SupersetClient — markdown chart CRUD and layout manipulation for maintenance banners.
/// @invariant All network operations use self.network.request()
/// @}
void SupersetDashboardsWriteMixin(void);

/// @defgroup create_markdown_chart "create_markdown_chart"
/// @{
/// @brief Create a markdown chart and return the new chart ID.
/// @post Returns chart_id (int). Chart is NOT yet placed in dashboard layout.
/// @pre dashboard_id exists in Superset. markdown_text not empty.
/// @}
void create_markdown_chart(void);

/// @defgroup update_markdown_chart "update_markdown_chart"
/// @{
/// @brief Update the markdown text of an existing markdown chart.
/// @post Chart markdown content updated.
/// @pre chart_id exists and is a markdown chart.
/// @}
void update_markdown_chart(void);

/// @defgroup update_dashboard_layout "update_dashboard_layout"
/// @{
/// @brief Insert a native MARKDOWN element at (0,0) with full width (12 cols),
/// @}
void update_dashboard_layout(void);

/// @defgroup remove_chart_from_layout "remove_chart_from_layout"
/// @{
/// @brief Remove banner markdown element from dashboard layout without deleting the chart.
/// @post MARKDOWN element removed from position_json; items shifted up.
/// @pre dashboard_id exists. chart_id exists in layout as MARKDOWN-banner-{chart_id}.
/// @}
void remove_chart_from_layout(void);

/// @defgroup delete_chart "delete_chart"
/// @{
/// @brief Delete a chart from Superset by ID.
/// @post Chart permanently deleted from Superset.
/// @pre chart_id exists.
/// @}
void delete_chart(void);

/// @defgroup update_banner_on_dashboard "update_banner_on_dashboard"
/// @{
/// @brief Update the content of a native MARKDOWN banner element on a dashboard.
/// @post MARKDOWN element content updated on dashboard.
/// @pre dashboard_id exists. chart_id used for key lookup.
/// @}
void update_banner_on_dashboard(void);

/// @defgroup get_dashboard_layout "get_dashboard_layout"
/// @{
/// @brief Fetch the position_json layout of a dashboard.
/// @post Returns the dashboard layout dict.
/// @pre dashboard_id exists.
/// @}
void get_dashboard_layout(void);

/// @defgroup _resolve_markdown_datasource "_resolve_markdown_datasource"
/// @{
/// @brief Find a valid datasource_id for markdown chart creation.
/// @post Returns an integer datasource_id.
/// @pre dashboard_id exists.
/// @}
void _resolve_markdown_datasource(void);

/// @defgroup SupersetDatabasesMixin "SupersetDatabasesMixin"
/// @{
/// @brief Database domain mixin for SupersetClient — list, get, summary, by_uuid.
/// @}
void SupersetDatabasesMixin(void);

/// @defgroup SupersetClientGetDatabases "SupersetClientGetDatabases"
/// @{
/// @brief Получает полный список баз данных.
/// @}
void SupersetClientGetDatabases(void);

/// @defgroup SupersetClientGetDatabase "SupersetClientGetDatabase"
/// @{
/// @brief Получает информацию о конкретной базе данных по её ID.
/// @}
void SupersetClientGetDatabase(void);

/// @defgroup SupersetClientGetDatabasesSummary "SupersetClientGetDatabasesSummary"
/// @{
/// @brief Fetch a summary of databases including uuid, name, and engine.
/// @}
void SupersetClientGetDatabasesSummary(void);

/// @defgroup SupersetClientGetDatabaseByUuid "SupersetClientGetDatabaseByUuid"
/// @{
/// @brief Find a database by its UUID.
/// @}
void SupersetClientGetDatabaseByUuid(void);

/// @defgroup SupersetDatasetsMixin "SupersetDatasetsMixin"
/// @{
/// @brief Dataset domain mixin for SupersetClient — list, get, detail, update.
/// @}
void SupersetDatasetsMixin(void);

/// @defgroup SupersetClientGetDatasets "SupersetClientGetDatasets"
/// @{
/// @brief Получает полный список датасетов, автоматически обрабатывая пагинацию.
/// @}
void SupersetClientGetDatasets(void);

/// @defgroup SupersetClientGetDatasetsSummary "SupersetClientGetDatasetsSummary"
/// @{
/// @brief Fetches dataset metadata optimized for the Dataset Hub grid.
/// @}
void SupersetClientGetDatasetsSummary(void);

/// @defgroup SupersetClientGetDatasetLinkedDashboardCount "SupersetClientGetDatasetLinkedDashboardCount"
/// @{
/// @brief Fetch the number of dashboards linked to a dataset via related_objects endpoint.
/// @}
void SupersetClientGetDatasetLinkedDashboardCount(void);

/// @defgroup SupersetClientGetDatasetDetail "SupersetClientGetDatasetDetail"
/// @{
/// @brief Fetches detailed dataset information including columns and linked dashboards.
/// @}
void SupersetClientGetDatasetDetail(void);

/// @defgroup SupersetClientGetDataset "SupersetClientGetDataset"
/// @{
/// @brief Получает информацию о конкретном датасете по его ID.
/// @}
void SupersetClientGetDataset(void);

/// @defgroup SupersetClientUpdateDataset "SupersetClientUpdateDataset"
/// @{
/// @brief Обновляет данные датасета по его ID.
/// @}
void SupersetClientUpdateDataset(void);

/// @defgroup SupersetDatasetsPreviewMixin "SupersetDatasetsPreviewMixin"
/// @{
/// @brief Dataset preview compilation mixin for SupersetClient — build query context, compile SQL.
/// @}
void SupersetDatasetsPreviewMixin(void);

/// @defgroup SupersetClientCompileDatasetPreview "SupersetClientCompileDatasetPreview"
/// @{
/// @brief Compile dataset preview SQL through the strongest supported Superset preview endpoint family and return normalized SQL output.
/// @}
void SupersetClientCompileDatasetPreview(void);

/// @defgroup SupersetClientBuildDatasetPreviewLegacyFormData "SupersetClientBuildDatasetPreviewLegacyFormData"
/// @{
/// @brief Build browser-style legacy form_data payload for Superset preview endpoints inferred from observed deployment traffic.
/// @}
void SupersetClientBuildDatasetPreviewLegacyFormData(void);

/// @defgroup SupersetClientBuildDatasetPreviewQueryContext "SupersetClientBuildDatasetPreviewQueryContext"
/// @{
/// @brief Build a reduced-scope chart-data query context for deterministic dataset preview compilation.
/// @}
void SupersetClientBuildDatasetPreviewQueryContext(void);

/// @defgroup SupersetDatasetsPreviewFiltersMixin "SupersetDatasetsPreviewFiltersMixin"
/// @{
/// @brief Filter normalization and SQL extraction helpers for dataset preview compilation.
/// @}
void SupersetDatasetsPreviewFiltersMixin(void);

/// @defgroup SupersetClientNormalizeEffectiveFiltersForQueryContext "SupersetClientNormalizeEffectiveFiltersForQueryContext"
/// @{
/// @brief Convert execution mappings into Superset chart-data filter objects.
/// @}
void SupersetClientNormalizeEffectiveFiltersForQueryContext(void);

/// @defgroup SupersetClientExtractCompiledSqlFromPreviewResponse "SupersetClientExtractCompiledSqlFromPreviewResponse"
/// @{
/// @brief Normalize compiled SQL from either chart-data or legacy form_data preview responses.
/// @}
void SupersetClientExtractCompiledSqlFromPreviewResponse(void);

/// @defgroup LayoutUtils "LayoutUtils"
/// @{
/// @brief Utility functions for manipulating Superset dashboard position_json layout.
/// @}
void LayoutUtils(void);

/// @defgroup parse_position_json "parse_position_json"
/// @{
/// @brief Parse position_json from a dashboard API response (may be string or dict).
/// @post Returns a dict.
/// @pre raw_position is a string, dict, or None.
/// @}
void parse_position_json(void);

/// @defgroup _estimate_markdown_height "_estimate_markdown_height"
/// @{
/// @brief Estimate grid height for a MARKDOWN element based on HTML content.
/// @}
void _estimate_markdown_height(void);

/// @defgroup _generate_banner_id "_generate_banner_id"
/// @{
/// @brief Generate a deterministic row and markdown key for a banner chart.
/// @}
void _generate_banner_id(void);

/// @defgroup insert_banner_markdown_at_top "insert_banner_markdown_at_top"
/// @{
/// @brief Insert a ROW + native MARKDOWN pair at the top of the dashboard grid.
/// @}
void insert_banner_markdown_at_top(void);

/// @defgroup update_banner_markdown_content "update_banner_markdown_content"
/// @{
/// @brief Update the code content and adaptive height of an existing banner markdown element.
/// @post position_json is mutated; markdown content and height updated.
/// @pre position_json has markdown_key. content is the new HTML/markdown string.
/// @}
void update_banner_markdown_content(void);

/// @defgroup remove_banner_from_position "remove_banner_from_position"
/// @{
/// @brief Remove the banner ROW + MARKDOWN pair from the position dict and GRID children.
/// @}
void remove_banner_from_position(void);

/// @defgroup SupersetUserProjection "SupersetUserProjection"
/// @{
/// @brief User/owner payload normalization helpers for Superset client responses.
/// @}
void SupersetUserProjection(void);

/// @defgroup SupersetUserProjectionMixin "SupersetUserProjectionMixin"
/// @{
/// @brief Mixin providing user/owner payload normalization for Superset API responses.
/// @}
void SupersetUserProjectionMixin(void);

/// @defgroup SupersetClientExtractOwnerLabels "SupersetClientExtractOwnerLabels"
/// @{
/// @brief Normalize dashboard owners payload to stable display labels.
/// @}
void SupersetClientExtractOwnerLabels(void);

/// @defgroup SupersetClientExtractUserDisplay "SupersetClientExtractUserDisplay"
/// @{
/// @brief Normalize user payload to a stable display name.
/// @}
void SupersetClientExtractUserDisplay(void);

/// @defgroup SupersetClientSanitizeUserText "SupersetClientSanitizeUserText"
/// @{
/// @brief Convert scalar value to non-empty user-facing text.
/// @}
void SupersetClientSanitizeUserText(void);

/// @defgroup SupersetProfileLookup "SupersetProfileLookup"
/// @{
/// @brief Provides environment-scoped Superset account lookup adapter with stable normalized output.
/// @invariant Adapter never leaks raw upstream payload shape to API consumers.
/// @}
void SupersetProfileLookup(void);

/// @defgroup SupersetAccountLookupAdapter "SupersetAccountLookupAdapter"
/// @{
/// @brief Lookup Superset users and normalize candidates for profile binding.
/// @}
void SupersetAccountLookupAdapter(void);

/// @defgroup __init__ "__init__"
/// @{
/// @brief Initializes lookup adapter with authenticated API client and environment context.
/// @post Adapter is ready to perform users lookup requests.
/// @pre network_client supports request(method, endpoint, params=...).
/// @}
void __init__(void);

/// @defgroup get_users_page "get_users_page"
/// @{
/// @brief Fetch one users page from Superset with passthrough search/sort parameters.
/// @post Returns deterministic payload with normalized items and total count.
/// @pre page_index >= 0 and page_size >= 1.
/// @return Dict[str, Any]
/// @}
void get_users_page(void);

/// @defgroup _normalize_lookup_payload "_normalize_lookup_payload"
/// @{
/// @brief Convert Superset users response variants into stable candidates payload.
/// @post Output contains canonical keys: status, environment_id, page_index, page_size, total, items.
/// @pre response can be dict/list in any supported upstream shape.
/// @return Dict[str, Any]
/// @}
void _normalize_lookup_payload(void);

/// @defgroup normalize_user_payload "normalize_user_payload"
/// @{
/// @brief Project raw Superset user object to canonical candidate shape.
/// @post Returns normalized candidate keys (environment_id, username, display_name, email, is_active).
/// @pre raw_user may have heterogenous key names between Superset versions.
/// @return Dict[str, Any]
/// @}
void normalize_user_payload(void);

/// @defgroup TaskManagerPackage "TaskManagerPackage"
/// @{
/// @}
void TaskManagerPackage(void);

/// @defgroup TestContext "TestContext"
/// @{
/// @brief Verify TaskContext preserves optional background task scheduler across sub-context creation.
/// @}
void TestContext(void);

/// @defgroup test_task_context_preserves_background_tasks_across_sub_context "test_task_context_preserves_background_tasks_across_sub_context"
/// @{
/// @brief Plugins must be able to access background_tasks from both root and sub-context loggers.
/// @post background_tasks remains available on root and derived sub-contexts.
/// @pre TaskContext is initialized with a BackgroundTasks-like object.
/// @}
void test_task_context_preserves_background_tasks_across_sub_context(void);

/// @defgroup __tests___test_task_logger "__tests__/test_task_logger"
/// @{
/// @brief Contract testing for TaskLogger
/// @}
void __tests___test_task_logger(void);

/// @defgroup test_task_logger_initialization "test_task_logger_initialization"
/// @{
/// @brief Verify TaskLogger initializes with correct task_id and state.
/// @}
void test_task_logger_initialization(void);

/// @defgroup test_log_methods_delegation "test_log_methods_delegation"
/// @{
/// @brief Verify TaskLogger delegates log method calls to the underlying persistence service.
/// @}
void test_log_methods_delegation(void);

/// @defgroup test_with_source "test_with_source"
/// @{
/// @brief Verify TaskLogger.with_source returns a new logger with the correct source attribution.
/// @}
void test_with_source(void);

/// @defgroup test_missing_task_id "test_missing_task_id"
/// @{
/// @brief Verify TaskLogger raises or handles missing task_id gracefully.
/// @}
void test_missing_task_id(void);

/// @defgroup test_invalid_add_log_fn "test_invalid_add_log_fn"
/// @{
/// @brief Verify TaskLogger raises ValueError for invalid add_log_fn parameter.
/// @}
void test_invalid_add_log_fn(void);

/// @defgroup test_progress_log "test_progress_log"
/// @{
/// @brief Verify TaskLogger correctly logs progress updates with percentage and message.
/// @}
void test_progress_log(void);

/// @defgroup TaskCleanupModule "TaskCleanupModule"
/// @{
/// @brief Implements task cleanup and retention policies, including associated logs.
/// @}
void TaskCleanupModule(void);

/// @defgroup TaskCleanupService "TaskCleanupService"
/// @{
/// @brief Provides methods to clean up old task records and their associated logs.
/// @}
void TaskCleanupService(void);

/// @defgroup run_cleanup "run_cleanup"
/// @{
/// @brief Deletes tasks older than the configured retention period and their logs.
/// @post Old tasks and their logs are deleted from persistence.
/// @pre Config manager has valid settings.
/// @}
void run_cleanup(void);

/// @defgroup delete_task_with_logs "delete_task_with_logs"
/// @{
/// @brief Delete a single task and all its associated logs.
/// @param task_id (str) - The task ID to delete.
/// @post Task and all its logs are deleted.
/// @pre task_id is a valid task ID.
/// @}
void delete_task_with_logs(void);

/// @defgroup TaskContextModule "TaskContextModule"
/// @{
/// @brief Provides execution context passed to plugins during task execution.
/// @invariant Each TaskContext is bound to a single task execution.
/// @post Plugins receive context instances with stable logger and parameter accessors.
/// @pre Task execution pipeline provides valid task identifiers, logging callbacks, and parameter dictionaries.
/// @}
void TaskContextModule(void);

/// @defgroup TaskContext "TaskContext"
/// @{
/// @brief A container passed to plugin.execute() providing the logger and other task-specific utilities.
/// @invariant logger is always a valid TaskLogger instance.
/// @post Instance exposes immutable task identity with logger, params, and optional background task access.
/// @pre Constructor receives non-empty task_id, callable add_log_fn, and params mapping.
/// @}
void TaskContext(void);

/// @defgroup task_id "task_id"
/// @{
/// @brief Get the task ID.
/// @post Returns the task ID string.
/// @pre TaskContext must be initialized.
/// @return str - The task ID.
/// @}
void task_id(void);

/// @defgroup logger "logger"
/// @{
/// @brief Get the TaskLogger instance for this context.
/// @post Returns the TaskLogger instance.
/// @pre TaskContext must be initialized.
/// @return TaskLogger - The logger instance.
/// @}
void logger(void);

/// @defgroup params "params"
/// @{
/// @brief Get the task parameters.
/// @post Returns the parameters dictionary.
/// @pre TaskContext must be initialized.
/// @return Dict[str, Any] - The task parameters.
/// @}
void params(void);

/// @defgroup background_tasks "background_tasks"
/// @{
/// @brief Expose optional background task scheduler for plugins that dispatch deferred side effects.
/// @post Returns BackgroundTasks-like object or None.
/// @pre TaskContext must be initialized.
/// @}
void background_tasks(void);

/// @defgroup get_param "get_param"
/// @{
/// @brief Get a specific parameter value with optional default.
/// @param default (Any) - Default value if key not found.
/// @post Returns parameter value or default.
/// @pre TaskContext must be initialized.
/// @return Any - Parameter value or default.
/// @}
void get_param(void);

/// @defgroup create_sub_context "create_sub_context"
/// @{
/// @brief Create a sub-context with a different default source.
/// @param source (str) - New default source for logging.
/// @post Returns new TaskContext with different logger source.
/// @pre source is a non-empty string.
/// @return TaskContext - New context with different source.
/// @}
void create_sub_context(void);

/// @defgroup EventBusModule "EventBusModule"
/// @{
/// @brief Task-scoped log buffering, persistence flushes, and subscriber fan-out for real-time
/// @}
void EventBusModule(void);

/// @defgroup EventBus "EventBus"
/// @{
/// @brief Coordinates task-scoped log buffering, persistence flushes, and subscriber fan-out
/// @}
void EventBus(void);

/// @defgroup flush_task_logs "flush_task_logs"
/// @{
/// @brief Flush logs for a specific task immediately.
/// @post Task's buffered logs are written to database.
/// @pre task_id exists.
/// @}
void flush_task_logs(void);

/// @defgroup add_log "add_log"
/// @{
/// @brief Adds a log entry to a task buffer and notifies subscribers.
/// @post Log added to buffer and pushed to queues (if level meets task_log_level filter).
/// @pre Task exists.
/// @}
void add_log(void);

/// @defgroup TaskGraphModule "TaskGraphModule"
/// @{
/// @brief In-memory task registry with persistence-backed hydration, pagination, and
/// @}
void TaskGraphModule(void);

/// @defgroup TaskGraph "TaskGraph"
/// @{
/// @brief In-memory task dependency graph spanning task registry nodes, pause futures,
/// @}
void TaskGraph(void);

/// @defgroup add_task "add_task"
/// @{
/// @brief Register a task in the in-memory registry.
/// @}
void add_task(void);

/// @defgroup remove_tasks "remove_tasks"
/// @{
/// @brief Remove tasks from registry and persistence, cancel futures for waiting tasks.
/// @}
void remove_tasks(void);

/// @defgroup create_future "create_future"
/// @{
/// @brief Create and store a future for a paused task.
/// @}
void create_future(void);

/// @defgroup resolve_future "resolve_future"
/// @{
/// @brief Resolve a paused task's future and remove it from the map.
/// @}
void resolve_future(void);

/// @defgroup remove_future "remove_future"
/// @{
/// @brief Remove a future without resolving it.
/// @}
void remove_future(void);

/// @defgroup JobLifecycleModule "JobLifecycleModule"
/// @{
/// @brief Task creation, execution, pause/resume, and completion transitions for plugin-backed
/// @}
void JobLifecycleModule(void);

/// @defgroup JobLifecycle "JobLifecycle"
/// @{
/// @brief Encodes task creation, execution, pause/resume, and completion transitions for
/// @}
void JobLifecycle(void);

/// @defgroup _broadcast_dataset_updated "_broadcast_dataset_updated"
/// @{
/// @brief Broadcast dataset.updated event to all subscribers for a given environment.
/// @}
void _broadcast_dataset_updated(void);

/// @defgroup TaskManagerModule "TaskManagerModule"
/// @{
/// @brief Thin facade composing TaskGraph (registry), EventBus (log/pub-sub), and JobLifecycle
/// @}
void TaskManagerModule(void);

/// @defgroup TaskManager "TaskManager"
/// @{
/// @brief Facade composing TaskGraph, EventBus, and JobLifecycle into a single interface.
/// @post In-memory task graph, lifecycle scheduler, and log event bus stay consistent with
/// @pre Plugin loader resolves plugin ids and persistence services are available.
/// @}
void TaskManager(void);

/// @defgroup _make_add_log_callback "_make_add_log_callback"
/// @{
/// @brief Create a closure for adding logs that looks up the task and delegates to EventBus.
/// @}
void _make_add_log_callback(void);

/// @defgroup _flusher_loop "_flusher_loop"
/// @{
/// @brief Legacy alias delegating to EventBus._flusher_loop.
/// @}
void _flusher_loop(void);

/// @defgroup _flush_logs "_flush_logs"
/// @{
/// @brief Legacy alias delegating to EventBus._flush_logs.
/// @}
void _flush_logs(void);

/// @defgroup _flush_task_logs "_flush_task_logs"
/// @{
/// @brief Legacy alias delegating to EventBus.flush_task_logs.
/// @}
void _flush_task_logs(void);

/// @defgroup get_task "get_task"
/// @{
/// @brief Retrieves a task by its ID.
/// @}
void get_task(void);

/// @defgroup get_all_tasks "get_all_tasks"
/// @{
/// @brief Retrieves all registered tasks.
/// @}
void get_all_tasks(void);

/// @defgroup get_tasks "get_tasks"
/// @{
/// @brief Retrieves tasks with pagination and optional status filter.
/// @}
void get_tasks(void);

/// @defgroup load_persisted_tasks "load_persisted_tasks"
/// @{
/// @brief Load persisted tasks using persistence service.
/// @}
void load_persisted_tasks(void);

/// @defgroup clear_tasks "clear_tasks"
/// @{
/// @brief Clears tasks based on status filter (also deletes associated logs).
/// @}
void clear_tasks(void);

/// @defgroup get_task_logs "get_task_logs"
/// @{
/// @brief Retrieves logs for a specific task (from memory or persistence).
/// @}
void get_task_logs(void);

/// @defgroup get_task_log_stats "get_task_log_stats"
/// @{
/// @brief Get statistics about logs for a task.
/// @}
void get_task_log_stats(void);

/// @defgroup get_task_log_sources "get_task_log_sources"
/// @{
/// @brief Get unique sources for a task's logs.
/// @}
void get_task_log_sources(void);

/// @defgroup subscribe_logs "subscribe_logs"
/// @{
/// @brief Subscribes to real-time logs for a task.
/// @}
void subscribe_logs(void);

/// @defgroup unsubscribe_logs "unsubscribe_logs"
/// @{
/// @brief Unsubscribes from real-time logs for a task.
/// @}
void unsubscribe_logs(void);

/// @defgroup create_task "create_task"
/// @{
/// @brief Creates and queues a new task for execution.
/// @}
void create_task(void);

/// @defgroup _run_task "_run_task"
/// @{
/// @brief Internal method to execute a task with TaskContext support (delegates to lifecycle).
/// @}
void _run_task(void);

/// @defgroup resolve_task "resolve_task"
/// @{
/// @brief Resumes a task that is awaiting mapping.
/// @}
void resolve_task(void);

/// @defgroup wait_for_resolution "wait_for_resolution"
/// @{
/// @brief Pauses execution and waits for a resolution signal.
/// @}
void wait_for_resolution(void);

/// @defgroup wait_for_input "wait_for_input"
/// @{
/// @brief Pauses execution and waits for user input.
/// @}
void wait_for_input(void);

/// @defgroup await_input "await_input"
/// @{
/// @brief Transition a task to AWAITING_INPUT state with input request.
/// @}
void await_input(void);

/// @defgroup resume_task_with_password "resume_task_with_password"
/// @{
/// @brief Resume a task that is awaiting input with provided passwords.
/// @}
void resume_task_with_password(void);

/// @defgroup subscribe_dataset_events "subscribe_dataset_events"
/// @{
/// @brief Subscribe to dataset.updated events for an environment.
/// @}
void subscribe_dataset_events(void);

/// @defgroup unsubscribe_dataset_events "unsubscribe_dataset_events"
/// @{
/// @brief Unsubscribe from dataset.updated events.
/// @}
void unsubscribe_dataset_events(void);

/// @defgroup TaskManagerModels "TaskManagerModels"
/// @{
/// @brief Defines the data models and enumerations used by the Task Manager.
/// @invariant Must use Pydantic for data validation.
/// @post Task models exported with immutable IDs
/// @pre Task manager initialized
/// @}
void TaskManagerModels(void);

/// @defgroup TaskStatus "TaskStatus"
/// @{
/// @}
void TaskStatus(void);

/// @defgroup LogLevel "LogLevel"
/// @{
/// @}
void LogLevel(void);

/// @defgroup TaskLog "TaskLog"
/// @{
/// @brief A Pydantic model representing a persisted log entry from the database.
/// @}
void TaskLog(void);

/// @defgroup LogFilter "LogFilter"
/// @{
/// @}
void LogFilter(void);

/// @defgroup LogStats "LogStats"
/// @{
/// @brief Statistics about log entries for a task.
/// @}
void LogStats(void);

/// @defgroup Task "Task"
/// @{
/// @brief A Pydantic model representing a single execution instance of a plugin, including its status, parameters, and logs.
/// @}
void Task(void);

/// @defgroup TaskPersistenceModule "TaskPersistenceModule"
/// @{
/// @brief Handles the persistence of tasks using SQLAlchemy and the tasks.db database.
/// @invariant Database schema must match the TaskRecord model structure.
/// @post Provides reliable storage and retrieval for task metadata and logs.
/// @pre Tasks database must be initialized with TaskRecord and TaskLogRecord schemas.
/// @}
void TaskPersistenceModule(void);

/// @defgroup TaskPersistenceService "TaskPersistenceService"
/// @{
/// @brief Provides methods to save, load, and delete task records in tasks.db using SQLAlchemy models.
/// @invariant Persistence must handle potentially missing task fields natively.
/// @post Persist operations leave matching TaskRecord rows committed or rolled back without leaking sessions, load operations return reconstructed Task objects from stored TaskRecord rows, and delete operations remove only the addressed task rows.
/// @pre TasksSessionLocal must provide an active SQLAlchemy session, Task inputs must expose id/plugin_id/status/params/result/logs fields, and TaskRecord plus Environment schemas must be available.
/// @}
void TaskPersistenceService(void);

/// @defgroup _json_load_if_needed "_json_load_if_needed"
/// @{
/// @brief Safely load JSON strings from DB if necessary
/// @post Returns parsed JSON object, list, string, or primitive
/// @pre value is an arbitrary database value
/// @}
void _json_load_if_needed(void);

/// @defgroup _parse_datetime "_parse_datetime"
/// @{
/// @brief Safely parse a datetime string from the database
/// @post Returns datetime object or None
/// @pre value is an ISO string or datetime object
/// @}
void _parse_datetime(void);

/// @defgroup _resolve_environment_id "_resolve_environment_id"
/// @{
/// @brief Resolve environment id into existing environments.id value to satisfy FK constraints.
/// @post Returns existing environments.id or None when unresolved.
/// @pre Session is active
/// @}
void _resolve_environment_id(void);

/// @defgroup persist_task "persist_task"
/// @{
/// @brief Persists or updates a single task in the database.
/// @param task (Task) - The task object to persist.
/// @post Task record created or updated in database.
/// @pre isinstance(task, Task)
/// @}
void persist_task(void);

/// @defgroup persist_tasks "persist_tasks"
/// @{
/// @brief Persists multiple tasks.
/// @param tasks (List[Task]) - The list of tasks to persist.
/// @post All tasks in list are persisted.
/// @pre isinstance(tasks, list)
/// @}
void persist_tasks(void);

/// @defgroup load_tasks "load_tasks"
/// @{
/// @brief Loads tasks from the database.
/// @param status (Optional[TaskStatus]) - Filter by status.
/// @post Returns list of Task objects.
/// @pre limit is an integer.
/// @return List[Task] - The loaded tasks.
/// @}
void load_tasks(void);

/// @defgroup delete_tasks "delete_tasks"
/// @{
/// @brief Deletes specific tasks from the database.
/// @param task_ids (List[str]) - List of task IDs to delete.
/// @post Specified task records deleted from database.
/// @pre task_ids is a list of strings.
/// @}
void delete_tasks(void);

/// @defgroup TaskLogPersistenceService "TaskLogPersistenceService"
/// @{
/// @brief Provides methods to store, query, summarize, and delete task log rows in the task_logs table.
/// @invariant Log entries are batch-inserted for performance.
/// @post add_logs commits all provided log entries or rolls back on failure, query methods return TaskLog or LogStats views reconstructed from TaskLogRecord rows, and delete methods remove only log rows matching the supplied task identifiers.
/// @pre TasksSessionLocal must provide an active SQLAlchemy session, task_id inputs must identify task log rows, LogEntry batches must expose timestamp/level/source/message/metadata fields, and LogFilter inputs must provide pagination and filter attributes used by queries.
/// @}
void TaskLogPersistenceService(void);

/// @defgroup add_logs "add_logs"
/// @{
/// @brief Batch insert log entries for a task.
/// @param logs (List[LogEntry]) - Log entries to insert.
/// @post All logs inserted into task_logs table.
/// @pre logs is a list of LogEntry objects.
/// @}
void add_logs(void);

/// @defgroup get_logs "get_logs"
/// @{
/// @brief Query logs for a task with filtering and pagination.
/// @param log_filter (LogFilter) - Filter parameters.
/// @post Returns list of TaskLog objects matching filters.
/// @pre task_id is a valid task ID.
/// @return List[TaskLog] - Filtered log entries.
/// @}
void get_logs(void);

/// @defgroup get_log_stats "get_log_stats"
/// @{
/// @brief Get statistics about logs for a task.
/// @param task_id (str) - The task ID.
/// @post Returns LogStats with counts by level and source.
/// @pre task_id is a valid task ID.
/// @return LogStats - Statistics about task logs.
/// @}
void get_log_stats(void);

/// @defgroup get_sources "get_sources"
/// @{
/// @brief Get unique sources for a task's logs.
/// @param task_id (str) - The task ID.
/// @post Returns list of unique source strings.
/// @pre task_id is a valid task ID.
/// @return List[str] - Unique source names.
/// @}
void get_sources(void);

/// @defgroup delete_logs_for_task "delete_logs_for_task"
/// @{
/// @brief Delete all logs for a specific task.
/// @param task_id (str) - The task ID.
/// @post All logs for the task are deleted.
/// @pre task_id is a valid task ID.
/// @}
void delete_logs_for_task(void);

/// @defgroup delete_logs_for_tasks "delete_logs_for_tasks"
/// @{
/// @brief Delete all logs for multiple tasks.
/// @param task_ids (List[str]) - List of task IDs.
/// @post All logs for the tasks are deleted.
/// @pre task_ids is a list of task IDs.
/// @}
void delete_logs_for_tasks(void);

/// @defgroup TaskLoggerModule "TaskLoggerModule"
/// @{
/// @brief Provides a dedicated logger for tasks with automatic source attribution.
/// @invariant Each TaskLogger instance is bound to a specific task_id and default source.
/// @}
void TaskLoggerModule(void);

/// @defgroup TaskLogger "TaskLogger"
/// @{
/// @brief A wrapper around TaskManager._add_log that carries task_id and source context.
/// @invariant All log calls include the task_id and source.
/// @}
void TaskLogger(void);

/// @defgroup with_source "with_source"
/// @{
/// @brief Create a sub-logger with a different default source.
/// @param source (str) - New default source.
/// @post Returns new TaskLogger with the same task_id but different source.
/// @pre source is a non-empty string.
/// @return TaskLogger - New logger instance.
/// @}
void with_source(void);

/// @defgroup _log "_log"
/// @{
/// @brief Internal method to log a message at a given level.
/// @param metadata (Optional[Dict]) - Additional structured data.
/// @post Log entry added via add_log_fn.
/// @pre level is a valid log level string.
/// @}
void _log(void);

/// @defgroup debug "debug"
/// @{
/// @brief Log a DEBUG level message.
/// @param metadata (Optional[Dict]) - Additional data.
/// @post Log entry added via internally with DEBUG level.
/// @pre message is a string.
/// @}
void debug(void);

/// @defgroup info "info"
/// @{
/// @brief Log an INFO level message.
/// @param metadata (Optional[Dict]) - Additional data.
/// @post Log entry added internally with INFO level.
/// @pre message is a string.
/// @}
void info(void);

/// @defgroup warning "warning"
/// @{
/// @brief Log a WARNING level message.
/// @param metadata (Optional[Dict]) - Additional data.
/// @post Log entry added internally with WARNING level.
/// @pre message is a string.
/// @}
void warning(void);

/// @defgroup error "error"
/// @{
/// @brief Log an ERROR level message.
/// @param metadata (Optional[Dict]) - Additional data.
/// @post Log entry added internally with ERROR level.
/// @pre message is a string.
/// @}
void error(void);

/// @defgroup progress "progress"
/// @{
/// @brief Log a progress update with percentage.
/// @param source (Optional[str]) - Override source.
/// @post Log entry with progress metadata added.
/// @pre percent is between 0 and 100.
/// @}
void progress(void);

/// @defgroup AppTimezone "AppTimezone"
/// @{
/// @brief Application-level timezone utilities. Reads APP_TIMEZONE from env (default Europe/Moscow)
/// @}
void AppTimezone(void);

/// @defgroup _get_default_tz_name "_get_default_tz_name"
/// @{
/// @brief Read APP_TIMEZONE from env, fall back to Europe/Moscow.
/// @post Returns a valid IANA timezone string.
/// @pre Environment is loaded (dotenv or os.environ).
/// @}
void _get_default_tz_name(void);

/// @defgroup get_app_timezone "get_app_timezone"
/// @{
/// @brief Return cached ZoneInfo for the configured application timezone.
/// @post Returns a ZoneInfo instance matching APP_TIMEZONE env var.
/// @}
void get_app_timezone(void);

/// @defgroup invalidate_timezone_cache "invalidate_timezone_cache"
/// @{
/// @brief Reset the cached ZoneInfo so the next get_app_timezone() call re-reads from env/DB.
/// @post _APP_TZ_CACHE is set to None; subsequent get_app_timezone() will re-resolve.
/// @}
void invalidate_timezone_cache(void);

/// @defgroup validate_timezone "validate_timezone"
/// @{
/// @brief Validate that a timezone string is a known IANA timezone.
/// @post Returns True if ZoneInfo accepts the name, False otherwise.
/// @pre tz_name is a string.
/// @}
void validate_timezone(void);

/// @defgroup localize "localize"
/// @{
/// @brief Convert a timezone-aware or naive UTC datetime to the configured app timezone.
/// @post Returns a datetime with the app timezone attached (astimezone).
/// @pre If dt is timezone-naive, it is assumed to be UTC.
/// @}
void localize(void);

/// @defgroup now "now"
/// @{
/// @brief Get current time in the configured application timezone.
/// @post Returns timezone-aware datetime in the app timezone.
/// @}
void now(void);

/// @defgroup format_timezone_offset "format_timezone_offset"
/// @{
/// @brief Return the UTC offset string for the configured timezone (e.g. "+03:00").
/// @post Returns string like "+03:00" or "+00:00".
/// @}
void format_timezone_offset(void);

/// @defgroup CoreUtils "CoreUtils"
/// @{
/// @brief Shared utility package root.
/// @}
void CoreUtils(void);

/// @defgroup AsyncAPIClient___init__ "AsyncAPIClient.__init__"
/// @{
/// @brief Initialize async API client for one environment.
/// @post Client is ready for async request/authentication flow.
/// @pre config contains base_url and auth payload.
/// @}
void AsyncAPIClient___init__(void);

/// @defgroup AsyncAPIClient__normalize_base_url "AsyncAPIClient._normalize_base_url"
/// @{
/// @brief Normalize base URL for Superset API root construction.
/// @post Returns canonical base URL without trailing slash and duplicate /api/v1 suffix.
/// @}
void AsyncAPIClient__normalize_base_url(void);

/// @defgroup AsyncAPIClient__build_api_url "AsyncAPIClient._build_api_url"
/// @{
/// @brief Build full API URL from relative Superset endpoint.
/// @post Returns absolute URL for upstream request.
/// @}
void AsyncAPIClient__build_api_url(void);

/// @defgroup AsyncAPIClient__get_auth_lock "AsyncAPIClient._get_auth_lock"
/// @{
/// @brief Return per-cache-key async lock to serialize fresh login attempts.
/// @post Returns stable asyncio.Lock instance.
/// @}
void AsyncAPIClient__get_auth_lock(void);

/// @defgroup AsyncAPIClient_authenticate "AsyncAPIClient.authenticate"
/// @{
/// @brief Authenticate against Superset and cache access/csrf tokens.
/// @post Client tokens are populated and reusable across requests.
/// @}
void AsyncAPIClient_authenticate(void);

/// @defgroup AsyncAPIClient_get_headers "AsyncAPIClient.get_headers"
/// @{
/// @brief Return authenticated Superset headers for async requests.
/// @post Headers include Authorization and CSRF tokens.
/// @}
void AsyncAPIClient_get_headers(void);

/// @defgroup AsyncAPIClient__is_dashboard_endpoint "AsyncAPIClient._is_dashboard_endpoint"
/// @{
/// @brief Determine whether an API endpoint represents a dashboard resource for 404 translation.
/// @post Returns true only for dashboard-specific endpoints.
/// @}
void AsyncAPIClient__is_dashboard_endpoint(void);

/// @defgroup AsyncAPIClient__handle_network_error "AsyncAPIClient._handle_network_error"
/// @{
/// @brief Translate generic httpx errors into NetworkError.
/// @post Raises NetworkError with URL context.
/// @}
void AsyncAPIClient__handle_network_error(void);

/// @defgroup AsyncAPIClient_aclose "AsyncAPIClient.aclose"
/// @{
/// @brief Close underlying httpx client.
/// @post Client resources are released.
/// @}
void AsyncAPIClient_aclose(void);

/// @defgroup DatasetMapperModule "DatasetMapperModule"
/// @{
/// @brief Этот модуль отвечает за обновление метаданных (verbose_name) в датасетах Superset,
/// @}
void DatasetMapperModule(void);

/// @defgroup DatasetMapper "DatasetMapper"
/// @{
/// @brief Класс для маппинга и обновления verbose_name в датасетах Superset.
/// @}
void DatasetMapper(void);

/// @defgroup get_sqllab_mappings "get_sqllab_mappings"
/// @{
/// @brief Извлекает маппинги column_name -> verbose_name через SQL Lab Superset.
/// @post Возвращается словарь column_name -> verbose_name из результатов SQL-запроса.
/// @pre dataset_id должен существовать в Superset.
/// @}
void get_sqllab_mappings(void);

/// @defgroup load_excel_mappings "load_excel_mappings"
/// @{
/// @brief Загружает маппинги column_name -> verbose_name из XLSX файла.
/// @param file_path (str) - Путь к XLSX файлу.
/// @post Возвращается словарь с маппингами из файла.
/// @pre file_path должен указывать на существующий XLSX файл.
/// @return Dict[str, str] - Словарь с маппингами.
/// @}
void load_excel_mappings(void);

/// @defgroup run_mapping "run_mapping"
/// @{
/// @brief Основная функция для выполнения маппинга и обновления verbose_name датасета в Superset.
/// @param excel_path (Optional[str]) - Путь к XLSX файлу.
/// @post Если найдены изменения, датасет в Superset обновлен через API.
/// @pre dataset_id должен быть существующим ID в Superset.
/// @}
void run_mapping(void);

/// @defgroup FileIO "FileIO"
/// @{
/// @brief Предоставляет набор утилит для управления файловыми операциями, включая работу с временными файлами, архивами ZIP, файлами YAML и очистку директорий.
/// @}
void FileIO(void);

/// @defgroup InvalidZipFormatError "InvalidZipFormatError"
/// @{
/// @brief Exception raised when a file is not a valid ZIP archive.
/// @}
void InvalidZipFormatError(void);

/// @defgroup create_temp_file "create_temp_file"
/// @{
/// @brief Контекстный менеджер для создания временного файла или директории с гарантированным удалением.
/// @post Временный ресурс создан и путь к нему возвращен; ресурс удален после выхода из контекста.
/// @pre suffix должен быть строкой, определяющей тип ресурса.
/// @}
void create_temp_file(void);

/// @defgroup remove_empty_directories "remove_empty_directories"
/// @{
/// @brief Рекурсивно удаляет все пустые поддиректории, начиная с указанного пути.
/// @post Все пустые поддиректории удалены, возвращено их количество.
/// @pre root_dir должен быть путем к существующей директории.
/// @}
void remove_empty_directories(void);

/// @defgroup read_dashboard_from_disk "read_dashboard_from_disk"
/// @{
/// @brief Читает бинарное содержимое файла с диска.
/// @post Возвращает байты содержимого и имя файла.
/// @pre file_path должен указывать на существующий файл.
/// @}
void read_dashboard_from_disk(void);

/// @defgroup calculate_crc32 "calculate_crc32"
/// @{
/// @brief Вычисляет контрольную сумму CRC32 для файла.
/// @post Возвращает 8-значную hex-строку CRC32.
/// @pre file_path должен быть объектом Path к существующему файлу.
/// @}
void calculate_crc32(void);

/// @defgroup RetentionPolicy "RetentionPolicy"
/// @{
/// @brief Определяет политику хранения для архивов (ежедневные, еженедельные, ежемесячные).
/// @}
void RetentionPolicy(void);

/// @defgroup archive_exports "archive_exports"
/// @{
/// @brief Управляет архивом экспортированных файлов, применяя политику хранения и дедупликацию.
/// @post Старые или дублирующиеся архивы удалены согласно политике.
/// @pre output_dir должен быть путем к существующей директории.
/// @}
void archive_exports(void);

/// @defgroup apply_retention_policy "apply_retention_policy"
/// @{
/// @brief (Helper) Применяет политику хранения к списку файлов, возвращая те, что нужно сохранить.
/// @post Returns a set of files to keep.
/// @pre files_with_dates is a list of (Path, date) tuples.
/// @}
void apply_retention_policy(void);

/// @defgroup save_and_unpack_dashboard "save_and_unpack_dashboard"
/// @{
/// @brief Сохраняет бинарное содержимое ZIP-архива на диск и опционально распаковывает его.
/// @post ZIP-файл сохранен, и если unpack=True, он распакован в output_dir.
/// @pre zip_content должен быть байтами валидного ZIP-архива.
/// @}
void save_and_unpack_dashboard(void);

/// @defgroup update_yamls "update_yamls"
/// @{
/// @brief Обновляет конфигурации в YAML-файлах, заменяя значения или применяя regex.
/// @post Все YAML файлы в директории обновлены согласно переданным параметрам.
/// @pre path должен быть существующей директорией.
/// @}
void update_yamls(void);

/// @defgroup _update_yaml_file "_update_yaml_file"
/// @{
/// @brief (Helper) Обновляет один YAML файл.
/// @post Файл обновлен согласно переданным конфигурациям или регулярному выражению.
/// @pre file_path должен быть объектом Path к существующему YAML файлу.
/// @}
void _update_yaml_file(void);

/// @defgroup replacer "replacer"
/// @{
/// @brief Функция замены, сохраняющая кавычки если они были.
/// @post Возвращает строку с новым значением, сохраняя префикс и кавычки.
/// @pre match должен быть объектом совпадения регулярного выражения.
/// @}
void replacer(void);

/// @defgroup create_dashboard_export "create_dashboard_export"
/// @{
/// @brief Создает ZIP-архив из указанных исходных путей.
/// @post ZIP-архив создан по пути zip_path.
/// @pre source_paths должен содержать существующие пути.
/// @}
void create_dashboard_export(void);

/// @defgroup sanitize_filename "sanitize_filename"
/// @{
/// @brief Очищает строку от символов, недопустимых в именах файлов.
/// @post Возвращает строку без спецсимволов.
/// @pre filename должен быть строкой.
/// @}
void sanitize_filename(void);

/// @defgroup get_filename_from_headers "get_filename_from_headers"
/// @{
/// @brief Извлекает имя файла из HTTP заголовка 'Content-Disposition'.
/// @post Возвращает имя файла или None, если заголовок отсутствует.
/// @pre headers должен быть словарем заголовков.
/// @}
void get_filename_from_headers(void);

/// @defgroup consolidate_archive_folders "consolidate_archive_folders"
/// @{
/// @brief Консолидирует директории архивов на основе общего слага в имени.
/// @post Директории с одинаковым префиксом объединены в одну.
/// @pre root_directory должен быть объектом Path к существующей директории.
/// @}
void consolidate_archive_folders(void);

/// @defgroup FuzzyMatching "FuzzyMatching"
/// @{
/// @brief Provides utility functions for fuzzy matching database names.
/// @invariant Confidence scores are returned as floats between 0.0 and 1.0.
/// @}
void FuzzyMatching(void);

/// @defgroup suggest_mappings "suggest_mappings"
/// @{
/// @brief Suggests mappings between source and target databases using fuzzy matching.
/// @post Returns a list of suggested mappings with confidence scores.
/// @pre source_databases and target_databases are lists of dictionaries with 'uuid' and 'database_name'.
/// @}
void suggest_mappings(void);

/// @defgroup NetworkModule "NetworkModule"
/// @{
/// @brief Инкапсулирует низкоуровневую HTTP-логику для взаимодействия с Superset API, включая аутентификацию, управление сессией, retry-логику и обработку ошибок.
/// @}
void NetworkModule(void);

/// @defgroup SupersetAPIError "SupersetAPIError"
/// @{
/// @brief Base exception for all Superset API related errors.
/// @}
void SupersetAPIError(void);

/// @defgroup AuthenticationError "AuthenticationError"
/// @{
/// @brief Exception raised when authentication fails.
/// @}
void AuthenticationError(void);

/// @defgroup PermissionDeniedError "PermissionDeniedError"
/// @{
/// @brief Exception raised when access is denied.
/// @}
void PermissionDeniedError(void);

/// @defgroup DashboardNotFoundError "DashboardNotFoundError"
/// @{
/// @brief Exception raised when a dashboard cannot be found.
/// @}
void DashboardNotFoundError(void);

/// @defgroup NetworkError "NetworkError"
/// @{
/// @brief Exception raised when a network level error occurs.
/// @}
void NetworkError(void);

/// @defgroup NetworkError___init__ "NetworkError.__init__"
/// @{
/// @brief Initializes the network error.
/// @post NetworkError is initialized.
/// @pre message is a string.
/// @}
void NetworkError___init__(void);

/// @defgroup SupersetAuthCache "SupersetAuthCache"
/// @{
/// @brief Process-local cache for Superset access/csrf tokens keyed by environment credentials.
/// @post Cached entries expire automatically by TTL and can be reused across requests.
/// @pre base_url and username are stable strings.
/// @}
void SupersetAuthCache(void);

/// @defgroup SupersetAuthCache_get "SupersetAuthCache.get"
/// @{
/// @}
void SupersetAuthCache_get(void);

/// @defgroup SupersetAuthCache_set "SupersetAuthCache.set"
/// @{
/// @}
void SupersetAuthCache_set(void);

/// @defgroup APIClient "APIClient"
/// @{
/// @brief Synchronous Superset API client with process-local auth token caching.
/// @}
void APIClient(void);

/// @defgroup APIClient___init__ "APIClient.__init__"
/// @{
/// @brief Инициализирует API клиент с конфигурацией, сессией и логгером.
/// @param timeout (int) - Таймаут запросов.
/// @post APIClient instance is initialized with a session.
/// @pre config must contain 'base_url' and 'auth'.
/// @}
void APIClient___init__(void);

/// @defgroup _init_session "_init_session"
/// @{
/// @brief Создает и настраивает `requests.Session` с retry-логикой.
/// @post Returns a configured requests.Session instance.
/// @pre self.request_settings must be initialized.
/// @return requests.Session - Настроенная сессия.
/// @}
void _init_session(void);

/// @defgroup _normalize_base_url "_normalize_base_url"
/// @{
/// @brief Normalize Superset environment URL to base host/path without trailing slash and /api/v1 suffix.
/// @}
void _normalize_base_url(void);

/// @defgroup _build_api_url "_build_api_url"
/// @{
/// @brief Build absolute Superset API URL for endpoint using canonical /api/v1 base.
/// @post Returns full URL without accidental duplicate slashes.
/// @pre endpoint is relative path or absolute URL.
/// @return str
/// @}
void _build_api_url(void);

/// @defgroup APIClient_authenticate "APIClient.authenticate"
/// @{
/// @brief Выполняет аутентификацию в Superset API и получает access и CSRF токены.
/// @post `self._tokens` заполнен, `self._authenticated` установлен в `True`.
/// @pre self.auth and self.base_url must be valid.
/// @return Dict[str, str] - Словарь с токенами.
/// @}
void APIClient_authenticate(void);

/// @defgroup headers "headers"
/// @{
/// @brief Возвращает HTTP-заголовки для аутентифицированных запросов.
/// @post Returns headers including auth tokens.
/// @pre APIClient is initialized and authenticated or can be authenticated.
/// @}
void headers(void);

/// @defgroup request "request"
/// @{
/// @brief Выполняет универсальный HTTP-запрос к API.
/// @param raw_response (bool) - Возвращать ли сырой ответ.
/// @post Returns response content or raw Response object.
/// @pre method and endpoint must be strings.
/// @return `requests.Response` если `raw_response=True`, иначе `dict`.
/// @}
void request(void);

/// @defgroup _handle_http_error "_handle_http_error"
/// @{
/// @brief (Helper) Преобразует HTTP ошибки в кастомные исключения.
/// @param endpoint (str) - Эндпоинт.
/// @post Raises a specific SupersetAPIError or subclass.
/// @pre e must be a valid HTTPError with a response.
/// @}
void _handle_http_error(void);

/// @defgroup _is_dashboard_endpoint "_is_dashboard_endpoint"
/// @{
/// @brief Determine whether an API endpoint represents a dashboard resource for 404 translation.
/// @post Returns true only for dashboard-specific endpoints.
/// @pre endpoint may be relative or absolute.
/// @}
void _is_dashboard_endpoint(void);

/// @defgroup _handle_network_error "_handle_network_error"
/// @{
/// @brief (Helper) Преобразует сетевые ошибки в `NetworkError`.
/// @param url (str) - URL.
/// @post Raises a NetworkError.
/// @pre e must be a RequestException.
/// @}
void _handle_network_error(void);

/// @defgroup upload_file "upload_file"
/// @{
/// @brief Загружает файл на сервер через multipart/form-data.
/// @param timeout (Optional[int]) - Таймаут.
/// @post File is uploaded and response returned.
/// @pre file_info must contain 'file_obj' and 'file_name'.
/// @return Ответ API в виде словаря.
/// @}
void upload_file(void);

/// @defgroup _perform_upload "_perform_upload"
/// @{
/// @brief (Helper) Выполняет POST запрос с файлом.
/// @param timeout (Optional[int]) - Таймаут.
/// @post POST request is performed and JSON response returned.
/// @pre url, files, and headers must be provided.
/// @return Dict - Ответ.
/// @}
void _perform_upload(void);

/// @defgroup fetch_paginated_count "fetch_paginated_count"
/// @{
/// @brief Получает общее количество элементов для пагинации.
/// @param count_field (str) - Поле с количеством.
/// @post Returns total count of items.
/// @pre query_params must be a dictionary.
/// @return int - Количество.
/// @}
void fetch_paginated_count(void);

/// @defgroup fetch_paginated_data "fetch_paginated_data"
/// @{
/// @brief Автоматически собирает данные со всех страниц пагинированного эндпоинта.
/// @param pagination_options (Dict[str, Any]) - Опции пагинации.
/// @post Returns all items across all pages.
/// @pre pagination_options must contain 'base_query', 'results_field'. 'total_count' is optional.
/// @return List[Any] - Список данных.
/// @}
void fetch_paginated_data(void);

/// @defgroup SupersetCompilationAdapter "SupersetCompilationAdapter"
/// @{
/// @brief Interact with Superset preview compilation and SQL Lab execution endpoints using the current approved execution context.
/// @invariant The adapter never fabricates compiled SQL locally; preview truth is delegated to Superset only.
/// @post preview and launch calls return Superset-originated artifacts or explicit errors.
/// @pre effective template params and dataset execution reference are available.
/// @}
void SupersetCompilationAdapter(void);

/// @defgroup SupersetCompilationAdapter_imports "SupersetCompilationAdapter.imports"
/// @{
/// @}
void SupersetCompilationAdapter_imports(void);

/// @defgroup PreviewCompilationPayload "PreviewCompilationPayload"
/// @{
/// @brief Typed preview payload for Superset-side compilation.
/// @}
void PreviewCompilationPayload(void);

/// @defgroup SqlLabLaunchPayload "SqlLabLaunchPayload"
/// @{
/// @brief Typed SQL Lab payload for audited launch handoff.
/// @}
void SqlLabLaunchPayload(void);

/// @defgroup SupersetCompilationAdapter___init__ "SupersetCompilationAdapter.__init__"
/// @{
/// @brief Bind adapter to one Superset environment and client instance.
/// @}
void SupersetCompilationAdapter___init__(void);

/// @defgroup SupersetCompilationAdapter__supports_client_method "SupersetCompilationAdapter._supports_client_method"
/// @{
/// @brief Detect explicitly implemented client capabilities without treating loose mocks as real methods.
/// @}
void SupersetCompilationAdapter__supports_client_method(void);

/// @defgroup SupersetCompilationAdapter_compile_preview "SupersetCompilationAdapter.compile_preview"
/// @{
/// @brief Request Superset-side compiled SQL preview for the current effective inputs.
/// @post returns a ready or failed preview artifact backed only by Superset-originated SQL or diagnostics.
/// @pre dataset_id and effective inputs are available for the current session.
/// @}
void SupersetCompilationAdapter_compile_preview(void);

/// @defgroup SupersetCompilationAdapter_mark_preview_stale "SupersetCompilationAdapter.mark_preview_stale"
/// @{
/// @brief Invalidate previous preview after mapping or value changes.
/// @post preview status becomes stale without fabricating a replacement artifact.
/// @pre preview is a persisted preview artifact or current in-memory snapshot.
/// @}
void SupersetCompilationAdapter_mark_preview_stale(void);

/// @defgroup SupersetCompilationAdapter_create_sql_lab_session "SupersetCompilationAdapter.create_sql_lab_session"
/// @{
/// @brief Create the canonical audited execution session after all launch gates pass.
/// @post returns one canonical SQL Lab session reference from Superset.
/// @pre compiled_sql is Superset-originated and launch gates are already satisfied.
/// @}
void SupersetCompilationAdapter_create_sql_lab_session(void);

/// @defgroup SupersetCompilationAdapter__request_superset_preview "SupersetCompilationAdapter._request_superset_preview"
/// @{
/// @brief Request preview compilation through explicit client support backed by real Superset endpoints only.
/// @post returns one normalized upstream compilation response including the chosen strategy metadata.
/// @pre payload contains a valid dataset identifier and deterministic execution inputs for one preview attempt.
/// @}
void SupersetCompilationAdapter__request_superset_preview(void);

/// @defgroup SupersetCompilationAdapter__request_sql_lab_session "SupersetCompilationAdapter._request_sql_lab_session"
/// @{
/// @brief Probe supported SQL Lab execution surfaces and return the first successful response.
/// @post returns the first successful SQL Lab execution response from Superset.
/// @pre payload carries non-empty Superset-originated SQL and a preview identifier for the current launch.
/// @}
void SupersetCompilationAdapter__request_sql_lab_session(void);

/// @defgroup SupersetCompilationAdapter__normalize_preview_response "SupersetCompilationAdapter._normalize_preview_response"
/// @{
/// @brief Normalize candidate Superset preview responses into one compiled-sql structure.
/// @}
void SupersetCompilationAdapter__normalize_preview_response(void);

/// @defgroup SupersetCompilationAdapter__dump_json "SupersetCompilationAdapter._dump_json"
/// @{
/// @brief Serialize Superset request payload deterministically for network transport.
/// @}
void SupersetCompilationAdapter__dump_json(void);

/// @defgroup SupersetContextExtractorPackage "SupersetContextExtractorPackage"
/// @{
/// @brief Recover dataset and dashboard context from Superset links while preserving explicit partial-recovery markers.
/// @invariant Partial recovery is surfaced explicitly and never misrepresented as fully confirmed context.
/// @post Returns the best available recovered context with explicit provenance and partial-recovery markers when necessary.
/// @pre Superset link or dataset reference must be parseable enough to resolve an environment-scoped target resource.
/// @}
void SupersetContextExtractorPackage(void);

/// @defgroup SupersetContextExtractor "SupersetContextExtractor"
/// @{
/// @brief Parse supported Superset URLs and recover canonical dataset/dashboard references for review-session intake.
/// @post extractor instance is ready to parse links against one Superset environment.
/// @pre constructor receives a configured environment with a usable Superset base URL.
/// @}
void SupersetContextExtractor(void);

/// @defgroup SupersetContextExtractorBase "SupersetContextExtractorBase"
/// @{
/// @brief Base class and helpers for recovering dataset/dashboard context from Superset links with explicit partial-recovery markers.
/// @invariant Partial recovery is surfaced explicitly and never misrepresented as fully confirmed context.
/// @post Returns the best available recovered context with explicit provenance and partial-recovery markers when necessary.
/// @pre Superset link or dataset reference must be parseable enough to resolve an environment-scoped target resource.
/// @}
void SupersetContextExtractorBase(void);

/// @defgroup _base_imports "_base_imports"
/// @{
/// @}
void _base_imports(void);

/// @defgroup SupersetParsedContext "SupersetParsedContext"
/// @{
/// @brief Normalized output of Superset link parsing for session intake and recovery.
/// @}
void SupersetParsedContext(void);

/// @defgroup SupersetContextExtractorBase___init__ "SupersetContextExtractorBase.__init__"
/// @{
/// @brief Bind extractor to one Superset environment and client instance.
/// @}
void SupersetContextExtractorBase___init__(void);

/// @defgroup SupersetContextExtractorBase_build_recovery_summary "SupersetContextExtractorBase.build_recovery_summary"
/// @{
/// @brief Summarize recovered, partial, and unresolved context for session state and UX.
/// @}
void SupersetContextExtractorBase_build_recovery_summary(void);

/// @defgroup SupersetContextExtractorBase__extract_numeric_identifier "SupersetContextExtractorBase._extract_numeric_identifier"
/// @{
/// @brief Extract a numeric identifier from a REST-like Superset URL path.
/// @}
void SupersetContextExtractorBase__extract_numeric_identifier(void);

/// @defgroup SupersetContextExtractorBase__extract_dashboard_reference "SupersetContextExtractorBase._extract_dashboard_reference"
/// @{
/// @brief Extract a dashboard id-or-slug reference from a Superset URL path.
/// @}
void SupersetContextExtractorBase__extract_dashboard_reference(void);

/// @defgroup SupersetContextExtractorBase__extract_dashboard_permalink_key "SupersetContextExtractorBase._extract_dashboard_permalink_key"
/// @{
/// @brief Extract a dashboard permalink key from a Superset URL path.
/// @}
void SupersetContextExtractorBase__extract_dashboard_permalink_key(void);

/// @defgroup SupersetContextExtractorBase__extract_dashboard_id_from_state "SupersetContextExtractorBase._extract_dashboard_id_from_state"
/// @{
/// @brief Extract a dashboard identifier from returned permalink state when present.
/// @}
void SupersetContextExtractorBase__extract_dashboard_id_from_state(void);

/// @defgroup SupersetContextExtractorBase__extract_chart_id_from_state "SupersetContextExtractorBase._extract_chart_id_from_state"
/// @{
/// @brief Extract a chart identifier from returned permalink state when dashboard id is absent.
/// @}
void SupersetContextExtractorBase__extract_chart_id_from_state(void);

/// @defgroup SupersetContextExtractorBase__search_nested_numeric_key "SupersetContextExtractorBase._search_nested_numeric_key"
/// @{
/// @brief Recursively search nested dict/list payloads for the first numeric value under a candidate key set.
/// @}
void SupersetContextExtractorBase__search_nested_numeric_key(void);

/// @defgroup SupersetContextExtractorBase__decode_query_state "SupersetContextExtractorBase._decode_query_state"
/// @{
/// @brief Decode query-string structures used by Superset URL state transport.
/// @}
void SupersetContextExtractorBase__decode_query_state(void);

/// @defgroup SupersetContextFiltersExtractMixin "SupersetContextFiltersExtractMixin"
/// @{
/// @brief Extract normalized imported filters from decoded Superset query state (native_filters, dataMask, native_filter_state, form_data).
/// @}
void SupersetContextFiltersExtractMixin(void);

/// @defgroup _filters_imports "_filters_imports"
/// @{
/// @}
void _filters_imports(void);

/// @defgroup SupersetContextFiltersExtractMixin__extract_imported_filters "SupersetContextFiltersExtractMixin._extract_imported_filters"
/// @{
/// @brief Normalize imported filters from decoded query state without fabricating missing values.
/// @}
void SupersetContextFiltersExtractMixin__extract_imported_filters(void);

/// @defgroup SupersetContextParsingMixin "SupersetContextParsingMixin"
/// @{
/// @brief Parse supported Superset URLs and recover canonical dataset/dashboard references for review-session intake.
/// @}
void SupersetContextParsingMixin(void);

/// @defgroup _parsing_imports "_parsing_imports"
/// @{
/// @}
void _parsing_imports(void);

/// @defgroup SupersetContextParsingMixin_parse_superset_link "SupersetContextParsingMixin.parse_superset_link"
/// @{
/// @brief Extract candidate identifiers and query state from supported Superset URLs.
/// @post returns resolved dataset/dashboard context, preserving explicit partial-recovery state if some identifiers cannot be confirmed.
/// @pre link is a non-empty Superset URL compatible with the configured environment.
/// @}
void SupersetContextParsingMixin_parse_superset_link(void);

/// @defgroup SupersetContextParsingMixin__recover_dataset_binding_from_dashboard "SupersetContextParsingMixin._recover_dataset_binding_from_dashboard"
/// @{
/// @brief Recover a dataset binding from resolved dashboard context while preserving explicit unresolved markers.
/// @}
void SupersetContextParsingMixin__recover_dataset_binding_from_dashboard(void);

/// @defgroup SupersetContextExtractorPII "SupersetContextExtractorPII"
/// @{
/// @brief PII redaction helpers for assistant-facing dataset-review context — mask emails, UUIDs, long digit strings, and mixed identifiers.
/// @}
void SupersetContextExtractorPII(void);

/// @defgroup _pii_imports "_pii_imports"
/// @{
/// @}
void _pii_imports(void);

/// @defgroup mask_pii_value "mask_pii_value"
/// @{
/// @brief Redact likely sensitive identifiers while preserving structural hints for assistant-facing dataset-review context.
/// @}
void mask_pii_value(void);

/// @defgroup sanitize_imported_filter_for_assistant "sanitize_imported_filter_for_assistant"
/// @{
/// @brief Build assistant-safe imported-filter payload with raw-value redaction metadata when sensitive tokens are detected.
/// @}
void sanitize_imported_filter_for_assistant(void);

/// @defgroup _mask_sensitive_text "_mask_sensitive_text"
/// @{
/// @brief Redact likely PII substrings from one string while preserving non-sensitive delimiters and token shape.
/// @}
void _mask_sensitive_text(void);

/// @defgroup SupersetContextRecoveryMixin "SupersetContextRecoveryMixin"
/// @{
/// @brief Recover imported filters from Superset parsed context and dashboard metadata.
/// @}
void SupersetContextRecoveryMixin(void);

/// @defgroup _recovery_imports "_recovery_imports"
/// @{
/// @}
void _recovery_imports(void);

/// @defgroup SupersetContextRecoveryMixin_recover_imported_filters "SupersetContextRecoveryMixin.recover_imported_filters"
/// @{
/// @brief Build imported filter entries from URL state and Superset-side saved context.
/// @post returns explicit recovered and partial filter entries with preserved provenance and confirmation requirements.
/// @pre parsed_context comes from a successful Superset link parse for one environment.
/// @}
void SupersetContextRecoveryMixin_recover_imported_filters(void);

/// @defgroup SupersetContextRecoveryMixin__normalize_imported_filter_payload "SupersetContextRecoveryMixin._normalize_imported_filter_payload"
/// @{
/// @brief Normalize one imported-filter payload with explicit provenance and confirmation state.
/// @}
void SupersetContextRecoveryMixin__normalize_imported_filter_payload(void);

/// @defgroup SupersetContextTemplatesMixin "SupersetContextTemplatesMixin"
/// @{
/// @brief Deterministically detect runtime variables and Jinja references from dataset query-bearing fields without execution.
/// @}
void SupersetContextTemplatesMixin(void);

/// @defgroup _templates_imports "_templates_imports"
/// @{
/// @}
void _templates_imports(void);

/// @defgroup SupersetContextTemplatesMixin_discover_template_variables "SupersetContextTemplatesMixin.discover_template_variables"
/// @{
/// @brief Detect runtime variables and Jinja references from dataset query-bearing fields.
/// @post returns deduplicated explicit variable records without executing Jinja or fabricating runtime values.
/// @pre dataset_payload is a Superset dataset-detail style payload with query-bearing fields when available.
/// @}
void SupersetContextTemplatesMixin_discover_template_variables(void);

/// @defgroup SupersetContextTemplatesMixin__collect_query_bearing_expressions "SupersetContextTemplatesMixin._collect_query_bearing_expressions"
/// @{
/// @brief Collect SQL and expression-bearing dataset fields for deterministic template-variable discovery.
/// @}
void SupersetContextTemplatesMixin__collect_query_bearing_expressions(void);

/// @defgroup SupersetContextTemplatesMixin__append_template_variable "SupersetContextTemplatesMixin._append_template_variable"
/// @{
/// @brief Append one deduplicated template-variable descriptor.
/// @}
void SupersetContextTemplatesMixin__append_template_variable(void);

/// @defgroup SupersetContextTemplatesMixin__extract_primary_jinja_identifier "SupersetContextTemplatesMixin._extract_primary_jinja_identifier"
/// @{
/// @brief Extract a deterministic primary identifier from a Jinja expression without executing it.
/// @}
void SupersetContextTemplatesMixin__extract_primary_jinja_identifier(void);

/// @defgroup SupersetContextTemplatesMixin__normalize_default_literal "SupersetContextTemplatesMixin._normalize_default_literal"
/// @{
/// @brief Normalize literal default fragments from template helper calls into JSON-safe values.
/// @}
void SupersetContextTemplatesMixin__normalize_default_literal(void);

/// @defgroup WsLogHandlerModule "WsLogHandlerModule"
/// @{
/// @brief WebSocket log handler module providing LogEntry DTO and WebSocketLogHandler for buffered log streaming.
/// @}
void WsLogHandlerModule(void);

/// @defgroup WebSocketLogHandler "WebSocketLogHandler"
/// @{
/// @brief Custom logging handler that captures log records into a fixed-capacity buffer for WebSocket streaming.
/// @}
void WebSocketLogHandler(void);

/// @defgroup WebSocketLogHandler___init__ "WebSocketLogHandler.__init__"
/// @{
/// @}
void WebSocketLogHandler___init__(void);

/// @defgroup WebSocketLogHandler_emit "WebSocketLogHandler.emit"
/// @{
/// @brief Captures a log record, formats it, and stores it in the buffer as a LogEntry.
/// @}
void WebSocketLogHandler_emit(void);

/// @defgroup WebSocketLogHandler_get_recent_logs "WebSocketLogHandler.get_recent_logs"
/// @{
/// @brief Returns a list of recent log entries from the buffer.
/// @}
void WebSocketLogHandler_get_recent_logs(void);

/// @defgroup AppDependencies "AppDependencies"
/// @{
/// @brief Provides shared instances to app and routers.
/// @}
void AppDependencies(void);

/// @defgroup get_config_manager "get_config_manager"
/// @{
/// @brief Dependency injector for ConfigManager.
/// @post Returns shared ConfigManager instance.
/// @pre Global config_manager must be initialized.
/// @}
void get_config_manager(void);

/// @defgroup get_plugin_loader "get_plugin_loader"
/// @{
/// @brief Dependency injector for PluginLoader.
/// @post Returns shared PluginLoader instance.
/// @pre Global plugin_loader must be initialized.
/// @}
void get_plugin_loader(void);

/// @defgroup get_task_manager "get_task_manager"
/// @{
/// @brief Dependency injector for TaskManager.
/// @post Returns shared TaskManager instance.
/// @pre Global task_manager must be initialized.
/// @}
void get_task_manager(void);

/// @defgroup get_scheduler_service "get_scheduler_service"
/// @{
/// @brief Dependency injector for SchedulerService.
/// @post Returns shared SchedulerService instance.
/// @pre Global scheduler_service must be initialized.
/// @}
void get_scheduler_service(void);

/// @defgroup get_resource_service "get_resource_service"
/// @{
/// @brief Dependency injector for ResourceService.
/// @post Returns shared ResourceService instance.
/// @pre Global resource_service must be initialized.
/// @}
void get_resource_service(void);

/// @defgroup get_mapping_service "get_mapping_service"
/// @{
/// @brief Dependency injector for MappingService.
/// @post Returns new MappingService instance.
/// @pre Global config_manager must be initialized.
/// @}
void get_mapping_service(void);

/// @defgroup get_clean_release_repository "get_clean_release_repository"
/// @{
/// @brief Legacy compatibility shim for CleanReleaseRepository.
/// @post Returns a shared CleanReleaseRepository instance.
/// @}
void get_clean_release_repository(void);

/// @defgroup get_clean_release_facade "get_clean_release_facade"
/// @{
/// @brief Dependency injector for CleanReleaseFacade.
/// @post Returns a facade instance with a fresh DB session.
/// @}
void get_clean_release_facade(void);

/// @defgroup APIKeyPrincipal "APIKeyPrincipal"
/// @{
/// @brief Dataclass representing an authenticated API key principal for service-to-service auth.
/// @}
void APIKeyPrincipal(void);

/// @defgroup require_api_key_or_jwt "require_api_key_or_jwt"
/// @{
/// @brief Factory: creates a dependency that accepts either a valid API key (with permission check)
/// @}
void require_api_key_or_jwt(void);

/// @defgroup check_api_key_environment_scope "check_api_key_environment_scope"
/// @{
/// @brief Check the request's API key environment scope against a target env_id. Raises 400 if mismatch.
/// @}
void check_api_key_environment_scope(void);

/// @defgroup get_api_key_principal "get_api_key_principal"
/// @{
/// @brief FastAPI dependency that reads X-API-Key header and returns APIKeyPrincipal or None.
/// @post If valid key: returns APIKeyPrincipal; if no header: returns None; if invalid: raises 401.
/// @pre X-API-Key header may be present in the request.
/// @}
void get_api_key_principal(void);

/// @defgroup oauth2_scheme "oauth2_scheme"
/// @{
/// @brief OAuth2 password bearer scheme for token extraction (raises 401 on missing token).
/// @}
void oauth2_scheme(void);

/// @defgroup oauth2_scheme_optional "oauth2_scheme_optional"
/// @{
/// @brief Optional OAuth2 scheme — returns None instead of raising 401 when no token.
/// @}
void oauth2_scheme_optional(void);

/// @defgroup get_current_user "get_current_user"
/// @{
/// @brief Dependency for retrieving currently authenticated user from a JWT.
/// @post Returns User object if token is valid.
/// @pre JWT token provided in Authorization header.
/// @}
void get_current_user(void);

/// @defgroup has_permission "has_permission"
/// @{
/// @brief Dependency for checking if the current user has a specific permission.
/// @post Returns True if user has permission.
/// @pre User is authenticated.
/// @}
void has_permission(void);

/// @defgroup ModelsPackage "ModelsPackage"
/// @{
/// @brief Domain model package root.
/// @}
void ModelsPackage(void);

/// @defgroup TestCleanReleaseModels "TestCleanReleaseModels"
/// @{
/// @brief Contract testing for Clean Release models
/// @}
void TestCleanReleaseModels(void);

/// @defgroup test_release_candidate_valid "test_release_candidate_valid"
/// @{
/// @brief Verify that a valid release candidate can be instantiated.
/// @}
void test_release_candidate_valid(void);

/// @defgroup test_release_candidate_empty_id "test_release_candidate_empty_id"
/// @{
/// @brief Verify that a release candidate with an empty ID is rejected.
/// @}
void test_release_candidate_empty_id(void);

/// @defgroup test_enterprise_policy_valid "test_enterprise_policy_valid"
/// @{
/// @brief Verify that a valid enterprise policy is accepted.
/// @}
void test_enterprise_policy_valid(void);

/// @defgroup test_enterprise_policy_missing_prohibited "test_enterprise_policy_missing_prohibited"
/// @{
/// @brief Verify that an enterprise policy without prohibited categories is rejected.
/// @}
void test_enterprise_policy_missing_prohibited(void);

/// @defgroup test_enterprise_policy_external_allowed "test_enterprise_policy_external_allowed"
/// @{
/// @brief Verify that an enterprise policy allowing external sources is rejected.
/// @}
void test_enterprise_policy_external_allowed(void);

/// @defgroup test_manifest_count_mismatch "test_manifest_count_mismatch"
/// @{
/// @brief Verify that a manifest with count mismatches is rejected.
/// @}
void test_manifest_count_mismatch(void);

/// @defgroup test_compliant_run_validation "test_compliant_run_validation"
/// @{
/// @brief Verify compliant run validation logic and mandatory stage checks.
/// @}
void test_compliant_run_validation(void);

/// @defgroup test_report_validation "test_report_validation"
/// @{
/// @brief Verify compliance report validation based on status and violation counts.
/// @}
void test_report_validation(void);

/// @defgroup test_models "test_models"
/// @{
/// @brief Unit tests for data models
/// @}
void test_models(void);

/// @defgroup test_environment_model "test_environment_model"
/// @{
/// @brief Tests that Environment model correctly stores values.
/// @post Values are verified.
/// @pre Environment class is available.
/// @}
void test_environment_model(void);

/// @defgroup test_report_models "test_report_models"
/// @{
/// @brief Unit tests for report Pydantic models and their validators
/// @}
void test_report_models(void);

/// @defgroup APIKeyModel "APIKeyModel"
/// @{
/// @brief SQLAlchemy model for API Key authentication — stores SHA-256 hash only, raw key shown once at creation.
/// @invariant Raw key is NEVER stored — shown once at creation and discarded.
/// @}
void APIKeyModel(void);

/// @defgroup APIKey "APIKey"
/// @{
/// @brief Stores API key metadata and SHA-256 hash for service-to-service authentication.
/// @}
void APIKey(void);

/// @defgroup AssistantModels "AssistantModels"
/// @{
/// @brief SQLAlchemy models for assistant audit trail and confirmation tokens.
/// @invariant Assistant records preserve immutable ids and creation timestamps.
/// @}
void AssistantModels(void);

/// @defgroup AssistantAuditRecord "AssistantAuditRecord"
/// @{
/// @brief Store audit decisions and outcomes produced by assistant command handling.
/// @post Audit payload remains available for compliance and debugging.
/// @pre user_id must identify the actor for every record.
/// @}
void AssistantAuditRecord(void);

/// @defgroup AssistantMessageRecord "AssistantMessageRecord"
/// @{
/// @brief Persist chat history entries for assistant conversations.
/// @post Message row can be queried in chronological order.
/// @pre user_id, conversation_id, role and text must be present.
/// @}
void AssistantMessageRecord(void);

/// @defgroup AssistantConfirmationRecord "AssistantConfirmationRecord"
/// @{
/// @brief Persist risky operation confirmation tokens with lifecycle state.
/// @post State transitions can be tracked and audited.
/// @pre intent/dispatch and expiry timestamp must be provided.
/// @}
void AssistantConfirmationRecord(void);

/// @defgroup AuthModels "AuthModels"
/// @{
/// @brief SQLAlchemy models for multi-user authentication and authorization.
/// @invariant Usernames and emails must be unique.
/// @post Auth ORM models registered with unique constraints
/// @pre Database engine initialized
/// @}
void AuthModels(void);

/// @defgroup generate_uuid "generate_uuid"
/// @{
/// @brief Generates a unique UUID string.
/// @post Returns a string representation of a new UUID.
/// @}
void generate_uuid(void);

/// @defgroup user_roles "user_roles"
/// @{
/// @brief Association table for many-to-many relationship between Users and Roles.
/// @}
void user_roles(void);

/// @defgroup role_permissions "role_permissions"
/// @{
/// @brief Association table for many-to-many relationship between Roles and Permissions.
/// @}
void role_permissions(void);

/// @defgroup Role "Role"
/// @{
/// @brief Represents a collection of permissions.
/// @}
void Role(void);

/// @defgroup Permission "Permission"
/// @{
/// @brief Represents a specific capability within the system.
/// @}
void Permission(void);

/// @defgroup ADGroupMapping "ADGroupMapping"
/// @{
/// @brief Maps an Active Directory group to a local System Role.
/// @}
void ADGroupMapping(void);

/// @defgroup CleanReleaseModels "CleanReleaseModels"
/// @{
/// @brief Define canonical clean release domain entities and lifecycle guards.
/// @invariant Immutable snapshots are never mutated; forbidden lifecycle transitions are rejected.
/// @post Provides SQLAlchemy and dataclass definitions for governance domain.
/// @pre Base mapping model and release enums are available.
/// @}
void CleanReleaseModels(void);

/// @defgroup ExecutionMode "ExecutionMode"
/// @{
/// @brief Backward-compatible execution mode enum for legacy TUI/orchestrator tests.
/// @}
void ExecutionMode(void);

/// @defgroup CheckFinalStatus "CheckFinalStatus"
/// @{
/// @brief Backward-compatible final status enum for legacy TUI/orchestrator tests.
/// @}
void CheckFinalStatus(void);

/// @defgroup CheckStageName "CheckStageName"
/// @{
/// @brief Backward-compatible stage name enum for legacy TUI/orchestrator tests.
/// @}
void CheckStageName(void);

/// @defgroup CheckStageStatus "CheckStageStatus"
/// @{
/// @brief Backward-compatible stage status enum for legacy TUI/orchestrator tests.
/// @}
void CheckStageStatus(void);

/// @defgroup CheckStageResult "CheckStageResult"
/// @{
/// @brief Backward-compatible stage result container for legacy TUI/orchestrator tests.
/// @}
void CheckStageResult(void);

/// @defgroup ProfileType "ProfileType"
/// @{
/// @brief Backward-compatible profile enum for legacy TUI bootstrap logic.
/// @}
void ProfileType(void);

/// @defgroup RegistryStatus "RegistryStatus"
/// @{
/// @brief Backward-compatible registry status enum for legacy TUI bootstrap logic.
/// @}
void RegistryStatus(void);

/// @defgroup ReleaseCandidateStatus "ReleaseCandidateStatus"
/// @{
/// @brief Backward-compatible release candidate status enum for legacy TUI.
/// @}
void ReleaseCandidateStatus(void);

/// @defgroup ResourceSourceEntry "ResourceSourceEntry"
/// @{
/// @brief Backward-compatible source entry model for legacy TUI bootstrap logic.
/// @}
void ResourceSourceEntry(void);

/// @defgroup ResourceSourceRegistry "ResourceSourceRegistry"
/// @{
/// @brief Backward-compatible source registry model for legacy TUI bootstrap logic.
/// @}
void ResourceSourceRegistry(void);

/// @defgroup CleanProfilePolicy "CleanProfilePolicy"
/// @{
/// @brief Backward-compatible policy model for legacy TUI bootstrap logic.
/// @}
void CleanProfilePolicy(void);

/// @defgroup ComplianceCheckRun "ComplianceCheckRun"
/// @{
/// @brief Backward-compatible run model for legacy TUI typing/import compatibility.
/// @}
void ComplianceCheckRun(void);

/// @defgroup ReleaseCandidate "ReleaseCandidate"
/// @{
/// @brief Represents the release unit being prepared and governed.
/// @post status advances only through legal transitions.
/// @pre id, version, source_snapshot_ref are non-empty.
/// @}
void ReleaseCandidate(void);

/// @defgroup CandidateArtifact "CandidateArtifact"
/// @{
/// @brief Represents one artifact associated with a release candidate.
/// @}
void CandidateArtifact(void);

/// @defgroup ManifestItem "ManifestItem"
/// @{
/// @}
void ManifestItem(void);

/// @defgroup ManifestSummary "ManifestSummary"
/// @{
/// @}
void ManifestSummary(void);

/// @defgroup DistributionManifest "DistributionManifest"
/// @{
/// @brief Immutable snapshot of the candidate payload.
/// @invariant Immutable after creation.
/// @}
void DistributionManifest(void);

/// @defgroup SourceRegistrySnapshot "SourceRegistrySnapshot"
/// @{
/// @brief Immutable registry snapshot for allowed sources.
/// @}
void SourceRegistrySnapshot(void);

/// @defgroup CleanPolicySnapshot "CleanPolicySnapshot"
/// @{
/// @brief Immutable policy snapshot used to evaluate a run.
/// @}
void CleanPolicySnapshot(void);

/// @defgroup ComplianceRun "ComplianceRun"
/// @{
/// @brief Operational record for one compliance execution.
/// @}
void ComplianceRun(void);

/// @defgroup ComplianceStageRun "ComplianceStageRun"
/// @{
/// @brief Stage-level execution record inside a run.
/// @}
void ComplianceStageRun(void);

/// @defgroup ViolationSeverity "ViolationSeverity"
/// @{
/// @brief Backward-compatible violation severity enum for legacy clean-release tests.
/// @}
void ViolationSeverity(void);

/// @defgroup ViolationCategory "ViolationCategory"
/// @{
/// @brief Backward-compatible violation category enum for legacy clean-release tests.
/// @}
void ViolationCategory(void);

/// @defgroup ComplianceViolation "ComplianceViolation"
/// @{
/// @brief Violation produced by a stage.
/// @}
void ComplianceViolation(void);

/// @defgroup ComplianceReport "ComplianceReport"
/// @{
/// @brief Immutable result derived from a completed run.
/// @invariant Immutable after creation.
/// @}
void ComplianceReport(void);

/// @defgroup ApprovalDecision "ApprovalDecision"
/// @{
/// @brief Approval or rejection bound to a candidate and report.
/// @}
void ApprovalDecision(void);

/// @defgroup PublicationRecord "PublicationRecord"
/// @{
/// @brief Publication or revocation record.
/// @}
void PublicationRecord(void);

/// @defgroup CleanReleaseAuditLog "CleanReleaseAuditLog"
/// @{
/// @brief Represents a persistent audit log entry for clean release actions.
/// @}
void CleanReleaseAuditLog(void);

/// @defgroup AppConfigRecord "AppConfigRecord"
/// @{
/// @brief Stores persisted application configuration as a single authoritative record model.
/// @post ORM table 'app_configurations' exposes id, payload, and updated_at fields with declared nullability/default semantics.
/// @pre SQLAlchemy declarative Base is initialized and table metadata registration is active.
/// @}
void AppConfigRecord(void);

/// @defgroup NotificationConfig "NotificationConfig"
/// @{
/// @brief Stores persisted provider-level notification configuration and encrypted credentials metadata.
/// @post ORM table 'notification_configs' exposes id, type, name, credentials, is_active, created_at, updated_at fields with declared constraints/defaults.
/// @pre SQLAlchemy declarative Base is initialized and uuid generation is available at instance creation time.
/// @}
void NotificationConfig(void);

/// @defgroup DashboardModels "DashboardModels"
/// @{
/// @brief Defines data models for dashboard metadata and selection.
/// @}
void DashboardModels(void);

/// @defgroup DashboardMetadata "DashboardMetadata"
/// @{
/// @brief Represents a dashboard available for migration.
/// @}
void DashboardMetadata(void);

/// @defgroup DashboardSelection "DashboardSelection"
/// @{
/// @brief Represents the user's selection of dashboards to migrate.
/// @}
void DashboardSelection(void);

/// @defgroup DatasetReviewModels "DatasetReviewModels"
/// @{
/// @brief Thin facade re-exporting all dataset review domain models from the decomposed sub-package.
/// @invariant All public model classes and enums remain importable from `src.models.dataset_review` without changes.
/// @}
void DatasetReviewModels(void);

/// @defgroup DatasetReviewClarificationModels "DatasetReviewClarificationModels"
/// @{
/// @brief Clarification session, question, option, and answer models for guided review flow.
/// @invariant Only one active clarification question may exist at a time per session.
/// @post Clarification ORM models registered
/// @pre Database engine initialized
/// @}
void DatasetReviewClarificationModels(void);

/// @defgroup ClarificationSession "ClarificationSession"
/// @{
/// @brief One clarification session aggregate owning questions and tracking resolution progress.
/// @}
void ClarificationSession(void);

/// @defgroup ClarificationQuestion "ClarificationQuestion"
/// @{
/// @brief One clarification question with priority ordering, options, and state machine.
/// @}
void ClarificationQuestion(void);

/// @defgroup ClarificationOption "ClarificationOption"
/// @{
/// @brief One selectable option for a clarification question with recommendation flag.
/// @}
void ClarificationOption(void);

/// @defgroup ClarificationAnswer "ClarificationAnswer"
/// @{
/// @brief One persisted clarification answer with impact summary and feedback tracking.
/// @}
void ClarificationAnswer(void);

/// @defgroup DatasetReviewEnums "DatasetReviewEnums"
/// @{
/// @brief All enumeration types for the dataset review domain, grouped for stable cross-module reuse.
/// @invariant Enum values are string-based for JSON serialization compatibility.
/// @}
void DatasetReviewEnums(void);

/// @defgroup SessionStatus "SessionStatus"
/// @{
/// @brief Lifecycle status of a dataset review session.
/// @}
void SessionStatus(void);

/// @defgroup SessionPhase "SessionPhase"
/// @{
/// @brief Ordered phase progression for dataset review orchestration.
/// @}
void SessionPhase(void);

/// @defgroup ReadinessState "ReadinessState"
/// @{
/// @brief Granular readiness indicator driving the recommended-action UX flow.
/// @}
void ReadinessState(void);

/// @defgroup RecommendedAction "RecommendedAction"
/// @{
/// @brief Next-action guidance derived from the current readiness state.
/// @}
void RecommendedAction(void);

/// @defgroup SessionCollaboratorRole "SessionCollaboratorRole"
/// @{
/// @brief RBAC role for session collaborators.
/// @}
void SessionCollaboratorRole(void);

/// @defgroup BusinessSummarySource "BusinessSummarySource"
/// @{
/// @brief Provenance of the dataset business summary text.
/// @}
void BusinessSummarySource(void);

/// @defgroup ConfidenceState "ConfidenceState"
/// @{
/// @brief Confidence level for dataset profile completeness.
/// @}
void ConfidenceState(void);

/// @defgroup FindingArea "FindingArea"
/// @{
/// @brief Domain area classification for validation findings.
/// @}
void FindingArea(void);

/// @defgroup FindingSeverity "FindingSeverity"
/// @{
/// @brief Severity classification for validation findings.
/// @}
void FindingSeverity(void);

/// @defgroup ResolutionState "ResolutionState"
/// @{
/// @brief Resolution status for validation findings and clarification items.
/// @}
void ResolutionState(void);

/// @defgroup SemanticSourceType "SemanticSourceType"
/// @{
/// @brief Classification of semantic enrichment source origins.
/// @}
void SemanticSourceType(void);

/// @defgroup TrustLevel "TrustLevel"
/// @{
/// @brief Trust classification for semantic source reliability.
/// @}
void TrustLevel(void);

/// @defgroup SemanticSourceStatus "SemanticSourceStatus"
/// @{
/// @brief Lifecycle status for semantic source application.
/// @}
void SemanticSourceStatus(void);

/// @defgroup FieldKind "FieldKind"
/// @{
/// @brief Kind classification for semantic field entries.
/// @}
void FieldKind(void);

/// @defgroup FieldProvenance "FieldProvenance"
/// @{
/// @brief Provenance tracking for semantic field value origin.
/// @}
void FieldProvenance(void);

/// @defgroup CandidateMatchType "CandidateMatchType"
/// @{
/// @brief Match type classification for semantic candidates.
/// @}
void CandidateMatchType(void);

/// @defgroup CandidateStatus "CandidateStatus"
/// @{
/// @brief Lifecycle status for semantic candidate proposals.
/// @}
void CandidateStatus(void);

/// @defgroup FilterSource "FilterSource"
/// @{
/// @brief Origin classification for imported filters.
/// @}
void FilterSource(void);

/// @defgroup FilterConfidenceState "FilterConfidenceState"
/// @{
/// @brief Confidence classification for imported filter values.
/// @}
void FilterConfidenceState(void);

/// @defgroup FilterRecoveryStatus "FilterRecoveryStatus"
/// @{
/// @brief Recovery quality status for imported filters.
/// @}
void FilterRecoveryStatus(void);

/// @defgroup VariableKind "VariableKind"
/// @{
/// @brief Kind classification for template variables.
/// @}
void VariableKind(void);

/// @defgroup MappingStatus "MappingStatus"
/// @{
/// @brief Lifecycle status for template variable mapping.
/// @}
void MappingStatus(void);

/// @defgroup MappingMethod "MappingMethod"
/// @{
/// @brief Method classification for execution mapping creation.
/// @}
void MappingMethod(void);

/// @defgroup MappingWarningLevel "MappingWarningLevel"
/// @{
/// @brief Warning severity for execution mapping quality indicators.
/// @}
void MappingWarningLevel(void);

/// @defgroup ApprovalState "ApprovalState"
/// @{
/// @brief Approval lifecycle for execution mapping gate checks.
/// @}
void ApprovalState(void);

/// @defgroup ClarificationStatus "ClarificationStatus"
/// @{
/// @brief Lifecycle status for clarification sessions.
/// @}
void ClarificationStatus(void);

/// @defgroup QuestionState "QuestionState"
/// @{
/// @brief State machine for individual clarification questions.
/// @}
void QuestionState(void);

/// @defgroup AnswerKind "AnswerKind"
/// @{
/// @brief Classification of clarification answer types.
/// @}
void AnswerKind(void);

/// @defgroup PreviewStatus "PreviewStatus"
/// @{
/// @brief Lifecycle status for compiled SQL previews.
/// @}
void PreviewStatus(void);

/// @defgroup LaunchStatus "LaunchStatus"
/// @{
/// @brief Outcome status for dataset launch handoff.
/// @}
void LaunchStatus(void);

/// @defgroup ArtifactType "ArtifactType"
/// @{
/// @brief Type classification for export artifacts.
/// @}
void ArtifactType(void);

/// @defgroup ArtifactFormat "ArtifactFormat"
/// @{
/// @brief Format classification for export artifact output.
/// @}
void ArtifactFormat(void);

/// @defgroup DatasetReviewExecutionModels "DatasetReviewExecutionModels"
/// @{
/// @brief Compiled preview, run context, session event, and export artifact models for execution and audit.
/// @}
void DatasetReviewExecutionModels(void);

/// @defgroup CompiledPreview "CompiledPreview"
/// @{
/// @brief One compiled SQL preview snapshot with fingerprint for staleness detection.
/// @}
void CompiledPreview(void);

/// @defgroup DatasetRunContext "DatasetRunContext"
/// @{
/// @brief Immutable launch audit snapshot capturing effective filters, template params, and approval state at launch time.
/// @}
void DatasetRunContext(void);

/// @defgroup SessionEvent "SessionEvent"
/// @{
/// @brief One persisted audit event for dataset review session mutations.
/// @}
void SessionEvent(void);

/// @defgroup ExportArtifact "ExportArtifact"
/// @{
/// @brief One persisted export artifact reference for documentation and validation outputs.
/// @}
void ExportArtifact(void);

/// @defgroup DatasetReviewFilterModels "DatasetReviewFilterModels"
/// @{
/// @brief Imported filter and template variable models for Superset context recovery and execution mapping.
/// @}
void DatasetReviewFilterModels(void);

/// @defgroup ImportedFilter "ImportedFilter"
/// @{
/// @brief Recovered Superset filter with confidence and recovery status tracking.
/// @}
void ImportedFilter(void);

/// @defgroup TemplateVariable "TemplateVariable"
/// @{
/// @brief Discovered template variable from dataset SQL with mapping status tracking.
/// @}
void TemplateVariable(void);

/// @defgroup DatasetReviewFindingModels "DatasetReviewFindingModels"
/// @{
/// @brief Validation finding model for tracking blocking, warning, and informational issues during review.
/// @}
void DatasetReviewFindingModels(void);

/// @defgroup ValidationFinding "ValidationFinding"
/// @{
/// @brief Structured finding record for dataset review validation issues with resolution tracking.
/// @}
void ValidationFinding(void);

/// @defgroup DatasetReviewMappingModels "DatasetReviewMappingModels"
/// @{
/// @brief Execution mapping model linking imported filters to template variables with approval gates.
/// @}
void DatasetReviewMappingModels(void);

/// @defgroup ExecutionMapping "ExecutionMapping"
/// @{
/// @brief One filter-to-variable mapping with approval gate, effective value, and transformation metadata.
/// @invariant Explicit approval is required before launch when requires_explicit_approval is true.
/// @}
void ExecutionMapping(void);

/// @defgroup DatasetReviewProfileModels "DatasetReviewProfileModels"
/// @{
/// @brief Dataset profile model capturing business summary, confidence, and completeness metadata.
/// @}
void DatasetReviewProfileModels(void);

/// @defgroup DatasetProfile "DatasetProfile"
/// @{
/// @brief One-to-one profile snapshot for a dataset review session, tracking business summary provenance and completeness.
/// @}
void DatasetProfile(void);

/// @defgroup DatasetReviewSemanticModels "DatasetReviewSemanticModels"
/// @{
/// @brief Semantic source, field entry, and candidate models for dictionary-driven semantic enrichment.
/// @invariant Manual overrides are never silently replaced by imported, inferred, or AI-generated values.
/// @post Semantic ORM models registered with override protection
/// @pre Database engine initialized
/// @}
void DatasetReviewSemanticModels(void);

/// @defgroup SemanticSource "SemanticSource"
/// @{
/// @brief Registered semantic enrichment source with trust level and application status.
/// @}
void SemanticSource(void);

/// @defgroup SemanticFieldEntry "SemanticFieldEntry"
/// @{
/// @brief Per-field semantic metadata entry with provenance tracking, lock state, and candidate set.
/// @invariant Locked fields preserve their active value regardless of later candidate proposals.
/// @}
void SemanticFieldEntry(void);

/// @defgroup SemanticCandidate "SemanticCandidate"
/// @{
/// @brief One proposed semantic value for a field entry, ranked by match type and confidence.
/// @}
void SemanticCandidate(void);

/// @defgroup DatasetReviewSessionModels "DatasetReviewSessionModels"
/// @{
/// @brief Session aggregate root and collaborator models for dataset review orchestration.
/// @invariant Session and profile entities are strictly scoped to an authenticated user.
/// @post Session ORM models registered with optimistic locking
/// @pre Database engine initialized
/// @}
void DatasetReviewSessionModels(void);

/// @defgroup SessionCollaborator "SessionCollaborator"
/// @{
/// @brief RBAC collaborator record linking a user to a dataset review session with a specific role.
/// @}
void SessionCollaborator(void);

/// @defgroup DatasetReviewSession "DatasetReviewSession"
/// @{
/// @brief Aggregate root for the dataset review lifecycle, owning all child entities and driving readiness transitions.
/// @invariant Optimistic-lock version column prevents lost-update races on concurrent mutations.
/// @}
void DatasetReviewSession(void);

/// @defgroup FilterStateModels "FilterStateModels"
/// @{
/// @brief Pydantic models for Superset native filter state extraction and restoration.
/// @}
void FilterStateModels(void);

/// @defgroup FilterState "FilterState"
/// @{
/// @brief Represents the state of a single native filter.
/// @}
void FilterState(void);

/// @defgroup NativeFilterDataMask "NativeFilterDataMask"
/// @{
/// @brief Represents the dataMask containing all native filter states.
/// @}
void NativeFilterDataMask(void);

/// @defgroup ParsedNativeFilters "ParsedNativeFilters"
/// @{
/// @brief Result of parsing native filters from permalink or native_filters_key.
/// @}
void ParsedNativeFilters(void);

/// @defgroup DashboardURLFilterExtraction "DashboardURLFilterExtraction"
/// @{
/// @brief Result of parsing a complete dashboard URL for filter information.
/// @}
void DashboardURLFilterExtraction(void);

/// @defgroup ExtraFormDataMerge "ExtraFormDataMerge"
/// @{
/// @brief Configuration for merging extraFormData from different sources.
/// @}
void ExtraFormDataMerge(void);

/// @defgroup GitModels "GitModels"
/// @{
/// @}
void GitModels(void);

/// @defgroup GitServerConfig "GitServerConfig"
/// @{
/// @brief Configuration for a Git server connection.
/// @}
void GitServerConfig(void);

/// @defgroup GitRepository "GitRepository"
/// @{
/// @brief Tracking for a local Git repository linked to a dashboard.
/// @}
void GitRepository(void);

/// @defgroup DeploymentEnvironment "DeploymentEnvironment"
/// @{
/// @brief Target Superset environments for dashboard deployment.
/// @}
void DeploymentEnvironment(void);

/// @defgroup LlmModels "LlmModels"
/// @{
/// @brief SQLAlchemy models for LLM provider configuration and validation results.
/// @}
void LlmModels(void);

/// @defgroup ValidationPolicy "ValidationPolicy"
/// @{
/// @brief Defines a scheduled rule for validating a group of dashboards within an execution window.
/// @}
void ValidationPolicy(void);

/// @defgroup LLMProvider "LLMProvider"
/// @{
/// @brief SQLAlchemy model for LLM provider configuration.
/// @}
void LLMProvider(void);

/// @defgroup ValidationRecord "ValidationRecord"
/// @{
/// @brief SQLAlchemy model for dashboard validation history.
/// @}
void ValidationRecord(void);

/// @defgroup MaintenanceModels "MaintenanceModels"
/// @{
/// @brief SQLAlchemy models for the Maintenance Banner feature: event, banner, dashboard state, and settings.
/// @invariant MaintenanceSettings is a singleton row (id='default') enforced by CheckConstraint
/// @}
void MaintenanceModels(void);

/// @defgroup MaintenanceEventStatus "MaintenanceEventStatus"
/// @{
/// @}
void MaintenanceEventStatus(void);

/// @defgroup MaintenanceDashboardBannerStatus "MaintenanceDashboardBannerStatus"
/// @{
/// @}
void MaintenanceDashboardBannerStatus(void);

/// @defgroup MaintenanceDashboardStateStatus "MaintenanceDashboardStateStatus"
/// @{
/// @}
void MaintenanceDashboardStateStatus(void);

/// @defgroup DashboardScope "DashboardScope"
/// @{
/// @}
void DashboardScope(void);

/// @defgroup MaintenanceEvent "MaintenanceEvent"
/// @{
/// @brief A record of a maintenance event with table list, time window, status, and linked dashboard states.
/// @}
void MaintenanceEvent(void);

/// @defgroup MaintenanceDashboardBanner "MaintenanceDashboardBanner"
/// @{
/// @brief The canonical "one chart per dashboard" entity. Unique partial index enforces single active banner per dashboard.
/// @invariant Unique partial index (environment_id, dashboard_id) WHERE status='active'
/// @}
void MaintenanceDashboardBanner(void);

/// @defgroup MaintenanceDashboardState "MaintenanceDashboardState"
/// @{
/// @brief Links a maintenance event to a dashboard via a banner. Tracks per-dashboard-per-event lifecycle.
/// @}
void MaintenanceDashboardState(void);

/// @defgroup MaintenanceSettings "MaintenanceSettings"
/// @{
/// @brief Single-row maintenance mode configuration. Enforces singleton via CheckConstraint(id='default').
/// @invariant id must always be 'default' — enforced by CheckConstraint
/// @}
void MaintenanceSettings(void);

/// @defgroup MappingModels "MappingModels"
/// @{
/// @brief Defines the database schema for environment metadata and database mappings using SQLAlchemy.
/// @invariant All primary keys are UUID strings.
/// @}
void MappingModels(void);

/// @defgroup Base "Base"
/// @{
/// @brief SQLAlchemy declarative base for all domain models.
/// @}
void Base(void);

/// @defgroup ResourceType "ResourceType"
/// @{
/// @brief Enumeration of possible Superset resource types for ID mapping.
/// @}
void ResourceType(void);

/// @defgroup MigrationStatus "MigrationStatus"
/// @{
/// @brief Enumeration of possible migration job statuses.
/// @}
void MigrationStatus(void);

/// @defgroup MigrationJob "MigrationJob"
/// @{
/// @brief Represents a single migration execution job.
/// @}
void MigrationJob(void);

/// @defgroup ResourceMapping "ResourceMapping"
/// @{
/// @brief Maps a universal UUID for a resource to its actual ID on a specific environment.
/// @}
void ResourceMapping(void);

/// @defgroup ProfileModels "ProfileModels"
/// @{
/// @brief Defines persistent per-user profile settings for dashboard filter, Git identity/token, and UX preferences.
/// @invariant Sensitive Git token is stored encrypted and never returned in plaintext.
/// @post Profile ORM models registered
/// @pre Database engine initialized
/// @}
void ProfileModels(void);

/// @defgroup UserDashboardPreference "UserDashboardPreference"
/// @{
/// @brief Stores Superset username binding and default "my dashboards" toggle for one authenticated user.
/// @}
void UserDashboardPreference(void);

/// @defgroup ReportModels "ReportModels"
/// @{
/// @brief Canonical report schemas for unified task reporting across heterogeneous task types.
/// @invariant Canonical report fields are always present for every report item.
/// @post Provides validated schemas for cross-plugin reporting and UI consumption.
/// @pre Pydantic library and task manager models are available.
/// @}
void ReportModels(void);

/// @defgroup TaskType "TaskType"
/// @{
/// @brief Supported normalized task report types.
/// @invariant Must contain valid generic task type mappings.
/// @}
void TaskType(void);

/// @defgroup ReportStatus "ReportStatus"
/// @{
/// @brief Supported normalized report status values.
/// @invariant TaskStatus enum mapping logic holds.
/// @}
void ReportStatus(void);

/// @defgroup ErrorContext "ErrorContext"
/// @{
/// @brief Error and recovery context for failed/partial reports.
/// @invariant The properties accurately describe error state.
/// @}
void ErrorContext(void);

/// @defgroup TaskReport "TaskReport"
/// @{
/// @brief Canonical normalized report envelope for one task execution.
/// @invariant Must represent canonical task record attributes.
/// @}
void TaskReport(void);

/// @defgroup ReportQuery "ReportQuery"
/// @{
/// @brief Query object for server-side report filtering, sorting, and pagination.
/// @invariant Time and pagination queries are mutually consistent.
/// @}
void ReportQuery(void);

/// @defgroup ReportCollection "ReportCollection"
/// @{
/// @brief Paginated collection of normalized task reports.
/// @invariant Represents paginated data correctly.
/// @}
void ReportCollection(void);

/// @defgroup ReportDetailView "ReportDetailView"
/// @{
/// @brief Detailed report representation including diagnostics and recovery actions.
/// @invariant Incorporates a report and logs correctly.
/// @}
void ReportDetailView(void);

/// @defgroup StorageModels "StorageModels"
/// @{
/// @}
void StorageModels(void);

/// @defgroup FileCategory "FileCategory"
/// @{
/// @brief Enumeration of supported file categories in the storage system.
/// @}
void FileCategory(void);

/// @defgroup StorageConfig "StorageConfig"
/// @{
/// @brief Configuration model for the storage system, defining paths and naming patterns.
/// @}
void StorageConfig(void);

/// @defgroup StoredFile "StoredFile"
/// @{
/// @brief Data model representing metadata for a file stored in the system.
/// @}
void StoredFile(void);

/// @defgroup TaskModels "TaskModels"
/// @{
/// @brief Defines the database schema for task execution records.
/// @invariant All primary keys are UUID strings.
/// @}
void TaskModels(void);

/// @defgroup TaskRecord "TaskRecord"
/// @{
/// @brief Represents a persistent record of a task execution.
/// @}
void TaskRecord(void);

/// @defgroup TaskLogRecord "TaskLogRecord"
/// @{
/// @brief Represents a single persistent log entry for a task.
/// @invariant Each log entry belongs to exactly one task.
/// @}
void TaskLogRecord(void);

/// @defgroup TranslateModels "TranslateModels"
/// @{
/// @brief SQLAlchemy ORM models for LLM-based SQL/dashboard translation across dialects.
/// @}
void TranslateModels(void);

/// @defgroup TranslationJob "TranslationJob"
/// @{
/// @brief A translation job representing a multi-dialect conversion task with column mappings, LLM config, and dictionary attachments.
/// @}
void TranslationJob(void);

/// @defgroup TranslationRun "TranslationRun"
/// @{
/// @brief Represents a single execution of a translation job, capturing status, timing, and Superset execution metadata.
/// @}
void TranslationRun(void);

/// @defgroup TranslationBatch "TranslationBatch"
/// @{
/// @brief Groups translation records within a run into manageable batches with timing and record counts.
/// @}
void TranslationBatch(void);

/// @defgroup TranslationRecord "TranslationRecord"
/// @{
/// @brief Individual translation result for a single SQL statement or dashboard element, tracking source, target, and error state.
/// @}
void TranslationRecord(void);

/// @defgroup TranslationEvent "TranslationEvent"
/// @{
/// @brief Audit/event log for translation operations, with optional run_id for context.
/// @}
void TranslationEvent(void);

/// @defgroup TranslationPreviewSession "TranslationPreviewSession"
/// @{
/// @brief A preview session allowing users to review proposed translations before applying them.
/// @}
void TranslationPreviewSession(void);

/// @defgroup TranslationPreviewRecord "TranslationPreviewRecord"
/// @{
/// @brief Individual preview entry within a preview session, showing original and translated content side by side.
/// @}
void TranslationPreviewRecord(void);

/// @defgroup TerminologyDictionary "TerminologyDictionary"
/// @{
/// @brief A named collection of terminology mappings used during translation to ensure consistent term translation.
/// @}
void TerminologyDictionary(void);

/// @defgroup DictionaryEntry "DictionaryEntry"
/// @{
/// @brief A single term mapping entry with case-insensitive unique constraint on source_term_normalized and origin tracking.
/// @}
void DictionaryEntry(void);

/// @defgroup TranslationSchedule "TranslationSchedule"
/// @{
/// @brief Defines a cron-based schedule for recurring translation jobs.
/// @}
void TranslationSchedule(void);

/// @defgroup TranslationJobDictionary "TranslationJobDictionary"
/// @{
/// @brief Many-to-many association between translation jobs and terminology dictionaries.
/// @}
void TranslationJobDictionary(void);

/// @defgroup MetricSnapshot "MetricSnapshot"
/// @{
/// @brief Captures translation performance metrics at a point in time with config/content/dictionary hash keys for aggregation.
/// @}
void MetricSnapshot(void);

/// @defgroup TranslationLanguage "TranslationLanguage"
/// @{
/// @brief Per-language translation result for a single record, supporting multi-language output.
/// @}
void TranslationLanguage(void);

/// @defgroup TranslationPreviewLanguage "TranslationPreviewLanguage"
/// @{
/// @brief Per-language preview entry within a preview session.
/// @}
void TranslationPreviewLanguage(void);

/// @defgroup TranslationRunLanguageStats "TranslationRunLanguageStats"
/// @{
/// @brief Per-language statistics for a translation run (row counts, tokens, cost).
/// @}
void TranslationRunLanguageStats(void);

/// @defgroup src_plugins "src.plugins"
/// @{
/// @brief Plugin package root for dynamic discovery and runtime imports.
/// @}
void src_plugins(void);

/// @defgroup BackupPlugin "BackupPlugin"
/// @{
/// @brief A plugin that provides functionality to back up Superset dashboards.
/// @}
void BackupPlugin(void);

/// @defgroup DebugPluginModule "DebugPluginModule"
/// @{
/// @brief Plugin for diagnostics. Inherits PluginBase.
/// @}
void DebugPluginModule(void);

/// @defgroup DebugPlugin "DebugPlugin"
/// @{
/// @brief Plugin for system diagnostics and debugging.
/// @}
void DebugPlugin(void);

/// @defgroup GitPluginExt "GitPluginExt"
/// @{
/// @brief Git plugin extension package root.
/// @}
void GitPluginExt(void);

/// @defgroup GitLLMExtensionModule "GitLLMExtensionModule"
/// @{
/// @brief LLM-based extensions for the Git plugin, specifically for commit message generation.
/// @}
void GitLLMExtensionModule(void);

/// @defgroup GitLLMExtension "GitLLMExtension"
/// @{
/// @brief Provides LLM capabilities to the Git plugin.
/// @}
void GitLLMExtension(void);

/// @defgroup GitPluginModule "GitPluginModule"
/// @{
/// @brief Предоставляет плагин для версионирования и развертывания дашбордов Superset.
/// @invariant _handle_sync сохраняет backup управляемых директорий перед удалением;
/// @}
void GitPluginModule(void);

/// @defgroup GitPlugin "GitPlugin"
/// @{
/// @brief Реализация плагина Git Integration для управления версиями дашбордов.
/// @}
void GitPlugin(void);

/// @defgroup LLMAnalysisPackage "LLMAnalysisPackage"
/// @{
/// @}
void LLMAnalysisPackage(void);

/// @defgroup LLMAnalysisModels "LLMAnalysisModels"
/// @{
/// @brief Define Pydantic models for LLM Analysis plugin.
/// @}
void LLMAnalysisModels(void);

/// @defgroup LLMProviderType "LLMProviderType"
/// @{
/// @brief Enum for supported LLM providers.
/// @}
void LLMProviderType(void);

/// @defgroup LLMProviderConfig "LLMProviderConfig"
/// @{
/// @brief Configuration for an LLM provider.
/// @}
void LLMProviderConfig(void);

/// @defgroup ValidationStatus "ValidationStatus"
/// @{
/// @brief Enum for dashboard validation status.
/// @}
void ValidationStatus(void);

/// @defgroup DetectedIssue "DetectedIssue"
/// @{
/// @brief Model for a single issue detected during validation.
/// @}
void DetectedIssue(void);

/// @defgroup ValidationResult "ValidationResult"
/// @{
/// @brief Model for dashboard validation result.
/// @}
void ValidationResult(void);

/// @defgroup LLMAnalysisPlugin "LLMAnalysisPlugin"
/// @{
/// @brief Implements DashboardValidationPlugin and DocumentationPlugin.
/// @invariant All LLM interactions must be executed as asynchronous tasks.
/// @}
void LLMAnalysisPlugin(void);

/// @defgroup _is_masked_or_invalid_api_key "_is_masked_or_invalid_api_key"
/// @{
/// @brief Guards against placeholder or malformed API keys in runtime.
/// @post Returns True when value cannot be used for authenticated provider calls.
/// @pre value may be None.
/// @}
void _is_masked_or_invalid_api_key(void);

/// @defgroup _json_safe_value "_json_safe_value"
/// @{
/// @brief Recursively normalize payload values for JSON serialization.
/// @post datetime values are converted to ISO strings.
/// @pre value may be nested dict/list with datetime values.
/// @}
void _json_safe_value(void);

/// @defgroup DashboardValidationPlugin "DashboardValidationPlugin"
/// @{
/// @brief Plugin for automated dashboard health analysis using LLMs.
/// @}
void DashboardValidationPlugin(void);

/// @defgroup DocumentationPlugin "DocumentationPlugin"
/// @{
/// @brief Plugin for automated dataset documentation using LLMs.
/// @}
void DocumentationPlugin(void);

/// @defgroup LLMAnalysisScheduler "LLMAnalysisScheduler"
/// @{
/// @brief Provides helper functions to schedule LLM-based validation tasks.
/// @}
void LLMAnalysisScheduler(void);

/// @defgroup schedule_dashboard_validation "schedule_dashboard_validation"
/// @{
/// @brief Schedules a recurring dashboard validation task.
/// @}
void schedule_dashboard_validation(void);

/// @defgroup _parse_cron "_parse_cron"
/// @{
/// @brief Basic cron parser placeholder.
/// @}
void _parse_cron(void);

/// @defgroup LLMAnalysisService "LLMAnalysisService"
/// @{
/// @brief Services for LLM interaction and dashboard screenshots.
/// @invariant Screenshots must be 1920px width and capture full page height.
/// @}
void LLMAnalysisService(void);

/// @defgroup ScreenshotService "ScreenshotService"
/// @{
/// @brief Handles capturing screenshots of Superset dashboards.
/// @}
void ScreenshotService(void);

/// @defgroup LLMClient "LLMClient"
/// @{
/// @brief Wrapper for LLM provider APIs.
/// @}
void LLMClient(void);

/// @defgroup MaintenanceBannerPlugin "MaintenanceBannerPlugin"
/// @{
/// @brief TaskManager plugin for executing maintenance banner operations (start, end, end-all).
/// @}
void MaintenanceBannerPlugin(void);

/// @defgroup MapperPluginModule "MapperPluginModule"
/// @{
/// @brief Plugin for dataset column mapping. Inherits PluginBase.
/// @}
void MapperPluginModule(void);

/// @defgroup MapperPlugin "MapperPlugin"
/// @{
/// @brief Plugin for mapping dataset columns verbose names.
/// @}
void MapperPlugin(void);

/// @defgroup MigrationPlugin "MigrationPlugin"
/// @{
/// @brief Orchestrates export, DB-mapping transformation, and import of Superset dashboards across environments.
/// @invariant Dashboards must never be imported with unmapped/source DB connections to prevent data leaks or cross-environment pollution.
/// @post Plugin metadata remains stable and migration execution preserves mapped-environment import guarantees.
/// @pre Plugin loader can resolve infrastructure dependencies and execution requests provide validated migration context.
/// @}
void MigrationPlugin(void);

/// @defgroup SearchPluginModule "SearchPluginModule"
/// @{
/// @brief Plugin for text search across datasets. Inherits PluginBase.
/// @}
void SearchPluginModule(void);

/// @defgroup SearchPlugin "SearchPlugin"
/// @{
/// @brief Plugin for searching text patterns in Superset datasets.
/// @}
void SearchPlugin(void);

/// @defgroup StoragePluginPackage "StoragePluginPackage"
/// @{
/// @}
void StoragePluginPackage(void);

/// @defgroup StoragePlugin "StoragePlugin"
/// @{
/// @brief Provides core filesystem operations for managing backups and repositories.
/// @invariant All file operations must be restricted to the configured storage root.
/// @}
void StoragePlugin(void);

/// @defgroup TranslatePluginPackage "TranslatePluginPackage"
/// @{
/// @}
void TranslatePluginPackage(void);

/// @defgroup TestClickHouseTimestampNormalization "TestClickHouseTimestampNormalization"
/// @{
/// @brief Verify Unix timestamp detection and conversion for ClickHouse Date columns.
/// @}
void TestClickHouseTimestampNormalization(void);

/// @defgroup TestClickHouseInsertSqlGeneration "TestClickHouseInsertSqlGeneration"
/// @{
/// @brief Verify SQLGenerator produces valid ClickHouse INSERT SQL with normalized dates.
/// @}
void TestClickHouseInsertSqlGeneration(void);

/// @defgroup TestClickHouseJoinVerification "TestClickHouseJoinVerification"
/// @{
/// @brief Verify the JOIN query SQL is syntactically correct for ClickHouse.
/// @}
void TestClickHouseJoinVerification(void);

/// @defgroup TestOrchestratorInsertFlow "TestOrchestratorInsertFlow"
/// @{
/// @brief Verify the orchestrator's _generate_and_insert_sql produces correct SQL for ClickHouse.
/// @}
void TestOrchestratorInsertFlow(void);

/// @defgroup TestClickHouseEndToEnd "TestClickHouseEndToEnd"
/// @{
/// @brief End-to-end test: generate SQL, verify structure, simulate execution.
/// @}
void TestClickHouseEndToEnd(void);

/// @defgroup TestDictionaryLegacyHub "TestDictionaryLegacyHub"
/// @{
/// @brief Legacy test module — all tests migrated to domain-specific test files:
/// @}
void TestDictionaryLegacyHub(void);

/// @defgroup TestDictionaryCorrection "TestDictionaryCorrection"
/// @{
/// @brief Validate InlineCorrectionService and dictionary correction flows.
/// @}
void TestDictionaryCorrection(void);

/// @defgroup TestDictionaryCRUD "TestDictionaryCRUD"
/// @{
/// @brief Validate DictionaryCRUD and DictionaryEntryCRUD operations.
/// @}
void TestDictionaryCRUD(void);

/// @defgroup TestDictionaryFilter "TestDictionaryFilter"
/// @{
/// @brief Validate DictionaryBatchFilter operations.
/// @}
void TestDictionaryFilter(void);

/// @defgroup TestDictionaryImport "TestDictionaryImport"
/// @{
/// @brief Validate DictionaryImportExport operations.
/// @}
void TestDictionaryImport(void);

/// @defgroup TestDictionaryPromptBuilder "TestDictionaryPromptBuilder"
/// @{
/// @brief Validate ContextAwarePromptBuilder operations: Jaccard similarity, context truncation, entry rendering.
/// @}
void TestDictionaryPromptBuilder(void);

/// @defgroup TestDictionaryUtils "TestDictionaryUtils"
/// @{
/// @brief Validate utility functions: _normalize_term and _detect_delimiter.
/// @}
void TestDictionaryUtils(void);

/// @defgroup LanguageDetectServiceTests "LanguageDetectServiceTests"
/// @{
/// @brief Unit tests for LanguageDetectService — local language detection via lingua.
/// @}
void LanguageDetectServiceTests(void);

/// @defgroup test_detect_language_basic "test_detect_language_basic"
/// @{
/// @brief Verify core language detection for common languages.
/// @}
void test_detect_language_basic(void);

/// @defgroup test_detect_language_edge_cases "test_detect_language_edge_cases"
/// @{
/// @}
void test_detect_language_edge_cases(void);

/// @defgroup test_batch_detect "test_batch_detect"
/// @{
/// @}
void test_batch_detect(void);

/// @defgroup test_build_detector "test_build_detector"
/// @{
/// @}
void test_build_detector(void);

/// @defgroup test_get_detector_cache "test_get_detector_cache"
/// @{
/// @}
void test_get_detector_cache(void);

/// @defgroup test_code_to_lang_mapping "test_code_to_lang_mapping"
/// @{
/// @}
void test_code_to_lang_mapping(void);

/// @defgroup fixtures "fixtures"
/// @{
/// @}
void fixtures(void);

/// @defgroup TestTextCleaner "TestTextCleaner"
/// @{
/// @brief Verify text cleaning contracts — normalize_whitespace, truncate_text, clean_text.
/// @}
void TestTextCleaner(void);

/// @defgroup TestTokenBudget "TestTokenBudget"
/// @{
/// @brief Verify estimate_token_budget contracts — safe batch sizing, auto-reduction, warning generation.
/// @}
void TestTokenBudget(void);

/// @defgroup BatchInsertService "BatchInsertService"
/// @{
/// @brief Insert successful translation records into target table via Superset SQL Lab.
/// @}
void BatchInsertService(void);

/// @defgroup insert_batch_to_target "insert_batch_to_target"
/// @{
/// @brief Insert successful records from a single batch into the target table.
/// @}
void insert_batch_to_target(void);

/// @defgroup _fetch_batch_records "_fetch_batch_records"
/// @{
/// @}
void _fetch_batch_records(void);

/// @defgroup _build_target_columns "_build_target_columns"
/// @{
/// @}
void _build_target_columns(void);

/// @defgroup _build_context_keys "_build_context_keys"
/// @{
/// @}
void _build_context_keys(void);

/// @defgroup _build_insert_rows "_build_insert_rows"
/// @{
/// @}
void _build_insert_rows(void);

/// @defgroup _resolve_insert_backend "_resolve_insert_backend"
/// @{
/// @}
void _resolve_insert_backend(void);

/// @defgroup _generate_insert_sql "_generate_insert_sql"
/// @{
/// @}
void _generate_insert_sql(void);

/// @defgroup _execute_insert_sql "_execute_insert_sql"
/// @{
/// @}
void _execute_insert_sql(void);

/// @defgroup BatchProcessingService "BatchProcessingService"
/// @{
/// @brief Batch processing for translation: classify rows (same-language/cache/preview/LLM),
/// @}
void BatchProcessingService(void);

/// @defgroup process_batch "process_batch"
/// @{
/// @brief Process a single batch: create record, classify rows, call LLM, persist.
/// @post TranslationBatch and TranslationRecord rows are created.
/// @pre job and batch_rows are valid.
/// @}
void process_batch(void);

/// @defgroup AdaptiveBatchSizer "AdaptiveBatchSizer"
/// @{
/// @brief Adaptive batch sizing for LLM translation — splits source rows into variable-sized
/// @}
void AdaptiveBatchSizer(void);

/// @defgroup resolve_provider_model "resolve_provider_model"
/// @{
/// @brief Resolve the LLM provider model name for token budget estimation.
/// @post Returns model name string or None if resolution fails.
/// @}
void resolve_provider_model(void);

/// @defgroup auto_size_batches "auto_size_batches"
/// @{
/// @brief Split source rows into variable-sized batches based on content length.
/// @post Returns list of batches, each batch is a list of row dicts.
/// @pre source_rows is non-empty. job has valid config.
/// @}
void auto_size_batches(void);

/// @defgroup LanguageDetectService "LanguageDetectService"
/// @{
/// @brief Local language detection powered by lingua-language-detector (no LLM).
/// @}
void LanguageDetectService(void);

/// @defgroup _detector_cache_key "_detector_cache_key"
/// @{
/// @brief Build a deterministic cache key from target languages list.
/// @}
void _detector_cache_key(void);

/// @defgroup build_detector "build_detector"
/// @{
/// @brief Build a LanguageDetector restricted to target + common source languages.
/// @}
void build_detector(void);

/// @defgroup get_detector "get_detector"
/// @{
/// @brief Get or create a cached detector for the given target languages.
/// @}
void get_detector(void);

/// @defgroup detect_language "detect_language"
/// @{
/// @brief Detect the language of a single text string. Returns BCP-47 code or "und".
/// @}
void detect_language(void);

/// @defgroup _character_block_fallback "_character_block_fallback"
/// @{
/// @brief When lingua returns "und", check if character-block dominance (e.g. Cyrillic)
/// @}
void _character_block_fallback(void);

/// @defgroup batch_detect "batch_detect"
/// @{
/// @brief Detect language for multiple texts in batch. Builds detector if not provided.
/// @}
void batch_detect(void);

/// @defgroup LLMTranslationService "LLMTranslationService"
/// @{
/// @brief LLM interaction for batch translation: call provider with retry, handle truncation
/// @}
void LLMTranslationService(void);

/// @defgroup call_llm_for_batch "call_llm_for_batch"
/// @{
/// @brief Call LLM for a batch of rows requiring translation. Parse and persist results.
/// @post Returns dict with successful/failed/skipped counts.
/// @pre job has valid provider_id. batch_rows is non-empty.
/// @}
void call_llm_for_batch(void);

/// @defgroup call_llm "call_llm"
/// @{
/// @brief Route to provider-specific LLM call implementation.
/// @}
void call_llm(void);

/// @defgroup LLMHttpClient "LLMHttpClient"
/// @{
/// @brief HTTP client for OpenAI-compatible LLM API calls with rate-limit handling and
/// @}
void LLMHttpClient(void);

/// @defgroup call_openai_compatible "call_openai_compatible"
/// @{
/// @brief Call OpenAI-compatible API with rate-limit handling and structured output fallback.
/// @post Returns (response text, finish_reason).
/// @pre Valid API endpoint, key, model, and prompt.
/// @}
void call_openai_compatible(void);

/// @defgroup _do_http_request "_do_http_request"
/// @{
/// @}
void _do_http_request(void);

/// @defgroup _handle_response_format_fallback "_handle_response_format_fallback"
/// @{
/// @}
void _handle_response_format_fallback(void);

/// @defgroup LLMResponseParser "LLMResponseParser"
/// @{
/// @brief Parse LLM JSON response into per-row translations with support for markdown code
/// @}
void LLMResponseParser(void);

/// @defgroup _recover_from_markdown "_recover_from_markdown"
/// @{
/// @}
void _recover_from_markdown(void);

/// @defgroup _recover_truncated_rows "_recover_truncated_rows"
/// @{
/// @}
void _recover_truncated_rows(void);

/// @defgroup RunExecutionService "RunExecutionService"
/// @{
/// @brief Full run lifecycle: prepare run, fetch source rows, filter new keys, orchestrate batches,
/// @}
void RunExecutionService(void);

/// @defgroup RunSourceFetcher "RunSourceFetcher"
/// @{
/// @brief Fetch source rows for translation runs from Superset datasource or preview session.
/// @}
void RunSourceFetcher(void);

/// @defgroup fetch_source_rows "fetch_source_rows"
/// @{
/// @brief Fetch source rows from Superset datasource or preview session fallback.
/// @}
void fetch_source_rows(void);

/// @defgroup _extract_chart_data_rows "_extract_chart_data_rows"
/// @{
/// @}
void _extract_chart_data_rows(void);

/// @defgroup TextCleaner "TextCleaner"
/// @{
/// @brief Text cleaning utilities for the translation pipeline — whitespace normalization
/// @}
void TextCleaner(void);

/// @defgroup normalize_whitespace "normalize_whitespace"
/// @{
/// @brief Collapse multiple spaces, tabs, and newlines into single spaces; trim leading/trailing
/// @}
void normalize_whitespace(void);

/// @defgroup truncate_text "truncate_text"
/// @{
/// @brief Truncate text to max_length characters, appending "..." if truncation occurs.
/// @post When len(text) <= max_length, returns text unchanged.
/// @pre text is a string. max_length >= 0.
/// @}
void truncate_text(void);

/// @defgroup clean_text "clean_text"
/// @{
/// @brief Combine whitespace normalization and truncation into one step.
/// @}
void clean_text(void);

/// @defgroup estimate_token_budget "estimate_token_budget"
/// @{
/// @brief Calculate safe batch_size and max_tokens for LLM translation calls based on actual content length and model context window limits.
/// @}
void estimate_token_budget(void);

/// @defgroup DEFAULT_CONTEXT_WINDOW "DEFAULT_CONTEXT_WINDOW"
/// @{
/// @}
void DEFAULT_CONTEXT_WINDOW(void);

/// @defgroup DEFAULT_MAX_OUTPUT_TOKENS "DEFAULT_MAX_OUTPUT_TOKENS"
/// @{
/// @}
void DEFAULT_MAX_OUTPUT_TOKENS(void);

/// @defgroup REASONING_OVERHEAD "REASONING_OVERHEAD"
/// @{
/// @}
void REASONING_OVERHEAD(void);

/// @defgroup PROVIDER_DEFAULTS "PROVIDER_DEFAULTS"
/// @{
/// @}
void PROVIDER_DEFAULTS(void);

/// @defgroup OUTPUT_PER_ROW_PER_LANG "OUTPUT_PER_ROW_PER_LANG"
/// @{
/// @}
void OUTPUT_PER_ROW_PER_LANG(void);

/// @defgroup JSON_OVERHEAD_PER_ROW "JSON_OVERHEAD_PER_ROW"
/// @{
/// @}
void JSON_OVERHEAD_PER_ROW(void);

/// @defgroup PROMPT_BASE_TOKENS "PROMPT_BASE_TOKENS"
/// @{
/// @}
void PROMPT_BASE_TOKENS(void);

/// @defgroup DICT_TOKENS_PER_ENTRY "DICT_TOKENS_PER_ENTRY"
/// @{
/// @}
void DICT_TOKENS_PER_ENTRY(void);

/// @defgroup DICT_TOKENS_MAX "DICT_TOKENS_MAX"
/// @{
/// @}
void DICT_TOKENS_MAX(void);

/// @defgroup CHARS_PER_TOKEN_MIXED "CHARS_PER_TOKEN_MIXED"
/// @{
/// @}
void CHARS_PER_TOKEN_MIXED(void);

/// @defgroup MIN_MAX_TOKENS "MIN_MAX_TOKENS"
/// @{
/// @}
void MIN_MAX_TOKENS(void);

/// @defgroup MAX_OUTPUT_HEADROOM "MAX_OUTPUT_HEADROOM"
/// @{
/// @}
void MAX_OUTPUT_HEADROOM(void);

/// @defgroup TranslationUtils "TranslationUtils"
/// @{
/// @brief Shared utility functions for the translation plugin — dictionary enforcement,
/// @}
void TranslationUtils(void);

/// @defgroup _normalize_term "_normalize_term"
/// @{
/// @brief Normalize a term for case-insensitive unique constraint lookup.
/// @}
void _normalize_term(void);

/// @defgroup _detect_delimiter "_detect_delimiter"
/// @{
/// @brief Detect the delimiter used in a CSV/TSV header line.
/// @}
void _detect_delimiter(void);

/// @defgroup _enforce_dictionary "_enforce_dictionary"
/// @{
/// @brief Post-process LLM output: enforce dictionary term replacements.
/// @post per_lang_values may be mutated to include forced dictionary replacements.
/// @pre dict_matches is a list of dict entries with source_term/target_term.
/// @}
void _enforce_dictionary(void);

/// @defgroup _compute_source_hash "_compute_source_hash"
/// @{
/// @brief Compute deterministic cache key for a source row.
/// @}
void _compute_source_hash(void);

/// @defgroup _check_translation_cache "_check_translation_cache"
/// @{
/// @brief Look up a previously successful translation by source_hash.
/// @}
void _check_translation_cache(void);

/// @defgroup _compute_key_hash "_compute_key_hash"
/// @{
/// @brief Compute a stable hash from source_data dict for matching preview edits.
/// @}
void _compute_key_hash(void);

/// @defgroup estimate_row_tokens "estimate_row_tokens"
/// @{
/// @brief Estimate token count for a single source row including context fields.
/// @post Returns estimated token count >= 1.
/// @pre source_text is a string.
/// @}
void estimate_row_tokens(void);

/// @defgroup DictionaryManagerModule "DictionaryManagerModule"
/// @{
/// @brief Business logic for terminology dictionary management, entry CRUD, CSV/TSV import with conflict detection, and per-batch filtering.
/// @post Dictionary and entry mutations are persisted with conflict detection.
/// @pre Database session is open and valid.
/// @}
void DictionaryManagerModule(void);

/// @defgroup DictionaryManager "DictionaryManager"
/// @{
/// @brief Facade for terminology dictionaries: delegates to DictionaryCRUD, DictionaryEntryCRUD, DictionaryImportExport, DictionaryBatchFilter, DictionaryCorrectionService.
/// @post Dictionary and entry mutations are persisted with conflict detection.
/// @pre Database session is open and valid.
/// @}
void DictionaryManager(void);

/// @defgroup DictionaryCorrectionService "DictionaryCorrectionService"
/// @{
/// @brief Submit term corrections and bulk corrections to dictionaries with conflict detection.
/// @}
void DictionaryCorrectionService(void);

/// @defgroup DictionaryCRUD "DictionaryCRUD"
/// @{
/// @brief CRUD operations for TerminologyDictionary records.
/// @}
void DictionaryCRUD(void);

/// @defgroup DictionaryEntryCRUD "DictionaryEntryCRUD"
/// @{
/// @brief CRUD operations for DictionaryEntry records.
/// @}
void DictionaryEntryCRUD(void);

/// @defgroup DictionaryBatchFilter "DictionaryBatchFilter"
/// @{
/// @brief Scan batch texts for case-insensitive, word-boundary-aware matches against dictionaries.
/// @}
void DictionaryBatchFilter(void);

/// @defgroup DictionaryImportExport "DictionaryImportExport"
/// @{
/// @brief Import/export entries as CSV/TSV with conflict detection, and migration of old entries.
/// @}
void DictionaryImportExport(void);

/// @defgroup _validate_bcp47 "_validate_bcp47"
/// @{
/// @brief Validate that a language tag is a non-empty BCP-47 string.
/// @}
void _validate_bcp47(void);

/// @defgroup TranslationEventLog "TranslationEventLog"
/// @{
/// @brief Structured event logging for translation operations with terminal event invariant enforcement.
/// @invariant Exactly one run_started + exactly one terminal event per non-null run_id.
/// @post Events are persisted immutably; terminal events enforce exactly-one invariant per run.
/// @pre Database session is open and valid.
/// @}
void TranslationEventLog(void);

/// @defgroup TranslationExecutor "TranslationExecutor"
/// @{
/// @brief Process translation in batches: fetch source rows, call LLM, persist TranslationBatch
/// @}
void TranslationExecutor(void);

/// @defgroup TranslationMetrics "TranslationMetrics"
/// @{
/// @brief Aggregate translation metrics from live TranslationEvent + MetricSnapshot for per-job reporting.
/// @post Metrics are aggregated and returned; no side effects.
/// @pre Database session is open.
/// @}
void TranslationMetrics(void);

/// @defgroup TranslationOrchestrator "TranslationOrchestrator"
/// @{
/// @brief Run lifecycle coordination: validate preconditions, dispatch executor, generate SQL, submit to Superset, record events.
/// @invariant State transitions: PENDING -> RUNNING -> COMPLETED|FAILED|CANCELLED. Exactly one terminal event per run.
/// @post Translation run is executed, SQL generated and submitted, events recorded.
/// @pre Valid job and accepted preview (for manual runs). Superset and LLM are reachable.
/// @}
void TranslationOrchestrator(void);

/// @defgroup TranslationResultAggregator "TranslationResultAggregator"
/// @{
/// @brief Query translation run status, records, and history.
/// @post Returns structured run data with pagination.
/// @pre Database session is available.
/// @}
void TranslationResultAggregator(void);

/// @defgroup orchestrator_cancel "orchestrator_cancel"
/// @{
/// @brief Cancel and retry-insert operations for translation runs.
/// @}
void orchestrator_cancel(void);

/// @defgroup orchestrator_config "orchestrator_config"
/// @{
/// @brief Config hash and dictionary snapshot hash utilities for translation planning.
/// @}
void orchestrator_config(void);

/// @defgroup TranslationExecutionEngine "TranslationExecutionEngine"
/// @{
/// @brief Execute translation runs: dispatch executor, manage completion and failure paths.
/// @post Run is executed with SQL generated; events recorded.
/// @pre Database session and config manager are available. Run is in valid state.
/// @}
void TranslationExecutionEngine(void);

/// @defgroup update_language_stats "update_language_stats"
/// @{
/// @brief Aggregate TranslationLanguage entries by language_code and update TranslationRunLanguageStats.
/// @}
void update_language_stats(void);

/// @defgroup TranslationPlanner "TranslationPlanner"
/// @{
/// @brief Handle translation run planning: validation, config hashing, dictionary snapshot.
/// @post TranslationRun is planned with hashes and config snapshot; events recorded.
/// @pre Database session and config manager are available.
/// @}
void TranslationPlanner(void);

/// @defgroup orchestrator_query "orchestrator_query"
/// @{
/// @brief Query translation run records and history with pagination.
/// @}
void orchestrator_query(void);

/// @defgroup TranslationRunRetryManager "TranslationRunRetryManager"
/// @{
/// @brief Manage retry of translation run batches.
/// @post Retried batches are re-executed.
/// @pre Database session and config manager are available.
/// @}
void TranslationRunRetryManager(void);

/// @defgroup orchestrator_run_completion "orchestrator_run_completion"
/// @{
/// @brief Post-execution run completion handlers: cancelled, success-with-insert, and failure paths.
/// @}
void orchestrator_run_completion(void);

/// @defgroup TranslationStageRunner "TranslationStageRunner"
/// @{
/// @brief Coordinate translation run execution, retry, and cancellation via delegated components.
/// @post Run is executed; events recorded.
/// @pre Database session and config manager are available. Run is in valid state.
/// @}
void TranslationStageRunner(void);

/// @defgroup SQLInsertService "SQLInsertService"
/// @{
/// @brief Generate INSERT SQL from translation records and submit to Superset SQL Lab.
/// @post SQL is generated and submitted to Superset; returns execution result.
/// @pre Job has target table configured. Run has successful records.
/// @}
void SQLInsertService(void);

/// @defgroup orchestrator_sql_rows "orchestrator_sql_rows"
/// @{
/// @brief Column and row building utilities for SQL insertion in translate plugin.
/// @}
void orchestrator_sql_rows(void);

/// @defgroup build_columns "build_columns"
/// @{
/// @brief Build list of target columns for SQL INSERT from job configuration.
/// @}
void build_columns(void);

/// @defgroup build_context_keys "build_context_keys"
/// @{
/// @brief Build list of context keys for SQL row data.
/// @}
void build_context_keys(void);

/// @defgroup build_rows "build_rows"
/// @{
/// @brief Build row data for SQL INSERT with per-language expansion.
/// @}
void build_rows(void);

/// @defgroup validate_job_preconditions "validate_job_preconditions"
/// @{
/// @brief Validate preconditions before starting a translation run.
/// @post Raises ValueError if any precondition fails.
/// @pre Job exists and db session is valid.
/// @}
void validate_job_preconditions(void);

/// @defgroup TranslatePlugin "TranslatePlugin"
/// @{
/// @brief TranslatePlugin skeleton for cross-dialect SQL and dashboard translation.
/// @}
void TranslatePlugin(void);

/// @defgroup DEFAULT_EXECUTION_PROMPT_TEMPLATE "DEFAULT_EXECUTION_PROMPT_TEMPLATE"
/// @{
/// @brief Default LLM prompt template for full execution (batch translation).
/// @}
void DEFAULT_EXECUTION_PROMPT_TEMPLATE(void);

/// @defgroup DEFAULT_PREVIEW_PROMPT_TEMPLATE "DEFAULT_PREVIEW_PROMPT_TEMPLATE"
/// @{
/// @brief Default LLM prompt template for preview (sample translation).
/// @}
void DEFAULT_PREVIEW_PROMPT_TEMPLATE(void);

/// @defgroup PreviewExecutor "PreviewExecutor"
/// @{
/// @brief Fetch sample data from Superset and call LLM provider for preview.
/// @post Sample rows fetched, LLM called.
/// @pre Database session, config manager, and Superset client are available.
/// @}
void PreviewExecutor(void);

/// @defgroup PreviewPromptBuilder "PreviewPromptBuilder"
/// @{
/// @brief Build LLM prompts for preview sessions including dictionary glossary and row context.
/// @}
void PreviewPromptBuilder(void);

/// @defgroup preview_prompt_helpers "preview_prompt_helpers"
/// @{
/// @brief Token estimation metadata and budget helpers for preview prompt building.
/// @}
void preview_prompt_helpers(void);

/// @defgroup estimate_token_budget_for_rows "estimate_token_budget_for_rows"
/// @{
/// @brief Check token budget and optionally truncate source rows for preview.
/// @post Returns adjusted source_rows, actual_row_count, and token_budget dict.
/// @}
void estimate_token_budget_for_rows(void);

/// @defgroup compute_build_token_metadata "compute_build_token_metadata"
/// @{
/// @brief Compute token estimation metadata for prompt builder return dict.
/// @post Returns prompt, row_meta, target_languages, cost estimates, and cost_warning.
/// @}
void compute_build_token_metadata(void);

/// @defgroup preview_response_parser "preview_response_parser"
/// @{
/// @brief Parse LLM JSON responses and Superset data; compute config/dict hashes for preview.
/// @}
void preview_response_parser(void);

/// @defgroup parse_llm_response "parse_llm_response"
/// @{
/// @brief Parse LLM JSON response into structured translations dict with per-language support.
/// @post Returns dict mapping row_id -> {detected_source_language, lang_code: translation, ...}.
/// @pre response_text is a valid JSON string (possibly wrapped in markdown code block).
/// @}
void parse_llm_response(void);

/// @defgroup extract_data_rows "extract_data_rows"
/// @{
/// @brief Extract data rows from Superset chart data API response.
/// @}
void extract_data_rows(void);

/// @defgroup compute_config_hash "compute_config_hash"
/// @{
/// @brief Compute a deterministic hash of job configuration for snapshot comparison.
/// @}
void compute_config_hash(void);

/// @defgroup compute_dict_snapshot_hash "compute_dict_snapshot_hash"
/// @{
/// @brief Compute a hash of dictionary state for snapshot comparison.
/// @}
void compute_dict_snapshot_hash(void);

/// @defgroup PreviewSessionManager "PreviewSessionManager"
/// @{
/// @brief Manage preview session row-level actions: approve/edit/reject rows.
/// @}
void PreviewSessionManager(void);

/// @defgroup preview_session_ops "preview_session_ops"
/// @{
/// @brief Preview session lifecycle operations: accept and query preview sessions.
/// @}
void preview_session_ops(void);

/// @defgroup get_preview_session "get_preview_session"
/// @{
/// @brief Get the latest preview session for a job with its records.
/// @}
void get_preview_session(void);

/// @defgroup preview_session_serializer "preview_session_serializer"
/// @{
/// @brief Serialization and action helpers for preview sessions: record serialization and per-row approve/reject/edit actions.
/// @}
void preview_session_serializer(void);

/// @defgroup serialize_preview_record "serialize_preview_record"
/// @{
/// @brief Serialize a TranslationPreviewRecord to a response dict.
/// @}
void serialize_preview_record(void);

/// @defgroup apply_language_action "apply_language_action"
/// @{
/// @brief Apply approve/reject/edit action to a TranslationPreviewLanguage entry.
/// @}
void apply_language_action(void);

/// @defgroup apply_record_action "apply_record_action"
/// @{
/// @brief Apply approve/reject/edit action to a TranslationPreviewRecord and its language entries.
/// @}
void apply_record_action(void);

/// @defgroup TokenEstimator "TokenEstimator"
/// @{
/// @brief Estimate token counts and costs for LLM translation operations.
/// @}
void TokenEstimator(void);

/// @defgroup ContextAwarePromptBuilder "ContextAwarePromptBuilder"
/// @{
/// @brief Pure-function prompt builder that enhances dictionary entries with context annotations.
/// @}
void ContextAwarePromptBuilder(void);

/// @defgroup TranslationScheduler "TranslationScheduler"
/// @{
/// @brief Manage TranslationSchedule rows and register them with core SchedulerService.
/// @post TranslationSchedule CRUD persisted; APScheduler jobs registered/updated/removed.
/// @pre Database session and SchedulerService are available.
/// @}
void TranslationScheduler(void);

/// @defgroup execute_scheduled_translation "execute_scheduled_translation"
/// @{
/// @brief APScheduler job handler — runs scheduled translation with concurrency check and new-key-only fallback.
/// @post Translation run created and executed if no concurrent run exists.
/// @pre schedule_id is valid.
/// @}
void execute_scheduled_translation(void);

/// @defgroup TranslateJobService "TranslateJobService"
/// @{
/// @brief Service layer for translation job CRUD with datasource column validation and database dialect detection.
/// @post Translation jobs are created/updated/deleted with column validation and dialect caching.
/// @pre Database session and config manager are available.
/// @}
void TranslateJobService(void);

/// @defgroup BulkFindReplaceService "BulkFindReplaceService"
/// @{
/// @brief Service for bulk find-and-replace operations on translated values.
/// @}
void BulkFindReplaceService(void);

/// @defgroup DatasourceMetadataService "DatasourceMetadataService"
/// @{
/// @brief Fetch datasource column metadata and database dialect from Superset.
/// @post Datasource metadata is fetched with column details and normalized dialect.
/// @pre Database session and config manager are available.
/// @}
void DatasourceMetadataService(void);

/// @defgroup get_dialect_from_database "get_dialect_from_database"
/// @{
/// @brief Extract normalized dialect string from a Superset database record.
/// @}
void get_dialect_from_database(void);

/// @defgroup fetch_datasource_metadata "fetch_datasource_metadata"
/// @{
/// @brief Fetch datasource columns and database dialect from Superset.
/// @}
void fetch_datasource_metadata(void);

/// @defgroup detect_virtual_columns "detect_virtual_columns"
/// @{
/// @brief Identify virtual (calculated) columns from column metadata.
/// @}
void detect_virtual_columns(void);

/// @defgroup InlineCorrectionService "InlineCorrectionService"
/// @{
/// @brief Service for inline editing translated values and submitting corrections to dictionaries.
/// @post Inline edits applied with optional dictionary submission.
/// @pre Database session is available.
/// @}
void InlineCorrectionService(void);

/// @defgroup TargetSchemaValidation "TargetSchemaValidation"
/// @{
/// @brief Проверка схемы целевой таблицы: запрос колонок через Superset SQL Lab,
/// @}
void TargetSchemaValidation(void);

/// @defgroup _build_expected_columns "_build_expected_columns"
/// @{
/// @brief Собирает список ожидаемых колонок по конфигурации column mapping.
/// @}
void _build_expected_columns(void);

/// @defgroup _extract_columns_from_rows "_extract_columns_from_rows"
/// @{
/// @brief Извлекает список колонок таблицы из data-строк результата SQL Lab.
/// @}
void _extract_columns_from_rows(void);

/// @defgroup _parse_sqllab_result "_parse_sqllab_result"
/// @{
/// @brief Извлекает data-строки из ответа Superset SQL Lab.
/// @}
void _parse_sqllab_result(void);

/// @defgroup validate_target_table_schema "validate_target_table_schema"
/// @{
/// @brief Основная функция: проверяет схему целевой таблицы через Superset SQL Lab.
/// @post Возвращает TargetSchemaValidationResponse с diff-анализом.
/// @pre Superset окружение и target_database_id валидны.
/// @}
void validate_target_table_schema(void);

/// @defgroup ServiceUtils "ServiceUtils"
/// @{
/// @brief Utility functions for the translate service layer.
/// @}
void ServiceUtils(void);

/// @defgroup _extract_dialect "_extract_dialect"
/// @{
/// @brief Extract database dialect from Superset backend URI.
/// @}
void _extract_dialect(void);

/// @defgroup job_to_response "job_to_response"
/// @{
/// @brief Convert a TranslationJob ORM model to a TranslateJobResponse schema with dictionary_ids.
/// @}
void job_to_response(void);

/// @defgroup SQLGenerator "SQLGenerator"
/// @{
/// @brief Dialect-aware safe SQL generation for INSERT/UPSERT operations.
/// @post Returns safe SQL strings for the target dialect.
/// @pre Job has target_schema and target_table configured. Dialect is one of supported SUPPORTED_DIALECTS.
/// @}
void SQLGenerator(void);

/// @defgroup _normalize_timestamp_value "_normalize_timestamp_value"
/// @{
/// @brief Detect Unix timestamp strings (seconds or millis) and convert to 'YYYY-MM-DD' for Date columns.
/// @}
void _normalize_timestamp_value(void);

/// @defgroup _quote_identifier "_quote_identifier"
/// @{
/// @brief Quote an identifier per dialect rules. PostgreSQL uses double quotes; ClickHouse uses backticks.
/// @post Returns safely quoted identifier.
/// @pre identifier is a non-empty string.
/// @}
void _quote_identifier(void);

/// @defgroup _encode_sql_value "_encode_sql_value"
/// @{
/// @brief Encode a Python value into a SQL-safe literal for INSERT VALUES, with ClickHouse timestamp normalization.
/// @}
void _encode_sql_value(void);

/// @defgroup _build_values_clause "_build_values_clause"
/// @{
/// @brief Build a VALUES clause for multiple rows with per-column value encoding and dialect-aware quoting.
/// @}
void _build_values_clause(void);

/// @defgroup generate_insert_sql "generate_insert_sql"
/// @{
/// @brief Generate a dialect-aware plain INSERT SQL statement for the given table, columns, and rows.
/// @}
void generate_insert_sql(void);

/// @defgroup generate_upsert_sql "generate_upsert_sql"
/// @{
/// @brief Generate PostgreSQL dialect UPSERT SQL with ON CONFLICT DO UPDATE.
/// @post Returns UPSERT SQL string or raises ValueError.
/// @pre dialect is postgresql-compatible. target_table, columns, key_columns are non-empty.
/// @}
void generate_upsert_sql(void);

/// @defgroup SupersetSqlLabExecutor "SupersetSqlLabExecutor"
/// @{
/// @brief Submit SQL to Superset SQL Lab API and poll execution status.
/// @post SQL is submitted to Superset SQL Lab; execution reference is returned.
/// @pre Valid Superset environment configuration and authenticated client.
/// @}
void SupersetSqlLabExecutor(void);

/// @defgroup SchemasPackage "SchemasPackage"
/// @{
/// @brief API schema package root.
/// @}
void SchemasPackage(void);

/// @defgroup TestSettingsAndHealthSchemas "TestSettingsAndHealthSchemas"
/// @{
/// @brief Regression tests for settings and health schema contracts updated in 026 fix batch.
/// @}
void TestSettingsAndHealthSchemas(void);

/// @defgroup test_validation_policy_create_accepts_structured_custom_channels "test_validation_policy_create_accepts_structured_custom_channels"
/// @{
/// @brief Ensure policy schema accepts structured custom channel objects with type/target fields.
/// @}
void test_validation_policy_create_accepts_structured_custom_channels(void);

/// @defgroup test_validation_policy_create_rejects_legacy_string_custom_channels "test_validation_policy_create_rejects_legacy_string_custom_channels"
/// @{
/// @brief Ensure legacy list[str] custom channel payload is rejected by typed channel contract.
/// @}
void test_validation_policy_create_rejects_legacy_string_custom_channels(void);

/// @defgroup test_dashboard_health_item_status_accepts_only_whitelisted_values "test_dashboard_health_item_status_accepts_only_whitelisted_values"
/// @{
/// @brief Verify strict grouped regex only accepts PASS/WARN/FAIL/UNKNOWN exact statuses.
/// @}
void test_dashboard_health_item_status_accepts_only_whitelisted_values(void);

/// @defgroup AuthSchemas "AuthSchemas"
/// @{
/// @brief Pydantic schemas for authentication requests and responses.
/// @invariant Sensitive fields like password must not be included in response schemas.
/// @}
void AuthSchemas(void);

/// @defgroup Token "Token"
/// @{
/// @brief Represents a JWT access token response.
/// @}
void Token(void);

/// @defgroup TokenData "TokenData"
/// @{
/// @brief Represents the data encoded in a JWT token.
/// @}
void TokenData(void);

/// @defgroup PermissionSchema "PermissionSchema"
/// @{
/// @brief Represents a permission in API responses.
/// @}
void PermissionSchema(void);

/// @defgroup RoleSchema "RoleSchema"
/// @{
/// @brief Represents a role in API responses.
/// @}
void RoleSchema(void);

/// @defgroup RoleCreate "RoleCreate"
/// @{
/// @brief Schema for creating a new role.
/// @}
void RoleCreate(void);

/// @defgroup RoleUpdate "RoleUpdate"
/// @{
/// @brief Schema for updating an existing role.
/// @}
void RoleUpdate(void);

/// @defgroup ADGroupMappingSchema "ADGroupMappingSchema"
/// @{
/// @brief Represents an AD Group to Role mapping in API responses.
/// @}
void ADGroupMappingSchema(void);

/// @defgroup ADGroupMappingCreate "ADGroupMappingCreate"
/// @{
/// @brief Schema for creating an AD Group mapping.
/// @}
void ADGroupMappingCreate(void);

/// @defgroup UserBase "UserBase"
/// @{
/// @brief Base schema for user data.
/// @}
void UserBase(void);

/// @defgroup UserCreate "UserCreate"
/// @{
/// @brief Schema for creating a new user.
/// @}
void UserCreate(void);

/// @defgroup UserUpdate "UserUpdate"
/// @{
/// @brief Schema for updating an existing user.
/// @}
void UserUpdate(void);

/// @defgroup User "User"
/// @{
/// @brief Schema for user data in API responses.
/// @}
void User(void);

/// @defgroup DatasetReviewSchemas "DatasetReviewSchemas"
/// @{
/// @brief Thin facade re-exporting all dataset review API schemas from decomposed sub-modules.
/// @}
void DatasetReviewSchemas(void);

/// @defgroup DatasetReviewSchemaComposites "DatasetReviewSchemaComposites"
/// @{
/// @brief Composite Pydantic DTOs for clarification, preview, run context, and session summary/detail responses.
/// @}
void DatasetReviewSchemaComposites(void);

/// @defgroup ClarificationOptionDto "ClarificationOptionDto"
/// @{
/// @brief Clarification option DTO.
/// @}
void ClarificationOptionDto(void);

/// @defgroup ClarificationAnswerDto "ClarificationAnswerDto"
/// @{
/// @brief Clarification answer DTO with feedback.
/// @}
void ClarificationAnswerDto(void);

/// @defgroup ClarificationQuestionDto "ClarificationQuestionDto"
/// @{
/// @brief Clarification question DTO with nested options and answer.
/// @}
void ClarificationQuestionDto(void);

/// @defgroup ClarificationSessionDto "ClarificationSessionDto"
/// @{
/// @brief Clarification session DTO with nested questions.
/// @}
void ClarificationSessionDto(void);

/// @defgroup CompiledPreviewDto "CompiledPreviewDto"
/// @{
/// @brief Compiled preview DTO with fingerprint and session version.
/// @}
void CompiledPreviewDto(void);

/// @defgroup DatasetRunContextDto "DatasetRunContextDto"
/// @{
/// @brief Run context DTO with launch audit data and session version.
/// @}
void DatasetRunContextDto(void);

/// @defgroup SessionSummary "SessionSummary"
/// @{
/// @brief Lightweight session summary DTO for list responses.
/// @}
void SessionSummary(void);

/// @defgroup SessionDetail "SessionDetail"
/// @{
/// @brief Full session detail DTO with all nested aggregates for detail views.
/// @}
void SessionDetail(void);

/// @defgroup DatasetReviewSchemaDtos "DatasetReviewSchemaDtos"
/// @{
/// @brief Pydantic DTOs for session, profile, findings, collaborators, and semantic field API payloads.
/// @}
void DatasetReviewSchemaDtos(void);

/// @defgroup SessionCollaboratorDto "SessionCollaboratorDto"
/// @{
/// @brief Collaborator DTO for session access control.
/// @}
void SessionCollaboratorDto(void);

/// @defgroup DatasetProfileDto "DatasetProfileDto"
/// @{
/// @brief Dataset profile DTO with business summary and confidence metadata.
/// @}
void DatasetProfileDto(void);

/// @defgroup ValidationFindingDto "ValidationFindingDto"
/// @{
/// @brief Validation finding DTO with resolution tracking.
/// @}
void ValidationFindingDto(void);

/// @defgroup SemanticSourceDto "SemanticSourceDto"
/// @{
/// @brief Semantic source DTO with trust level and status.
/// @}
void SemanticSourceDto(void);

/// @defgroup SemanticCandidateDto "SemanticCandidateDto"
/// @{
/// @brief Semantic candidate DTO with match type and confidence score.
/// @}
void SemanticCandidateDto(void);

/// @defgroup SemanticFieldEntryDto "SemanticFieldEntryDto"
/// @{
/// @brief Semantic field entry DTO with nested candidates and session version.
/// @}
void SemanticFieldEntryDto(void);

/// @defgroup ImportedFilterDto "ImportedFilterDto"
/// @{
/// @brief Imported filter DTO with confidence and recovery status.
/// @}
void ImportedFilterDto(void);

/// @defgroup TemplateVariableDto "TemplateVariableDto"
/// @{
/// @brief Template variable DTO with mapping status.
/// @}
void TemplateVariableDto(void);

/// @defgroup ExecutionMappingDto "ExecutionMappingDto"
/// @{
/// @brief Execution mapping DTO with approval state and session version.
/// @}
void ExecutionMappingDto(void);

/// @defgroup HealthSchemas "HealthSchemas"
/// @{
/// @brief Pydantic schemas for dashboard health summary.
/// @}
void HealthSchemas(void);

/// @defgroup DashboardHealthItem "DashboardHealthItem"
/// @{
/// @brief Represents the latest health status of a single dashboard.
/// @}
void DashboardHealthItem(void);

/// @defgroup HealthSummaryResponse "HealthSummaryResponse"
/// @{
/// @brief Aggregated health summary for all dashboards.
/// @}
void HealthSummaryResponse(void);

/// @defgroup ProfileSchemas "ProfileSchemas"
/// @{
/// @brief Defines API schemas for profile preference persistence, security read-only snapshot, and Superset account lookup.
/// @invariant Schema shapes stay stable for profile UI states and backend preference contracts.
/// @}
void ProfileSchemas(void);

/// @defgroup ProfilePermissionState "ProfilePermissionState"
/// @{
/// @brief Represents one permission badge state for profile read-only security view.
/// @}
void ProfilePermissionState(void);

/// @defgroup ProfileSecuritySummary "ProfileSecuritySummary"
/// @{
/// @brief Read-only security and access snapshot for current user.
/// @}
void ProfileSecuritySummary(void);

/// @defgroup ProfilePreference "ProfilePreference"
/// @{
/// @brief Represents persisted profile preference for a single authenticated user.
/// @}
void ProfilePreference(void);

/// @defgroup ProfilePreferenceUpdateRequest "ProfilePreferenceUpdateRequest"
/// @{
/// @brief Request payload for updating current user's profile settings.
/// @}
void ProfilePreferenceUpdateRequest(void);

/// @defgroup ProfilePreferenceResponse "ProfilePreferenceResponse"
/// @{
/// @brief Response envelope for profile preference read/update endpoints.
/// @}
void ProfilePreferenceResponse(void);

/// @defgroup SupersetAccountLookupRequest "SupersetAccountLookupRequest"
/// @{
/// @brief Query contract for Superset account lookup by selected environment.
/// @}
void SupersetAccountLookupRequest(void);

/// @defgroup SupersetAccountCandidate "SupersetAccountCandidate"
/// @{
/// @brief Canonical account candidate projected from Superset users payload.
/// @}
void SupersetAccountCandidate(void);

/// @defgroup SupersetAccountLookupResponse "SupersetAccountLookupResponse"
/// @{
/// @brief Response envelope for Superset account lookup (success or degraded mode).
/// @}
void SupersetAccountLookupResponse(void);

/// @defgroup SettingsSchemas "SettingsSchemas"
/// @{
/// @brief Pydantic schemas for application settings and automation policies.
/// @}
void SettingsSchemas(void);

/// @defgroup NotificationChannel "NotificationChannel"
/// @{
/// @brief Structured notification channel definition for policy-level custom routing.
/// @}
void NotificationChannel(void);

/// @defgroup ValidationPolicyBase "ValidationPolicyBase"
/// @{
/// @brief Base schema for validation policy data.
/// @}
void ValidationPolicyBase(void);

/// @defgroup ValidationPolicyCreate "ValidationPolicyCreate"
/// @{
/// @brief Schema for creating a new validation policy.
/// @}
void ValidationPolicyCreate(void);

/// @defgroup ValidationPolicyUpdate "ValidationPolicyUpdate"
/// @{
/// @brief Schema for updating an existing validation policy.
/// @}
void ValidationPolicyUpdate(void);

/// @defgroup ValidationPolicyResponse "ValidationPolicyResponse"
/// @{
/// @brief Schema for validation policy response data.
/// @}
void ValidationPolicyResponse(void);

/// @defgroup TranslationScheduleItem "TranslationScheduleItem"
/// @{
/// @brief Response schema for a translation schedule item with joined job name.
/// @}
void TranslationScheduleItem(void);

/// @defgroup TranslateSchemas "TranslateSchemas"
/// @{
/// @brief Pydantic v2 schemas for translation API request/response serialization.
/// @}
void TranslateSchemas(void);

/// @defgroup TranslateJobCreate "TranslateJobCreate"
/// @{
/// @brief Schema for creating a new translation job.
/// @}
void TranslateJobCreate(void);

/// @defgroup TranslateJobUpdate "TranslateJobUpdate"
/// @{
/// @brief Schema for updating an existing translation job.
/// @}
void TranslateJobUpdate(void);

/// @defgroup TranslateJobResponse "TranslateJobResponse"
/// @{
/// @brief Schema for translation job API responses.
/// @}
void TranslateJobResponse(void);

/// @defgroup DatasourceColumnResponse "DatasourceColumnResponse"
/// @{
/// @brief Schema for datasource column metadata response.
/// @}
void DatasourceColumnResponse(void);

/// @defgroup DatasourceColumnsResponse "DatasourceColumnsResponse"
/// @{
/// @brief Schema for datasource columns endpoint response.
/// @}
void DatasourceColumnsResponse(void);

/// @defgroup DuplicateJobResponse "DuplicateJobResponse"
/// @{
/// @brief Schema for duplicate job response.
/// @}
void DuplicateJobResponse(void);

/// @defgroup DictionaryCreate "DictionaryCreate"
/// @{
/// @brief Schema for creating a new terminology dictionary.
/// @}
void DictionaryCreate(void);

/// @defgroup DictionaryImport "DictionaryImport"
/// @{
/// @brief Schema for importing entries into a terminology dictionary.
/// @}
void DictionaryImport(void);

/// @defgroup DictionaryResponse "DictionaryResponse"
/// @{
/// @brief Schema for terminology dictionary API responses.
/// @}
void DictionaryResponse(void);

/// @defgroup DictionaryEntryCreate "DictionaryEntryCreate"
/// @{
/// @brief Schema for adding/editing a dictionary entry with language pair support.
/// @}
void DictionaryEntryCreate(void);

/// @defgroup DictionaryEntryResponse "DictionaryEntryResponse"
/// @{
/// @brief Schema for dictionary entry API responses.
/// @}
void DictionaryEntryResponse(void);

/// @defgroup DictionaryImportResult "DictionaryImportResult"
/// @{
/// @brief Schema for dictionary import result.
/// @}
void DictionaryImportResult(void);

/// @defgroup PreviewRequest "PreviewRequest"
/// @{
/// @brief Schema for triggering a translation preview.
/// @}
void PreviewRequest(void);

/// @defgroup PreviewRowUpdate "PreviewRowUpdate"
/// @{
/// @brief Schema for approving/editing/rejecting a preview row.
/// @}
void PreviewRowUpdate(void);

/// @defgroup PreviewAcceptResponse "PreviewAcceptResponse"
/// @{
/// @brief Schema for preview accept response.
/// @}
void PreviewAcceptResponse(void);

/// @defgroup CostEstimate "CostEstimate"
/// @{
/// @brief Schema for cost estimation in preview response.
/// @}
void CostEstimate(void);

/// @defgroup TermCorrectionSubmit "TermCorrectionSubmit"
/// @{
/// @brief Schema for submitting a term correction in a translation preview.
/// @}
void TermCorrectionSubmit(void);

/// @defgroup TermCorrectionBulkSubmit "TermCorrectionBulkSubmit"
/// @{
/// @brief Schema for submitting multiple term corrections atomically.
/// @}
void TermCorrectionBulkSubmit(void);

/// @defgroup CorrectionConflictResult "CorrectionConflictResult"
/// @{
/// @brief Schema for reporting conflicts in correction submission.
/// @}
void CorrectionConflictResult(void);

/// @defgroup CorrectionSubmitResponse "CorrectionSubmitResponse"
/// @{
/// @brief Schema for correction submission response.
/// @}
void CorrectionSubmitResponse(void);

/// @defgroup ScheduleResponse "ScheduleResponse"
/// @{
/// @brief Schema for schedule API responses.
/// @}
void ScheduleResponse(void);

/// @defgroup NextExecutionResponse "NextExecutionResponse"
/// @{
/// @brief Schema for next execution preview.
/// @}
void NextExecutionResponse(void);

/// @defgroup TranslationRunResponse "TranslationRunResponse"
/// @{
/// @brief Schema for translation run API responses.
/// @}
void TranslationRunResponse(void);

/// @defgroup RunDetailResponse "RunDetailResponse"
/// @{
/// @brief Schema for detailed run response including records, events, and config snapshot.
/// @}
void RunDetailResponse(void);

/// @defgroup RunHistoryFilter "RunHistoryFilter"
/// @{
/// @brief Schema for filtering run history.
/// @}
void RunHistoryFilter(void);

/// @defgroup RunListResponse "RunListResponse"
/// @{
/// @brief Schema for paginated run list response.
/// @}
void RunListResponse(void);

/// @defgroup AggregatedMetricsResponse "AggregatedMetricsResponse"
/// @{
/// @brief Schema for aggregated per-job metrics.
/// @}
void AggregatedMetricsResponse(void);

/// @defgroup TranslationPreviewLanguageResponse "TranslationPreviewLanguageResponse"
/// @{
/// @brief Schema for per-language preview data in API responses.
/// @}
void TranslationPreviewLanguageResponse(void);

/// @defgroup PreviewRow "PreviewRow"
/// @{
/// @brief A single row in a translation preview showing original and translated content side by side.
/// @}
void PreviewRow(void);

/// @defgroup TranslationPreviewResponse "TranslationPreviewResponse"
/// @{
/// @brief Schema for translation preview session API responses.
/// @}
void TranslationPreviewResponse(void);

/// @defgroup TranslationBatchResponse "TranslationBatchResponse"
/// @{
/// @brief Schema for translation batch API responses.
/// @}
void TranslationBatchResponse(void);

/// @defgroup MetricsResponse "MetricsResponse"
/// @{
/// @brief Schema for translation metrics API responses.
/// @}
void MetricsResponse(void);

/// @defgroup TranslationLanguageResponse "TranslationLanguageResponse"
/// @{
/// @brief Schema for per-language translation data in API responses.
/// @}
void TranslationLanguageResponse(void);

/// @defgroup TranslationRunLanguageStatsResponse "TranslationRunLanguageStatsResponse"
/// @{
/// @brief Schema for per-language statistics in run API responses.
/// @}
void TranslationRunLanguageStatsResponse(void);

/// @defgroup OverrideLanguageRequest "OverrideLanguageRequest"
/// @{
/// @brief Schema for manually overriding the detected source language of a translation.
/// @}
void OverrideLanguageRequest(void);

/// @defgroup BulkFindReplaceRequest "BulkFindReplaceRequest"
/// @{
/// @brief Schema for bulk find-and-replace within translations for a target language.
/// @}
void BulkFindReplaceRequest(void);

/// @defgroup InlineEditRequest "InlineEditRequest"
/// @{
/// @brief Schema for inline editing a translated value on a completed run result.
/// @}
void InlineEditRequest(void);

/// @defgroup BulkReplacePreviewItem "BulkReplacePreviewItem"
/// @{
/// @brief A single item in a bulk replace preview list.
/// @}
void BulkReplacePreviewItem(void);

/// @defgroup BulkReplaceResponse "BulkReplaceResponse"
/// @{
/// @brief Response for bulk find-and-replace operation.
/// @}
void BulkReplaceResponse(void);

/// @defgroup InlineCorrectionSubmit "InlineCorrectionSubmit"
/// @{
/// @brief Schema for submitting an inline correction for a specific translated record.
/// @}
void InlineCorrectionSubmit(void);

/// @defgroup TargetSchemaValidationRequest "TargetSchemaValidationRequest"
/// @{
/// @brief Schema for requesting target table schema validation.
/// @}
void TargetSchemaValidationRequest(void);

/// @defgroup TargetSchemaColumnInfo "TargetSchemaColumnInfo"
/// @{
/// @brief Schema for a single column in the schema validation response.
/// @}
void TargetSchemaColumnInfo(void);

/// @defgroup TargetSchemaValidationResponse "TargetSchemaValidationResponse"
/// @{
/// @brief Schema for target table schema validation response.
/// @}
void TargetSchemaValidationResponse(void);

/// @defgroup ValidationSchemas "ValidationSchemas"
/// @{
/// @brief Pydantic v2 schemas for validation task management and run history API serialization.
/// @}
void ValidationSchemas(void);

/// @defgroup ValidationTaskCreate "ValidationTaskCreate"
/// @{
/// @brief Schema for creating a new validation task (policy).
/// @}
void ValidationTaskCreate(void);

/// @defgroup ValidationTaskUpdate "ValidationTaskUpdate"
/// @{
/// @brief Schema for updating an existing validation task (policy).
/// @}
void ValidationTaskUpdate(void);

/// @defgroup ValidationTaskResponse "ValidationTaskResponse"
/// @{
/// @brief Schema for validation task API responses — includes last run status from join.
/// @}
void ValidationTaskResponse(void);

/// @defgroup ValidationTaskListResponse "ValidationTaskListResponse"
/// @{
/// @brief Schema for paginated task list response.
/// @}
void ValidationTaskListResponse(void);

/// @defgroup ValidationRunResponse "ValidationRunResponse"
/// @{
/// @brief Schema for validation run history listing.
/// @}
void ValidationRunResponse(void);

/// @defgroup ValidationRunListResponse "ValidationRunListResponse"
/// @{
/// @brief Schema for paginated run list response.
/// @}
void ValidationRunListResponse(void);

/// @defgroup ValidationRunDetailResponse "ValidationRunDetailResponse"
/// @{
/// @brief Schema for full run detail including parsed issues and raw response.
/// @}
void ValidationRunDetailResponse(void);

/// @defgroup TriggerRunResponse "TriggerRunResponse"
/// @{
/// @brief Schema for trigger-run response — returns spawned task ID.
/// @}
void TriggerRunResponse(void);

/// @defgroup ScriptsPackage "ScriptsPackage"
/// @{
/// @brief Script entrypoint package root.
/// @}
void ScriptsPackage(void);

/// @defgroup CleanReleaseCliScript "CleanReleaseCliScript"
/// @{
/// @brief Provide headless CLI commands for candidate registration, artifact import and manifest build.
/// @}
void CleanReleaseCliScript(void);

/// @defgroup build_parser "build_parser"
/// @{
/// @brief Build argparse parser for clean release CLI.
/// @}
void build_parser(void);

/// @defgroup run_candidate_register "run_candidate_register"
/// @{
/// @brief Register candidate in repository via CLI command.
/// @post Candidate is persisted in DRAFT status.
/// @pre Candidate ID must be unique.
/// @}
void run_candidate_register(void);

/// @defgroup run_artifact_import "run_artifact_import"
/// @{
/// @brief Import single artifact for existing candidate.
/// @post Artifact is persisted for candidate.
/// @pre Candidate must exist.
/// @}
void run_artifact_import(void);

/// @defgroup run_manifest_build "run_manifest_build"
/// @{
/// @brief Build immutable manifest snapshot for candidate.
/// @post New manifest version is persisted.
/// @pre Candidate must exist.
/// @}
void run_manifest_build(void);

/// @defgroup run_compliance_run "run_compliance_run"
/// @{
/// @brief Execute compliance run for candidate with optional manifest fallback.
/// @post Returns run payload and exit code 0 on success.
/// @pre Candidate exists and trusted snapshots are configured.
/// @}
void run_compliance_run(void);

/// @defgroup run_compliance_status "run_compliance_status"
/// @{
/// @brief Read run status by run id.
/// @post Returns run status payload.
/// @pre Run exists.
/// @}
void run_compliance_status(void);

/// @defgroup _to_payload "_to_payload"
/// @{
/// @brief Serialize domain models for CLI JSON output across SQLAlchemy/Pydantic variants.
/// @post Returns dictionary payload without mutating value.
/// @pre value is serializable model or primitive object.
/// @}
void _to_payload(void);

/// @defgroup run_compliance_report "run_compliance_report"
/// @{
/// @brief Read immutable report by run id.
/// @post Returns report payload.
/// @pre Run and report exist.
/// @}
void run_compliance_report(void);

/// @defgroup run_compliance_violations "run_compliance_violations"
/// @{
/// @brief Read run violations by run id.
/// @post Returns violations payload.
/// @pre Run exists.
/// @}
void run_compliance_violations(void);

/// @defgroup run_approve "run_approve"
/// @{
/// @brief Approve candidate based on immutable PASSED report.
/// @post Persists APPROVED decision and returns success payload.
/// @pre Candidate and report exist; report is PASSED.
/// @}
void run_approve(void);

/// @defgroup run_reject "run_reject"
/// @{
/// @brief Reject candidate without mutating compliance evidence.
/// @post Persists REJECTED decision and returns success payload.
/// @pre Candidate and report exist.
/// @}
void run_reject(void);

/// @defgroup run_publish "run_publish"
/// @{
/// @brief Publish approved candidate to target channel.
/// @post Appends ACTIVE publication record and returns payload.
/// @pre Candidate is approved and report belongs to candidate.
/// @}
void run_publish(void);

/// @defgroup run_revoke "run_revoke"
/// @{
/// @brief Revoke active publication record.
/// @post Publication record status becomes REVOKED.
/// @pre Publication id exists and is ACTIVE.
/// @}
void run_revoke(void);

/// @defgroup CleanReleaseTuiScript "CleanReleaseTuiScript"
/// @{
/// @brief Interactive terminal interface for Enterprise Clean Release compliance validation.
/// @invariant TUI refuses startup in non-TTY environments; headless flow is CLI/API only.
/// @}
void CleanReleaseTuiScript(void);

/// @defgroup TuiFacadeAdapter "TuiFacadeAdapter"
/// @{
/// @brief Thin TUI adapter that routes business mutations through application services.
/// @post Business actions return service results/errors without direct TUI-owned mutations.
/// @pre repository contains candidate and trusted policy/registry snapshots for execution.
/// @}
void TuiFacadeAdapter(void);

/// @defgroup CleanReleaseTUI "CleanReleaseTUI"
/// @{
/// @brief Curses-based application for compliance monitoring.
/// @}
void CleanReleaseTUI(void);

/// @defgroup run_checks "run_checks"
/// @{
/// @brief Execute compliance run via facade adapter and update UI state.
/// @post UI reflects final run/report/violation state from service result.
/// @pre Candidate and policy snapshots are present in repository.
/// @}
void run_checks(void);

/// @defgroup bundle_build_mode "bundle_build_mode"
/// @{
/// @brief Interactive bundle build screen — select type, enter tag, watch live build output.
/// @post Subprocess completes (success/failure). Output displayed. User returns via Esc.
/// @pre TTY is available. Bundle type selected (1 or 2). Tag is non-empty.
/// @}
void bundle_build_mode(void);

/// @defgroup CreateAdminScript "CreateAdminScript"
/// @{
/// @brief CLI tool for creating the initial admin user.
/// @invariant Admin user must have the "Admin" role.
/// @}
void CreateAdminScript(void);

/// @defgroup create_admin "create_admin"
/// @{
/// @brief Creates an admin user and necessary roles/permissions.
/// @post Admin user exists in auth.db.
/// @pre username and password provided via CLI.
/// @}
void create_admin(void);

/// @defgroup DeleteRunningTasksUtil "DeleteRunningTasksUtil"
/// @{
/// @brief Script to delete tasks with RUNNING status from the database.
/// @}
void DeleteRunningTasksUtil(void);

/// @defgroup delete_running_tasks "delete_running_tasks"
/// @{
/// @brief Delete all tasks with RUNNING status from the database.
/// @post All tasks with status 'RUNNING' are removed from the database.
/// @pre Database is accessible and TaskRecord model is defined.
/// @}
void delete_running_tasks(void);

/// @defgroup InitAuthDbScript "InitAuthDbScript"
/// @{
/// @brief Initializes the auth database and creates the necessary tables.
/// @invariant Safe to run multiple times (idempotent).
/// @}
void InitAuthDbScript(void);

/// @defgroup run_init "run_init"
/// @{
/// @brief Main entry point for the initialization script.
/// @post auth.db is initialized with the correct schema and seeded permissions.
/// @}
void run_init(void);

/// @defgroup SeedPermissionsScript "SeedPermissionsScript"
/// @{
/// @brief Populates the auth database with initial system permissions.
/// @invariant Safe to run multiple times (idempotent).
/// @}
void SeedPermissionsScript(void);

/// @defgroup INITIAL_PERMISSIONS "INITIAL_PERMISSIONS"
/// @{
/// @brief Canonical bootstrap permission tuples seeded into auth storage.
/// @}
void INITIAL_PERMISSIONS(void);

/// @defgroup seed_permissions "seed_permissions"
/// @{
/// @brief Inserts missing permissions into the database.
/// @post All INITIAL_PERMISSIONS exist in the DB.
/// @}
void seed_permissions(void);

/// @defgroup SeedSupersetLoadTestScript "SeedSupersetLoadTestScript"
/// @{
/// @brief Creates randomized load-test data in Superset by cloning chart configurations and creating dashboards in target environments.
/// @invariant Created chart and dashboard names are globally unique for one script run.
/// @}
void SeedSupersetLoadTestScript(void);

/// @defgroup _parse_args "_parse_args"
/// @{
/// @brief Parses CLI arguments for load-test data generation.
/// @post Returns validated argument namespace.
/// @pre Script is called from CLI.
/// @}
void _parse_args(void);

/// @defgroup _extract_result_payload "_extract_result_payload"
/// @{
/// @brief Normalizes Superset API payloads that may be wrapped in `result`.
/// @post Returns the unwrapped object when present.
/// @pre payload is a JSON-decoded API response.
/// @}
void _extract_result_payload(void);

/// @defgroup _extract_created_id "_extract_created_id"
/// @{
/// @brief Extracts object ID from create/update API response.
/// @post Returns integer object ID or None if missing.
/// @pre payload is a JSON-decoded API response.
/// @}
void _extract_created_id(void);

/// @defgroup _generate_unique_name "_generate_unique_name"
/// @{
/// @brief Generates globally unique random names for charts/dashboards.
/// @post Returns a unique string and stores it in used_names.
/// @pre used_names is mutable set for collision tracking.
/// @}
void _generate_unique_name(void);

/// @defgroup _resolve_target_envs "_resolve_target_envs"
/// @{
/// @brief Resolves requested environment IDs from configuration.
/// @post Returns mapping env_id -> configured environment object.
/// @pre env_ids is non-empty.
/// @}
void _resolve_target_envs(void);

/// @defgroup _build_chart_template_pool "_build_chart_template_pool"
/// @{
/// @brief Builds a pool of source chart templates to clone in one environment.
/// @post Returns non-empty list of chart payload templates.
/// @pre Client is authenticated.
/// @}
void _build_chart_template_pool(void);

/// @defgroup seed_superset_load_data "seed_superset_load_data"
/// @{
/// @brief Creates dashboards and cloned charts for load testing across target environments.
/// @post Returns execution statistics dictionary.
/// @pre Target environments must be reachable and authenticated.
/// @}
void seed_superset_load_data(void);

/// @defgroup main "main"
/// @{
/// @brief CLI entrypoint for Superset load-test data seeding.
/// @post Prints summary and exits with non-zero status on failure.
/// @pre Command line arguments are valid.
/// @}
void main(void);

/// @defgroup test_dataset_dashboard_relations_script "test_dataset_dashboard_relations_script"
/// @{
/// @brief Tests and inspects dataset-to-dashboard relationship responses from Superset API.
/// @}
void test_dataset_dashboard_relations_script(void);

/// @defgroup services "services"
/// @{
/// @brief Package initialization for services module
/// @note GitService, AuthService, LLMProviderService have circular import issues - import directly when needed
/// @}
void services(void);

/// @defgroup auth_service "auth_service"
/// @{
/// @brief Orchestrates credential authentication and ADFS JIT user provisioning.
/// @invariant Authentication succeeds only for active users with valid credentials; issued sessions encode subject and scopes from assigned roles.
/// @post User identity verified and session tokens issued according to role scopes.
/// @pre Core auth models and security utilities available.
/// @}
void auth_service(void);

/// @defgroup AuthService "AuthService"
/// @{
/// @brief Provides high-level authentication services.
/// @}
void AuthService(void);

/// @defgroup CleanReleaseContracts "CleanReleaseContracts"
/// @{
/// @brief Publish the canonical semantic root for the clean-release backend service cluster.
/// @}
void CleanReleaseContracts(void);

/// @defgroup ApprovalService "ApprovalService"
/// @{
/// @brief Enforce approval/rejection gates over immutable compliance reports.
/// @invariant Approval is allowed only for PASSED report bound to candidate; decisions are append-only.
/// @post Approval decision appended; candidate lifecycle advanced
/// @pre Report with PASSED final_status exists for candidate
/// @}
void ApprovalService(void);

/// @defgroup _get_or_init_decisions_store "_get_or_init_decisions_store"
/// @{
/// @brief Provide append-only in-memory storage for approval decisions.
/// @post Returns mutable decision list attached to repository.
/// @pre repository is initialized.
/// @}
void _get_or_init_decisions_store(void);

/// @defgroup _latest_decision_for_candidate "_latest_decision_for_candidate"
/// @{
/// @brief Resolve latest approval decision for candidate from append-only store.
/// @post Returns latest ApprovalDecision or None.
/// @pre candidate_id is non-empty.
/// @}
void _latest_decision_for_candidate(void);

/// @defgroup _resolve_candidate_and_report "_resolve_candidate_and_report"
/// @{
/// @brief Validate candidate/report existence and ownership prior to decision persistence.
/// @post Returns tuple(candidate, report); raises ApprovalGateError on contract violation.
/// @pre candidate_id and report_id are non-empty.
/// @}
void _resolve_candidate_and_report(void);

/// @defgroup approve_candidate "approve_candidate"
/// @{
/// @brief Persist immutable APPROVED decision and advance candidate lifecycle to APPROVED.
/// @post Approval decision is appended and candidate transitions to APPROVED.
/// @pre Candidate exists, report belongs to candidate, report final_status is PASSED, candidate not already APPROVED.
/// @}
void approve_candidate(void);

/// @defgroup reject_candidate "reject_candidate"
/// @{
/// @brief Persist immutable REJECTED decision without promoting candidate lifecycle.
/// @post Rejected decision is appended; candidate lifecycle is unchanged.
/// @pre Candidate exists and report belongs to candidate.
/// @}
void reject_candidate(void);

/// @defgroup ArtifactCatalogLoader "ArtifactCatalogLoader"
/// @{
/// @brief Load bootstrap artifact catalogs for clean release real-mode flows.
/// @invariant Artifact catalog must produce deterministic CandidateArtifact entries with required identity and checksum fields.
/// @}
void ArtifactCatalogLoader(void);

/// @defgroup load_bootstrap_artifacts "load_bootstrap_artifacts"
/// @{
/// @brief Parse artifact catalog JSON into CandidateArtifact models for TUI/bootstrap flows.
/// @post Returns non-mutated CandidateArtifact models with required fields populated.
/// @pre path points to readable JSON file; payload is list[artifact] or {"artifacts": list[artifact]}.
/// @}
void load_bootstrap_artifacts(void);

/// @defgroup AuditService "AuditService"
/// @{
/// @brief Provide lightweight audit hooks for clean release preparation/check/report lifecycle.
/// @invariant Audit hooks are append-only log actions.
/// @post Audit events appended to log
/// @pre Logger configured
/// @}
void AuditService(void);

/// @defgroup candidate_service "candidate_service"
/// @{
/// @brief Register release candidates with validated artifacts and advance lifecycle through legal transitions.
/// @invariant Candidate lifecycle transitions are delegated to domain guard logic.
/// @post candidate and artifacts are persisted; candidate transitions DRAFT -> PREPARED only.
/// @pre candidate_id must be unique; artifacts input must be non-empty and valid.
/// @}
void candidate_service(void);

/// @defgroup _validate_artifacts "_validate_artifacts"
/// @{
/// @brief Validate raw artifact payload list for required fields and shape.
/// @post Returns normalized artifact list or raises ValueError.
/// @pre artifacts payload is provided by caller.
/// @}
void _validate_artifacts(void);

/// @defgroup ComplianceExecutionService "ComplianceExecutionService"
/// @{
/// @brief Create and execute compliance runs with trusted snapshots, deterministic stages, violations and immutable report persistence.
/// @invariant A run binds to exactly one candidate/manifest/policy/registry snapshot set.
/// @post Candidate-scoped compliance runs persist stage evidence, terminal status, and immutable report artifacts when execution succeeds.
/// @pre Repository adapters, trusted policy resolution, and deterministic stage implementations are available for the run request.
/// @}
void ComplianceExecutionService(void);

/// @defgroup ComplianceExecutionResult "ComplianceExecutionResult"
/// @{
/// @brief Return envelope for compliance execution with run/report and persisted stage artifacts.
/// @}
void ComplianceExecutionResult(void);

/// @defgroup ComplianceOrchestrator "ComplianceOrchestrator"
/// @{
/// @brief Execute mandatory clean compliance stages and produce final COMPLIANT/BLOCKED/FAILED outcome.
/// @invariant COMPLIANT is impossible when any mandatory stage fails.
/// @post OrchestrationResult with compliance status
/// @pre ManifestService and PolicyEngine are available
/// @}
void ComplianceOrchestrator(void);

/// @defgroup CleanComplianceOrchestrator "CleanComplianceOrchestrator"
/// @{
/// @brief Coordinate clean-release compliance verification stages.
/// @}
void CleanComplianceOrchestrator(void);

/// @defgroup run_check_legacy "run_check_legacy"
/// @{
/// @brief Legacy wrapper for compatibility with previous orchestrator call style.
/// @post Returns finalized ComplianceRun produced by orchestrator start->execute->finalize sequence.
/// @pre repository and identifiers are valid and resolvable by orchestrator dependencies.
/// @}
void run_check_legacy(void);

/// @defgroup DemoDataService "DemoDataService"
/// @{
/// @brief Provide deterministic namespace helpers and isolated in-memory repository creation for demo and real modes.
/// @invariant Demo and real namespaces must never collide for generated physical identifiers.
/// @}
void DemoDataService(void);

/// @defgroup resolve_namespace "resolve_namespace"
/// @{
/// @brief Resolve canonical clean-release namespace for requested mode.
/// @post Returns deterministic namespace key for demo/real separation.
/// @pre mode is a non-empty string identifying runtime mode.
/// @}
void resolve_namespace(void);

/// @defgroup build_namespaced_id "build_namespaced_id"
/// @{
/// @brief Build storage-safe physical identifier under mode namespace.
/// @post Returns deterministic "{namespace}::{logical_id}" identifier.
/// @pre namespace and logical_id are non-empty strings.
/// @}
void build_namespaced_id(void);

/// @defgroup create_isolated_repository "create_isolated_repository"
/// @{
/// @brief Create isolated in-memory repository instance for selected mode namespace.
/// @post Returns repository instance tagged with namespace metadata.
/// @pre mode is a valid runtime mode marker.
/// @}
void create_isolated_repository(void);

/// @defgroup clean_release_dto "clean_release_dto"
/// @{
/// @brief Data Transfer Objects for clean release compliance subsystem.
/// @}
void clean_release_dto(void);

/// @defgroup clean_release_enums "clean_release_enums"
/// @{
/// @brief Canonical enums for clean release lifecycle and compliance.
/// @}
void clean_release_enums(void);

/// @defgroup clean_release_exceptions "clean_release_exceptions"
/// @{
/// @brief Domain exceptions for clean release compliance subsystem.
/// @}
void clean_release_exceptions(void);

/// @defgroup clean_release_facade "clean_release_facade"
/// @{
/// @brief Unified entry point for clean release operations.
/// @}
void clean_release_facade(void);

/// @defgroup ManifestBuilder "ManifestBuilder"
/// @{
/// @brief Build deterministic distribution manifest from classified artifact input.
/// @invariant Equal semantic artifact sets produce identical deterministic hash values.
/// @}
void ManifestBuilder(void);

/// @defgroup build_distribution_manifest "build_distribution_manifest"
/// @{
/// @brief Build DistributionManifest with deterministic hash and validated counters.
/// @post Returns DistributionManifest with summary counts matching items cardinality.
/// @pre artifacts list contains normalized classification values.
/// @}
void build_distribution_manifest(void);

/// @defgroup ManifestService "ManifestService"
/// @{
/// @brief Build immutable distribution manifests with deterministic digest and version increment.
/// @invariant Existing manifests are never mutated.
/// @post New immutable manifest is persisted with incremented version and deterministic digest.
/// @pre Candidate exists and is PREPARED or MANIFEST_BUILT; artifacts are present.
/// @}
void ManifestService(void);

/// @defgroup build_manifest_snapshot "build_manifest_snapshot"
/// @{
/// @brief Create a new immutable manifest version for a candidate.
/// @post Returns persisted DistributionManifest with monotonically incremented version.
/// @pre Candidate is prepared, artifacts are available, candidate_id is valid.
/// @}
void build_manifest_snapshot(void);

/// @defgroup clean_release_mappers "clean_release_mappers"
/// @{
/// @brief Map between domain entities (SQLAlchemy models) and DTOs.
/// @}
void clean_release_mappers(void);

/// @defgroup PolicyEngine "PolicyEngine"
/// @{
/// @brief Evaluate artifact/source policies for enterprise clean profile with deterministic outcomes.
/// @invariant Enterprise-clean policy always treats non-registry sources as violations.
/// @post PolicyDecision returned with approval status
/// @pre PolicyRepository is accessible
/// @}
void PolicyEngine(void);

/// @defgroup CleanPolicyEngine "CleanPolicyEngine"
/// @{
/// @post Deterministic classification and source validation are available.
/// @pre Active policy exists and is internally consistent.
/// @}
void CleanPolicyEngine(void);

/// @defgroup PolicyResolutionService "PolicyResolutionService"
/// @{
/// @brief Resolve trusted policy and registry snapshots from ConfigManager without runtime overrides.
/// @invariant Trusted snapshot resolution is based only on ConfigManager active identifiers.
/// @post ResolutionResult with matched policies
/// @pre PolicyRepository and Manifest are available
/// @}
void PolicyResolutionService(void);

/// @defgroup resolve_trusted_policy_snapshots "resolve_trusted_policy_snapshots"
/// @{
/// @brief Resolve immutable trusted policy and registry snapshots using active config IDs only.
/// @post Returns immutable policy and registry snapshots; runtime override attempts are rejected.
/// @pre ConfigManager provides active_policy_id and active_registry_id; repository contains referenced snapshots.
/// @}
void resolve_trusted_policy_snapshots(void);

/// @defgroup PreparationService "PreparationService"
/// @{
/// @brief Prepare release candidate by policy evaluation and deterministic manifest creation.
/// @invariant Candidate preparation always persists manifest and candidate status deterministically.
/// @}
void PreparationService(void);

/// @defgroup prepare_candidate_legacy "prepare_candidate_legacy"
/// @{
/// @brief Legacy compatibility wrapper kept for migration period.
/// @post Delegates to canonical prepare_candidate and preserves response shape.
/// @pre Same as prepare_candidate.
/// @}
void prepare_candidate_legacy(void);

/// @defgroup PublicationService "PublicationService"
/// @{
/// @brief Enforce publication and revocation gates with append-only publication records.
/// @invariant Publication records are append-only snapshots; revoke mutates only publication status for targeted record.
/// @}
void PublicationService(void);

/// @defgroup _get_or_init_publications_store "_get_or_init_publications_store"
/// @{
/// @brief Provide in-memory append-only publication storage.
/// @post Returns publication list attached to repository.
/// @pre repository is initialized.
/// @}
void _get_or_init_publications_store(void);

/// @defgroup _latest_publication_for_candidate "_latest_publication_for_candidate"
/// @{
/// @brief Resolve latest publication record for candidate.
/// @post Returns latest record or None.
/// @pre candidate_id is non-empty.
/// @}
void _latest_publication_for_candidate(void);

/// @defgroup _latest_approval_for_candidate "_latest_approval_for_candidate"
/// @{
/// @brief Resolve latest approval decision from repository decision store.
/// @post Returns latest decision object or None.
/// @pre candidate_id is non-empty.
/// @}
void _latest_approval_for_candidate(void);

/// @defgroup publish_candidate "publish_candidate"
/// @{
/// @brief Create immutable publication record for approved candidate.
/// @post New ACTIVE publication record is appended.
/// @pre Candidate exists, report belongs to candidate, latest approval is APPROVED.
/// @}
void publish_candidate(void);

/// @defgroup revoke_publication "revoke_publication"
/// @{
/// @brief Revoke existing publication record without deleting history.
/// @post Target publication status becomes REVOKED and updated record is returned.
/// @pre publication_id exists in repository publication store.
/// @}
void revoke_publication(void);

/// @defgroup ReportBuilder "ReportBuilder"
/// @{
/// @brief Build and persist compliance reports with consistent counter invariants.
/// @invariant blocking_violations_count never exceeds violations_count.
/// @post Returns immutable report payloads with consistent violation counters and operator summary content.
/// @pre Compliance run is terminal and repository persistence is available for report storage.
/// @}
void ReportBuilder(void);

/// @defgroup clean_release_repositories "clean_release_repositories"
/// @{
/// @brief Export all clean release repositories.
/// @}
void clean_release_repositories(void);

/// @defgroup approval_repository "approval_repository"
/// @{
/// @brief Persist and query approval decisions.
/// @}
void approval_repository(void);

/// @defgroup artifact_repository "artifact_repository"
/// @{
/// @brief Persist and query candidate artifacts.
/// @}
void artifact_repository(void);

/// @defgroup audit_repository "audit_repository"
/// @{
/// @brief Persist and query audit logs for clean release operations.
/// @}
void audit_repository(void);

/// @defgroup candidate_repository "candidate_repository"
/// @{
/// @brief Persist and query release candidates.
/// @}
void candidate_repository(void);

/// @defgroup compliance_repository "compliance_repository"
/// @{
/// @brief Persist and query compliance runs, stage runs, and violations.
/// @}
void compliance_repository(void);

/// @defgroup ManifestRepositoryModule "ManifestRepositoryModule"
/// @{
/// @brief Persist and query distribution manifests.
/// @}
void ManifestRepositoryModule(void);

/// @defgroup ManifestRepository "ManifestRepository"
/// @{
/// @brief Encapsulates database CRUD operations for DistributionManifest entities.
/// @}
void ManifestRepository(void);

/// @defgroup policy_repository "policy_repository"
/// @{
/// @brief Persist and query policy and registry snapshots.
/// @}
void policy_repository(void);

/// @defgroup publication_repository "publication_repository"
/// @{
/// @brief Persist and query publication records.
/// @}
void publication_repository(void);

/// @defgroup report_repository "report_repository"
/// @{
/// @brief Persist and query compliance reports.
/// @}
void report_repository(void);

/// @defgroup RepositoryRelations "RepositoryRelations"
/// @{
/// @brief Provide repository adapter for clean release entities with deterministic access methods.
/// @invariant Repository operations are side-effect free outside explicit save/update calls.
/// @post Repository operations exported
/// @pre In-memory storage initialized
/// @}
void RepositoryRelations(void);

/// @defgroup CleanReleaseRepository "CleanReleaseRepository"
/// @{
/// @brief Data access object for clean release lifecycle.
/// @}
void CleanReleaseRepository(void);

/// @defgroup SourceIsolation "SourceIsolation"
/// @{
/// @brief Validate that all resource endpoints belong to the approved internal source registry.
/// @invariant Any endpoint outside enabled registry entries is treated as external-source violation.
/// @post Source isolation violations identified
/// @pre Source registry configured
/// @}
void SourceIsolation(void);

/// @defgroup ComplianceStages "ComplianceStages"
/// @{
/// @brief Define compliance stage order and helper functions for deterministic run-state evaluation.
/// @invariant Stage order remains deterministic for all compliance runs.
/// @}
void ComplianceStages(void);

/// @defgroup build_default_stages "build_default_stages"
/// @{
/// @brief Build default deterministic stage pipeline implementation order.
/// @post Returns stage instances in mandatory execution order.
/// @pre None.
/// @}
void build_default_stages(void);

/// @defgroup stage_result_map "stage_result_map"
/// @{
/// @brief Convert stage result list to dictionary by stage name.
/// @post Returns stage->status dictionary for downstream evaluation.
/// @pre stage_results may be empty or contain unique stage names.
/// @}
void stage_result_map(void);

/// @defgroup missing_mandatory_stages "missing_mandatory_stages"
/// @{
/// @brief Identify mandatory stages that are absent from run results.
/// @post Returns ordered list of missing mandatory stages.
/// @pre stage_status_map contains zero or more known stage statuses.
/// @}
void missing_mandatory_stages(void);

/// @defgroup derive_final_status "derive_final_status"
/// @{
/// @brief Derive final run status from stage results with deterministic blocking behavior.
/// @post Returns one of PASSED/BLOCKED/ERROR according to mandatory stage outcomes.
/// @pre Stage statuses correspond to compliance checks.
/// @}
void derive_final_status(void);

/// @defgroup ComplianceStageBase "ComplianceStageBase"
/// @{
/// @brief Define shared contracts and helpers for pluggable clean-release compliance stages.
/// @invariant Stage execution is deterministic for equal input context.
/// @}
void ComplianceStageBase(void);

/// @defgroup ComplianceStageContext "ComplianceStageContext"
/// @{
/// @brief Immutable input envelope passed to each compliance stage.
/// @}
void ComplianceStageContext(void);

/// @defgroup StageExecutionResult "StageExecutionResult"
/// @{
/// @brief Structured stage output containing decision, details and violations.
/// @}
void StageExecutionResult(void);

/// @defgroup ComplianceStage "ComplianceStage"
/// @{
/// @brief Protocol for pluggable stage implementations.
/// @}
void ComplianceStage(void);

/// @defgroup build_stage_run_record "build_stage_run_record"
/// @{
/// @brief Build persisted stage run record from stage result.
/// @post Returns ComplianceStageRun with deterministic identifiers and timestamps.
/// @pre run_id and stage_name are non-empty.
/// @}
void build_stage_run_record(void);

/// @defgroup build_violation "build_violation"
/// @{
/// @brief Construct a compliance violation with normalized defaults.
/// @post Returns immutable-style violation payload ready for persistence.
/// @pre run_id, stage_name, code and message are non-empty.
/// @}
void build_violation(void);

/// @defgroup data_purity "data_purity"
/// @{
/// @brief Evaluate manifest purity counters and emit blocking violations for prohibited artifacts.
/// @invariant prohibited_detected_count > 0 always yields BLOCKED stage decision.
/// @}
void data_purity(void);

/// @defgroup DataPurityStage "DataPurityStage"
/// @{
/// @brief Validate manifest summary for prohibited artifacts.
/// @post Returns PASSED when no prohibited artifacts are detected, otherwise BLOCKED with violations.
/// @pre context.manifest.content_json contains summary block or defaults to safe counters.
/// @}
void DataPurityStage(void);

/// @defgroup internal_sources_only "internal_sources_only"
/// @{
/// @brief Verify manifest-declared sources belong to trusted internal registry allowlist.
/// @invariant Any source host outside allowed_hosts yields BLOCKED decision with at least one violation.
/// @}
void internal_sources_only(void);

/// @defgroup InternalSourcesOnlyStage "InternalSourcesOnlyStage"
/// @{
/// @brief Enforce internal-source-only policy from trusted registry snapshot.
/// @post Returns PASSED when all hosts are allowed; otherwise BLOCKED and violations captured.
/// @pre context.registry.allowed_hosts is available.
/// @}
void InternalSourcesOnlyStage(void);

/// @defgroup manifest_consistency "manifest_consistency"
/// @{
/// @brief Ensure run is bound to the exact manifest snapshot and digest used at run creation time.
/// @invariant Digest mismatch between run and manifest yields ERROR with blocking violation evidence.
/// @}
void manifest_consistency(void);

/// @defgroup ManifestConsistencyStage "ManifestConsistencyStage"
/// @{
/// @brief Validate run/manifest linkage consistency.
/// @post Returns PASSED when digests match, otherwise ERROR with one violation.
/// @pre context.run and context.manifest are loaded from repository for same run.
/// @}
void ManifestConsistencyStage(void);

/// @defgroup no_external_endpoints "no_external_endpoints"
/// @{
/// @brief Block manifest payloads that expose external endpoints outside trusted schemes and hosts.
/// @invariant Endpoint outside allowed scheme/host always yields BLOCKED stage decision.
/// @}
void no_external_endpoints(void);

/// @defgroup NoExternalEndpointsStage "NoExternalEndpointsStage"
/// @{
/// @brief Validate endpoint references from manifest against trusted registry.
/// @post Returns PASSED when all endpoints are trusted, otherwise BLOCKED with endpoint violations.
/// @pre context.registry includes allowed hosts and schemes.
/// @}
void NoExternalEndpointsStage(void);

/// @defgroup dataset_review "dataset_review"
/// @{
/// @brief Provides services for dataset-centered orchestration flow.
/// @}
void dataset_review(void);

/// @defgroup ClarificationEngine "ClarificationEngine"
/// @{
/// @brief Manage one-question-at-a-time clarification state, deterministic answer persistence, and readiness/finding updates.
/// @invariant Only one active clarification question may exist at a time; skipped and expert-review items remain unresolved and visible.
/// @post Active clarification payload exposes one highest-priority unresolved question, and each recorded answer is persisted before pointer/readiness mutation.
/// @pre Target session contains a persisted clarification aggregate in the current ownership scope.
/// @}
void ClarificationEngine(void);

/// @defgroup ClarificationQuestionPayload "ClarificationQuestionPayload"
/// @{
/// @brief Typed active-question payload returned to the API layer.
/// @}
void ClarificationQuestionPayload(void);

/// @defgroup ClarificationStateResult "ClarificationStateResult"
/// @{
/// @brief Clarification state result carrying the current session, active payload, and changed findings.
/// @}
void ClarificationStateResult(void);

/// @defgroup ClarificationAnswerCommand "ClarificationAnswerCommand"
/// @{
/// @brief Typed answer command for clarification state mutation.
/// @}
void ClarificationAnswerCommand(void);

/// @defgroup ClarificationHelpers "ClarificationHelpers"
/// @{
/// @brief Pure helper functions for clarification engine — question selection, counting, normalization, finding upsert, and readiness derivation.
/// @}
void ClarificationHelpers(void);

/// @defgroup select_next_open_question "select_next_open_question"
/// @{
/// @brief Select the next unresolved question in deterministic priority order.
/// @}
void select_next_open_question(void);

/// @defgroup count_resolved_questions "count_resolved_questions"
/// @{
/// @brief Count questions whose answers fully resolved the ambiguity.
/// @}
void count_resolved_questions(void);

/// @defgroup count_remaining_questions "count_remaining_questions"
/// @{
/// @brief Count questions still unresolved or deferred after clarification interaction.
/// @}
void count_remaining_questions(void);

/// @defgroup normalize_answer_value "normalize_answer_value"
/// @{
/// @brief Validate and normalize answer payload based on answer kind and active question options.
/// @}
void normalize_answer_value(void);

/// @defgroup build_impact_summary "build_impact_summary"
/// @{
/// @brief Build a compact audit note describing how the clarification answer affects session state.
/// @}
void build_impact_summary(void);

/// @defgroup upsert_clarification_finding "upsert_clarification_finding"
/// @{
/// @brief Keep one finding per clarification topic aligned with answer outcome and unresolved visibility rules.
/// @}
void upsert_clarification_finding(void);

/// @defgroup derive_readiness_state "derive_readiness_state"
/// @{
/// @brief Recompute readiness after clarification mutation while preserving unresolved visibility semantics.
/// @}
void derive_readiness_state(void);

/// @defgroup derive_recommended_action "derive_recommended_action"
/// @{
/// @brief Recompute next-action guidance after clarification mutations.
/// @}
void derive_recommended_action(void);

/// @defgroup SessionEventLoggerModule "SessionEventLoggerModule"
/// @{
/// @brief Persist explicit session mutation events for dataset-review audit trails without weakening ownership or approval invariants.
/// @post Every logged event is committed as an explicit, queryable audit record with deterministic event metadata.
/// @pre Caller provides an owned session scope and an authenticated actor identifier for each persisted mutation event.
/// @}
void SessionEventLoggerModule(void);

/// @defgroup SessionEventLoggerImports "SessionEventLoggerImports"
/// @{
/// @}
void SessionEventLoggerImports(void);

/// @defgroup SessionEventPayload "SessionEventPayload"
/// @{
/// @brief Typed input contract for one persisted dataset-review session audit event.
/// @}
void SessionEventPayload(void);

/// @defgroup SessionEventLogger "SessionEventLogger"
/// @{
/// @brief Persist explicit dataset-review session audit events with meaningful runtime reasoning logs.
/// @post Returns the committed session event row with a stable identifier and stored detail payload.
/// @pre The database session is live and payload identifiers are non-empty.
/// @}
void SessionEventLogger(void);

/// @defgroup DatasetReviewOrchestrator "DatasetReviewOrchestrator"
/// @{
/// @brief Coordinate dataset review session startup and lifecycle-safe intake recovery for one authenticated user.
/// @invariant Launch is blocked unless a current session has no open blocking findings, all launch-sensitive mappings are approved, and a non-stale Superset-generated compiled preview matches the current input fingerprint.
/// @post state transitions are persisted atomically and emit observable progress for long-running steps.
/// @pre session mutations must execute inside a persisted session boundary scoped to one authenticated user.
/// @}
void DatasetReviewOrchestrator(void);

/// @defgroup OrchestratorCommands "OrchestratorCommands"
/// @{
/// @brief Typed command and result dataclasses for dataset review orchestration boundary.
/// @}
void OrchestratorCommands(void);

/// @defgroup StartSessionCommand "StartSessionCommand"
/// @{
/// @brief Typed input contract for starting a dataset review session.
/// @}
void StartSessionCommand(void);

/// @defgroup StartSessionResult "StartSessionResult"
/// @{
/// @brief Session-start result carrying the persisted session and intake recovery metadata.
/// @}
void StartSessionResult(void);

/// @defgroup PreparePreviewCommand "PreparePreviewCommand"
/// @{
/// @brief Typed input contract for compiling one Superset-backed session preview.
/// @}
void PreparePreviewCommand(void);

/// @defgroup PreparePreviewResult "PreparePreviewResult"
/// @{
/// @brief Result contract for one persisted compiled preview attempt.
/// @}
void PreparePreviewResult(void);

/// @defgroup LaunchDatasetCommand "LaunchDatasetCommand"
/// @{
/// @brief Typed input contract for launching one dataset-review session into SQL Lab.
/// @}
void LaunchDatasetCommand(void);

/// @defgroup LaunchDatasetResult "LaunchDatasetResult"
/// @{
/// @brief Launch result carrying immutable run context and any gate blockers.
/// @}
void LaunchDatasetResult(void);

/// @defgroup OrchestratorHelpers "OrchestratorHelpers"
/// @{
/// @brief Pure helper methods extracted from DatasetReviewOrchestrator for INV_7 compliance — snapshot, blockers, fingerprint, recovery bootstrap.
/// @post Helper results are deterministic and do not mutate persistence directly.
/// @pre Caller provides a loaded session aggregate with hydrated child collections.
/// @}
void OrchestratorHelpers(void);

/// @defgroup parse_dataset_selection "parse_dataset_selection"
/// @{
/// @brief Normalize dataset-selection payload into canonical session references.
/// @}
void parse_dataset_selection(void);

/// @defgroup build_initial_profile "build_initial_profile"
/// @{
/// @brief Create the first profile snapshot so exports and detail views remain usable immediately after intake.
/// @}
void build_initial_profile(void);

/// @defgroup build_partial_recovery_findings "build_partial_recovery_findings"
/// @{
/// @brief Project partial Superset intake recovery into explicit findings without blocking session usability.
/// @post Returns warning-level findings that preserve usable but incomplete state.
/// @pre parsed_context.partial_recovery is true.
/// @}
void build_partial_recovery_findings(void);

/// @defgroup extract_effective_filter_value "extract_effective_filter_value"
/// @{
/// @brief Separate normalized filter payload metadata from the user-facing effective filter value.
/// @}
void extract_effective_filter_value(void);

/// @defgroup build_execution_snapshot "build_execution_snapshot"
/// @{
/// @brief Build effective filters, template params, approvals, and fingerprint for preview and launch gating.
/// @post Returns deterministic execution snapshot for current session state without mutating persistence.
/// @pre Session aggregate includes imported filters, template variables, and current execution mappings.
/// @}
void build_execution_snapshot(void);

/// @defgroup build_launch_blockers "build_launch_blockers"
/// @{
/// @brief Enforce launch gates from findings, approvals, and current preview truth.
/// @post Returns explicit blocker codes for every unmet launch invariant.
/// @pre execution_snapshot was computed from current session state.
/// @}
void build_launch_blockers(void);

/// @defgroup get_latest_preview "get_latest_preview"
/// @{
/// @brief Resolve the current latest preview snapshot for one session aggregate.
/// @}
void get_latest_preview(void);

/// @defgroup compute_preview_fingerprint "compute_preview_fingerprint"
/// @{
/// @brief Produce deterministic execution fingerprint for preview truth and staleness checks.
/// @}
void compute_preview_fingerprint(void);

/// @defgroup SessionRepositoryMutations "SessionRepositoryMutations"
/// @{
/// @brief Persistence mutation operations for dataset review session aggregates — profile/findings, recovery state, preview, run context.
/// @post Session aggregate writes preserve ownership and version semantics.
/// @pre All mutations execute within authenticated request or task scope.
/// @}
void SessionRepositoryMutations(void);

/// @defgroup save_profile_and_findings "save_profile_and_findings"
/// @{
/// @brief Persist profile state and replace validation findings for an owned session in one transaction.
/// @post stored profile matches the current session and findings are replaced by the supplied collection.
/// @pre session_id belongs to user_id and the supplied profile/findings belong to the same aggregate scope.
/// @}
void save_profile_and_findings(void);

/// @defgroup save_recovery_state "save_recovery_state"
/// @{
/// @brief Persist imported filters, template variables, and initial execution mappings for one owned session.
/// @post Recovery state persisted to database.
/// @pre session_id belongs to user_id.
/// @}
void save_recovery_state(void);

/// @defgroup save_preview "save_preview"
/// @{
/// @brief Persist a preview snapshot and mark prior session previews stale.
/// @post preview is persisted and the session points to the latest preview identifier.
/// @pre session_id belongs to user_id and preview is prepared for the same session aggregate.
/// @}
void save_preview(void);

/// @defgroup save_run_context "save_run_context"
/// @{
/// @brief Persist an immutable launch audit snapshot for an owned session.
/// @post run context is persisted and linked as the latest launch snapshot for the session.
/// @pre session_id belongs to user_id and run_context targets the same aggregate.
/// @}
void save_run_context(void);

/// @defgroup DatasetReviewSessionRepository "DatasetReviewSessionRepository"
/// @{
/// @brief Persist and retrieve dataset review session aggregates, including readiness, findings, semantic decisions, clarification state, previews, and run contexts.
/// @invariant answers, mapping approvals, preview artifacts, and launch snapshots are never attributed to the wrong user or session.
/// @post session aggregate reads are structurally consistent and writes preserve ownership and version semantics.
/// @pre repository operations execute within authenticated request or task scope.
/// @}
void DatasetReviewSessionRepository(void);

/// @defgroup DatasetReviewSessionVersionConflictError "DatasetReviewSessionVersionConflictError"
/// @{
/// @brief Signal optimistic-lock conflicts for dataset review session mutations.
/// @}
void DatasetReviewSessionVersionConflictError(void);

/// @defgroup SemanticSourceResolver "SemanticSourceResolver"
/// @{
/// @brief Resolve and rank semantic candidates from trusted dictionary-like sources before any inferred fallback.
/// @invariant Manual overrides are never silently replaced by imported, inferred, or AI-generated values.
/// @post candidate ranking follows the configured confidence hierarchy and unresolved fuzzy matches remain reviewable.
/// @pre selected source and target field set must be known.
/// @}
void SemanticSourceResolver(void);

/// @defgroup imports "imports"
/// @{
/// @}
void imports(void);

/// @defgroup DictionaryResolutionResult "DictionaryResolutionResult"
/// @{
/// @brief Carries field-level dictionary resolution output with explicit review and partial-recovery state.
/// @}
void DictionaryResolutionResult(void);

/// @defgroup GitServiceModule "GitServiceModule"
/// @{
/// @brief Composed GitService via multiple inheritance from domain-specific mixins.
/// @}
void GitServiceModule(void);

/// @defgroup GitService "GitService"
/// @{
/// @brief Composed GitService class providing all Git operations — init, clone, branches, commits, push, pull,
/// @}
void GitService(void);

/// @defgroup GitServiceBase "GitServiceBase"
/// @{
/// @brief Core GitService base class — initialization, path resolution, repo lifecycle (init/delete/get), identity configuration, concurrent locking, and shared HTTP client pool.
/// @}
void GitServiceBase(void);

/// @defgroup GitServiceBranchMixin "GitServiceBranchMixin"
/// @{
/// @brief Branch and commit operations for GitService — gitflow branches, list/create/checkout branches, commit changes (all concurrent-safe via per-dashboard locks).
/// @}
void GitServiceBranchMixin(void);

/// @defgroup GitServiceGiteaMixin "GitServiceGiteaMixin"
/// @{
/// @brief Gitea API operations for GitService — connection testing, repository CRUD, and pull request creation. Uses shared self._http_client for connection pooling.
/// @}
void GitServiceGiteaMixin(void);

/// @defgroup GitServiceMergeMixin "GitServiceMergeMixin"
/// @{
/// @brief Merge operations for GitService — conflict detection, resolution, abort, continue, and direct promote (all concurrent-safe via per-dashboard locks).
/// @}
void GitServiceMergeMixin(void);

/// @defgroup GitServiceRemoteMixin "GitServiceRemoteMixin"
/// @{
/// @brief GitHub and GitLab provider operations for GitService — repository creation and PR/MR creation. Uses shared self._http_client for connection pooling.
/// @}
void GitServiceRemoteMixin(void);

/// @defgroup GitServiceGithubMixin "GitServiceGithubMixin"
/// @{
/// @brief Mixin providing GitHub API operations for GitService.
/// @}
void GitServiceGithubMixin(void);

/// @defgroup GitServiceGitlabMixin "GitServiceGitlabMixin"
/// @{
/// @brief Mixin providing GitLab API operations for GitService.
/// @}
void GitServiceGitlabMixin(void);

/// @defgroup GitServiceStatusMixin "GitServiceStatusMixin"
/// @{
/// @brief Status, diff, and commit history operations for GitService (all concurrent-safe via per-dashboard locks).
/// @}
void GitServiceStatusMixin(void);

/// @defgroup GitServiceSyncMixin "GitServiceSyncMixin"
/// @{
/// @brief Push and pull operations for GitService with origin host auto-alignment (concurrent-safe).
/// @}
void GitServiceSyncMixin(void);

/// @defgroup GitServiceUrlMixin "GitServiceUrlMixin"
/// @{
/// @brief URL helper mixin for GitService — parse, normalize, align, and strip credentials from Git URLs.
/// @}
void GitServiceUrlMixin(void);

/// @defgroup health_service "health_service"
/// @{
/// @brief Business logic for aggregating dashboard health status from validation records.
/// @}
void health_service(void);

/// @defgroup HealthService "HealthService"
/// @{
/// @brief Aggregate latest dashboard validation state and manage persisted health report lifecycle.
/// @post Exposes health summary aggregation and validation report deletion operations.
/// @pre Service is constructed with a live SQLAlchemy session and optional config manager.
/// @}
void HealthService(void);

/// @defgroup llm_prompt_templates "llm_prompt_templates"
/// @{
/// @brief Provide default LLM prompt templates and normalization helpers for runtime usage.
/// @invariant All required prompt template keys are always present after normalization.
/// @}
void llm_prompt_templates(void);

/// @defgroup DEFAULT_LLM_PROMPTS "DEFAULT_LLM_PROMPTS"
/// @{
/// @brief Default prompt templates used by documentation, dashboard validation, and git commit generation.
/// @}
void DEFAULT_LLM_PROMPTS(void);

/// @defgroup DEFAULT_LLM_PROVIDER_BINDINGS "DEFAULT_LLM_PROVIDER_BINDINGS"
/// @{
/// @brief Default provider binding per task domain.
/// @}
void DEFAULT_LLM_PROVIDER_BINDINGS(void);

/// @defgroup DEFAULT_LLM_ASSISTANT_SETTINGS "DEFAULT_LLM_ASSISTANT_SETTINGS"
/// @{
/// @brief Default planner settings for assistant chat intent model/provider resolution.
/// @}
void DEFAULT_LLM_ASSISTANT_SETTINGS(void);

/// @defgroup normalize_llm_settings "normalize_llm_settings"
/// @{
/// @brief Ensure llm settings contain stable schema with prompts section and default templates.
/// @post Returned dict contains prompts with all required template keys.
/// @pre llm_settings is dictionary-like value or None.
/// @}
void normalize_llm_settings(void);

/// @defgroup is_multimodal_model "is_multimodal_model"
/// @{
/// @brief Heuristically determine whether model supports image input required for dashboard validation.
/// @deprecated Use the explicit `db_provider.is_multimodal` flag instead (see migration 9f8e7d6c5b4a).
/// @}
void is_multimodal_model(void);

/// @defgroup resolve_bound_provider_id "resolve_bound_provider_id"
/// @{
/// @brief Resolve provider id configured for a task binding with fallback to default provider.
/// @post Returns configured provider id or fallback id/empty string when not defined.
/// @pre llm_settings is normalized or raw dict from config.
/// @}
void resolve_bound_provider_id(void);

/// @defgroup render_prompt "render_prompt"
/// @{
/// @brief Render prompt template using deterministic placeholder replacement with graceful fallback.
/// @post Returns rendered prompt text with known placeholders substituted. Warns about unfilled placeholders.
/// @pre template is a string and variables values are already stringifiable.
/// @}
void render_prompt(void);

/// @defgroup llm_provider "llm_provider"
/// @{
/// @brief Service for managing LLM provider configurations with encrypted API keys.
/// @}
void llm_provider(void);

/// @defgroup mask_api_key "mask_api_key"
/// @{
/// @brief Mask an API key for safe display, showing first 4 and last 4 characters.
/// @post Returns "****" for very short keys; "{first 2}...{last 2}" for <=8 chars;
/// @pre api_key is a plaintext string or None.
/// @}
void mask_api_key(void);

/// @defgroup is_masked_or_placeholder "is_masked_or_placeholder"
/// @{
/// @brief Predicate: True when api_key is None, empty, "********", or contains "...".
/// @post Returns True only for non-real-key values.
/// @pre api_key can be None.
/// @}
void is_masked_or_placeholder(void);

/// @defgroup _require_fernet_key "_require_fernet_key"
/// @{
/// @brief Load and validate the Fernet key used for secret encryption.
/// @invariant Encryption initialization never falls back to a hardcoded secret.
/// @post Returns validated key bytes ready for Fernet initialization.
/// @pre ENCRYPTION_KEY environment variable must be set to a valid Fernet key.
/// @}
void _require_fernet_key(void);

/// @defgroup EncryptionManager "EncryptionManager"
/// @{
/// @brief Handles encryption and decryption of sensitive data like API keys.
/// @invariant Uses only a validated secret key from environment.
/// @post Manager exposes reversible encrypt/decrypt operations for persisted secrets.
/// @pre ENCRYPTION_KEY is configured with a valid Fernet key before instantiation.
/// @}
void EncryptionManager(void);

/// @defgroup LLMProviderService "LLMProviderService"
/// @{
/// @brief Service to manage LLM provider lifecycle.
/// @}
void LLMProviderService(void);

/// @defgroup MaintenancePackage "MaintenancePackage"
/// @{
/// @brief Maintenance Banner service package. Re-exports all public orchestrators and helpers.
/// @}
void MaintenancePackage(void);

/// @defgroup MaintenanceBannerRenderer "MaintenanceBannerRenderer"
/// @{
/// @brief Banner text rendering and rebuild helpers. Build aggregated markdown from
/// @}
void MaintenanceBannerRenderer(void);

/// @defgroup build_banner_text "build_banner_text"
/// @{
/// @brief Build aggregated banner markdown text from events using settings template.
/// @}
void build_banner_text(void);

/// @defgroup _build_banner_text_for_dashboard "_build_banner_text_for_dashboard"
/// @{
/// @brief Build aggregated banner text for a banner based on all active events linked to it.
/// @}
void _build_banner_text_for_dashboard(void);

/// @defgroup rebuild_banner "rebuild_banner"
/// @{
/// @brief Rebuild aggregated banner text for a banner and update the Superset chart.
/// @}
void rebuild_banner(void);

/// @defgroup MaintenanceChartManager "MaintenanceChartManager"
/// @{
/// @brief Chart operations for maintenance banners: create/get banner charts, process
/// @}
void MaintenanceChartManager(void);

/// @defgroup ensure_banner_chart "ensure_banner_chart"
/// @{
/// @brief Get or create a MaintenanceDashboardBanner for a dashboard in the target environment.
/// @}
void ensure_banner_chart(void);

/// @defgroup _process_dashboards_for_start "_process_dashboards_for_start"
/// @{
/// @brief Process each dashboard for a start maintenance event: ensure banner chart,
/// @}
void _process_dashboards_for_start(void);

/// @defgroup _process_states_for_end "_process_states_for_end"
/// @{
/// @brief Process each dashboard state for an end maintenance event: if other events
/// @}
void _process_states_for_end(void);

/// @defgroup MaintenanceDashboardScanner "MaintenanceDashboardScanner"
/// @{
/// @brief Dashboard discovery and filtering helpers for maintenance banner feature.
/// @}
void MaintenanceDashboardScanner(void);

/// @defgroup find_affected_dashboards "find_affected_dashboards"
/// @{
/// @brief Find all dashboard IDs whose datasets reference any of the given tables.
/// @}
void find_affected_dashboards(void);

/// @defgroup _get_linked_dashboards "_get_linked_dashboards"
/// @{
/// @brief Fetch linked dashboards for a dataset from Superset.
/// @}
void _get_linked_dashboards(void);

/// @defgroup _apply_dashboard_filters "_apply_dashboard_filters"
/// @{
/// @brief Apply scope (published/draft/all), excluded, and forced filters from settings.
/// @}
void _apply_dashboard_filters(void);

/// @defgroup _resolve_dashboard_title "_resolve_dashboard_title"
/// @{
/// @brief Resolve dashboard title from Superset by ID.
/// @}
void _resolve_dashboard_title(void);

/// @defgroup MaintenanceOrchestrators "MaintenanceOrchestrators"
/// @{
/// @brief C4 orchestrators for maintenance event lifecycle: start, end, end-all.
/// @}
void MaintenanceOrchestrators(void);

/// @defgroup build_idempotency_key "build_idempotency_key"
/// @{
/// @brief Build idempotency key from (tables, start_time, end_time). Sorted lowercased tables, ISO timestamps.
/// @post Returns a tuple of (frozenset(str), str|None, str|None) for DB comparison.
/// @pre tables is a list of strings. start_time is a datetime or None. end_time is a datetime or None.
/// @}
void build_idempotency_key(void);

/// @defgroup mapping_service "mapping_service"
/// @{
/// @brief Orchestrates database fetching and fuzzy matching suggestions.
/// @invariant Suggestions are based on database names.
/// @post Exposes stateless mapping suggestion orchestration over configured environments.
/// @pre source/target environment identifiers are provided by caller.
/// @}
void mapping_service(void);

/// @defgroup MappingService "MappingService"
/// @{
/// @brief Service for handling database mapping logic.
/// @post Provides client resolution and mapping suggestion methods.
/// @pre config_manager exposes get_environments() with environment objects containing id.
/// @}
void MappingService(void);

/// @defgroup notifications "notifications"
/// @{
/// @brief Notification service package root.
/// @}
void notifications(void);

/// @defgroup providers "providers"
/// @{
/// @brief Defines abstract base and concrete implementations for external notification delivery.
/// @invariant Sensitive credentials must be handled via encrypted config.
/// @post Each provider exposes async send contract returning boolean delivery outcome.
/// @pre Provider configuration dictionaries are supplied by trusted configuration sources.
/// @}
void providers(void);

/// @defgroup NotificationProvider "NotificationProvider"
/// @{
/// @brief Abstract base class for all notification providers.
/// @}
void NotificationProvider(void);

/// @defgroup SMTPProvider "SMTPProvider"
/// @{
/// @brief Delivers notifications via SMTP.
/// @}
void SMTPProvider(void);

/// @defgroup TelegramProvider "TelegramProvider"
/// @{
/// @brief Delivers notifications via Telegram Bot API.
/// @}
void TelegramProvider(void);

/// @defgroup SlackProvider "SlackProvider"
/// @{
/// @brief Delivers notifications via Slack Webhooks or API.
/// @}
void SlackProvider(void);

/// @defgroup service "service"
/// @{
/// @brief Orchestrates notification routing based on user preferences and policy context.
/// @invariant NotificationService maintains singleton pattern for per-channel notifications
/// @post Notification dispatched via configured providers
/// @pre channel_config is loaded
/// @}
void service(void);

/// @defgroup NotificationService "NotificationService"
/// @{
/// @brief Routes validation reports to appropriate users and channels.
/// @post Service can resolve targets and dispatch provider sends without mutating validation records.
/// @pre Service receives a live DB session and configuration manager with notification payload settings.
/// @}
void NotificationService(void);

/// @defgroup profile_preference_service "profile_preference_service"
/// @{
/// @brief Profile preference persistence — read, update, and normalize user dashboard filter preferences
/// @}
void profile_preference_service(void);

/// @defgroup ProfilePreferenceService "ProfilePreferenceService"
/// @{
/// @brief Handles profile preference persistence, validation, and token encryption.
/// @post Preference CRUD operations are user-scoped and return normalized ProfilePreferenceResponse.
/// @pre db session is active.
/// @}
void ProfilePreferenceService(void);

/// @defgroup get_my_preference "get_my_preference"
/// @{
/// @brief Return current user's persisted preference or default non-configured view.
/// @post Returned payload belongs to current_user only.
/// @pre current_user is authenticated.
/// @}
void get_my_preference(void);

/// @defgroup get_dashboard_filter_binding "get_dashboard_filter_binding"
/// @{
/// @brief Return only dashboard-filter fields required by dashboards listing hot path.
/// @post Returns normalized username and profile-default filter toggles without security summary expansion.
/// @pre current_user is authenticated.
/// @}
void get_dashboard_filter_binding(void);

/// @defgroup update_my_preference "update_my_preference"
/// @{
/// @brief Validate and persist current user's profile preference in self-scoped mode.
/// @post Preference row for current_user is created/updated when validation passes.
/// @pre current_user is authenticated and payload is provided.
/// @}
void update_my_preference(void);

/// @defgroup _to_preference_payload "_to_preference_payload"
/// @{
/// @brief Map ORM preference row to API DTO with token metadata.
/// @post Returns normalized ProfilePreference object.
/// @pre preference row can contain nullable optional fields.
/// @}
void _to_preference_payload(void);

/// @defgroup _build_default_preference "_build_default_preference"
/// @{
/// @brief Delegate to ProfileUtils.build_default_preference.
/// @}
void _build_default_preference(void);

/// @defgroup _get_preference_row "_get_preference_row"
/// @{
/// @brief Return persisted preference row for user or None.
/// @}
void _get_preference_row(void);

/// @defgroup _get_or_create_preference_row "_get_or_create_preference_row"
/// @{
/// @brief Return existing preference row or create new unsaved row.
/// @}
void _get_or_create_preference_row(void);

/// @defgroup profile_service "profile_service"
/// @{
/// @brief Composite facade orchestrating profile preference persistence, Superset account lookup,
/// @}
void profile_service(void);

/// @defgroup ProfileService "ProfileService"
/// @{
/// @brief Facade that composes ProfilePreferenceService, SupersetLookupService, and
/// @}
void ProfileService(void);

/// @defgroup ProfileUtils "ProfileUtils"
/// @{
/// @brief Pure utility helpers for profile data sanitization, normalization, and secret masking.
/// @}
void ProfileUtils(void);

/// @defgroup ProfileValidationError "ProfileValidationError"
/// @{
/// @brief Domain validation error for profile preference update requests.
/// @}
void ProfileValidationError(void);

/// @defgroup EnvironmentNotFoundError "EnvironmentNotFoundError"
/// @{
/// @brief Raised when environment_id from lookup request is unknown in app configuration.
/// @}
void EnvironmentNotFoundError(void);

/// @defgroup ProfileAuthorizationError "ProfileAuthorizationError"
/// @{
/// @brief Raised when caller attempts cross-user preference mutation.
/// @}
void ProfileAuthorizationError(void);

/// @defgroup sanitize_text "sanitize_text"
/// @{
/// @brief Normalize optional text into trimmed form or None.
/// @}
void sanitize_text(void);

/// @defgroup sanitize_secret "sanitize_secret"
/// @{
/// @brief Normalize secret input into trimmed form or None.
/// @}
void sanitize_secret(void);

/// @defgroup sanitize_username "sanitize_username"
/// @{
/// @brief Normalize raw username into trimmed form or None for empty input.
/// @}
void sanitize_username(void);

/// @defgroup normalize_username "normalize_username"
/// @{
/// @brief Apply deterministic trim+lower normalization for actor matching.
/// @}
void normalize_username(void);

/// @defgroup normalize_start_page "normalize_start_page"
/// @{
/// @brief Normalize supported start page aliases to canonical values.
/// @}
void normalize_start_page(void);

/// @defgroup normalize_density "normalize_density"
/// @{
/// @brief Normalize supported density aliases to canonical values.
/// @}
void normalize_density(void);

/// @defgroup mask_secret_value "mask_secret_value"
/// @{
/// @brief Build a safe display value for sensitive secrets.
/// @}
void mask_secret_value(void);

/// @defgroup validate_update_payload "validate_update_payload"
/// @{
/// @brief Validate username/toggle constraints for preference mutation.
/// @post Returns validation errors list; empty list means valid.
/// @}
void validate_update_payload(void);

/// @defgroup build_default_preference "build_default_preference"
/// @{
/// @brief Build non-persisted default preference DTO for unconfigured users.
/// @}
void build_default_preference(void);

/// @defgroup normalize_owner_tokens "normalize_owner_tokens"
/// @{
/// @brief Normalize owners payload into deduplicated lower-cased tokens.
/// @}
void normalize_owner_tokens(void);

/// @defgroup rbac_permission_catalog "rbac_permission_catalog"
/// @{
/// @brief Discovers declared RBAC permissions from API routes/plugins and synchronizes them into auth database.
/// @}
void rbac_permission_catalog(void);

/// @defgroup HAS_PERMISSION_PATTERN "HAS_PERMISSION_PATTERN"
/// @{
/// @brief Regex pattern for extracting has_permission("resource", "ACTION") declarations.
/// @}
void HAS_PERMISSION_PATTERN(void);

/// @defgroup ROUTES_DIR "ROUTES_DIR"
/// @{
/// @brief Absolute directory path where API route RBAC declarations are defined.
/// @}
void ROUTES_DIR(void);

/// @defgroup _iter_route_files "_iter_route_files"
/// @{
/// @brief Iterates API route files that may contain RBAC declarations.
/// @post Yields Python files excluding test and cache directories.
/// @pre ROUTES_DIR points to backend/src/api/routes.
/// @}
void _iter_route_files(void);

/// @defgroup _discover_route_permissions "_discover_route_permissions"
/// @{
/// @brief Extracts explicit has_permission declarations from API route source code.
/// @post Returns unique set of (resource, action) pairs declared in route guards.
/// @pre Route files are readable UTF-8 text files.
/// @}
void _discover_route_permissions(void);

/// @defgroup _discover_route_permissions_cached "_discover_route_permissions_cached"
/// @{
/// @brief Cache route permission discovery because route source files are static during normal runtime.
/// @post Returns stable discovered route permission pairs without repeated filesystem scans.
/// @pre None.
/// @}
void _discover_route_permissions_cached(void);

/// @defgroup _discover_plugin_execute_permissions "_discover_plugin_execute_permissions"
/// @{
/// @brief Derives dynamic task permissions of form plugin:{plugin_id}:EXECUTE from plugin registry.
/// @post Returns unique plugin EXECUTE permissions if loader is available.
/// @pre plugin_loader is optional and may expose get_all_plugin_configs.
/// @}
void _discover_plugin_execute_permissions(void);

/// @defgroup _discover_plugin_execute_permissions_cached "_discover_plugin_execute_permissions_cached"
/// @{
/// @brief Cache dynamic plugin EXECUTE permission pairs by normalized plugin id tuple.
/// @post Returns stable permission tuple without repeated plugin catalog expansion.
/// @pre plugin_ids is a deterministic tuple of plugin ids.
/// @}
void _discover_plugin_execute_permissions_cached(void);

/// @defgroup discover_declared_permissions "discover_declared_permissions"
/// @{
/// @brief Builds canonical RBAC permission catalog from routes and plugin registry.
/// @post Returns union of route-declared and dynamic plugin EXECUTE permissions.
/// @pre plugin_loader may be provided for dynamic task plugin permission discovery.
/// @}
void discover_declared_permissions(void);

/// @defgroup sync_permission_catalog "sync_permission_catalog"
/// @{
/// @brief Persists missing RBAC permission pairs into auth database.
/// @post Missing permissions are inserted; existing permissions remain untouched.
/// @pre declared_permissions is an iterable of (resource, action) tuples.
/// @}
void sync_permission_catalog(void);

/// @defgroup reports "reports"
/// @{
/// @brief Report service package root.
/// @}
void reports(void);

/// @defgroup normalizer "normalizer"
/// @{
/// @brief Convert task manager task objects into canonical unified TaskReport entities with deterministic fallback behavior.
/// @invariant Normalizer instance maintains consistent field order
/// @post Returns Normalizer output with normalized fields
/// @pre session is active and valid
/// @}
void normalizer(void);

/// @defgroup status_to_report_status "status_to_report_status"
/// @{
/// @brief Normalize internal task status to canonical report status.
/// @post Always returns one of canonical ReportStatus values.
/// @pre status may be known or unknown string/enum value.
/// @}
void status_to_report_status(void);

/// @defgroup build_summary "build_summary"
/// @{
/// @brief Build deterministic user-facing summary from task payload and status.
/// @post Returns non-empty summary text.
/// @pre report_status is canonical; plugin_id may be unknown.
/// @}
void build_summary(void);

/// @defgroup extract_error_context "extract_error_context"
/// @{
/// @brief Extract normalized error context and next actions for failed/partial reports.
/// @post Returns ErrorContext for failed/partial when context exists; otherwise None.
/// @pre task is a valid Task object.
/// @}
void extract_error_context(void);

/// @defgroup normalize_task_report "normalize_task_report"
/// @{
/// @brief Convert one Task to canonical TaskReport envelope.
/// @post Returns TaskReport with required fields and deterministic fallback behavior.
/// @pre task has valid id and plugin_id fields.
/// @}
void normalize_task_report(void);

/// @defgroup report_service "report_service"
/// @{
/// @brief Aggregate, normalize, filter, and paginate task reports for unified list/detail API use cases.
/// @invariant ReportService maintains consistent report structure
/// @post Returns Report with generated summary
/// @pre session is active and valid
/// @}
void report_service(void);

/// @defgroup ReportsService "ReportsService"
/// @{
/// @brief Service layer for list/detail report retrieval and normalization.
/// @invariant Service methods are read-only over task history source.
/// @post Provides deterministic list/detail report responses.
/// @pre TaskManager dependency is initialized.
/// @}
void ReportsService(void);

/// @defgroup type_profiles "type_profiles"
/// @{
/// @brief Deterministic mapping of plugin/task identifiers to canonical report task types and fallback profile metadata.
/// @}
void type_profiles(void);

/// @defgroup PLUGIN_TO_TASK_TYPE "PLUGIN_TO_TASK_TYPE"
/// @{
/// @brief Maps plugin identifiers to normalized report task types.
/// @}
void PLUGIN_TO_TASK_TYPE(void);

/// @defgroup TASK_TYPE_PROFILES "TASK_TYPE_PROFILES"
/// @{
/// @brief Profile metadata registry for each normalized task type.
/// @}
void TASK_TYPE_PROFILES(void);

/// @defgroup resolve_task_type "resolve_task_type"
/// @{
/// @brief Resolve canonical task type from plugin/task identifier with guaranteed fallback.
/// @post Always returns one of TaskType enum values.
/// @pre plugin_id may be None or unknown.
/// @}
void resolve_task_type(void);

/// @defgroup get_type_profile "get_type_profile"
/// @{
/// @brief Return deterministic profile metadata for a task type.
/// @post Returns a profile dict and never raises for unknown types.
/// @pre task_type may be known or unknown.
/// @}
void get_type_profile(void);

/// @defgroup ResourceServiceModule "ResourceServiceModule"
/// @{
/// @brief Shared service for fetching resource data with Git status and task status
/// @invariant All resources include metadata about their current state
/// @}
void ResourceServiceModule(void);

/// @defgroup ResourceService "ResourceService"
/// @{
/// @brief Provides centralized access to resource data with enhanced metadata
/// @}
void ResourceService(void);

/// @defgroup security_badge_service "security_badge_service"
/// @{
/// @brief Builds security summary and permission badges for profile UI — role extraction,
/// @}
void security_badge_service(void);

/// @defgroup SecurityBadgeService "SecurityBadgeService"
/// @{
/// @brief Builds security summary with role names and permission badges for profile UI display.
/// @post build_security_summary returns ProfileSecuritySummary with deterministic sorted permissions.
/// @pre plugin_loader may be None for degraded permission discovery.
/// @}
void SecurityBadgeService(void);

/// @defgroup build_security_summary "build_security_summary"
/// @{
/// @brief Build read-only security snapshot with role and permission badges.
/// @post Returns deterministic security projection for profile UI.
/// @pre current_user is authenticated.
/// @}
void build_security_summary(void);

/// @defgroup _collect_user_permission_pairs "_collect_user_permission_pairs"
/// @{
/// @brief Collect effective permission tuples from current user's roles.
/// @post Returns unique normalized (resource, ACTION) tuples.
/// @pre current_user can include role/permission graph.
/// @}
void _collect_user_permission_pairs(void);

/// @defgroup _format_permission_key "_format_permission_key"
/// @{
/// @brief Convert normalized permission pair to compact UI key.
/// @}
void _format_permission_key(void);

/// @defgroup SqlTableExtractorModule "SqlTableExtractorModule"
/// @{
/// @brief Three-phase SQL+Jinja table name extractor for virtual datasets as per FR-003.
/// @}
void SqlTableExtractorModule(void);

/// @defgroup detect_jinja_spans "detect_jinja_spans"
/// @{
/// @brief Phase 1: Split raw SQL text into Jinja spans and SQL spans.
/// @post Returns a list of (span_type: str, text: str) tuples.
/// @pre raw_sql is a string (possibly empty).
/// @}
void detect_jinja_spans(void);

/// @defgroup extract_tables_from_jinja "extract_tables_from_jinja"
/// @{
/// @brief Phase 2: Extract "schema.table" references from Jinja string values.
/// @}
void extract_tables_from_jinja(void);

/// @defgroup is_string_literal "is_string_literal"
/// @{
/// @brief Check if a sqlparse Token is a string literal (not a schema.table identifier).
/// @post Returns True if the token is a string/Single/Literal.String.
/// @pre token is a sqlparse Token.
/// @}
void is_string_literal(void);

/// @defgroup extract_tables_from_sql_span "extract_tables_from_sql_span"
/// @{
/// @brief Phase 3: Extract schema.table references from SQL text using regex + sqlparse filtering.
/// @}
void extract_tables_from_sql_span(void);

/// @defgroup extract_tables_from_sql "extract_tables_from_sql"
/// @{
/// @brief Three-phase entry point: extract all schema.table references from raw SQL+Jinja text.
/// @post Returns a set of lowercased fully-qualified table names (schema.table format).
/// @pre raw_sql is a string (possibly empty).
/// @}
void extract_tables_from_sql(void);

/// @defgroup superset_lookup_service "superset_lookup_service"
/// @{
/// @brief Environment-scoped Superset account lookup with degradation fallback for network failures.
/// @}
void superset_lookup_service(void);

/// @defgroup SupersetLookupService "SupersetLookupService"
/// @{
/// @brief Resolves environments and queries Superset users in selected environment,
/// @}
void SupersetLookupService(void);

/// @defgroup _resolve_environment "_resolve_environment"
/// @{
/// @brief Resolve environment model from configured environments by id.
/// @post Returns environment object when found else None.
/// @pre environment_id is provided.
/// @}
void _resolve_environment(void);

/// @defgroup ValidationRunService "ValidationRunService"
/// @{
/// @brief Business logic for validation run queries: list, detail, delete.
/// @}
void ValidationRunService(void);

/// @defgroup _resolve_task_name "_resolve_task_name"
/// @{
/// @}
void _resolve_task_name(void);

/// @defgroup ValidationService "ValidationService"
/// @{
/// @brief Business logic for validation task CRUD and trigger-run.
/// @}
void ValidationService(void);

/// @defgroup ValidationTaskService "ValidationTaskService"
/// @{
/// @brief Validation task (policy) CRUD with provider validation and trigger-run.
/// @}
void ValidationTaskService(void);

/// @defgroup _validate_provider "_validate_provider"
/// @{
/// @}
void _validate_provider(void);

/// @defgroup _validate_environment "_validate_environment"
/// @{
/// @}
void _validate_environment(void);

/// @defgroup _policy_to_response "_policy_to_response"
/// @{
/// @}
void _policy_to_response(void);

/// @defgroup TestSessionConfig "TestSessionConfig"
/// @{
/// @brief Shared pytest fixtures and session configuration for backend tests.
/// @post Database tables exist before test session executes.
/// @pre All test modules use sys.path patching to import from src/.
/// @}
void TestSessionConfig(void);

/// @defgroup TestArchiveParser "TestArchiveParser"
/// @{
/// @brief Unit tests for MigrationArchiveParser ZIP extraction contract.
/// @}
void TestArchiveParser(void);

/// @defgroup test_extract_objects_from_zip_collects_all_types "test_extract_objects_from_zip_collects_all_types"
/// @{
/// @brief Verify archive parser collects dashboard/chart/dataset YAML objects into typed buckets.
/// @}
void test_extract_objects_from_zip_collects_all_types(void);

/// @defgroup TestDryRunOrchestrator "TestDryRunOrchestrator"
/// @{
/// @brief Unit tests for MigrationDryRunService diff and risk computation contracts.
/// @}
void TestDryRunOrchestrator(void);

/// @defgroup _load_fixture "_load_fixture"
/// @{
/// @brief Load canonical migration dry-run fixture payload used by deterministic orchestration assertions.
/// @}
void _load_fixture(void);

/// @defgroup test_migration_dry_run_service_builds_diff_and_risk "test_migration_dry_run_service_builds_diff_and_risk"
/// @{
/// @brief Verify dry-run orchestration returns stable diff summary and required risk codes.
/// @}
void test_migration_dry_run_service_builds_diff_and_risk(void);

/// @defgroup test_git_service_get_repo_path_guard "test_git_service_get_repo_path_guard"
/// @{
/// @}
void test_git_service_get_repo_path_guard(void);

/// @defgroup test_git_service_get_repo_path_recreates_base_dir "test_git_service_get_repo_path_recreates_base_dir"
/// @{
/// @}
void test_git_service_get_repo_path_recreates_base_dir(void);

/// @defgroup test_superset_client_import_dashboard_guard "test_superset_client_import_dashboard_guard"
/// @{
/// @}
void test_superset_client_import_dashboard_guard(void);

/// @defgroup test_git_service_init_repo_reclones_when_path_is_not_a_git_repo "test_git_service_init_repo_reclones_when_path_is_not_a_git_repo"
/// @{
/// @}
void test_git_service_init_repo_reclones_when_path_is_not_a_git_repo(void);

/// @defgroup test_git_service_ensure_gitflow_branches_creates_and_pushes_missing_defaults "test_git_service_ensure_gitflow_branches_creates_and_pushes_missing_defaults"
/// @{
/// @}
void test_git_service_ensure_gitflow_branches_creates_and_pushes_missing_defaults(void);

/// @defgroup test_git_service_configure_identity_updates_repo_local_config "test_git_service_configure_identity_updates_repo_local_config"
/// @{
/// @}
void test_git_service_configure_identity_updates_repo_local_config(void);

/// @defgroup TestGitServiceGiteaPr "TestGitServiceGiteaPr"
/// @{
/// @brief Validate Gitea PR creation fallback behavior when configured server URL is stale.
/// @invariant A 404 from primary Gitea URL retries once against remote-url host when different.
/// @}
void TestGitServiceGiteaPr(void);

/// @defgroup test_derive_server_url_from_remote_strips_credentials "test_derive_server_url_from_remote_strips_credentials"
/// @{
/// @brief Ensure helper returns host base URL and removes embedded credentials.
/// @post Result is scheme+host only.
/// @pre remote_url is an https URL with username/token.
/// @}
void test_derive_server_url_from_remote_strips_credentials(void);

/// @defgroup test_create_gitea_pull_request_retries_with_remote_host_on_404 "test_create_gitea_pull_request_retries_with_remote_host_on_404"
/// @{
/// @brief Verify create_gitea_pull_request retries with remote URL host after primary 404.
/// @post Method returns success payload from fallback request.
/// @pre primary server_url differs from remote_url host.
/// @}
void test_create_gitea_pull_request_retries_with_remote_host_on_404(void);

/// @defgroup test_create_gitea_pull_request_returns_branch_error_when_target_missing "test_create_gitea_pull_request_returns_branch_error_when_target_missing"
/// @{
/// @brief Ensure Gitea 404 on PR creation is mapped to actionable target-branch validation error.
/// @post Service raises HTTPException 400 with explicit missing target branch message.
/// @pre PR create call returns 404 and target branch is absent.
/// @}
void test_create_gitea_pull_request_returns_branch_error_when_target_missing(void);

/// @defgroup TestMappingService "TestMappingService"
/// @{
/// @brief Unit tests for the IdMappingService matching UUIDs to integer IDs.
/// @}
void TestMappingService(void);

/// @defgroup test_sync_environment_upserts_correctly "test_sync_environment_upserts_correctly"
/// @{
/// @}
void test_sync_environment_upserts_correctly(void);

/// @defgroup test_get_remote_id_returns_integer "test_get_remote_id_returns_integer"
/// @{
/// @}
void test_get_remote_id_returns_integer(void);

/// @defgroup test_get_remote_ids_batch_returns_dict "test_get_remote_ids_batch_returns_dict"
/// @{
/// @}
void test_get_remote_ids_batch_returns_dict(void);

/// @defgroup test_sync_environment_updates_existing_mapping "test_sync_environment_updates_existing_mapping"
/// @{
/// @}
void test_sync_environment_updates_existing_mapping(void);

/// @defgroup test_sync_environment_skips_resources_without_uuid "test_sync_environment_skips_resources_without_uuid"
/// @{
/// @}
void test_sync_environment_skips_resources_without_uuid(void);

/// @defgroup test_sync_environment_handles_api_error_gracefully "test_sync_environment_handles_api_error_gracefully"
/// @{
/// @}
void test_sync_environment_handles_api_error_gracefully(void);

/// @defgroup test_get_remote_id_returns_none_for_missing "test_get_remote_id_returns_none_for_missing"
/// @{
/// @}
void test_get_remote_id_returns_none_for_missing(void);

/// @defgroup test_get_remote_ids_batch_returns_empty_for_empty_input "test_get_remote_ids_batch_returns_empty_for_empty_input"
/// @{
/// @}
void test_get_remote_ids_batch_returns_empty_for_empty_input(void);

/// @defgroup test_mapping_service_alignment_with_test_data "test_mapping_service_alignment_with_test_data"
/// @{
/// @}
void test_mapping_service_alignment_with_test_data(void);

/// @defgroup test_sync_environment_requires_existing_env "test_sync_environment_requires_existing_env"
/// @{
/// @}
void test_sync_environment_requires_existing_env(void);

/// @defgroup test_sync_environment_deletes_stale_mappings "test_sync_environment_deletes_stale_mappings"
/// @{
/// @}
void test_sync_environment_deletes_stale_mappings(void);

/// @defgroup TestMigrationEngine "TestMigrationEngine"
/// @{
/// @brief Unit tests for MigrationEngine's cross-filter patching algorithms.
/// @}
void TestMigrationEngine(void);

/// @defgroup MockMappingService "MockMappingService"
/// @{
/// @brief Deterministic mapping service double for native filter ID remapping scenarios.
/// @invariant Returns mappings only for requested UUID keys present in seeded map.
/// @}
void MockMappingService(void);

/// @defgroup _write_dashboard_yaml "_write_dashboard_yaml"
/// @{
/// @brief Serialize dashboard metadata into YAML fixture with json_metadata payload for patch tests.
/// @}
void _write_dashboard_yaml(void);

/// @defgroup test_patch_dashboard_metadata_replaces_chart_ids "test_patch_dashboard_metadata_replaces_chart_ids"
/// @{
/// @brief Verify native filter target chartId values are remapped via mapping service results.
/// @}
void test_patch_dashboard_metadata_replaces_chart_ids(void);

/// @defgroup test_patch_dashboard_metadata_replaces_dataset_ids "test_patch_dashboard_metadata_replaces_dataset_ids"
/// @{
/// @brief Verify native filter target datasetId values are remapped via mapping service results.
/// @}
void test_patch_dashboard_metadata_replaces_dataset_ids(void);

/// @defgroup test_patch_dashboard_metadata_skips_when_no_metadata "test_patch_dashboard_metadata_skips_when_no_metadata"
/// @{
/// @brief Ensure dashboard files without json_metadata are left unchanged by metadata patching.
/// @}
void test_patch_dashboard_metadata_skips_when_no_metadata(void);

/// @defgroup test_patch_dashboard_metadata_handles_missing_targets "test_patch_dashboard_metadata_handles_missing_targets"
/// @{
/// @brief Verify patching updates mapped targets while preserving unmapped native filter IDs.
/// @}
void test_patch_dashboard_metadata_handles_missing_targets(void);

/// @defgroup test_extract_chart_uuids_from_archive "test_extract_chart_uuids_from_archive"
/// @{
/// @brief Verify chart archive scan returns complete local chart id-to-uuid mapping.
/// @}
void test_extract_chart_uuids_from_archive(void);

/// @defgroup test_transform_yaml_replaces_database_uuid "test_transform_yaml_replaces_database_uuid"
/// @{
/// @brief Ensure dataset YAML database_uuid fields are replaced when source UUID mapping exists.
/// @}
void test_transform_yaml_replaces_database_uuid(void);

/// @defgroup test_transform_yaml_ignores_unmapped_uuid "test_transform_yaml_ignores_unmapped_uuid"
/// @{
/// @brief Ensure transform_yaml leaves dataset files untouched when database_uuid is not mapped.
/// @}
void test_transform_yaml_ignores_unmapped_uuid(void);

/// @defgroup test_transform_zip_end_to_end "test_transform_zip_end_to_end"
/// @{
/// @brief Validate full ZIP transform pipeline remaps datasets and dashboard cross-filter chart IDs.
/// @}
void test_transform_zip_end_to_end(void);

/// @defgroup test_transform_zip_invalid_path "test_transform_zip_invalid_path"
/// @{
/// @brief Verify transform_zip returns False when source archive path does not exist.
/// @}
void test_transform_zip_invalid_path(void);

/// @defgroup test_transform_yaml_nonexistent_file "test_transform_yaml_nonexistent_file"
/// @{
/// @brief Verify transform_yaml raises FileNotFoundError for missing YAML source files.
/// @}
void test_transform_yaml_nonexistent_file(void);

/// @defgroup test_clean_release_cli "test_clean_release_cli"
/// @{
/// @brief Smoke tests for the redesigned clean release CLI.
/// @}
void test_clean_release_cli(void);

/// @defgroup test_cli_candidate_register_scaffold "test_cli_candidate_register_scaffold"
/// @{
/// @brief Verify candidate-register command exits successfully for valid required arguments.
/// @}
void test_cli_candidate_register_scaffold(void);

/// @defgroup test_cli_manifest_build_scaffold "test_cli_manifest_build_scaffold"
/// @{
/// @brief Verify candidate-register/artifact-import/manifest-build smoke path succeeds end-to-end.
/// @}
void test_cli_manifest_build_scaffold(void);

/// @defgroup test_cli_compliance_run_scaffold "test_cli_compliance_run_scaffold"
/// @{
/// @brief Verify compliance run/status/violations/report commands complete for prepared candidate.
/// @invariant SimpleNamespace substitutes for GlobalSettings — any field rename in GlobalSettings will silently not propagate here; re-verify on GlobalSettings schema changes.
/// @}
void test_cli_compliance_run_scaffold(void);

/// @defgroup test_cli_release_gate_commands_scaffold "test_cli_release_gate_commands_scaffold"
/// @{
/// @brief Verify approve/reject/publish/revoke release-gate commands execute with valid fixtures.
/// @}
void test_cli_release_gate_commands_scaffold(void);

/// @defgroup TestCleanReleaseTui "TestCleanReleaseTui"
/// @{
/// @brief Unit tests for the interactive curses TUI of the clean release process.
/// @invariant TUI initializes, handles hotkeys (F5, F10) and safely falls back without TTY.
/// @}
void TestCleanReleaseTui(void);

/// @defgroup test_headless_fallback "test_headless_fallback"
/// @{
/// @}
void test_headless_fallback(void);

/// @defgroup test_tui_initial_render "test_tui_initial_render"
/// @{
/// @}
void test_tui_initial_render(void);

/// @defgroup test_tui_run_checks_f5 "test_tui_run_checks_f5"
/// @{
/// @}
void test_tui_run_checks_f5(void);

/// @defgroup test_tui_exit_f10 "test_tui_exit_f10"
/// @{
/// @}
void test_tui_exit_f10(void);

/// @defgroup test_tui_clear_history_f7 "test_tui_clear_history_f7"
/// @{
/// @}
void test_tui_clear_history_f7(void);

/// @defgroup test_tui_real_mode_bootstrap_imports_artifacts_catalog "test_tui_real_mode_bootstrap_imports_artifacts_catalog"
/// @{
/// @}
void test_tui_real_mode_bootstrap_imports_artifacts_catalog(void);

/// @defgroup test_clean_release_tui_v2 "test_clean_release_tui_v2"
/// @{
/// @brief Smoke tests for thin-client TUI action dispatch and blocked transition behavior.
/// @}
void test_clean_release_tui_v2(void);

/// @defgroup _build_mock_stdscr "_build_mock_stdscr"
/// @{
/// @brief Build deterministic curses screen mock with default terminal geometry and exit key.
/// @}
void _build_mock_stdscr(void);

/// @defgroup test_tui_f5_dispatches_run_action "test_tui_f5_dispatches_run_action"
/// @{
/// @brief Verify F5 key dispatch invokes run_checks exactly once before graceful exit.
/// @}
void test_tui_f5_dispatches_run_action(void);

/// @defgroup test_tui_f5_run_smoke_reports_blocked_state "test_tui_f5_run_smoke_reports_blocked_state"
/// @{
/// @brief Verify blocked compliance state is surfaced after F5-triggered run action.
/// @}
void test_tui_f5_run_smoke_reports_blocked_state(void);

/// @defgroup test_tui_non_tty_refuses_startup "test_tui_non_tty_refuses_startup"
/// @{
/// @brief Verify non-TTY execution returns exit code 2 with actionable stderr guidance.
/// @}
void test_tui_non_tty_refuses_startup(void);

/// @defgroup test_tui_f8_blocked_without_facade_binding "test_tui_f8_blocked_without_facade_binding"
/// @{
/// @brief Verify F8 path reports disabled action instead of mutating hidden facade state.
/// @}
void test_tui_f8_blocked_without_facade_binding(void);

/// @defgroup TestApprovalService "TestApprovalService"
/// @{
/// @brief Define approval gate contracts for approve/reject operations over immutable compliance evidence.
/// @invariant Approval is allowed only for PASSED report bound to candidate; duplicate approve and foreign report must be rejected.
/// @}
void TestApprovalService(void);

/// @defgroup _seed_candidate_with_report "_seed_candidate_with_report"
/// @{
/// @brief Seed candidate and report fixtures for approval gate tests.
/// @post Repository contains candidate and report linked by candidate_id.
/// @pre candidate_id and report_id are non-empty.
/// @}
void _seed_candidate_with_report(void);

/// @defgroup test_approve_rejects_blocked_report "test_approve_rejects_blocked_report"
/// @{
/// @brief Ensure approve is rejected when latest report final status is not PASSED.
/// @post approve_candidate raises ApprovalGateError.
/// @pre Candidate has BLOCKED report.
/// @}
void test_approve_rejects_blocked_report(void);

/// @defgroup test_approve_rejects_foreign_report "test_approve_rejects_foreign_report"
/// @{
/// @brief Ensure approve is rejected when report belongs to another candidate.
/// @post approve_candidate raises ApprovalGateError.
/// @pre Candidate exists, report candidate_id differs.
/// @}
void test_approve_rejects_foreign_report(void);

/// @defgroup test_approve_rejects_duplicate_approve "test_approve_rejects_duplicate_approve"
/// @{
/// @brief Ensure repeated approve decision for same candidate is blocked.
/// @post Second approve_candidate call raises ApprovalGateError.
/// @pre Candidate has already been approved once.
/// @}
void test_approve_rejects_duplicate_approve(void);

/// @defgroup test_reject_persists_decision_without_promoting_candidate_state "test_reject_persists_decision_without_promoting_candidate_state"
/// @{
/// @brief Ensure reject decision is immutable and does not promote candidate to APPROVED.
/// @post reject_candidate persists REJECTED decision; candidate status remains unchanged.
/// @pre Candidate has PASSED report and CHECK_PASSED lifecycle state.
/// @}
void test_reject_persists_decision_without_promoting_candidate_state(void);

/// @defgroup test_reject_then_publish_is_blocked "test_reject_then_publish_is_blocked"
/// @{
/// @brief Ensure latest REJECTED decision blocks publication gate.
/// @post publish_candidate raises PublicationGateError.
/// @pre Candidate is rejected for passed report.
/// @}
void test_reject_then_publish_is_blocked(void);

/// @defgroup test_candidate_manifest_services "test_candidate_manifest_services"
/// @{
/// @brief Test lifecycle and manifest versioning for release candidates.
/// @}
void test_candidate_manifest_services(void);

/// @defgroup test_candidate_lifecycle_transitions "test_candidate_lifecycle_transitions"
/// @{
/// @brief Verify release candidate allows legal status transitions and rejects forbidden back-transitions.
/// @}
void test_candidate_lifecycle_transitions(void);

/// @defgroup test_manifest_versioning_and_immutability "test_manifest_versioning_and_immutability"
/// @{
/// @brief Verify manifest versions increment monotonically and older snapshots remain queryable.
/// @}
void test_manifest_versioning_and_immutability(void);

/// @defgroup _valid_artifacts "_valid_artifacts"
/// @{
/// @brief Provide canonical valid artifact payload used by candidate registration tests.
/// @}
void _valid_artifacts(void);

/// @defgroup test_register_candidate_rejects_duplicate_candidate_id "test_register_candidate_rejects_duplicate_candidate_id"
/// @{
/// @brief Verify duplicate candidate_id registration is rejected by service invariants.
/// @}
void test_register_candidate_rejects_duplicate_candidate_id(void);

/// @defgroup test_register_candidate_rejects_malformed_artifact_input "test_register_candidate_rejects_malformed_artifact_input"
/// @{
/// @brief Verify candidate registration rejects artifact payloads missing required fields.
/// @}
void test_register_candidate_rejects_malformed_artifact_input(void);

/// @defgroup test_register_candidate_rejects_empty_artifact_set "test_register_candidate_rejects_empty_artifact_set"
/// @{
/// @brief Verify candidate registration rejects empty artifact collections.
/// @}
void test_register_candidate_rejects_empty_artifact_set(void);

/// @defgroup test_manifest_service_rebuild_creates_new_version "test_manifest_service_rebuild_creates_new_version"
/// @{
/// @brief Verify repeated manifest build creates a new incremented immutable version.
/// @}
void test_manifest_service_rebuild_creates_new_version(void);

/// @defgroup test_manifest_service_existing_manifest_cannot_be_mutated "test_manifest_service_existing_manifest_cannot_be_mutated"
/// @{
/// @brief Verify existing manifest snapshot remains immutable when rebuilding newer manifest version.
/// @}
void test_manifest_service_existing_manifest_cannot_be_mutated(void);

/// @defgroup test_manifest_service_rejects_missing_candidate "test_manifest_service_rejects_missing_candidate"
/// @{
/// @brief Verify manifest build fails with missing candidate identifier.
/// @}
void test_manifest_service_rejects_missing_candidate(void);

/// @defgroup TestComplianceExecutionService "TestComplianceExecutionService"
/// @{
/// @brief Validate stage pipeline and run finalization contracts for compliance execution.
/// @invariant Missing manifest prevents run startup; failed execution cannot finalize as PASSED.
/// @}
void TestComplianceExecutionService(void);

/// @defgroup _seed_with_candidate_policy_registry "_seed_with_candidate_policy_registry"
/// @{
/// @brief Build deterministic repository state for run startup tests.
/// @post Returns repository with candidate, policy and registry; manifest is optional.
/// @pre candidate_id and snapshot ids are non-empty.
/// @}
void _seed_with_candidate_policy_registry(void);

/// @defgroup test_run_without_manifest_rejected "test_run_without_manifest_rejected"
/// @{
/// @brief Ensure compliance run cannot start when manifest is unresolved.
/// @post start_check_run raises ValueError and no run is persisted.
/// @pre Candidate/policy exist but manifest is missing.
/// @}
void test_run_without_manifest_rejected(void);

/// @defgroup test_task_crash_mid_run_marks_failed "test_task_crash_mid_run_marks_failed"
/// @{
/// @brief Ensure execution crash conditions force FAILED run status.
/// @post execute_stages persists run with FAILED status.
/// @pre Run exists, then required dependency becomes unavailable before execute_stages.
/// @}
void test_task_crash_mid_run_marks_failed(void);

/// @defgroup test_blocked_run_finalization_blocks_report_builder "test_blocked_run_finalization_blocks_report_builder"
/// @{
/// @brief Ensure blocked runs require blocking violations before report creation.
/// @post finalize keeps BLOCKED and report_builder rejects zero blocking violations.
/// @pre Manifest contains prohibited artifacts leading to BLOCKED decision.
/// @}
void test_blocked_run_finalization_blocks_report_builder(void);

/// @defgroup TestComplianceTaskIntegration "TestComplianceTaskIntegration"
/// @{
/// @brief Verify clean release compliance runs execute through TaskManager lifecycle with observable success/failure outcomes.
/// @invariant Compliance execution triggered as task produces terminal task status and persists run evidence.
/// @}
void TestComplianceTaskIntegration(void);

/// @defgroup _seed_repository "_seed_repository"
/// @{
/// @brief Prepare deterministic candidate/policy/registry/manifest fixtures for task integration tests.
/// @post Returns initialized repository and identifiers for compliance run startup.
/// @pre with_manifest controls manifest availability.
/// @}
void _seed_repository(void);

/// @defgroup CleanReleaseCompliancePlugin "CleanReleaseCompliancePlugin"
/// @{
/// @brief TaskManager plugin shim that executes clean release compliance orchestration.
/// @}
void CleanReleaseCompliancePlugin(void);

/// @defgroup _PluginLoaderStub "_PluginLoaderStub"
/// @{
/// @brief Provide minimal plugin loader contract used by TaskManager in integration tests.
/// @invariant has_plugin/get_plugin only acknowledge the seeded compliance plugin id.
/// @}
void _PluginLoaderStub(void);

/// @defgroup _make_task_manager "_make_task_manager"
/// @{
/// @brief Build TaskManager with mocked persistence services for isolated integration tests.
/// @post Returns TaskManager ready for async task execution.
/// @}
void _make_task_manager(void);

/// @defgroup _wait_for_terminal_task "_wait_for_terminal_task"
/// @{
/// @brief Poll task registry until target task reaches terminal status.
/// @post Returns task with SUCCESS or FAILED status, otherwise raises TimeoutError.
/// @pre task_id exists in manager registry.
/// @}
void _wait_for_terminal_task(void);

/// @defgroup test_compliance_run_executes_as_task_manager_task "test_compliance_run_executes_as_task_manager_task"
/// @{
/// @brief Verify successful compliance execution is observable as TaskManager SUCCESS task.
/// @post Task ends with SUCCESS; run is persisted with SUCCEEDED status and task binding.
/// @pre Candidate, policy and manifest are available in repository.
/// @}
void test_compliance_run_executes_as_task_manager_task(void);

/// @defgroup test_compliance_run_missing_manifest_marks_task_failed "test_compliance_run_missing_manifest_marks_task_failed"
/// @{
/// @brief Verify missing manifest startup failure is surfaced as TaskManager FAILED task.
/// @post Task ends with FAILED and run history remains empty.
/// @pre Candidate/policy exist but manifest is absent.
/// @}
void test_compliance_run_missing_manifest_marks_task_failed(void);

/// @defgroup TestDemoModeIsolation "TestDemoModeIsolation"
/// @{
/// @brief Verify demo and real mode namespace isolation contracts before TUI integration.
/// @}
void TestDemoModeIsolation(void);

/// @defgroup test_resolve_namespace_separates_demo_and_real "test_resolve_namespace_separates_demo_and_real"
/// @{
/// @brief Ensure namespace resolver returns deterministic and distinct namespaces.
/// @post Demo and real namespaces are different and stable.
/// @pre Mode names are provided as user/runtime strings.
/// @}
void test_resolve_namespace_separates_demo_and_real(void);

/// @defgroup test_build_namespaced_id_prevents_cross_mode_collisions "test_build_namespaced_id_prevents_cross_mode_collisions"
/// @{
/// @brief Ensure ID generation prevents demo/real collisions for identical logical IDs.
/// @post Produced physical IDs differ by namespace prefix.
/// @pre Same logical candidate id is used in two different namespaces.
/// @}
void test_build_namespaced_id_prevents_cross_mode_collisions(void);

/// @defgroup test_create_isolated_repository_keeps_mode_data_separate "test_create_isolated_repository_keeps_mode_data_separate"
/// @{
/// @brief Verify demo and real repositories do not leak state across mode boundaries.
/// @post Candidate mutations in one mode are not visible in the other mode.
/// @pre Two repositories are created for distinct modes.
/// @}
void test_create_isolated_repository_keeps_mode_data_separate(void);

/// @defgroup TestPolicyResolutionService "TestPolicyResolutionService"
/// @{
/// @brief Verify trusted policy snapshot resolution contract and error guards.
/// @invariant Resolution uses only ConfigManager active IDs and rejects runtime override attempts.
/// @}
void TestPolicyResolutionService(void);

/// @defgroup _config_manager "_config_manager"
/// @{
/// @brief Build deterministic ConfigManager-like stub for tests.
/// @invariant Only settings.clean_release.active_policy_id and active_registry_id are populated; any other settings field access raises AttributeError.
/// @post Returns object exposing get_config().settings.clean_release active IDs.
/// @pre policy_id and registry_id may be None or non-empty strings.
/// @}
void _config_manager(void);

/// @defgroup test_resolve_trusted_policy_snapshots_missing_profile "test_resolve_trusted_policy_snapshots_missing_profile"
/// @{
/// @brief Ensure resolution fails when trusted profile is not configured.
/// @post Raises PolicyResolutionError with missing trusted profile reason.
/// @pre active_policy_id is None.
/// @}
void test_resolve_trusted_policy_snapshots_missing_profile(void);

/// @defgroup test_resolve_trusted_policy_snapshots_missing_registry "test_resolve_trusted_policy_snapshots_missing_registry"
/// @{
/// @brief Ensure resolution fails when trusted registry is not configured.
/// @post Raises PolicyResolutionError with missing trusted registry reason.
/// @pre active_registry_id is None and active_policy_id is set.
/// @}
void test_resolve_trusted_policy_snapshots_missing_registry(void);

/// @defgroup test_resolve_trusted_policy_snapshots_rejects_override_attempt "test_resolve_trusted_policy_snapshots_rejects_override_attempt"
/// @{
/// @brief Ensure runtime override attempt is rejected even if snapshots exist.
/// @post Raises PolicyResolutionError with override forbidden reason.
/// @pre valid trusted snapshots exist in repository and override is provided.
/// @}
void test_resolve_trusted_policy_snapshots_rejects_override_attempt(void);

/// @defgroup TestPublicationService "TestPublicationService"
/// @{
/// @brief Define publication gate contracts over approved candidates and immutable publication records.
/// @invariant Publish requires approval; revoke requires existing publication; republish after revoke is allowed as a new record.
/// @}
void TestPublicationService(void);

/// @defgroup _seed_candidate_with_passed_report "_seed_candidate_with_passed_report"
/// @{
/// @brief Seed candidate/report fixtures for publication gate scenarios.
/// @post Repository contains candidate and PASSED report.
/// @pre candidate_id and report_id are non-empty.
/// @}
void _seed_candidate_with_passed_report(void);

/// @defgroup test_publish_without_approval_rejected "test_publish_without_approval_rejected"
/// @{
/// @brief Ensure publish action is blocked until candidate is approved.
/// @post publish_candidate raises PublicationGateError.
/// @pre Candidate has PASSED report but status is not APPROVED.
/// @}
void test_publish_without_approval_rejected(void);

/// @defgroup test_revoke_unknown_publication_rejected "test_revoke_unknown_publication_rejected"
/// @{
/// @brief Ensure revocation is rejected for unknown publication id.
/// @post revoke_publication raises PublicationGateError.
/// @pre Repository has no matching publication record.
/// @}
void test_revoke_unknown_publication_rejected(void);

/// @defgroup test_republish_after_revoke_creates_new_active_record "test_republish_after_revoke_creates_new_active_record"
/// @{
/// @brief Ensure republish after revoke is allowed and creates a new ACTIVE record.
/// @post New publish call returns distinct publication id with ACTIVE status.
/// @pre Candidate is APPROVED and first publication has been revoked.
/// @}
void test_republish_after_revoke_creates_new_active_record(void);

/// @defgroup TestReportAuditImmutability "TestReportAuditImmutability"
/// @{
/// @brief Validate report snapshot immutability expectations and append-only audit hook behavior for US2.
/// @invariant Built reports are immutable snapshots; audit hooks produce append-only event traces.
/// @}
void TestReportAuditImmutability(void);

/// @defgroup _terminal_run "_terminal_run"
/// @{
/// @brief Build deterministic terminal run fixture for report snapshot tests.
/// @post Returns a terminal ComplianceRun suitable for report generation.
/// @pre final_status is a valid ComplianceDecision value.
/// @}
void _terminal_run(void);

/// @defgroup test_report_builder_sets_immutable_snapshot_flag "test_report_builder_sets_immutable_snapshot_flag"
/// @{
/// @brief Ensure generated report payload is marked immutable and persisted as snapshot.
/// @post Built report has immutable=True and repository stores same immutable object.
/// @pre Terminal run exists.
/// @}
void test_report_builder_sets_immutable_snapshot_flag(void);

/// @defgroup test_repository_rejects_report_overwrite_for_same_report_id "test_repository_rejects_report_overwrite_for_same_report_id"
/// @{
/// @brief Define immutability contract that report snapshots cannot be overwritten by same identifier.
/// @post Second save for same report id is rejected with explicit immutability error.
/// @pre Existing report with id is already persisted.
/// @}
void test_repository_rejects_report_overwrite_for_same_report_id(void);

/// @defgroup test_audit_hooks_emit_append_only_event_stream "test_audit_hooks_emit_append_only_event_stream"
/// @{
/// @brief Verify audit hooks emit one event per action call and preserve call order.
/// @post Three calls produce three ordered info entries with molecular prefixes.
/// @pre Logger backend is patched.
/// @}
void test_audit_hooks_emit_append_only_event_stream(void);

/// @defgroup SupersetCompatibilityMatrixTests "SupersetCompatibilityMatrixTests"
/// @{
/// @brief Verifies Superset preview and SQL Lab endpoint fallback strategy used by dataset-review orchestration.
/// @}
void SupersetCompatibilityMatrixTests(void);

/// @defgroup make_adapter "make_adapter"
/// @{
/// @brief Build an adapter with a mock Superset client and deterministic environment for compatibility tests.
/// @}
void make_adapter(void);

/// @defgroup test_preview_prefers_supported_client_method_before_network_fallback "test_preview_prefers_supported_client_method_before_network_fallback"
/// @{
/// @brief Confirms preview compilation uses a supported client method first when the capability exists.
/// @}
void test_preview_prefers_supported_client_method_before_network_fallback(void);

/// @defgroup test_preview_falls_back_across_matrix_until_supported_endpoint_returns_sql "test_preview_falls_back_across_matrix_until_supported_endpoint_returns_sql"
/// @{
/// @brief Confirms preview fallback walks the compatibility matrix from preferred to legacy endpoints until one returns compiled SQL.
/// @}
void test_preview_falls_back_across_matrix_until_supported_endpoint_returns_sql(void);

/// @defgroup test_sql_lab_launch_falls_back_to_legacy_execute_endpoint "test_sql_lab_launch_falls_back_to_legacy_execute_endpoint"
/// @{
/// @brief Confirms SQL Lab launch falls back from modern to legacy execute endpoint and preserves canonical session reference extraction.
/// @}
void test_sql_lab_launch_falls_back_to_legacy_execute_endpoint(void);

/// @defgroup TestAPIKeyAuth "TestAPIKeyAuth"
/// @{
/// @brief Contract tests for API key authentication — valid key, invalid, revoked, expired, missing permission,
/// @}
void TestAPIKeyAuth(void);

/// @defgroup test_no_header_returns_none "test_no_header_returns_none"
/// @{
/// @brief No X-API-Key header → returns None.
/// @}
void test_no_header_returns_none(void);

/// @defgroup test_valid_key_returns_principal "test_valid_key_returns_principal"
/// @{
/// @brief Valid API key → returns APIKeyPrincipal with correct fields.
/// @}
void test_valid_key_returns_principal(void);

/// @defgroup test_invalid_key_raises_401 "test_invalid_key_raises_401"
/// @{
/// @brief Invalid API key → 401.
/// @}
void test_invalid_key_raises_401(void);

/// @defgroup test_revoked_key_raises_401 "test_revoked_key_raises_401"
/// @{
/// @brief Revoked (active=False) API key → 401.
/// @}
void test_revoked_key_raises_401(void);

/// @defgroup test_expired_key_raises_401 "test_expired_key_raises_401"
/// @{
/// @brief Expired API key → 401.
/// @}
void test_expired_key_raises_401(void);

/// @defgroup test_api_key_auth_valid "test_api_key_auth_valid"
/// @{
/// @brief Valid API key with matching permission → 202.
/// @}
void test_api_key_auth_valid(void);

/// @defgroup test_api_key_auth_wrong_permission "test_api_key_auth_wrong_permission"
/// @{
/// @brief API key lacks required permission → 403.
/// @}
void test_api_key_auth_wrong_permission(void);

/// @defgroup test_api_key_auth_revoked "test_api_key_auth_revoked"
/// @{
/// @brief Revoked API key → 401.
/// @}
void test_api_key_auth_revoked(void);

/// @defgroup test_api_key_auth_expired "test_api_key_auth_expired"
/// @{
/// @brief Expired API key → 401.
/// @}
void test_api_key_auth_expired(void);

/// @defgroup test_api_key_auth_invalid "test_api_key_auth_invalid"
/// @{
/// @brief Non-existent key → 401.
/// @}
void test_api_key_auth_invalid(void);

/// @defgroup test_api_key_auth_environment_scope "test_api_key_auth_environment_scope"
/// @{
/// @brief Key scoped to ss-dev, request for ss-prod → 400.
/// @}
void test_api_key_auth_environment_scope(void);

/// @defgroup test_api_key_auth_environment_scope_ok "test_api_key_auth_environment_scope_ok"
/// @{
/// @brief Key scoped to ss-dev, request for ss-dev → 202.
/// @}
void test_api_key_auth_environment_scope_ok(void);

/// @defgroup test_jwt_precedence "test_jwt_precedence"
/// @{
/// @brief Both valid API key + valid JWT → JWT takes precedence.
/// @}
void test_jwt_precedence(void);

/// @defgroup TestAPIKeyModel "TestAPIKeyModel"
/// @{
/// @brief Contract tests for the APIKey SQLAlchemy model — creation, hash storage, and field constraints.
/// @}
void TestAPIKeyModel(void);

/// @defgroup clean_db "clean_db"
/// @{
/// @brief In-memory SQLite fixture for APIKey model tests.
/// @}
void clean_db(void);

/// @defgroup test_create_api_key "test_create_api_key"
/// @{
/// @brief Create APIKey with required fields and verify defaults.
/// @}
void test_create_api_key(void);

/// @defgroup test_key_hash_unique "test_key_hash_unique"
/// @{
/// @brief key_hash is unique — duplicate raises IntegrityError.
/// @}
void test_key_hash_unique(void);

/// @defgroup test_prefix_length "test_prefix_length"
/// @{
/// @brief prefix is exactly 11 characters.
/// @}
void test_prefix_length(void);

/// @defgroup test_active_default_true "test_active_default_true"
/// @{
/// @brief active column defaults to True.
/// @}
void test_active_default_true(void);

/// @defgroup TestAPIKeyRoutes "TestAPIKeyRoutes"
/// @{
/// @brief Contract tests for admin API key CRUD endpoints — list, create (raw key present), revoke, idempotent revoke.
/// @}
void TestAPIKeyRoutes(void);

/// @defgroup test_list_empty "test_list_empty"
/// @{
/// @brief No keys → returns empty list.
/// @}
void test_list_empty(void);

/// @defgroup test_list_with_keys "test_list_with_keys"
/// @{
/// @brief Keys exist → returns list without raw_key or key_hash fields.
/// @}
void test_list_with_keys(void);

/// @defgroup test_create_valid "test_create_valid"
/// @{
/// @brief Valid request → 201 with raw_key, prefix, id.
/// @}
void test_create_valid(void);

/// @defgroup test_create_missing_name "test_create_missing_name"
/// @{
/// @brief Missing name → 400 or 422.
/// @}
void test_create_missing_name(void);

/// @defgroup test_create_empty_permissions "test_create_empty_permissions"
/// @{
/// @brief Empty permissions → 400 or 422.
/// @}
void test_create_empty_permissions(void);

/// @defgroup test_revoke_valid "test_revoke_valid"
/// @{
/// @brief Revoke existing active key → 200 with status=revoked.
/// @}
void test_revoke_valid(void);

/// @defgroup test_revoke_already_revoked "test_revoke_already_revoked"
/// @{
/// @brief Revoke already revoked key → 404.
/// @}
void test_revoke_already_revoked(void);

/// @defgroup test_revoke_not_found "test_revoke_not_found"
/// @{
/// @brief Revoke non-existent key → 404.
/// @}
void test_revoke_not_found(void);

/// @defgroup TestAuth "TestAuth"
/// @{
/// @brief Covers authentication service/repository behavior and auth bootstrap helpers.
/// @}
void TestAuth(void);

/// @defgroup test_create_admin_creates_user_with_optional_email "test_create_admin_creates_user_with_optional_email"
/// @{
/// @}
void test_create_admin_creates_user_with_optional_email(void);

/// @defgroup test_create_admin_is_idempotent_for_existing_user "test_create_admin_is_idempotent_for_existing_user"
/// @{
/// @}
void test_create_admin_is_idempotent_for_existing_user(void);

/// @defgroup test_ensure_encryption_key_generates_backend_env_file "test_ensure_encryption_key_generates_backend_env_file"
/// @{
/// @}
void test_ensure_encryption_key_generates_backend_env_file(void);

/// @defgroup test_ensure_encryption_key_reuses_existing_env_file_value "test_ensure_encryption_key_reuses_existing_env_file_value"
/// @{
/// @}
void test_ensure_encryption_key_reuses_existing_env_file_value(void);

/// @defgroup test_ensure_encryption_key_prefers_process_environment "test_ensure_encryption_key_prefers_process_environment"
/// @{
/// @}
void test_ensure_encryption_key_prefers_process_environment(void);

/// @defgroup TestConstantsAuditFixes "TestConstantsAuditFixes"
/// @{
/// @brief Verify Class 5 fix — hardcoded values extracted to named module-level constants.
/// @}
void TestConstantsAuditFixes(void);

/// @defgroup test_page_size_constant_exists "test_page_size_constant_exists"
/// @{
/// @brief DEFAULT_PAGE_SIZE contract: importable, int > 0 (not yet defined in source).
/// @}
void test_page_size_constant_exists(void);

/// @defgroup test_llm_analysis_timeout_constants "test_llm_analysis_timeout_constants"
/// @{
/// @brief Named timeout constants should exist per RATIONALE comment (not yet defined).
/// @}
void test_llm_analysis_timeout_constants(void);

/// @defgroup test_base_dir_constant_replaces_parents "test_base_dir_constant_replaces_parents"
/// @{
/// @brief BASE_DIR resolves to backend/ root, not __file__-dependent relative path.
/// @}
void test_base_dir_constant_replaces_parents(void);

/// @defgroup test_git_service_repositorys_typo_regression "test_git_service_repositorys_typo_regression"
/// @{
/// @brief services/git/_base.py still has "repositorys" (old typo) at line 148 — known bug.
/// @}
void test_git_service_repositorys_typo_regression(void);

/// @defgroup test_git_default_repos_path_constant "test_git_default_repos_path_constant"
/// @{
/// @brief DEFAULT_GIT_REPOS_PATH should be defined per RATIONALE (not yet defined).
/// @}
void test_git_default_repos_path_constant(void);

/// @defgroup test_superset_client_module_loads "test_superset_client_module_loads"
/// @{
/// @brief superset_client._base is importable (no dependency on crashing modules).
/// @}
void test_superset_client_module_loads(void);

/// @defgroup test_constants_are_immutable "test_constants_are_immutable"
/// @{
/// @brief Module-level constants use int/str types (immutable by convention).
/// @}
void test_constants_are_immutable(void);

/// @defgroup TestCoreScheduler "TestCoreScheduler"
/// @{
/// @brief Verify SchedulerService load_schedules and translation job add/remove contracts.
/// @}
void TestCoreScheduler(void);

/// @defgroup test_load_schedules_reloads_translation_schedules "test_load_schedules_reloads_translation_schedules"
/// @{
/// @}
void test_load_schedules_reloads_translation_schedules(void);

/// @defgroup test_add_and_remove_translation_job "test_add_and_remove_translation_job"
/// @{
/// @}
void test_add_and_remove_translation_job(void);

/// @defgroup test_remove_nonexistent_translation_job_no_error "test_remove_nonexistent_translation_job_no_error"
/// @{
/// @}
void test_remove_nonexistent_translation_job_no_error(void);

/// @defgroup test_add_validation_job "test_add_validation_job"
/// @{
/// @}
void test_add_validation_job(void);

/// @defgroup test_load_schedules_loads_validation_policies "test_load_schedules_loads_validation_policies"
/// @{
/// @}
void test_load_schedules_loads_validation_policies(void);

/// @defgroup test_trigger_validation_creates_tasks "test_trigger_validation_creates_tasks"
/// @{
/// @}
void test_trigger_validation_creates_tasks(void);

/// @defgroup test_trigger_validation_skips_missing_policy "test_trigger_validation_skips_missing_policy"
/// @{
/// @}
void test_trigger_validation_skips_missing_policy(void);

/// @defgroup test_trigger_validation_skips_inactive_policy "test_trigger_validation_skips_inactive_policy"
/// @{
/// @}
void test_trigger_validation_skips_inactive_policy(void);

/// @defgroup test_trigger_validation_skips_no_dashboards "test_trigger_validation_skips_no_dashboards"
/// @{
/// @}
void test_trigger_validation_skips_no_dashboards(void);

/// @defgroup test_remove_validation_job "test_remove_validation_job"
/// @{
/// @}
void test_remove_validation_job(void);

/// @defgroup test_remove_nonexistent_validation_job "test_remove_nonexistent_validation_job"
/// @{
/// @}
void test_remove_nonexistent_validation_job(void);

/// @defgroup test_reload_validation_policy_adds_job "test_reload_validation_policy_adds_job"
/// @{
/// @}
void test_reload_validation_policy_adds_job(void);

/// @defgroup test_reload_validation_policy_removes_job_when_policy_gone "test_reload_validation_policy_removes_job_when_policy_gone"
/// @{
/// @}
void test_reload_validation_policy_removes_job_when_policy_gone(void);

/// @defgroup TestDashboardsApi "TestDashboardsApi"
/// @{
/// @brief Comprehensive contract-driven tests for Dashboard Hub API
/// @}
void TestDashboardsApi(void);

/// @defgroup test_get_dashboard_tasks_history_success "test_get_dashboard_tasks_history_success"
/// @{
/// @}
void test_get_dashboard_tasks_history_success(void);

/// @defgroup test_get_dashboard_tasks_history_sorting "test_get_dashboard_tasks_history_sorting"
/// @{
/// @}
void test_get_dashboard_tasks_history_sorting(void);

/// @defgroup test_get_dashboard_thumbnail_env_not_found "test_get_dashboard_thumbnail_env_not_found"
/// @{
/// @}
void test_get_dashboard_thumbnail_env_not_found(void);

/// @defgroup test_get_dashboard_thumbnail_202 "test_get_dashboard_thumbnail_202"
/// @{
/// @}
void test_get_dashboard_thumbnail_202(void);

/// @defgroup test_migrate_dashboards_pre_checks "test_migrate_dashboards_pre_checks"
/// @{
/// @}
void test_migrate_dashboards_pre_checks(void);

/// @defgroup test_backup_dashboards_pre_checks "test_backup_dashboards_pre_checks"
/// @{
/// @}
void test_backup_dashboards_pre_checks(void);

/// @defgroup test_backup_dashboards_with_schedule "test_backup_dashboards_with_schedule"
/// @{
/// @}
void test_backup_dashboards_with_schedule(void);

/// @defgroup test_task_matches_dashboard_logic "test_task_matches_dashboard_logic"
/// @{
/// @}
void test_task_matches_dashboard_logic(void);

/// @defgroup TestDeprecationAuditFixes "TestDeprecationAuditFixes"
/// @{
/// @brief Verify Class 7 fix — is_multimodal_model should emit DeprecationWarning.
/// @}
void TestDeprecationAuditFixes(void);

/// @defgroup test_is_multimodal_model_emits_warning "test_is_multimodal_model_emits_warning"
/// @{
/// @brief is_multimodal_model should emit DeprecationWarning (shim not yet implemented).
/// @}
void test_is_multimodal_model_emits_warning(void);

/// @defgroup test_multimodal_model_returns_true "test_multimodal_model_returns_true"
/// @{
/// @brief Known multimodal models (gpt-4o, claude-3, gemini) return True.
/// @}
void test_multimodal_model_returns_true(void);

/// @defgroup test_text_only_model_returns_false "test_text_only_model_returns_false"
/// @{
/// @brief Text-only models (embedding, whisper, rerank) return False.
/// @}
void test_text_only_model_returns_false(void);

/// @defgroup test_empty_model_returns_false "test_empty_model_returns_false"
/// @{
/// @brief Empty or None model name returns False without error.
/// @}
void test_empty_model_returns_false(void);

/// @defgroup test_case_insensitive_matching "test_case_insensitive_matching"
/// @{
/// @brief Model name matching is case-insensitive.
/// @}
void test_case_insensitive_matching(void);

/// @defgroup test_deprecation_comment_exists "test_deprecation_comment_exists"
/// @{
/// @brief The source module documents the @DEPRECATED rationale in the region header.
/// @}
void test_deprecation_comment_exists(void);

/// @defgroup TestLayoutUtils "TestLayoutUtils"
/// @{
/// @brief Contract tests for layout utility functions — _estimate_markdown_height.
/// @}
void TestLayoutUtils(void);

/// @defgroup test_empty_content "test_empty_content"
/// @{
/// @brief Empty string returns minimum height 19.
/// @}
void test_empty_content(void);

/// @defgroup test_single_line_text "test_single_line_text"
/// @{
/// @brief Short text without padding returns expected computed height.
/// @}
void test_single_line_text(void);

/// @defgroup test_content_with_padding "test_content_with_padding"
/// @{
/// @brief Content with padding:12 — 24px added to content height.
/// @}
void test_content_with_padding(void);

/// @defgroup test_very_long_content "test_very_long_content"
/// @{
/// @brief Very long content (3000 chars) capped at max height 200.
/// @}
void test_very_long_content(void);

/// @defgroup test_html_only_content "test_html_only_content"
/// @{
/// @brief HTML-only content (no visible text) returns minimum height 19.
/// @}
void test_html_only_content(void);

/// @defgroup test_log_persistence "test_log_persistence"
/// @{
/// @brief Unit tests for TaskLogPersistenceService.
/// @}
void test_log_persistence(void);

/// @defgroup TestLogPersistence "TestLogPersistence"
/// @{
/// @brief Test suite for TaskLogPersistenceService.
/// @}
void TestLogPersistence(void);

/// @defgroup test_add_logs_single "test_add_logs_single"
/// @{
/// @brief Test adding a single log entry.
/// @post Log entry persisted to database.
/// @pre Service and session initialized.
/// @}
void test_add_logs_single(void);

/// @defgroup test_add_logs_batch "test_add_logs_batch"
/// @{
/// @brief Test adding multiple log entries in batch.
/// @post All log entries persisted to database.
/// @pre Service and session initialized.
/// @}
void test_add_logs_batch(void);

/// @defgroup test_add_logs_empty "test_add_logs_empty"
/// @{
/// @brief Test adding empty log list (should be no-op).
/// @post No logs added.
/// @pre Service initialized.
/// @}
void test_add_logs_empty(void);

/// @defgroup test_get_logs_by_task_id "test_get_logs_by_task_id"
/// @{
/// @brief Test retrieving logs by task ID.
/// @post Returns logs for the specified task.
/// @pre Service and session initialized, logs exist.
/// @}
void test_get_logs_by_task_id(void);

/// @defgroup test_get_logs_with_filters "test_get_logs_with_filters"
/// @{
/// @brief Test retrieving logs with level and source filters.
/// @post Returns filtered logs.
/// @pre Service and session initialized, logs exist.
/// @}
void test_get_logs_with_filters(void);

/// @defgroup test_get_logs_with_pagination "test_get_logs_with_pagination"
/// @{
/// @brief Test retrieving logs with pagination.
/// @post Returns paginated logs.
/// @pre Service and session initialized, logs exist.
/// @}
void test_get_logs_with_pagination(void);

/// @defgroup test_get_logs_with_search "test_get_logs_with_search"
/// @{
/// @brief Test retrieving logs with search query.
/// @post Returns logs matching search query.
/// @pre Service and session initialized, logs exist.
/// @}
void test_get_logs_with_search(void);

/// @defgroup test_get_log_stats "test_get_log_stats"
/// @{
/// @brief Test retrieving log statistics.
/// @post Returns LogStats model with counts by level and source.
/// @pre Service and session initialized, logs exist.
/// @}
void test_get_log_stats(void);

/// @defgroup test_get_sources "test_get_sources"
/// @{
/// @brief Test retrieving unique log sources.
/// @post Returns list of unique sources.
/// @pre Service and session initialized, logs exist.
/// @}
void test_get_sources(void);

/// @defgroup test_delete_logs_for_task "test_delete_logs_for_task"
/// @{
/// @brief Test deleting logs by task ID.
/// @post Logs for the task are deleted.
/// @pre Service and session initialized, logs exist.
/// @}
void test_delete_logs_for_task(void);

/// @defgroup test_delete_logs_for_tasks "test_delete_logs_for_tasks"
/// @{
/// @brief Test deleting logs for multiple tasks.
/// @post Logs for all specified tasks are deleted.
/// @pre Service and session initialized, logs exist.
/// @}
void test_delete_logs_for_tasks(void);

/// @defgroup test_delete_logs_for_tasks_empty "test_delete_logs_for_tasks_empty"
/// @{
/// @brief Test deleting with empty list (no-op).
/// @post No error, no deletion.
/// @pre Service initialized.
/// @}
void test_delete_logs_for_tasks_empty(void);

/// @defgroup TestLogger "TestLogger"
/// @{
/// @brief Unit tests for the custom logger CoT JSON formatters and configuration context manager.
/// @invariant All required log statements must correctly check the threshold.
/// @}
void TestLogger(void);

/// @defgroup test_belief_scope_success_coherence "test_belief_scope_success_coherence"
/// @{
/// @brief Test that belief_scope logs REFLECT marker on success.
/// @post Logs are verified to contain REFLECT marker.
/// @pre belief_scope is available. caplog fixture is used. Logger configured to DEBUG.
/// @}
void test_belief_scope_success_coherence(void);

/// @defgroup test_belief_scope_reason_not_visible_at_info "test_belief_scope_reason_not_visible_at_info"
/// @{
/// @brief Test that belief_scope REASON/REFLECT markers are NOT visible at INFO level.
/// @post REASON/REFLECT markers are not captured at INFO level.
/// @pre belief_scope is available. caplog fixture is used.
/// @}
void test_belief_scope_reason_not_visible_at_info(void);

/// @defgroup test_cot_json_formatter_output "test_cot_json_formatter_output"
/// @{
/// @brief Test that CotJsonFormatter produces valid JSON with expected fields.
/// @}
void test_cot_json_formatter_output(void);

/// @defgroup test_cot_json_formatter_plain_message "test_cot_json_formatter_plain_message"
/// @{
/// @brief Test that CotJsonFormatter wraps plain messages (no extra) with default marker.
/// @}
void test_cot_json_formatter_plain_message(void);

/// @defgroup TestLoggingAuditFixes "TestLoggingAuditFixes"
/// @{
/// @brief Verify Class 2 fix — no bare `except: pass` patterns remain in src/.
/// @}
void TestLoggingAuditFixes(void);

/// @defgroup _collect_src_files "_collect_src_files"
/// @{
/// @brief Collect all .py files under src/ excluding test/ and mock/ directories.
/// @}
void _collect_src_files(void);

/// @defgroup test_except_pass_replaced_with_log "test_except_pass_replaced_with_log"
/// @{
/// @brief AST audit: bare `except: pass` nodes are absent from src/ source files.
/// @}
void test_except_pass_replaced_with_log(void);

/// @defgroup test_plugin_loader_uses_logger_not_print "test_plugin_loader_uses_logger_not_print"
/// @{
/// @brief plugin_loader.py (src/core/) uses logger for error/warning, not print().
/// @}
void test_plugin_loader_uses_logger_not_print(void);

/// @defgroup test_plugin_loader_imports_logger "test_plugin_loader_imports_logger"
/// @{
/// @brief plugin_loader.py imports a logger or _logger for structured reporting.
/// @}
void test_plugin_loader_imports_logger(void);

/// @defgroup test_plugin_loader_logger_calls_exist "test_plugin_loader_logger_calls_exist"
/// @{
/// @brief plugin_loader.py references logger.error/warning/info in its code.
/// @}
void test_plugin_loader_logger_calls_exist(void);

/// @defgroup test_maintenance_api "test_maintenance_api"
/// @{
/// @brief Contract tests for Maintenance Banner API endpoints — T016, T025.
/// @}
void test_maintenance_api(void);

/// @defgroup test_start_returns_202 "test_start_returns_202"
/// @{
/// @brief Valid request returns 202 with task_id and maintenance_id.
/// @}
void test_start_returns_202(void);

/// @defgroup test_start_missing_tables "test_start_missing_tables"
/// @{
/// @brief Missing tables field returns 422.
/// @}
void test_start_missing_tables(void);

/// @defgroup test_start_end_time_before_start "test_start_end_time_before_start"
/// @{
/// @brief end_time before start_time returns 400.
/// @}
void test_start_end_time_before_start(void);

/// @defgroup test_start_too_many_tables "test_start_too_many_tables"
/// @{
/// @brief More than 100 tables returns 422 (Pydantic validation).
/// @}
void test_start_too_many_tables(void);

/// @defgroup test_start_idempotency "test_start_idempotency"
/// @{
/// @brief Same (tables, start, end) returns already_active.
/// @}
void test_start_idempotency(void);

/// @defgroup test_end_returns_202 "test_end_returns_202"
/// @{
/// @brief Valid maintenance_id returns 202.
/// @}
void test_end_returns_202(void);

/// @defgroup test_end_not_found "test_end_not_found"
/// @{
/// @brief Non-existent maintenance_id returns 404.
/// @}
void test_end_not_found(void);

/// @defgroup test_end_all_returns_202 "test_end_all_returns_202"
/// @{
/// @brief end-all returns 202.
/// @}
void test_end_all_returns_202(void);

/// @defgroup test_list_events "test_list_events"
/// @{
/// @brief Returns active and completed events.
/// @}
void test_list_events(void);

/// @defgroup test_expired_event_auto_ends "test_expired_event_auto_ends"
/// @{
/// @brief Event past end_time with ACTIVE status → create_task called with auto-end params.
/// @}
void test_expired_event_auto_ends(void);

/// @defgroup test_future_end_time_skipped "test_future_end_time_skipped"
/// @{
/// @brief Event with future end_time → no task created, skipped by < now filter.
/// @}
void test_future_end_time_skipped(void);

/// @defgroup test_no_end_time_skipped "test_no_end_time_skipped"
/// @{
/// @brief Event with end_time=None → no task created, skipped by isnot(None) filter.
/// @}
void test_no_end_time_skipped(void);

/// @defgroup test_list_banners "test_list_banners"
/// @{
/// @brief Returns list of active banners.
/// @}
void test_list_banners(void);

/// @defgroup test_get_settings "test_get_settings"
/// @{
/// @brief GET returns settings.
/// @}
void test_get_settings(void);

/// @defgroup test_put_settings "test_put_settings"
/// @{
/// @brief PUT updates settings.
/// @}
void test_put_settings(void);

/// @defgroup test_maintenance_service "test_maintenance_service"
/// @{
/// @brief Integration tests for MaintenanceService — T018, T026, T026a.
/// @}
void test_maintenance_service(void);

/// @defgroup test_basic_key "test_basic_key"
/// @{
/// @brief Basic idempotency key with tables and times.
/// @}
void test_basic_key(void);

/// @defgroup test_key_without_end_time "test_key_without_end_time"
/// @{
/// @brief Idempotency key with None end_time.
/// @}
void test_key_without_end_time(void);

/// @defgroup test_key_table_sorting "test_key_table_sorting"
/// @{
/// @brief Tables are sorted alphabetically in frozenset.
/// @}
void test_key_table_sorting(void);

/// @defgroup test_empty_tables "test_empty_tables"
/// @{
/// @brief Empty tables list returns empty.
/// @}
void test_empty_tables(void);

/// @defgroup test_table_based_match "test_table_based_match"
/// @{
/// @brief Table-based dataset matching.
/// @}
void test_table_based_match(void);

/// @defgroup test_virtual_dataset_match "test_virtual_dataset_match"
/// @{
/// @brief Virtual SQL dataset matching via SqlTableExtractor.
/// @}
void test_virtual_dataset_match(void);

/// @defgroup test_superset_api_failure "test_superset_api_failure"
/// @{
/// @brief Superset API failure propagates.
/// @}
void test_superset_api_failure(void);

/// @defgroup test_creates_new_banner "test_creates_new_banner"
/// @{
/// @brief No existing banner — creates new chart and banner row.
/// @}
void test_creates_new_banner(void);

/// @defgroup test_returns_existing_banner "test_returns_existing_banner"
/// @{
/// @brief Existing active banner — returns it.
/// @}
void test_returns_existing_banner(void);

/// @defgroup test_chart_creation_failure "test_chart_creation_failure"
/// @{
/// @brief Chart creation failure propagates.
/// @}
void test_chart_creation_failure(void);

/// @defgroup test_single_event "test_single_event"
/// @{
/// @brief Single event — direct substitution.
/// @}
void test_single_event(void);

/// @defgroup test_multiple_events "test_multiple_events"
/// @{
/// @brief Multiple events — combined message.
/// @}
void test_multiple_events(void);

/// @defgroup test_empty_events "test_empty_events"
/// @{
/// @brief Empty events list returns empty string.
/// @}
void test_empty_events(void);

/// @defgroup test_missing_variables "test_missing_variables"
/// @{
/// @brief Missing variables replaced with empty string.
/// @}
void test_missing_variables(void);

/// @defgroup test_html_escaping "test_html_escaping"
/// @{
/// @brief Message is HTML-escaped.
/// @}
void test_html_escaping(void);

/// @defgroup test_happy_path "test_happy_path"
/// @{
/// @brief Happy path: event with matching dashboards.
/// @}
void test_happy_path(void);

/// @defgroup test_no_matching_dashboards "test_no_matching_dashboards"
/// @{
/// @brief No dashboards match the tables.
/// @}
void test_no_matching_dashboards(void);

/// @defgroup test_event_not_found "test_event_not_found"
/// @{
/// @brief Event ID not in DB.
/// @}
void test_event_not_found(void);

/// @defgroup test_already_processed_event "test_already_processed_event"
/// @{
/// @brief Event already ACTIVE — idempotent.
/// @}
void test_already_processed_event(void);

/// @defgroup test_rebuild_active_banner "test_rebuild_active_banner"
/// @{
/// @brief Active banner with active state — rebuilds text.
/// @}
void test_rebuild_active_banner(void);

/// @defgroup test_banner_not_found "test_banner_not_found"
/// @{
/// @brief Banner ID not found.
/// @}
void test_banner_not_found(void);

/// @defgroup test_end_active_event_single_banner "test_end_active_event_single_banner"
/// @{
/// @brief End event with single active dashboard — banner removed entirely.
/// @}
void test_end_active_event_single_banner(void);

/// @defgroup test_end_event_shared_banner "test_end_event_shared_banner"
/// @{
/// @brief Two events, same dashboard — ending one rebuilds banner, doesn't delete.
/// @}
void test_end_event_shared_banner(void);

/// @defgroup test_end_already_completed_event "test_end_already_completed_event"
/// @{
/// @brief Already completed event — idempotent.
/// @}
void test_end_already_completed_event(void);

/// @defgroup test_end_all_active_events "test_end_all_active_events"
/// @{
/// @brief End all active events.
/// @}
void test_end_all_active_events(void);

/// @defgroup test_no_active_events "test_no_active_events"
/// @{
/// @brief No active events.
/// @}
void test_no_active_events(void);

/// @defgroup test_mixed_active_and_completed "test_mixed_active_and_completed"
/// @{
/// @brief Mix of active and completed events — only active get ended.
/// @}
void test_mixed_active_and_completed(void);

/// @defgroup TestResourceHubs "TestResourceHubs"
/// @{
/// @brief Contract tests for resource hub dashboards/datasets listing and pagination boundary validation.
/// @}
void TestResourceHubs(void);

/// @defgroup test_dashboards_api "test_dashboards_api"
/// @{
/// @brief Verify GET /api/dashboards contract compliance
/// @}
void test_dashboards_api(void);

/// @defgroup mock_deps "mock_deps"
/// @{
/// @brief Provide dependency override fixture for resource hub route tests.
/// @invariant unconstrained mock — no spec= enforced; attribute typos will silently pass
/// @}
void mock_deps(void);

/// @defgroup test_get_dashboards_not_found "test_get_dashboards_not_found"
/// @{
/// @brief Verify dashboards endpoint returns 404 for unknown environment identifier.
/// @}
void test_get_dashboards_not_found(void);

/// @defgroup test_get_dashboards_search "test_get_dashboards_search"
/// @{
/// @brief Verify dashboards endpoint search filter returns matching subset.
/// @}
void test_get_dashboards_search(void);

/// @defgroup test_datasets_api "test_datasets_api"
/// @{
/// @brief Verify GET /api/datasets contract compliance
/// @}
void test_datasets_api(void);

/// @defgroup test_get_datasets_not_found "test_get_datasets_not_found"
/// @{
/// @brief Verify datasets endpoint returns 404 for unknown environment identifier.
/// @}
void test_get_datasets_not_found(void);

/// @defgroup test_get_datasets_search "test_get_datasets_search"
/// @{
/// @brief Verify datasets endpoint search filter returns matching dataset subset.
/// @}
void test_get_datasets_search(void);

/// @defgroup test_get_datasets_service_failure "test_get_datasets_service_failure"
/// @{
/// @brief Verify datasets endpoint surfaces backend fetch failure as HTTP 503.
/// @}
void test_get_datasets_service_failure(void);

/// @defgroup test_pagination_boundaries "test_pagination_boundaries"
/// @{
/// @brief Verify pagination validation for GET endpoints
/// @}
void test_pagination_boundaries(void);

/// @defgroup test_get_dashboards_pagination_zero_page "test_get_dashboards_pagination_zero_page"
/// @{
/// @brief Verify dashboards endpoint rejects page=0 with HTTP 400 validation error.
/// @}
void test_get_dashboards_pagination_zero_page(void);

/// @defgroup test_get_dashboards_pagination_oversize "test_get_dashboards_pagination_oversize"
/// @{
/// @brief Verify dashboards endpoint rejects oversized page_size with HTTP 400.
/// @}
void test_get_dashboards_pagination_oversize(void);

/// @defgroup test_get_datasets_pagination_zero_page "test_get_datasets_pagination_zero_page"
/// @{
/// @brief Verify datasets endpoint rejects page=0 with HTTP 400.
/// @}
void test_get_datasets_pagination_zero_page(void);

/// @defgroup test_get_datasets_pagination_oversize "test_get_datasets_pagination_oversize"
/// @{
/// @brief Verify datasets endpoint rejects oversized page_size with HTTP 400.
/// @}
void test_get_datasets_pagination_oversize(void);

/// @defgroup TestSecurityAuditFixes "TestSecurityAuditFixes"
/// @{
/// @brief Verify Class 1 security audit fixes — env-only secrets, crash-early, CORS parsing.
/// @}
void TestSecurityAuditFixes(void);

/// @defgroup test_missing_secret_key_crashes "test_missing_secret_key_crashes"
/// @{
/// @brief AuthConfig.validate_secret_key raises ValueError when value is empty (crash-early).
/// @}
void test_missing_secret_key_crashes(void);

/// @defgroup test_missing_auth_db_url_crashes "test_missing_auth_db_url_crashes"
/// @{
/// @brief AuthConfig.validate_auth_db_url raises ValueError when URL is empty and DEV_MODE is off.
/// @}
void test_missing_auth_db_url_crashes(void);

/// @defgroup test_auth_db_dev_fallback_works "test_auth_db_dev_fallback_works"
/// @{
/// @brief When DEV_MODE=true and AUTH_DATABASE_URL is unset, dev fallback is used without crash.
/// @}
void test_auth_db_dev_fallback_works(void);

/// @defgroup test_allowed_origins_parsing "test_allowed_origins_parsing"
/// @{
/// @brief os.getenv("ALLOWED_ORIGINS").split(",") correctly parses comma-separated origins.
/// @}
void test_allowed_origins_parsing(void);

/// @defgroup test_cors_wildcard_default "test_cors_wildcard_default"
/// @{
/// @brief When ALLOWED_ORIGINS is not set, default returns ["*"].
/// @}
void test_cors_wildcard_default(void);

/// @defgroup test_cors_parsing_single_value "test_cors_parsing_single_value"
/// @{
/// @brief Single origin returns single-element list.
/// @}
void test_cors_parsing_single_value(void);

/// @defgroup test_cors_parsing_with_trailing_spaces "test_cors_parsing_with_trailing_spaces"
/// @{
/// @brief Origins with trailing spaces are preserved (no strip).
/// @}
void test_cors_parsing_with_trailing_spaces(void);

/// @defgroup test_database_url_env_override "test_database_url_env_override"
/// @{
/// @brief DATABASE_URL env var takes precedence over POSTGRES_URL.
/// @}
void test_database_url_env_override(void);

/// @defgroup test_database_url_postgres_fallback "test_database_url_postgres_fallback"
/// @{
/// @brief POSTGRES_URL is used when DATABASE_URL is unset.
/// @}
void test_database_url_postgres_fallback(void);

/// @defgroup test_database_url_raises_when_both_unset "test_database_url_raises_when_both_unset"
/// @{
/// @brief RuntimeError is expected when both DATABASE_URL and POSTGRES_URL are unset (non-dev).
/// @}
void test_database_url_raises_when_both_unset(void);

/// @defgroup test_auth_config_module_contract "test_auth_config_module_contract"
/// @{
/// @brief AuthConfig contract: the class exists, validators are documented.
/// @}
void test_auth_config_module_contract(void);

/// @defgroup test_sql_table_extractor "test_sql_table_extractor"
/// @{
/// @brief Unit tests for SqlTableExtractor — T017. Verifies three-phase extraction of schema.table references from SQL+Jinja.
/// @}
void test_sql_table_extractor(void);

/// @defgroup test_simple_select "test_simple_select"
/// @{
/// @brief Happy path: simple SELECT with FROM schema.table.
/// @}
void test_simple_select(void);

/// @defgroup test_multiple_tables "test_multiple_tables"
/// @{
/// @brief JOIN with multiple schema-qualified tables.
/// @}
void test_multiple_tables(void);

/// @defgroup test_empty_input "test_empty_input"
/// @{
/// @brief Empty string returns empty set.
/// @}
void test_empty_input(void);

/// @defgroup test_no_schema_qualified_tables "test_no_schema_qualified_tables"
/// @{
/// @brief Unqualified table names are NOT matched.
/// @}
void test_no_schema_qualified_tables(void);

/// @defgroup test_case_insensitive "test_case_insensitive"
/// @{
/// @brief Matching is case-insensitive; result is lowercased.
/// @}
void test_case_insensitive(void);

/// @defgroup test_string_literal_false_positive "test_string_literal_false_positive"
/// @{
/// @brief Date literal like '2026.04.30' must NOT be matched as schema.table.
/// @}
void test_string_literal_false_positive(void);

/// @defgroup test_jinja_string_concat "test_jinja_string_concat"
/// @{
/// @brief Table reference inside Jinja {{ 'raw.sales' }} as a direct string.
/// @}
void test_jinja_string_concat(void);

/// @defgroup test_jinja_set_block "test_jinja_set_block"
/// @{
/// @brief Table name in Jinja {% set %} block string value.
/// @}
void test_jinja_set_block(void);

/// @defgroup test_mixed_jinja_and_sql "test_mixed_jinja_and_sql"
/// @{
/// @brief Mixed Jinja string and plain SQL schema.table references.
/// @}
void test_mixed_jinja_and_sql(void);

/// @defgroup test_cte_with_schema_tables "test_cte_with_schema_tables"
/// @{
/// @brief CTE body with schema-qualified table references.
/// @}
void test_cte_with_schema_tables(void);

/// @defgroup test_jinja_comment_excluded "test_jinja_comment_excluded"
/// @{
/// @brief Jinja comment {# ... #} content should not produce table extraction (no string patterns inside comments).
/// @}
void test_jinja_comment_excluded(void);

/// @defgroup TestStorageAuditFixes "TestStorageAuditFixes"
/// @{
/// @brief Verify Class 7 typo fix — "repositorys" → "repositories" across all storage/git modules.
/// @}
void TestStorageAuditFixes(void);

/// @defgroup test_repository_typo_fixed "test_repository_typo_fixed"
/// @{
/// @brief FileCategory.REPOSITORY equals "repositories", NOT "repositorys".
/// @}
void test_repository_typo_fixed(void);

/// @defgroup test_repo_path_default_fixed "test_repo_path_default_fixed"
/// @{
/// @brief StorageConfig().repo_path defaults to "repositories".
/// @}
void test_repo_path_default_fixed(void);

/// @defgroup test_storage_model_compiles "test_storage_model_compiles"
/// @{
/// @brief All storage model classes import without errors.
/// @}
void test_storage_model_compiles(void);

/// @defgroup test_backup_category_unchanged "test_backup_category_unchanged"
/// @{
/// @brief FileCategory.BACKUP still equals "backups" (not affected by typo fix).
/// @}
void test_backup_category_unchanged(void);

/// @defgroup test_storage_config_fields_have_correct_types "test_storage_config_fields_have_correct_types"
/// @{
/// @brief StorageConfig fields are all strings with correct defaults.
/// @}
void test_storage_config_fields_have_correct_types(void);

/// @defgroup TestStorageConfigMigration "TestStorageConfigMigration"
/// @{
/// @brief Verify StorageConfig root_path change from "backups" to "/app/storage",
/// @}
void TestStorageConfigMigration(void);

/// @defgroup TestStorageConfigDefaults "TestStorageConfigDefaults"
/// @{
/// @brief Verify StorageConfig default field values after the root_path change.
/// @}
void TestStorageConfigDefaults(void);

/// @defgroup test_root_path_default "test_root_path_default"
/// @{
/// @brief StorageConfig().root_path must equal "/app/storage" (was "backups").
/// @}
void test_root_path_default(void);

/// @defgroup test_root_path_is_string "test_root_path_is_string"
/// @{
/// @brief root_path is always a str (type safety).
/// @}
void test_root_path_is_string(void);

/// @defgroup test_other_defaults_unchanged "test_other_defaults_unchanged"
/// @{
/// @brief Other StorageConfig fields were not affected by the root_path change.
/// @}
void test_other_defaults_unchanged(void);

/// @defgroup test_global_settings_propagates_storage "test_global_settings_propagates_storage"
/// @{
/// @brief GlobalSettings().storage.root_path inherits the StorageConfig default.
/// @}
void test_global_settings_propagates_storage(void);

/// @defgroup test_override_root_path "test_override_root_path"
/// @{
/// @brief Explicit root_path overrides the default.
/// @}
void test_override_root_path(void);

/// @defgroup TestConfigManagerDefaults "TestConfigManagerDefaults"
/// @{
/// @brief Verify ConfigManager produces correct defaults when no config.json exists.
/// @}
void TestConfigManagerDefaults(void);

/// @defgroup test_init_falls_to_defaults "test_init_falls_to_defaults"
/// @{
/// @brief ConfigManager(…nonexistent…) loads defaults when both DB and config.json are absent.
/// @}
void test_init_falls_to_defaults(void);

/// @defgroup test_default_config_root_path "test_default_config_root_path"
/// @{
/// @brief _default_config() hardcodes root_path == "/app/storage" via StorageConfig default.
/// @}
void test_default_config_root_path(void);

/// @defgroup test_features_from_env_still_applied "test_features_from_env_still_applied"
/// @{
/// @brief Even without config.json, _apply_features_from_env runs during default init.
/// @}
void test_features_from_env_still_applied(void);

/// @defgroup TestValidatePath "TestValidatePath"
/// @{
/// @brief Verify ConfigManager.validate_path contract.
/// @}
void TestValidatePath(void);

/// @defgroup test_validate_path_creates_directory "test_validate_path_creates_directory"
/// @{
/// @brief validate_path creates the target directory and returns (True, "OK").
/// @}
void test_validate_path_creates_directory(void);

/// @defgroup test_validate_path_already_exists "test_validate_path_already_exists"
/// @{
/// @brief validate_path succeeds when the directory already exists.
/// @}
void test_validate_path_already_exists(void);

/// @defgroup test_validate_path_nonexistent_root "test_validate_path_nonexistent_root"
/// @{
/// @brief validate_path returns False for a path under / (non-writable by non-root).
/// @}
void test_validate_path_nonexistent_root(void);

/// @defgroup test_validate_path_read_only_parent "test_validate_path_read_only_parent"
/// @{
/// @brief validate_path returns False when the parent directory is not writable.
/// @}
void test_validate_path_read_only_parent(void);

/// @defgroup TestGitPluginConfigIntegration "TestGitPluginConfigIntegration"
/// @{
/// @brief Verify GitPlugin uses shared config_manager from src.dependencies (no config.json fallback).
/// @}
void TestGitPluginConfigIntegration(void);

/// @defgroup test_git_plugin_uses_shared_config_manager "test_git_plugin_uses_shared_config_manager"
/// @{
/// @brief GitPlugin.__init__ picks up the shared config_manager from src.dependencies.
/// @}
void test_git_plugin_uses_shared_config_manager(void);

/// @defgroup test_git_plugin_fallback_creates_new "test_git_plugin_fallback_creates_new"
/// @{
/// @brief When from src.dependencies import config_manager fails,
/// @}
void test_git_plugin_fallback_creates_new(void);

/// @defgroup TestRegressionGuard "TestRegressionGuard"
/// @{
/// @brief Guard against regressions in existing test contracts and stale assertions.
/// @}
void TestRegressionGuard(void);

/// @defgroup test_existing_test_would_fail "test_existing_test_would_fail"
/// @{
/// @brief Existing test_storage_audit_fixes.py still asserts root_path=="backups" (WRONG).
/// @}
void test_existing_test_would_fail(void);

/// @defgroup test_storage_settings_endpoint_shape "test_storage_settings_endpoint_shape"
/// @{
/// @brief The API response shape for storage settings is still StorageConfig.
/// @}
void test_storage_settings_endpoint_shape(void);

/// @defgroup test_task_manager "test_task_manager"
/// @{
/// @brief Unit tests for TaskManager lifecycle, CRUD, log buffering, and filtering.
/// @invariant TaskManager state changes are deterministic and testable with mocked dependencies.
/// @}
void test_task_manager(void);

/// @defgroup _make_manager "_make_manager"
/// @{
/// @}
void _make_manager(void);

/// @defgroup _cleanup_manager "_cleanup_manager"
/// @{
/// @}
void _cleanup_manager(void);

/// @defgroup test_task_persistence "test_task_persistence"
/// @{
/// @brief Unit tests for TaskPersistenceService.
/// @}
void test_task_persistence(void);

/// @defgroup TestTaskPersistenceHelpers "TestTaskPersistenceHelpers"
/// @{
/// @brief Test suite for TaskPersistenceService static helper methods.
/// @}
void TestTaskPersistenceHelpers(void);

/// @defgroup test_json_load_if_needed_none "test_json_load_if_needed_none"
/// @{
/// @brief Test _json_load_if_needed with None input.
/// @}
void test_json_load_if_needed_none(void);

/// @defgroup test_json_load_if_needed_dict "test_json_load_if_needed_dict"
/// @{
/// @brief Test _json_load_if_needed with dict input.
/// @}
void test_json_load_if_needed_dict(void);

/// @defgroup test_json_load_if_needed_list "test_json_load_if_needed_list"
/// @{
/// @brief Test _json_load_if_needed with list input.
/// @}
void test_json_load_if_needed_list(void);

/// @defgroup test_json_load_if_needed_json_string "test_json_load_if_needed_json_string"
/// @{
/// @brief Test _json_load_if_needed with JSON string.
/// @}
void test_json_load_if_needed_json_string(void);

/// @defgroup test_json_load_if_needed_empty_string "test_json_load_if_needed_empty_string"
/// @{
/// @brief Test _json_load_if_needed with empty/null strings.
/// @}
void test_json_load_if_needed_empty_string(void);

/// @defgroup test_json_load_if_needed_plain_string "test_json_load_if_needed_plain_string"
/// @{
/// @brief Test _json_load_if_needed with non-JSON string.
/// @}
void test_json_load_if_needed_plain_string(void);

/// @defgroup test_json_load_if_needed_integer "test_json_load_if_needed_integer"
/// @{
/// @brief Test _json_load_if_needed with integer.
/// @}
void test_json_load_if_needed_integer(void);

/// @defgroup test_parse_datetime_none "test_parse_datetime_none"
/// @{
/// @brief Test _parse_datetime with None.
/// @}
void test_parse_datetime_none(void);

/// @defgroup test_parse_datetime_datetime_object "test_parse_datetime_datetime_object"
/// @{
/// @brief Test _parse_datetime with datetime object.
/// @}
void test_parse_datetime_datetime_object(void);

/// @defgroup test_parse_datetime_iso_string "test_parse_datetime_iso_string"
/// @{
/// @brief Test _parse_datetime with ISO string.
/// @}
void test_parse_datetime_iso_string(void);

/// @defgroup test_parse_datetime_invalid_string "test_parse_datetime_invalid_string"
/// @{
/// @brief Test _parse_datetime with invalid string.
/// @}
void test_parse_datetime_invalid_string(void);

/// @defgroup test_parse_datetime_integer "test_parse_datetime_integer"
/// @{
/// @brief Test _parse_datetime with non-string, non-datetime.
/// @}
void test_parse_datetime_integer(void);

/// @defgroup TestTaskPersistenceService "TestTaskPersistenceService"
/// @{
/// @brief Test suite for TaskPersistenceService CRUD operations.
/// @}
void TestTaskPersistenceService(void);

/// @defgroup setup_class "setup_class"
/// @{
/// @brief Setup in-memory test database.
/// @}
void setup_class(void);

/// @defgroup teardown_class "teardown_class"
/// @{
/// @brief Dispose of test database.
/// @}
void teardown_class(void);

/// @defgroup setup_method "setup_method"
/// @{
/// @brief Clean task_records table before each test.
/// @}
void setup_method(void);

/// @defgroup test_persist_task_new "test_persist_task_new"
/// @{
/// @brief Test persisting a new task creates a record.
/// @post TaskRecord exists in database.
/// @pre Empty database.
/// @}
void test_persist_task_new(void);

/// @defgroup test_persist_task_update "test_persist_task_update"
/// @{
/// @brief Test updating an existing task.
/// @post Task record updated with new status.
/// @pre Task already persisted.
/// @}
void test_persist_task_update(void);

/// @defgroup test_persist_task_with_logs "test_persist_task_with_logs"
/// @{
/// @brief Test persisting a task with log entries.
/// @post Logs serialized as JSON in task record.
/// @pre Task has logs attached.
/// @}
void test_persist_task_with_logs(void);

/// @defgroup test_persist_task_failed_extracts_error "test_persist_task_failed_extracts_error"
/// @{
/// @brief Test that FAILED task extracts last error message.
/// @post record.error contains last error message.
/// @pre Task has FAILED status with ERROR logs.
/// @}
void test_persist_task_failed_extracts_error(void);

/// @defgroup test_persist_tasks_batch "test_persist_tasks_batch"
/// @{
/// @brief Test persisting multiple tasks.
/// @post All task records created.
/// @pre Empty database.
/// @}
void test_persist_tasks_batch(void);

/// @defgroup test_load_tasks "test_load_tasks"
/// @{
/// @brief Test loading tasks from database.
/// @post Returns list of Task objects with correct data.
/// @pre Tasks persisted.
/// @}
void test_load_tasks(void);

/// @defgroup test_load_tasks_with_status_filter "test_load_tasks_with_status_filter"
/// @{
/// @brief Test loading tasks filtered by status.
/// @post Returns only tasks matching status filter.
/// @pre Tasks with different statuses persisted.
/// @}
void test_load_tasks_with_status_filter(void);

/// @defgroup test_load_tasks_with_limit "test_load_tasks_with_limit"
/// @{
/// @brief Test loading tasks with limit.
/// @post Returns at most `limit` tasks.
/// @pre Multiple tasks persisted.
/// @}
void test_load_tasks_with_limit(void);

/// @defgroup test_delete_tasks "test_delete_tasks"
/// @{
/// @brief Test deleting tasks by ID list.
/// @post Specified tasks deleted, others remain.
/// @pre Tasks persisted.
/// @}
void test_delete_tasks(void);

/// @defgroup test_delete_tasks_empty_list "test_delete_tasks_empty_list"
/// @{
/// @brief Test deleting with empty list (no-op).
/// @post No error, no changes.
/// @pre None.
/// @}
void test_delete_tasks_empty_list(void);

/// @defgroup test_persist_task_with_datetime_in_params "test_persist_task_with_datetime_in_params"
/// @{
/// @brief Test json_serializable handles datetime in params.
/// @post Params serialized correctly.
/// @pre Task params contain datetime values.
/// @}
void test_persist_task_with_datetime_in_params(void);

/// @defgroup test_persist_task_resolves_environment_slug_to_existing_id "test_persist_task_resolves_environment_slug_to_existing_id"
/// @{
/// @brief Ensure slug-like environment token resolves to environments.id before persisting task.
/// @post task_records.environment_id stores actual environments.id and does not violate FK.
/// @pre environments table contains env with name convertible to provided slug token.
/// @}
void test_persist_task_resolves_environment_slug_to_existing_id(void);

/// @defgroup TranslateCorrectionTests "TranslateCorrectionTests"
/// @{
/// @brief Tests for term correction API endpoints and DictionaryManager correction methods.
/// @}
void TranslateCorrectionTests(void);

/// @defgroup test_submit_correction_creates_entry "test_submit_correction_creates_entry"
/// @{
/// @brief Verify that a correction creates a new dictionary entry.
/// @}
void test_submit_correction_creates_entry(void);

/// @defgroup test_submit_correction_conflict_detected "test_submit_correction_conflict_detected"
/// @{
/// @brief Verify conflict detection when entry already exists.
/// @}
void test_submit_correction_conflict_detected(void);

/// @defgroup test_submit_correction_overwrite "test_submit_correction_overwrite"
/// @{
/// @brief Verify that correction overwrites existing entry.
/// @}
void test_submit_correction_overwrite(void);

/// @defgroup test_bulk_corrections_atomic "test_bulk_corrections_atomic"
/// @{
/// @brief Verify bulk corrections are applied atomically.
/// @}
void test_bulk_corrections_atomic(void);

/// @defgroup test_api_correction_missing_dict "test_api_correction_missing_dict"
/// @{
/// @brief Verify POST corrections without dictionary_id returns 422.
/// @}
void test_api_correction_missing_dict(void);

/// @defgroup test_api_bulk_corrections "test_api_bulk_corrections"
/// @{
/// @brief Verify POST /corrections/bulk works.
/// @}
void test_api_bulk_corrections(void);

/// @defgroup TestTranslateExecutorFilter "TestTranslateExecutorFilter"
/// @{
/// @brief Verify TranslationExecutor._filter_new_keys contracts — key dedup, empty-set, guard triggers.
/// @}
void TestTranslateExecutorFilter(void);

/// @defgroup test_no_prior_run_returns_all_rows "test_no_prior_run_returns_all_rows"
/// @{
/// @}
void test_no_prior_run_returns_all_rows(void);

/// @defgroup test_filters_existing_keys "test_filters_existing_keys"
/// @{
/// @}
void test_filters_existing_keys(void);

/// @defgroup test_composite_keys "test_composite_keys"
/// @{
/// @}
void test_composite_keys(void);

/// @defgroup test_all_keys_existing_returns_empty "test_all_keys_existing_returns_empty"
/// @{
/// @}
void test_all_keys_existing_returns_empty(void);

/// @defgroup test_empty_key_cols_returns_all_rows "test_empty_key_cols_returns_all_rows"
/// @{
/// @}
void test_empty_key_cols_returns_all_rows(void);

/// @defgroup test_null_source_data_handled "test_null_source_data_handled"
/// @{
/// @}
void test_null_source_data_handled(void);

/// @defgroup test_prior_run_no_records_returns_all "test_prior_run_no_records_returns_all"
/// @{
/// @}
void test_prior_run_no_records_returns_all(void);

/// @defgroup test_key_cols_none_returns_all "test_key_cols_none_returns_all"
/// @{
/// @}
void test_key_cols_none_returns_all(void);

/// @defgroup TranslateHistoryTests "TranslateHistoryTests"
/// @{
/// @brief Tests for run history list/detail endpoints and metrics aggregation.
/// @}
void TranslateHistoryTests(void);

/// @defgroup test_list_runs_empty "test_list_runs_empty"
/// @{
/// @brief Verify runs list returns empty result initially.
/// @}
void test_list_runs_empty(void);

/// @defgroup test_list_runs_with_data "test_list_runs_with_data"
/// @{
/// @brief Verify runs list returns data when runs exist.
/// @}
void test_list_runs_with_data(void);

/// @defgroup test_list_runs_filter_job_id "test_list_runs_filter_job_id"
/// @{
/// @brief Verify filtering runs by job_id works.
/// @}
void test_list_runs_filter_job_id(void);

/// @defgroup test_list_runs_filter_status "test_list_runs_filter_status"
/// @{
/// @brief Verify filtering runs by status works.
/// @}
void test_list_runs_filter_status(void);

/// @defgroup test_get_run_detail "test_get_run_detail"
/// @{
/// @brief Verify run detail returns config_snapshot, records, events.
/// @}
void test_get_run_detail(void);

/// @defgroup test_get_job_metrics "test_get_job_metrics"
/// @{
/// @brief Verify metrics endpoint returns aggregated data.
/// @}
void test_get_job_metrics(void);

/// @defgroup test_get_all_metrics "test_get_all_metrics"
/// @{
/// @brief Verify global metrics endpoint returns data.
/// @}
void test_get_all_metrics(void);

/// @defgroup test_metrics_empty_job "test_metrics_empty_job"
/// @{
/// @brief Verify metrics for job with no runs returns zeros.
/// @}
void test_metrics_empty_job(void);

/// @defgroup test_run_detail_not_found "test_run_detail_not_found"
/// @{
/// @brief Verify 404 on non-existent run detail.
/// @}
void test_run_detail_not_found(void);

/// @defgroup test_list_runs_includes_language_info "test_list_runs_includes_language_info"
/// @{
/// @brief Verify run list includes target_languages, total_translated, and language_stats.
/// @}
void test_list_runs_includes_language_info(void);

/// @defgroup test_metrics_per_language_breakdown "test_metrics_per_language_breakdown"
/// @{
/// @brief Verify metrics endpoint returns per_language_metrics.
/// @}
void test_metrics_per_language_breakdown(void);

/// @defgroup test_metric_snapshot_stores_per_language "test_metric_snapshot_stores_per_language"
/// @{
/// @brief Verify MetricSnapshot stores per_language_metrics via prune_expired.
/// @}
void test_metric_snapshot_stores_per_language(void);

/// @defgroup test_combined_metrics_live_and_snapshot "test_combined_metrics_live_and_snapshot"
/// @{
/// @brief Verify combined metrics merge live + snapshot per-language data.
/// @}
void test_combined_metrics_live_and_snapshot(void);

/// @defgroup TranslateJobTests "TranslateJobTests"
/// @{
/// @brief Tests for translation job CRUD endpoints and service layer with column validation.
/// @}
void TranslateJobTests(void);

/// @defgroup valid_job_payload "valid_job_payload"
/// @{
/// @brief Standard valid payload for creating a translation job.
/// @}
void valid_job_payload(void);

/// @defgroup MockConfigManager "MockConfigManager"
/// @{
/// @brief Mock ConfigManager for service tests that returns a test environment.
/// @}
void MockConfigManager(void);

/// @defgroup db_session "db_session"
/// @{
/// @brief Create a fresh DB session with transaction rollback for each test.
/// @}
void db_session(void);

/// @defgroup mock_api_deps "mock_api_deps"
/// @{
/// @brief Override FastAPI dependencies (including get_db with in-memory SQLite) for API route tests.
/// @}
void mock_api_deps(void);

/// @defgroup client "client"
/// @{
/// @brief FastAPI TestClient for API route tests.
/// @}
void client(void);

/// @defgroup test_create_job_valid "test_create_job_valid"
/// @{
/// @brief Verify that a valid job payload creates a job successfully.
/// @}
void test_create_job_valid(void);

/// @defgroup test_create_job_missing_translation_column "test_create_job_missing_translation_column"
/// @{
/// @brief Verify that creating a job with datasource but no translation column raises ValueError.
/// @}
void test_create_job_missing_translation_column(void);

/// @defgroup test_create_job_invalid_upsert_strategy "test_create_job_invalid_upsert_strategy"
/// @{
/// @brief Verify that an invalid upsert strategy is rejected.
/// @}
void test_create_job_invalid_upsert_strategy(void);

/// @defgroup test_get_job "test_get_job"
/// @{
/// @brief Verify that a job can be retrieved by ID.
/// @}
void test_get_job(void);

/// @defgroup test_get_job_not_found "test_get_job_not_found"
/// @{
/// @brief Verify that getting a non-existent job raises ValueError.
/// @}
void test_get_job_not_found(void);

/// @defgroup test_list_jobs "test_list_jobs"
/// @{
/// @brief Verify that listing jobs returns all created jobs.
/// @}
void test_list_jobs(void);

/// @defgroup test_list_jobs_with_status_filter "test_list_jobs_with_status_filter"
/// @{
/// @brief Verify that listing jobs with a status filter works.
/// @}
void test_list_jobs_with_status_filter(void);

/// @defgroup test_update_job "test_update_job"
/// @{
/// @brief Verify that a job can be updated.
/// @}
void test_update_job(void);

/// @defgroup test_delete_job "test_delete_job"
/// @{
/// @brief Verify that a job can be deleted.
/// @}
void test_delete_job(void);

/// @defgroup test_duplicate_job "test_duplicate_job"
/// @{
/// @brief Verify that a job can be duplicated.
/// @}
void test_duplicate_job(void);

/// @defgroup test_duplicate_job_custom_name "test_duplicate_job_custom_name"
/// @{
/// @brief Verify that a job can be duplicated with a custom name.
/// @}
void test_duplicate_job_custom_name(void);

/// @defgroup test_detect_virtual_columns "test_detect_virtual_columns"
/// @{
/// @brief Verify virtual column detection from column metadata.
/// @}
void test_detect_virtual_columns(void);

/// @defgroup test_get_dialect_from_database "test_get_dialect_from_database"
/// @{
/// @brief Verify dialect extraction from Superset database records.
/// @}
void test_get_dialect_from_database(void);

/// @defgroup test_get_dialect_from_database_unsupported "test_get_dialect_from_database_unsupported"
/// @{
/// @brief Verify that unsupported dialects raise ValueError.
/// @}
void test_get_dialect_from_database_unsupported(void);

/// @defgroup test_api_create_job "test_api_create_job"
/// @{
/// @brief Verify POST /api/translate/jobs returns 201 with valid payload.
/// @}
void test_api_create_job(void);

/// @defgroup test_api_list_jobs "test_api_list_jobs"
/// @{
/// @brief Verify GET /api/translate/jobs returns 200.
/// @}
void test_api_list_jobs(void);

/// @defgroup test_api_get_job_not_found "test_api_get_job_not_found"
/// @{
/// @brief Verify GET non-existent job returns 404.
/// @}
void test_api_get_job_not_found(void);

/// @defgroup test_api_delete_job_not_found "test_api_delete_job_not_found"
/// @{
/// @brief Verify DELETE non-existent job returns 404.
/// @}
void test_api_delete_job_not_found(void);

/// @defgroup test_api_duplicate_job_not_found "test_api_duplicate_job_not_found"
/// @{
/// @brief Verify duplicating a non-existent job returns 404.
/// @}
void test_api_duplicate_job_not_found(void);

/// @defgroup test_api_create_job_422_missing_name "test_api_create_job_422_missing_name"
/// @{
/// @brief Verify POST with missing required fields returns 422.
/// @}
void test_api_create_job_422_missing_name(void);

/// @defgroup test_api_datasource_columns_missing_env "test_api_datasource_columns_missing_env"
/// @{
/// @brief Verify datasource columns endpoint without env_id returns 422.
/// @}
void test_api_datasource_columns_missing_env(void);

/// @defgroup test_api_datasource_columns_bad_env "test_api_datasource_columns_bad_env"
/// @{
/// @brief Verify datasource columns with unknown env returns 400.
/// @}
void test_api_datasource_columns_bad_env(void);

/// @defgroup test_api_update_job_not_found "test_api_update_job_not_found"
/// @{
/// @brief Verify PUT non-existent job returns 404.
/// @}
void test_api_update_job_not_found(void);

/// @defgroup TranslateSchedulerTests "TranslateSchedulerTests"
/// @{
/// @brief Tests for TranslationScheduler CRUD and APScheduler integration.
/// @}
void TranslateSchedulerTests(void);

/// @defgroup test_create_schedule "test_create_schedule"
/// @{
/// @brief Verify schedule creation with valid params.
/// @}
void test_create_schedule(void);

/// @defgroup test_update_schedule "test_update_schedule"
/// @{
/// @brief Verify schedule update.
/// @}
void test_update_schedule(void);

/// @defgroup test_delete_schedule "test_delete_schedule"
/// @{
/// @brief Verify schedule deletion.
/// @}
void test_delete_schedule(void);

/// @defgroup test_enable_disable_schedule "test_enable_disable_schedule"
/// @{
/// @brief Verify enable/disable toggle.
/// @}
void test_enable_disable_schedule(void);

/// @defgroup test_get_schedule_not_found "test_get_schedule_not_found"
/// @{
/// @brief Verify ValueError on getting non-existent schedule.
/// @}
void test_get_schedule_not_found(void);

/// @defgroup test_list_active_schedules "test_list_active_schedules"
/// @{
/// @brief Verify listing only active schedules.
/// @}
void test_list_active_schedules(void);

/// @defgroup test_get_next_executions "test_get_next_executions"
/// @{
/// @brief Verify next execution time computation.
/// @}
void test_get_next_executions(void);

/// @defgroup test_get_next_executions_invalid "test_get_next_executions_invalid"
/// @{
/// @brief Verify invalid cron returns empty list.
/// @}
void test_get_next_executions_invalid(void);

/// @defgroup TestTranslateSchedulerExecution "TestTranslateSchedulerExecution"
/// @{
/// @brief Verify execute_scheduled_translation contracts — trigger_type dispatch, baseline expiry fallback.
/// @}
void TestTranslateSchedulerExecution(void);

/// @defgroup test_new_key_only_mode "test_new_key_only_mode"
/// @{
/// @}
void test_new_key_only_mode(void);

/// @defgroup test_baseline_expired_fallback "test_baseline_expired_fallback"
/// @{
/// @}
void test_baseline_expired_fallback(void);

/// @defgroup test_full_mode_default "test_full_mode_default"
/// @{
/// @}
void test_full_mode_default(void);

/// @defgroup test_inactive_schedule_skips "test_inactive_schedule_skips"
/// @{
/// @}
void test_inactive_schedule_skips(void);

/// @defgroup test_schedule_not_found_skips "test_schedule_not_found_skips"
/// @{
/// @}
void test_schedule_not_found_skips(void);

/// @defgroup test_baseline_expired_full_mode "test_baseline_expired_full_mode"
/// @{
/// @}
void test_baseline_expired_full_mode(void);

/// @defgroup test_execution_error_handled "test_execution_error_handled"
/// @{
/// @}
void test_execution_error_handled(void);

/// @defgroup TestTranslateSchedulerGuard "TestTranslateSchedulerGuard"
/// @{
/// @brief Verify execute_scheduled_translation concurrency guard and stale-PENDING clearance contracts.
/// @}
void TestTranslateSchedulerGuard(void);

/// @defgroup test_concurrent_run_skips "test_concurrent_run_skips"
/// @{
/// @}
void test_concurrent_run_skips(void);

/// @defgroup test_recent_pending_run_not_stale "test_recent_pending_run_not_stale"
/// @{
/// @}
void test_recent_pending_run_not_stale(void);

/// @defgroup test_stale_pending_cleared_and_proceeds "test_stale_pending_cleared_and_proceeds"
/// @{
/// @}
void test_stale_pending_cleared_and_proceeds(void);

/// @defgroup test_multiple_stale_pending_all_cleared "test_multiple_stale_pending_all_cleared"
/// @{
/// @}
void test_multiple_stale_pending_all_cleared(void);

/// @defgroup docker_backend_Dockerfile "docker.backend.Dockerfile"
/// @{
/// @brief Backend Dockerfile — Python 3.11 slim + Playwright + entrypoint с установкой сертификатов.
/// @post Образ с backend API, Playwright, entrypoint для bootstrap admin и установки сертификатов.
/// @pre Docker builder context — корень проекта. backend/ и docker/ доступны.
/// @}
void docker_backend_Dockerfile(void);

/// @defgroup docker_backend_entrypoint "docker.backend.entrypoint"
/// @{
/// @brief Container entrypoint — установка корп. сертификатов, Playwright (lazy), bootstrap admin,
/// @}
void docker_backend_entrypoint(void);

/// @defgroup docker_backend_entrypoint_install_certificates "docker.backend.entrypoint.install_certificates"
/// @{
/// @brief Устанавливает корпоративные .crt сертификаты из CERTS_PATH в системное хранилище Debian.
/// @pre CERTS_PATH указывает на директорию (может быть пуста или не существовать).
/// @}
void docker_backend_entrypoint_install_certificates(void);

/// @defgroup docker_backend_entrypoint_bootstrap_admin "docker.backend.entrypoint.bootstrap_admin"
/// @{
/// @brief Создание admin пользователя из переменных окружения (идемпотентно).
/// @post Admin пользователь создан в БД (если ещё не существовал).
/// @pre INITIAL_ADMIN_CREATE=true, INITIAL_ADMIN_USERNAME и INITIAL_ADMIN_PASSWORD заданы.
/// @}
void docker_backend_entrypoint_bootstrap_admin(void);

/// @defgroup docker_backend_entrypoint_install_playwright "docker.backend.entrypoint.install_playwright"
/// @{
/// @brief Lazy установка Playwright Chromium (~377 MB) при первом запуске.
/// @post Chromium установлен в PLAYWRIGHT_BROWSERS_PATH.
/// @pre ~/.cache/ms-playwright доступен (можно закешировать volume).
/// @}
void docker_backend_entrypoint_install_playwright(void);

/// @defgroup docker_frontend_Dockerfile "docker.frontend.Dockerfile"
/// @{
/// @brief Frontend Dockerfile — сборка SvelteKit (node:20) + nginx runtime с опциональным SSL.
/// @post nginx:alpine образ со статикой SvelteKit, entrypoint для выбора HTTP/SSL конфига.
/// @pre Docker builder context — корень проекта. frontend/ и docker/ доступны.
/// @}
void docker_frontend_Dockerfile(void);

/// @defgroup docker_frontend_entrypoint "docker.frontend.entrypoint"
/// @{
/// @brief Entrypoint для nginx-контейнера — установка корп. CA-сертификатов в Alpine,
/// @}
void docker_frontend_entrypoint(void);

/// @defgroup docker_frontend_entrypoint_install_ca_certificates "docker.frontend.entrypoint.install_ca_certificates"
/// @{
/// @brief Устанавливает .crt файлы из /opt/certs в системное хранилище Alpine.
/// @post Сертификаты скопированы в /usr/local/share/ca-certificates/ и добавлены в trust.
/// @pre /opt/certs может быть пуст или не существовать.
/// @}
void docker_frontend_entrypoint_install_ca_certificates(void);

/// @defgroup docker_frontend_entrypoint_select_nginx_config "docker.frontend.entrypoint.select_nginx_config"
/// @{
/// @brief Определяет, есть ли сертификаты для SSL, и копирует нужный nginx конфиг.
/// @post Если есть оба файла — /etc/nginx/ssl/ создан, server.crt/key скопированы,
/// @pre /opt/certs/server.crt и /opt/certs/server.key — опциональные SSL-сертификаты.
/// @}
void docker_frontend_entrypoint_select_nginx_config(void);

/// @defgroup docker_nginx_ssl_conf "docker.nginx.ssl.conf"
/// @{
/// @brief Nginx config с опциональным SSL — HTTP (порт 80) + HTTPS (порт 443).
/// @}
void docker_nginx_ssl_conf(void);

/// @defgroup AuthFixture "AuthFixture"
/// @{
/// @brief Playwright fixture for authenticated browser contexts.
/// @}
void AuthFixture(void);

/// @defgroup GlobalSetup "GlobalSetup"
/// @{
/// @brief Pre-flight check before any E2E tests run.
/// @post Exits with 1 if either service is down, else sets ENV vars.
/// @pre Backend and frontend must be reachable.
/// @}
void GlobalSetup(void);

/// @defgroup ApiHelper "ApiHelper"
/// @{
/// @brief Helper for backend API calls in E2E tests (settings CRUD, etc.)
/// @}
void ApiHelper(void);

/// @defgroup frontend_e2e_helpers_api_helper_js__getToken "frontend/e2e/helpers/api.helper.js::getToken"
/// @{
/// @}
void frontend_e2e_helpers_api_helper_js__getToken(void);

/// @defgroup frontend_e2e_helpers_api_helper_js__apiGet "frontend/e2e/helpers/api.helper.js::apiGet"
/// @{
/// @}
void frontend_e2e_helpers_api_helper_js__apiGet(void);

/// @defgroup frontend_e2e_helpers_api_helper_js__apiPost "frontend/e2e/helpers/api.helper.js::apiPost"
/// @{
/// @}
void frontend_e2e_helpers_api_helper_js__apiPost(void);

/// @defgroup frontend_e2e_helpers_api_helper_js__apiPut "frontend/e2e/helpers/api.helper.js::apiPut"
/// @{
/// @}
void frontend_e2e_helpers_api_helper_js__apiPut(void);

/// @defgroup frontend_e2e_helpers_api_helper_js__apiDelete "frontend/e2e/helpers/api.helper.js::apiDelete"
/// @{
/// @}
void frontend_e2e_helpers_api_helper_js__apiDelete(void);

/// @defgroup run_enterprise_clean_e2e "run-enterprise-clean-e2e"
/// @{
/// @brief Enterprise Clean E2E Orchestrator — полный протокол тестирования пустого образа перед передачей.
/// @}
void run_enterprise_clean_e2e(void);

/// @defgroup EnterpriseCleanSetupE2E "EnterpriseCleanSetupE2E"
/// @{
/// @brief Stage 1: E2E test for enterprise-clean empty image — first-run setup via StartupEnvironmentWizard.
/// @@RATIONALE All 4 tests pass after fixing: (1) button ambiguity — zero-state page and wizard modal both have 'Начать настройку' button, resolved by scoping to wizard modal via .fixed.inset-0.z-50; (2) wizard detection — changed from waitForSelector('text=...') to getByText() with regex for locale-robust matching; (3) form fill — connections.* i18n keys missing in Docker build, switched to placeholder-based locators scoped within wizard; (4) settings navigation — use authPage fixture for consistent login
/// @@REJECTED Using waitForSelector('text=...') fails for locale-sensitive text. getByLabel() with connections.* keys fails when i18n namespace missing. Using page.goto() with authPage fixture causes page reload issues
/// @}
void EnterpriseCleanSetupE2E(void);

/// @defgroup GitE2E "GitE2E"
/// @{
/// @brief E2E tests for Git integration — config CRUD, connection test.
/// @}
void GitE2E(void);

/// @defgroup LiveProjectCheckE2E "LiveProjectCheckE2E"
/// @{
/// @brief Stage 2: E2E test for live project verification — validates dashboard LLM analysis,
/// @}
void LiveProjectCheckE2E(void);

/// @defgroup LoginE2E "LoginE2E"
/// @{
/// @brief E2E tests for login/logout flow.
/// @}
void LoginE2E(void);

/// @defgroup MigrationE2E "MigrationE2E"
/// @{
/// @brief E2E tests for dataset/environment migration and sync.
/// @}
void MigrationE2E(void);

/// @defgroup SettingsE2E "SettingsE2E"
/// @{
/// @brief E2E tests for Settings page — environments, LLM providers, Git config.
/// @}
void SettingsE2E(void);

/// @defgroup SmokeE2E "SmokeE2E"
/// @{
/// @brief Golden-path smoke test: login → settings → translate → git → verify.
/// @}
void SmokeE2E(void);

/// @defgroup TranslationE2E "TranslationE2E"
/// @{
/// @brief E2E tests for the translation job lifecycle: create → preview → accept → run.
/// @}
void TranslationE2E(void);

/// @defgroup PlaywrightConfig "PlaywrightConfig"
/// @{
/// @brief Playwright E2E test configuration for ss-tools frontend.
/// @invariant All E2E tests run against a fully deployed stack (DB + backend + frontend).
/// @}
void PlaywrightConfig(void);

/// @defgroup handleValidate_Function "handleValidate:Function"
/// @{
/// @brief Triggers dashboard validation task.
/// @}
void handleValidate_Function(void);

/// @defgroup openGit_Function "openGit:Function"
/// @{
/// @brief Opens the Git management modal for a dashboard.
/// @}
void openGit_Function(void);

/// @defgroup initializeForm_Function "initializeForm:Function"
/// @{
/// @brief Initialize form data with default values from the schema.
/// @post formData is initialized with default values or empty strings.
/// @pre schema is provided and contains properties.
/// @}
void initializeForm_Function(void);

/// @defgroup Footer "Footer"
/// @{
/// @brief Displays the application footer with copyright information.
/// @}
void Footer(void);

/// @defgroup updateMapping_Function "updateMapping:Function"
/// @{
/// @brief Updates a mapping for a specific source database.
/// @post Parent callback receives normalized mapping payload.
/// @pre sourceUuid and targetUuid are provided.
/// @}
void updateMapping_Function(void);

/// @defgroup getSuggestion_Function "getSuggestion:Function"
/// @{
/// @brief Finds a suggestion for a source database.
/// @post Returns matching suggestion object or undefined.
/// @pre sourceUuid is provided.
/// @}
void getSuggestion_Function(void);

/// @defgroup MissingMappingModal "MissingMappingModal"
/// @{
/// @brief Prompts the user to provide a database mapping when one is missing during migration.
/// @invariant Modal blocks migration progress until resolved or cancelled.
/// @}
void MissingMappingModal(void);

/// @defgroup resolve_Function "resolve:Function"
/// @{
/// @brief Resolves the missing mapping via callback prop.
/// @post Parent callback receives mapping payload and modal closes.
/// @pre selectedTargetUuid must be set.
/// @}
void resolve_Function(void);

/// @defgroup cancel_Function "cancel:Function"
/// @{
/// @brief Cancels the mapping resolution modal.
/// @post Parent cancel callback is invoked and modal is hidden.
/// @pre Modal is open.
/// @}
void cancel_Function(void);

/// @defgroup Navbar "Navbar"
/// @{
/// @brief Main navigation bar for the application.
/// @}
void Navbar(void);

/// @defgroup PasswordPrompt "PasswordPrompt"
/// @{
/// @brief A modal component to prompt the user for database passwords when a migration task is paused.
/// @}
void PasswordPrompt(void);

/// @defgroup handleSubmit_Function "handleSubmit:Function"
/// @{
/// @brief Validates and forwards passwords to resume the task.
/// @post Parent resume callback receives passwords payload.
/// @pre All database passwords must be entered.
/// @}
void handleSubmit_Function(void);

/// @defgroup handleCancel_Function "handleCancel:Function"
/// @{
/// @brief Cancels the password prompt.
/// @post Parent cancel callback is invoked and show is set to false.
/// @pre Modal is open.
/// @}
void handleCancel_Function(void);

/// @defgroup handleSort_Function "handleSort:Function"
/// @{
/// @brief Toggles sort direction or changes sort column.
/// @post sortColumn and sortDirection state updated.
/// @pre column name is provided.
/// @}
void handleSort_Function(void);

/// @defgroup handleSelectionChange_Function "handleSelectionChange:Function"
/// @{
/// @brief Handles individual checkbox changes.
/// @post selectedIds array updated.
/// @pre dashboard ID and checked status provided.
/// @}
void handleSelectionChange_Function(void);

/// @defgroup handleSelectAll_Function "handleSelectAll:Function"
/// @{
/// @brief Handles select all checkbox.
/// @post selectedIds array updated for all paginated items.
/// @pre checked status provided.
/// @}
void handleSelectAll_Function(void);

/// @defgroup goToPage_Function "goToPage:Function"
/// @{
/// @brief Changes current page.
/// @post currentPage state updated if within valid range.
/// @pre page index is provided.
/// @}
void goToPage_Function(void);

/// @defgroup getRepositoryStatusToken_Function "getRepositoryStatusToken:Function"
/// @{
/// @brief Returns normalized repository status token for a dashboard.
/// @post Returns one of loading|no_repo|synced|changes|behind_remote|ahead_remote|diverged|error.
/// @pre Dashboard exists.
/// @}
void getRepositoryStatusToken_Function(void);

/// @defgroup isRepositoryReady_Function "isRepositoryReady:Function"
/// @{
/// @brief Determines whether git actions can run for a dashboard.
/// @}
void isRepositoryReady_Function(void);

/// @defgroup invalidateRepositoryStatuses_Function "invalidateRepositoryStatuses:Function"
/// @{
/// @brief Marks dashboard statuses as loading so they are refetched.
/// @}
void invalidateRepositoryStatuses_Function(void);

/// @defgroup resolveRepositoryStatusToken_Function "resolveRepositoryStatusToken:Function"
/// @{
/// @brief Converts git status payload into a stable UI status token.
/// @}
void resolveRepositoryStatusToken_Function(void);

/// @defgroup loadRepositoryStatuses_Function "loadRepositoryStatuses:Function"
/// @{
/// @brief Hydrates repository status map for dashboards in repository mode.
/// @}
void loadRepositoryStatuses_Function(void);

/// @defgroup runBulkGitAction_Function "runBulkGitAction:Function"
/// @{
/// @brief Executes git action for selected dashboards with limited parallelism.
/// @}
void runBulkGitAction_Function(void);

/// @defgroup handleBulkSync_Function "handleBulkSync:Function"
/// @{
/// @}
void handleBulkSync_Function(void);

/// @defgroup handleBulkCommit_Function "handleBulkCommit:Function"
/// @{
/// @}
void handleBulkCommit_Function(void);

/// @defgroup handleBulkPull_Function "handleBulkPull:Function"
/// @{
/// @}
void handleBulkPull_Function(void);

/// @defgroup handleBulkPush_Function "handleBulkPush:Function"
/// @{
/// @}
void handleBulkPush_Function(void);

/// @defgroup handleBulkDelete_Function "handleBulkDelete:Function"
/// @{
/// @brief Removes selected repositories from storage and binding table.
/// @}
void handleBulkDelete_Function(void);

/// @defgroup handleManageSelected_Function "handleManageSelected:Function"
/// @{
/// @brief Opens Git manager for exactly one selected dashboard.
/// @}
void handleManageSelected_Function(void);

/// @defgroup resolveDashboardRef_Function "resolveDashboardRef:Function"
/// @{
/// @brief Resolves dashboard slug from payload fields.
/// @post Returns slug string or null if unavailable.
/// @pre Dashboard metadata is provided.
/// @}
void resolveDashboardRef_Function(void);

/// @defgroup openGitManagerForDashboard_Function "openGitManagerForDashboard:Function"
/// @{
/// @brief Opens Git manager for provided dashboard metadata.
/// @}
void openGitManagerForDashboard_Function(void);

/// @defgroup handleInitializeRepositories_Function "handleInitializeRepositories:Function"
/// @{
/// @brief Opens Git manager from bulk actions to initialize selected repository.
/// @}
void handleInitializeRepositories_Function(void);

/// @defgroup getSortStatusValue_Function "getSortStatusValue:Function"
/// @{
/// @brief Returns sort value for status column based on mode.
/// @}
void getSortStatusValue_Function(void);

/// @defgroup getStatusLabel_Function "getStatusLabel:Function"
/// @{
/// @brief Returns localized label for status column.
/// @}
void getStatusLabel_Function(void);

/// @defgroup getStatusBadgeClass_Function "getStatusBadgeClass:Function"
/// @{
/// @brief Returns badge style for status column.
/// @}
void getStatusBadgeClass_Function(void);

/// @defgroup TaskHistory "TaskHistory"
/// @{
/// @brief Displays a list of recent tasks with their status and allows selecting them for viewing logs.
/// @}
void TaskHistory(void);

/// @defgroup getStatusColor_Function "getStatusColor:Function"
/// @{
/// @brief Returns the CSS color class for a given task status.
/// @post Returns tailwind color class string.
/// @pre status string is provided.
/// @}
void getStatusColor_Function(void);

/// @defgroup onDestroy_Function "onDestroy:Function"
/// @{
/// @brief Cleans up the polling interval when the component is destroyed.
/// @post Polling interval is cleared.
/// @pre Component is being destroyed.
/// @}
void onDestroy_Function(void);

/// @defgroup TaskList "TaskList"
/// @{
/// @brief Displays a list of tasks with their status and execution details.
/// @}
void TaskList(void);

/// @defgroup handleTaskClick_Function "handleTaskClick:Function"
/// @{
/// @brief Forwards the selected task through a callback prop.
/// @post Parent callback receives task id and task payload.
/// @pre taskId is provided.
/// @}
void handleTaskClick_Function(void);

/// @defgroup TaskLogViewer "TaskLogViewer"
/// @{
/// @brief Displays task logs inline (in drawer) or as modal. Merges real-time WebSocket logs with polled historical logs.
/// @invariant Real-time logs are always appended without duplicates.
/// @}
void TaskLogViewer(void);

/// @defgroup connect_Function "connect:Function"
/// @{
/// @brief Establishes WebSocket connection with exponential backoff and filter parameters.
/// @post WebSocket instance created and listeners attached.
/// @pre selectedTask must be set in the store.
/// @}
void connect_Function(void);

/// @defgroup handleFilterChange_Function "handleFilterChange:Function"
/// @{
/// @brief Handles filter changes and reconnects WebSocket with new parameters.
/// @post WebSocket reconnected with new filter parameters, logs cleared.
/// @pre event.detail contains source and level filter values.
/// @}
void handleFilterChange_Function(void);

/// @defgroup fetchTargetDatabases_Function "fetchTargetDatabases:Function"
/// @{
/// @brief Fetches available databases from target environment for mapping.
/// @post targetDatabases array populated with available databases.
/// @pre selectedTask must have to_env parameter set.
/// @}
void fetchTargetDatabases_Function(void);

/// @defgroup handleMappingResolve_Function "handleMappingResolve:Function"
/// @{
/// @brief Resolves missing database mapping and continues migration.
/// @post Mapping created in backend, task resumed with resolution params.
/// @pre event.detail contains sourceDbUuid, targetDbUuid, targetDbName.
/// @}
void handleMappingResolve_Function(void);

/// @defgroup handlePasswordResume_Function "handlePasswordResume:Function"
/// @{
/// @brief Submits passwords and resumes paused migration task.
/// @post Task resumed with passwords, connection status restored to connected.
/// @pre event.detail contains passwords object.
/// @}
void handlePasswordResume_Function(void);

/// @defgroup startDataTimeout_Function "startDataTimeout:Function"
/// @{
/// @brief Starts timeout timer to detect idle connection.
/// @post waitingForData set to true after 5 seconds if no data received.
/// @pre connectionStatus is 'connected'.
/// @}
void startDataTimeout_Function(void);

/// @defgroup resetDataTimeout_Function "resetDataTimeout:Function"
/// @{
/// @brief Resets data timeout timer when new data arrives.
/// @post waitingForData reset to false, new timeout started.
/// @pre dataTimeout must be set.
/// @}
void resetDataTimeout_Function(void);

/// @defgroup Toast "Toast"
/// @{
/// @brief Displays transient notifications (toasts) in the bottom-right corner.
/// @}
void Toast(void);

/// @defgroup TaskLogViewerTest_Module "TaskLogViewerTest:Module"
/// @{
/// @brief Unit tests for TaskLogViewer component by mounting it and observing the DOM.
/// @invariant Duplicate logs are never appended. Polling only active for in-progress tasks.
/// @}
void TaskLogViewerTest_Module(void);

/// @defgroup verifySessionAndAccess_Function "verifySessionAndAccess:Function"
/// @{
/// @brief Validates session and optional permission gate before allowing protected content render.
/// @post hasRouteAccess=true only when user identity is valid and permission check (if provided) passes.
/// @pre auth store is initialized and can provide token/user state; navigation is available.
/// @}
void verifySessionAndAccess_Function(void);

/// @defgroup handleCreateBackup_Function "handleCreateBackup:Function"
/// @{
/// @brief Triggers a new backup task for the selected environment.
/// @post A new task is created on the backend.
/// @pre selectedEnvId must be a valid environment ID.
/// @return {Promise<void>}
/// @}
void handleCreateBackup_Function(void);

/// @defgroup handleUpdateSchedule_Function "handleUpdateSchedule:Function"
/// @{
/// @brief Updates the backup schedule for the selected environment.
/// @post Environment config is updated on the backend.
/// @pre selectedEnvId must be set.
/// @}
void handleUpdateSchedule_Function(void);

/// @defgroup loadBranches_Function "loadBranches:Function"
/// @{
/// @brief Загружает список веток для дашборда.
/// @post branches обновлен.
/// @pre dashboardId is provided.
/// @}
void loadBranches_Function(void);

/// @defgroup handleSelect_Function "handleSelect:Function"
/// @{
/// @brief Handles branch selection from dropdown.
/// @post handleCheckout is called with selected branch.
/// @pre event contains branch name.
/// @}
void handleSelect_Function(void);

/// @defgroup handleCheckout_Function "handleCheckout:Function"
/// @{
/// @brief Переключает текущую ветку.
/// @param {string} branchName - Имя ветки.
/// @post currentBranch обновлен, родительский callback вызван.
/// @}
void handleCheckout_Function(void);

/// @defgroup handleCreate_Function "handleCreate:Function"
/// @{
/// @brief Создает новую ветку.
/// @post Новая ветка создана и загружена; showCreate reset.
/// @pre newBranchName is not empty.
/// @}
void handleCreate_Function(void);

/// @defgroup loadHistory_Function "loadHistory:Function"
/// @{
/// @brief Fetch commit history from the backend.
/// @post history state is updated.
/// @pre dashboardId is valid.
/// @}
void loadHistory_Function(void);

/// @defgroup handleGenerateMessage_Function "handleGenerateMessage:Function"
/// @{
/// @brief Generates a commit message using LLM.
/// @}
void handleGenerateMessage_Function(void);

/// @defgroup loadStatus_Function "loadStatus:Function"
/// @{
/// @brief Загружает текущий статус репозитория и diff.
/// @pre dashboardId должен быть валидным.
/// @}
void loadStatus_Function(void);

/// @defgroup handleCommit_Function "handleCommit:Function"
/// @{
/// @brief Создает коммит с указанным сообщением.
/// @post Коммит создан и модальное окно закрыто.
/// @pre message не должно быть пустым.
/// @}
void handleCommit_Function(void);

/// @defgroup loadStatus_Watcher "loadStatus:Watcher"
/// @{
/// @}
void loadStatus_Watcher(void);

/// @defgroup normalizeEnvStage_Function "normalizeEnvStage:Function"
/// @{
/// @brief Normalize environment stage with legacy production fallback.
/// @post Returns DEV/PREPROD/PROD.
/// @}
void normalizeEnvStage_Function(void);

/// @defgroup resolveEnvUrl_Function "resolveEnvUrl:Function"
/// @{
/// @brief Resolve environment URL from consolidated or git-specific payload shape.
/// @post Returns stable URL string.
/// @}
void resolveEnvUrl_Function(void);

/// @defgroup loadEnvironments_Function "loadEnvironments:Function"
/// @{
/// @brief Fetch available environments from API.
/// @post environments state is populated.
/// @}
void loadEnvironments_Function(void);

/// @defgroup handleDeploy_Function "handleDeploy:Function"
/// @{
/// @brief Trigger deployment to selected environment.
/// @post Deploy request finishes and modal closes on success.
/// @pre selectedEnv must be set.
/// @}
void handleDeploy_Function(void);

/// @defgroup GitInitPanel "GitInitPanel"
/// @{
/// @brief Git initialization panel: select config, create remote repo, init local repo.
/// @}
void GitInitPanel(void);

/// @defgroup GitManager "GitManager"
/// @{
/// @brief Central Git management UI — thin shell delegating to sub-panels and composable handlers.
/// @}
void GitManager(void);

/// @defgroup GitMergeDialog "GitMergeDialog"
/// @{
/// @brief Unfinished merge recovery dialog: abort, continue, resolve conflicts.
/// @}
void GitMergeDialog(void);

/// @defgroup GitOperationsPanel "GitOperationsPanel"
/// @{
/// @brief Git server operations panel: pull, push, and deploy actions.
/// @}
void GitOperationsPanel(void);

/// @defgroup GitReleasePanel "GitReleasePanel"
/// @{
/// @brief Git release panel: promote branches via MR or direct mode.
/// @}
void GitReleasePanel(void);

/// @defgroup GitWorkspacePanel "GitWorkspacePanel"
/// @{
/// @brief Git workspace panel: sync, commit message input, diff viewer, commit action.
/// @}
void GitWorkspacePanel(void);

/// @defgroup GitManagerUnfinishedMergeIntegrationTest_Module "GitManagerUnfinishedMergeIntegrationTest:Module"
/// @{
/// @brief Protect unresolved-merge dialog contract in GitManager pull flow.
/// @}
void GitManagerUnfinishedMergeIntegrationTest_Module(void);

/// @defgroup UseGitManager "UseGitManager"
/// @{
/// @brief Composable for GitManager handler functions — extracted to reduce component size per INV_7.
/// @}
void UseGitManager(void);

/// @defgroup DocPreview "DocPreview"
/// @{
/// @brief UI component for previewing generated dataset documentation before saving.
/// @}
void DocPreview(void);

/// @defgroup ProviderConfig "ProviderConfig"
/// @{
/// @brief UI form for managing LLM provider configurations.
/// @}
void ProviderConfig(void);

/// @defgroup ValidationReport "ValidationReport"
/// @{
/// @brief Displays the results of an LLM-based dashboard validation task.
/// @}
void ValidationReport(void);

/// @defgroup provider_config_edit_contract_tests_Function "provider_config_edit_contract_tests:Function"
/// @{
/// @brief Validate edit and delete handler wiring plus normalized edit form state mapping.
/// @post Contract checks ensure edit click cannot degrade into no-op flow.
/// @pre ProviderConfig component source exists in expected path.
/// @}
void provider_config_edit_contract_tests_Function(void);

/// @defgroup isDirectory_Function "isDirectory:Function"
/// @{
/// @brief Checks if a file object represents a directory.
/// @param {Object} file - The file object to check.
/// @post Returns boolean.
/// @pre file object has mime_type property.
/// @return {boolean} True if it's a directory, false otherwise.
/// @}
void isDirectory_Function(void);

/// @defgroup formatSize_Function "formatSize:Function"
/// @{
/// @brief Formats file size in bytes into a human-readable string.
/// @param {number} bytes - The size in bytes.
/// @post Returns formatted string.
/// @pre bytes is a number.
/// @return {string} Formatted size (e.g., "1.2 MB").
/// @}
void formatSize_Function(void);

/// @defgroup formatDate_Function "formatDate:Function"
/// @{
/// @brief Formats an ISO date string into a localized readable format.
/// @param {string} dateStr - The date string to format.
/// @post Returns localized string.
/// @pre dateStr is a valid date string.
/// @return {string} Localized date and time.
/// @}
void formatDate_Function(void);

/// @defgroup handleDownload_Function "handleDownload:Function"
/// @{
/// @brief Downloads selected file through authenticated API request.
/// @post Browser download starts or user sees toast on failure.
/// @pre file is a non-directory storage entry with category/path.
/// @}
void handleDownload_Function(void);

/// @defgroup handleUpload_Function "handleUpload:Function"
/// @{
/// @brief Handles the file upload process.
/// @post The file is uploaded to the server and a success toast is shown.
/// @pre A file must be selected in the file input.
/// @}
void handleUpload_Function(void);

/// @defgroup handleDrop_Function "handleDrop:Function"
/// @{
/// @brief Handles the file drop event for drag-and-drop.
/// @param {DragEvent} event - The drop event.
/// @}
void handleDrop_Function(void);

/// @defgroup LogEntryRow "LogEntryRow"
/// @{
/// @brief Renders a single log entry with stacked layout optimized for narrow drawer panels.
/// @}
void LogEntryRow(void);

/// @defgroup formatTime_Function "formatTime:Function"
/// @{
/// @brief Format ISO timestamp to HH:MM:SS
/// @}
void formatTime_Function(void);

/// @defgroup LogFilterBar "LogFilterBar"
/// @{
/// @brief Compact filter toolbar for logs — level, source, and text search in a single dense row.
/// @}
void LogFilterBar(void);

/// @defgroup TaskLogPanel "TaskLogPanel"
/// @{
/// @brief Combines log filtering and display into a single cohesive light-themed panel.
/// @invariant Must always display logs in chronological order and respect auto-scroll preference.
/// @}
void TaskLogPanel(void);

/// @defgroup TaskResultPanel "TaskResultPanel"
/// @{
/// @brief Displays formatted task result summary with status badges and result details.
/// @}
void TaskResultPanel(void);

/// @defgroup handleRunDebug_Function "handleRunDebug:Function"
/// @{
/// @brief Triggers the debug task.
/// @post Task is started and polling begins.
/// @pre Required fields are selected.
/// @return {Promise<void>}
/// @}
void handleRunDebug_Function(void);

/// @defgroup startPolling_Function "startPolling:Function"
/// @{
/// @brief Polls for task completion.
/// @param {string} taskId - ID of the task.
/// @post Polls until success/failure.
/// @pre Task ID is valid.
/// @return {void}
/// @}
void startPolling_Function(void);

/// @defgroup MapperTool "MapperTool"
/// @{
/// @brief UI component for mapping dataset column verbose names using Superset SQL Lab or Excel files.
/// @}
void MapperTool(void);

/// @defgroup fetchData_Function "fetchData:Function"
/// @{
/// @brief Fetches environments.
/// @post envs array is populated.
/// @pre None.
/// @}
void fetchData_Function(void);

/// @defgroup handleRunMapper_Function "handleRunMapper:Function"
/// @{
/// @brief Triggers the MapperPlugin task via new sqllab/excel sources.
/// @post Mapper task is started and selectedTask is updated.
/// @pre selectedEnv and datasetId are set; source-specific fields are valid.
/// @}
void handleRunMapper_Function(void);

/// @defgroup handleGenerateDocs_Function "handleGenerateDocs:Function"
/// @{
/// @brief Triggers the LLM Documentation task.
/// @post Documentation task is started.
/// @pre selectedEnv and datasetId are set.
/// @}
void handleGenerateDocs_Function(void);

/// @defgroup Counter "Counter"
/// @{
/// @brief Simple counter demo component
/// @}
void Counter(void);

/// @defgroup ApiModule "ApiModule"
/// @{
/// @brief Handles all communication with the backend API via fetch wrappers with auth, error normalization, and toast feedback.
/// @}
void ApiModule(void);

/// @defgroup ReportsApiTest "ReportsApiTest"
/// @{
/// @brief Unit tests for reports API client functions: query string building, error normalization, and fetch wrappers.
/// @}
void ReportsApiTest(void);

/// @defgroup ReportsApiTest_Module "ReportsApiTest:Module"
/// @{
/// @brief Unit tests for reports API client functions: query string building, error normalization, and fetch wrappers.
/// @invariant Pure functions produce deterministic output. Async wrappers propagate structured errors.
/// @}
void ReportsApiTest_Module(void);

/// @defgroup TestBuildReportQueryString_Class "TestBuildReportQueryString:Class"
/// @{
/// @brief Validate query string construction from filter options.
/// @post Correct URLSearchParams string produced.
/// @pre Options object with various filter fields.
/// @}
void TestBuildReportQueryString_Class(void);

/// @defgroup TestNormalizeApiError_Class "TestNormalizeApiError:Class"
/// @{
/// @brief Validate error normalization for UI-state mapping.
/// @post Always returns {message, code, retryable} object.
/// @pre Various error types (Error, string, object).
/// @}
void TestNormalizeApiError_Class(void);

/// @defgroup TestGetReportsAsync_Class "TestGetReportsAsync:Class"
/// @{
/// @brief Validate getReports and getReportDetail with mocked api.fetchApi.
/// @post Functions call correct endpoints and propagate results/errors.
/// @pre api.fetchApi is mocked via vi.mock.
/// @}
void TestGetReportsAsync_Class(void);

/// @defgroup AssistantApi "AssistantApi"
/// @{
/// @brief API client wrapper for assistant chat, session-scoped prompts, confirmation actions, conversation management, and history retrieval.
/// @}
void AssistantApi(void);

/// @defgroup AssistantApi_Module "AssistantApi:Module"
/// @{
/// @brief API client wrapper for assistant chat, session-scoped prompts, confirmation actions, and history retrieval.
/// @invariant All assistant requests must use requestApi wrapper (no native fetch).
/// @}
void AssistantApi_Module(void);

/// @defgroup sendAssistantMessage_Function "sendAssistantMessage:Function"
/// @{
/// @brief Send a user message to assistant orchestrator endpoint.
/// @post Returns assistant response object with deterministic state.
/// @pre payload.message is a non-empty string.
/// @}
void sendAssistantMessage_Function(void);

/// @defgroup buildAssistantSeedMessage_Function "buildAssistantSeedMessage:Function"
/// @{
/// @brief Compose visible assistant seed text from context label and prompt body.
/// @post Returns trimmed seed message string for prefilled input.
/// @pre prompt contains the user-visible request.
/// @}
void buildAssistantSeedMessage_Function(void);

/// @defgroup confirmAssistantOperation_Function "confirmAssistantOperation:Function"
/// @{
/// @brief Confirm a pending risky assistant operation.
/// @post Returns execution response (started/success/failed).
/// @pre confirmationId references an existing pending token.
/// @}
void confirmAssistantOperation_Function(void);

/// @defgroup cancelAssistantOperation_Function "cancelAssistantOperation:Function"
/// @{
/// @brief Cancel a pending risky assistant operation.
/// @post Operation is cancelled and cannot be executed by this token.
/// @pre confirmationId references an existing pending token.
/// @}
void cancelAssistantOperation_Function(void);

/// @defgroup getAssistantHistory_Function "getAssistantHistory:Function"
/// @{
/// @brief Retrieve paginated assistant conversation history.
/// @post Returns a paginated payload with history items.
/// @pre page/pageSize are positive integers.
/// @}
void getAssistantHistory_Function(void);

/// @defgroup getAssistantConversations_Function "getAssistantConversations:Function"
/// @{
/// @brief Retrieve paginated conversation list for assistant sidebar/history switcher.
/// @post Returns paginated conversation summaries.
/// @pre page/pageSize are positive integers.
/// @}
void getAssistantConversations_Function(void);

/// @defgroup deleteAssistantConversation_Function "deleteAssistantConversation:Function"
/// @{
/// @brief Soft-delete or hard-delete a conversation.
/// @post Returns success status.
/// @pre conversationId string is provided.
/// @}
void deleteAssistantConversation_Function(void);

/// @defgroup DatasetReviewApi "DatasetReviewApi"
/// @{
/// @brief Shared frontend helpers for dataset review session-scoped API requests, optimistic-lock propagation, and session DTO normalization.
/// @}
void DatasetReviewApi(void);

/// @defgroup DatasetReviewApi_Module "DatasetReviewApi:Module"
/// @{
/// @brief Provide shared frontend helpers for dataset review session-scoped API requests, optimistic-lock propagation, and refreshed session DTO normalization.
/// @}
void DatasetReviewApi_Module(void);

/// @defgroup buildDatasetReviewRequestOptions_Function "buildDatasetReviewRequestOptions:Function"
/// @{
/// @brief Attach optimistic-lock session version header when the current version is known.
/// @post Returns requestApi-compatible options object.
/// @pre sessionVersion may be null when no loaded session version exists yet.
/// @}
void buildDatasetReviewRequestOptions_Function(void);

/// @defgroup requestDatasetReviewApi_Function "requestDatasetReviewApi:Function"
/// @{
/// @brief Proxy dataset review mutations through requestApi with optional optimistic-lock headers.
/// @post Executes requestApi with X-Session-Version only when a session version is known.
/// @pre endpoint and method are valid requestApi inputs.
/// @}
void requestDatasetReviewApi_Function(void);

/// @defgroup isDatasetReviewConflictError_Function "isDatasetReviewConflictError:Function"
/// @{
/// @brief Detect optimistic-lock conflicts from dataset review mutations.
/// @post Returns true when the mutation failed with 409 conflict semantics.
/// @pre error may be null or a normalized API error.
/// @}
void isDatasetReviewConflictError_Function(void);

/// @defgroup getDatasetReviewConflictMessage_Function "getDatasetReviewConflictMessage:Function"
/// @{
/// @brief Return explicit 409-style guidance for stale dataset review mutations.
/// @post Returns a user-facing conflict message string.
/// @pre error may be null or a normalized API error.
/// @}
void getDatasetReviewConflictMessage_Function(void);

/// @defgroup extractDatasetReviewVersion_Function "extractDatasetReviewVersion:Function"
/// @{
/// @brief Resolve the latest session version from refreshed DTO fragments.
/// @post Returns the newest known session version or null.
/// @pre payload may be a session summary, a detail payload, or a mutation fragment.
/// @}
void extractDatasetReviewVersion_Function(void);

/// @defgroup normalizeDatasetReviewDetail_Function "normalizeDatasetReviewDetail:Function"
/// @{
/// @brief Normalize refreshed session-detail DTOs into the legacy route-friendly workspace shape.
/// @post Returns a shape with flattened summary fields plus refreshed collections and version metadata.
/// @pre detail may already be legacy-flat or refreshed with nested session/session_version fields.
/// @}
void normalizeDatasetReviewDetail_Function(void);

/// @defgroup MaintenanceApi "MaintenanceApi"
/// @{
/// @brief API client for Maintenance Banner endpoints. Uses requestApi for all calls.
/// @}
void MaintenanceApi(void);

/// @defgroup frontend_src_lib_api_maintenance_js__startMaintenance "frontend/src/lib/api/maintenance.js::startMaintenance"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__startMaintenance(void);

/// @defgroup frontend_src_lib_api_maintenance_js__endMaintenance "frontend/src/lib/api/maintenance.js::endMaintenance"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__endMaintenance(void);

/// @defgroup frontend_src_lib_api_maintenance_js__endAllMaintenance "frontend/src/lib/api/maintenance.js::endAllMaintenance"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__endAllMaintenance(void);

/// @defgroup frontend_src_lib_api_maintenance_js__getSettings "frontend/src/lib/api/maintenance.js::getSettings"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__getSettings(void);

/// @defgroup frontend_src_lib_api_maintenance_js__updateSettings "frontend/src/lib/api/maintenance.js::updateSettings"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__updateSettings(void);

/// @defgroup frontend_src_lib_api_maintenance_js__listEvents "frontend/src/lib/api/maintenance.js::listEvents"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__listEvents(void);

/// @defgroup frontend_src_lib_api_maintenance_js__listDashboardBanners "frontend/src/lib/api/maintenance.js::listDashboardBanners"
/// @{
/// @}
void frontend_src_lib_api_maintenance_js__listDashboardBanners(void);

/// @defgroup ReportsApi "ReportsApi"
/// @{
/// @brief Wrapper-based reports API client for list/detail retrieval through the shared API wrapper.
/// @post Report list and detail helpers return backend payloads or normalized UI-safe errors.
/// @pre Shared API wrapper is configured for the current frontend auth/session context.
/// @}
void ReportsApi(void);

/// @defgroup ReportsApi_Module "ReportsApi:Module"
/// @{
/// @brief Wrapper-based reports API client for list/detail retrieval without direct native fetch usage.
/// @invariant Uses existing api wrapper methods and returns structured errors for UI-state mapping.
/// @post Report list and detail helpers return backend payloads or normalized UI-safe errors.
/// @pre Shared API wrapper is configured for the current frontend auth/session context.
/// @}
void ReportsApi_Module(void);

/// @defgroup buildReportQueryString_Function "buildReportQueryString:Function"
/// @{
/// @brief Build query string for reports list endpoint from filter options.
/// @post Returns URL query string without leading '?'.
/// @pre options is an object with optional report query fields.
/// @}
void buildReportQueryString_Function(void);

/// @defgroup normalizeApiError_Function "normalizeApiError:Function"
/// @{
/// @brief Convert unknown API exceptions into deterministic UI-consumable error objects.
/// @post Returns structured error object.
/// @pre error may be Error/string/object.
/// @}
void normalizeApiError_Function(void);

/// @defgroup getReports_Function "getReports:Function"
/// @{
/// @brief Fetch unified report list using existing request wrapper.
/// @post Returns parsed payload or structured error for UI-state mapping.
/// @pre valid auth context for protected endpoint.
/// @}
void getReports_Function(void);

/// @defgroup getReportDetail_Function "getReportDetail:Function"
/// @{
/// @brief Fetch one report detail by report_id.
/// @post Returns parsed detail payload or structured error object.
/// @pre reportId is non-empty string; valid auth context.
/// @}
void getReportDetail_Function(void);

/// @defgroup TranslateApi "TranslateApi"
/// @{
/// @brief Barrel module re-exporting all translate API functions from domain-split modules.
/// @}
void TranslateApi(void);

/// @defgroup TargetSchemaApiTest "TargetSchemaApiTest"
/// @{
/// @brief Unit tests for checkTargetTableSchema API client fetch wrapper.
/// @}
void TargetSchemaApiTest(void);

/// @defgroup test_success "test_success"
/// @{
/// @brief Happy path — API returns full validation result.
/// @}
void test_success(void);

/// @defgroup test_api_error "test_api_error"
/// @{
/// @brief API error returns fallback response with error message.
/// @}
void test_api_error(void);

/// @defgroup test_error_string_fallback "test_error_string_fallback"
/// @{
/// @brief String error is captured as message.
/// @}
void test_error_string_fallback(void);

/// @defgroup TranslateCorrectionsApi "TranslateCorrectionsApi"
/// @{
/// @brief API client for translation corrections — inline edits, dictionary submission, bulk find-and-replace, CSV download.
/// @}
void TranslateCorrectionsApi(void);

/// @defgroup TranslateDatasourcesApi "TranslateDatasourcesApi"
/// @{
/// @brief API client for translation datasources — column fetching, preview, row-level review actions.
/// @}
void TranslateDatasourcesApi(void);

/// @defgroup TranslateDictionariesApi "TranslateDictionariesApi"
/// @{
/// @brief API client for translation dictionary CRUD — list, create, update, delete, entries, import.
/// @}
void TranslateDictionariesApi(void);

/// @defgroup TranslateJobsApi "TranslateJobsApi"
/// @{
/// @brief API client for translation job CRUD — list, create, update, delete, duplicate.
/// @}
void TranslateJobsApi(void);

/// @defgroup TranslateRunsApi "TranslateRunsApi"
/// @{
/// @brief API client for translation run control — trigger, status, history, records, retry, cancel, metrics.
/// @}
void TranslateRunsApi(void);

/// @defgroup TranslateSchedulesApi "TranslateSchedulesApi"
/// @{
/// @brief API client for translation job scheduling — CRUD, enable/disable, next executions.
/// @}
void TranslateSchedulesApi(void);

/// @defgroup TranslateTargetSchemaApi "TranslateTargetSchemaApi"
/// @{
/// @brief API client for target table schema validation.
/// @}
void TranslateTargetSchemaApi(void);

/// @defgroup frontend_src_lib_api_translate_target_schema_js__checkTargetTableSchema "frontend/src/lib/api/translate/target-schema.js::checkTargetTableSchema"
/// @{
/// @}
void frontend_src_lib_api_translate_target_schema_js__checkTargetTableSchema(void);

/// @defgroup ValidationApi "ValidationApi"
/// @{
/// @brief API client functions for the Validation section — tasks and runs CRUD.
/// @}
void ValidationApi(void);

/// @defgroup buildParams_Function "buildParams:Function"
/// @{
/// @brief Build URLSearchParams from a params object, skipping null/undefined/empty values.
/// @param {Record<string, any>} params
/// @}
void buildParams_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__buildParams "frontend/src/lib/api/validation.js::buildParams"
/// @{
/// @}
void frontend_src_lib_api_validation_js__buildParams(void);

/// @defgroup frontend_src_lib_api_validation_js__fetchTasks "frontend/src/lib/api/validation.js::fetchTasks"
/// @{
/// @}
void frontend_src_lib_api_validation_js__fetchTasks(void);

/// @defgroup createTask_Function "createTask:Function"
/// @{
/// @param {Record<string, any>} data
/// @}
void createTask_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__createTask "frontend/src/lib/api/validation.js::createTask"
/// @{
/// @}
void frontend_src_lib_api_validation_js__createTask(void);

/// @defgroup fetchTask_Function "fetchTask:Function"
/// @{
/// @param {string} id
/// @}
void fetchTask_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__fetchTask "frontend/src/lib/api/validation.js::fetchTask"
/// @{
/// @}
void frontend_src_lib_api_validation_js__fetchTask(void);

/// @defgroup updateTask_Function "updateTask:Function"
/// @{
/// @param {string} id @param {Record<string, any>} data
/// @}
void updateTask_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__updateTask "frontend/src/lib/api/validation.js::updateTask"
/// @{
/// @}
void frontend_src_lib_api_validation_js__updateTask(void);

/// @defgroup deleteTask_Function "deleteTask:Function"
/// @{
/// @param {string} id @param {boolean} [deleteRuns]
/// @}
void deleteTask_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__deleteTask "frontend/src/lib/api/validation.js::deleteTask"
/// @{
/// @}
void frontend_src_lib_api_validation_js__deleteTask(void);

/// @defgroup triggerRun_Function "triggerRun:Function"
/// @{
/// @param {string} id
/// @}
void triggerRun_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__triggerRun "frontend/src/lib/api/validation.js::triggerRun"
/// @{
/// @}
void frontend_src_lib_api_validation_js__triggerRun(void);

/// @defgroup duplicateTask_Function "duplicateTask:Function"
/// @{
/// @param {string} id
/// @}
void duplicateTask_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__duplicateTask "frontend/src/lib/api/validation.js::duplicateTask"
/// @{
/// @}
void frontend_src_lib_api_validation_js__duplicateTask(void);

/// @defgroup fetchRuns_Function "fetchRuns:Function"
/// @{
/// @param {{ task_id?: string, dashboard_id?: string, environment_id?: string, status?: string, date_from?: string, date_to?: string, page?: number, page_size?: number }} [params]
/// @}
void fetchRuns_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__fetchRuns "frontend/src/lib/api/validation.js::fetchRuns"
/// @{
/// @}
void frontend_src_lib_api_validation_js__fetchRuns(void);

/// @defgroup fetchRunDetail_Function "fetchRunDetail:Function"
/// @{
/// @param {string} id
/// @}
void fetchRunDetail_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__fetchRunDetail "frontend/src/lib/api/validation.js::fetchRunDetail"
/// @{
/// @}
void frontend_src_lib_api_validation_js__fetchRunDetail(void);

/// @defgroup deleteRun_Function "deleteRun:Function"
/// @{
/// @param {string} id
/// @}
void deleteRun_Function(void);

/// @defgroup frontend_src_lib_api_validation_js__deleteRun "frontend/src/lib/api/validation.js::deleteRun"
/// @{
/// @}
void frontend_src_lib_api_validation_js__deleteRun(void);

/// @defgroup PermissionsTest "PermissionsTest"
/// @{
/// @brief Verifies frontend RBAC permission parsing and access checks.
/// @}
void PermissionsTest(void);

/// @defgroup PermissionsTest_Module "PermissionsTest:Module"
/// @{
/// @brief Verifies frontend RBAC permission parsing and access checks.
/// @}
void PermissionsTest_Module(void);

/// @defgroup PermissionsModule "PermissionsModule"
/// @{
/// @brief Shared frontend RBAC utilities for route guards, permission checks, and menu visibility based on user roles.
/// @}
void PermissionsModule(void);

/// @defgroup Permissions_Module "Permissions:Module"
/// @{
/// @brief Shared frontend RBAC utilities for route guards and menu visibility.
/// @invariant Admin role always bypasses explicit permission checks.
/// @}
void Permissions_Module(void);

/// @defgroup normalizePermissionRequirement_Function "normalizePermissionRequirement:Function"
/// @{
/// @brief Convert permission requirement string to canonical resource/action tuple.
/// @post Returns normalized object with action in uppercase.
/// @pre Permission can be "resource" or "resource:ACTION" where resource itself may contain ":".
/// @}
void normalizePermissionRequirement_Function(void);

/// @defgroup isAdminUser_Function "isAdminUser:Function"
/// @{
/// @brief Determine whether user has Admin role.
/// @post Returns true when at least one role name equals "Admin" (case-insensitive).
/// @pre user can be null or partially populated.
/// @}
void isAdminUser_Function(void);

/// @defgroup hasPermission_Function "hasPermission:Function"
/// @{
/// @brief Check if user has a required resource/action permission.
/// @post Returns true when requirement is empty, user is admin, or matching permission exists.
/// @pre user contains roles with permissions from /api/auth/me payload.
/// @}
void hasPermission_Function(void);

/// @defgroup AuthStore "AuthStore"
/// @{
/// @brief Manages the global authentication state including JWT token, user profile, and login/logout lifecycle.
/// @}
void AuthStore(void);

/// @defgroup authStore_Store "authStore:Store"
/// @{
/// @brief Manages the global authentication state on the frontend.
/// @}
void authStore_Store(void);

/// @defgroup AuthState_Interface "AuthState:Interface"
/// @{
/// @brief Defines the structure of the authentication state.
/// @}
void AuthState_Interface(void);

/// @defgroup frontend_src_lib_auth_store_ts__AuthState "frontend/src/lib/auth/store.ts::AuthState"
/// @{
/// @}
void frontend_src_lib_auth_store_ts__AuthState(void);

/// @defgroup createAuthStore_Function "createAuthStore:Function"
/// @{
/// @brief Creates and configures the auth store with helper methods.
/// @post Returns configured auth store with subscribe, setToken, setUser, logout, setLoading methods.
/// @pre No preconditions - initialization function.
/// @return {Writable<AuthState>}
/// @}
void createAuthStore_Function(void);

/// @defgroup frontend_src_lib_auth_store_ts__createAuthStore "frontend/src/lib/auth/store.ts::createAuthStore"
/// @{
/// @post Returns configured auth store with subscribe, setToken, setUser, logout, setLoading methods.
/// @pre No preconditions - initialization function.
/// @}
void frontend_src_lib_auth_store_ts__createAuthStore(void);

/// @defgroup setToken_Function "setToken:Function"
/// @{
/// @brief Updates the store with a new JWT token.
/// @param {string} token - The JWT access token.
/// @post Store updated with new token, isAuthenticated set to true.
/// @pre token must be a valid JWT string.
/// @}
void setToken_Function(void);

/// @defgroup setUser_Function "setUser:Function"
/// @{
/// @brief Sets the current user profile data.
/// @param {any} user - The user profile object.
/// @post Store updated with user, isAuthenticated true, loading false.
/// @pre User object must contain valid profile data.
/// @}
void setUser_Function(void);

/// @defgroup logout_Function "logout:Function"
/// @{
/// @brief Clears authentication state and storage.
/// @post Auth token removed from localStorage, store reset to initial state.
/// @pre User is currently authenticated.
/// @}
void logout_Function(void);

/// @defgroup setLoading_Function "setLoading:Function"
/// @{
/// @brief Updates the loading state.
/// @param {boolean} loading - Loading status.
/// @post Store loading state updated.
/// @pre None.
/// @}
void setLoading_Function(void);

/// @defgroup AssistantClarificationCard "AssistantClarificationCard"
/// @{
/// @brief Render the active dataset-review clarification queue inside AssistantChatPanel so users can answer, skip, defer, and resume questions without leaving the assistant workspace.
/// @post Clarification queue state is readable in-chat and answer mutations refresh the active question state without requiring a dedicated dialog.
/// @pre sessionId belongs to the current dataset review workspace and the assistant drawer is open for session-scoped work.
/// @}
void AssistantClarificationCard(void);

/// @defgroup readJson_Function "readJson:Function"
/// @{
/// @brief Read and parse JSON fixture file from disk.
/// @post Returns parsed object representation.
/// @pre filePath points to existing UTF-8 JSON file.
/// @}
void readJson_Function(void);

/// @defgroup AssistantClarificationIntegrationTest_Module "AssistantClarificationIntegrationTest:Module"
/// @{
/// @brief Verify AssistantChatPanel hosts the resumable dataset-review clarification flow inside the assistant drawer and refreshes workspace session state after answering.
/// @}
void AssistantClarificationIntegrationTest_Module(void);

/// @defgroup AssistantFirstMessageIntegrationTest_Module "AssistantFirstMessageIntegrationTest:Module"
/// @{
/// @brief Verify first optimistic user message stays visible while a new conversation request is pending.
/// @invariant Starting a new conversation must not trigger history reload that overwrites the first local user message.
/// @}
void AssistantFirstMessageIntegrationTest_Module(void);

/// @defgroup assistant_first_message_tests_Function "assistant_first_message_tests:Function"
/// @{
/// @brief Guard optimistic first-message UX against history reload race in new conversation flow.
/// @post First user message remains visible before pending send request resolves.
/// @pre Assistant panel renders with open state and mocked network dependencies.
/// @}
void assistant_first_message_tests_Function(void);

/// @defgroup CompiledSQLPreview "CompiledSQLPreview"
/// @{
/// @brief Present the exact Superset-generated compiled SQL preview, expose readiness or staleness clearly, and preserve readable recovery paths when preview generation fails.
/// @post Users can distinguish missing, pending, ready, stale, and error preview states and can trigger only Superset-backed preview generation.
/// @pre Session id is available and preview state comes from the current ownership-scoped session detail payload.
/// @}
void CompiledSQLPreview(void);

/// @defgroup ExecutionMappingReview "ExecutionMappingReview"
/// @{
/// @brief Review imported-filter to template-variable mappings, surface effective values and blockers, and require explicit approval for warning-sensitive execution inputs before preview or launch.
/// @post Users can review effective mapping values, approve warning-sensitive transformations, or manually override them while unresolved required-value blockers remain visible.
/// @pre Session id, execution mappings, imported filters, and template variables belong to the current ownership-scoped session payload.
/// @}
void ExecutionMappingReview(void);

/// @defgroup LaunchConfirmationPanel "LaunchConfirmationPanel"
/// @{
/// @brief Summarize final execution context, surface launch blockers explicitly, and confirm only a gate-complete SQL Lab launch request.
/// @post Users can see why launch is blocked or confirm a run-ready launch with explicit SQL Lab handoff evidence.
/// @pre Session detail, mappings, findings, preview state, and latest run context belong to the current ownership-scoped session payload.
/// @}
void LaunchConfirmationPanel(void);

/// @defgroup SemanticLayerReview "SemanticLayerReview"
/// @{
/// @brief Surface field-level semantic decisions with provenance, confidence, candidate acceptance, and manual override safeguards for US2 review flow.
/// @post Users can review the current semantic value, accept a candidate, apply manual override, and lock or unlock field state without violating backend provenance rules.
/// @pre Session id is available and semantic field entries come from the current ownership-scoped session detail payload.
/// @}
void SemanticLayerReview(void);

/// @defgroup SourceIntakePanel "SourceIntakePanel"
/// @{
/// @brief Collect initial dataset source input through Superset link paste or dataset selection entry paths.
/// @}
void SourceIntakePanel(void);

/// @defgroup ValidationFindingsPanel "ValidationFindingsPanel"
/// @{
/// @brief Present validation findings grouped by severity with explicit resolution and actionability signals.
/// @}
void ValidationFindingsPanel(void);

/// @defgroup SourceIntakePanelUxTests_Module "SourceIntakePanelUxTests:Module"
/// @{
/// @brief Verify source intake entry paths, validation feedback, and submit payload behavior for US1.
/// @}
void SourceIntakePanelUxTests_Module(void);

/// @defgroup DatasetReviewUs2WorkspaceUxTests_Module "DatasetReviewUs2WorkspaceUxTests:Module"
/// @{
/// @brief Verify US2 dataset review surfaces keep semantic review actionable, route clarification through AssistantChatPanel, and preserve explicit preview/mapping gates.
/// @}
void DatasetReviewUs2WorkspaceUxTests_Module(void);

/// @defgroup DatasetReviewUs3UxTests_Module "DatasetReviewUs3UxTests:Module"
/// @{
/// @brief Verify US3 mapping review, Superset preview, and launch confirmation UX contracts.
/// @}
void DatasetReviewUs3UxTests_Module(void);

/// @defgroup ValidationFindingsPanelUxTests_Module "ValidationFindingsPanelUxTests:Module"
/// @{
/// @brief Verify grouped findings visibility, empty state, and remediation jump behavior for US1.
/// @}
void ValidationFindingsPanelUxTests_Module(void);

/// @defgroup HealthMatrix "HealthMatrix"
/// @{
/// @brief Visual grid summary representing dashboard health status counts.
/// @}
void HealthMatrix(void);

/// @defgroup PolicyForm "PolicyForm"
/// @{
/// @brief Form for creating and editing validation policies.
/// @post Form submission forwards the current draft to onSave and cancel delegates dismissal to the parent callback without mutating external state directly.
/// @pre Parent provides callable onSave/onCancel handlers and an environments collection that may be empty but remains array-like.
/// @}
void PolicyForm(void);

/// @defgroup ScheduleAtAGlance "ScheduleAtAGlance"
/// @{
/// @brief Compact weekly schedule widget showing active validation tasks with day grid, time windows, and cross-referenced health status.
/// @}
void ScheduleAtAGlance(void);

/// @defgroup Sidebar "Sidebar"
/// @{
/// @brief Persistent left sidebar with grouped sections (Resources/Operations/System), expand/collapse, health indicators, RBAC filtering, profile footer.
/// @}
void Sidebar(void);

/// @defgroup disconnectWebSocket_Function "disconnectWebSocket:Function"
/// @{
/// @brief Disconnects the active WebSocket connection
/// @post ws is closed and set to null
/// @pre ws may or may not be initialized
/// @}
void disconnectWebSocket_Function(void);

/// @defgroup loadRecentTasks_Function "loadRecentTasks:Function"
/// @{
/// @brief Load recent tasks for list mode display
/// @post recentTasks array populated with task list
/// @pre User is on task drawer or api is ready.
/// @}
void loadRecentTasks_Function(void);

/// @defgroup selectTask_Function "selectTask:Function"
/// @{
/// @brief Select a task from list to view details
/// @post drawer state updated to show task details
/// @pre task is a valid task object
/// @}
void selectTask_Function(void);

/// @defgroup goBackToList_Function "goBackToList:Function"
/// @{
/// @brief Return to task list view from task details
/// @post Drawer switches to list view and reloads tasks
/// @pre Drawer is open and activeTaskId is set
/// @}
void goBackToList_Function(void);

/// @defgroup SidebarNavigationTest_Module "SidebarNavigationTest:Module"
/// @{
/// @brief Verifies RBAC-based sidebar sections and category visibility.
/// @}
void SidebarNavigationTest_Module(void);

/// @defgroup BreadcrumbsContractTest_Module "BreadcrumbsContractTest:Module"
/// @{
/// @brief Contract-focused unit tests for Breadcrumbs.svelte logic and UX annotations
/// @}
void BreadcrumbsContractTest_Module(void);

/// @defgroup SidebarStoreTest_Module "SidebarStoreTest:Module"
/// @{
/// @brief Unit tests for Sidebar.svelte component
/// @}
void SidebarStoreTest_Module(void);

/// @defgroup TaskDrawerStoreTest_Module "TaskDrawerStoreTest:Module"
/// @{
/// @brief Unit tests for TaskDrawer.svelte component
/// @}
void TaskDrawerStoreTest_Module(void);

/// @defgroup TopNavbarStoreTest_Module "TopNavbarStoreTest:Module"
/// @{
/// @brief Unit tests for TopNavbar.svelte component
/// @}
void TopNavbarStoreTest_Module(void);

/// @defgroup PageContracts "PageContracts"
/// @{
/// @brief Contract implemented by all Svelte route pages — defines page-level behavior and routing structure.
/// @}
void PageContracts(void);

/// @defgroup NavigationContracts "NavigationContracts"
/// @{
/// @brief Contract for navigation structure — sidebar sections, route categories, and menu item hierarchy.
/// @}
void NavigationContracts(void);

/// @defgroup SidebarNavigation_Module "SidebarNavigation:Module"
/// @{
/// @brief Build sidebar navigation sections and categories filtered by user permissions and feature flags.
/// @invariant Admin role can access all categories and subitems through permission utility.
/// @}
void SidebarNavigation_Module(void);

/// @defgroup isItemAllowed_Function "isItemAllowed:Function"
/// @{
/// @brief Check whether a single menu node can be shown for a given user.
/// @post Returns true when no permission is required or permission check passes.
/// @pre item can contain optional requiredPermission/requiredAction.
/// @}
void isItemAllowed_Function(void);

/// @defgroup isFeatureEnabled_Function "isFeatureEnabled:Function"
/// @{
/// @}
void isFeatureEnabled_Function(void);

/// @defgroup buildSidebarSections_Function "buildSidebarSections:Function"
/// @{
/// @brief Build translated sidebar sections with categories, filtered by RBAC permissions and feature flags.
/// @post Returns only sections/categories/subitems available for provided user and enabled features.
/// @pre i18nState provides nav labels; user can be null; features default to {} (all enabled).
/// @}
void buildSidebarSections_Function(void);

/// @defgroup ReportCardTest_Module "ReportCardTest:Module"
/// @{
/// @brief Test UX states and transitions for ReportCard component
/// @invariant Each test asserts at least one observable UX contract outcome.
/// @}
void ReportCardTest_Module(void);

/// @defgroup ReportDetailIntegrationTest_Module "ReportDetailIntegrationTest:Module"
/// @{
/// @brief Validate detail-panel behavior for failed reports and recovery guidance visibility.
/// @invariant Failed report detail exposes actionable next actions when available.
/// @}
void ReportDetailIntegrationTest_Module(void);

/// @defgroup ReportDetailUxTest_Module "ReportDetailUxTest:Module"
/// @{
/// @brief Test UX states and recovery for ReportDetailPanel component
/// @invariant Detail UX tests keep placeholder-safe rendering and recovery visibility verifiable.
/// @}
void ReportDetailUxTest_Module(void);

/// @defgroup _EXT_frontend_ReportTypeProfiles_Test_Module "[EXT:frontend:ReportTypeProfiles]Test:Module"
/// @{
/// @brief Validate report type profile mapping and unknown fallback behavior.
/// @invariant Unknown task_type always resolves to the fallback profile.
/// @}
void _EXT_frontend_ReportTypeProfiles_Test_Module(void);

/// @defgroup ReportsFilterPerformanceTest_Module "ReportsFilterPerformanceTest:Module"
/// @{
/// @brief Guard test for report filter responsiveness on moderate in-memory dataset.
/// @}
void ReportsFilterPerformanceTest_Module(void);

/// @defgroup ReportsListTest_Module "ReportsListTest:Module"
/// @{
/// @brief Test ReportsList component iteration and event forwarding.
/// @}
void ReportsListTest_Module(void);

/// @defgroup ReportsPageTest_Module "ReportsPageTest:Module"
/// @{
/// @brief Integration-style checks for unified mixed-type reports rendering expectations.
/// @invariant Mixed fixture includes all supported report types in one list.
/// @}
void ReportsPageTest_Module(void);

/// @defgroup ReportTypeProfiles_Module "ReportTypeProfiles:Module"
/// @{
/// @brief Deterministic mapping from report task_type to visual profile with one fallback.
/// @}
void ReportTypeProfiles_Module(void);

/// @defgroup getReportTypeProfile_Function "getReportTypeProfile:Function"
/// @{
/// @brief Resolve visual profile by task type with guaranteed fallback.
/// @post Returns one profile object.
/// @pre taskType may be known/unknown/empty.
/// @}
void getReportTypeProfile_Function(void);

/// @defgroup ApiKeysTab "ApiKeysTab"
/// @{
/// @brief API Key management tab — list, generate (one-time reveal), and revoke API keys.
/// @}
void ApiKeysTab(void);

/// @defgroup BulkCorrectionSidebar "BulkCorrectionSidebar"
/// @{
/// @brief Component component: lib/components/translate/BulkCorrectionSidebar.svelte
/// @}
void BulkCorrectionSidebar(void);

/// @defgroup BulkReplaceModal "BulkReplaceModal"
/// @{
/// @brief Modal dialog for bulk find-and-replace on translated values within a completed run.
/// @}
void BulkReplaceModal(void);

/// @defgroup CorrectionCell "CorrectionCell"
/// @{
/// @brief Inline-editable cell for translation run results with edit-save-cancel UX and submit-to-dictionary flow.
/// @}
void CorrectionCell(void);

/// @defgroup ScheduleConfig "ScheduleConfig"
/// @{
/// @brief Component component: lib/components/translate/ScheduleConfig.svelte
/// @}
void ScheduleConfig(void);

/// @defgroup TargetSchemaHint "TargetSchemaHint"
/// @{
/// @brief Подсказка о колонках целевой таблицы + кнопка "Проверить схему".
/// @}
void TargetSchemaHint(void);

/// @defgroup TermCorrectionPopup "TermCorrectionPopup"
/// @{
/// @brief Component component: lib/components/translate/TermCorrectionPopup.svelte
/// @}
void TermCorrectionPopup(void);

/// @defgroup TranslationMetricsDashboard "TranslationMetricsDashboard"
/// @{
/// @brief Component component: lib/components/translate/TranslationMetricsDashboard.svelte
/// @}
void TranslationMetricsDashboard(void);

/// @defgroup TranslationPreview "TranslationPreview"
/// @{
/// @brief Component component: lib/components/translate/TranslationPreview.svelte
/// @}
void TranslationPreview(void);

/// @defgroup TranslationRunGlobalIndicator "TranslationRunGlobalIndicator"
/// @{
/// @brief Persistent rich progress panel for active translation runs, rendered in root layout.
/// @}
void TranslationRunGlobalIndicator(void);

/// @defgroup TranslationRunProgress "TranslationRunProgress"
/// @{
/// @brief Component component: lib/components/translate/TranslationRunProgress.svelte
/// @}
void TranslationRunProgress(void);

/// @defgroup TranslationRunResult "TranslationRunResult"
/// @{
/// @brief Component component: lib/components/translate/TranslationRunResult.svelte
/// @}
void TranslationRunResult(void);

/// @defgroup TargetSchemaHintTest "TargetSchemaHintTest"
/// @{
/// @brief Contract-focused unit tests for TargetSchemaHint.svelte component.
/// @}
void TargetSchemaHintTest(void);

/// @defgroup test_component_exists "test_component_exists"
/// @{
/// @brief Verify component file exists.
/// @}
void test_component_exists(void);

/// @defgroup test_ux_state_contracts "test_ux_state_contracts"
/// @{
/// @brief Component contains required UX state tags.
/// @}
void test_ux_state_contracts(void);

/// @defgroup test_props_definition "test_props_definition"
/// @{
/// @brief Component accepts required props.
/// @}
void test_props_definition(void);

/// @defgroup test_button_check_disabled_logic "test_button_check_disabled_logic"
/// @{
/// @brief Button disabled logic: canCheck derived checks all required props.
/// @}
void test_button_check_disabled_logic(void);

/// @defgroup test_idle_state "test_idle_state"
/// @{
/// @brief Idle state shows hint text and check button.
/// @}
void test_idle_state(void);

/// @defgroup test_checking_state "test_checking_state"
/// @{
/// @brief Checking state shows spinner and disables button.
/// @}
void test_checking_state(void);

/// @defgroup test_complete_state "test_complete_state"
/// @{
/// @brief Complete state shows result with green/yellow/red indicators.
/// @}
void test_complete_state(void);

/// @defgroup test_error_state "test_error_state"
/// @{
/// @brief Error state shows connection error message.
/// @}
void test_error_state(void);

/// @defgroup test_i18n_usage "test_i18n_usage"
/// @{
/// @brief Component uses i18n _() for all user-facing strings with fallbacks.
/// @}
void test_i18n_usage(void);

/// @defgroup test_abort_controller "test_abort_controller"
/// @{
/// @brief Component uses AbortController for request cancellation.
/// @}
void test_abort_controller(void);

/// @defgroup BulkReplaceModalTests "BulkReplaceModalTests"
/// @{
/// @brief Contract-focused unit tests for BulkReplaceModal.svelte component.
/// @}
void BulkReplaceModalTests(void);

/// @defgroup CorrectionCellTests "CorrectionCellTests"
/// @{
/// @brief Contract-focused unit tests for CorrectionCell.svelte component.
/// @}
void CorrectionCellTests(void);

/// @defgroup test_component_file_exists_Function "test_component_file_exists:Function"
/// @{
/// @brief Verify component file exists and has required contracts
/// @}
void test_component_file_exists_Function(void);

/// @defgroup TranslateApiTests_Class "TranslateApiTests:Class"
/// @{
/// @brief Unit tests for translate API preview functions.
/// @}
void TranslateApiTests_Class(void);

/// @defgroup test_fetchPreview_Function "test_fetchPreview:Function"
/// @{
/// @brief Verify fetchPreview calls postApi with correct endpoint and payload.
/// @}
void test_fetchPreview_Function(void);

/// @defgroup test_approveRow_Function "test_approveRow:Function"
/// @{
/// @brief Verify approveRow calls requestApi with correct action.
/// @}
void test_approveRow_Function(void);

/// @defgroup test_editRow_Function "test_editRow:Function"
/// @{
/// @brief Verify editRow calls requestApi with edit action and translation.
/// @}
void test_editRow_Function(void);

/// @defgroup test_rejectRow_Function "test_rejectRow:Function"
/// @{
/// @brief Verify rejectRow calls requestApi with reject action.
/// @}
void test_rejectRow_Function(void);

/// @defgroup test_acceptPreview_Function "test_acceptPreview:Function"
/// @{
/// @brief Verify acceptPreview calls postApi with correct endpoint.
/// @}
void test_acceptPreview_Function(void);

/// @defgroup test_fetchPreviewRecords_Function "test_fetchPreviewRecords:Function"
/// @{
/// @brief Verify fetchPreviewRecords calls fetchApi with correct endpoint.
/// @}
void test_fetchPreviewRecords_Function(void);

/// @defgroup test_normalizeTranslateError_Function "test_normalizeTranslateError:Function"
/// @{
/// @brief Verify API errors are normalized consistently.
/// @}
void test_normalizeTranslateError_Function(void);

/// @defgroup I18nModule "I18nModule"
/// @{
/// @brief Centralized internationalization management using Svelte stores with Russian and English locale support persisted in LocalStorage.
/// @}
void I18nModule(void);

/// @defgroup i18n_Module "i18n:Module"
/// @{
/// @brief Centralized internationalization management using Svelte stores.
/// @invariant Persistence is handled via LocalStorage.
/// @}
void i18n_Module(void);

/// @defgroup locale_Store "locale:Store"
/// @{
/// @brief Holds the current active locale string.
/// @}
void locale_Store(void);

/// @defgroup t_Store "t:Store"
/// @{
/// @brief Derived store providing the translation dictionary.
/// @}
void t_Store(void);

/// @defgroup __Function "_:Function"
/// @{
/// @brief Get translation by key path.
/// @param key - Translation key path (e.g., 'nav.dashboard')
/// @return Translation string or key if not found
/// @}
void __Function(void);

/// @defgroup frontend_src_lib_i18n_index_ts___ "frontend/src/lib/i18n/index.ts::_"
/// @{
/// @}
void frontend_src_lib_i18n_index_ts___(void);

/// @defgroup StoresModule "StoresModule"
/// @{
/// @brief Global Svelte writable stores for plugins, tasks, and UI page state management.
/// @}
void StoresModule(void);

/// @defgroup stores_module_Module "stores_module:Module"
/// @{
/// @brief Global state management using Svelte stores.
/// @}
void stores_module_Module(void);

/// @defgroup plugins_Data "plugins:Data"
/// @{
/// @brief Store for the list of available plugins.
/// @}
void plugins_Data(void);

/// @defgroup tasks_Data "tasks:Data"
/// @{
/// @brief Store for the list of tasks.
/// @}
void tasks_Data(void);

/// @defgroup selectedPlugin_Data "selectedPlugin:Data"
/// @{
/// @brief Store for the currently selected plugin.
/// @}
void selectedPlugin_Data(void);

/// @defgroup selectedTask_Data "selectedTask:Data"
/// @{
/// @brief Store for the currently selected task.
/// @}
void selectedTask_Data(void);

/// @defgroup currentPage_Data "currentPage:Data"
/// @{
/// @brief Store for the current page.
/// @}
void currentPage_Data(void);

/// @defgroup taskLogs_Data "taskLogs:Data"
/// @{
/// @brief Store for the logs of the currently selected task.
/// @}
void taskLogs_Data(void);

/// @defgroup fetchPlugins_Function "fetchPlugins:Function"
/// @{
/// @brief Fetches plugins from the API and updates the plugins store.
/// @post plugins store is updated with data from the API.
/// @pre None.
/// @}
void fetchPlugins_Function(void);

/// @defgroup fetchTasks_Function "fetchTasks:Function"
/// @{
/// @brief Fetches tasks from the API and updates the tasks store.
/// @post tasks store is updated with data from the API.
/// @pre None.
/// @}
void fetchTasks_Function(void);

/// @defgroup _EXT_frontend_AssistantChatTest_s "[EXT:frontend:AssistantChatTest]s"
/// @{
/// @brief Unit tests for assistant chat store validating open/close/toggle, conversation binding, session context, and seed message state transitions.
/// @}
void _EXT_frontend_AssistantChatTest_s(void);

/// @defgroup _EXT_frontend_AssistantChatTest__Module "[EXT:frontend:AssistantChatTest]:Module"
/// @{
/// @brief Validate assistant chat store visibility and conversation binding transitions.
/// @invariant Each test starts from default closed state.
/// @}
void _EXT_frontend_AssistantChatTest__Module(void);

/// @defgroup assistantChatStore_tests_Function "assistantChatStore_tests:Function"
/// @{
/// @brief Group store unit scenarios for assistant panel behavior.
/// @post Open/close/toggle/conversation transitions are validated.
/// @pre Store can be reset to baseline state in beforeEach hook.
/// @}
void assistantChatStore_tests_Function(void);

/// @defgroup MockEnvPublic "MockEnvPublic"
/// @{
/// @}
void MockEnvPublic(void);

/// @defgroup mock_env_public_Module "mock_env_public:Module"
/// @{
/// @brief Mock for $env/static/public SvelteKit module in vitest
/// @}
void mock_env_public_Module(void);

/// @defgroup EnvironmentMock "EnvironmentMock"
/// @{
/// @brief Mock for $app/environment in vitest, supplying browser, dev, and building flags.
/// @}
void EnvironmentMock(void);

/// @defgroup EnvironmentMock_Module "EnvironmentMock:Module"
/// @{
/// @brief Mock for $app/environment in tests
/// @}
void EnvironmentMock_Module(void);

/// @defgroup NavigationMock "NavigationMock"
/// @{
/// @brief Mock for $app/navigation in vitest, supplying goto, push, replace, prefetch, and prefetchRoutes stubs.
/// @}
void NavigationMock(void);

/// @defgroup NavigationMock_Module "NavigationMock:Module"
/// @{
/// @brief Mock for $app/navigation in tests
/// @invariant Includes SvelteKit v1-only APIs (push, prefetchRoutes) as compatibility surface for legacy test consumers; keep until all imports migrate to SvelteKit v2-compatible mocks.
/// @}
void NavigationMock_Module(void);

/// @defgroup StateMock "StateMock"
/// @{
/// @brief Mock for $app/state page data in vitest route/component tests, supplying default params, route, URL, status, and data.
/// @}
void StateMock(void);

/// @defgroup state_mock_Module "state_mock:Module"
/// @{
/// @brief Mock for AppState in vitest route/component tests.
/// @}
void state_mock_Module(void);

/// @defgroup StoresMock "StoresMock"
/// @{
/// @}
void StoresMock(void);

/// @defgroup StoresMock_Module "StoresMock:Module"
/// @{
/// @brief Mock for $app/stores in tests
/// @invariant Mocks $app/stores which is a SvelteKit v1 module; SvelteKit v2 uses $app/state. Verify no active test files import this mock before removal.
/// @}
void StoresMock_Module(void);

/// @defgroup SetupTestsModule "SetupTestsModule"
/// @{
/// @brief Global vitest test setup with mocks for SvelteKit modules ($app/environment, $app/stores, $app/navigation, localStorage).
/// @}
void SetupTestsModule(void);

/// @defgroup setupTests_Module "setupTests:Module"
/// @{
/// @brief Global test setup with mocks for SvelteKit modules
/// @}
void setupTests_Module(void);

/// @defgroup SidebarTest "SidebarTest"
/// @{
/// @brief Unit tests for sidebar store validating expansion toggles, active item selection, and mobile open/close transitions.
/// @}
void SidebarTest(void);

/// @defgroup SidebarTest_Module "SidebarTest:Module"
/// @{
/// @brief Unit tests for sidebar store
/// @invariant Sidebar store transitions must be deterministic across desktop/mobile toggles.
/// @}
void SidebarTest_Module(void);

/// @defgroup test_sidebar_initial_state_Function "test_sidebar_initial_state:Function"
/// @{
/// @brief Verify initial sidebar store values when no persisted state is available.
/// @post Default state is { isExpanded: true, activeCategory: 'dashboards', activeItem: '/dashboards', isMobileOpen: false }
/// @pre No localStorage state
/// @test Store initializes with default values
/// @}
void test_sidebar_initial_state_Function(void);

/// @defgroup test_toggleSidebar_Function "test_toggleSidebar:Function"
/// @{
/// @brief Verify desktop sidebar expansion toggles deterministically.
/// @post isExpanded is toggled from previous value
/// @pre Store is initialized
/// @test toggleSidebar toggles isExpanded state
/// @}
void test_toggleSidebar_Function(void);

/// @defgroup test_setActiveItem_Function "test_setActiveItem:Function"
/// @{
/// @brief Verify active-category updates remain deterministic after item selection.
/// @post activeCategory and activeItem are updated
/// @pre Store is initialized
/// @test setActiveItem updates activeCategory and activeItem
/// @}
void test_setActiveItem_Function(void);

/// @defgroup test_mobile_functions_Function "test_mobile_functions:Function"
/// @{
/// @brief Verify mobile sidebar helpers update open-state transitions predictably.
/// @post isMobileOpen is correctly updated
/// @pre Store is initialized
/// @test Mobile functions correctly update isMobileOpen
/// @}
void test_mobile_functions_Function(void);

/// @defgroup TaskDrawerTests "TaskDrawerTests"
/// @{
/// @brief Unit tests for task drawer store validating open/close, preference-aware opening, resource task mapping, and status-driven cleanup.
/// @}
void TaskDrawerTests(void);

/// @defgroup ActivityTestModule "ActivityTestModule"
/// @{
/// @brief Unit tests validating activity store derived count and recent task tracking behavior.
/// @}
void ActivityTestModule(void);

/// @defgroup ActivityTest_Module "ActivityTest:Module"
/// @{
/// @brief Unit tests for activity store
/// @}
void ActivityTest_Module(void);

/// @defgroup DatasetReviewSessionTests "DatasetReviewSessionTests"
/// @{
/// @brief Unit tests for dataset review session store: session set/reset, loading, error, dirty flag, and patch operations.
/// @}
void DatasetReviewSessionTests(void);

/// @defgroup DatasetReviewSessionStoreTests_Module "DatasetReviewSessionStoreTests:Module"
/// @{
/// @brief Unit tests for dataset review session store.
/// @}
void DatasetReviewSessionStoreTests_Module(void);

/// @defgroup SidebarTestModule "SidebarTestModule"
/// @{
/// @brief Unit tests for sidebar store validating initial state, toggle, navigation, mobile overlay, and localStorage persistence.
/// @}
void SidebarTestModule(void);

/// @defgroup SidebarIntegrationTest_Module "SidebarIntegrationTest:Module"
/// @{
/// @brief Unit tests for sidebar store
/// @}
void SidebarIntegrationTest_Module(void);

/// @defgroup TaskDrawerTestModule "TaskDrawerTestModule"
/// @{
/// @brief Unit tests for task drawer store validating open/close transitions, preference-aware opening, and resource-task mapping lifecycle.
/// @}
void TaskDrawerTestModule(void);

/// @defgroup TaskDrawerTest_Module "TaskDrawerTest:Module"
/// @{
/// @brief Unit tests for task drawer store
/// @invariant Store state transitions remain deterministic for open/close and task-status mapping.
/// @}
void TaskDrawerTest_Module(void);

/// @defgroup ActivityStore "ActivityStore"
/// @{
/// @brief Derived store that counts active running tasks for navbar indicator badge.
/// @}
void ActivityStore(void);

/// @defgroup activity_Store "activity:Store"
/// @{
/// @brief Track active task count for navbar indicator
/// @}
void activity_Store(void);

/// @defgroup AssistantChatStore "AssistantChatStore"
/// @{
/// @brief Control assistant chat panel visibility, conversation binding, session context, and seeded prompts.
/// @}
void AssistantChatStore(void);

/// @defgroup assistantChat_Store "assistantChat:Store"
/// @{
/// @brief Control assistant chat panel visibility and active conversation binding.
/// @}
void assistantChat_Store(void);

/// @defgroup toggleAssistantChat_Function "toggleAssistantChat:Function"
/// @{
/// @brief Toggle assistant panel visibility.
/// @post isOpen value inverted.
/// @pre Store is initialized.
/// @}
void toggleAssistantChat_Function(void);

/// @defgroup openAssistantChat_Function "openAssistantChat:Function"
/// @{
/// @brief Open assistant panel.
/// @post isOpen = true.
/// @pre Store is initialized.
/// @}
void openAssistantChat_Function(void);

/// @defgroup openAssistantChatWithContext_Function "openAssistantChatWithContext:Function"
/// @{
/// @brief Open assistant panel with dataset review session context and optional seeded prompt/focus target.
/// @post Assistant drawer opens with session binding and visible focus metadata.
/// @pre Context payload may be partial.
/// @}
void openAssistantChatWithContext_Function(void);

/// @defgroup closeAssistantChat_Function "closeAssistantChat:Function"
/// @{
/// @brief Close assistant panel.
/// @post isOpen = false.
/// @pre Store is initialized.
/// @}
void closeAssistantChat_Function(void);

/// @defgroup setAssistantConversationId_Function "setAssistantConversationId:Function"
/// @{
/// @brief Bind current conversation id in UI state.
/// @post store.conversationId updated.
/// @pre conversationId is string-like identifier.
/// @}
void setAssistantConversationId_Function(void);

/// @defgroup setAssistantDatasetReviewSessionId_Function "setAssistantDatasetReviewSessionId:Function"
/// @{
/// @brief Bind active dataset review session to assistant state.
/// @post store.datasetReviewSessionId updated.
/// @pre session identifier may be null when workspace context is cleared.
/// @}
void setAssistantDatasetReviewSessionId_Function(void);

/// @defgroup setAssistantSeedMessage_Function "setAssistantSeedMessage:Function"
/// @{
/// @brief Stage a seeded assistant prompt for contextual send UX.
/// @post store.seedMessage updated.
/// @pre seedMessage can be empty to clear staged draft.
/// @}
void setAssistantSeedMessage_Function(void);

/// @defgroup setAssistantFocusTarget_Function "setAssistantFocusTarget:Function"
/// @{
/// @brief Track the workspace entity currently referenced by assistant context.
/// @post store.focusTarget updated.
/// @pre focusTarget may be null to clear prior focus.
/// @}
void setAssistantFocusTarget_Function(void);

/// @defgroup DatasetReviewSessionStore "DatasetReviewSessionStore"
/// @{
/// @brief Manage active dataset review session state including loading, local edits, error capture, and reset semantics.
/// @post Store transitions keep session, loading, error, and dirty flags internally consistent after each helper call.
/// @pre Consumers provide session-shaped payloads and initialize the store before reading derived session fields.
/// @}
void DatasetReviewSessionStore(void);

/// @defgroup datasetReviewSession_Store "datasetReviewSession:Store"
/// @{
/// @brief Manage active dataset review session state, including loading, local edits, error capture, and reset semantics for the active review workspace.
/// @post Store transitions keep session, loading, error, and dirty flags internally consistent after each helper call.
/// @pre Consumers provide session-shaped payloads when setting or patching state and initialize the store before reading derived session fields.
/// @}
void datasetReviewSession_Store(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__setSession "frontend/src/lib/stores/datasetReviewSession.js::setSession"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__setSession(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__setLoading "frontend/src/lib/stores/datasetReviewSession.js::setLoading"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__setLoading(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__setError "frontend/src/lib/stores/datasetReviewSession.js::setError"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__setError(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__setDirty "frontend/src/lib/stores/datasetReviewSession.js::setDirty"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__setDirty(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__resetSession "frontend/src/lib/stores/datasetReviewSession.js::resetSession"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__resetSession(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__patchSession "frontend/src/lib/stores/datasetReviewSession.js::patchSession"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__patchSession(void);

/// @defgroup frontend_src_lib_stores_datasetReviewSession_js__getSessionUiPhase "frontend/src/lib/stores/datasetReviewSession.js::getSessionUiPhase"
/// @{
/// @}
void frontend_src_lib_stores_datasetReviewSession_js__getSessionUiPhase(void);

/// @defgroup EnvironmentContextStore "EnvironmentContextStore"
/// @{
/// @brief Global selected environment context for navigation, safety cues, and environment-based filtering.
/// @}
void EnvironmentContextStore(void);

/// @defgroup environmentContext_Store "environmentContext:Store"
/// @{
/// @brief Global selected environment context for navigation and safety cues.
/// @}
void environmentContext_Store(void);

/// @defgroup HealthStore "HealthStore"
/// @{
/// @brief Manage dashboard health summary state and failing counts for UI badges.
/// @}
void HealthStore(void);

/// @defgroup health_store_Store "health_store:Store"
/// @{
/// @brief Manage dashboard health summary state and failing counts for UI badges.
/// @}
void health_store_Store(void);

/// @defgroup frontend_src_lib_stores_health_js__createHealthStore "frontend/src/lib/stores/health.js::createHealthStore"
/// @{
/// @}
void frontend_src_lib_stores_health_js__createHealthStore(void);

/// @defgroup frontend_src_lib_stores_health_js__refresh "frontend/src/lib/stores/health.js::refresh"
/// @{
/// @}
void frontend_src_lib_stores_health_js__refresh(void);

/// @defgroup MaintenanceStore "MaintenanceStore"
/// @{
/// @brief Svelte 5 (Runes) store for maintenance banner state. Auto-polls events every 30s via interval.
/// @return {object} Maintenance store with runes state and methods.
/// @}
void MaintenanceStore(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__createMaintenanceStore "frontend/src/lib/stores/maintenance.svelte.js::createMaintenanceStore"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__createMaintenanceStore(void);

/// @defgroup MaintenanceStore_state "MaintenanceStore.state"
/// @{
/// @}
void MaintenanceStore_state(void);

/// @defgroup MaintenanceStore_methods "MaintenanceStore.methods"
/// @{
/// @}
void MaintenanceStore_methods(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__loadEvents "frontend/src/lib/stores/maintenance.svelte.js::loadEvents"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__loadEvents(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__loadDashboardBanners "frontend/src/lib/stores/maintenance.svelte.js::loadDashboardBanners"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__loadDashboardBanners(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__loadSettings "frontend/src/lib/stores/maintenance.svelte.js::loadSettings"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__loadSettings(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__endEvent "frontend/src/lib/stores/maintenance.svelte.js::endEvent"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__endEvent(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__endAllEvents "frontend/src/lib/stores/maintenance.svelte.js::endAllEvents"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__endAllEvents(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__updateSettings "frontend/src/lib/stores/maintenance.svelte.js::updateSettings"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__updateSettings(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__init "frontend/src/lib/stores/maintenance.svelte.js::init"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__init(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__startPolling "frontend/src/lib/stores/maintenance.svelte.js::startPolling"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__startPolling(void);

/// @defgroup frontend_src_lib_stores_maintenance_svelte_js__stopPolling "frontend/src/lib/stores/maintenance.svelte.js::stopPolling"
/// @{
/// @}
void frontend_src_lib_stores_maintenance_svelte_js__stopPolling(void);

/// @defgroup SidebarStore "SidebarStore"
/// @{
/// @brief Manage sidebar visibility, expansion state, active navigation item, and mobile overlay.
/// @}
void SidebarStore(void);

/// @defgroup sidebar_Store "sidebar:Store"
/// @{
/// @brief Manage sidebar visibility and navigation state
/// @invariant isExpanded state is always synced with localStorage
/// @}
void sidebar_Store(void);

/// @defgroup frontend_src_lib_stores_sidebar_js__toggleSidebar "frontend/src/lib/stores/sidebar.js::toggleSidebar"
/// @{
/// @}
void frontend_src_lib_stores_sidebar_js__toggleSidebar(void);

/// @defgroup frontend_src_lib_stores_sidebar_js__setActiveItem "frontend/src/lib/stores/sidebar.js::setActiveItem"
/// @{
/// @}
void frontend_src_lib_stores_sidebar_js__setActiveItem(void);

/// @defgroup frontend_src_lib_stores_sidebar_js__setMobileOpen "frontend/src/lib/stores/sidebar.js::setMobileOpen"
/// @{
/// @}
void frontend_src_lib_stores_sidebar_js__setMobileOpen(void);

/// @defgroup frontend_src_lib_stores_sidebar_js__closeMobile "frontend/src/lib/stores/sidebar.js::closeMobile"
/// @{
/// @}
void frontend_src_lib_stores_sidebar_js__closeMobile(void);

/// @defgroup frontend_src_lib_stores_sidebar_js__toggleMobileSidebar "frontend/src/lib/stores/sidebar.js::toggleMobileSidebar"
/// @{
/// @}
void frontend_src_lib_stores_sidebar_js__toggleMobileSidebar(void);

/// @defgroup TaskDrawerStore "TaskDrawerStore"
/// @{
/// @brief Manage Task Drawer visibility, active task binding, and resource-to-task mapping.
/// @}
void TaskDrawerStore(void);

/// @defgroup taskDrawer_Store "taskDrawer:Store"
/// @{
/// @brief Manage Task Drawer visibility and resource-to-task mapping
/// @}
void taskDrawer_Store(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__openDrawerForTask "frontend/src/lib/stores/taskDrawer.js::openDrawerForTask"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__openDrawerForTask(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__setTaskDrawerAutoOpenPreference "frontend/src/lib/stores/taskDrawer.js::setTaskDrawerAutoOpenPreference"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__setTaskDrawerAutoOpenPreference(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__getTaskDrawerAutoOpenPreference "frontend/src/lib/stores/taskDrawer.js::getTaskDrawerAutoOpenPreference"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__getTaskDrawerAutoOpenPreference(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__openDrawerForTaskIfPreferred "frontend/src/lib/stores/taskDrawer.js::openDrawerForTaskIfPreferred"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__openDrawerForTaskIfPreferred(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__openDrawer "frontend/src/lib/stores/taskDrawer.js::openDrawer"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__openDrawer(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__closeDrawer "frontend/src/lib/stores/taskDrawer.js::closeDrawer"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__closeDrawer(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__updateResourceTask "frontend/src/lib/stores/taskDrawer.js::updateResourceTask"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__updateResourceTask(void);

/// @defgroup frontend_src_lib_stores_taskDrawer_js__getTaskForResource "frontend/src/lib/stores/taskDrawer.js::getTaskForResource"
/// @{
/// @}
void frontend_src_lib_stores_taskDrawer_js__getTaskForResource(void);

/// @defgroup TranslationRunStore "TranslationRunStore"
/// @{
/// @brief Global store for active translation run progress — survives page navigation.
/// @}
void TranslationRunStore(void);

/// @defgroup frontend_src_lib_stores_translationRun_js__clearOnCompleteCallback "frontend/src/lib/stores/translationRun.js::clearOnCompleteCallback"
/// @{
/// @}
void frontend_src_lib_stores_translationRun_js__clearOnCompleteCallback(void);

/// @defgroup frontend_src_lib_stores_translationRun_js__startTranslationRun "frontend/src/lib/stores/translationRun.js::startTranslationRun"
/// @{
/// @}
void frontend_src_lib_stores_translationRun_js__startTranslationRun(void);

/// @defgroup frontend_src_lib_stores_translationRun_js__stopTranslationRun "frontend/src/lib/stores/translationRun.js::stopTranslationRun"
/// @{
/// @}
void frontend_src_lib_stores_translationRun_js__stopTranslationRun(void);

/// @defgroup frontend_src_lib_stores_translationRun_js__resetTranslationRun "frontend/src/lib/stores/translationRun.js::resetTranslationRun"
/// @{
/// @}
void frontend_src_lib_stores_translationRun_js__resetTranslationRun(void);

/// @defgroup frontend_src_lib_stores_translationRun_js__updateTranslationRunState "frontend/src/lib/stores/translationRun.js::updateTranslationRunState"
/// @{
/// @}
void frontend_src_lib_stores_translationRun_js__updateTranslationRunState(void);

/// @defgroup frontend_src_lib_stores_translationRun_js__pollStatus "frontend/src/lib/stores/translationRun.js::pollStatus"
/// @{
/// @}
void frontend_src_lib_stores_translationRun_js__pollStatus(void);

/// @defgroup ToastsModule "ToastsModule"
/// @{
/// @brief Manages toast notifications using a Svelte writable store with deduplication and auto-removal.
/// @}
void ToastsModule(void);

/// @defgroup toasts_module_Module "toasts_module:Module"
/// @{
/// @brief Manages toast notifications using a Svelte writable store.
/// @}
void toasts_module_Module(void);

/// @defgroup toasts_Data "toasts:Data"
/// @{
/// @brief Writable store containing the list of active toasts.
/// @}
void toasts_Data(void);

/// @defgroup addToast_Function "addToast:Function"
/// @{
/// @brief Adds a new toast message.
/// @param duration (number) - Duration in ms before the toast is removed.
/// @post New toast is added to the store and scheduled for removal.
/// @pre message string is provided.
/// @}
void addToast_Function(void);

/// @defgroup removeToast_Function "removeToast:Function"
/// @{
/// @brief Removes a toast message by ID.
/// @param id (string) - The ID of the toast to remove.
/// @post Toast is removed from the store.
/// @pre id is provided.
/// @}
void removeToast_Function(void);

/// @defgroup Button "Button"
/// @{
/// @brief Standardized button component with variants and loading states.
/// @invariant Supports accessible labels and keyboard navigation.
/// @}
void Button(void);

/// @defgroup Card "Card"
/// @{
/// @brief Standardized container with padding and elevation.
/// @}
void Card(void);

/// @defgroup Icon "Icon"
/// @{
/// @brief Render the shared inline SVG icon set with consistent sizing and stroke props.
/// @invariant Icon output remains aria-hidden because labels belong to the interactive parent.
/// @}
void Icon(void);

/// @defgroup Input "Input"
/// @{
/// @brief Standardized text input component with label and error handling.
/// @invariant Consistent spacing and focus states.
/// @}
void Input(void);

/// @defgroup LanguageSwitcher "LanguageSwitcher"
/// @{
/// @brief Dropdown component to switch between supported languages.
/// @}
void LanguageSwitcher(void);

/// @defgroup PageHeader "PageHeader"
/// @{
/// @brief Standardized page header with title and action area.
/// @}
void PageHeader(void);

/// @defgroup Select "Select"
/// @{
/// @brief Standardized dropdown selection component.
/// @}
void Select(void);

/// @defgroup ui_Module "ui:Module"
/// @{
/// @brief Central export point for standardized UI components.
/// @invariant All components exported here must follow Semantic Protocol.
/// @}
void ui_Module(void);

/// @defgroup UtilsModule "UtilsModule"
/// @{
/// @}
void UtilsModule(void);

/// @defgroup Utils_Module "Utils:Module"
/// @{
/// @brief General utility functions (class merging)
/// @}
void Utils_Module(void);

/// @defgroup frontend_src_lib_utils_js__cn "frontend/src/lib/utils.js::cn"
/// @{
/// @}
void frontend_src_lib_utils_js__cn(void);

/// @defgroup DebounceModule "DebounceModule"
/// @{
/// @}
void DebounceModule(void);

/// @defgroup Debounce_Module "Debounce:Module"
/// @{
/// @brief Debounce utility for limiting function execution rate
/// @}
void Debounce_Module(void);

/// @defgroup frontend_src_lib_utils_debounce_js__debounce "frontend/src/lib/utils/debounce.js::debounce"
/// @{
/// @}
void frontend_src_lib_utils_debounce_js__debounce(void);

/// @defgroup onMount_Function "onMount:Function"
/// @{
/// @brief Fetch plugins when the component mounts.
/// @post plugins store is populated with available tools.
/// @pre Component is mounting.
/// @}
void onMount_Function(void);

/// @defgroup selectPlugin_Function "selectPlugin:Function"
/// @{
/// @brief Selects a plugin to display its form.
/// @param {Object} plugin - The plugin object to select.
/// @post selectedPlugin store is updated.
/// @pre plugin object is provided.
/// @}
void selectPlugin_Function(void);

/// @defgroup loadSettings_Function "loadSettings:Function"
/// @{
/// @brief Loads settings from the backend.
/// @post settings object is populated with backend data.
/// @pre Component mounted or refresh requested.
/// @}
void loadSettings_Function(void);

/// @defgroup handleSaveGlobal_Function "handleSaveGlobal:Function"
/// @{
/// @brief Saves global settings to the backend.
/// @post Backend global settings are updated.
/// @pre settings.settings contains valid configuration.
/// @}
void handleSaveGlobal_Function(void);

/// @defgroup handleAddOrUpdateEnv_Function "handleAddOrUpdateEnv:Function"
/// @{
/// @brief Adds or updates an environment.
/// @post Environment list is updated on backend and reloaded locally.
/// @pre newEnv contains valid environment details.
/// @}
void handleAddOrUpdateEnv_Function(void);

/// @defgroup handleDeleteEnv_Function "handleDeleteEnv:Function"
/// @{
/// @brief Deletes an environment.
/// @param {string} id - The ID of the environment to delete.
/// @post Environment is removed from backend and list is reloaded.
/// @pre id of environment to delete is provided.
/// @}
void handleDeleteEnv_Function(void);

/// @defgroup handleTestEnv_Function "handleTestEnv:Function"
/// @{
/// @brief Tests the connection to an environment.
/// @param {string} id - The ID of the environment to test.
/// @post Connection test result is displayed via toast.
/// @pre Environment ID is valid.
/// @}
void handleTestEnv_Function(void);

/// @defgroup editEnv_Function "editEnv:Function"
/// @{
/// @brief Sets the form to edit an existing environment.
/// @param {Object} env - The environment object to edit.
/// @post newEnv is populated with env data and editingEnvId is set.
/// @pre env object is provided.
/// @}
void editEnv_Function(void);

/// @defgroup resetEnvForm_Function "resetEnvForm:Function"
/// @{
/// @brief Resets the environment form.
/// @post newEnv is reset to initial state and editingEnvId is cleared.
/// @pre None.
/// @}
void resetEnvForm_Function(void);

/// @defgroup ErrorPage "ErrorPage"
/// @{
/// @brief Global error page displaying HTTP status code and error message with navigation back to dashboard.
/// @}
void ErrorPage(void);

/// @defgroup RootLayout "RootLayout"
/// @{
/// @brief Root layout component providing global UI structure: Sidebar, TopNavbar, Footer, TaskDrawer, Toasts.
/// @invariant Sidebar width adapts (ml-60 vs ml-16) based on sidebar expanded state.
/// @}
void RootLayout(void);

/// @defgroup RootLayoutConfig_Module "RootLayoutConfig:Module"
/// @{
/// @brief Root layout configuration (SPA mode)
/// @}
void RootLayoutConfig_Module(void);

/// @defgroup HomePage "HomePage"
/// @{
/// @brief Redirect to preferred start page (dashboards/datasets/reports) based on profile settings, with safe fallback.
/// @invariant Redirect target resolves to one of /dashboards, /datasets, /reports.
/// @}
void HomePage(void);

/// @defgroup load_Function "load:Function"
/// @{
/// @brief Loads initial plugin data for the dashboard.
/// @post Returns an object with plugins or an error message.
/// @pre None.
/// @}
void load_Function(void);

/// @defgroup frontend_src_routes__page_ts__load "frontend/src/routes/+page.ts::load"
/// @{
/// @}
void frontend_src_routes__page_ts__load(void);

/// @defgroup openCreateModal_Function "openCreateModal:Function"
/// @{
/// @brief Initializes state for creating a new role.
/// @post showModal is true, roleForm is reset.
/// @pre None.
/// @}
void openCreateModal_Function(void);

/// @defgroup openEditModal_Function "openEditModal:Function"
/// @{
/// @brief Initializes state for editing an existing role.
/// @post showModal is true, roleForm is populated.
/// @pre role object is provided.
/// @}
void openEditModal_Function(void);

/// @defgroup handleSaveRole_Function "handleSaveRole:Function"
/// @{
/// @brief Submits role data (create or update).
/// @post Role is saved, modal closed, data reloaded.
/// @pre roleForm contains valid data.
/// @}
void handleSaveRole_Function(void);

/// @defgroup handleDeleteRole_Function "handleDeleteRole:Function"
/// @{
/// @brief Deletes a role after confirmation.
/// @post Role is deleted if confirmed, data reloaded.
/// @pre role object is provided.
/// @}
void handleDeleteRole_Function(void);

/// @defgroup handleCreateMapping_Function "handleCreateMapping:Function"
/// @{
/// @brief Submits a new AD Group to Role mapping to the backend.
/// @post A new mapping is created in the database and the table is refreshed.
/// @pre 'newMapping' object contains valid 'ad_group' and 'role_id'.
/// @return {Promise<void>}
/// @}
void handleCreateMapping_Function(void);

/// @defgroup loadLoggingConfig_Function "loadLoggingConfig:Function"
/// @{
/// @brief Fetches current logging configuration from the backend.
/// @post loggingConfig variable is updated with backend data.
/// @pre Component is mounted and user has active session.
/// @return {Promise<void>}
/// @}
void loadLoggingConfig_Function(void);

/// @defgroup saveLoggingConfig_Function "saveLoggingConfig:Function"
/// @{
/// @brief Saves logging configuration to the backend.
/// @post Configuration is saved and feedback is shown.
/// @pre loggingConfig contains valid values.
/// @return {Promise<void>}
/// @}
void saveLoggingConfig_Function(void);

/// @defgroup LLMReportPage "LLMReportPage"
/// @{
/// @brief Admin settings page for LLM provider configuration.
/// @}
void LLMReportPage(void);

/// @defgroup handleSaveUser_Function "handleSaveUser:Function"
/// @{
/// @brief Submits user data to the backend (create or update).
/// @post User created or updated, modal closed, data reloaded.
/// @pre userForm must be valid.
/// @}
void handleSaveUser_Function(void);

/// @defgroup handleDeleteUser_Function "handleDeleteUser:Function"
/// @{
/// @brief Deletes a user after confirmation.
/// @param {Object} user - The user to delete.
/// @post User deleted if confirmed, data reloaded.
/// @pre user object must be valid.
/// @}
void handleDeleteUser_Function(void);

/// @defgroup DashboardHub_normalizeTaskStatus_Function "DashboardHub.normalizeTaskStatus:Function"
/// @{
/// @brief Normalize raw task status to stable lowercase token for UI.
/// @post returns null or normalized token without enum namespace.
/// @pre status can be enum-like string or null.
/// @}
void DashboardHub_normalizeTaskStatus_Function(void);

/// @defgroup DashboardHub_normalizeValidationStatus_Function "DashboardHub.normalizeValidationStatus:Function"
/// @{
/// @brief Normalize validation status to pass/fail/warn/unknown.
/// @post returns one of pass|fail|warn|unknown.
/// @pre status can be any scalar.
/// @}
void DashboardHub_normalizeValidationStatus_Function(void);

/// @defgroup DashboardHub_getValidationBadgeClass_Function "DashboardHub.getValidationBadgeClass:Function"
/// @{
/// @brief Map validation level to badge class tuple.
/// @post returns deterministic tailwind class string.
/// @pre level in pass|fail|warn|unknown.
/// @}
void DashboardHub_getValidationBadgeClass_Function(void);

/// @defgroup DashboardHub_getValidationLabel_Function "DashboardHub.getValidationLabel:Function"
/// @{
/// @brief Map normalized validation level to compact UI label.
/// @post returns uppercase status label.
/// @pre level in pass|fail|warn|unknown.
/// @}
void DashboardHub_getValidationLabel_Function(void);

/// @defgroup DashboardHub_normalizeOwners_Function "DashboardHub.normalizeOwners:Function"
/// @{
/// @brief Normalize owners payload to unique non-empty display labels.
/// @post Returns owner labels preserving source order.
/// @pre owners can be null, list of strings, or list of user objects.
/// @}
void DashboardHub_normalizeOwners_Function(void);

/// @defgroup DashboardHub_loadDashboards_Function "DashboardHub.loadDashboards:Function"
/// @{
/// @brief Load full dashboard dataset for current environment and hydrate grid projection.
/// @post allDashboards, dashboards, pagination and selection state are synchronized.
/// @pre selectedEnv is not null.
/// @}
void DashboardHub_loadDashboards_Function(void);

/// @defgroup DashboardHub_handleTemporaryShowAll_Function "DashboardHub.handleTemporaryShowAll:Function"
/// @{
/// @brief Temporarily disable profile-default dashboard filter for current page context.
/// @post Next request is sent with override_show_all=true.
/// @pre Dashboards list is loaded in dashboards_main context.
/// @}
void DashboardHub_handleTemporaryShowAll_Function(void);

/// @defgroup DashboardHub_handleRestoreProfileFilter_Function "DashboardHub.handleRestoreProfileFilter:Function"
/// @{
/// @brief Re-enable persisted profile-default filtering after temporary override.
/// @post Next request is sent with override_show_all=false.
/// @pre Current page is in override mode.
/// @}
void DashboardHub_handleRestoreProfileFilter_Function(void);

/// @defgroup DashboardHub_formatDate_Function "DashboardHub.formatDate:Function"
/// @{
/// @brief Convert ISO timestamp to locale date string.
/// @post returns formatted date or "-".
/// @pre value may be null or invalid date string.
/// @}
void DashboardHub_formatDate_Function(void);

/// @defgroup DashboardHub_getGitSummaryLabel_Function "DashboardHub.getGitSummaryLabel:Function"
/// @{
/// @brief Compute stable text label for git state column.
/// @post returns localized summary string.
/// @pre dashboard has git projection fields.
/// @}
void DashboardHub_getGitSummaryLabel_Function(void);

/// @defgroup DashboardHub_getLlmSummaryLabel_Function "DashboardHub.getLlmSummaryLabel:Function"
/// @{
/// @brief Compute normalized LLM validation summary label.
/// @post returns UNKNOWN fallback for missing status.
/// @pre dashboard may have null lastTask.
/// @}
void DashboardHub_getLlmSummaryLabel_Function(void);

/// @defgroup DashboardHub_getColumnCellValue_Function "DashboardHub.getColumnCellValue:Function"
/// @{
/// @brief Resolve comparable/filterable display value for any grid column.
/// @post returns non-empty scalar display value.
/// @pre column belongs to filterable column set.
/// @}
void DashboardHub_getColumnCellValue_Function(void);

/// @defgroup DashboardHub_getFilterOptions_Function "DashboardHub.getFilterOptions:Function"
/// @{
/// @brief Build unique sorted value list for a column filter dropdown.
/// @post returns de-duplicated sorted options.
/// @pre allDashboards is hydrated.
/// @}
void DashboardHub_getFilterOptions_Function(void);

/// @defgroup DashboardHub_getVisibleFilterOptions_Function "DashboardHub.getVisibleFilterOptions:Function"
/// @{
/// @brief Apply in-dropdown search over full filter options.
/// @post returns subset for current filter popover list.
/// @pre columnFilterSearch contains search token for column.
/// @}
void DashboardHub_getVisibleFilterOptions_Function(void);

/// @defgroup DashboardHub_toggleFilterDropdown_Function "DashboardHub.toggleFilterDropdown:Function"
/// @{
/// @brief Toggle active column filter popover.
/// @post openFilterColumn updated.
/// @pre column is valid filter key.
/// @}
void DashboardHub_toggleFilterDropdown_Function(void);

/// @defgroup DashboardHub_toggleFilterValue_Function "DashboardHub.toggleFilterValue:Function"
/// @{
/// @brief Add/remove specific filter value and reapply projection.
/// @post columnFilters updated and grid reprojected from page 1.
/// @pre value comes from option list of the same column.
/// @}
void DashboardHub_toggleFilterValue_Function(void);

/// @defgroup DashboardHub_clearColumnFilter_Function "DashboardHub.clearColumnFilter:Function"
/// @{
/// @brief Reset selected values for one column.
/// @post filter cleared and projection refreshed.
/// @pre column is valid filter key.
/// @}
void DashboardHub_clearColumnFilter_Function(void);

/// @defgroup DashboardHub_selectAllColumnFilterValues_Function "DashboardHub.selectAllColumnFilterValues:Function"
/// @{
/// @brief Select all currently visible values in filter popover.
/// @post column filter equals current visible option set.
/// @pre visible options computed for current search token.
/// @}
void DashboardHub_selectAllColumnFilterValues_Function(void);

/// @defgroup DashboardHub_updateColumnFilterSearch_Function "DashboardHub.updateColumnFilterSearch:Function"
/// @{
/// @brief Update local search token for one filter popover.
/// @post columnFilterSearch updated immutably.
/// @pre value is text from input.
/// @}
void DashboardHub_updateColumnFilterSearch_Function(void);

/// @defgroup DashboardHub_hasColumnFilter_Function "DashboardHub.hasColumnFilter:Function"
/// @{
/// @brief Determine if column has active selected values.
/// @post returns boolean activation marker.
/// @pre column is valid filter key.
/// @}
void DashboardHub_hasColumnFilter_Function(void);

/// @defgroup DashboardHub_doesDashboardPassColumnFilters_Function "DashboardHub.doesDashboardPassColumnFilters:Function"
/// @{
/// @brief Evaluate dashboard row against all active column filters.
/// @post returns true only when row matches every active filter.
/// @pre dashboard contains projected values for each filterable column.
/// @}
void DashboardHub_doesDashboardPassColumnFilters_Function(void);

/// @defgroup DashboardHub_getSortValue_Function "DashboardHub.getSortValue:Function"
/// @{
/// @brief Compute stable comparable sort key for chosen column.
/// @post returns string/number key suitable for deterministic comparison.
/// @pre column belongs to sortable set.
/// @}
void DashboardHub_getSortValue_Function(void);

/// @defgroup DashboardHub_handleSort_Function "DashboardHub.handleSort:Function"
/// @{
/// @brief Toggle or switch sort order and reapply grid projection.
/// @post sortColumn/sortDirection updated and page reset to 1.
/// @pre column belongs to sortable set.
/// @}
void DashboardHub_handleSort_Function(void);

/// @defgroup DashboardHub_getSortIndicator_Function "DashboardHub.getSortIndicator:Function"
/// @{
/// @brief Return visual indicator for active/inactive sort header.
/// @post returns one of ↕ | ↑ | ↓.
/// @pre column belongs to sortable set.
/// @}
void DashboardHub_getSortIndicator_Function(void);

/// @defgroup DashboardHub_applyGridTransforms_Function "DashboardHub.applyGridTransforms:Function"
/// @{
/// @brief Apply search + column filters + sort + pagination to grid data.
/// @post filteredDashboards/dashboards/total/totalPages are synchronized.
/// @pre allDashboards is current source collection.
/// @}
void DashboardHub_applyGridTransforms_Function(void);

/// @defgroup DashboardHeader "DashboardHeader"
/// @{
/// @brief Top title area, breadcrumb, Git branch selector, and action buttons for dashboard detail.
/// @}
void DashboardHeader(void);

/// @defgroup DashboardProfileOverrideIntegrationTest_Module "DashboardProfileOverrideIntegrationTest:Module"
/// @{
/// @brief Verifies temporary show-all override and restore-on-return behavior for profile-default dashboard filtering.
/// @}
void DashboardProfileOverrideIntegrationTest_Module(void);

/// @defgroup HealthCenterPage "HealthCenterPage"
/// @{
/// @brief Main page for the Dashboard Health Center showing health matrix table with environment filtering.
/// @}
void HealthCenterPage(void);

/// @defgroup loadData_Function "loadData:Function"
/// @{
/// @brief Load health summary rows and environment options for the current filter.
/// @post `healthData` and `environments` reflect latest backend response.
/// @pre Page is mounted or environment selection changed.
/// @}
void loadData_Function(void);

/// @defgroup handleEnvChange_Function "handleEnvChange:Function"
/// @{
/// @brief Apply environment filter and trigger health summary reload.
/// @post selectedEnvId is updated and new data load starts.
/// @pre DOM change event carries target value.
/// @}
void handleEnvChange_Function(void);

/// @defgroup handleDeleteReport_Function "handleDeleteReport:Function"
/// @{
/// @brief Delete one health report row with confirmation and optimistic button lock.
/// @post Row is removed from backend and page data is reloaded on success.
/// @pre item contains `record_id` from health summary payload.
/// @}
void handleDeleteReport_Function(void);

/// @defgroup HealthPageIntegrationTest_Module "HealthPageIntegrationTest:Module"
/// @{
/// @brief Lock dashboard health page contract for slug navigation and report deletion.
/// @}
void HealthPageIntegrationTest_Module(void);

/// @defgroup DatasetHub "DatasetHub"
/// @{
/// @}
void DatasetHub(void);

/// @defgroup ColumnsTable "ColumnsTable"
/// @{
/// @brief Table of dataset columns with type chips, description, and inline-edit capability.
/// @}
void ColumnsTable(void);

/// @defgroup DatasetList "DatasetList"
/// @{
/// @brief Renders paginated dataset cards with mapping progress bars, checkboxes, and quick actions.
/// @}
void DatasetList(void);

/// @defgroup DatasetPreview "DatasetPreview"
/// @{
/// @brief Right panel showing dataset detail: header info, columns table, metrics table, linked dashboards. Presentational.
/// @}
void DatasetPreview(void);

/// @defgroup MetricsTable "MetricsTable"
/// @{
/// @brief Table of dataset metrics with expression, description, and inline-edit capability.
/// @}
void MetricsTable(void);

/// @defgroup StatsBar "StatsBar"
/// @{
/// @brief Compact filter pills showing aggregate counts (All, Without mapping, Mapped, Linked).
/// @}
void StatsBar(void);

/// @defgroup DatasetReviewWorkspaceEntry "DatasetReviewWorkspaceEntry"
/// @{
/// @brief Entry route for Dataset Review Workspace — start a new resumable review session or navigate to existing sessions.
/// @}
void DatasetReviewWorkspaceEntry(void);

/// @defgroup ReviewWorkspaceHeader "ReviewWorkspaceHeader"
/// @{
/// @brief Header section for the dataset review workspace with title, description, and status badges.
/// @}
void ReviewWorkspaceHeader(void);

/// @defgroup ReviewWorkspaceLeftSidebar "ReviewWorkspaceLeftSidebar"
/// @{
/// @brief Left sidebar for dataset review workspace: source info, import status, session summary, clarification focus, primary actions.
/// @}
void ReviewWorkspaceLeftSidebar(void);

/// @defgroup ReviewWorkspaceRightRail "ReviewWorkspaceRightRail"
/// @{
/// @brief Right rail for dataset review workspace: next action, blockers, health counts, exports, SQL preview, launch panel.
/// @}
void ReviewWorkspaceRightRail(void);

/// @defgroup DatasetReviewWorkspace "DatasetReviewWorkspace"
/// @{
/// @brief Main dataset review workspace — thin shell delegating to extracted components.
/// @deprecated N/A — active workspace page.
/// @}
void DatasetReviewWorkspace(void);

/// @defgroup DatasetReviewEntryUxTests "DatasetReviewEntryUxTests"
/// @{
/// @brief Verify dataset review entry route exposes resumable sessions alongside the new session intake flow.
/// @}
void DatasetReviewEntryUxTests(void);

/// @defgroup DatasetReviewEntryUxPageTests "DatasetReviewEntryUxPageTests"
/// @{
/// @brief Verify dataset review entry route exposes resumable sessions alongside the new session intake flow.
/// @}
void DatasetReviewEntryUxPageTests(void);

/// @defgroup ReviewWorkspaceHelpers "ReviewWorkspaceHelpers"
/// @{
/// @brief Shared helper functions for the dataset review workspace.
/// @}
void ReviewWorkspaceHelpers(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__buildImportMilestones "frontend/src/routes/datasets/review/review-workspace-helpers.js::buildImportMilestones"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__buildImportMilestones(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__buildWorkspaceLaunchBlockers "frontend/src/routes/datasets/review/review-workspace-helpers.js::buildWorkspaceLaunchBlockers"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__buildWorkspaceLaunchBlockers(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__buildAssistantSeedPrompt "frontend/src/routes/datasets/review/review-workspace-helpers.js::buildAssistantSeedPrompt"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__buildAssistantSeedPrompt(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__buildAssistantContextPrompt "frontend/src/routes/datasets/review/review-workspace-helpers.js::buildAssistantContextPrompt"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__buildAssistantContextPrompt(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__getWorkspaceStateLabel "frontend/src/routes/datasets/review/review-workspace-helpers.js::getWorkspaceStateLabel"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__getWorkspaceStateLabel(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__getRecommendedActionLabel "frontend/src/routes/datasets/review/review-workspace-helpers.js::getRecommendedActionLabel"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__getRecommendedActionLabel(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__getPrimaryActionCtaLabel "frontend/src/routes/datasets/review/review-workspace-helpers.js::getPrimaryActionCtaLabel"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__getPrimaryActionCtaLabel(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__mergeCollectionItem "frontend/src/routes/datasets/review/review-workspace-helpers.js::mergeCollectionItem"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__mergeCollectionItem(void);

/// @defgroup frontend_src_routes_datasets_review_review_workspace_helpers_js__stringifyValue "frontend/src/routes/datasets/review/review-workspace-helpers.js::stringifyValue"
/// @{
/// @}
void frontend_src_routes_datasets_review_review_workspace_helpers_js__stringifyValue(void);

/// @defgroup UseReviewSession "UseReviewSession"
/// @{
/// @brief Composable for dataset review session state management — load, update, export, and clarify.
/// @}
void UseReviewSession(void);

/// @defgroup GitDashboardPage "GitDashboardPage"
/// @{
/// @brief Git integration page for selecting environments and managing dashboard repositories.
/// @}
void GitDashboardPage(void);

/// @defgroup LoginPage "LoginPage"
/// @{
/// @brief Provides the user interface for local (username/password) and ADFS SSO authentication.
/// @invariant Shows both local login form and ADFS SSO button.
/// @}
void LoginPage(void);

/// @defgroup MaintenanceBannerPage "MaintenanceBannerPage"
/// @{
/// @brief Maintenance Banners management page. Composes SettingsPanel and EventsTable from store.
/// @}
void MaintenanceBannerPage(void);

/// @defgroup ReactiveDashboardFetch_Block "ReactiveDashboardFetch:Block"
/// @{
/// @brief Automatically fetch dashboards when the source environment is changed.
/// @post fetchDashboards is called with the new sourceEnvId.
/// @pre sourceEnvId is not empty.
/// @}
void ReactiveDashboardFetch_Block(void);

/// @defgroup handleMappingUpdate_Function "handleMappingUpdate:Function"
/// @{
/// @brief Saves a mapping to the backend.
/// @post Mapping is saved and local mappings list is updated.
/// @pre event.detail contains sourceUuid and targetUuid.
/// @}
void handleMappingUpdate_Function(void);

/// @defgroup handleViewLogs_Function "handleViewLogs:Function"
/// @{
/// @brief Opens the log viewer for a specific task.
/// @post logViewer state updated and showLogViewer set to true.
/// @pre event.detail contains task object.
/// @}
void handleViewLogs_Function(void);

/// @defgroup handlePasswordPrompt_Function "handlePasswordPrompt:Function"
/// @{
/// @brief Reactive logic to show password prompt when a task is awaiting input.
/// @post showPasswordPrompt set to true with request data.
/// @pre selectedTask status is AWAITING_INPUT.
/// @}
void handlePasswordPrompt_Function(void);

/// @defgroup ReactivePasswordPrompt_Block "ReactivePasswordPrompt:Block"
/// @{
/// @brief Monitor selected task for input requests and trigger password prompt.
/// @post showPasswordPrompt is set to true if input_request is database_password.
/// @pre $selectedTask is not null and status is AWAITING_INPUT.
/// @}
void ReactivePasswordPrompt_Block(void);

/// @defgroup handleResumeMigration_Function "handleResumeMigration:Function"
/// @{
/// @brief Resumes a migration task with provided passwords.
/// @post resumeTask is called and showPasswordPrompt is hidden on success.
/// @pre event.detail contains passwords.
/// @}
void handleResumeMigration_Function(void);

/// @defgroup startMigration_Function "startMigration:Function"
/// @{
/// @brief Initiates the migration process by sending the selection to the backend.
/// @post A migration task is created and selectedTask store is updated.
/// @pre sourceEnvId and targetEnvId are set and different; at least one dashboard is selected.
/// @}
void startMigration_Function(void);

/// @defgroup startDryRun_Function "startDryRun:Function"
/// @{
/// @brief Performs a dry-run migration to identify potential risks and changes.
/// @post dryRunResult is populated with the pre-flight analysis.
/// @pre source/target environments and selected dashboards are valid.
/// @}
void startDryRun_Function(void);

/// @defgroup MigrationMappingsPage "MigrationMappingsPage"
/// @{
/// @brief Render and orchestrate mapping management UI for source/target environments with backend persistence.
/// @invariant Persisted mapping state in backend remains the source of truth for rendered mapping pairs.
/// @post UI exposes deterministic Idle/Loading/Error/Success states for environment loading, database fetch, and mapping save.
/// @pre Translation store and API client are available; route is mounted in authenticated UI shell.
/// @}
void MigrationMappingsPage(void);

/// @defgroup MappingsPageScript_Block "MappingsPageScript:Block"
/// @{
/// @brief Define imports, state, and handlers that drive migration mappings page FSM.
/// @}
void MappingsPageScript_Block(void);

/// @defgroup Imports_Block "Imports:Block"
/// @{
/// @}
void Imports_Block(void);

/// @defgroup UiState_Store "UiState:Store"
/// @{
/// @brief Maintain local page state for environments, fetched databases, mappings, suggestions, and UX messages.
/// @}
void UiState_Store(void);

/// @defgroup belief_scope_Function "belief_scope:Function"
/// @{
/// @brief Frontend semantic scope wrapper for CRITICAL trace boundaries without changing business behavior.
/// @post Executes run exactly once and returns/rejects with the same outcome.
/// @pre scopeId is non-empty and run is callable.
/// @}
void belief_scope_Function(void);

/// @defgroup fetchDatabases_Function "fetchDatabases:Function"
/// @{
/// @brief Fetch both environment database catalogs, existing mappings, and suggested matches.
/// @post fetchingDbs=false and sourceDatabases/targetDatabases/mappings/suggestions updated or error set.
/// @pre sourceEnvId and targetEnvId are both selected and non-empty.
/// @}
void fetchDatabases_Function(void);

/// @defgroup handleUpdate_Function "handleUpdate:Function"
/// @{
/// @brief Persist a selected mapping pair and reconcile local mapping list by source database UUID.
/// @post mapping persisted; local mappings replaced for same source UUID; success or error feedback shown.
/// @pre event.detail includes sourceUuid/targetUuid and matching source/target database records exist.
/// @}
void handleUpdate_Function(void);

/// @defgroup MappingsPageTemplate "MappingsPageTemplate"
/// @{
/// @brief Mapping page template with environment selectors, database mapping table, and action buttons.
/// @}
void MappingsPageTemplate(void);

/// @defgroup ProfilePage "ProfilePage"
/// @{
/// @brief User profile page for viewing and editing personal preferences and settings.
/// @}
void ProfilePage(void);

/// @defgroup ProfileFixtures_Module "ProfileFixtures:Module"
/// @{
/// @brief Shared deterministic fixture inputs for profile page integration tests.
/// @invariant lookupFailedManualFallback.warning is a hardcoded English string; drift risk if i18n key profile.lookup_error changes without updating this fixture.
/// @}
void ProfileFixtures_Module(void);

/// @defgroup ProfilePreferencesIntegrationTest "ProfilePreferencesIntegrationTest"
/// @{
/// @brief Verifies profile page loads preferences and saves them.
/// @}
void ProfilePreferencesIntegrationTest(void);

/// @defgroup ProfileSettingsStateIntegrationTest "ProfileSettingsStateIntegrationTest"
/// @{
/// @brief Verifies profile loads preferences, allows changes, and saves correctly.
/// @}
void ProfileSettingsStateIntegrationTest(void);

/// @defgroup UnifiedReportsPage "UnifiedReportsPage"
/// @{
/// @brief Unified reports page with task-type and status filtering, list selection, detail panel, and resilient UX states for mixed task types.
/// @}
void UnifiedReportsPage(void);

/// @defgroup ReportPageContractTest_Module "ReportPageContractTest:Module"
/// @{
/// @brief Protect the LLM report page from self-triggering screenshot load effects.
/// @}
void ReportPageContractTest_Module(void);

/// @defgroup llm_report_screenshot_effect_contract_Function "llm_report_screenshot_effect_contract:Function"
/// @{
/// @brief Ensure screenshot loading stays untracked from blob-url mutation state.
/// @post Contract fails if screenshot loading effect can subscribe to screenshotBlobUrls updates.
/// @pre Report page source exists.
/// @}
void llm_report_screenshot_effect_contract_Function(void);

/// @defgroup SettingsPage "SettingsPage"
/// @{
/// @brief Consolidated Settings Page shell — thin layout that delegates each tab to its own component.
/// @deprecated N/A
/// @post Page exposes consolidated settings tabs; each tab manages its own state.
/// @pre Route is loaded in the authenticated UI shell.
/// @}
void SettingsPage(void);

/// @defgroup frontend_src_routes_settings__page_ts__load "frontend/src/routes/settings/+page.ts::load"
/// @{
/// @}
void frontend_src_routes_settings__page_ts__load(void);

/// @defgroup FeaturesSettings "FeaturesSettings"
/// @{
/// @brief Feature flags configuration tab: enable/disable top-level application features.
/// @post User can toggle feature flags.
/// @pre settings object with features config is provided.
/// @}
void FeaturesSettings(void);

/// @defgroup LlmSettings "LlmSettings"
/// @{
/// @brief LLM configuration tab: providers, bindings, prompts for chatbot and validation.
/// @post User can configure LLM provider bindings and prompts.
/// @pre settings object with llm config and llm_providers list is provided.
/// @}
void LlmSettings(void);

/// @defgroup LoggingSettings "LoggingSettings"
/// @{
/// @brief Logging configuration tab: log level, task log level, belief state toggle.
/// @post User can adjust logging levels and toggle belief state.
/// @pre settings object with logging config is provided.
/// @}
void LoggingSettings(void);

/// @defgroup MigrationMappingsTable "MigrationMappingsTable"
/// @{
/// @brief Mappings data table with search, filtering, and pagination for migration sync resources. Isolated from the main MigrationSettings to keep each module < 400 lines.
/// @post User can search, filter by environment/type, and paginate through resource mappings.
/// @pre API client initialized, refreshKey provided by parent.
/// @}
void MigrationMappingsTable(void);

/// @defgroup MigrationSettings "MigrationSettings"
/// @{
/// @brief Migration sync configuration tab: cron schedule, sync now, mappings table with filtering and pagination.
/// @post User can configure sync schedule, trigger sync, and browse resource mappings.
/// @pre API client initialized.
/// @}
void MigrationSettings(void);

/// @defgroup StorageSettings "StorageSettings"
/// @{
/// @brief Storage configuration tab: root path, backup path, repo path.
/// @post User can view and edit storage paths.
/// @pre settings object with storage config is provided.
/// @}
void StorageSettings(void);

/// @defgroup SystemSettings "SystemSettings"
/// @{
/// @brief System settings tab: timezone configuration and API key management.
/// @post User can select the application timezone and manage API keys.
/// @pre settings object is provided with app_timezone field.
/// @}
void SystemSettings(void);

/// @defgroup SettingsPageUxTest_Module "SettingsPageUxTest:Module"
/// @{
/// @brief Test UX states and transitions
/// @}
void SettingsPageUxTest_Module(void);

/// @defgroup AutomationPage "AutomationPage"
/// @{
/// @brief Settings page for managing validation policies.
/// @}
void AutomationPage(void);

/// @defgroup loadConfigs_Function "loadConfigs:Function"
/// @{
/// @brief Fetches existing git configurations.
/// @post configs state is populated.
/// @pre Component is mounted.
/// @}
void loadConfigs_Function(void);

/// @defgroup handleTest_Function "handleTest:Function"
/// @{
/// @brief Tests connection to a git server with current form data.
/// @post testing state is managed; toast shown with result.
/// @pre newConfig contains valid provider, url, and pat.
/// @}
void handleTest_Function(void);

/// @defgroup handleSave_Function "handleSave:Function"
/// @{
/// @brief Saves a new git configuration.
/// @post New config is saved to DB and added to configs list.
/// @pre newConfig is valid and tested.
/// @}
void handleSave_Function(void);

/// @defgroup handleEdit_Function "handleEdit:Function"
/// @{
/// @brief Populates the form with an existing config to edit.
/// @param {Object} config - Configuration object to edit.
/// @post Form is populated and isEditing state is set.
/// @}
void handleEdit_Function(void);

/// @defgroup resetForm_Function "resetForm:Function"
/// @{
/// @brief Resets the configuration form.
/// @}
void resetForm_Function(void);

/// @defgroup loadGiteaRepos_Function "loadGiteaRepos:Function"
/// @{
/// @brief Loads repositories from selected Gitea config.
/// @post giteaRepos state updated.
/// @pre selectedGiteaConfigId is set.
/// @}
void loadGiteaRepos_Function(void);

/// @defgroup handleCreateGiteaRepo_Function "handleCreateGiteaRepo:Function"
/// @{
/// @brief Creates new repository on selected Gitea server.
/// @post Repository created and repos list reloaded.
/// @pre selectedGiteaConfigId and newGiteaRepo.name are set.
/// @}
void handleCreateGiteaRepo_Function(void);

/// @defgroup handleDeleteGiteaRepo_Function "handleDeleteGiteaRepo:Function"
/// @{
/// @brief Deletes repository from selected Gitea server.
/// @post Repository deleted and repos list reloaded.
/// @pre selectedGiteaConfigId is set.
/// @}
void handleDeleteGiteaRepo_Function(void);

/// @defgroup GitSettingsPageUxTest_Module "GitSettingsPageUxTest:Module"
/// @{
/// @brief Test UX states and transitions for the Git Settings page
/// @}
void GitSettingsPageUxTest_Module(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__readTabFromUrl "frontend/src/routes/settings/settings-utils.js::readTabFromUrl"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__readTabFromUrl(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__writeTabToUrl "frontend/src/routes/settings/settings-utils.js::writeTabToUrl"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__writeTabToUrl(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__normalizeTab "frontend/src/routes/settings/settings-utils.js::normalizeTab"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__normalizeTab(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__normalizeLlmSettings "frontend/src/routes/settings/settings-utils.js::normalizeLlmSettings"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__normalizeLlmSettings(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__isDashboardValidationBindingValid "frontend/src/routes/settings/settings-utils.js::isDashboardValidationBindingValid"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__isDashboardValidationBindingValid(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__getProviderById "frontend/src/routes/settings/settings-utils.js::getProviderById"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__getProviderById(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__normalizeSupersetBaseUrl "frontend/src/routes/settings/settings-utils.js::normalizeSupersetBaseUrl"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__normalizeSupersetBaseUrl(void);

/// @defgroup frontend_src_routes_settings_settings_utils_js__resolveEnvStage "frontend/src/routes/settings/settings-utils.js::resolveEnvStage"
/// @{
/// @}
void frontend_src_routes_settings_settings_utils_js__resolveEnvStage(void);

/// @defgroup StorageIndexPage "StorageIndexPage"
/// @{
/// @brief Redirect to the backups page as the default storage view.
/// @invariant Always redirects to /storage/backups.
/// @}
void StorageIndexPage(void);

/// @defgroup BackupsRedirectPage "BackupsRedirectPage"
/// @{
/// @brief Temporary switch to legacy storage browser for backup UX validation.
/// @invariant Always redirects to /tools/storage.
/// @}
void BackupsRedirectPage(void);

/// @defgroup fetchEnvironments_Function "fetchEnvironments:Function"
/// @{
/// @brief Fetches the list of available environments.
/// @post environments array is populated, selectedEnvId is set to first env if available.
/// @pre None.
/// @}
void fetchEnvironments_Function(void);

/// @defgroup fetchDashboards_Function "fetchDashboards:Function"
/// @{
/// @brief Fetches dashboards for a specific environment.
/// @post dashboards array is populated with metadata for the selected environment.
/// @pre envId is a valid environment ID.
/// @}
void fetchDashboards_Function(void);

/// @defgroup filterDashboardsWithRepositories_Function "filterDashboardsWithRepositories:Function"
/// @{
/// @brief Keep only dashboards that already have initialized Git repositories.
/// @post Returns dashboards with status != NO_REPO.
/// @pre dashboards list is loaded for selected environment.
/// @}
void filterDashboardsWithRepositories_Function(void);

/// @defgroup BackupsPage "BackupsPage"
/// @{
/// @brief Entry point for the Backup Management interface.
/// @}
void BackupsPage(void);

/// @defgroup DebugToolPage "DebugToolPage"
/// @{
/// @brief Page for system diagnostics and debugging.
/// @}
void DebugToolPage(void);

/// @defgroup MapperToolPage "MapperToolPage"
/// @{
/// @brief Page for the dataset column mapper tool.
/// @}
void MapperToolPage(void);

/// @defgroup loadFiles_Function "loadFiles:Function"
/// @{
/// @brief Fetches the list of files from the server.
/// @post Updates the `files` array with the latest data.
/// @pre currentPath is a valid storage path or empty for root.
/// @}
void loadFiles_Function(void);

/// @defgroup resolveStorageQueryFromPath_Function "resolveStorageQueryFromPath:Function"
/// @{
/// @brief Splits UI path into storage API category and category-local subpath.
/// @post Returns {category, subpath} compatible with /api/storage/files.
/// @pre uiPath may be empty or start with backups/repositorys.
/// @}
void resolveStorageQueryFromPath_Function(void);

/// @defgroup handleDelete_Function "handleDelete:Function"
/// @{
/// @brief Handles the file deletion process.
/// @param {CustomEvent} event - The delete event containing category and path.
/// @post File is deleted and file list is refreshed.
/// @pre The event contains valid category and path.
/// @}
void handleDelete_Function(void);

/// @defgroup handleNavigate_Function "handleNavigate:Function"
/// @{
/// @brief Updates the current path and reloads files when navigating into a directory.
/// @param {CustomEvent} event - The navigation event containing the new path.
/// @post currentPath is updated and files are reloaded.
/// @pre The event contains a valid path string.
/// @}
void handleNavigate_Function(void);

/// @defgroup navigateUp_Function "navigateUp:Function"
/// @{
/// @brief Navigates one level up in the directory structure.
/// @post currentPath is moved up one directory level.
/// @pre currentPath is not root.
/// @}
void navigateUp_Function(void);

/// @defgroup updateUploadCategory_Function "updateUploadCategory:Function"
/// @{
/// @brief Keeps upload category aligned with the currently viewed top-level folder.
/// @post uploadCategory is either backups or repositorys.
/// @pre currentPath can be empty or a slash-delimited path.
/// @}
void updateUploadCategory_Function(void);

/// @defgroup TranslateJobList "TranslateJobList"
/// @{
/// @}
void TranslateJobList(void);

/// @defgroup TranslationJobConfig "TranslationJobConfig"
/// @{
/// @brief Translation job configuration page - orchestrates form state, datasource loading, LLM settings, run/schedule tabs.
/// @deprecated N/A — active page.
/// @}
void TranslationJobConfig(void);

/// @defgroup DictionariesPage "DictionariesPage"
/// @{
/// @}
void DictionariesPage(void);

/// @defgroup DictionaryDetailPage "DictionaryDetailPage"
/// @{
/// @}
void DictionaryDetailPage(void);

/// @defgroup TranslateHistoryPage "TranslateHistoryPage"
/// @{
/// @}
void TranslateHistoryPage(void);

/// @defgroup ValidationTaskList "ValidationTaskList"
/// @{
/// @brief Validation task list page with status filter, task cards, and create/duplicate/delete actions.
/// @param {string} status
/// @}
void ValidationTaskList(void);

/// @defgroup ValidationTaskConfig "ValidationTaskConfig"
/// @{
/// @brief Validation task configuration page with Config and History tabs. Handles new and edit modes.
/// @}
void ValidationTaskConfig(void);

/// @defgroup ValidationHistory "ValidationHistory"
/// @{
/// @brief Validation run history page with filters, metrics summary, and run cards.
/// @}
void ValidationHistory(void);

/// @defgroup GitServiceContractTests "GitServiceContractTests"
/// @{
/// @brief API client tests ensuring correct endpoints are called per contract for Git service operations.
/// @}
void GitServiceContractTests(void);

/// @defgroup gitServiceContractTests_Module "gitServiceContractTests:Module"
/// @{
/// @brief API client tests ensuring correct endpoints are called per contract
/// @post Returns promotion metadata
/// @pre Repo initialized
/// @}
void gitServiceContractTests_Module(void);

/// @defgroup AdminService "AdminService"
/// @{
/// @brief Service for Admin-related API calls including User and Role management, AD group mappings, and logging configuration.
/// @}
void AdminService(void);

/// @defgroup adminService_Module "adminService:Module"
/// @{
/// @brief Service for Admin-related API calls (User and Role management).
/// @invariant All requests must include valid Admin JWT token (handled by api client).
/// @}
void adminService_Module(void);

/// @defgroup getUsers_Function "getUsers:Function"
/// @{
/// @brief Fetches all registered users from the backend.
/// @post Returns an array of user objects.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Array>}
/// @}
void getUsers_Function(void);

/// @defgroup frontend_src_services_adminService_js__getUsers "frontend/src/services/adminService.js::getUsers"
/// @{
/// @post Returns an array of user objects.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__getUsers(void);

/// @defgroup createUser_Function "createUser:Function"
/// @{
/// @brief Creates a new local user.
/// @param {Object} userData - User details (username, email, password, roles, is_active).
/// @post New user record created in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Object>}
/// @}
void createUser_Function(void);

/// @defgroup frontend_src_services_adminService_js__createUser "frontend/src/services/adminService.js::createUser"
/// @{
/// @post New user record created in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__createUser(void);

/// @defgroup getRoles_Function "getRoles:Function"
/// @{
/// @brief Fetches all available system roles.
/// @post Returns an array of role objects.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Array>}
/// @}
void getRoles_Function(void);

/// @defgroup frontend_src_services_adminService_js__getRoles "frontend/src/services/adminService.js::getRoles"
/// @{
/// @post Returns an array of role objects.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__getRoles(void);

/// @defgroup getADGroupMappings_Function "getADGroupMappings:Function"
/// @{
/// @brief Fetches mappings between AD groups and local roles.
/// @post Returns an array of AD group mapping objects.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Array>}
/// @}
void getADGroupMappings_Function(void);

/// @defgroup frontend_src_services_adminService_js__getADGroupMappings "frontend/src/services/adminService.js::getADGroupMappings"
/// @{
/// @post Returns an array of AD group mapping objects.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__getADGroupMappings(void);

/// @defgroup createADGroupMapping_Function "createADGroupMapping:Function"
/// @{
/// @brief Creates or updates an AD group to Role mapping.
/// @param {Object} mappingData - Mapping details (ad_group, role_id).
/// @post New or updated mapping created in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Object>}
/// @}
void createADGroupMapping_Function(void);

/// @defgroup frontend_src_services_adminService_js__createADGroupMapping "frontend/src/services/adminService.js::createADGroupMapping"
/// @{
/// @post New or updated mapping created in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__createADGroupMapping(void);

/// @defgroup updateUser_Function "updateUser:Function"
/// @{
/// @brief Updates an existing user.
/// @param {Object} userData - Updated user data.
/// @post User record updated in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Object>}
/// @}
void updateUser_Function(void);

/// @defgroup frontend_src_services_adminService_js__updateUser "frontend/src/services/adminService.js::updateUser"
/// @{
/// @post User record updated in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__updateUser(void);

/// @defgroup deleteUser_Function "deleteUser:Function"
/// @{
/// @brief Deletes a user.
/// @param {string} userId - Target user ID.
/// @post User record removed from auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<void>}
/// @}
void deleteUser_Function(void);

/// @defgroup frontend_src_services_adminService_js__deleteUser "frontend/src/services/adminService.js::deleteUser"
/// @{
/// @post User record removed from auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__deleteUser(void);

/// @defgroup createRole_Function "createRole:Function"
/// @{
/// @brief Creates a new role.
/// @param {Object} roleData - Role details (name, description, permissions).
/// @post New role created in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @return {Promise<Object>}
/// @}
void createRole_Function(void);

/// @defgroup frontend_src_services_adminService_js__createRole "frontend/src/services/adminService.js::createRole"
/// @{
/// @post New role created in auth.db.
/// @pre User must be authenticated with Admin privileges.
/// @}
void frontend_src_services_adminService_js__createRole(void);

/// @defgroup updateRole_Function "updateRole:Function"
/// @{
/// @brief Updates an existing role.
/// @param {Object} roleData - Updated role data.
/// @return {Promise<Object>}
/// @}
void updateRole_Function(void);

/// @defgroup frontend_src_services_adminService_js__updateRole "frontend/src/services/adminService.js::updateRole"
/// @{
/// @}
void frontend_src_services_adminService_js__updateRole(void);

/// @defgroup deleteRole_Function "deleteRole:Function"
/// @{
/// @brief Deletes a role.
/// @param {string} roleId - Target role ID.
/// @return {Promise<void>}
/// @}
void deleteRole_Function(void);

/// @defgroup frontend_src_services_adminService_js__deleteRole "frontend/src/services/adminService.js::deleteRole"
/// @{
/// @}
void frontend_src_services_adminService_js__deleteRole(void);

/// @defgroup getPermissions_Function "getPermissions:Function"
/// @{
/// @brief Fetches all available permissions.
/// @return {Promise<Array>}
/// @}
void getPermissions_Function(void);

/// @defgroup frontend_src_services_adminService_js__getPermissions "frontend/src/services/adminService.js::getPermissions"
/// @{
/// @}
void frontend_src_services_adminService_js__getPermissions(void);

/// @defgroup getLoggingConfig_Function "getLoggingConfig:Function"
/// @{
/// @brief Fetches current logging configuration.
/// @return {Promise<Object>} - Logging config with level, task_log_level, enable_belief_state.
/// @}
void getLoggingConfig_Function(void);

/// @defgroup frontend_src_services_adminService_js__getLoggingConfig "frontend/src/services/adminService.js::getLoggingConfig"
/// @{
/// @}
void frontend_src_services_adminService_js__getLoggingConfig(void);

/// @defgroup updateLoggingConfig_Function "updateLoggingConfig:Function"
/// @{
/// @brief Updates logging configuration.
/// @param {Object} configData - Logging config (level, task_log_level, enable_belief_state).
/// @return {Promise<Object>}
/// @}
void updateLoggingConfig_Function(void);

/// @defgroup frontend_src_services_adminService_js__updateLoggingConfig "frontend/src/services/adminService.js::updateLoggingConfig"
/// @{
/// @}
void frontend_src_services_adminService_js__updateLoggingConfig(void);

/// @defgroup GitUtils "GitUtils"
/// @{
/// @brief Shared utility functions extracted from GitManager.svelte.
/// @}
void GitUtils(void);

/// @defgroup frontend_src_services_git_utils_js__normalizeEnvStage "frontend/src/services/git-utils.js::normalizeEnvStage"
/// @{
/// @}
void frontend_src_services_git_utils_js__normalizeEnvStage(void);

/// @defgroup frontend_src_services_git_utils_js__stageBadgeClass "frontend/src/services/git-utils.js::stageBadgeClass"
/// @{
/// @}
void frontend_src_services_git_utils_js__stageBadgeClass(void);

/// @defgroup frontend_src_services_git_utils_js__resolveCurrentEnvironmentId "frontend/src/services/git-utils.js::resolveCurrentEnvironmentId"
/// @{
/// @}
void frontend_src_services_git_utils_js__resolveCurrentEnvironmentId(void);

/// @defgroup frontend_src_services_git_utils_js__applyGitflowStageDefaults "frontend/src/services/git-utils.js::applyGitflowStageDefaults"
/// @{
/// @}
void frontend_src_services_git_utils_js__applyGitflowStageDefaults(void);

/// @defgroup frontend_src_services_git_utils_js__isNumericDashboardRef "frontend/src/services/git-utils.js::isNumericDashboardRef"
/// @{
/// @}
void frontend_src_services_git_utils_js__isNumericDashboardRef(void);

/// @defgroup frontend_src_services_git_utils_js__getSelectedConfig "frontend/src/services/git-utils.js::getSelectedConfig"
/// @{
/// @}
void frontend_src_services_git_utils_js__getSelectedConfig(void);

/// @defgroup frontend_src_services_git_utils_js__resolveDefaultConfig "frontend/src/services/git-utils.js::resolveDefaultConfig"
/// @{
/// @}
void frontend_src_services_git_utils_js__resolveDefaultConfig(void);

/// @defgroup frontend_src_services_git_utils_js__resolvePushProviderLabel "frontend/src/services/git-utils.js::resolvePushProviderLabel"
/// @{
/// @}
void frontend_src_services_git_utils_js__resolvePushProviderLabel(void);

/// @defgroup frontend_src_services_git_utils_js__extractHttpHost "frontend/src/services/git-utils.js::extractHttpHost"
/// @{
/// @}
void frontend_src_services_git_utils_js__extractHttpHost(void);

/// @defgroup frontend_src_services_git_utils_js__buildSuggestedRepoName "frontend/src/services/git-utils.js::buildSuggestedRepoName"
/// @{
/// @}
void frontend_src_services_git_utils_js__buildSuggestedRepoName(void);

/// @defgroup frontend_src_services_git_utils_js__tryParseJsonObject "frontend/src/services/git-utils.js::tryParseJsonObject"
/// @{
/// @}
void frontend_src_services_git_utils_js__tryParseJsonObject(void);

/// @defgroup frontend_src_services_git_utils_js__extractUnfinishedMergeContext "frontend/src/services/git-utils.js::extractUnfinishedMergeContext"
/// @{
/// @}
void frontend_src_services_git_utils_js__extractUnfinishedMergeContext(void);

/// @defgroup StorageService "StorageService"
/// @{
/// @brief Frontend API client for file storage management including list, upload, download, and delete operations.
/// @}
void StorageService(void);

/// @defgroup storageService_Module "storageService:Module"
/// @{
/// @brief Frontend API client for file storage management.
/// @}
void storageService_Module(void);

/// @defgroup getStorageAuthHeaders_Function "getStorageAuthHeaders:Function"
/// @{
/// @brief Returns headers with Authorization for storage API calls.
/// @note Unlike api.js getAuthHeaders, this doesn't set Content-Type
/// @return {Object} Headers object with Authorization if token exists.
/// @}
void getStorageAuthHeaders_Function(void);

/// @defgroup frontend_src_services_storageService_js__getStorageAuthHeaders "frontend/src/services/storageService.js::getStorageAuthHeaders"
/// @{
/// @}
void frontend_src_services_storageService_js__getStorageAuthHeaders(void);

/// @defgroup encodeStoragePath_Function "encodeStoragePath:Function"
/// @{
/// @brief Encodes a storage-relative path preserving slash separators.
/// @param {string} path - Relative storage path.
/// @return {string} Encoded path safe for URL segments.
/// @}
void encodeStoragePath_Function(void);

/// @defgroup frontend_src_services_storageService_js__encodeStoragePath "frontend/src/services/storageService.js::encodeStoragePath"
/// @{
/// @}
void frontend_src_services_storageService_js__encodeStoragePath(void);

/// @defgroup listFiles_Function "listFiles:Function"
/// @{
/// @brief Fetches the list of files for a given category and subpath.
/// @param {string} [path] - Optional subpath filter.
/// @post Returns a promise resolving to an array of StoredFile objects.
/// @pre category and path should be valid strings if provided.
/// @return {Promise<Array>}
/// @}
void listFiles_Function(void);

/// @defgroup frontend_src_services_storageService_js__listFiles "frontend/src/services/storageService.js::listFiles"
/// @{
/// @post Returns a promise resolving to an array of StoredFile objects.
/// @pre category and path should be valid strings if provided.
/// @}
void frontend_src_services_storageService_js__listFiles(void);

/// @defgroup uploadFile_Function "uploadFile:Function"
/// @{
/// @brief Uploads a file to the storage system.
/// @param {string} [path] - Target subpath.
/// @post Returns a promise resolving to the metadata of the uploaded file.
/// @pre file must be a valid File object; category must be specified.
/// @return {Promise<Object>}
/// @}
void uploadFile_Function(void);

/// @defgroup frontend_src_services_storageService_js__uploadFile "frontend/src/services/storageService.js::uploadFile"
/// @{
/// @post Returns a promise resolving to the metadata of the uploaded file.
/// @pre file must be a valid File object; category must be specified.
/// @}
void frontend_src_services_storageService_js__uploadFile(void);

/// @defgroup deleteFile_Function "deleteFile:Function"
/// @{
/// @brief Deletes a file or directory from storage.
/// @param {string} path - Relative path of the item.
/// @post The specified file or directory is removed from storage.
/// @pre category and path must identify an existing file or directory.
/// @return {Promise<void>}
/// @}
void deleteFile_Function(void);

/// @defgroup frontend_src_services_storageService_js__deleteFile "frontend/src/services/storageService.js::deleteFile"
/// @{
/// @post The specified file or directory is removed from storage.
/// @pre category and path must identify an existing file or directory.
/// @}
void frontend_src_services_storageService_js__deleteFile(void);

/// @defgroup downloadFileUrl_Function "downloadFileUrl:Function"
/// @{
/// @brief Returns the URL for downloading a file.
/// @note Downloads use browser navigation, so auth is handled via cookies
/// @param {string} path - Relative path of the file.
/// @post Returns a valid API URL for file download.
/// @pre category and path must identify an existing file.
/// @return {string}
/// @}
void downloadFileUrl_Function(void);

/// @defgroup frontend_src_services_storageService_js__downloadFileUrl "frontend/src/services/storageService.js::downloadFileUrl"
/// @{
/// @post Returns a valid API URL for file download.
/// @pre category and path must identify an existing file.
/// @}
void frontend_src_services_storageService_js__downloadFileUrl(void);

/// @defgroup downloadFile_Function "downloadFile:Function"
/// @{
/// @brief Downloads a file using authenticated fetch and saves it in browser.
/// @param {string} [filename] - Optional preferred filename.
/// @post Browser download is triggered or an Error is thrown.
/// @pre category/path identify an existing file and user has READ permission.
/// @return {Promise<void>}
/// @}
void downloadFile_Function(void);

/// @defgroup frontend_src_services_storageService_js__downloadFile "frontend/src/services/storageService.js::downloadFile"
/// @{
/// @post Browser download is triggered or an Error is thrown.
/// @pre category/path identify an existing file and user has READ permission.
/// @}
void frontend_src_services_storageService_js__downloadFile(void);

/// @defgroup TaskService "TaskService"
/// @{
/// @brief Service for Task Management API interactions: listing, fetching details, resuming, resolving, and clearing tasks.
/// @}
void TaskService(void);

/// @defgroup getTasks_Function "getTasks:Function"
/// @{
/// @brief Fetch a list of tasks with pagination and optional status filter.
/// @post Returns a promise resolving to a list of tasks.
/// @pre limit and offset are numbers.
/// @}
void getTasks_Function(void);

/// @defgroup frontend_src_services_taskService_js__getTasks "frontend/src/services/taskService.js::getTasks"
/// @{
/// @}
void frontend_src_services_taskService_js__getTasks(void);

/// @defgroup getTask_Function "getTask:Function"
/// @{
/// @brief Fetch details for a specific task.
/// @post Returns a promise resolving to task details.
/// @pre taskId must be provided.
/// @}
void getTask_Function(void);

/// @defgroup frontend_src_services_taskService_js__getTask "frontend/src/services/taskService.js::getTask"
/// @{
/// @}
void frontend_src_services_taskService_js__getTask(void);

/// @defgroup getTaskLogs_Function "getTaskLogs:Function"
/// @{
/// @brief Fetch logs for a specific task.
/// @post Returns a promise resolving to a list of log entries.
/// @pre taskId must be provided.
/// @}
void getTaskLogs_Function(void);

/// @defgroup frontend_src_services_taskService_js__getTaskLogs "frontend/src/services/taskService.js::getTaskLogs"
/// @{
/// @}
void frontend_src_services_taskService_js__getTaskLogs(void);

/// @defgroup resumeTask_Function "resumeTask:Function"
/// @{
/// @brief Resume a task that is awaiting input (e.g., passwords).
/// @post Returns a promise resolving to the updated task object.
/// @pre taskId and passwords must be provided.
/// @}
void resumeTask_Function(void);

/// @defgroup frontend_src_services_taskService_js__resumeTask "frontend/src/services/taskService.js::resumeTask"
/// @{
/// @}
void frontend_src_services_taskService_js__resumeTask(void);

/// @defgroup resolveTask_Function "resolveTask:Function"
/// @{
/// @brief Resolve a task that is awaiting mapping.
/// @post Returns a promise resolving to the updated task object.
/// @pre taskId and resolutionParams must be provided.
/// @}
void resolveTask_Function(void);

/// @defgroup frontend_src_services_taskService_js__resolveTask "frontend/src/services/taskService.js::resolveTask"
/// @{
/// @}
void frontend_src_services_taskService_js__resolveTask(void);

/// @defgroup clearTasks_Function "clearTasks:Function"
/// @{
/// @brief Clear tasks based on status.
/// @post Returns a promise that resolves when tasks are cleared.
/// @pre status is a string or null.
/// @}
void clearTasks_Function(void);

/// @defgroup frontend_src_services_taskService_js__clearTasks "frontend/src/services/taskService.js::clearTasks"
/// @{
/// @}
void frontend_src_services_taskService_js__clearTasks(void);

/// @defgroup ToolsService "ToolsService"
/// @{
/// @brief Service for generic Task API communication used by Tools — run tasks and poll status.
/// @}
void ToolsService(void);

/// @defgroup runTask_Function "runTask:Function"
/// @{
/// @brief Start a new task for a given plugin.
/// @post Returns a promise resolving to the task instance.
/// @pre pluginId and params must be provided.
/// @}
void runTask_Function(void);

/// @defgroup frontend_src_services_toolsService_js__runTask "frontend/src/services/toolsService.js::runTask"
/// @{
/// @}
void frontend_src_services_toolsService_js__runTask(void);

/// @defgroup getTaskStatus_Function "getTaskStatus:Function"
/// @{
/// @brief Fetch details for a specific task (to poll status or get result).
/// @post Returns a promise resolving to task details.
/// @pre taskId must be provided.
/// @}
void getTaskStatus_Function(void);

/// @defgroup frontend_src_services_toolsService_js__getTaskStatus "frontend/src/services/toolsService.js::getTaskStatus"
/// @{
/// @}
void frontend_src_services_toolsService_js__getTaskStatus(void);

/// @defgroup BackupTypes "BackupTypes"
/// @{
/// @}
void BackupTypes(void);

/// @defgroup frontend_src_types_backup_ts__Backup "frontend/src/types/backup.ts::Backup"
/// @{
/// @}
void frontend_src_types_backup_ts__Backup(void);

/// @defgroup BackupTypes_Module "BackupTypes:Module"
/// @{
/// @}
void BackupTypes_Module(void);

/// @defgroup DashboardTypes "DashboardTypes"
/// @{
/// @}
void DashboardTypes(void);

/// @defgroup DashboardTypes_Module "DashboardTypes:Module"
/// @{
/// @brief TypeScript interfaces for Dashboard entities
/// @}
void DashboardTypes_Module(void);

/// @defgroup frontend_src_types_dashboard_ts__DashboardMetadata "frontend/src/types/dashboard.ts::DashboardMetadata"
/// @{
/// @}
void frontend_src_types_dashboard_ts__DashboardMetadata(void);

/// @defgroup MaintenanceStoreTests "MaintenanceStoreTests"
/// @{
/// @brief Unit tests for MaintenanceStore runes-based store.
/// @}
void MaintenanceStoreTests(void);

/// @defgroup MaintenanceComponentTests "MaintenanceComponentTests"
/// @{
/// @brief Component tests for MaintenanceEventsTable and DashboardMaintenanceBadge.
/// @}
void MaintenanceComponentTests(void);

/// @defgroup MergeSpec "MergeSpec"
/// @{
/// @}
void MergeSpec(void);

/// @defgroup merge_spec "merge_spec"
/// @{
/// @}
void merge_spec(void);

/// @defgroup BuildOfflineDockerBundle "BuildOfflineDockerBundle"
/// @{
/// @brief Thin wrapper — delegates to ./build.sh bundle (.tar.xz output)
/// @}
void BuildOfflineDockerBundle(void);

/// @defgroup venv_lib_python3_13_site_packages_greenlet_TThreadState_hpp__ThreadState "venv/lib/python3.13/site-packages/greenlet/TThreadState.hpp::ThreadState"
/// @{
/// @}
void venv_lib_python3_13_site_packages_greenlet_TThreadState_hpp__ThreadState(void);
