# Kế hoạch chống "mất trí nhớ" trước khi triển khai hardening DSCons

## Mục đích

Tài liệu này khóa bối cảnh làm việc trước khi bước vào giai đoạn triển khai hardening DSCons, nhằm tránh tình trạng:

- quên thứ tự ưu tiên
- drift giữa kế hoạch và code thực tế
- triển khai chồng chéo giữa nhiều wave hoặc nhiều sub-agent
- sửa đúng kỹ thuật nhưng sai mục tiêu vận hành
- quay lại vá cục bộ làm vỡ kiến trúc tổng thể

Tài liệu này là **memory lock** cho toàn bộ giai đoạn triển khai tiếp theo.

---

## Trạng thái dự án tại thời điểm khóa nhớ

DSCons hiện là hệ thống Python/FastAPI cho vận hành công ty xây dựng, dùng:

- FastAPI
- PostgreSQL
- Qdrant
- MLX local LLM
- pytest cho test hiện có

Cấu trúc chính:

- `app/`
- `docs/`
- `tests/`
- `tools/`
- `docker/`

Dự án đã có API thật, workflow persisted, dashboard nội bộ, ingestion scripts, và một phần test coverage. Tuy nhiên hệ thống hiện ở trạng thái:

- pilot mạnh
- có dùng dữ liệu và flow thật từng phần
- chưa đủ chắc để coi là internal production ổn định toàn hệ thống

---

## 5 vấn đề ưu tiên đã chốt

### 1. Workflow persisted có nguy cơ partial state
Nguồn chính:
- `app/services/workflow_persistence_service.py`
- `app/services/workflow_policy_service.py`
- `app/core/postgres.py`

Vấn đề:
- nhiều bước ghi DB liên tiếp
- chưa có transaction boundary đủ rõ
- side effects và persistence lõi đang bị trộn
- retry/replay chưa có idempotency đủ mạnh

Mục tiêu xử lý:
- atomic core transaction
- post-commit projection cho side effects
- execution ledger/checkpoint
- reconciliation rõ ràng

---

### 2. Drift schema giữa code và SQL init
Nguồn chính:
- `app/core/postgres.py`
- `docker/postgres/init/01_init.sql`

Vấn đề:
- lệch tên cột
- lệch type
- code insert cột chưa có trong schema
- thiếu source-of-truth cho schema evolution

Mục tiêu xử lý:
- migration history là canonical source-of-truth
- bootstrap SQL chỉ là artifact đồng bộ
- drift guard trong CI
- additive migration trước, cleanup sau

---

### 3. Fail-soft/fallback che lỗi thật
Nguồn chính:
- `app/services/company_operational_state_service.py`
- `app/services/remediation_planning_service.py`
- `app/services/dossier_report_service.py`
- `app/api/routes.py`

Vấn đề:
- response vẫn hợp lệ dù dependency hỏng
- chưa phân biệt rõ no-data và degraded-data
- readiness chưa phản ánh capability health thật

Mục tiêu xử lý:
- degraded-state contract thống nhất
- source health machine-readable
- fail-open / fail-soft / fail-closed rõ ràng
- readiness chuyển từ infra-only sang capability readiness

---

### 4. Semantics review-derived bị phân tán
Nguồn chính:
- `app/services/company_operational_state_service.py`
- `app/services/operations_case_management_service.py`
- `app/services/remediation_planning_service.py`
- `app/services/workflow_persistence_service.py`

Vấn đề:
- nhiều service tự suy diễn follow-up/blocker/backlog/risk
- dễ drift semantics
- khó kiểm chứng parity
- khó refactor an toàn

Mục tiêu xử lý:
- shared review-derived projection layer
- canonical domain model cho derived semantics
- presentation tách khỏi semantic derivation
- migrate incrementally, không rewrite toàn khối

---

### 5. Thiếu integration / E2E verification
Nguồn chính:
- `tests/`
- `app/api/routes.py`
- các workflow/service chính

Vấn đề:
- test hiện nghiêng về unit + fake clients
- thiếu integration DB/Qdrant thật
- thiếu E2E business-flow
- thiếu readiness/SSE/error-path coverage

Mục tiêu xử lý:
- test pyramid mới
- integration harness chuẩn
- E2E flows ưu tiên
- CI phân tầng
- verification là lớp bao trùm mọi refactor

---

## Thứ tự triển khai đã chốt

Không làm ngẫu hứng. Không đảo thứ tự nếu chưa có lý do rất mạnh.

### Wave 0 — Verification bootstrap
Làm trước để khóa baseline:

- dựng verification scaffold tối thiểu
- thêm guard tests cho current behavior
- tạo baseline để refactor an toàn

### Wave 1 — Schema governance
Làm sớm nhất trong implementation lõi:

- khóa drift
- chốt canonical contracts
- chuẩn bị additive migrations

### Wave 2 — Workflow atomicity
Làm ngay sau schema:

- transaction hóa core persistence
- tách post-commit projection
- chuẩn hóa checkpoint và reconciliation

### Wave 3 — Shared projection
Làm sau khi persistence và schema ổn hơn:

- dựng shared review-derived projection
- migrate consumers dần
- kiểm tra parity trước/sau

### Wave 4 — Degraded observability
Làm khi data path và semantics đã vững hơn:

- surfacing degraded state thống nhất
- readiness theo capability
- logging/metrics/error taxonomy

### Wave 5 — Verification expansion
Diễn ra xuyên suốt, nhưng hoàn thiện ở cuối mỗi phase:

- route contract
- Postgres integration
- Qdrant integration
- core E2E
- nightly smoke

---

## Phụ thuộc giữa các vấn đề

### #2 trước #1
Vì transaction hardening không bền nếu schema còn drift.

### #1 trước #4
Vì projection layer không nên xây trên persistence contract chưa ổn định.

### #4 trước phần hoàn thiện của #3
Vì degraded observability phải phản ánh semantics dùng chung, không phản ánh nhiều cách suy diễn khác nhau.

### #5 vừa đi trước vừa đi cùng
Vì verification cần xuất hiện từ đầu để khóa baseline, nhưng cũng phải mở rộng song song với từng phase.

---

## Các quyết định kiến trúc đã chốt, không quên

### Quyết định 1
Dùng mô hình **hybrid transaction + post-commit projection** cho workflow persistence.

### Quyết định 2
`migration history` là source-of-truth cho schema, không phải `docker/postgres/init/01_init.sql`.

### Quyết định 3
Degraded state phải là **machine-readable contract**, không chỉ là `message` hoặc `used_fallback` rải rác.

### Quyết định 4
Review-derived semantics phải có **shared projection layer** dùng chung.

### Quyết định 5
Không dựa hoàn toàn vào unit tests/fake clients; phải có integration + E2E tối thiểu cho các flow lõi.

---

## Các contract dự kiến cần nhớ khi triển khai

### Workflow persistence
Các khái niệm additive cần cân nhắc:

- `workflow_run_id`
- `persistence_status`
- `execution_status`
- `completed_checkpoints`
- `reconciliation_required`

Request convention tối thiểu:

- `metadata.idempotency_key`

Khái niệm hạ tầng:

- execution ledger kiểu `workflow_run_executions`

---

### Degraded observability
Response envelope đề xuất:

- `status`
- `degraded`
- `fail_policy`
- `decision`
- `warnings`
- `source_health`

Taxonomy gợi ý:

- `configuration`
- `dependency_unavailable`
- `timeout`
- `data_missing`
- `data_invalid`
- `schema_mismatch`
- `transform_error`
- `partial_result`
- `permission`
- `unexpected`

---

### Shared projection
Projection layer phải là nơi canonical hóa:

- follow-up
- blocker
- backlog
- action
- risk
- remediation signal
- assignment state summary
- workflow execution summary

---

### Verification architecture
Test pyramid cần giữ:

1. unit + schema
2. route-contract
3. integration
4. E2E business-flow
5. nightly/manual smoke

---

## Phạm vi các tài liệu kế hoạch đã có

### Tài liệu chính đã tạo
- `docs/workflow-persistence-transaction-hardening-plan.md`
- `docs/postgres-schema-drift-remediation-plan.md`
- `docs/degraded-state-observability-plan.md`
- `docs/integration-e2e-verification-master-plan.md`

### Ghi chú quan trọng
Nhánh kế hoạch cho shared projection từ sub-agent trước **không đáng tin cậy như artifact file**, vì agent đó claim sửa file ngoài phạm vi. Vì vậy khi triển khai, phải xem phần shared projection trong memory lock này là nguồn tóm tắt đã được hợp nhất ở mức parent.

---

## Cách dùng 5 sub-agent khi bắt đầu triển khai thật

### Đợt A — Foundation/spec
- Agent 1: schema governance và migration groundwork
- Agent 2: verification scaffold và integration harness nền
- Agent 3: workflow transaction implementation spike
- Agent 4: shared projection spec và canonical semantics
- Agent 5: degraded-state contract và readiness redesign spec

### Đợt B — Core implementation
- Agent 1: transaction-scoped persistence
- Agent 2: DB migrations + drift guard
- Agent 3: shared projection service/model
- Agent 4: degraded-state surfacing + readiness capability health
- Agent 5: tests/integration/E2E

### Đợt C — Rollout/hardening
- Agent 1: reconciliation tooling + parity verification
- Agent 2: migrate consumers sang projection
- Agent 3: cleanup legacy schema
- Agent 4: dashboard/API observability polish
- Agent 5: nightly smoke + regression stabilization

---

## Nguyên tắc chống mất trí nhớ khi triển khai

### 1. Không sửa theo cảm giác
Mọi thay đổi phải map được vào một trong 5 vấn đề đã chốt.

### 2. Không vá cục bộ làm lệch hướng
Nếu sửa nhanh một lỗi mà làm tăng coupling hoặc tạo contract mờ hơn, dừng lại và đối chiếu với tài liệu này.

### 3. Mỗi PR/đợt làm phải tự khai báo thuộc wave nào
Ví dụ:
- Wave 1 / Schema governance
- Wave 2 / Workflow atomicity

### 4. Trước khi sửa code, nhắc lại dependency chain
- schema
- transaction
- projection
- observability
- verification

### 5. Không merge logic semantics mới vào nhiều service cùng lúc
Ưu tiên tạo canonical projection trước, rồi migrate consumer.

### 6. Không xem fallback “không crash” là thành công
Nếu response degraded mà không surfacing đủ, coi như chưa hoàn tất.

### 7. Không coi docs là tùy chọn
Mỗi phase xong phải đồng bộ docs tương ứng, tránh drift lặp lại.

### 8. Verification không được để cuối cùng
Mọi phase đều phải thêm kiểm chứng tương ứng ngay khi triển khai.

---

## Checklist bắt buộc trước khi bắt đầu ACT triển khai

- [ ] Xác nhận wave hiện tại
- [ ] Xác nhận task đang xử lý thuộc vấn đề #1, #2, #3, #4 hay #5
- [ ] Xác nhận dependency trước đó đã sẵn sàng
- [ ] Xác nhận contract nào bị ảnh hưởng
- [ ] Xác nhận test layer cần thêm cùng thay đổi
- [ ] Xác nhận docs nào phải cập nhật sau khi sửa code

---

## Câu nhắc ngắn để tự neo bối cảnh

> DSCons hiện cần hardening theo thứ tự: verification baseline -> schema governance -> workflow atomicity -> shared projection -> degraded observability -> verification expansion. Không vá lẻ, không drift semantics, không chấp nhận xanh giả.

---

## Tiến độ triển khai đã xác minh

### Wave hiện tại
- Wave 0 / Verification bootstrap
- Wave 1 / Schema governance (slice mở đầu, phạm vi hẹp)

### Slice đã hoàn tất trong đợt này
- Thêm guard test `tests/test_postgres_schema_contracts.py` để khóa contract bootstrap tối thiểu giữa code Postgres và schema init cho employee work logs.
- Sửa mapping trong `app/services/workflow_persistence_service.py` để `_normalize_work_log_status()` trả về tập giá trị phù hợp với contract lưu trữ:
  - `completed` cho các trạng thái hoàn tất
  - `blocked` cho trạng thái bị chặn/hủy
  - `planned` cho trạng thái dạng chưa bắt đầu / chuẩn bị
  - fallback mặc định là `in_progress` cho trạng thái lạ nhưng vẫn cần tương thích với persisted work-log contract
- Cài `pytest` vào môi trường editable hiện tại để chạy verification baseline.

### Validation đã chạy
- `python3 -m pytest tests/test_postgres_schema_contracts.py tests/test_workflow_persistence_service.py -q`
- Kết quả sau slice đầu: `10 passed`
- Kết quả sau khi mở rộng guard schema-governance: `12 passed`
- `python3 -m pytest tests/test_postgres_schema_contracts.py -q`
- Kết quả sau khi thêm migration backbone tối thiểu: `8 passed`
- `python3 -m pytest tests/test_workflow_persistence_service.py -q`
- Kết quả sau khi thêm write-sequence verification: `6 passed`
- `python3 -m pytest tests/test_workflow_persistence_service.py -q`
- Kết quả sau khi tách core write phase thành helper riêng: `6 passed`
- `python3 -m pytest tests/test_workflow_persistence_service.py tests/test_postgres_schema_contracts.py -q`
- Kết quả sau khi nối transaction wrapper vào core write phase và thêm transactional guard: `15 passed`
- `python -m pytest tests/test_workflow_persistence_service.py tests/test_postgres_schema_contracts.py -q`
- Kết quả sau khi nối transactional context thật vào chuỗi core write và cập nhật fake/invariant tests: `15 passed`
- `python3 -m pytest tests/test_workflow_persistence_service.py tests/test_postgres_schema_contracts.py -q`
- Kết quả sau khi thêm rollback/partial-state verification cho failure giữa core write chain: `20 passed`
- `python3 -m pytest tests/test_workflow_persistence_service.py -q`
- Kết quả sau khi dựng reusable failure-path scaffold cho multi-point rollback verification: `8 passed`
- `python3 -m pytest tests/test_workflow_persistence_service.py tests/test_postgres_schema_contracts.py -q`
- Kết quả sau khi mở rộng rollback verification sang nhiều core write stage: `23 passed`

### Ý nghĩa của slice này
- Đã khóa một phần baseline verification cho risk #2 (schema drift).
- Đã sửa một lỗi runtime contract ở risk #1/#2 boundary: workflow persistence có thể phát sinh status không an toàn cho bảng employee work logs.
- Đã mở rộng guard test cho các hotspot drift giá trị miền và shape contract của workflow review:
  - `dossier_review_findings`
  - `dossier_review_assignments`
  - các check constraint chính trong `docker/postgres/init/01_init.sql` cho:
    - `employee_work_log_sessions.status`
    - `employee_work_log_actions.action_type`
    - `dossier_review_sessions.status`
    - `dossier_review_findings.status`
    - `dossier_review_findings.supplement_status`
    - `dossier_review_assignments.priority`
- Đã bắt đầu migration history tối thiểu bằng cách thêm `db/migrations/0001_schema_baseline.sql`:
  - tạo bảng `schema_migrations`
  - ghi version baseline đầu tiên `0001_schema_baseline`
  - biến migration history thành artifact có version trong repo, thay vì chỉ dựa vào `docker/postgres/init/01_init.sql`
- Đã thêm test guard xác nhận migration backbone tồn tại.
- Đã hoàn tất Wave 2 entry discovery ở mức verification artifact:
  - khóa thứ tự write hiện tại của `start_review_run`
  - xác nhận chuỗi ghi lõi hiện tại là:
    - `create_session`
    - `create_finding`
    - `assign_finding`
    - `submit_finding`
    - `verify_finding`
    - `close_session`
  - xác nhận employee work log persistence đang diễn ra sau khi close review
  - xác nhận reload `fetch_review_session` cũng đang diễn ra sau cụm write lõi
- Đã hoàn tất Wave 2 implementation guard đầu tiên:
  - tách core write phase của `start_review_run` vào helper riêng `_execute_core_review_write_phase(...)`
  - giữ nguyên behavior đã được guard bởi test
  - làm rõ ranh giới giữa:
    - core persisted workflow writes
    - employee work-log projection
    - refresh/read-model fetch
    - operational-state enrichment
  - tạo điểm bám rõ hơn cho bước tiếp theo là transaction hóa phase ghi lõi
- Đã hoàn tất bước transactionization additive đầu tiên cho Wave 2:
  - thêm transaction helper abstraction ở tầng Postgres client
  - route `_execute_core_review_write_phase(...)` qua `run_in_transaction(...)` khi client hỗ trợ transaction runner
  - giữ fallback an toàn `operation(None)` để không phá fake client hoặc môi trường chưa hỗ trợ transaction thật
  - thêm test guard xác nhận core write phase thực sự đi qua transaction wrapper đúng một lần
  - giữ nguyên invariant rằng employee log projection, reload read-model và operational-state enrichment vẫn ở ngoài cụm write lõi
- Đã hoàn tất bước transaction-context plumbing đầu tiên cho Wave 2:
  - nối `connection` dùng chung từ `run_in_transaction(...)` xuống toàn bộ core write chain trong `WorkflowPersistenceService`
  - truyền cùng transaction context cho:
    - `create_dossier_review_session`
    - `create_dossier_review_finding`
    - `assign_dossier_review_finding`
    - `submit_dossier_review_supplement`
    - `verify_dossier_review_finding`
    - `close_dossier_review_session`
  - cập nhật fake test client để chấp nhận và ghi nhận `connection`
  - thêm assertion xác nhận tất cả core write steps đều nhận đúng cùng token transaction `tx-conn-1`
  - tăng độ tin cậy rằng cụm write lõi đang dùng chung transactional context thay vì chỉ được bọc logic ở service layer
- Đã thêm rollback/partial-state verification cho Wave 2:
  - giả lập lỗi ngay tại bước `assign_dossier_review_finding`
  - xác nhận `run_in_transaction(...)` ở fake client rollback toàn bộ state core review về snapshot ban đầu
  - xác nhận side effects ngoài transaction không chạy khi core write chain thất bại:
    - không upsert employee work-log session
    - không append employee work-log action
    - không fetch lại read model sau transaction lỗi
  - khóa kỳ vọng rằng failure giữa core write chain không để lại partial persisted state ở mức verification baseline
- Đã mở rộng rollback verification sang nhiều điểm lỗi trong core write chain:
  - thêm reusable failure-path scaffold để bắn lỗi có kiểm soát theo từng stage
  - đã khóa ít nhất các điểm:
    - `create_session`
    - `assign_finding`
    - `submit_finding`
    - `close_session`
  - xác nhận invariant chung ở mọi điểm lỗi đã cover:
    - transaction runner chỉ được gọi một lần
    - core review state quay về snapshot ban đầu
    - không có persisted finding/assignment/submission/verification/close artifact bị rò
    - không chạy post-commit employee work-log projection
    - không chạy read-model refresh sau lỗi
- Từ discovery, refactor và transaction wrapper này có thể tách sơ bộ:
  - transaction-bound candidates:
    - create session
    - create finding
    - assign finding
    - submit supplement
    - verify finding
    - close session
  - post-core / post-commit candidates:
    - persist employee work logs
    - refresh/read-model fetch
    - operational state enrichment
- Chưa nối chain migration này vào bootstrap/runtime apply path.
- Chưa transaction hóa workflow core thật sự.
- Chưa mở rộng sang degraded-state contract hay shared projection.

### Top 3 việc tiếp theo
1. Đẩy Wave 2 rollback verification từ fake level sang integration semantics:
   - nếu khả thi, tạo harness Postgres thật để kiểm tra commit/rollback thực sự
   - xác nhận DB không giữ partial row khi lỗi xuất hiện ở giữa chain ghi lõi
2. Mở rộng schema-governance guard đợt kế tiếp:
   - thêm guard cho contract còn rủi ro cao như `dossier_review_submissions`, `dossier_review_actions`, unique/dedup scope của employee work logs, và các alias legacy dễ drift
3. Nối migration backbone vào bootstrap/verification:
   - quyết định cách sync `docker/postgres/init/01_init.sql` với chain migration
   - thêm manifest/quy ước áp dụng migration cho local/dev/test

## Kết luận

Nếu trong quá trình triển khai xuất hiện nhiễu ngữ cảnh, ưu tiên quay lại tài liệu này trước khi tiếp tục. Tài liệu này là bản khóa nhớ chính thức để giữ:

- đúng ưu tiên
- đúng thứ tự
- đúng dependency
- đúng kiến trúc đích
- đúng tiêu chí hoàn tất
