Công Ty 1 Người — 9 AI Agent (v5 — Full Tools + Embedded ECC Skills + Skill Organization)
Kiến trúc (v5.1 — Full Real Tools + English Channel + Media nâng cấp)
Web Dashboard (uvicorn :8137) ← mobile-first, 5 tabs SPA (v3, 19/07/2026) + click-to-detail modals + web chat CEO + auto backup D:\Backups\
│
▼
CEO (trợ lý LLM) → intake → plan → HỎI chủ tịch → dispatch
│
├─ 💻 Dev (code thật: tạo file + terminal + TDD)
├─ 🎨 Media (image gen: FAL cho GMSP / Pollinations cho Airfare Decoded + HyperFrames CLI + Edge TTS Anh/Việt auto-detect)
├─ 🔍 Research (web_search Hermes + multi-query niche)
├─ 🛒 Sales (DuckDuckGo lead search)
├─ 📢 Marketing(brand-voice + content-engine ECC)
├─ ⚙️ Ops (PowerShell real healthcheck)
├─ 🎫 Support (SQLite ticket + knowledge-ops)
├─ 📊 Analytics(SQL query + CSV export)
└─ 🤖 Auto-Learn (self-learning engine)
Web Dashboard (uvicorn :8137) ← mobile-first, 7 tabs (Chat/Health/Kanban/Tickets/Outbox/Agents/Văn Phòng)
## Cronjob tự động (Hermes scheduler) — 7 jobs (updated 18/07/2026)
| Cronjob | Schedule | Script | Chức năng |
|---------|----------|--------|-----------|
| Auto Dispatch | every 30m | `cron_dispatch.py` | Quét Kanban, dispatch task `ready` → agents, move card qua `running` → `review` / `blocked` |
| Telegram Delivery | every 15m | `cron_telegram.py` | Quét `outbox.json`, gửi pending items lên Telegram API |
| Morning Briefing | 0 8 * * * | `cron_morning.py` | CEO tóm tắt sáng: taskboard + 5 dự án — ghi outbox → cron Telegram gửi |
| Afternoon Briefing | 0 17 * * * | `cron_afternoon.py` | CEO tổng kết chiều: xong/dang dở/checklist — ghi outbox → cron Telegram gửi |
| Skill Sync | 0 9 * * * | `sync-skills.sh` | Push local skills → GitHub (mirror) |
| Auto Learn | */30 * * * * | `auto-learn.py` | Self-learning engine (correction/error/repetition/workflow patterns) |
| Daily Backup | 0 3 * * * | `backup.py` (no_agent) | Sao lưu DB + config + code → D:\\Backups\\TANO-AGENCY\\, giữ 7 ngày |
Scripts đặt trong `~/.hermes/scripts/` (Hermes yêu cầu path relative).
Telegram delivery cần `TELEGRAM_BOT_TOKEN` + `TELEGRAM_CHAT_ID` trong `.env` của `agent-core/.env`.
**Cron path pitfall:** không dùng `Path(__file__).parent` trong Hermes cron context. Fix:
```python
AGENT_DIR = Path.home() / "AppData" / "Local" / "hermes" / "scripts"
AGENT_CORE = Path("D:/MMO Du an/TANO-AGENCY/PLATFORM/agent-core")
sys.path.insert(0, str(AGENT_CORE))
Note: Các script báo cáo ghi vào ~/.hermes/outbox/ → cron Telegram mỗi 15p gửi lên API — không gọi Telegram API trực tiếp từ script (ko có Hermes tool context).
Não
- LLM: DeepSeek (chính) → OpenRouter → Gemini (fallback)
- Tay chân:
real_adapters.py— tự động inject khi gọiget_brain() - Memory: SQLite (
core/memory.py) — tasks, evidence_cache, domain_scores, lessons, kv_store - Harness:
core/harness.py— budget, retry, human gate
Thư mục
TANO-AGENCY/
PLATFORM/agent-core/
run.py # CLI smoke test: --stub / --real
main.py # Telegram command center
real_adapters.py # Tool thật cho 8 agent ($0)
.env # DeepSeek + OpenRouter + Gemini keys
core/
brain.py # AgentBrain pipeline
harness.py # Budget + gate
memory.py # SQLite memory
llm.py # Multi-provider router
validator.py # Rating system + anti-hallucination
ratelimit.py # TokenBucket + backoff
agents/
__init__.py # get_brain() auto-injects real adapters
ceo/ # Dispatch agent
dev/ # Code + infra agent
sales/ # Lead search
marketing/ # Content + publish
operations/ # Takeover + incident
support/ # Reply + ticket
analytics/ # Report
media/ # Video + design
research/ # Research Officer (agent thứ 9, dùng ddgs library)
Cronjob tự động (Hermes scheduler)
| Cronjob | Schedule | Chức năng |
|---|---|---|
| Auto Dispatch | every 30m | Quét Kanban, dispatch task ready → agents, move card qua running → review / blocked |
| Telegram Delivery | every 15m | Quét outbox.json, gửi pending items lên Telegram API |
| Morning Briefing | 0 8 * * * | CEO tóm tắt sáng: taskboard + 4 dự án |
| Afternoon Briefing | 0 17 * * * | CEO tổng kết chiều: xong/dang dở/checklist |
| Skill Sync | 0 9 * * * | Push local skills → GitHub (mirror) |
| Auto Learn | */30 * * * * | Self-learning engine (correction/error/repetition/workflow patterns) |
Scripts đặt trong ~/.hermes/scripts/. Telegram delivery cần TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID trong .env.
Cron path pitfall: không dùng Path(__file__).parent trong Hermes cron. Fix hardcode path D:/MMO Du an/TANO-AGENCY/PLATFORM/agent-core.
Note: Các script báo cáo sáng/chiều ghi vào ~/.hermes/outbox/ → cron Telegram mỗi 15p gửi lên API. Script no_agent=True nên ko thể gọi hermes_tools.send_message() — phải dùng outbox 2-step.
Lưu ý: TELEGRAM_CHAT_ID trong .env phải được set, nếu không cron Telegram bỏ qua. Giá trị: 762010475 (chat ID của user từ @userinfobot).
Disk C constraint
Ổ C rất hạn chế (171GB, thường 0-14GB free). Luôn ưu tiên cài đặt mọi thứ sang ổ D:
- Hermes venv: D:\ (đã có)
- Pip cache: set
pip config set global.cache-dir D:/pip-cache - TEMP: set env
TEMP=D:\TempvàTMP=D:\Temp - Các tools cache (.gemini, .cursor, .vscode): dọn định kỳ
- Docker images: chưa dùng — nếu dùng thì cài trên D
Biggest C: cleaners (19/07/2026):
.gemini— 6.8GB (xoá an toàn).cursorCache — 2.1GB (xoá an toàn).vscodeextensions — 1.9GB (cài lại được).cache— 1GB (cache pip/hermes/uv)AppData\Local\Temp— 2.6GB
Clean script mẫu: scripts/deep_clean.ps1 — xoá .gemini, .cursor cache, .vscode extensions, npm cache, TEMP
| ECC Skill | Agent | Phương pháp | File | Chi tiết |
|---|---|---|---|---|
| brand-voice | Marketing | Prompt embedding | agents/marketing/adapters.py |
Brand color #0D0D12+#FFD700+#8B0000, tone gai góc, formula truth→hidden→urgency |
| content-engine | Marketing | Code embedding | real_adapters.py |
1 source → multi-platform pipeline + quality gate |
| knowledge-ops | Support, Analytics | Code embedding | real_adapters.py |
6-layer: GitHub→Memory→MCP→KB→External→Archive |
| verification-loop | Dev | Code embedding | real_adapters.py |
6 phase: build→type→lint→test→security→diff |
| team-orchestration | CEO | Code embedding | real_adapters.py |
SQLite Kanban: backlog→ready→running→review→blocked→merged→archived |
| python-testing | Dev | Prompt embedding | agents/dev/adapters.py |
TDD: test trước code, mock external deps, edge cases |
| security-review | Dev | Prompt embedding + Code | agents/dev/adapters.py |
Checklist: secrets exposure, input validation, path traversal, SQL injection, resource exhaustion. Nhúng vào 3-layer guard (budget → file I/O → terminal). |
| fal-ai-media | Media | Prompt embedding | agents/media/adapters.py |
Image prompt tiếng Anh chuẩn FAL format |
| git-workflow | Dev | Prompt embedding | agents/dev/adapters.py |
Conventional commits, branch naming feat/fix |
Phương pháp:
- Prompt embedding: skill pattern/directive → nhúng vào
llm.make_analyzer(system_prompt=...)— không cần code mới - Code embedding: skill có workflow actionable → viết function Python trong
real_adapters.py
Skill đã review không nhúng: ecc-autonomous-loops (đã có brain.run + budget), ecc-token-budget-advisor (cho Hermes), ecc-deep-research (cần Exa/Firecrawl trả phí), ecc-lead-intelligence (cần X API), ecc-social-publisher (cần SocialClaw).
Chi tiết: references/ecc-skill-embedding-map.md
Skill Organization (tách Hermes generic vs dự án)
Cấu trúc thư mục skills sau khi dọn dẹp (Jul 2026):
skills/
├── 📁 tano/ ← 140 skills dự án của user
│ ├── company-one-person/ (skill này)
│ ├── tuvi/ (Tử Vi)
│ ├── hyperframes/ (Content Pipeline)
│ ├── gmsp-video-production/
│ └── ... (HyperFrames, kế toán, marketing, coding rules, v.v.)
├── 📁 ecc-*/ ← 270 ECC generic skills (Hermes ecosystem)
│ ├── ecc-brand-voice/
│ ├── ecc-python-testing/
│ ├── ecc-fal-ai-media/
│ └── ...
├── 📁 agent-skills/ (generic)
├── 📁 analytics/ (generic)
└── ...
Phân loại: skills dự án = có frontmatter + nội dung liên quan tới business của user.
ECC = skills từ kho cộng đồng, giữ nguyên tên, ko move vào tano/.
Nguyên tắc:
- Skill nào user từng dùng hoặc do Hermes sinh ra trong quá trình build dự án →
tano/ - Skill nào có tiền tố
ecc-hoặc generic pattern → giữ nguyên root - Khi dùng: load bằng
skill_view("tano/<tên>")hoặcskill_view("ecc-<tên>")
- Load skill —
skill_view("ecc-<tên>")đọc SKILL.md - Phân loại:
- Skill pattern/directive (vd: brand-voice, content-engine) → viết hàm mới trong
real_adapters.py - Skill code/infra (vd: mcp-server-patterns, dashboard-builder) → cài CLI/MCP + config
- Skill pattern/directive (vd: brand-voice, content-engine) → viết hàm mới trong
- Map pattern → code:
When to Activate→ xác định agent nào cần- Hard bans / quality gates → code vào hàm (regex check, rule list)
- Workflow steps → không copy verbatim, tóm thành logic function
- Output contract → dùng làm schema response
- Inject vào registry —
build_real_registry()thêm {tên: callable} - Smoke test —
python run.py --real(phải 13/13 pass) - Update skill — lưu skill reference vào SKILL.md
Pitfalls khi cắm skill
| Vấn đề | Giải pháp |
|---|---|
| Skill từ kho là markdown, không phải code | Phải tự viết function mapping. Không copy-paste markdown vào code. |
| Skill tưởng free nhưng cần API key trả phí | Kiểm tra required_environment_variables + required_credentials trước. Exa/Firecrawl/SocialClaw đều trả tiền — tránh. |
| Skill có references/scripts nhưng không kèm file | skill_view kiểm tra linked_files — nếu null thì skill chỉ có pattern, không có code sẵn. |
| Nhiều skill overlap | brand-voice x content-engine (brand-voice là canonical voice layer). knowledge-ops x kb_search (knowledge-ops thay thế kb_search cũ). |
| Agent không nhận ra adapter mới | Phải thêm tên adapter vào SEARCH_LIKE set trong core/brain.py, nếu không brain sẽ bỏ qua COLLECT phase. |
_agent_kanban cần DB riêng |
Tạo _ensure_kanban_db() tách biệt khỏi AgentMemory — không lẫn với memory của agent khác. |
_kb_ingest có thể tạo duplicate |
Luôn check dedup trước khi store — dùng AgentMemory.retrieve_lessons() so sánh prefix 100 chars. |
| Adapter registry ≠ spec task_types | Adding reg.register("initiative", ...) is NOT enough. Must also add the task type to SPEC.task_types in spec.py — otherwise brain.run('initiative', ...) returns "không hỗ trợ task type". The "analyze" field in spec must match the registry name. |
Agent Kanban commands
from real_adapters import _agent_kanban
# Thêm card
_agent_kanban(task, action='add', title='Build feature X', owner='dev', state='ready')
# Move card
_agent_kanban(task, card_id='agent-card-abc123', action='move', to_state='running')
# Ghi handoff note
_agent_kanban(task, card_id='agent-card-abc123', action='handoff', note='Tests pass, ready for review')
# Xem board (mặc định)
_agent_kanban(task)
Columns: backlog → ready → running → review → blocked → merged → archived
Mỗi card có: id, title, owner, state, branch, worktree, acceptance, merge_gate, handoff, evidence.
Knowledge Ops layers
| Layer | Tên | Implementation | Use case |
|---|---|---|---|
| 1 | GitHub/Linear | (manual) | Active execution truth |
| 2 | AgentMemory | core/memory.py lessons + kv_store |
Cross-session quick access ✅ |
| 3 | MCP Memory Graph | MCP server entities/relations | Semantic search |
| 4 | KB repo | File search .md/.txt/.json |
Durable document store ✅ |
| 5 | External DB | Supabase/PostgreSQL | Large doc search |
| 6 | Local archive | data/ folder |
Human-facing notes ✅ |
Dùng _kb_ingest() để auto classify/dedup/store. Dùng _kb_search_v2() để multi-layer retrieval.
CEO v2 — Trợ lý thông minh (LLM-powered)
CEO được nâng cấp từ rule-based lên LLM-powered. 6 adapter chính:
| Adapter | LLM | Fallback | Mô tả |
|---|---|---|---|
clarifier |
DeepSeek | _fallback_intake() |
Phân tích mệnh lệnh: mục tiêu, phạm vi, phòng ban, deadline, câu hỏi làm rõ |
planner |
DeepSeek | _fallback_planner() |
Phân rã nhiệm vụ — output tự nhiên, KO format bảng corporate (đã bỏ JSON parsing tháng 7/2026). Nói như trò chuyện, không icon |
reporter |
DeepSeek (summarize) | _ceo_reporter() |
Executive brief từ taskboard: tiến độ, điểm nổi bật, vướng mắc, đề xuất |
dispatch |
— (code) | — | Ghi taskboard → auto gọi brain.run() từng phòng ban (ThreadPoolExecutor + 90s timeout) |
taskboard |
— (code) | — | SQLite kv_store 'assignments' — mission group, trạng thái, kết quả |
initiative |
DeepSeek | _ceo_initiative() |
Chủ động gợi ý dự án đang làm dở + kickstart |
Không cần format cứng. Nói tiếng Việt bất kỳ:
- "ra mắt dịch vụ Fast Track tháng sau"
- "kiểm tra sức khoẻ hệ thống"
- "viết content về AI du lịch"
Luồng chat — CEO xác nhận trước, dispatch sau:
User: "làm landing page Fast Track"
→ CEO intake: LLM phân tích → JSON
→ CEO delegate: LLM lập kế hoạch → JSON bảng phân công
→ CEO track: đọc taskboard cũ
→ CEO DỪNG — HỎI Chủ tịch xác nhận
(KHÔNG dispatch tự động)
User: "ok" / "làm đi" / bấm nút [✅ Duyệt — Triển khai]
→ CEO dispatch: ghi taskboard + gọi brain.run() cho từng phòng ban
Confirm keywords (dashboard detect): ok, làm, làm đi, triển khai, đồng ý, ừ, go, duyệt, chạy, dispatch
QUAN TRỌNG: CEO KHÔNG được tự động dispatch. Luôn trình plan → chờ confirm → mới chạy.
Code confirm logic ở web/dashboard.py — endpoint /api/chat kiểm tra message có match confirm keywords không, dispatch_results chỉ populate khi is_confirm=True. Frontend hiển thị nút "✅ Duyệt — Triển khai" khi data.needs_confirm === true.
File: agents/ceo/adapters.py (21KB)
File: web/dashboard.py — /api/chat endpoint chứa confirm logic
Web Dashboard (mobile-first) — v5 Single-Screen SAAS (19/07/2026, redesign)
IMPORTANT: The dashboard was COMPLETELY REDESIGNED on 19/07/2026. No more tabs. Single-screen layout.
Single-screen architecture (v5, 19/07/2026)
┌───────────────────────────────────┐
│ TANO.AGENCY 📁5/5 📋3/10 🟢OK │ Header: tình hình chung
├────┬──────────────────────────────┤
│ │ 📋 Công việc │
│ 👔 │ ┌──────────────────────────┐ │
│ 💻 │ │ 💻 Landing Page GMSP │ │ ← Bấm → modal: chi tiết + chat inline
│ 🎯 │ │ Developer · 2h 🟢 │ │
│ 📢 │ ├──────────────────────────┤ │
│ ⚙️ │ │ 🎯 KPI tháng 7 │ │
│ 🎧 │ │ Sales · 1ng 🟡 │ │
│ 📊 │ └──────────────────────────┘ │
│ 🎨 │ │
│ 🔬 │ ┌──────────────────────────┐ │
│ 🏠 │ │ 💬 Chat CEO │ │ ← Chat bar cố định (luôn visible)
│ │ └──────────────────────────┘ │
│ │ [📋] [📊] [🏛️] │ ← Quick tools (Giao việc/Báo cáo/Họp)
└────┴──────────────────────────────┘
| Component | What | API |
|---|---|---|
| Header | Project count, task count, health dot | /api/projects, /api/kanban |
| Sidebar | 9 agents + "Tất cả" — click to filter tasks | Filter client-side |
| Feed | Task cards sorted by priority (running > ready > review > blocked > backlog > done). Each card shows: agent icon + title + owner + time ago + state badge. Click → modal. | /api/kanban |
| Chat bar | Fixed at bottom. Enter to send. CEO responds via /api/chat with project context. | POST /api/chat |
| Quick tools | 📋 Giao việc mới (modal: title + phòng ban + priority) | POST /api/kanban/add |
| 📊 Báo cáo nhanh (system health + task stats + projects) | /api/health, /api/kanban_summary | |
| 🏛️ Họp (shortcut: gửi "/ceo họp khẩn") | POST /api/chat |
Task Modal (click any task card)
- Tiêu đề + agent icon + màu sắc
- State dropdown — chọn trạng thái mới + nút cập nhật
- Thông tin: created_at, current state
- Nút 🤝 Giao CEO — gửi lệnh qua API, hiện toast, ko chuyển tab
- Nút 💬 Chỉ đạo — chuyển tab Chat + điền sẵn
/agent_name - 💬 Chat CEO inline — ô chat ngay trong modal, session_id riêng (
task_<id>), CEO trả lời ngay trong modal
Giao việc Modal (📋 quick tool)
- Tiêu đề input
- Phòng ban dropdown (9 agents)
- Ưu tiên: "Làm ngay" (ready) / "Để sau" (backlog)
- Nút 🚀 Giao việc → POST /api/kanban/add
Báo cáo Modal (📊 quick tool)
- Hệ thống: CPU, RAM, Ổ C, Ổ D
- Công việc: tổng/đang chạy/sẵn sàng/bị chặn
- Dự án: 5 items với ✅/❌
- Nút "Yêu cầu CEO báo cáo" → gửi chat
/ceo báo cáo tổng quan
Design tokens (light theme — user preference, CONFIRMED 19/07/2026)
:root {
--bg: #F5F5F7; /* xám nhạt */
--card: #FFFFFF; /* trắng */
--card-hover: #EBEBF0;
--border: #D4D4D8;
--text: #1A1A2E; /* đen chì */
--text-muted: #6B6B80;
--gold: #B8860B; /* vàng đậm */
--green: #16A34A;
--red: #DC2626;
}
⚠️ USER PREFERENCE — LIGHT THEME ONLY. User explicitly rejected dark theme. Never suggest or offer dark theme. Default confirmed 19/07/2026:
:root {
--bg: #F5F5F7; /* xám nhạt */
--card: #FFFFFF; /* trắng */
--card-hover: #EBEBF0;
--border: #D4D4D8;
--text: #1A1A2E; /* đen chì */
--text-muted: #6B6B80;
--gold: #B8860B; /* VÀNG ĐẬM — not #FFD700, not #D4A843 */
--green: #16A34A;
--red: #DC2626;
}
Sidebar (left) — confirmed design 19/07/2026
- 180px wide on desktop, 50px on mobile (<480px)
- Section titles visible on desktop: "Phòng ban" / "Chung" / "Dự án" (hidden on mobile)
- Each agent: icon + full name (e.g. 👔 CEO, 💻 Developer) — NOT just icon
- "Tất cả" button under "Chung" — gold bg when active
- "Dự án" section — auto-populated from
/api/projectsviaupdateProjectsSidebar(). Each project button: icon + name + green/red dot (active/inactive). Click →openProjectModal(name)— shows facts, decisions, inline chat. - Mobile (<480px): collapses to 50px, labels and section titles hidden
Key interactive patterns
- 30s auto-refresh —
setInterval(loadAll, 30000) - Toast notifications — position fixed bottom-100px, fade out 3.5s
- Modal scrollable —
.modal { max-height: 85vh; overflow-y: auto; animation: slideUp .25s } - Enter to send — chat input + modal chat both support Enter key
- Inline modal chat — separate session_id per modal instance, CEO remembers context within that modal
API changes from v4 → v5
New endpoints added:
GET /api/memory/facts— facts by project/category/searchPOST /api/memory/facts— add a factGET /api/memory/decisions— decisions by projectPOST /api/memory/decisions— add a decisionGET /api/memory/projects— list projects with memoryGET /api/preferences— all user preferencesPOST /api/preferences— set a preferenceGET /api/skills— all skillsPOST /api/skills— add a skill
Port note
Dashboard runs on port 8138 (8137 left in TIME_WAIT by stale process on 19/07/2026). Stick with 8138 — 8137 may become available but switching back is low priority. User accesses via http://localhost:8138.
def run():
port = 8138 # was 8137, changed due to persistent TIME_WAIT
uvicorn.run(app, host="0.0.0.0", port=port)
Agent profile modal — 5 MUST sections:
- 👤 Tôi là ai — Vietnamese introduction
- 🎯 Nhiệm vụ của tôi — mission statement
- 🛠️ Tôi có gì — tools as tag chips + skills
- 📋 Tôi đang làm gì — live tasks from /api/kanban filtered by owner
- 💬 Chat trực tiếp — button switches to chat tab and pre-fills "/agent_name "
Update 19/07/2026 — Mini chat inside modals. User hated being kicked to chat tab. Now each task and project modal has an inline chat box at the bottom with its own session_id (modal_<timestamp>). "Giao CEO" button calls /api/chat directly via fetch + shows a toast notification — doesn't switch tabs. "Chỉ đạo trực tiếp" still navigates to chat tab with pre-filled /agent .
- Modal chat:
#modal-chat-input+#modal-chat-msgsdiv +sendModalChat()function - Toast pattern:
document.createElement('div')positionedbottom:90px, fades out after 4s assignToCEO()posts to/api/chatwithsession_id='dashboard_assign', shows CEO response in toastdirectChatTask()stays old flow: close modal → switchTab('chat') → pre-fill input
Dashboard architecture (v4, 19/07/2026): Redesigned from 5-tab to 4-tab "Văn Phòng Đại Lý" layout:
- 🏢 VP: 9 agent cards grid. Click → full-page scrollable modal (5 sections)
- 📋 Bảng Tin: Live feed of all non-idle kanban tasks. Click task → detail modal with mini chat + state change
Project Memory System (new 19/07/2026) — dashboard/project_memory.py
Purpose: Each project has its own memory — chat history, facts, decisions — so CEO doesn't confuse projects. Skills are shared (cross-project reusable tools).
⚠️ TELEGRAM CEO RESPONSE: NO "đang nghĩ" MESSAGE. User explicitly complained about double-message spam. Instead:
tg_no_wait("sendChatAction", chat_id=chat_id, action="typing")— Tele shows "...đang gõ" indicator- Only send 1 message — the final LLM response
tg_no_wait()helper: fire-and-forget, non-blocking
Tele session commands (confirmed working 19/07/2026):
/gmsp → switch to GMSP session
/abtrip → switch to ABTrip
/airfare → switch to AirFares Decoded
/tuvi → switch to Tử Vi
/fasttrack → switch to Fast Track
/thoát → return to global chat
/new → reset current session (history still in DB, just clears RAM session)
_project_sessions[chat_id]dict persists session per chat/newdoes NOT delete history — only pops from session dict- Fallback:
_detect_project(text)runs if no active session
Database: data/project_memory.db
| Table | Contents | Key |
|---|---|---|
project_chat |
Per-project chat history | project column (name) |
global_chat |
Non-project chat | — |
facts |
Confirmed knowledge | project (or __global__), category, confidence |
decisions |
Business decisions made | project, status |
preferences |
User settings (theme, filters...) | key/value (JSON) |
skills |
Cross-project reusable skills | name, category, tools (JSON array) |
Telegram session commands (NEW 19/07/2026)
_project_sessions = {} # chat_id -> project name
# Commands in handle():
/gmsp → session switch to GMSP
/abtrip → session switch to ABTrip
/airfare → session switch to AirFares Decoded
/tuvi → session switch to Tử Vi
/fasttrack → session switch to Fast Track
/thoát or /all → return to global chat
Flow: User gõ /gmsp → bot confirm "Đã chuyển sang dự án GMSP" → mọi chat sau đó tự động inject project context. Chỉ cần /thoát để quay lại tổng quát.
Priority: _project_sessions.get(chat_id) > _detect_project(text) — nếu đang trong session GMSP, nói "airfare" cũng ko lẫn.
CEO response style (user preference):
- KHÔNG gửi "CEO đang nghĩ..." trước — user ghét bị spam 2 tin nhắn
- Dùng
sendChatAction(typing indicator) thay vì send message tạm — Tele hiện "...đang gõ" mà ko tạo message thật - Chỉ send 1 tin nhắn duy nhất khi LLM hoàn thành
tg_no_wait()helper: fire-and-forget API call, ko chặn luồng
Key functions (import from dashboard.project_memory)
| Function | Purpose |
|---|---|
save_chat(project, role, content) |
Save message to correct project table |
load_chat_history(project, limit=30) |
Load last N messages for project |
add_fact(project, fact, category, confidence, source) |
Store confirmed fact |
get_facts(project, category, limit) |
Retrieve facts |
search_facts(query, project, limit) |
Search facts by text |
add_decision(project, decision, context) |
Record a decision |
get_decisions(project, limit) |
Get decisions |
set_pref(key, value) |
Save user preference (JSON) |
get_pref(key, default) |
Read preference |
get_all_prefs() |
All preferences dict |
add_skill(name, description, category, tools) |
Add reusable skill |
get_skills(category) |
List skills |
build_project_context(project) |
Build context string for CEO prompt (facts + decisions + skills) |
extract_facts_from_message(project, message, role) |
Auto-extract emails, phones, URLs from messages |
CEO integration — /api/chat
The chat endpoint now accepts session_type parameter:
"global"(default) — uses global_chat, no project context"GMSP"/"ABTrip"etc — uses project_chat + injectsbuild_project_context()into system prompt
CEO system prompt now includes:
- All available skills (
=== KỸ NĂNG CÓ THỂ DÙNG ===) - Project facts + decisions (
=== DỰ ÁN HIỆN TẠI ===) - Rules to auto-save:
[LƯU FACT: ...] [CATEGORY: ...]and[QUYẾT ĐỊNH: ...]
Auto-extraction:
- From user messages: regex for emails, phones, URLs →
add_fact() - From CEO responses: parse
[LƯU FACT]and[QUYẾT ĐỊNH]brackets →add_fact()/add_decision()
API endpoints
| Endpoint | Method | Params |
|---|---|---|
/api/memory/facts |
GET | ?project=GMSP&category=contact&q=search&limit=20 |
/api/memory/facts |
POST | {project, fact, category, confidence, source} |
/api/memory/decisions |
GET | ?project=GMSP&limit=20 |
/api/memory/decisions |
POST | {project, decision, context} |
/api/memory/projects |
GET | Lists projects with memory (facts+decisions+chat counts) |
/api/preferences |
GET | All preferences |
/api/preferences |
POST | {key, value} |
/api/skills |
GET | ?category=general |
/api/skills |
POST | {name, description, category, tools[]} |
Chat flow (per-project)
User: "dự án GMSP có contact gì?"
→ POST /api/chat {message, session_type: "GMSP", session_id: "main_123"}
→ Server builds context: get_facts("GMSP") + get_skills() + load_chat_history("GMSP")
→ DeepSeek receives: [project facts] + [skills] + [last 30 messages]
→ CEO knows it's about GMSP, responds with facts
→ save_chat("GMSP", "user", msg) + save_chat("GMSP", "assistant", response)
→ extract_facts_from_message("GMSP", msg) → auto-save emails/phones
→ Parse CEO response for [LƯU FACT: ...] or [QUYẾT ĐỊNH: ...] → save
User: "còn ABTrip?" (different session_type: "ABTrip")
→ Same flow, different project context — CEO doesn't confuse
UI Integration: See references/project-sidebar-modal.md for the frontend pattern:
session_type: projectNamein inline modal chatopenProjectModal()loads facts + decisions on openprojectAddFact()posts to/api/memory/factsvia prompt- Sidebar "Dự án" section shows all projects with active/inactive dots
Pitfalls
project_memory.pymust be importable fromdashboard/dir → addsys.path.insert(0, str(BASE / "dashboard"))before import- Database path:
DATA / "project_memory.db"(same DATA dir as other DBs) _extract_bracket()helper function needed for CEO response parsing
Critical: Modal must be position:fixed; overflow-y:auto; max-height:100vh; overscroll-behavior:contain — user complained that content wasn't scrollable in the first version.
Web Dashboard (mobile-first) — 5 tabs (v3 SPA, 19/07/2026)
FastAPI + jinja2.Environment (raw, không dùng Jinja2Templates). Single SPA HTML file, giao diện dark theme (#0D0D12 bg + #FFD700 gold + #006885 teal). Chạy port 8137.
Password: tano2026 (hardcode trong app.py, localStorage trên frontend).
5 tabs
| Tab | Mô tả |
|---|---|
| 📊 Tổng Quan | System health (CPU/RAM/Disk C/D từ PowerShell) + 5 project cards (GMSP/Fast Track/ABTrip/Tử Vi/AirFares Decoded — check filesystem) + kanban/tickets/learning stats + outbox list |
| 👥 Phòng Ban | 9 agent cards (👔💻🎯📢⚙️🎧📊🎨🔬) với task count từ memory DBs — click vào mở modal info |
| 🏢 Văn Phòng | CEO avatar header + kanban board items + agents grid — auto-refresh 30s |
| 📋 Tasks | Kanban board (click→detail modal→state change) + tickets (click→detail modal) + nút "Thêm Card" |
| 💬 Chat | Chat với CEO — POST /api/chat, 1 LLM call (giống Telegram bot). Có nhớ lịch sử trò chuyện qua SQLite (data/chat_history.db) — F5/restart không mất. 20 messages gần nhất được gửi lên LLM. Bubbles: user right (gold), CEO left (card). Loading dots animation. Gửi session_id để grouping (dashboard_quick, dashboard_tab). |
API Endpoints
| Endpoint | Method | Mô tả |
|---|---|---|
/ |
GET | SPA HTML |
/login |
POST | Check password tano2026 (JSON hoặc form) |
/api/health |
GET | System stats từ PowerShell (CPU/RAM/Disk/Python processes) |
/api/projects |
GET | 5 project dirs (check filesystem): GMSP, Fast Track, ABTrip, Tử Vi, AirFares Decoded |
/api/chat |
POST | Chat CEO — gọi core.llm.chat() trực tiếp. Nhận {message}, trả {ok, response, time_ms} |
/api/kanban_summary |
GET | Count cards by state từ agent_kanban.db |
/api/kanban |
GET | All kanban cards |
/api/kanban/add |
POST | Thêm card mới |
/api/kanban/move |
POST | Move card state (click→modal dropdown) |
/api/tickets_summary |
GET | Count tickets by status từ tickets.db |
/api/tickets |
GET | All tickets |
/api/agents |
GET | 9 agents + task counts từ memory DBs |
/api/learning |
GET | observations + instincts từ learning.db |
/api/outbox |
GET | Files từ ~/.hermes/outbox/ |
/api/file/ls |
GET | ?path=... — list directory (bounded to D:\\MMO Du an) |
/api/file/read |
GET | ?path=...&offset=1&limit=200 — read text file (ext whitelist) |
/api/file/search |
GET | ?path=...&pattern=...&ext=.md — find files by name |
/api/file/ls |
GET | ?path=D:/MMO Du an — list directory (security: _safe_path() only allows under D:\\MMO Du an) |
/api/file/read |
GET | ?path=...&offset=1&limit=200 — read text file (whitelisted extensions only) |
/api/file/search |
GET | ?path=...&pattern=...&ext=.md — find files by name |
Detail Modal System
Từ 18/07 — tất cả các thẻ (kanban, ticket, agent, project) đều có click handler mở modal chi tiết:
- Kanban card → modal: title, owner, state, description (nếu có), created_at, updated_at + state change dropdown
- Ticket → modal: id, title, priority, status, customer, description
- Agent → modal: icon, name, task count + link
- Project → modal: name, status, filesystem path
Dùng MutationObserver để re-attach click handlers sau mỗi lần reload data (dynamic content).
Important: Click → modal detail pattern requires 3 parts in the HTML:
- overlay HTML —
.modal-overlaydiv with.modal-content+.modal-close - CSS —
.modal-overlay { display: flex/block },.modal-content { ... },.modal-close - JS —
document.querySelector('.modal-overlay').classList.add('active')+renderModalContent(data)+ close on overlay click
Cards use data-id attributes for identification. MutationObserver watches document.getElementById('tab-content') for new cards.
Error handling pattern — Chat
Khi /api/chat trả về lỗi, frontend hiển thị trong chat bubble:
data.error→ "❌ Lỗi: ..."!data.ok || !data.response→ "⚠️ CEO không phản hồi. Thử lại nhé."fetch exception→ "❌ Lỗi kết nối: ..."
File structure
dashboard/
app.py # FastAPI app (~400 lines, 13KB)
templates/
dashboard.html # SPA single-page (~1150 lines, 52KB — CSS+JS inline)
Văn Phòng tab (Situation Room)
Mô phỏng văn phòng: 1 bàn họp phát sáng + CEO avatar ở giữa + 8 agent card 2 cột.
Mỗi agent có trạng thái realtime qua CSS class — ring xoay khi running, shake avatar, glow pulse vàng.
JS fetch /api/kanban + /api/agents, auto-refresh 15s.
Chi tiết CSS class names: .running, .done, .blocked, .agent-ring, @keyframes ring-rotate, @keyframes avatar-shake.
Critical: Sync checklist when adding NEW project (e.g. Airfare Decoded)
Khi thêm dự án mới, patch CẢ 7 chỗ này — quên 1 chỗ là CEO không biết dự án hoặc dashboard hiển thị sai:
- CLIENTS//SKILL.md — pipeline + brand + rules
- Media adapter (
agents/media/adapters.py) — thêm tools + updatevideo_pipelineanalyzer - Dev adapter (
agents/dev/adapters.py) — thêm keyword→path vàoproject_map - CEO system prompt (
main.pycmd_naturalsystem string) — thêm vào "5 DỰ ÁN HIỆN TẠI:" section - CEO adapter (
agents/ceo/adapters.py) — thêm vàoCOMPANY_PROJECTSdict - Dashboard API (
dashboard/app.py) — thêm project entry vàoapi_projects()endpoint (Path check + project dict) - Dashboard JS (
dashboard/templates/dashboard.html) — thêm icon+label vàoPROJ_ICONSvàPROJ_LABELSconstants
Dashboard deploy pitfall: sau khi sửa app.py, __pycache__ giữ code cũ. Process mới python dashboard/app.py dùng .pyc cũ → không thấy thay đổi (ví dụ: API trả về 4 projects dù code có 5).
Fix:
- Xoá toàn bộ
__pycache__trong agent-core tree. Dùng Python script:import shutil, os; root = "D:/MMO Du an/TANO-AGENCY/PLATFORM/agent-core" [shutil.rmtree(os.path.join(d,'__pycache__')) for d,dirs,_ in os.walk(root) if '__pycache__' in dirs] - Kill ALL old Python processes đang giữ port 8137 — không chỉ PID mới. Process cũ (PID 34520) vẫn LISTENING dù đã kill "tất cả". Dùng:
netstat -ano | grep 8137 # tìm LISTENING PID taskkill /F /PID <PID> # kill đúng PID đó - Verify port free:
netstat -ano | grep 8137→ ko còn LISTENING - Restart dashboard:
python dashboard/app.py
Double-kill pattern: git-bash taskkill thường fail với lỗi "Invalid argument". Dùng: cmd.exe /c "taskkill /F /PID <PID>" hoặc powershell Stop-Process -Id <PID> -Force qua write_file script.
Triple-verify: process mới ≠ process thật. Luôn check netstat -ano | grep 8137 sau khi restart + curl http://localhost:8137/api/projects để confirm code mới.
- CLIENTS//SKILL.md — pipeline + brand + rules
- Media adapter (
agents/media/adapters.py) — thêm tools + updatevideo_pipelineanalyzer - Dev adapter (
agents/dev/adapters.py) — thêm keyword→path vàoproject_map - CEO system prompt (
main.pycmd_naturalsystem string) — thêm vào "5 DỰ ÁN HIỆN TẠI:" section - CEO adapter (
agents/ceo/adapters.py) — thêm vàoCOMPANY_PROJECTSdict
Pitfalls:
main.pycmd_naturalsystem prompt dùng Python string concatenation —\nphải viết là\\n(double escape) vì nó là literal string trong source code. Nếu dùngpatchtool với old_string/new_string chứa\\, tool có thể double-escape lại thành\\\\. Luôn verify sau patch bằng cách đọc lại file dòng 111-132.agents/ceo/adapters.py_ceo_initiative()dùngCOMPANY_PROJECTSdict — chỉ cần thêm entry, không cần sửa prompt não của CEO vì nó đọc từ dict runtime.- planner adapter (
plugins/adapters/planner.py) đã bị xóa (format corporate), không tồn tại trên disk nữa.main.pycmd_naturallà entry point duy nhất cho chat CEO.
Công ty: 5 trụ cột chính (updated 18/07/2026)
Đăng ký trong CEO adapters (COMPANY_PROJECTS dict):
| # | Dự án | Phòng ban | Mô tả | Trạng thái |
|---|---|---|---|---|
| 1 | GMSP | research, marketing, media, video | Pipeline video content (Tử Vi, PTBT, Cổ Kim). Đã gộp Giải Mã Số Phận vào pipeline. 7-stage: Research→Script→TTS→Media→Render→Publish→Social. EP01 done, EP02 script. | ✅ active |
| 2 | ABTrip (Smart Agent) | dev, ticketing, operations, sales | Đặt vé máy bay + dịch vụ du lịch. Brand mới: Smart Agent (Travel Tech Hybrid). Mô hình "bán cần câu" — bán giải pháp phòng vé mini cho CTV. 3 gói: CTV Cơ bản (free) → Đại Lý Pro (199K/tháng) → White-label (1.5tr/tháng). Đối thủ cạnh tranh: AI Travel (Layla, Wander AI, Mindtrip, Roam Around — zero overlap ngách CTV). Cơ hội: 12-18 tháng. Hướng build-to-flip: Hybrid (ưu tiên). Gồm: AGT API, Flight MCP, Fast Track Nội Bài (An Bình), Lounge, eSIM (IST1). Chat LLM UI mobile-first. Backend FastAPI port 8138, Frontend Next.js 14 port 4321. | ✅ active |
| 3 | An Bình Fast Track | dev, marketing, media, sales | Fast Track + VIP B + Lounge Nội Bài — đơn vị duy nhất có onsite staff 24/7. Landing page + OTA listing + hotel/DMC partnership. Teal #006885 + gold #DBA011. Đang đổi tên do quy định Nội Bài. | ✅ active |
| 4 | Tử Vi | dev, research | Tử Vi Đẩu Số platform — iztro + MCP + Python engine. Đã train + agent v3.0. | ✅ active |
| 5. Airfare Decoded (English Channel) | media, research, marketing | Kênh YouTube English faceless — stick-figure explainer về insider kiến thức vé máy bay. Pipeline: HyperFrames + Pollinations + Edge TTS AndrewNeural. 2 video/tuần. Variation guard (≥3/5 trục khác video trước). | ✅ active (setup 18/07) |
Onboarding Client Mới — SOP (Standard Operating Procedure)
Khi kickstart dự án mới (VD: Airfare Decoded), cần patch 4 chỗ:
- CLIENTS//SKILL.md — pipeline, brand, design tokens, key files, skill references, hard rules
- Media adapter (
agents/media/adapters.py) — thêm tools mới (_tool_hyperframes,_tool_pollinations), update_real_image_gen()auto-detect context, updatevideo_pipelineanalyzer prompt, register tools + set workdir constant trongbuild_registry() - Dev adapter (
agents/dev/adapters.py) — thêm keyword→path vàoproject_map - CEO adapter (
agents/ceo/adapters.py) — thêm vàoCOMPANY_PROJECTS+ update intake system prompt list
Verify: python -c "import ast; ast.parse(open('...').read()); print('✅ syntax OK')" mỗi file + test CEO biết dự án mới.
Provider fallback rule: Luôn document alternative providers trong SKILL.md. VD: ElevenLabs cần trả tiền → Edge TTS fallback. Edge TTS AndrewNeural cho English, NamMinhNeural cho Việt.
Lưu ý: Dự án số 5 là English channel
CLIENTS/ import pattern
Khi import project mới vào TANO-AGENCY:
- Tạo
TANO-AGENCY/CLIENTS/<PROJECT>/folder - Viết
SKILL.md— pipeline + brand + config + skill references từ toolkit - Viết supporting docs (architecture, database, roadmap)
- Link skills từ AI-Vibe-Toolkit qua section "Agent Skills (load from AI-Vibe-Toolkit)"
- Update
PROJECT-MAP.mdở TANO-AGENCY/ root — ánh xạ thư mục
Toolkit skill linking: không copy skill .md vào CLIENTS/ — chỉ reference bằng tên + description. Agent dùng skill_view() để load từ toolkit khi cần.
Ví dụ GMSP import:
CLIENTS/GMSP/
├── SKILL.md ← Pipeline 7-stage + brand + render config
└── gmsp-content-engine.md ← Skill reference
Ví dụ ABTrip import:
CLIENTS/ABTRIP/
├── ABTRIP.md ← Overview + status
├── SKILL.md ← Ticketing + Fast Track + eSIM
├── ABTRIP-ARCHITECTURE.md
├── ABTRIP-DATABASE.md
├── ABTRIP-ROADMAP.md
└── sub-services/
└── fast-track.md
Ví dụ Airfare Decoded import:
CLIENTS/AIRFARE-DECODED/
└── SKILL.md ← Pipeline 6 scene + brand + variation guard + HyperFrames config + agent skills
Lưu ý: Airfare Decoded khác GMSP — không có 7-stage pipeline, thay bằng HyperFrames compose→render workflow. Brand tokens: ink #111111, paper #fdfdfb, accent #d92b2b, display font Patrick Hand, body font Inter. V
…(truncated)