Project Positioning: OPC-Starter (One-Person Company Starter) is an AI-friendly React Boilerplate designed for developers using AI Coding tools such as Cursor and Qoder.
Core Philosophy: Execute like senior R&D expert Amelia — tests are specifications, code is implementation, precise positioning, no redundant output.
🎯 Dynamic Context System
Context-Aware Rules
Automatically load relevant documents and constraints based on task type, avoiding interference from irrelevant information.
| Task Keywords | Trigger Context | Load Documents |
|---|---|---|
Agent、工具、Tool、A2UI |
Agent Studio Development | AGENTS.md → Agent specification section |
组件、页面、UI、样式 |
Frontend UI Development | references/coding-constraints.md → Design system |
数据库、SQL、表、字段 |
Database Changes | references/db-sync-checklist.md |
测试、TDD、Cypress、Vitest |
Test Development | references/tdd-workflow.md |
Bug、修复、异常、报错 |
Troubleshooting | references/troubleshooting.md |
架构、模块、服务 |
System Design | docs/Architecture.md |
Pre-Execution Self-Check
Before starting a task, detect the following conditions and dynamically load rules:
context_check:
- keyword_match: 检测任务描述关键词
- file_scope: 检测涉及的文件路径
- change_type: 判断是新功能/Bug修复/重构
auto_load:
agent_module: "app/src/components/agent/**" | "app/src/lib/agent/**"
ui_module: "app/src/components/**" | "app/src/pages/**"
data_module: "app/src/services/data/**" | "app/supabase/**"
test_module: "**/*.test.ts" | "**/*.spec.ts" | "cypress/**"
📊 Project Core Architecture
Tech Stack
| Technology | Version | Notes |
|---|---|---|
| React | 19.1 | Latest stable version |
| TypeScript | 5.9 | Strict typing |
| Vite | 7.1 | Build tool |
| Tailwind CSS | 4.1 | ⚠️ Must use v4 syntax |
| Supabase | 2.80 | Auth + Storage + Realtime + Edge Functions |
| Zustand | 5.0 | State management |
| Vitest | 4.0 | Unit testing framework |
| Cypress | 15.7 | E2E testing framework |
| Qwen-Plus | via Bailian API | Agent LLM (Tongyi Qianwen) |
| A2UI | v0.8 | Agent dynamic UI protocol |
Directory Structure
opc-starter/
├── app/ # 主应用
│ ├── src/
│ │ ├── auth/ # 认证模块
│ │ ├── components/
│ │ │ ├── agent/ # Agent Studio ⭐
│ │ │ │ └── a2ui/ # A2UI 渲染系统
│ │ │ ├── business/ # 业务组件
│ │ │ ├── layout/ # 布局组件
│ │ │ ├── organization/ # 组织架构
│ │ │ └── ui/ # 基础 UI (shadcn)
│ │ ├── pages/ # 页面组件
│ │ ├── services/
│ │ │ └── data/ # DataService (核心) ⭐
│ │ ├── stores/ # Zustand Store
│ │ ├── lib/
│ │ │ ├── agent/ # Agent 客户端 ⭐
│ │ │ │ └── tools/ # 前端工具执行器
│ │ │ └── supabase/ # Supabase 客户端
│ │ ├── hooks/ # 自定义 Hooks
│ │ ├── types/ # TypeScript 类型
│ │ └── mocks/ # MSW Mock
│ └── supabase/
│ ├── functions/
│ │ └── ai-assistant/ # Agent SSE 网关 ⭐
│ └── setup.sql # 数据库脚本 (所有变更集中于此)
├── docs/
│ ├── Architecture.md # 系统架构
│ └── Epics.yaml # 项目进度
├── _bmad/ # BMAD 方法论 (可选参考)
└── AGENTS.md # AI Coding 快速指南
Core Capability Modules
| Module | Key Files | Description |
|---|---|---|
| Authentication System | app/src/auth/ |
Supabase Auth + JWT |
| Organizational Structure | app/src/components/organization/ |
Multi-level teams, members, roles |
| Agent Studio | app/src/components/agent/ |
Natural language AI assistant ⭐ |
| Data Synchronization | app/src/services/data/DataService.ts |
IndexedDB + Realtime |
| Personal Center | app/src/pages/ProfilePage.tsx |
User information, avatar |
🔴🟢🔵 TDD Core Principles
Red-Green-Refactor Cycle
┌─────────────────────────────────────────────────────────────┐
│ TDD 循环 (每个功能点) │
│ │
│ 🔴 RED 🟢 GREEN 🔵 REFACTOR │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 写失败 │────▶│ 写最小 │────▶│ 优化 │──┐ │
│ │ 的测试 │ │ 实现代码 │ │ 重构 │ │ │
│ └─────────┘ └─────────┘ └─────────┘ │ │
│ ▲ │ │
│ └────────────────────────────────────────┘ │
│ (下一个功能点) │
└─────────────────────────────────────────────────────────────┘
| Phase | Goal | Rule |
|---|---|---|
| 🔴 RED | Write a failing test | The test must clearly express the requirement intent |
| 🟢 GREEN | Write the minimum code to pass the test | Only write code that is just enough to make the test pass |
| 🔵 REFACTOR | Optimize code structure | Keep tests passing, eliminate duplication |
Test-First Principle ⚠️ MANDATORY
❌ 禁止:先写代码再补测试
❌ 禁止:提交没有测试覆盖的新功能
❌ 禁止:修改代码后不运行测试就提交
✅ 必须:新功能先写测试用例
✅ 必须:Bug 修复先写复现测试
✅ 必须:每次提交前运行完整测试套件
Test Pyramid
| Level | Test Type | Coverage Target | Run Frequency |
|---|---|---|---|
| Bottom layer | Unit Tests (Vitest) | Utility functions, Services, Hooks | Every save |
| Middle layer | Integration Tests (Vitest) | DataService, Store interactions | Every commit |
| Top-level | E2E Testing (Cypress) | Login, core user flows | Before PR merge |
🤖 Agent Studio Development Guidelines
When a task involves Agent-related development, this section is automatically loaded.
Architecture Flow
用户 ←→ AgentWindow (悬浮对话框)
↓
useAgentChat Hook
↓
SSE Client ←→ ai-assistant (Edge Function)
↓ ↓
Tool Executor Qwen-Plus (百炼 API)
↓
A2UI Renderer (动态 UI)
Core Files
| File | Responsibility |
|---|---|
app/src/components/agent/AgentWindow.tsx |
Floating chat window |
app/src/hooks/useAgentChat.ts |
Agent chat state management |
app/src/lib/agent/sseClient.ts |
SSE streaming client |
app/src/lib/agent/toolExecutor.ts |
Local tool executor |
app/src/components/agent/a2ui/A2UIRenderer.tsx |
A2UI component renderer |
app/src/components/agent/a2ui/registry.ts |
Component whitelist registry |
app/supabase/functions/ai-assistant/ |
Agent backend gateway |
Add a New Agent Tool
- Backend: In
ai-assistant/tools.tsadd the tool definition (OpenAI format) - Frontend: In
app/src/lib/agent/tools/create the tool directory - Register: In
app/src/lib/agent/tools/registry.tsregister - System Prompt: In
ai-assistant/sse.tsofbuildSystemPrompt()add usage instructions
// 工具定义示例 (OpenAI 格式)
{
type: "function",
function: {
name: "myNewTool",
description: "工具描述",
parameters: {
type: "object",
properties: { /* ... */ },
required: ["param1"],
},
},
}
Add a New A2UI Component
- In
app/src/components/agent/a2ui/components/create the component - In
registry.tsregister the component (whitelist mode) - In
app/src/types/a2ui.tsadd the type definition
// registry.ts 注册示例
export const A2UI_REGISTRY: A2UIComponentRegistry = {
'my-component': MyComponent,
};
A2UI Action ID Specification
| Category | Action ID Format | Example |
|---|---|---|
| Navigation | navigation.* |
navigation.goTo |
| User | user.* |
user.updateProfile |
| Organization | org.* |
org.createTeam |
Mock LLM Testing
Use MSW to mock Agent responses:
// app/src/mocks/handlers/agentHandlers.ts
http.post('*/functions/v1/ai-assistant', async ({ request }) => {
// 返回 SSE 流式响应
});
🎨 Design System Guidelines
When a task involves UI component development, this section is automatically loaded.
Tailwind CSS v4 Syntax (Mandatory)
// ❌ 禁止:v2/v3 语法
className="bg-opacity-50 bg-gradient-to-r"
// ✅ 正确:v4 语法
className="bg-black/50 bg-linear-to-r"
| Prohibited (v2/v3) | Use (v4) |
|---|---|
bg-opacity-* |
bg-color/opacity |
bg-gradient-to-* |
bg-linear-to-* |
Semantic Colors (Dark Mode Adaptation)
Core Principles: Use semantic colors; hardcoded color values are prohibited.
| Semantic Color | Usage | ❌ Prohibited |
|---|---|---|
bg-background |
Page background | bg-gray-50, bg-white |
bg-card |
Card/container background | bg-white |
text-foreground |
Primary text | text-gray-900, text-black |
text-muted-foreground |
Secondary text | text-gray-500 |
border |
Border | border-gray-200 |
bg-primary |
Primary button | bg-blue-600 |
bg-destructive |
Dangerous action | bg-red-600 |
// ❌ 禁止:硬编码颜色
<div className="bg-white text-gray-900 border-gray-200">
// ✅ 正确:语义化颜色
<div className="bg-card text-foreground border">
Mobile Overlay Components ⚠️ CRITICAL
Overlays such as Sidebar, Modal, and Dropdown must use explicit colors + dark: prefix
// ❌ 错误:CSS 变量在移动端覆盖层可能失效
<aside className="bg-card text-foreground">
// ✅ 正确:显式颜色
<aside className="bg-white dark:bg-slate-900 text-gray-900 dark:text-gray-100">
💾 Data Access Guidelines
Unified Access via DataService
// ✅ 正确:通过 DataService 访问
import { dataService } from '@/services/data/DataService'
await dataService.getAll('profiles')
// ❌ 禁止:直接访问
import { supabase } from '@/lib/supabase/client' // 禁止
Data Flow Architecture
┌─────────────────────────────────────────────────┐
│ UI Layer → Zustand Stores → DataService │
│ │ │
│ ┌──────────────┼──────────┐ │
│ │ IndexedDB │ │
│ │ • 读: 100% 本地 │ │
│ │ • 写: 乐观更新 │ │
│ │ • 同步: Realtime │ │
│ └──────────────┼──────────┘ │
│ │ │
│ ┌──────────────┼──────────┐ │
│ │ Supabase │ │
│ │ • Postgres Changes │ │
│ └─────────────────────────┘ │
└─────────────────────────────────────────────────┘
Centralized SQL Change Management
All database changes → app/supabase/setup.sql(creating standalone SQL files is prohibited)
🐛 Bug Fix Guidelines
When the task is a bug fix, this section is automatically loaded.
Core principle: inspect the data first, then change the code
发现问题 → 浏览器调试验证 → 定位根因 → 一次性修复 → 验证通过
Debugging Steps
-
Use browser DevTools
- Network panel: inspect API requests and response data
- Console panel: view logs and error messages
-
Add temporary debug logs
console.log('[Debug] 数据状态:', JSON.stringify(data, null, 2)); -
Common Data Integrity Issues
| Problem Scenario | Symptom | Troubleshooting Method |
|---|---|---|
| Foreign key reference is invalid | Join query returned null |
Check whether the referenced record exists |
| Array contains invalid ID | Batch query returns partial data | Compare request ID and response data |
| Field is empty | Feature does not work | Check actual database record values |
Defensive coding
// ❌ 假设数据一定有效
const coverUrl = await getPhotoUrl(album.photoIds[0]);
// ✅ 遍历找到第一个有效项
for (const photoId of album.photoIds) {
const url = photoUrlMap.get(photoId);
if (url) {
album.coverPhotoUrl = url;
break;
}
}
✅ Development workflow
Complete process
需求/Bug → BMAD 方案讨论(可选) → Epic/Story/Task → 🔴测试先行 → 🟢代码实现 → 🔵重构优化 → 质量验证 → 人工审查 → 上线
Phase 1: TDD tests first 🔴
npm run test:watch # 监听模式(开发时)
Test file naming: *.test.ts or *.spec.ts, in the same directory as the source file
// app/src/services/example.test.ts
import { describe, it, expect, vi } from 'vitest'
describe('ExampleService', () => {
it('应该完成预期功能', async () => {
// Arrange - 准备测试数据
// Act - 执行待测函数
// Assert - 验证结果
})
})
Phase 2: Code implementation 🟢
Complete the code implementation in accordance with technical constraints. See references/coding-constraints.md。
Phase 3: Refactoring and optimization 🔵
✅ 测试全部通过后再重构
✅ 每次小步重构后运行测试
✅ 提取公共方法、消除重复
❌ 不要在重构时添加新功能
Phase 4: Quality verification
# 一键质量验证
./scripts/quality_check.sh
# 核心校验(不含 E2E)
npm run ai:check
# 或手动执行
npm run lint:check # ESLint 检查
npm run format:check # Prettier 格式检查
npm run type-check # TypeScript 类型检查
npm run test # 单元测试
npm run test:e2e:headless # E2E 回归测试
npm run build # 构建验证
| Check item | Command | Pass criteria |
|---|---|---|
| ESLint | npm run lint:check |
0 errors |
| TypeScript | npm run type-check |
0 errors |
| Unit tests | npm run test |
All passed |
| E2E tests | npm run test:e2e:headless |
All passed |
| Build | npm run build |
Success |
🚫 Prohibited list
Coding prohibitions
| Category | Prohibited items |
|---|---|
| Tailwind | *-opacity-* syntax,bg-gradient-to-* |
| Color | Hardcoded colors such as bg-white、text-gray-900、bg-blue-600 |
| Overlay | Sidebar/Modal/Dropdown use CSS variable colors |
| Data access | Direct import supabase client |
| File management | Create standalone SQL migration files, create new document files |
| TypeScript | Use any type |
| React Hooks | useCallback as useEffect dependency (no ref guard) |
| Agent | Use unregistered component types in A2UI |
| Agent | Call the LLM API directly (must go through the ai-assistant Edge Function) |
TDD prohibitions
| Prohibited items | Consequences |
|---|---|
| Write code first, then add tests | Poor code design, difficult to test |
| Submit new features without test coverage | Regression risk, quality cannot be guaranteed |
| Submit code without running tests | CI fails, blocking others |
| Ignore test failures and continue development | Problems accumulate, fixing costs increase |
📚 Reference documents
Load on demand
| Document | Content | Trigger keywords |
|---|---|---|
references/tdd-workflow.md |
Complete TDD process, test writing standards | vitest, cypress, test |
references/coding-constraints.md |
Coding constraints, React Hooks anti-patterns | useEffect, hooks, ltree |
references/project-structure.md |
Project structure, NPM commands | structure, npm |
references/db-sync-checklist.md |
Database consistency checks | CHECK, migration, sql |
references/troubleshooting.md |
Common problems and solutions | error, fix, debug |
External documents
| Document | Purpose |
|---|---|
docs/Architecture.md |
Complete system architecture |
docs/Epics.yaml |
Project progress tracking |
AGENTS.md |
AI Coding quick guide |
app/supabase/SUPABASE_COOKBOOK.md |
Database operations manual |
BMAD methodology reference (optional)
When requirements analysis and solution design need to be standardized, refer to the BMAD workflow:
| Agent | Purpose |
|---|---|
_bmad/bmm/agents/dev.md (Amelia) |
Senior R&D expert, precisely executes Stories |
_bmad/bmm/agents/architect.md |
System architect, technical solution design |
_bmad/bmm/workflows/ |
Standardized workflow |
🚀 Quick commands
# 开发
npm run dev # 启动开发服务器
npm run dev:test # 测试模式 (MSW mock)
# TDD 测试
npm run test # 运行单元测试
npm run test:watch # 监听模式(开发时推荐)
npm run coverage # 生成覆盖率报告
# E2E 测试
npm run cypress:open # 在已启动 dev:test 时交互运行 Cypress
npm run test:e2e # 启动 dev:test 后无头运行 E2E
npm run test:e2e:headless # Cypress 无头模式 (CI)
# 质量检查
npm run lint # ESLint 检查并修复
npm run format # Prettier 格式化
npm run type-check # TypeScript 类型检查
npm run build # 生产构建
# 一键质量验证
npm run ai:check
./scripts/quality_check.sh
Recommended workflow
# 1. 启动测试监听(新终端窗口)
npm run test:watch
# 2. 启动开发服务器(另一个终端窗口)
npm run dev:test
# 3. 🔴 编写测试 → 看到红色失败
# 4. 🟢 实现代码 → 看到绿色通过
# 5. 🔵 重构优化
# 6. 提交前运行完整质量检查
./scripts/quality_check.sh