kiro-spec-engine 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +172 -0
  3. package/bin/kiro-spec-engine.js +62 -0
  4. package/docs/adoption-guide.md +506 -0
  5. package/docs/agent-hooks-analysis.md +815 -0
  6. package/docs/architecture.md +706 -0
  7. package/docs/cross-tool-guide.md +554 -0
  8. package/docs/developer-guide.md +615 -0
  9. package/docs/manual-workflows-guide.md +417 -0
  10. package/docs/steering-strategy-guide.md +196 -0
  11. package/docs/upgrade-guide.md +632 -0
  12. package/lib/adoption/detection-engine.js +14 -4
  13. package/lib/commands/adopt.js +117 -3
  14. package/lib/commands/context.js +99 -0
  15. package/lib/commands/prompt.js +105 -0
  16. package/lib/commands/status.js +225 -0
  17. package/lib/commands/task.js +199 -0
  18. package/lib/commands/watch.js +569 -0
  19. package/lib/commands/workflows.js +240 -0
  20. package/lib/commands/workspace.js +189 -0
  21. package/lib/context/context-exporter.js +378 -0
  22. package/lib/context/prompt-generator.js +482 -0
  23. package/lib/steering/adoption-config.js +164 -0
  24. package/lib/steering/steering-manager.js +289 -0
  25. package/lib/task/task-claimer.js +430 -0
  26. package/lib/utils/tool-detector.js +383 -0
  27. package/lib/watch/action-executor.js +458 -0
  28. package/lib/watch/event-debouncer.js +323 -0
  29. package/lib/watch/execution-logger.js +550 -0
  30. package/lib/watch/file-watcher.js +499 -0
  31. package/lib/watch/presets.js +266 -0
  32. package/lib/watch/watch-manager.js +533 -0
  33. package/lib/workspace/workspace-manager.js +370 -0
  34. package/lib/workspace/workspace-sync.js +356 -0
  35. package/package.json +4 -1
  36. package/template/.kiro/tools/backup_manager.py +295 -0
  37. package/template/.kiro/tools/configuration_manager.py +218 -0
  38. package/template/.kiro/tools/document_evaluator.py +550 -0
  39. package/template/.kiro/tools/enhancement_logger.py +168 -0
  40. package/template/.kiro/tools/error_handler.py +335 -0
  41. package/template/.kiro/tools/improvement_identifier.py +444 -0
  42. package/template/.kiro/tools/modification_applicator.py +737 -0
  43. package/template/.kiro/tools/quality_gate_enforcer.py +207 -0
  44. package/template/.kiro/tools/quality_scorer.py +305 -0
  45. package/template/.kiro/tools/report_generator.py +154 -0
  46. package/template/.kiro/tools/ultrawork_enhancer_refactored.py +0 -0
  47. package/template/.kiro/tools/ultrawork_enhancer_v2.py +463 -0
  48. package/template/.kiro/tools/ultrawork_enhancer_v3.py +606 -0
  49. package/template/.kiro/tools/workflow_quality_gate.py +100 -0
@@ -0,0 +1,463 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Ultrawork Enhancer V2 - 模块化重构版本
4
+
5
+ 核心理念: 像西西弗斯推石上山一样,永不放弃,不懈努力,直到任务完美完成
6
+
7
+ 重构目标:
8
+ - 提取评估、识别、应用逻辑到独立的类
9
+ - 创建基础接口
10
+ - 保持现有功能不变
11
+ """
12
+
13
+ import os
14
+ from pathlib import Path
15
+ from typing import Dict, List, Optional
16
+ from dataclasses import dataclass, field
17
+
18
+ # 导入模块化组件
19
+ from document_evaluator import DocumentEvaluator, QualityAssessment
20
+ from improvement_identifier import ImprovementIdentifier, Improvement
21
+ from modification_applicator import ModificationApplicator, ModificationResult
22
+
23
+
24
+ @dataclass
25
+ class EnhancementResult:
26
+ """增强结果"""
27
+ success: bool
28
+ document_type: str # 'requirements', 'design', 'tasks'
29
+ initial_score: float
30
+ final_score: float
31
+ iterations: int
32
+ improvements_applied: List[Improvement] = field(default_factory=list)
33
+ improvements_failed: List = field(default_factory=list)
34
+ stopping_reason: str = ""
35
+ modification_report: str = ""
36
+ message: str = ""
37
+
38
+
39
+ class UltraworkEnhancer:
40
+ """
41
+ Ultrawork 增强器 V2 - 模块化架构
42
+
43
+ 使用独立的评估器、识别器和应用器组件
44
+ """
45
+
46
+ def __init__(self):
47
+ self.quality_threshold = 9.0 # 专业级质量标准 (0-10)
48
+ self.max_iterations = 10 # 防止无限循环
49
+ self.improvement_log = [] # 记录改进过程
50
+
51
+ # 初始化模块化组件
52
+ self.evaluator = DocumentEvaluator()
53
+ self.identifier = ImprovementIdentifier()
54
+ self.applicator = ModificationApplicator()
55
+
56
+ def enhance_requirements_quality(self, requirements_path: str) -> Dict:
57
+ """
58
+ Requirements 阶段的 Ultrawork 增强
59
+
60
+ 像资深产品经理一样深入思考每个用户场景
61
+ """
62
+ print("🔥 启动 Requirements 阶段 Ultrawork 增强...")
63
+
64
+ if not os.path.exists(requirements_path):
65
+ return {"error": "Requirements 文件不存在", "success": False}
66
+
67
+ with open(requirements_path, 'r', encoding='utf-8') as f:
68
+ content = f.read()
69
+
70
+ # 使用 DocumentEvaluator 评估质量
71
+ assessment = self.evaluator.assess_requirements_quality(content)
72
+ language = assessment.language
73
+
74
+ print(f"📝 检测到文档语言: {'中文' if language == 'zh' else 'English'}")
75
+ print(f"📊 Requirements 质量评分: {assessment.score}/10")
76
+
77
+ if assessment.score >= self.quality_threshold:
78
+ print("✅ Requirements 已达到专业级标准! Ultrawork 精神得到体现!")
79
+ return {
80
+ "success": True,
81
+ "iterations": 0,
82
+ "final_quality_score": assessment.score,
83
+ "message": "文档质量已达到专业级标准,无需进一步改进"
84
+ }
85
+
86
+ iteration = 0
87
+ original_content = content
88
+ quality_score = assessment.score
89
+
90
+ while iteration < self.max_iterations:
91
+ # 使用 ImprovementIdentifier 识别改进点
92
+ improvements = self.identifier.identify_requirements_improvements(content, assessment)
93
+
94
+ if not improvements:
95
+ print("⚠️ 无法识别更多改进点,停止迭代")
96
+ stopping_reason = "no_improvements"
97
+ break
98
+
99
+ # 使用 ModificationApplicator 应用改进
100
+ result = self.applicator.apply_requirements_improvements(content, improvements, language)
101
+ content = result.modified_content
102
+ iteration += 1
103
+
104
+ # 重新评估质量
105
+ assessment = self.evaluator.assess_requirements_quality(content)
106
+ new_quality_score = assessment.score
107
+
108
+ # 记录改进过程
109
+ self.improvement_log.append({
110
+ "stage": "requirements",
111
+ "iteration": iteration,
112
+ "improvements": [imp.description for imp in result.applied_improvements],
113
+ "quality_score": new_quality_score
114
+ })
115
+
116
+ print(f"🔄 第 {iteration} 轮改进: {', '.join([imp.description for imp in result.applied_improvements])}")
117
+ print(f"📊 改进后质量评分: {new_quality_score}/10")
118
+
119
+ # 检查是否达到质量标准
120
+ if new_quality_score >= self.quality_threshold:
121
+ print("✅ Requirements 已达到专业级标准!")
122
+ stopping_reason = "threshold_reached"
123
+ break
124
+
125
+ # 检查是否有实际改进
126
+ if new_quality_score <= quality_score:
127
+ print("⚠️ 质量评分未提升,停止迭代")
128
+ stopping_reason = "plateau"
129
+ break
130
+
131
+ quality_score = new_quality_score
132
+ else:
133
+ stopping_reason = "max_iterations"
134
+
135
+ # 如果有改进,更新文件
136
+ if content != original_content:
137
+ with open(requirements_path, 'w', encoding='utf-8') as f:
138
+ f.write(content)
139
+ print(f"📝 Requirements 已更新,共进行 {iteration} 轮 Ultrawork 改进")
140
+
141
+ final_assessment = self.evaluator.assess_requirements_quality(content)
142
+
143
+ return {
144
+ "success": True,
145
+ "iterations": iteration,
146
+ "initial_quality_score": quality_score,
147
+ "final_quality_score": final_assessment.score,
148
+ "stopping_reason": stopping_reason,
149
+ "improvements_applied": self.improvement_log
150
+ }
151
+
152
+ def enhance_design_completeness(self, design_path: str, requirements_path: str) -> Dict:
153
+ """
154
+ Design 阶段的 Ultrawork 增强
155
+
156
+ 像资深架构师一样设计每个组件
157
+ """
158
+ print("🔥 启动 Design 阶段 Ultrawork 增强...")
159
+
160
+ if not os.path.exists(design_path):
161
+ return {"error": "Design 文件不存在", "success": False}
162
+
163
+ if not os.path.exists(requirements_path):
164
+ return {"error": "Requirements 文件不存在,无法进行双向追溯", "success": False}
165
+
166
+ with open(design_path, 'r', encoding='utf-8') as f:
167
+ design_content = f.read()
168
+
169
+ with open(requirements_path, 'r', encoding='utf-8') as f:
170
+ requirements_content = f.read()
171
+
172
+ # 使用 DocumentEvaluator 评估质量
173
+ assessment = self.evaluator.assess_design_quality(design_content, requirements_content)
174
+ language = assessment.language
175
+
176
+ print(f"📝 检测到文档语言: {'中文' if language == 'zh' else 'English'}")
177
+ print(f"📊 Design 质量评分: {assessment.score}/10")
178
+
179
+ iteration = 0
180
+ original_content = design_content
181
+ quality_score = assessment.score
182
+
183
+ while iteration < self.max_iterations:
184
+ if quality_score >= self.quality_threshold:
185
+ print("✅ Design 已达到专业级标准!")
186
+ stopping_reason = "threshold_reached"
187
+ break
188
+
189
+ # 使用 ImprovementIdentifier 识别改进点
190
+ improvements = self.identifier.identify_design_improvements(design_content, requirements_content, assessment)
191
+
192
+ if not improvements:
193
+ print("⚠️ 无法识别更多改进点,停止迭代")
194
+ stopping_reason = "no_improvements"
195
+ break
196
+
197
+ # 使用 ModificationApplicator 应用改进
198
+ result = self.applicator.apply_design_improvements(design_content, improvements, requirements_content, language)
199
+ design_content = result.modified_content
200
+ iteration += 1
201
+
202
+ # 重新评估质量
203
+ assessment = self.evaluator.assess_design_quality(design_content, requirements_content)
204
+ new_quality_score = assessment.score
205
+
206
+ # 记录改进过程
207
+ self.improvement_log.append({
208
+ "stage": "design",
209
+ "iteration": iteration,
210
+ "improvements": [imp.description for imp in result.applied_improvements],
211
+ "quality_score": new_quality_score
212
+ })
213
+
214
+ print(f"🔄 第 {iteration} 轮改进: {', '.join([imp.description for imp in result.applied_improvements])}")
215
+ print(f"📊 改进后质量评分: {new_quality_score}/10")
216
+
217
+ # 检查是否有实际改进
218
+ if new_quality_score <= quality_score:
219
+ print("⚠️ 质量评分未提升,停止迭代")
220
+ stopping_reason = "plateau"
221
+ break
222
+
223
+ quality_score = new_quality_score
224
+ else:
225
+ stopping_reason = "max_iterations"
226
+
227
+ # 如果有改进,更新文件
228
+ if design_content != original_content:
229
+ with open(design_path, 'w', encoding='utf-8') as f:
230
+ f.write(design_content)
231
+ print(f"📝 Design 已更新,共进行 {iteration} 轮 Ultrawork 改进")
232
+
233
+ final_assessment = self.evaluator.assess_design_quality(design_content, requirements_content)
234
+
235
+ return {
236
+ "success": True,
237
+ "iterations": iteration,
238
+ "initial_quality_score": quality_score,
239
+ "final_quality_score": final_assessment.score,
240
+ "stopping_reason": stopping_reason,
241
+ "improvements_applied": self.improvement_log
242
+ }
243
+
244
+ def enhance_task_execution(self, tasks_path: str) -> Dict:
245
+ """
246
+ Tasks 阶段的 Ultrawork 增强
247
+
248
+ 像资深开发者一样实现每行代码,遇到困难不放弃
249
+ """
250
+ print("🔥 启动 Tasks 阶段 Ultrawork 增强...")
251
+
252
+ if not os.path.exists(tasks_path):
253
+ return {"error": "Tasks 文件不存在", "success": False}
254
+
255
+ with open(tasks_path, 'r', encoding='utf-8') as f:
256
+ content = f.read()
257
+
258
+ # 使用 DocumentEvaluator 评估任务完成情况
259
+ assessment = self.evaluator.assess_tasks_quality(content)
260
+
261
+ # 分析任务完成情况 (保持原有逻辑)
262
+ task_analysis = self._analyze_task_completion(content)
263
+
264
+ if task_analysis['incomplete_count'] == 0:
265
+ return {
266
+ "success": True,
267
+ "message": "✅ 所有任务已完成! Ultrawork 精神得到完美体现!",
268
+ "task_analysis": task_analysis
269
+ }
270
+
271
+ print(f"📋 任务完成情况分析:")
272
+ print(f" - 总任务数: {task_analysis['total_count']}")
273
+ print(f" - 已完成: {task_analysis['completed_count']}")
274
+ print(f" - 进行中: {task_analysis['in_progress_count']}")
275
+ print(f" - 未开始: {task_analysis['not_started_count']}")
276
+ print(f" - 完成率: {task_analysis['completion_rate']:.1f}%")
277
+
278
+ # Ultrawork 精神: 不懈努力提醒
279
+ ultrawork_messages = self._generate_ultrawork_reminders(task_analysis)
280
+
281
+ for message in ultrawork_messages:
282
+ print(f"🔥 {message}")
283
+
284
+ # 识别阻塞任务和优先级
285
+ priority_tasks = self._identify_priority_tasks(task_analysis['incomplete_tasks'])
286
+
287
+ return {
288
+ "success": True,
289
+ "message": f"发现 {task_analysis['incomplete_count']} 个未完成任务,需要继续推进",
290
+ "task_analysis": task_analysis,
291
+ "priority_tasks": priority_tasks,
292
+ "ultrawork_reminders": ultrawork_messages,
293
+ "next_actions": self._suggest_next_actions(task_analysis)
294
+ }
295
+
296
+ # 保持原有的辅助方法
297
+ def _analyze_task_completion(self, content: str) -> Dict:
298
+ """分析任务完成情况"""
299
+ import re
300
+
301
+ completed_tasks = re.findall(r'- \[x\] (.+)', content)
302
+ in_progress_tasks = re.findall(r'- \[-\] (.+)', content)
303
+ not_started_tasks = re.findall(r'- \[ \] (.+)', content)
304
+ queued_tasks = re.findall(r'- \[~\] (.+)', content)
305
+
306
+ total_count = len(completed_tasks) + len(in_progress_tasks) + len(not_started_tasks) + len(queued_tasks)
307
+ completed_count = len(completed_tasks)
308
+ incomplete_count = len(in_progress_tasks) + len(not_started_tasks) + len(queued_tasks)
309
+
310
+ completion_rate = (completed_count / total_count * 100) if total_count > 0 else 0
311
+
312
+ return {
313
+ "total_count": total_count,
314
+ "completed_count": completed_count,
315
+ "completed_tasks": completed_tasks,
316
+ "in_progress_count": len(in_progress_tasks),
317
+ "in_progress_tasks": in_progress_tasks,
318
+ "not_started_count": len(not_started_tasks),
319
+ "not_started_tasks": not_started_tasks,
320
+ "queued_count": len(queued_tasks),
321
+ "queued_tasks": queued_tasks,
322
+ "incomplete_count": incomplete_count,
323
+ "incomplete_tasks": in_progress_tasks + not_started_tasks + queued_tasks,
324
+ "completion_rate": completion_rate
325
+ }
326
+
327
+ def _generate_ultrawork_reminders(self, task_analysis: Dict) -> List[str]:
328
+ """生成 Ultrawork 精神提醒"""
329
+ reminders = []
330
+
331
+ completion_rate = task_analysis['completion_rate']
332
+
333
+ if completion_rate == 0:
334
+ reminders.append("Sisyphus 精神: 万事开头难,但永不放弃! 开始推动第一块石头!")
335
+ elif completion_rate < 30:
336
+ reminders.append("Sisyphus 精神: 石头刚开始滚动,保持动力,持续推进!")
337
+ elif completion_rate < 70:
338
+ reminders.append("Sisyphus 精神: 已经爬到半山腰,不能松懈,继续向山顶冲刺!")
339
+ elif completion_rate < 95:
340
+ reminders.append("Sisyphus 精神: 接近山顶了,最后的冲刺最关键,不懈努力!")
341
+ else:
342
+ reminders.append("Sisyphus 精神: 即将登顶,每个细节都要完美,追求卓越!")
343
+
344
+ if task_analysis['in_progress_count'] > 0:
345
+ reminders.append(f"有 {task_analysis['in_progress_count']} 个任务正在进行中,保持专注,逐个击破!")
346
+
347
+ if task_analysis['not_started_count'] > 3:
348
+ reminders.append("任务较多,但不要被数量吓倒,分解执行,每完成一个都是胜利!")
349
+
350
+ return reminders
351
+
352
+ def _identify_priority_tasks(self, incomplete_tasks: List[str]) -> List[Dict]:
353
+ """识别优先级任务"""
354
+ import re
355
+
356
+ priority_tasks = []
357
+
358
+ for i, task in enumerate(incomplete_tasks):
359
+ priority = "normal"
360
+ reasons = []
361
+
362
+ # 基于关键词判断优先级
363
+ high_priority_keywords = ['基础', '核心', '关键', '重要', '阻塞', '依赖']
364
+ urgent_keywords = ['紧急', '立即', '马上', '优先']
365
+
366
+ if any(keyword in task for keyword in high_priority_keywords):
367
+ priority = "high"
368
+ reasons.append("包含关键词")
369
+
370
+ if any(keyword in task for keyword in urgent_keywords):
371
+ priority = "urgent"
372
+ reasons.append("标记为紧急")
373
+
374
+ # 基于任务编号判断(假设编号小的更基础)
375
+ if re.match(r'^\d+\.\d+', task) and task.startswith(('1.', '2.')):
376
+ if priority == "normal":
377
+ priority = "high"
378
+ reasons.append("基础任务")
379
+
380
+ priority_tasks.append({
381
+ "task": task,
382
+ "priority": priority,
383
+ "reasons": reasons,
384
+ "index": i
385
+ })
386
+
387
+ # 按优先级排序
388
+ priority_order = {"urgent": 0, "high": 1, "normal": 2}
389
+ priority_tasks.sort(key=lambda x: priority_order[x["priority"]])
390
+
391
+ return priority_tasks
392
+
393
+ def _suggest_next_actions(self, task_analysis: Dict) -> List[str]:
394
+ """建议下一步行动"""
395
+ suggestions = []
396
+
397
+ if task_analysis['in_progress_count'] > 0:
398
+ suggestions.append("优先完成进行中的任务,避免任务切换成本")
399
+
400
+ if task_analysis['not_started_count'] > 0:
401
+ suggestions.append("从最基础或最重要的未开始任务开始")
402
+
403
+ if task_analysis['completion_rate'] < 50:
404
+ suggestions.append("建议专注于单个任务,避免并行过多任务")
405
+ else:
406
+ suggestions.append("可以考虑并行处理独立的任务以提高效率")
407
+
408
+ suggestions.append("每完成一个任务立即更新状态,保持进度可见性")
409
+ suggestions.append("遇到困难时体现 Ultrawork 精神: 不放弃,寻找替代方案")
410
+
411
+ return suggestions
412
+
413
+ # 通用工具方法
414
+ def get_improvement_log(self) -> List[Dict]:
415
+ """获取改进日志"""
416
+ return self.improvement_log
417
+
418
+ def reset_log(self):
419
+ """重置改进日志"""
420
+ self.improvement_log = []
421
+
422
+ def set_quality_threshold(self, threshold: float):
423
+ """设置质量阈值"""
424
+ self.quality_threshold = max(0.0, min(10.0, threshold))
425
+
426
+ def set_max_iterations(self, max_iter: int):
427
+ """设置最大迭代次数"""
428
+ self.max_iterations = max(1, min(100, max_iter))
429
+
430
+
431
+ def main():
432
+ """命令行工具入口"""
433
+ import sys
434
+
435
+ if len(sys.argv) < 2:
436
+ print("用法: python ultrawork_enhancer_v2.py <command> [args]")
437
+ print("命令:")
438
+ print(" requirements <path> - 增强 Requirements 文档质量")
439
+ print(" design <design_path> <requirements_path> - 增强 Design 文档完整性")
440
+ print(" tasks <path> - 检查 Tasks 完成情况")
441
+ return
442
+
443
+ enhancer = UltraworkEnhancer()
444
+ command = sys.argv[1]
445
+
446
+ if command == "requirements" and len(sys.argv) >= 3:
447
+ result = enhancer.enhance_requirements_quality(sys.argv[2])
448
+ print(f"结果: {result}")
449
+
450
+ elif command == "design" and len(sys.argv) >= 4:
451
+ result = enhancer.enhance_design_completeness(sys.argv[2], sys.argv[3])
452
+ print(f"结果: {result}")
453
+
454
+ elif command == "tasks" and len(sys.argv) >= 3:
455
+ result = enhancer.enhance_task_execution(sys.argv[2])
456
+ print(f"结果: {result}")
457
+
458
+ else:
459
+ print("❌ 无效的命令或参数")
460
+
461
+
462
+ if __name__ == "__main__":
463
+ main()