goal_models.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """
  2. Goal 数据模型
  3. Goal: 执行计划中的目标节点
  4. GoalTree: 目标树,管理整个执行计划
  5. GoalStats: 目标统计信息
  6. """
  7. from dataclasses import dataclass, field
  8. from datetime import datetime
  9. from typing import Dict, Any, List, Optional, Literal
  10. import json
  11. # Goal 状态
  12. GoalStatus = Literal["pending", "in_progress", "completed", "abandoned"]
  13. # Goal 类型
  14. GoalType = Literal["normal", "agent_call"]
  15. @dataclass
  16. class GoalStats:
  17. """目标统计信息"""
  18. message_count: int = 0 # 消息数量
  19. total_tokens: int = 0 # Token 总数
  20. total_cost: float = 0.0 # 总成本
  21. preview: Optional[str] = None # 工具调用摘要,如 "read_file → edit_file → bash"
  22. def to_dict(self) -> Dict[str, Any]:
  23. return {
  24. "message_count": self.message_count,
  25. "total_tokens": self.total_tokens,
  26. "total_cost": self.total_cost,
  27. "preview": self.preview,
  28. }
  29. @classmethod
  30. def from_dict(cls, data: Dict[str, Any]) -> "GoalStats":
  31. return cls(
  32. message_count=data.get("message_count", 0),
  33. total_tokens=data.get("total_tokens", 0),
  34. total_cost=data.get("total_cost", 0.0),
  35. preview=data.get("preview"),
  36. )
  37. @dataclass
  38. class Goal:
  39. """
  40. 执行目标
  41. 使用扁平列表 + parent_id 构建层级结构。
  42. agent_call 类型用于标记启动了 Sub-Trace 的 Goal。
  43. """
  44. id: str # 内部唯一 ID,纯自增("1", "2", "3"...)
  45. description: str # 目标描述
  46. reason: str = "" # 创建理由(为什么做)
  47. parent_id: Optional[str] = None # 父 Goal ID(层级关系)
  48. type: GoalType = "normal" # Goal 类型
  49. status: GoalStatus = "pending" # 状态
  50. summary: Optional[str] = None # 完成/放弃时的总结
  51. # agent_call 特有
  52. sub_trace_ids: Optional[List[Dict[str, str]]] = None # 启动的 Sub-Trace 信息 [{"trace_id": "...", "mission": "..."}]
  53. agent_call_mode: Optional[str] = None # "explore" | "delegate" | "sequential"
  54. sub_trace_metadata: Optional[Dict[str, Dict[str, Any]]] = None # Sub-Trace 元数据
  55. # 统计(后端维护,用于可视化边的数据)
  56. self_stats: GoalStats = field(default_factory=GoalStats) # 自身统计(仅直接关联的 messages)
  57. cumulative_stats: GoalStats = field(default_factory=GoalStats) # 累计统计(自身 + 所有后代)
  58. created_at: datetime = field(default_factory=datetime.now)
  59. def to_dict(self) -> Dict[str, Any]:
  60. """转换为字典"""
  61. return {
  62. "id": self.id,
  63. "description": self.description,
  64. "reason": self.reason,
  65. "parent_id": self.parent_id,
  66. "type": self.type,
  67. "status": self.status,
  68. "summary": self.summary,
  69. "sub_trace_ids": self.sub_trace_ids,
  70. "agent_call_mode": self.agent_call_mode,
  71. "sub_trace_metadata": self.sub_trace_metadata,
  72. "self_stats": self.self_stats.to_dict(),
  73. "cumulative_stats": self.cumulative_stats.to_dict(),
  74. "created_at": self.created_at.isoformat() if self.created_at else None,
  75. }
  76. @classmethod
  77. def from_dict(cls, data: Dict[str, Any]) -> "Goal":
  78. """从字典创建"""
  79. created_at = data.get("created_at")
  80. if isinstance(created_at, str):
  81. created_at = datetime.fromisoformat(created_at)
  82. self_stats = data.get("self_stats", {})
  83. if isinstance(self_stats, dict):
  84. self_stats = GoalStats.from_dict(self_stats)
  85. cumulative_stats = data.get("cumulative_stats", {})
  86. if isinstance(cumulative_stats, dict):
  87. cumulative_stats = GoalStats.from_dict(cumulative_stats)
  88. return cls(
  89. id=data["id"],
  90. description=data["description"],
  91. reason=data.get("reason", ""),
  92. parent_id=data.get("parent_id"),
  93. type=data.get("type", "normal"),
  94. status=data.get("status", "pending"),
  95. summary=data.get("summary"),
  96. sub_trace_ids=data.get("sub_trace_ids"),
  97. agent_call_mode=data.get("agent_call_mode"),
  98. sub_trace_metadata=data.get("sub_trace_metadata"),
  99. self_stats=self_stats,
  100. cumulative_stats=cumulative_stats,
  101. created_at=created_at or datetime.now(),
  102. )
  103. @dataclass
  104. class GoalTree:
  105. """
  106. 目标树 - 管理整个执行计划
  107. 使用扁平列表 + parent_id 构建层级结构
  108. """
  109. mission: str # 总任务描述
  110. goals: List[Goal] = field(default_factory=list) # 扁平列表(通过 parent_id 构建层级)
  111. current_id: Optional[str] = None # 当前焦点 goal ID
  112. _next_id: int = 1 # 内部 ID 计数器(私有字段)
  113. created_at: datetime = field(default_factory=datetime.now)
  114. def find(self, goal_id: str) -> Optional[Goal]:
  115. """按 ID 查找 Goal"""
  116. for goal in self.goals:
  117. if goal.id == goal_id:
  118. return goal
  119. return None
  120. def find_by_display_id(self, display_id: str) -> Optional[Goal]:
  121. """按显示 ID 查找 Goal(如 "1", "2.1", "2.2")"""
  122. for goal in self.goals:
  123. if self._generate_display_id(goal) == display_id:
  124. return goal
  125. return None
  126. def find_parent(self, goal_id: str) -> Optional[Goal]:
  127. """查找指定 Goal 的父节点"""
  128. goal = self.find(goal_id)
  129. if not goal or not goal.parent_id:
  130. return None
  131. return self.find(goal.parent_id)
  132. def get_children(self, parent_id: Optional[str]) -> List[Goal]:
  133. """获取指定父节点的所有子节点"""
  134. return [g for g in self.goals if g.parent_id == parent_id]
  135. def get_current(self) -> Optional[Goal]:
  136. """获取当前焦点 Goal"""
  137. if self.current_id:
  138. return self.find(self.current_id)
  139. return None
  140. def _generate_id(self) -> str:
  141. """生成新的 Goal ID(纯自增)"""
  142. new_id = str(self._next_id)
  143. self._next_id += 1
  144. return new_id
  145. def _generate_display_id(self, goal: Goal) -> str:
  146. """生成显示序号(1, 2, 2.1, 2.2...)"""
  147. if not goal.parent_id:
  148. # 顶层目标:找到在同级中的序号
  149. siblings = [g for g in self.goals if g.parent_id is None and g.status != "abandoned"]
  150. try:
  151. index = [g.id for g in siblings].index(goal.id) + 1
  152. return str(index)
  153. except ValueError:
  154. return "?"
  155. else:
  156. # 子目标:父序号 + "." + 在同级中的序号
  157. parent = self.find(goal.parent_id)
  158. if not parent:
  159. return "?"
  160. parent_display = self._generate_display_id(parent)
  161. siblings = [g for g in self.goals if g.parent_id == goal.parent_id and g.status != "abandoned"]
  162. try:
  163. index = [g.id for g in siblings].index(goal.id) + 1
  164. return f"{parent_display}.{index}"
  165. except ValueError:
  166. return f"{parent_display}.?"
  167. def add_goals(
  168. self,
  169. descriptions: List[str],
  170. reasons: Optional[List[str]] = None,
  171. parent_id: Optional[str] = None
  172. ) -> List[Goal]:
  173. """
  174. 添加目标
  175. 如果 parent_id 为 None,添加到顶层
  176. 如果 parent_id 有值,添加为该 goal 的子目标
  177. """
  178. if parent_id:
  179. parent = self.find(parent_id)
  180. if not parent:
  181. raise ValueError(f"Parent goal not found: {parent_id}")
  182. # 创建新目标
  183. new_goals = []
  184. for i, desc in enumerate(descriptions):
  185. goal_id = self._generate_id()
  186. reason = reasons[i] if reasons and i < len(reasons) else ""
  187. goal = Goal(
  188. id=goal_id,
  189. description=desc.strip(),
  190. reason=reason,
  191. parent_id=parent_id
  192. )
  193. self.goals.append(goal)
  194. new_goals.append(goal)
  195. return new_goals
  196. def add_goals_after(
  197. self,
  198. target_id: str,
  199. descriptions: List[str],
  200. reasons: Optional[List[str]] = None
  201. ) -> List[Goal]:
  202. """
  203. 在指定 Goal 后面添加兄弟节点
  204. 新创建的 goals 与 target 有相同的 parent_id,
  205. 并插入到 goals 列表中 target 的后面。
  206. """
  207. target = self.find(target_id)
  208. if not target:
  209. raise ValueError(f"Target goal not found: {target_id}")
  210. # 创建新 goals(parent_id 与 target 相同)
  211. new_goals = []
  212. for i, desc in enumerate(descriptions):
  213. goal_id = self._generate_id()
  214. reason = reasons[i] if reasons and i < len(reasons) else ""
  215. goal = Goal(
  216. id=goal_id,
  217. description=desc.strip(),
  218. reason=reason,
  219. parent_id=target.parent_id # 同层级
  220. )
  221. new_goals.append(goal)
  222. # 插入到 target 后面(调整 goals 列表顺序)
  223. target_index = self.goals.index(target)
  224. for i, goal in enumerate(new_goals):
  225. self.goals.insert(target_index + 1 + i, goal)
  226. return new_goals
  227. def focus(self, goal_id: str) -> Goal:
  228. """切换焦点到指定 Goal,并将其状态设为 in_progress"""
  229. goal = self.find(goal_id)
  230. if not goal:
  231. raise ValueError(f"Goal not found: {goal_id}")
  232. # 更新状态
  233. if goal.status == "pending":
  234. goal.status = "in_progress"
  235. self.current_id = goal_id
  236. return goal
  237. def complete(self, goal_id: str, summary: str, clear_focus: bool = True) -> Goal:
  238. """
  239. 完成指定 Goal
  240. Args:
  241. goal_id: 要完成的目标 ID
  242. summary: 完成总结
  243. clear_focus: 如果完成的是当前焦点,是否清除焦点(默认 True)
  244. """
  245. goal = self.find(goal_id)
  246. if not goal:
  247. raise ValueError(f"Goal not found: {goal_id}")
  248. goal.status = "completed"
  249. goal.summary = summary
  250. # 如果完成的是当前焦点,根据参数决定是否清除焦点
  251. if clear_focus and self.current_id == goal_id:
  252. self.current_id = None
  253. # 检查是否所有兄弟都完成了,如果是则自动完成父节点
  254. if goal.parent_id:
  255. siblings = self.get_children(goal.parent_id)
  256. all_completed = all(g.status == "completed" for g in siblings)
  257. if all_completed:
  258. parent = self.find(goal.parent_id)
  259. if parent and parent.status != "completed":
  260. # 自动级联完成父节点
  261. parent.status = "completed"
  262. if not parent.summary:
  263. parent.summary = "所有子目标已完成"
  264. return goal
  265. def abandon(self, goal_id: str, reason: str) -> Goal:
  266. """放弃指定 Goal"""
  267. goal = self.find(goal_id)
  268. if not goal:
  269. raise ValueError(f"Goal not found: {goal_id}")
  270. goal.status = "abandoned"
  271. goal.summary = reason
  272. # 如果放弃的是当前焦点,清除焦点
  273. if self.current_id == goal_id:
  274. self.current_id = None
  275. return goal
  276. def to_prompt(self, include_abandoned: bool = False, include_summary: bool = False) -> str:
  277. """
  278. 格式化为 Prompt 注入文本
  279. Args:
  280. include_abandoned: 是否包含已废弃的目标
  281. include_summary: 是否显示 completed/abandoned goals 的 summary 详情
  282. False(默认)= 精简视图,用于日常周期性注入
  283. True = 完整视图(含 summary),用于压缩时提供上下文
  284. 展示策略:
  285. - 过滤掉 abandoned 目标(除非明确要求)
  286. - 完整展示所有顶层目标
  287. - 完整展示当前 focus 目标的父链及其所有子孙
  288. - 其他分支的子目标折叠显示(只显示数量和状态)
  289. - include_summary=True 时不折叠,全部展开并显示 summary
  290. """
  291. lines = []
  292. lines.append(f"**Mission**: {self.mission}")
  293. if self.current_id:
  294. current = self.find(self.current_id)
  295. if current:
  296. display_id = self._generate_display_id(current)
  297. lines.append(f"**Current**: {display_id} {current.description}")
  298. lines.append("")
  299. lines.append("**Progress**:")
  300. # 获取当前焦点的祖先链(从根到当前节点的路径)
  301. current_path = set()
  302. if self.current_id:
  303. goal = self.find(self.current_id)
  304. while goal:
  305. current_path.add(goal.id)
  306. if goal.parent_id:
  307. goal = self.find(goal.parent_id)
  308. else:
  309. break
  310. def format_goal(goal: Goal, indent: int = 0) -> List[str]:
  311. # 跳过废弃的目标(除非明确要求包含)
  312. if goal.status == "abandoned" and not include_abandoned:
  313. return []
  314. prefix = " " * indent
  315. # 状态图标
  316. if goal.status == "completed":
  317. icon = "[✓]"
  318. elif goal.status == "in_progress":
  319. icon = "[→]"
  320. elif goal.status == "abandoned":
  321. icon = "[✗]"
  322. else:
  323. icon = "[ ]"
  324. # 生成显示序号
  325. display_id = self._generate_display_id(goal)
  326. # 当前焦点标记
  327. current_mark = " ← current" if goal.id == self.current_id else ""
  328. result = [f"{prefix}{icon} {display_id}. {goal.description}{current_mark}"]
  329. # 显示 summary:include_summary=True 时全部显示,否则只在焦点路径上显示
  330. if goal.summary and (include_summary or goal.id in current_path):
  331. result.append(f"{prefix} → {goal.summary}")
  332. # 递归处理子目标
  333. children = self.get_children(goal.id)
  334. # include_summary 模式下不折叠,全部展开
  335. if include_summary:
  336. for child in children:
  337. result.extend(format_goal(child, indent + 1))
  338. return result
  339. # 判断是否需要折叠
  340. # 如果当前 goal 或其子孙在焦点路径上,完整展示
  341. should_expand = goal.id in current_path or any(
  342. child.id in current_path for child in self._get_all_descendants(goal.id)
  343. )
  344. if should_expand or not children:
  345. # 完整展示子目标
  346. for child in children:
  347. result.extend(format_goal(child, indent + 1))
  348. else:
  349. # 折叠显示:只显示子目标的统计
  350. non_abandoned = [c for c in children if c.status != "abandoned"]
  351. if non_abandoned:
  352. completed = sum(1 for c in non_abandoned if c.status == "completed")
  353. in_progress = sum(1 for c in non_abandoned if c.status == "in_progress")
  354. pending = sum(1 for c in non_abandoned if c.status == "pending")
  355. status_parts = []
  356. if completed > 0:
  357. status_parts.append(f"{completed} completed")
  358. if in_progress > 0:
  359. status_parts.append(f"{in_progress} in progress")
  360. if pending > 0:
  361. status_parts.append(f"{pending} pending")
  362. status_str = ", ".join(status_parts)
  363. result.append(f"{prefix} ({len(non_abandoned)} subtasks: {status_str})")
  364. return result
  365. # 处理所有顶层目标
  366. top_goals = self.get_children(None)
  367. for goal in top_goals:
  368. lines.extend(format_goal(goal))
  369. return "\n".join(lines)
  370. def _get_all_descendants(self, goal_id: str) -> List[Goal]:
  371. """获取指定 Goal 的所有子孙节点"""
  372. descendants = []
  373. children = self.get_children(goal_id)
  374. for child in children:
  375. descendants.append(child)
  376. descendants.extend(self._get_all_descendants(child.id))
  377. return descendants
  378. def to_dict(self) -> Dict[str, Any]:
  379. """转换为字典"""
  380. return {
  381. "mission": self.mission,
  382. "goals": [g.to_dict() for g in self.goals],
  383. "current_id": self.current_id,
  384. "_next_id": self._next_id,
  385. "created_at": self.created_at.isoformat() if self.created_at else None,
  386. }
  387. @classmethod
  388. def from_dict(cls, data: Dict[str, Any]) -> "GoalTree":
  389. """从字典创建"""
  390. goals = [Goal.from_dict(g) for g in data.get("goals", [])]
  391. created_at = data.get("created_at")
  392. if isinstance(created_at, str):
  393. created_at = datetime.fromisoformat(created_at)
  394. return cls(
  395. mission=data["mission"],
  396. goals=goals,
  397. current_id=data.get("current_id"),
  398. _next_id=data.get("_next_id", 1),
  399. created_at=created_at or datetime.now(),
  400. )
  401. def rebuild_for_rewind(self, cutoff_time: datetime) -> "GoalTree":
  402. """
  403. 为 Rewind 重建干净的 GoalTree
  404. 以截断点消息的 created_at 为界:
  405. - 保留 created_at <= cutoff_time 的所有 goals(无论状态)
  406. - 丢弃 cutoff_time 之后创建的 goals
  407. - 将被保留的 in_progress goals 重置为 pending
  408. - 清空 current_id,让 Agent 重新选择焦点
  409. Args:
  410. cutoff_time: 截断点消息的创建时间
  411. Returns:
  412. 新的干净 GoalTree
  413. """
  414. surviving_goals = []
  415. for goal in self.goals:
  416. if goal.created_at <= cutoff_time:
  417. surviving_goals.append(goal)
  418. # 清理 parent_id 引用:如果 parent 不在存活列表中,设为 None
  419. surviving_ids = {g.id for g in surviving_goals}
  420. for goal in surviving_goals:
  421. if goal.parent_id and goal.parent_id not in surviving_ids:
  422. goal.parent_id = None
  423. # 将 in_progress 重置为 pending(回溯后需要重新执行)
  424. if goal.status == "in_progress":
  425. goal.status = "pending"
  426. new_tree = GoalTree(
  427. mission=self.mission,
  428. goals=surviving_goals,
  429. current_id=None,
  430. _next_id=self._next_id,
  431. created_at=self.created_at,
  432. )
  433. return new_tree
  434. def save(self, path: str) -> None:
  435. """保存到 JSON 文件"""
  436. with open(path, "w", encoding="utf-8") as f:
  437. json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
  438. @classmethod
  439. def load(cls, path: str) -> "GoalTree":
  440. """从 JSON 文件加载"""
  441. with open(path, "r", encoding="utf-8") as f:
  442. data = json.load(f)
  443. return cls.from_dict(data)