# Implementation Plan: Clean Release Compliance Subsystem Redesign

**Branch**: `025-clean-release-compliance` | **Date**: 2026-03-09 | **Spec**: [spec.md](./spec.md)  
**Input**: Feature specification from [`/specs/025-clean-release-compliance/spec.md`](./spec.md)

## Summary

Перевести текущую clean-release подсистему из TUI-first orchestration в API/CLI-first release/compliance subsystem с четырьмя жёстко разделёнными слоями:
1. domain model для candidate, manifest, policy snapshot, run, report, approval, publication;
2. application services для candidate preparation, manifest build, policy resolution, compliance execution, approval, publication и audit;
3. infrastructure layer для repositories, trusted policy access, artifact storage, audit storage и task execution;
4. thin interfaces для CLI, TUI, REST API и будущего Web UI.

Ключевой результат: TUI перестаёт быть местом, где живёт release logic. Все критические действия выполняются единым facade/application layer, compliance evidence становится immutable/append-only, а long-running runs интегрируются с существующим TaskManager.

## Technical Context

**Language/Version**: Python 3.9+ for backend services, CLI, API and TUI  
**Primary Dependencies**: FastAPI, Pydantic models, existing `TaskManager`, existing reports service patterns, repository adapters, curses-compatible TUI runtime  
**Storage**: PostgreSQL for metadata and snapshots, filesystem/object storage for artifacts and persisted reports, trusted policy/registry store (read-only source)  
**Testing**: pytest unit/integration/contract suites, CLI smoke tests, API contract checks, TUI facade smoke tests  
**Target Platform**: Linux server and CI pipeline in enterprise environment  
**Project Type**: Backend web service with operational CLI/TUI interfaces  
**Performance Goals**:
- request to start compliance returns run/task identifiers in <= 2 seconds for a typical candidate;
- candidate overview and status reads return in <= 1 second for the latest candidate history;
- final report becomes available immediately after terminal run finalization.
**Constraints**:
- policy and registry are trusted read-only inputs, never sourced from TUI/env bootstrap payloads;
- trusted policy store location, active profile selection, mode switching and storage wiring must be resolved through existing `ConfigManager` access patterns rather than ad hoc constants or raw env reads;
- long-running compliance execution must use `TaskManager` and non-blocking API behavior;
- real mode audit history and compliance evidence are append-only;
- TUI must remain usable for operators but cannot contain hidden business logic;
- migration should be incremental because existing code already exposes `clean_release` routes, services and a TUI entrypoint.
**Scale/Scope**:
- tens to hundreds of release candidates per month;
- each candidate may include thousands of artifacts;
- multiple compliance runs and reports may exist for one candidate;
- redesign touches backend domain, API, CLI, TUI and operational documentation.

## Constitution Check

*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*

1. **Semantic Protocol Compliance**: All new modules in this plan are defined via explicit contracts in [`contracts/modules.md`](./contracts/modules.md). Code implementation must follow `[DEF]`, `@PRE`, `@POST`, testing tags and closing anchors. Status: PASS.
2. **Modular Architecture**: Business logic is moved into `backend/src/services/clean_release/` services and repository adapters; interfaces remain thin. Status: PASS.
3. **Independent Testability**: Spec defines independent tests for each user story; tasks will preserve isolated validation paths. Status: PASS.
4. **Asynchronous Execution**: Compliance run execution is explicitly mapped to `TaskManager`, and API launch endpoints are non-blocking. Status: PASS.
5. **Config Discipline**: Policy and registry sources are moved out of ad hoc env/bootstrap input into trusted resolution services. Status: PASS with migration note that existing env-based flows must be deprecated, not silently retained.
6. **Centralized Config**: Trusted store endpoints, mode/profile selection and storage wiring must reuse `ConfigManager` / `get_config_manager()` patterns required by repository constitution. Status: PASS with explicit implementation follow-up in foundational tasks.

## Project Structure

### Documentation (this feature)

```text
specs/025-clean-release-compliance/
├── spec.md
├── plan.md
├── research.md
├── data-model.md
├── quickstart.md
├── ux_reference.md
├── contracts/
│   ├── modules.md
│   ├── clean-release-api.openapi.yaml
│   └── cli.md
├── checklists/
│   └── requirements.md
└── tasks.md
```

### Source Code (repository root)

```text
backend/
├── src/
│   ├── api/routes/clean_release.py
│   ├── dependencies.py
│   ├── models/clean_release.py
│   ├── scripts/
│   │   ├── clean_release_cli.py
│   │   └── clean_release_tui.py
│   └── services/clean_release/
│       ├── __init__.py
│       ├── facade.py
│       ├── enums.py
│       ├── exceptions.py
│       ├── dto.py
│       ├── mappers.py
│       ├── candidate_service.py
│       ├── manifest_service.py
│       ├── policy_resolution_service.py
│       ├── compliance_execution_service.py
│       ├── approval_service.py
│       ├── publication_service.py
│       ├── audit_service.py
│       ├── demo_data_service.py
│       ├── stages/
│       │   ├── base.py
│       │   ├── data_purity.py
│       │   ├── internal_sources_only.py
│       │   ├── no_external_endpoints.py
│       │   └── manifest_consistency.py
│       └── repositories/
│           ├── candidate_repository.py
│           ├── artifact_repository.py
│           ├── manifest_repository.py
│           ├── policy_repository.py
│           ├── compliance_repository.py
│           ├── report_repository.py
│           ├── approval_repository.py
│           ├── publication_repository.py
│           └── audit_repository.py
└── tests/
    ├── api/routes/
    ├── scripts/
    └── services/clean_release/
```

**Structure Decision**: Сохраняем существующую backend-centric структуру проекта и расширяем текущий пакет `backend/src/services/clean_release/` вместо выделения нового top-level приложения. Это уменьшает migration risk и позволяет поэтапно заменить текущие `preparation_service`, `manifest_builder`, `compliance_orchestrator` и `clean_release_tui.py` на фасадную архитектуру.

## Phase 0 Research Scope

Research resolved the main architectural questions and produced decisions in [`research.md`](./research.md):
- trust model for policy and registry;
- immutable snapshot strategy;
- lifecycle/state machine design;
- TaskManager integration strategy;
- interface split between CLI/API/TUI;
- repository decomposition and migration approach;
- demo mode isolation.

## Phase 1 Design Outputs

Phase 1 produces:
- [`data-model.md`](./data-model.md) with canonical entities, states and relationships;
- [`contracts/modules.md`](./contracts/modules.md) with module-level contracts for new services and interfaces;
- [`contracts/clean-release-api.openapi.yaml`](./contracts/clean-release-api.openapi.yaml) and [`contracts/cli.md`](./contracts/cli.md) for programmatic interfaces;
- [`ux_reference.md`](./ux_reference.md) for thin-client TUI/CLI behavior;
- [`quickstart.md`](./quickstart.md) for implementation and validation scenarios.

## Post-Design Constitution Re-Check

1. **No interface-owned business logic**: Preserved by facade + application services. PASS.
2. **Async long-running work**: Preserved by explicit `ComplianceExecutionService -> TaskManager` mapping. PASS.
3. **Independent testability**: Preserved via user-story tasks and dedicated contract tests. PASS.
4. **Config discipline and trust boundaries**: Preserved by read-only policy resolution service and immutable snapshots. PASS.

## Implementation Risks To Control

- Existing `clean_release_tui.py` currently owns preparation/build/run logic and must be thinned without breaking operator workflow.
- Existing repository and model naming may conflict with the redesigned entity boundaries; migration shims may be needed.
- Existing `/api/clean-release/checks*` endpoints may require compatibility strategy while introducing candidate/manifest/run-oriented endpoints.
- Existing `.clean-release.yaml` driven flow from `023-clean-repo-enterprise` conflicts with the new trusted policy-store model and must be deliberately deprecated or scoped.

## Complexity Tracking

| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| Multiple service modules instead of one orchestrator | Trust boundaries, immutability and lifecycle rules need explicit ownership | One orchestrator keeps the current blending of UI, policy, execution and persistence concerns |
| Separate repositories/facade layer | Needed for append-only evidence and independent interfaces | Single universal repository would keep ambiguous ownership and weak contracts |
| TaskManager integration for runs | Constitution requires async lifecycle and observability | Synchronous API/TUI execution would violate non-blocking execution requirements |
