Commit f24d1b6f authored by Admin's avatar Admin

docs: add generic platform roadmap, ideas, and decanifa audit report (Phase 0)

parent 45f3f2f7
# 🚀 DOING: Generic AI Company Platform — Roadmap A→Z (file-by-file)
## 📌 Context
- **Idea:** `plan/ideas/24_generic_ai_company_platform.md` (vision + gap analysis + 7-layer architecture)
- **Status:** 🟡 Planning → ready to execute
- **Insight nền:** Generic core đã tồn tại với tên **Paperclip** (`paperclip.db`, prefix `PAP`, `admin@paperclip.ai`,
`frontend/src/lib → outsource/paperclip/ui/src/lib`). **Canifa = 1 fork customize của Paperclip.**
→ Việc của ta: (a) refactor pipeline hardcode → DAG động, (b) thêm tầng **Company Blueprint**,
(c) de-brand Canifa thành 1 blueprint mẫu.
## 🎯 Goal
Biến repo từ "Canifa-specific instance" thành **nền tảng generic** có thể tạo công ty AI cho **bất kỳ ngành nào**
bằng **1 file blueprint + 1 API call**, không cần sửa core orchestrator.
**Success criteria (đo được):**
1. `POST /api/companies/from-blueprint {blueprint: "software-studio"}` → tạo company + seed agents (đúng `reports_to`) + provision NocoBase, KHÔNG đụng code orchestrator.
2. `ProjectOrchestrator` chạy stages **suy ra từ org-chart/blueprint**, không còn `PIPELINE_STAGES` hardcode.
3. Có ≥3 blueprint ngành (fashion-retail, software-studio, ecommerce-brand) chạy end-to-end.
4. `grep -ri "canifa"` trong `backend/{models,services,api,tasks}` = 0 hit (Canifa chỉ còn ở blueprint + plugins).
## ⚠️ Active Trade-offs
- **Refactor `project_orchestrator.py`** là điểm rủi ro cao nhất → giữ **backward-compat**: nếu blueprint không khai báo `pipeline`, fallback về `PIPELINE_STAGES` cũ. Test trước/sau bằng cùng 1 brief.
- **Không gom hết trong 1 PR.** Mỗi Phase = 1 PR độc lập, mergeable, có verify riêng.
- **Chain-reaction auto-spawn** (issue done → sinh issue kế) CHƯA xác nhận tồn tại → Phase 0 phải audit trước, nếu chưa có thì tách thành doing riêng (không nhồi vào roadmap này).
## 🛠 Impact & Files Touched (tổng quan)
| Phase | File chính | Symbol/Anchor | Change |
|-------|-----------|---------------|--------|
| 0 | _(audit only)_ | — | Tạo `plan/process/00_decanifa_audit.md` |
| 1 | `backend/services/project_orchestrator.py` | `PIPELINE_STAGES:28`, `_group_into_stages:205`, `_get_ordered_agents:273` | MODIFY → DAG động |
| 2 | `backend/schemas/blueprint.py` (new), `backend/services/blueprint_service.py` (new), `backend/blueprints/*.yaml` (new) | — | CREATE |
| 3 | `backend/api/routes/companies.py`, `backend/api/routes/pipelines.py:73-96` | `run_pipeline:40` | ADD endpoint + refactor inline-deploy |
| 4 | `backend/services/nocobase_connector.py:9,21`, `backend/models/company_secrets.py` | `NocoBaseConnector.__init__` | MODIFY → per-company config |
| 5 | `backend/blueprints/{fashion-retail,software-studio,ecommerce-brand,marketing-agency}.yaml` | — | CREATE (data) |
| 6 | `README.md`, `brand-spec.md`, `backend/scratch/seed_db.py` | `seed_db.main` | MODIFY → blueprint-driven |
| 7 | `frontend/src/pages/*`, `frontend/src/api/*` | — | ADD onboarding wizard |
| 8 | `backend/tests/*` | — | ADD integration tests + docs |
**Risk tổng:** Medium. Tập trung ở Phase 1 & 4.
---
## 📋 Execution Checklist
### Phase 0 — Audit & De-Canifa Inventory (~30m, rủi ro 0)
> Không đổi behavior. Chỉ tìm hiểu & ghi nhận. Output: `plan/process/00_decanifa_audit.md`.
- [x] 0.1 — Grep toàn bộ coupling Canifa: `rtk grep -ri "canifa" backend/ --glob '!**/agent/**'` → liệt kê file:line.
- [x] 0.2 — Grep brand/hardcode khác: tìm `"company_123"`, `"PAP"`, `"CAN"`, `localhost:13001`, `admin@paperclip.ai`, `admin@nocobase.com`.
- [x] 0.3 — Liệt kê toàn bộ role hardcode: đọc `project_orchestrator.py:28-37` (`PIPELINE_STAGES`, `ROLE_ORDER`).
- [x] 0.4 — **Verify chain-reaction:** `rtk grep -rn "origin_kind\|monitor_wake\|checkout_wakeup\|auto.*spawn\|create_followup" backend/api/routes/issues*.py backend/tasks/` → xác định issue-done có tự sinh issue kế chưa.
- [x] 0.5 — Liệt kê feature thời trang cần tách ra plugin: `outfit`, `stylist`, `ultra_desc`, `stock`, `fashion` trong `backend/{services,api,tasks}`.
- [x] 0.6 — Map các blueprint-anchor có sẵn: `marketplace_templates.json` (schema `agents[]`), `company_portability.py` (export shape), `company_import_requests.py`.
- [x] 0.7 — Ghi tất cả vào `plan/process/00_decanifa_audit.md` (bảng: file:line | loại coupling | phase xử lý).
- [x] 0.8 — **Verify gate:** audit doc liệt kê đủ, mỗi coupling đã gán phase. ✅ trước khi sang Phase 1.
---
### Phase 1 — Config-Driven Pipeline (DAG động) (~3h, rủi ro Medium)
> Mục tiêu: `ProjectOrchestrator` nhận dependency-graph thay vì hardcode. Giữ fallback cũ.
**1A. Thêm cấu trúc DAG**
- [ ] 1.1 — Trong `project_orchestrator.py`, thêm tham số `pipeline_spec: list[dict] | None = None` vào `__init__` (mỗi item `{role, depends_on: [], parallel: int, approval_gate: bool}`).
- [ ] 1.2 — Viết hàm `_stages_from_spec(self, agents, pipeline_spec) -> list[list[dict]]`: topological-sort theo `depends_on`, gom các role cùng "level" vào 1 stage (chạy song song).
- [ ] 1.3 — Sửa `_group_into_stages` (dòng 205): nếu `self.pipeline_spec` có → gọi `_stages_from_spec`; else giữ nguyên logic `PIPELINE_STAGES` cũ (backward-compat).
- [ ] 1.4 — Sửa `_get_ordered_agents` (dòng 273): nếu có `pipeline_spec`, sort theo thứ tự topo của spec thay vì `ROLE_ORDER`.
**1B. Approval gate node**
- [ ] 1.5 — Trong vòng lặp `run()` (dòng 111+): trước khi chạy stage có `approval_gate=True`, tạo bản ghi `Approval` (model `approvals`) + broadcast event `pipeline.approval_required`, rồi **poll** tới khi approved/rejected (giống `_run_single_agent` poll loop).
- [ ] 1.6 — Nếu rejected → set `pipeline_status = FAILED`, break, broadcast `pipeline.rejected`.
**1C. Backward-compat & test**
- [ ] 1.7 — Đảm bảo `PIPELINE_STAGES` & `ROLE_ORDER` vẫn tồn tại làm default (không xoá).
- [ ] 1.8 — Test cũ: chạy 1 brief với `pipeline_spec=None` → kết quả stages == kết quả trước refactor (snapshot `_group_into_stages`).
- [ ] 1.9 — Test mới: `pipeline_spec=[{role:ceo,depends_on:[]},{role:pm,depends_on:[ceo]},{role:coder,depends_on:[pm],parallel:2}]` → assert 3 stages, stage cuối có 2 coder song song.
- [ ] 1.10 — Test approval gate: stage có `approval_gate` → pipeline pause cho tới khi `Approval.status` đổi.
- [ ] 1.11 — `rtk pytest backend/tests/ -k orchestrator` xanh.
- [ ] 1.12 — **Verify gate:** 2 test snapshot (cũ) + 3 test mới pass. ✅
---
### Phase 2 — Company Blueprint Schema + Loader (~2.5h, rủi ro Low)
> Định nghĩa "blueprint" là cấu hình, không phải code.
**2A. Schema**
- [ ] 2.1 — Tạo `backend/schemas/blueprint.py`: Pydantic models `BlueprintRole`, `BlueprintPipelineNode`, `BlueprintCollection`, `CompanyBlueprint` (fields theo IDEA #24 §2).
- [ ] 2.2 — `BlueprintRole`: `{role, title, reports_to: Optional[str], capabilities: list[str], adapter_type, adapter_config: dict, permissions: dict, parallel: int=1, budget_monthly_cents: int=0}`.
- [ ] 2.3 — `CompanyBlueprint`: `{blueprint(id), industry, display_name, issue_prefix, brand: dict, org_chart: list[BlueprintRole], pipeline: list[BlueprintPipelineNode], nocobase_collections: list, default_skills: list, seed_goals: list}`.
- [ ] 2.4 — Validator: `reports_to` phải trỏ tới role tồn tại; `pipeline.depends_on` phải là role hợp lệ; DAG không cycle (reuse topo-sort của Phase 1).
**2B. Loader service**
- [ ] 2.5 — Tạo thư mục `backend/blueprints/` (chứa `*.yaml`).
- [ ] 2.6 — Tạo `backend/services/blueprint_service.py`: `load_blueprint(id) -> CompanyBlueprint` (đọc yaml, validate), `list_blueprints() -> list[summary]`, cache module-level (giống `marketplace._load_templates`).
- [ ] 2.7 — Thêm `pyyaml` vào deps nếu chưa có (`rtk grep -n "pyyaml\|yaml" backend/requirements*.txt pyproject.toml`).
**2C. Test**
- [ ] 2.8 — Test load 1 blueprint hợp lệ → object đúng field.
- [ ] 2.9 — Test blueprint có cycle trong pipeline → raise ValidationError.
- [ ] 2.10 — Test `reports_to` trỏ role không tồn tại → raise.
- [ ] 2.11 — **Verify gate:** loader + validator pass test. ✅
---
### Phase 3 — "Create Company from Blueprint" API (~3h, rủi ro Medium)
> 1 API call dựng cả công ty. Tái dùng logic seed agent (rút từ `pipelines.py:73-96`).
**3A. Refactor inline-deploy thành service**
- [ ] 3.1 — Rút khối tạo Agent inline ở `pipelines.py:81-96` thành hàm dùng chung `seed_agents_from_specs(db, company_id, specs)` trong `services/blueprint_service.py`.
- [ ] 3.2 — Sửa `pipelines.py` gọi hàm mới (giữ behavior cũ y hệt — chỉ refactor, không đổi kết quả).
- [ ] 3.3 — Thêm hỗ trợ `reports_to`: sau khi tạo agents, pass 2 (resolve `reports_to` từ role→agent_id, update FK).
**3B. Endpoint**
- [ ] 3.4 — Trong `backend/api/routes/companies.py`, thêm `POST /companies/from-blueprint` (body `{blueprint_id, name?, overrides?}`).
- [ ] 3.5 — Flow: `load_blueprint` → tạo `Company` (prefix/brand/budget từ blueprint) → `seed_agents_from_specs` (org_chart) → resolve `reports_to` → (tuỳ chọn) seed `goals` từ `seed_goals`.
- [ ] 3.6 — Trả về `{company_id, agents: [...], blueprint_id}`.
- [ ] 3.7 — Thêm `GET /blueprints` + `GET /blueprints/{id}` (list/detail) — có thể đặt ở route mới `backend/api/routes/blueprints.py`, đăng ký trong `server.py`/router include.
**3C. Pipeline nhận pipeline_spec từ blueprint**
- [ ] 3.8 — Sửa `PipelineRunRequest` (`pipelines.py:28`) thêm optional `blueprint_id`.
- [ ] 3.9 — Trong `run_pipeline`: nếu có `blueprint_id` → load blueprint → truyền `pipeline_spec=blueprint.pipeline` vào `ProjectOrchestrator(...)`.
**3D. Test**
- [ ] 3.10 — Test `from-blueprint` tạo đúng số agents + `reports_to` đúng cây.
- [ ] 3.11 — Test `pipelines.py` cũ vẫn pass (refactor 3.1-3.2 không phá behavior).
- [ ] 3.12 — Test end-to-end: from-blueprint → run_pipeline với `blueprint_id` → stages suy từ blueprint.
- [ ] 3.13 — **Verify gate:** tạo company từ blueprint + chạy pipeline xanh. ✅
---
### Phase 4 — NocoBase Per-Company Provisioning (~2.5h, rủi ro Medium)
> Bỏ hardcode creds; mỗi company tự cấu hình ERP; provision collections theo blueprint.
- [ ] 4.1 — Đọc `models/company_secrets.py` để biết shape lưu secret.
- [ ] 4.2 — Sửa `NocoBaseConnector.__init__` (`nocobase_connector.py:9`): nhận `base_url`, `email`, `password`/`token` từ tham số thay vì default hardcode (`:21`).
- [ ] 4.3 — Thêm `NocoBaseConnector.from_company(company_id)` classmethod: đọc `company_secrets` (key `nocobase_url`, `nocobase_token`...) → khởi tạo connector. Fallback env var nếu thiếu.
- [ ] 4.4 — Thêm method `ensure_collection(name, fields)` (tạo collection nếu chưa có) — dùng NocoBase collections API.
- [ ] 4.5 — Trong `from-blueprint` flow (Phase 3): sau khi tạo company, nếu blueprint có `nocobase_collections` → loop `ensure_collection`. Bọc try/except (provision lỗi không được làm fail tạo company — chỉ log + cảnh báo).
- [ ] 4.6 — Đưa creds Canifa hiện tại (`localhost:13001`/`admin@nocobase.com`) ra `.env`/`company_secrets`, không để trong code.
- [ ] 4.7 — Test: mock NocoBase API → `from_company` đọc đúng secret; `ensure_collection` gọi đúng endpoint.
- [ ] 4.8 — **Verify gate:** connector không còn hardcode; provision chạy best-effort. ✅
---
### Phase 5 — Industry Blueprint Pack (~2h, rủi ro Low — chỉ là data)
> Viết các file `backend/blueprints/*.yaml`.
- [ ] 5.1 — `fashion-retail.yaml` — **chính là Canifa** (ceo,pm → rd,designer,finance,hr → marketing,ecom,coder → qa → devops), prefix `CAN`, collections: Products/Outfits/Campaigns.
- [ ] 5.2 — `software-studio.yaml` — ceo→pm→architect→coder(parallel:3)→qa→devops(approval_gate), prefix `DEV`, collections: Repositories/Releases/Bugs.
- [ ] 5.3 — `ecommerce-brand.yaml` — ceo→pm→{merchandiser,marketing,finance}→ops→qa, prefix `ECM`, collections: Products/Orders/Campaigns.
- [ ] 5.4 — `marketing-agency.yaml` — ceo→strategist→{copywriter,designer}→media-buyer→qa(approval_gate trước publish), prefix `MKT`, collections: Clients/Campaigns/Assets.
- [ ] 5.5 — Mỗi blueprint: load qua `blueprint_service` không lỗi validate.
- [ ] 5.6 — Smoke: tạo company từ từng blueprint → đúng org-chart.
- [ ] 5.7 — **Verify gate:** 4 blueprint load + tạo company OK. ✅
---
### Phase 6 — De-Brand & Extract Canifa (~2h, rủi ro Low-Med)
> Canifa rời core, thành 1 blueprint + plugins.
- [ ] 6.1 — `README.md`: viết lại thành README của **platform generic** (Paperclip-style), chuyển nội dung Canifa-specific sang `backend/blueprints/fashion-retail.README.md`.
- [ ] 6.2 — `brand-spec.md`: tách brand Canifa thành asset của blueprint fashion-retail (không phải brand mặc định của platform).
- [ ] 6.3 — `backend/scratch/seed_db.py`: refactor `main()` để seed qua `create_company_from_blueprint("fashion-retail")` thay vì hardcode `company_123`/`Canifa Company`/`CAN`.
- [ ] 6.4 — Theo audit Phase 0: di chuyển feature thời trang (`outfit_pairing`, `ultra_desc`, `stylist`, `stock`) vào namespace plugin/skill (không nằm trong `services/` core). _Có thể tách doing riêng nếu lớn._
- [ ] 6.5 — `rtk grep -ri "canifa" backend/{models,services,api,tasks}/` → **0 hit** (trừ blueprint & plugin).
- [ ] 6.6 — **Verify gate:** grep clean + seed_db chạy ra company từ blueprint. ✅
---
### Phase 7 — Frontend Onboarding Wizard (~3h, rủi ro Low)
> UI "Tạo công ty mới từ blueprint".
- [ ] 7.1 — Audit `frontend/src/pages/` + `frontend/src/api/` để tìm chỗ list company / create company hiện tại.
- [ ] 7.2 — Thêm API client `frontend/src/api/blueprints.ts`: `listBlueprints()`, `createCompanyFromBlueprint(payload)`.
- [ ] 7.3 — Trang `frontend/src/pages/Onboarding/` (hoặc theo cấu trúc có sẵn): bước 1 chọn blueprint (card grid), bước 2 đặt tên + brand, bước 3 preview org-chart, bước 4 confirm → gọi API.
- [ ] 7.4 — Preview org-chart: tái dùng `org_chart_svg` (đã có `backend/api/routes/org_chart_svg.py`) để render cây từ blueprint.
- [ ] 7.5 — Sau tạo: redirect vào dashboard company mới.
- [ ] 7.6 — `rtk tsc` + `rtk vitest` xanh.
- [ ] 7.7 — **Verify gate:** click-through wizard tạo được company thật. ✅ (dùng skill `/verify` hoặc playwright)
---
### Phase 8 — Tests, Docs, Demo (~2h, rủi ro 0)
- [ ] 8.1 — Integration test `backend/tests/test_blueprint_e2e.py`: from-blueprint (software-studio) → run_pipeline → assert deliverables + report.
- [ ] 8.2 — Test multi-tenant isolation: 2 company từ 2 blueprint khác nhau không lẫn agents/workspace.
- [ ] 8.3 — Docs: `docs/blueprints.md` — cách viết 1 blueprint mới (schema + ví dụ + cách thêm collection).
- [ ] 8.4 — Demo script: tạo "software-studio" live, chạy 1 brief, show CEO report.
- [ ] 8.5 — Cập nhật `plan/done/` khi hoàn tất từng phase.
- [ ] 8.6 — **Verify gate cuối:** 4 success-criteria ở §Goal đều đạt. ✅
---
## 🔄 Sub-Doings
_Tạo khi cần (vd: "tách feature thời trang ra plugin" nếu Phase 6.4 lớn) → `plan/doings/sub_doings/`._
## ✅ Completion Gate
- [ ] Tất cả Phase 0–8 [x] | [ ] 4 success-criteria đạt | [ ] Test suite xanh | [ ] grep "canifa" core = 0 | [ ] Demo tạo company mới từ blueprint chạy được
---
_Started: 2026-06-01 | Updated: 2026-06-01_
# 💡 IDEA #24: Generic AI Agent Company Platform — "Bóc tách OS ra khỏi Canifa"
## Origin
User request (2026-06-01): "Canifa chỉ là một use case. Ưu tiên xây nền tảng **Full AI Agent Company** tổng quát,
cấu hình được cho bất kỳ doanh nghiệp nào (thời trang, e-commerce, software...). Cho tao ý tưởng + kế hoạch A→Z."
## TL;DR — Insight quan trọng nhất
**Codebase này ĐÃ gần như là một AI-Company OS generic rồi.** Sau khi đào codegraph + đọc core:
- 54 models, ~65 route files, full Hermes agent runtime đa provider (Anthropic/Bedrock/Gemini/Codex/Copilot).
- 5 trụ cột mà user mô tả đều **đã có hạ tầng** (xem mapping bên dưới).
"Canifa" thực chất chỉ là một lớp mỏng coupling:
1. **Branding** — `README.md`, `brand-spec.md`, `Company.brand_color`.
2. **Pipeline hardcode** — `PIPELINE_STAGES` trong `backend/services/project_orchestrator.py:28-34` cứng theo roles
kiểu thời trang/dev (`ceo,pm → rd,designer,finance,hr → marketing,ecom,coder → qa → devops`).
3. **Feature thời trang** — stylist, ultra product-desc, stock intelligence (đây là *plugin/skill*, KHÔNG phải core).
4. **Seed data** — `backend/scratch/seed_db.py`.
→ Vậy task KHÔNG phải "build lại từ đầu", mà là **(a) bóc tách generic core, (b) thêm tầng Company Blueprint
để instantiate org của bất kỳ ngành nào, (c) de-brand Canifa thành 1 blueprint mẫu.**
---
## 1. Bản đồ 5 trụ cột → code đã có (Gap Analysis)
| # | Trụ cột (user mô tả) | Đã có trong code | Gap cần làm |
|---|----------------------|------------------|-------------|
| 1 | **Issue-Driven Swarm** (ticket → trạng thái → cuộn xích sang issue kế tiếp) | `models/issues.py` (có `parent_id`, `origin_kind`, `monitor_*` wakeup fields, `execution_*`), `routes/issues.py` (21KB), `issues_checkout_wakeup.py`, `issue_recovery.py`, `pipelines.py`, `hermes_cli/kanban_swarm.py` | **Chain-reaction engine**: issue `completed` → tự sinh/đánh thức issue kế tiếp theo DAG. Cần verify logic auto-spawn có chưa, hay mới dừng ở manual + monitor. |
| 2 | **Shared Workspace + Sandbox** | `services/workspace_manager.py` (L1 isolation + `path_security`), `services/cubesandbox.py`, `models/execution_workspaces.py`, `models/project_workspaces.py`, `routes/execution_workspaces.py` | Hầu như xong. Chỉ cần chuẩn hoá "shared dir" per-project (hiện `workspaces/{company}/shared`) thành first-class artifact store. |
| 3 | **Swarm 3 cấp (CEO→Manager→Worker)** | `services/project_orchestrator.py` (pipeline stages song song), `agent/tools/delegate_tool.py` (delegation), `models/agents.py` có `reports_to` (hierarchy!) | **Bỏ hardcode `PIPELINE_STAGES`** → suy ra stages từ org-chart (`reports_to`) + dependency metadata của blueprint. |
| 4 | **Central ERP / NocoBase** | `services/nocobase_connector.py` (login/list/get/CRUD collections), `docker-compose.yml` | **Per-company config** (URL/token vào `company_secrets`), và **provision collections theo blueprint** (Products/Campaigns/Invoices...). Hiện hardcode `localhost:13001` + `admin@nocobase.com`. |
| 5 | **Human-in-the-loop Approval** | `models/approvals.py`, `routes/approvals.py`, `agent/acp_adapter/edit_approval.py`, `Company.require_board_approval_for_new_agents` | Hầu như xong. Cần expose "approval gate" như một **node cấu hình được** trong pipeline DAG (trước deploy/spend/gửi email). |
**Kết luận gap:** 4/5 trụ cột ~80-95% xong. Việc còn lại tập trung vào **#3 (pipeline động)** và một **tầng sản phẩm mới: Company Blueprint**.
---
## 2. Tầng còn thiếu: "Company Blueprint" (linh hồn của generic platform)
Hiện đã có **marketplace agent-templates** (`backend/data/marketplace_templates.json`, `routes/marketplace.py` `DeployTemplateRequest`)
và **company portability** (`routes/company_portability.py` export/import, `models/company_import_requests.py`).
Nhưng đó là template cho *từng agent*. Cái thiếu là template cho *cả công ty*.
**Company Blueprint** = một spec (JSON/YAML) mô tả trọn vẹn 1 doanh nghiệp:
```yaml
blueprint: software-studio # id duy nhất
industry: software
display_name: "AI Software Studio"
issue_prefix: DEV
brand: { color: "#4F46E5" }
org_chart: # → seed bảng agents (reports_to dựng hierarchy)
- role: ceo title: "CEO / Director" reports_to: null
- role: pm title: "Product Manager" reports_to: ceo
- role: architect title: "Tech Lead" reports_to: pm
- role: coder title: "Engineer" reports_to: architect parallel: 3
- role: qa title: "QA" reports_to: pm
- role: devops title: "DevOps" reports_to: pm
pipeline: # → thay PIPELINE_STAGES hardcode (DAG động)
- { role: ceo, depends_on: [] }
- { role: pm, depends_on: [ceo] }
- { role: architect, depends_on: [pm] }
- { role: coder, depends_on: [architect] }
- { role: qa, depends_on: [coder] }
- { role: devops, depends_on: [qa], approval_gate: true } # 🔒 human approve trước deploy
nocobase_collections: # → provision ERP theo ngành
- { name: Repositories, fields: [...] }
- { name: Releases, fields: [...] }
default_skills: [code_review, web_search, file_ops]
seed_goals:
- "Ship MVP v0.1"
```
**"Create Company from Blueprint"** = 1 API call → tự động:
1. Tạo row `companies` (prefix, brand, budget).
2. Seed `agents` theo `org_chart` (dựng `reports_to`).
3. Provision NocoBase collections theo `nocobase_collections`.
4. (tuỳ chọn) Seed `goals`/`issues` khởi đầu.
→ User "tuyển dụng" agents tuỳ ý, "liên kết DB chung", rồi để agents tự cuộn xích — đúng như tầm nhìn.
---
## 3. Kiến trúc generic platform (7 lớp)
```
L7 PRODUCT Company Blueprints · Marketplace · Onboarding Wizard · Dashboard (frontend/)
L6 INTEGRATION NocoBase ERP · gateway/platforms (messaging) · plugins · MCP
L5 GOVERNANCE Approvals · Budget policies · cost_events · activity_log · feedback
L4 EXECUTION Hermes runtime (multi-provider) · Workspaces/Sandbox · Environments
L3 ORCHESTRATION ProjectOrchestrator (DAG động) · delegate_tool (swarm) · routines/triggers · monitor-wakeup
L2 WORK Issues · Projects · Goals · labels/comments/attachments
L1 ORG Agents (reports_to hierarchy) · roles · capabilities · permissions
L0 TENANCY Company · memberships · secrets · budgets (multi-tenant isolation)
```
**Nguyên tắc thiết kế:**
- **Core = ngành-trung-lập.** Mọi thứ đặc thù ngành (fashion stylist, dev code-review) phải nằm ở **skills/plugins/blueprint**, không lọt vào L0–L5.
- **Blueprint là cấu hình, không phải code.** Thêm ngành mới = thêm 1 file blueprint, không sửa orchestrator.
- **Canifa trở thành `blueprints/fashion-retail.yaml`** — 1 instance mẫu, không còn là "the product".
---
## 4. Vì sao cách này đúng (trade-offs đã cân nhắc)
- ✅ **Tận dụng 80-90% đã build** — không đập đi xây lại, rủi ro thấp, ship nhanh.
- ✅ **Data model đã sẵn sàng generic** — `Agent.reports_to`, `Issue.parent_id/monitor_*`, `Company.issue_prefix` → không cần migration lớn.
- ✅ **Có sẵn đường ray sản phẩm** — marketplace + portability + import_requests chỉ cần nâng cấp từ agent-level lên company-level.
- ⚠️ **Trade-off:** phải refactor `project_orchestrator.py` (bỏ hardcode) — đây là điểm rủi ro chính, cần test kỹ (Phase 1).
- ⚠️ **Chưa chắc chain-reaction auto-spawn đã có** — cần verify ở Phase 0 trước khi cam kết Phase 1.
---
## 5. Hướng mở rộng (Expansion) — sau khi có generic core
Khi nền tảng đã generic + blueprint hoạt động, các hướng mở rộng theo độ ưu tiên:
| # | Hướng | Mô tả | Dựa trên cái đã có |
|---|-------|-------|--------------------|
| E1 | **Blueprint Marketplace** | Cộng đồng publish/clone blueprint ngành (như template store). | `routes/marketplace.py`, `company_portability.py` |
| E2 | **Multi-tenant SaaS** | Mỗi khách 1 workspace cô lập, billing theo `cost_events`/`budget_policies`. | `models/cost_events.py`, `budget_policies.py`, `company_memberships.py` |
| E3 | **Chain-reaction Rules Engine** | Issue `done` → tự sinh/đánh thức issue kế theo rule (event-driven swarm thật sự). | `Issue.monitor_*`, `issues_checkout_wakeup.py`, `routines/triggers` |
| E4 | **Agent-to-Agent Protocol** | Chuẩn hoá giao tiếp liên-agent (đã có ACP adapter) → liên-company. | `agent/acp_adapter/`, `delegate_tool.py` |
| E5 | **Connector Hub** | Ngoài NocoBase: Postgres, Sheets, Slack, Jira... mỗi connector là plugin. | `services/nocobase_connector.py` pattern, `gateway/platforms/` |
| E6 | **Skill/Capability Store** | Gắn skill cho agent theo nhu cầu ngành (đã có `company_skills`). | `models/company_skills.py`, `agent/skills/` |
| E7 | **Observability & Eval** | Dashboard hiệu năng agent, auto-prompt-improvement (đã có idea #17). | `services/activity_logger.py`, `feedback_*` |
## 6. Hướng phát triển (Development direction) — triết lý lâu dài
- **Core ngành-trung-lập, đặc thù nằm ở rìa.** Mọi thứ "biết về fashion/dev/marketing" phải sống trong
`blueprints/` + `plugins/` + `skills/`. Core (L0–L5) tuyệt đối không hardcode ngành.
- **Cấu hình > code.** Thêm năng lực mới ưu tiên qua blueprint/plugin/skill thay vì sửa orchestrator.
- **Backward-compat là luật.** Canifa đang chạy production-ish → mọi refactor phải có fallback + test snapshot.
- **Mỗi tầng thay được độc lập.** Đổi LLM provider, đổi ERP, đổi sandbox — không kéo theo tầng khác (nhờ adapter pattern đã có sẵn trong Hermes runtime).
- **"Paperclip core" là thượng nguồn.** Giữ khả năng rebase/đồng bộ với `outsource/paperclip/` — tránh fork phân kỳ.
## 7. North-star
> Một người không-kỹ-thuật mở UI → chọn "Tôi muốn lập một công ty phần mềm" →
> hệ thống seed CEO/PM/Coder/QA, nối DB chung, agents tự cuộn xích làm việc, người chỉ Approve ở các cổng nhạy cảm.
> **Canifa chỉ là blueprint đầu tiên trong số rất nhiều.**
## Type
Platform Architecture / Generalization (Pipeline A) — chi tiết thực thi (A→Z, file-by-file, ~70 checkbox)
xem `plan/doings/03_platform_generalization_roadmap.md`.
# 🔍 Audit & De-Canifa Inventory (Phase 0)
This document contains a comprehensive audit of all branding, coupling, hardcoded configuration, and fashion-vertical specific logic across the codebase, mapping them to specific roadmap phases for clean, generic refactoring.
---
## 1. Canifa Brand & Platform Coupling (Phase 6)
The following references to "Canifa" exist in the core backend code and must be de-branded, genericized, or extracted into the `fashion-retail` blueprint/plugin pack in **Phase 6**:
| File Path | Line(s) | Description / Type of Coupling |
|---|---|---|
| [backend/agent/tools/mcp_client.py](file:///d:/a/ai_canifa_company/backend/agent/tools/mcp_client.py) | 134 | Hardcoded agent client name: `"canifa-company-agent-client"` |
| [backend/api/routes/agents.py](file:///d:/a/ai_canifa_company/backend/api/routes/agents.py) | 259 | Hardcoded HTML string `<title>CANIFA Premium</title>` |
| [backend/api/routes/run_logs.py](file:///d:/a/ai_canifa_company/backend/api/routes/run_logs.py) | 438, 551-553, 571, 628 | Hardcoded log descriptions and CEO report templates mentioning "Canifa Premium Landing Page" and "Canifa Magento 2 server sync" |
| [backend/auth/\_\_init\_\_.py](file:///d:/a/ai_canifa_company/backend/auth/__init__.py) | 11 | Default auth secret key `canifa-dashboard-secret-2024-change-me` |
| [backend/auth/models.py](file:///d:/a/ai_canifa_company/backend/auth/models.py) | 10 | Hardcoded schema name `dashboard_canifa` |
| [backend/common/cache.py](file:///d:/a/ai_canifa_company/backend/common/cache.py) | 27 | Docstring reference: `"Hybrid Cache Client for Canifa Chatbot"` |
| [backend/common/codex_auth.py](file:///d:/a/ai_canifa_company/backend/common/codex_auth.py) | 3 | Docstring reference: `"Codex OAuth Token Manager (Simplified for Canifa AI Platform)"` |
---
## 2. Hardcoded Configuration & Credentials (Phase 4)
These hardcoded settings and environment fallbacks must be migrated to tenant-level configuration or environment-driven variables in **Phase 4**:
| Code/Pattern | File Path | Line(s) | Impact / Cleanup Action |
|---|---|---|---|
| `"company_123"` | `backend/tests/test_agent_flow.py` & `backend/scratch/*.py` | Multiple | Keep in test suite (mocking), but remove from database initialization seed scripts in `seed_db.py` (replace with dynamic seed from blueprint). |
| `"PAP"` | [backend/models/companies.py](file:///d:/a/ai_canifa_company/backend/models/companies.py) | 23 | Default issue prefix. Should be read dynamically from the database row (which is seeded by the company blueprint). |
| `"http://localhost:13001"` | [backend/services/nocobase_connector.py](file:///d:/a/ai_canifa_company/backend/services/nocobase_connector.py) | 9, 12 | Default NocoBase host URL. Must be fetched dynamically from `CompanySecret` or company-scoped database configs. |
| `"admin@nocobase.com"` / `"admin123"` | [backend/services/nocobase_connector.py](file:///d:/a/ai_canifa_company/backend/services/nocobase_connector.py) | 21 | Default NocoBase administrator credentials. Must be loaded from secrets. |
| `"admin@paperclip.ai"` | `backend/scratch/*.py` | Multiple | Default admin email. Convert to a dynamic config parameter. |
---
## 3. Hardcoded Swarm Role Pipeline (Phase 1)
Swarm orchestration stages are currently hardcoded in [backend/services/project_orchestrator.py](file:///d:/a/ai_canifa_company/backend/services/project_orchestrator.py):
* **PIPELINE_STAGES** (Lines 28-34):
```python
PIPELINE_STAGES = [
["ceo", "pm"], # Stage 1: CEO strategy + PM spec
["rd", "designer", "finance", "hr"], # Stage 2: Independent departments (parallel)
["marketing", "ecom", "coder"], # Stage 3: Depends on design/spec output
["qa"], # Stage 4: QA reviews everything
["devops"], # Stage 5: DevOps deploys (optional)
]
```
* **ROLE_ORDER** (Line 37): Flattened version of the above.
**Phase 1 Action**: Refactor `ProjectOrchestrator` to accept a dynamic topological sorting of roles (pipeline DAG spec) loaded from the `CompanyBlueprint`. If none is specified, fall back to the default `PIPELINE_STAGES` list to maintain backward compatibility.
---
## 4. Chain-Reaction Issue Flow Verification (Phase 0/1)
We investigated the issue completion triggers in `backend/api/routes/issues.py` and `backend/tasks/agent_tasks.py`:
* **Current state**: There is **no automated chain-reaction issue auto-spawn logic** running inside the backend core when an issue transitions to `"completed"` or `"resolved"`.
* **Trigger structure**: Waking up agent checkout runs is handled via the explicit POST endpoint `/api/issues-checkout-wakeup` (in `backend/api/routes/issues_checkout_wakeup.py`) which inserts a queued `HeartbeatRun` record.
* **Conclusion**: Since there is no existing chain-reaction logic to refactor, we do not need to worry about breaking implicit triggers. Building a true auto-spawning rule engine is scheduled as an extension task (E3) in the roadmap rather than a core refactoring item.
---
## 5. Fashion-Vertical Specific Features (Phase 6)
The following modules contain business logic coupled directly to fashion retail, styling, and product description generation. These should be isolated as plugins or blueprints in **Phase 6**:
1. [backend/common/canifa_api.py](file:///d:/a/ai_canifa_company/backend/common/canifa_api.py): Magento client integration with Canifa customer and authentication APIs.
2. [backend/common/content_templates.py](file:///d:/a/ai_canifa_company/backend/common/content_templates.py): Custom social/marketing templates in Vietnamese specifically customized for Canifa clothing, outfit styling, and campaigns.
3. [backend/common/outfit_db.py](file:///d:/a/ai_canifa_company/backend/common/outfit_db.py): Helper classes and DB wrappers for outfit compositions and "stylist pins".
4. [backend/common/ultra_desc_db.py](file:///d:/a/ai_canifa_company/backend/common/ultra_desc_db.py): Special generator and database connector for ultra-long fashion marketing descriptions.
5. [backend/common/social/approval_gate.py](file:///d:/a/ai_canifa_company/backend/common/social/approval_gate.py): References to the AI stylist engine generating fashion suggestions.
---
## 6. Blueprint-Anchor Schema Mapping (Phase 2 & 3)
The following existing components provide structures that can be utilized to implement company-level blueprints:
* **Marketplace Templates**: [backend/data/marketplace_templates.json](file:///d:/a/ai_canifa_company/backend/data/marketplace_templates.json) defines an array of deployment templates (e.g., `landing-page-builder`, `mobile-app-team`) containing fields like `name`, `description`, and `agents` (with `role`, `name`, `skills`).
* **Deploy Logic**: [backend/api/routes/pipelines.py](file:///d:/a/ai_canifa_company/backend/api/routes/pipelines.py) (Lines 73-96) shows how agents are instantiated from templates.
* **Portability Exports**: [backend/api/routes/company_portability.py](file:///d:/a/ai_canifa_company/backend/api/routes/company_portability.py) defines how company data (agents, pipelines, secrets) is serialized/deserialized, serving as a base model for importing blueprints.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment