# 🚀 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).
-[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.
> 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.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.
### 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).
-[] 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.
> 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.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)
-[] 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._
| 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. |
| 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)
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 |
| `"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):
["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.
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.
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.