state_manager.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/env python3
  2. # .aceflow/scripts/state_manager.py
  3. """
  4. AceFlow 状态管理器
  5. 用于更新和查询流程状态。
  6. """
  7. import json
  8. import sys
  9. from datetime import datetime
  10. from pathlib import Path
  11. from typing import Dict, Any, Optional
  12. class StateManager:
  13. """管理 state.json 文件的类"""
  14. def __init__(self, state_file: Path = Path(".aceflow/state.json")):
  15. self.state_file = state_file
  16. if not self.state_file.exists():
  17. print(f"❌ 错误: 状态文件不存在于 {self.state_file}")
  18. print("请先运行 'python .aceflow/scripts/init.py'")
  19. sys.exit(1)
  20. self.state = self._load_state()
  21. def _load_state(self) -> Dict[str, Any]:
  22. """加载状态文件"""
  23. return json.loads(self.state_file.read_text(encoding='utf-8'))
  24. def _save_state(self):
  25. """保存状态文件"""
  26. self.state['updated_at'] = datetime.now().isoformat()
  27. self.state_file.write_text(json.dumps(self.state, indent=2, ensure_ascii=False), encoding='utf-8')
  28. def update_stage(self, stage: str, progress: int):
  29. """更新当前阶段和进度"""
  30. self.state['current_stage'] = stage
  31. self.state['progress'] = progress
  32. self.state['status'] = 'in_progress' if progress < 100 else 'completed'
  33. if progress == 100 and stage not in self.state.get('completed_stages', []):
  34. self.state.setdefault('completed_stages', []).append(stage)
  35. self._save_state()
  36. print(f"✅ 状态更新 -> 阶段: {stage}, 进度: {progress}%")
  37. def add_memory_ref(self, memory_id: str):
  38. """添加记忆引用"""
  39. self.state.setdefault('memory_refs', []).append(memory_id)
  40. self._save_state()
  41. print(f"✅ 添加记忆引用: {memory_id}")
  42. def update_metrics(self, **kwargs):
  43. """更新指标"""
  44. self.state.setdefault('metrics', {}).update(kwargs)
  45. self._save_state()
  46. print(f"✅ 更新指标: {kwargs}")
  47. def print_status(self):
  48. """打印当前状态"""
  49. print("\n📊 AceFlow 当前状态")
  50. print("="*40)
  51. for key, value in self.state.items():
  52. if isinstance(value, list) and value:
  53. print(f"- {key.replace('_', ' ').title()}: {', '.join(map(str, value))}")
  54. elif isinstance(value, dict):
  55. print(f"- {key.replace('_', ' ').title()}:")
  56. for sub_key, sub_value in value.items():
  57. print(f" - {sub_key}: {sub_value}")
  58. else:
  59. print(f"- {key.replace('_', ' ').title()}: {value}")
  60. print("="*40)
  61. def main():
  62. """命令行接口"""
  63. manager = StateManager()
  64. if len(sys.argv) < 2 or sys.argv[1] not in ['status', 'update', 'memory', 'metric']:
  65. print("用法: python state_manager.py <command> [args]")
  66. print("命令:")
  67. print(" status - 显示当前状态")
  68. print(" update <stage> <progress> - 更新阶段进度 (e.g., S1 100)")
  69. print(" memory <memory_id> - 添加记忆引用 (e.g., REQ-001)")
  70. print(" metric <key> <value> - 更新指标 (e.g., total_tasks 15)")
  71. sys.exit(1)
  72. command = sys.argv[1]
  73. if command == "status":
  74. manager.print_status()
  75. elif command == "update":
  76. if len(sys.argv) != 4:
  77. print("错误: 'update' 命令需要 <stage> 和 <progress> 参数。")
  78. sys.exit(1)
  79. manager.update_stage(sys.argv[2], int(sys.argv[3]))
  80. elif command == "memory":
  81. if len(sys.argv) != 3:
  82. print("错误: 'memory' 命令需要 <memory_id> 参数。")
  83. sys.exit(1)
  84. manager.add_memory_ref(sys.argv[2])
  85. elif command == "metric":
  86. if len(sys.argv) != 4:
  87. print("错误: 'metric' 命令需要 <key> 和 <value> 参数。")
  88. sys.exit(1)
  89. key, value_str = sys.argv[2], sys.argv[3]
  90. try:
  91. value = float(value_str) if '.' in value_str else int(value_str)
  92. except ValueError:
  93. value = value_str
  94. manager.update_metrics(**{key: value})
  95. if __name__ == "__main__":
  96. main()