# 💡 BRIEF: Multi-Agent Pipeline — Consolidate & Instrument

**Ngày tạo:** 2026-07-05
**Brainstorm mode:** Feature
**Nguồn brainstorm:** `~/.gemini/antigravity-ide/brain/6d539c84-259d-4fcd-84a1-9bcb2094bfb6/ai_agents_model_roles_brainstorm.md`

---

## 1. VẤN ĐỀ CẦN GIẢI QUYẾT

Bản đồ phân vai 4 runner (Claude Code = Architect, Codex CLI = UI/QA, Qwen Coder = Executor, agy = Conductor) đã có prototype chạy được (`scripts/escalate-helper.js`, `scripts/model-manager.js`), nhưng khi vận hành thật đã lộ 4 lỗ hổng — có bằng chứng trực tiếp trong repo:

1. **Escalation thiếu điều kiện dừng & phân loại lỗi.** Flow Qwen fail 2 lần → Claude consult → Qwen áp dụng không có max rounds (nguy cơ ping-pong Qwen↔Claude vô hạn). Lần consult thật (`docs/specs/escalation_consult.md`) cho thấy lỗi infra (git credentials) bị escalate sang Claude vô ích — chỉ lỗi code/test mới đáng consult.
2. **Thiếu artifact contract giữa các phase.** Executor đã ghi đè spec 247 dòng bằng message chat; temp files (`scripts/temp_qwen_input_*.txt`) bị auto-commit vào repo. Không có quy định mỗi phase ghi gì, vào đâu, format nào.
3. **Hardcode tên model trong docs.** Tài liệu tự mâu thuẫn (`Claude 3.5/3.7 Sonnet` vs `claude-sonnet-4.6`) trong khi `model-manager.js` đã có khả năng resolve runner/model động.
4. **Pipeline 5-phase chưa map vào 8-Gate system; reviewer không độc lập.** Hai process model song song gây nhầm lẫn vận hành; Claude vừa Plan vừa Review chính plan của mình → confirmation bias. Claim "tiết kiệm ~85% chi phí" chưa có telemetry để kiểm chứng.

## 2. GIẢI PHÁP ĐỀ XUẤT

**Hướng "Consolidate & Instrument"** — củng cố nền tảng trước khi mở rộng:

- Hardening escalation protocol (cap rounds, error classification, attempted-diff packaging).
- Định nghĩa artifact contract cho từng phase + chặn temp artifacts khỏi auto-commit.
- Role map chỉ định nghĩa **role → runner**; model cụ thể resolve động qua `awkit model`.
- Map pipeline vào 8-Gate system, phases có điều kiện theo triage; Codex làm primary reviewer.
- Telemetry KPI để mọi quyết định routing sau này dựa trên evidence.

**Lý do chọn:** 2 hướng còn lại (Parallel Execution, Adaptive Routing) đều phụ thuộc nền tảng và data từ hướng này. Nguyên tắc: Evidence > Assumptions, Small > Big.

## 2.5. THIẾT KẾ HÀNH VI (MÔ HÌNH HOOKED)

- **Kích hoạt (Trigger):**
  - *Internal:* Bức xúc khi executor loop vô hạn đốt token, hoặc pipeline commit rác vào repo — mất niềm tin vào automation.
  - *External:* Cảnh báo escalation/telemetry từ `awkit model stats` sau mỗi task.
- **Hành động (Action):** Operator chỉ cần giao task; pipeline tự route, tự escalate có kiểm soát, tự dừng đúng lúc và báo cáo.
- **Phần thưởng biến thiên (Variable Reward):** Báo cáo sau task (escalation rate, tokens/phase, chi phí tiết kiệm thực đo) — mỗi task một bức tranh khác nhau về hiệu quả routing.
- **Sự đầu tư (Investment):** Mỗi task chạy qua pipeline tích lũy telemetry → routing càng ngày càng chính xác → nền cho Adaptive Routing (Phase sau).

## 3. ĐỐI TƯỢNG SỬ DỤNG

- **Primary:** Operator AWKit (dev sử dụng pipeline đa agent hàng ngày).
- **Secondary:** Chính các AI agents (Claude/Codex/Qwen/agy) — consumer của artifact contract và role map.

## 4. TÍNH NĂNG

### 🚀 MVP: ✅ Hoàn thành 2026-07-05 — xem `docs/specs/PIPELINE_CONTRACT.md`
- [x] **Escalation cap:** tối đa 2 round consult → DỪNG + báo user (sửa `scripts/escalate-helper.js`).
- [x] **Error classification trước escalate:** code/test error → Claude consult; infra/auth/quota error → báo user ngay, không đốt token.
- [x] **Context packaging kèm attempted-diffs:** gói gửi Claude phải chứa diff các lần Qwen đã thử để không đề xuất lại giải pháp đã fail.
- [x] **Trigger deterministic:** đếm số lần thử (2 fails) là trigger chính; wall-clock chỉ còn là safety timeout (10 phút), bỏ ngưỡng "3 phút không tiến triển".
- [x] **Artifact contract:** bảng quy định output của từng phase (Plan → `docs/specs/<task>_spec.md`; Consult → `docs/specs/escalation/`; Review → `codex-reports/`; temp → `tmp/`) + `.gitignore` cho `scripts/temp_*` và artifacts tạm. Bonus: fix root cause leak (`qwen-exec.js` ghi temp vào `tmp/`) + fix double-writer làm hỏng consult report (model không tự ghi file nữa).
- [x] **Dynamic model resolution:** role map chỉ chứa role → runner; model resolve qua `awkit model` / `model-manager.js`. Xóa mọi hardcode tên model trong docs.
- [x] **8-Gate mapping:** Plan = Gate 0–2, UI = Gate 2.5, Code = Gate 4, Review = Gate 5, Commit = auto-commit rule; phases conditional theo triage (TRIVIAL → thẳng Gate 4).
- [x] **Reviewer độc lập:** Codex = primary code reviewer; Claude chỉ review architecture-conformance. Chốt ranh giới Codex: tạo file asset mới = OK, sửa code = không (nhất quán với `codex-conductor`).

### 🎁 Phase 2: ✅ Hoàn thành 2026-07-05
- [x] **Telemetry KPI:** log escalation rate, tokens/phase, retry count, wall-time per task (`scripts/pipeline-telemetry.js`, JSONL → `tmp/`).
- [x] **`awkit model stats`:** báo cáo escalation rate, tokens/phase, retry TB, infra-skip/cap-reached (`model-manager.js`).
- [x] **Consult report format chuẩn hóa:** JSON schema `schemas/consult-report.schema.json` + `validateConsultReport()` (root_cause, files_to_modify, precise_diff).

### 💭 Backlog:
- [ ] **Parallel Execution:** Qwen chạy nhiều module độc lập song song (worktree isolation + merge handling).
- [ ] **Adaptive Routing:** route theo track record từ telemetry (task type nào Qwen hay fail → thẳng Claude).
- [ ] **Conductor fallback:** phương án khi agy chết — Claude Code kiêm Conductor.

## 5. MODULE BREAKDOWN

### Module: escalation-hardening
- **Mục đích:** Escalation có điều kiện dừng, phân loại lỗi, context đầy đủ.
- **Thành phần chính:** `scripts/escalate-helper.js`, error classifier, context packager.
- **Core flows:** Qwen fail ×2 → classify error → (code) package context + diffs → Claude consult (≤2 rounds) → apply hoặc DỪNG báo user; (infra) → báo user ngay.

### Module: artifact-contract
- **Mục đích:** Mỗi phase ghi đúng chỗ, đúng format; repo sạch.
- **Thành phần chính:** Bảng contract trong docs, `.gitignore` updates, (optional) pre-commit validation.
- **Core flows:** Phase hoàn thành → ghi artifact theo contract → auto-commit chỉ nhận file hợp lệ.

### Module: model-resolution
- **Mục đích:** Một source of truth cho model — không hardcode trong docs.
- **Thành phần chính:** Role map config (role → runner), `scripts/model-manager.js`.
- **Core flows:** Pipeline cần model → hỏi `awkit model` → nhận model active + quota status của runner.

### Module: gate-mapping
- **Mục đích:** Hợp nhất pipeline 5-phase vào 8-Gate system, phases conditional theo triage.
- **Thành phần chính:** Cập nhật brainstorm doc + CLAUDE.md orchestrator rules.
- **Core flows:** Task vào → triage → chỉ chạy các gate/phase áp dụng → reviewer độc lập ở Gate 5.

### Module: telemetry (Phase 2)
- **Mục đích:** Đo để kiểm chứng giả định chi phí/chất lượng routing.
- **Thành phần chính:** Logger trong pipeline, `awkit model stats`.
- **Core flows:** Mỗi phase kết thúc → log KPI → tổng hợp báo cáo sau task.

## 6. ƯỚC TÍNH

- **Độ phức tạp:** Trung bình (MVP toàn fix nhỏ trên code sẵn có; không big-bang refactor).
- **Hướng tiếp cận:** Consolidate & Instrument — củng cố + đo lường trước, mở rộng sau.
- **Số modules:** 5 (4 MVP + 1 Phase 2).

## 7. BƯỚC TIẾP THEO

→ Module spec chi tiết (Gate 1.5 — `module-spec-writer` cho escalation-hardening & artifact-contract trước) → Thiết kế kỹ thuật (Gate 2 — `spec-gate`).
