集成方案设计
方案设计 架构设计 集成
设计 Trellis 思想与 pi-mono agent 助手的集成方案,包含架构设计、数据模型和实施路径
1. 设计原则与约束
1.1 设计原则
在将 Trellis 的思想融入 pi-mono agent 助手时,遵循以下原则:
- 渐进式采用:不要求一次性重构,允许逐步引入 Trellis 的模块
- 向后兼容:保留 pi-mono 现有的核心设计,Treillis 作为增强层
- 模块化:每个 Trellis 能力都是可选模块,可按需启用
- 最小侵入:尽量通过适配器和扩展点集成,避免修改核心代码
- 可验证:每个集成点都应有明确的验证标准和回滚方案
1.2 技术约束
pi-mono 现有架构:
- 需要评估 pi-mono 的插件系统或扩展点
- 了解现有的任务管理和上下文管理机制
- 识别不可修改的核心部分
兼容性要求:
- 保持与现有 pi-mono 工作流的兼容
- 不影响不使用 Trellis 功能的用户
- 支持配置驱动的渐进式启用
1.3 非功能性需求
| 需求 | 目标 | 衡量指标 |
|---|---|---|
| 性能 | Spec 注入延迟 < 100ms | 上下文加载时间 |
| 可扩展性 | 支持 10+ 任务并行 | 并发任务数 |
| 可维护性 | 新增平台适配器 < 1 天 | 开发效率 |
| 学习曲线 | 新用户 30 分钟内上手 | 文档完整性 |
2. 整体架构设计
2.1 分层架构
┌─────────────────────────────────────────────────────┐
│ Agent Interface Layer │
│ (Claude Code, Cursor, OpenCode, etc.) │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Trellis Integration Layer │
│ ┌──────────────┬──────────────┬─────────────────┐ │
│ │ Spec Manager │ Task Manager │ Workspace Mgr │ │
│ └──────────────┴──────────────┴─────────────────┘ │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ pi-mono Core Layer │
│ (Agent Runtime, Context Management, etc.) │
└─────────────────────────────────────────────────────┘
层级职责:
-
Agent Interface Layer:
- 对接各种 AI coding 平台
- 处理平台特定的协议和格式
- 不关心 Trellis 或 pi-mono 的内部实现
-
Trellis Integration Layer:
- Spec Manager:分层 Spec 的存储、检索、注入
- Task Manager:任务生命周期、上下文隔离、状态管理
- Workspace Manager:Journal、会话连续性、个人偏好
-
pi-mono Core Layer:
- Agent 运行时
- 基础上下文管理
- 核心编排逻辑
2.2 数据流设计
sequenceDiagram
participant User as 用户
participant Agent as AI Agent
participant Trellis as Trellis 层
participant PiMono as pi-mono 核心
participant Storage as 存储层
User->>Agent: 发起任务
Agent->>Trellis: 请求上下文
Trellis->>Storage: 加载 Spec
Trellis->>Storage: 加载任务上下文
Trellis->>Storage: 加载 Journal
Storage-->>Trellis: 返回上下文
Trellis->>Trellis: 智能注入
Trellis-->>Agent: 组合上下文
Agent->>PiMono: 执行任务
PiMono-->>Agent: 执行结果
Agent->>Trellis: 更新 Journal
Trellis->>Storage: 持久化
Agent-->>User: 返回结果
2.3 模块依赖关系
trellis-integration/
├── spec-manager/ # Spec 管理模块
│ ├── spec-loader.ts # Spec 加载器
│ ├── spec-injector.ts # Spec 注入器
│ └── spec-validator.ts # Spec 验证器
├── task-manager/ # 任务管理模块
│ ├── task-context.ts # 任务上下文
│ ├── task-state.ts # 任务状态机
│ └── task-isolator.ts # 任务隔离
├── workspace-manager/ # Workspace 管理模块
│ ├── journal.ts # Journal 管理
│ ├── session.ts # 会话管理
│ └── preferences.ts # 偏好管理
└── platform-adapters/ # 平台适配器
├── claude-code.ts
├── cursor.ts
├── opencode.ts
└── ...
3. 核心模块设计
3.1 Spec Manager
职责:管理分层 Spec 的存储、检索和注入
接口设计:
interface SpecManager {
// 初始化 Spec 目录
initialize(projectRoot: string): Promise<void>;
// 获取基础 Spec(始终注入)
getBaseSpecs(): Promise<Spec[]>;
// 根据任务类型选择上下文 Spec
selectContextSpecs(taskType: TaskType): Promise<Spec[]>;
// 加载显式声明的 Spec
loadExplicitSpecs(specIds: string[]): Promise<Spec[]>;
// 组合并注入 Spec
injectSpecs(task: Task): Promise<InjectedContext>;
// 验证 Spec 格式
validateSpec(spec: Spec): ValidationResult;
}
数据模型:
interface Spec {
id: string; // spec-001
name: string; // "Coding Standards"
path: string; // ".trellis/spec/coding-standards.md"
type: SpecType; // base | architecture | domain | integration
content: string; // Markdown 内容
metadata: {
version: string; // "1.0.0"
lastUpdated: Date; // 最后更新时间
requiredFor: TaskType[]; // 适用的任务类型
optionalFor: TaskType[]; // 可选的任务类型
};
}
interface InjectedContext {
specs: Spec[]; // 已选择的 Spec 列表
combined: string; // 组合后的 Markdown
checksum: string; // 用于缓存验证
injectedAt: Date; // 注入时间
}
注入策略:
class SpecInjector {
async inject(task: Task): Promise<InjectedContext> {
// 1. 加载基础 Spec
const baseSpecs = await this.getBaseSpecs();
// 2. 根据任务类型选择 Spec
const contextSpecs = await this.selectContextSpecs(task.type);
// 3. 加载显式声明的 Spec
const explicitSpecs = await this.loadExplicitSpecs(task.requiredSpecs);
// 4. 去重(按 Spec ID)
const allSpecs = this.deduplicate([...baseSpecs, ...contextSpecs, ...explicitSpecs]);
// 5. 组合为 Markdown
const combined = this.combineToMarkdown(allSpecs);
// 6. 生成缓存 checksum
const checksum = this.generateChecksum(allSpecs);
return {
specs: allSpecs,
combined,
checksum,
injectedAt: new Date()
};
}
}
3.2 Task Manager
职责:管理任务生命周期、上下文隔离和状态
接口设计:
interface TaskManager {
// 创建新任务
createTask(prd: TaskPRD): Promise<Task>;
// 加载任务上下文
loadTaskContext(taskId: string): Promise<TaskContext>;
// 更新任务状态
updateTaskState(taskId: string, state: TaskState): Promise<void>;
// 记录任务决策
logDecision(taskId: string, decision: Decision): Promise<void>;
// 完成任务
completeTask(taskId: string, summary: TaskSummary): Promise<void>;
// 获取活跃任务列表
getActiveTasks(): Promise<Task[]>;
}
数据模型:
interface Task {
id: string; // task-001
prd: TaskPRD; // 产品需求文档
type: TaskType; // feature | bugfix | refactor | docs
status: TaskStatus; // pending | in_progress | blocked | completed
createdAt: Date;
updatedAt: Date;
assignedTo?: string; // 开发者/Agent ID
branch?: string; // git 分支名
worktree?: string; // worktree 路径
context: TaskContext; // 任务上下文
state: TaskState; // 任务状态
}
interface TaskContext {
files: FileInfo[]; // 相关文件
decisions: Decision[]; // 决策记录
snippets: CodeSnippet[]; // 关键代码片段
specIds: string[]; // 关联的 Spec ID
}
interface TaskState {
currentStep: number; // 当前步骤
checkpoints: Checkpoint[]; // 检查点
errors: TaskError[]; // 错误列表
metrics: {
estimatedHours: number;
actualHours: number;
startedAt?: Date;
completedAt?: Date;
};
}
状态机设计:
type TaskStatus = 'pending' | 'in_progress' | 'blocked' | 'completed' | 'cancelled';
class TaskStateMachine {
private transitions: Record<TaskStatus, TaskStatus[]> = {
'pending': ['in_progress', 'cancelled'],
'in_progress': ['blocked', 'completed', 'cancelled'],
'blocked': ['in_progress', 'cancelled'],
'completed': [],
'cancelled': []
};
canTransition(from: TaskStatus, to: TaskStatus): boolean {
return this.transitions[from].includes(to);
}
async transition(task: Task, to: TaskStatus): Promise<void> {
if (!this.canTransition(task.status, to)) {
throw new Error(`Invalid state transition: ${task.status} → ${to}`);
}
task.status = to;
task.updatedAt = new Date();
// 触发状态变更事件
await this.emitEvent('task.state.changed', { task, to });
}
}
3.3 Workspace Manager
职责:管理 Journal、会话和个人偏好
接口设计:
interface WorkspaceManager {
// 初始化 Workspace
initialize(userId: string): Promise<void>;
// 加载用户偏好
loadPreferences(): Promise<UserPreferences>;
// 开始新会话
startSession(taskId: string): Promise<SessionContext>;
// 记录 Journal 条目
appendJournal(entry: JournalEntry): Promise<void>;
// 结束会话
endSession(summary: SessionSummary): Promise<void>;
// 获取最近 Journal 条目
getRecentEntries(count: number): Promise<JournalEntry[]>;
}
数据模型:
interface JournalEntry {
id: string; // journal-001
taskId: string; // 关联任务 ID
sessionId: string; // 关联会话 ID
type: JournalEntryType; // decision | issue | solution | note
content: string; // 条目内容
tags: string[]; // 标签
createdAt: Date;
metadata?: {
file?: string; // 相关文件
code?: string; // 相关代码
references?: string[]; // 相关条目 ID
};
}
interface SessionContext {
sessionId: string;
taskId: string;
userId: string;
preferences: UserPreferences;
recentJournal: JournalEntry[];
taskContext: TaskContext;
startTime: Date;
}
Journal 管理:
class JournalManager {
async appendJournal(entry: JournalEntry): Promise<void> {
// 1. 验证条目格式
this.validateEntry(entry);
// 2. 追加到 Journal 文件
const journalPath = this.getJournalPath(entry.userId);
await this.appendToFile(journalPath, this.formatEntry(entry));
// 3. 创建会话文件(如果是会话相关)
if (entry.sessionId) {
await this.ensureSessionFile(entry.sessionId);
}
// 4. 触发事件
await this.emitEvent('journal.entry.added', { entry });
}
async getRecentEntries(userId: string, count: number): Promise<JournalEntry[]> {
const journalPath = this.getJournalPath(userId);
const content = await this.readFile(journalPath);
const entries = this.parseEntries(content);
return entries.slice(-count);
}
}
4. 平台适配器设计
4.1 适配器接口
interface PlatformAdapter {
// 平台元信息
getName(): string;
getVersion(): string;
// Spec 格式
getSpecFormat(): SpecFormat;
// 上下文注入
injectContext(context: InjectedContext): Promise<void>;
// 会话配置
getSessionConfig(): SessionConfig;
// 生命周期钩子
onSessionStart?(session: Session): Promise<void>;
onSessionEnd?(session: Session): Promise<void>;
}
4.2 Claude Code 适配器示例
class ClaudeCodeAdapter implements PlatformAdapter {
getName() { return 'Claude Code'; }
getVersion() { return '1.0.0'; }
getSpecFormat(): SpecFormat {
return {
type: 'markdown',
location: '.claude/CLAUDE.md',
format: 'full-file',
encoding: 'utf-8'
};
}
async injectContext(context: InjectedContext): Promise<void> {
const specPath = '.claude/CLAUDE.md';
// 读取现有内容(保留用户自定义部分)
const existing = await this.readExistingSpec(specPath);
// 组合 Trellis Spec
const combined = this.combineSpecs(existing, context.combined);
// 写入文件
await writeFile(specPath, combined);
}
private combineSpecs(existing: string, trellisSpec: string): string {
return `# Claude Code Spec (Managed by Trellis)
<!-- TRELLIS_MANAGED: DO NOT EDIT MANUALLY -->
${trellisSpec}
<!-- USER_CUSTOM: Your custom rules below -->
${existing}
`;
}
}
4.3 Cursor 适配器示例
class CursorAdapter implements PlatformAdapter {
getName() { return 'Cursor'; }
getSpecFormat(): SpecFormat {
return {
type: 'markdown',
location: '.cursor/rules.md',
format: 'rule-list',
encoding: 'utf-8'
};
}
async injectContext(context: InjectedContext): Promise<void> {
const rulesPath = '.cursor/rules.md';
// Cursor 规则格式转换
const rules = this.convertToRules(context.combined);
await writeFile(rulesPath, rules);
}
private convertToRules(markdown: string): string {
// 将 Markdown 转换为 Cursor 规则格式
// 例如:提取 ## 标题作为规则分类,### 作为具体规则
const lines = markdown.split('\n');
const rules: string[] = [];
for (const line of lines) {
if (line.startsWith('### ')) {
rules.push(`- ${line.replace('### ', '')}`);
}
}
return `# Cursor Rules (Generated by Trellis)\n\n${rules.join('\n')}`;
}
}
5. 实施路径
5.1 Phase 1: 基础架构(1-2 周)
目标:建立 Trellis 集成层的基础架构
任务:
- 设计模块接口和数据结构
- 实现 Spec Manager 基础功能
- 实现 Task Manager 基础功能
- 创建配置文件格式
- 编写单元测试
交付物:
trellis-integration/目录结构- 基础模块实现
- 配置 Schema 定义
5.2 Phase 2: Spec 注入(2-3 周)
目标:实现分层 Spec 的智能注入
任务:
- 实现 Spec 加载器
- 实现 Spec 选择策略
- 实现 Spec 组合器
- 开发 Claude Code 适配器
- 端到端测试
交付物:
- 可工作的 Spec 注入系统
- 至少 1 个平台适配器
- 集成测试用例
5.3 Phase 3: 任务管理(3-4 周)
目标:实现任务隔离和状态管理
任务:
- 实现任务状态机
- 实现任务上下文管理
- 实现 Journal 系统
- 开发 Cursor 适配器
- 性能优化
交付物:
- 完整的任务管理系统
- 2 个平台适配器
- 性能基准测试
5.4 Phase 4: 高级功能(4-6 周)
目标:实现 Git Worktree 集成和多平台支持
任务:
- 实现 Git Worktree 管理
- 开发更多平台适配器
- 实现任务并行执行
- 文档和示例
- Beta 测试
交付物:
- Git Worktree 集成
- 5+ 平台适配器
- 完整文档
6. 风险与缓解
6.1 技术风险
| 风险 | 可能性 | 影响 | 缓解措施 |
|---|---|---|---|
| pi-mono 扩展性不足 | 中 | 高 | 早期验证扩展点,准备 fork 方案 |
| Spec 注入性能问题 | 低 | 中 | 实现缓存机制,懒加载 |
| 平台 API 变化 | 中 | 中 | 适配器隔离,版本锁定 |
| Worktree 磁盘占用 | 高 | 低 | 按需创建,自动清理 |
6.2 非技术风险
| 风险 | 可能性 | 影响 | 缓解措施 |
|---|---|---|---|
| 学习曲线陡峭 | 高 | 中 | 渐进式文档,示例驱动 |
| 团队 adoption 低 | 中 | 中 | 早期参与,痛点驱动 |
| 维护成本高 | 中 | 高 | 模块化设计,社区贡献 |
7. 成功指标
7.1 技术指标
- Spec 注入延迟 < 100ms
- 支持 10+ 并发任务
- 新增平台适配器 < 1 天
- 代码覆盖率 > 80%
7.2 用户体验指标
- 新用户 30 分钟内完成首次配置
- 任务切换时间 < 1 分钟
- Journal 查找时间 < 5 分钟
- 用户满意度 > 4.5/5