pdd-skills 3.0.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 (261) hide show
  1. package/README.md +1478 -0
  2. package/bin/pdd.js +354 -0
  3. package/config/bpmn-rules.yaml +166 -0
  4. package/config/checkstyle.xml +105 -0
  5. package/config/eslint.config.js +48 -0
  6. package/config/pmd.xml +91 -0
  7. package/config/prd-rules.yaml +113 -0
  8. package/config/ruff.toml +45 -0
  9. package/config/sqlfluff.cfg +82 -0
  10. package/hooks/hook-executor.js +332 -0
  11. package/index.js +43 -0
  12. package/lib/api-routes.js +750 -0
  13. package/lib/api-server.js +408 -0
  14. package/lib/cache/cache-config.js +209 -0
  15. package/lib/cache/system-cache.js +852 -0
  16. package/lib/config-manager.js +373 -0
  17. package/lib/generate.js +528 -0
  18. package/lib/grpc/grpc-routes.js +1134 -0
  19. package/lib/grpc/grpc-server.js +912 -0
  20. package/lib/grpc/proto-definitions.js +1033 -0
  21. package/lib/init.js +172 -0
  22. package/lib/iteration/auto-fixer.js +1025 -0
  23. package/lib/iteration/auto-reviewer.js +923 -0
  24. package/lib/iteration/controller.js +577 -0
  25. package/lib/list.js +130 -0
  26. package/lib/mcp-server.js +548 -0
  27. package/lib/openclaw/api-integration.js +535 -0
  28. package/lib/openclaw/cli-integration.js +567 -0
  29. package/lib/openclaw/data-sync.js +845 -0
  30. package/lib/openclaw/openclaw-adapter.js +783 -0
  31. package/lib/plugin/example-plugins/code-stats/index.js +332 -0
  32. package/lib/plugin/example-plugins/code-stats/plugin.json +1 -0
  33. package/lib/plugin/example-plugins/custom-linter/index.js +472 -0
  34. package/lib/plugin/example-plugins/custom-linter/plugin.json +1 -0
  35. package/lib/plugin/example-plugins/hello-world/index.js +86 -0
  36. package/lib/plugin/example-plugins/hello-world/plugin.json +1 -0
  37. package/lib/plugin/plugin-manager.js +655 -0
  38. package/lib/plugin/plugin-sdk.js +565 -0
  39. package/lib/plugin/sandbox.js +627 -0
  40. package/lib/quality/rules/maintainability.js +418 -0
  41. package/lib/quality/rules/performance.js +498 -0
  42. package/lib/quality/rules/readability.js +441 -0
  43. package/lib/quality/rules/robustness.js +504 -0
  44. package/lib/quality/rules/security.js +444 -0
  45. package/lib/quality/scorer.js +576 -0
  46. package/lib/report.js +669 -0
  47. package/lib/sdk-base.js +301 -0
  48. package/lib/sdk-js.js +446 -0
  49. package/lib/sdk-python/README.md +546 -0
  50. package/lib/sdk-python/examples/basic_usage.py +450 -0
  51. package/lib/sdk-python/pdd_sdk/__init__.py +180 -0
  52. package/lib/sdk-python/pdd_sdk/client.py +1170 -0
  53. package/lib/sdk-python/pdd_sdk/events.py +423 -0
  54. package/lib/sdk-python/pdd_sdk/exceptions.py +158 -0
  55. package/lib/sdk-python/pdd_sdk/models.py +518 -0
  56. package/lib/sdk-python/pdd_sdk/utils.py +759 -0
  57. package/lib/token/budget-alert.js +367 -0
  58. package/lib/token/budget-manager.js +485 -0
  59. package/lib/update.js +54 -0
  60. package/lib/utils/logger.js +88 -0
  61. package/lib/verify.js +741 -0
  62. package/lib/version.js +52 -0
  63. package/lib/vm/README.md +102 -0
  64. package/lib/vm/dashboard/api-routes.js +669 -0
  65. package/lib/vm/dashboard/server.js +391 -0
  66. package/lib/vm/dashboard/sse.js +358 -0
  67. package/lib/vm/dashboard/static/css/dashboard.css +1378 -0
  68. package/lib/vm/dashboard/static/index.html +118 -0
  69. package/lib/vm/dashboard/static/js/app.js +949 -0
  70. package/lib/vm/dashboard/static/js/charts.js +913 -0
  71. package/lib/vm/dashboard/static/js/kanban-view.js +1053 -0
  72. package/lib/vm/dashboard/static/js/pipeline-view.js +463 -0
  73. package/lib/vm/dashboard/static/js/quality-view.js +598 -0
  74. package/lib/vm/dashboard/static/js/system-view.js +1021 -0
  75. package/lib/vm/data-provider.js +1191 -0
  76. package/lib/vm/event-bus.js +402 -0
  77. package/lib/vm/hooks/extract-hook.js +307 -0
  78. package/lib/vm/hooks/generate-hook.js +374 -0
  79. package/lib/vm/hooks/hook-interface.js +458 -0
  80. package/lib/vm/hooks/report-hook.js +331 -0
  81. package/lib/vm/hooks/verify-hook.js +454 -0
  82. package/lib/vm/models.js +1003 -0
  83. package/lib/vm/reconciler.js +855 -0
  84. package/lib/vm/scanner.js +988 -0
  85. package/lib/vm/state-schema.js +955 -0
  86. package/lib/vm/state-store.js +733 -0
  87. package/lib/vm/tui/components/card.js +339 -0
  88. package/lib/vm/tui/components/progress-bar.js +368 -0
  89. package/lib/vm/tui/components/sparkline.js +327 -0
  90. package/lib/vm/tui/components/status-light.js +294 -0
  91. package/lib/vm/tui/components/table.js +370 -0
  92. package/lib/vm/tui/input.js +335 -0
  93. package/lib/vm/tui/renderer.js +548 -0
  94. package/lib/vm/tui/screens/kanban-screen.js +397 -0
  95. package/lib/vm/tui/screens/overview-screen.js +357 -0
  96. package/lib/vm/tui/screens/quality-screen.js +336 -0
  97. package/lib/vm/tui/screens/system-screen.js +379 -0
  98. package/lib/vm/tui/tui.js +805 -0
  99. package/package.json +1 -0
  100. package/scripts/cso-analyzer.js +198 -0
  101. package/scripts/eval-runner.js +359 -0
  102. package/scripts/i18n-checker.js +109 -0
  103. package/scripts/linter/activiti-linter.js +272 -0
  104. package/scripts/linter/prd-linter.js +162 -0
  105. package/scripts/linter/report-generator.js +207 -0
  106. package/scripts/linter/run-linters.js +285 -0
  107. package/scripts/linter/sql-linter.js +166 -0
  108. package/scripts/token-analyzer.js +162 -0
  109. package/scripts/vm-test.js +180 -0
  110. package/skills/core/official-doc-writer/LICENSE +21 -0
  111. package/skills/core/official-doc-writer/README.md +232 -0
  112. package/skills/core/official-doc-writer/SKILL.md +475 -0
  113. package/skills/core/official-doc-writer/_meta.json +1 -0
  114. package/skills/core/official-doc-writer/document_generator.py +580 -0
  115. package/skills/core/official-doc-writer/evals/default-evals.json +1 -0
  116. package/skills/core/official-doc-writer/examples.md +150 -0
  117. package/skills/core/official-doc-writer/fonts/FONTS_LIST.md +45 -0
  118. package/skills/core/official-doc-writer/fonts/README.md +141 -0
  119. package/skills/core/official-doc-writer/fonts/SIMFANG.TTF +0 -0
  120. package/skills/core/official-doc-writer/fonts/SIMHEI.TTF +0 -0
  121. package/skills/core/official-doc-writer/fonts/SIMKAI.TTF +0 -0
  122. package/skills/core/official-doc-writer/fonts/SIMSUN.TTC +0 -0
  123. package/skills/core/official-doc-writer/fonts//346/226/271/346/255/243/345/260/217/346/240/207/345/256/213GBK.TTF +0 -0
  124. package/skills/core/official-doc-writer/references/GBT_9704-2012_/345/205/232/346/224/277/346/234/272/345/205/263/345/205/254/346/226/207/346/240/274/345/274/217.md +422 -0
  125. package/skills/core/official-doc-writer/scripts/__pycache__/generate_official_doc.cpython-313.pyc +0 -0
  126. package/skills/core/official-doc-writer/scripts/dialog_manager.py +564 -0
  127. package/skills/core/official-doc-writer/scripts/generate_official_doc.py +252 -0
  128. package/skills/core/official-doc-writer/scripts/install_fonts.py +390 -0
  129. package/skills/core/official-doc-writer/scripts/smart_prompts.py +363 -0
  130. package/skills/core/pdd-ba/SKILL.md +305 -0
  131. package/skills/core/pdd-ba/_meta.json +1 -0
  132. package/skills/core/pdd-ba/evals/default-evals.json +1 -0
  133. package/skills/core/pdd-code-reviewer/SKILL.md +378 -0
  134. package/skills/core/pdd-code-reviewer/_meta.json +1 -0
  135. package/skills/core/pdd-code-reviewer/evals/default-evals.json +1 -0
  136. package/skills/core/pdd-doc-change/SKILL.md +350 -0
  137. package/skills/core/pdd-doc-change/_meta.json +1 -0
  138. package/skills/core/pdd-doc-change/evals/default-evals.json +1 -0
  139. package/skills/core/pdd-doc-gardener/SKILL.md +248 -0
  140. package/skills/core/pdd-doc-gardener/_meta.json +1 -0
  141. package/skills/core/pdd-doc-gardener/evals/default-evals.json +1 -0
  142. package/skills/core/pdd-entropy-reduction/SKILL.md +360 -0
  143. package/skills/core/pdd-entropy-reduction/_meta.json +1 -0
  144. package/skills/core/pdd-entropy-reduction/evals/default-evals.json +1 -0
  145. package/skills/core/pdd-entropy-reduction/references/entropy-report-template.md +287 -0
  146. package/skills/core/pdd-entropy-reduction/references/golden-principles.md +573 -0
  147. package/skills/core/pdd-entropy-reduction/scripts/entropy_scan.py +712 -0
  148. package/skills/core/pdd-extract-features/SKILL.md +320 -0
  149. package/skills/core/pdd-extract-features/_meta.json +1 -0
  150. package/skills/core/pdd-extract-features/evals/default-evals.json +1 -0
  151. package/skills/core/pdd-generate-spec/SKILL.md +418 -0
  152. package/skills/core/pdd-generate-spec/_meta.json +1 -0
  153. package/skills/core/pdd-generate-spec/evals/default-evals.json +1 -0
  154. package/skills/core/pdd-implement-feature/SKILL.md +332 -0
  155. package/skills/core/pdd-implement-feature/_meta.json +1 -0
  156. package/skills/core/pdd-implement-feature/evals/default-evals.json +1 -0
  157. package/skills/core/pdd-main/SKILL.md +540 -0
  158. package/skills/core/pdd-main/_meta.json +1 -0
  159. package/skills/core/pdd-main/evals/default-evals.json +1 -0
  160. package/skills/core/pdd-main/evals/evals.json +215 -0
  161. package/skills/core/pdd-verify-feature/SKILL.md +474 -0
  162. package/skills/core/pdd-verify-feature/_meta.json +1 -0
  163. package/skills/core/pdd-verify-feature/evals/default-evals.json +1 -0
  164. package/skills/core/pdd-vm/evals/default-evals.json +1 -0
  165. package/skills/core/traffic-accident-assessor/LICENSE +29 -0
  166. package/skills/core/traffic-accident-assessor/SKILL.md +439 -0
  167. package/skills/core/traffic-accident-assessor/evals/evals.json +1 -0
  168. package/skills/core/traffic-accident-assessor/references/accident-types.md +369 -0
  169. package/skills/core/traffic-accident-assessor/references/liability-rules.md +287 -0
  170. package/skills/core/traffic-accident-assessor/references/traffic-laws.md +226 -0
  171. package/skills/core/traffic-accident-assessor/references//351/253/230/345/260/224/345/244/253/350/257/264/346/230/216/344/271/246.pdf +32576 -106
  172. package/skills/core/traffic-accident-assessor/scripts/generate_official_statement.py +588 -0
  173. package/skills/core/traffic-accident-assessor/scripts/generate_report.py +495 -0
  174. package/skills/core/traffic-accident-assessor/scripts/generate_statement.py +528 -0
  175. package/skills/core/traffic-accident-assessor.zip +0 -0
  176. package/skills/entropy/expert-arch-enforcer/SKILL.md +292 -0
  177. package/skills/entropy/expert-arch-enforcer/_meta.json +1 -0
  178. package/skills/entropy/expert-arch-enforcer/evals/default-evals.json +1 -0
  179. package/skills/entropy/expert-auto-refactor/SKILL.md +327 -0
  180. package/skills/entropy/expert-auto-refactor/_meta.json +1 -0
  181. package/skills/entropy/expert-auto-refactor/evals/default-evals.json +1 -0
  182. package/skills/entropy/expert-code-quality/SKILL.md +468 -0
  183. package/skills/entropy/expert-code-quality/_meta.json +1 -0
  184. package/skills/entropy/expert-code-quality/evals/default-evals.json +1 -0
  185. package/skills/entropy/expert-code-quality/evals/evals.json +109 -0
  186. package/skills/entropy/expert-code-quality/references/code-smells.md +605 -0
  187. package/skills/entropy/expert-code-quality/references/design-patterns.md +1111 -0
  188. package/skills/entropy/expert-code-quality/references/refactoring-catalog.md +1281 -0
  189. package/skills/entropy/expert-code-quality/references/solid-principles.md +524 -0
  190. package/skills/entropy/expert-entropy-auditor/SKILL.md +276 -0
  191. package/skills/entropy/expert-entropy-auditor/_meta.json +1 -0
  192. package/skills/entropy/expert-entropy-auditor/evals/default-evals.json +1 -0
  193. package/skills/expert/expert-activiti/SKILL.md +497 -0
  194. package/skills/expert/expert-activiti/_meta.json +1 -0
  195. package/skills/expert/expert-mysql/SKILL.md +832 -0
  196. package/skills/expert/expert-mysql/_meta.json +1 -0
  197. package/skills/expert/expert-performance/SKILL.md +379 -0
  198. package/skills/expert/expert-performance/_meta.json +1 -0
  199. package/skills/expert/expert-performance/evals/default-evals.json +1 -0
  200. package/skills/expert/expert-ruoyi/SKILL.md +472 -0
  201. package/skills/expert/expert-ruoyi/_meta.json +1 -0
  202. package/skills/expert/expert-security/SKILL.md +1341 -0
  203. package/skills/expert/expert-security/_meta.json +1 -0
  204. package/skills/expert/expert-security/evals/default-evals.json +1 -0
  205. package/skills/expert/software-architect/SKILL.md +350 -0
  206. package/skills/expert/software-architect/_meta.json +1 -0
  207. package/skills/expert/software-engineer/SKILL.md +437 -0
  208. package/skills/expert/software-engineer/_meta.json +1 -0
  209. package/skills/expert/software-engineer/architecture.md +130 -0
  210. package/skills/expert/software-engineer/patterns.md +151 -0
  211. package/skills/expert/software-engineer/testing.md +135 -0
  212. package/skills/expert/system-architect/SKILL.md +628 -0
  213. package/skills/expert/system-architect/_meta.json +1 -0
  214. package/skills/expert/system-architect/assets/templates/ARCHITECTURE.md +25 -0
  215. package/skills/expert/system-architect/assets/templates/README.md +44 -0
  216. package/skills/expert/system-architect/references/js-ts-standards.md +18 -0
  217. package/skills/expert/system-architect/references/python-standards.md +19 -0
  218. package/skills/expert/system-architect/references/scaffolding.md +61 -0
  219. package/skills/expert/system-architect/references/security-checklist.md +21 -0
  220. package/skills/openspec/openspec-apply-change/SKILL.md +156 -0
  221. package/skills/openspec/openspec-apply-change/_meta.json +1 -0
  222. package/skills/openspec/openspec-archive-change/SKILL.md +114 -0
  223. package/skills/openspec/openspec-archive-change/_meta.json +1 -0
  224. package/skills/openspec/openspec-bulk-archive-change/SKILL.md +246 -0
  225. package/skills/openspec/openspec-bulk-archive-change/_meta.json +1 -0
  226. package/skills/openspec/openspec-continue-change/SKILL.md +118 -0
  227. package/skills/openspec/openspec-continue-change/_meta.json +1 -0
  228. package/skills/openspec/openspec-explore/SKILL.md +288 -0
  229. package/skills/openspec/openspec-explore/_meta.json +1 -0
  230. package/skills/openspec/openspec-ff-change/SKILL.md +101 -0
  231. package/skills/openspec/openspec-ff-change/_meta.json +1 -0
  232. package/skills/openspec/openspec-new-change/SKILL.md +74 -0
  233. package/skills/openspec/openspec-new-change/_meta.json +1 -0
  234. package/skills/openspec/openspec-onboard/SKILL.md +554 -0
  235. package/skills/openspec/openspec-onboard/_meta.json +1 -0
  236. package/skills/openspec/openspec-sync-specs/SKILL.md +138 -0
  237. package/skills/openspec/openspec-sync-specs/_meta.json +1 -0
  238. package/skills/openspec/openspec-verify-change/SKILL.md +168 -0
  239. package/skills/openspec/openspec-verify-change/_meta.json +1 -0
  240. package/skills/pr/pdd-multi-review/SKILL.md +534 -0
  241. package/skills/pr/pdd-multi-review/_meta.json +1 -0
  242. package/skills/pr/pdd-pr-batch/SKILL.md +303 -0
  243. package/skills/pr/pdd-pr-batch/_meta.json +1 -0
  244. package/skills/pr/pdd-pr-create/SKILL.md +344 -0
  245. package/skills/pr/pdd-pr-create/_meta.json +1 -0
  246. package/skills/pr/pdd-pr-merge/SKILL.md +286 -0
  247. package/skills/pr/pdd-pr-merge/_meta.json +1 -0
  248. package/skills/pr/pdd-pr-review/SKILL.md +217 -0
  249. package/skills/pr/pdd-pr-review/_meta.json +1 -0
  250. package/skills/pr/pdd-task-manager/SKILL.md +636 -0
  251. package/skills/pr/pdd-task-manager/_meta.json +1 -0
  252. package/skills/pr/pdd-template-engine/SKILL.md +306 -0
  253. package/skills/pr/pdd-template-engine/_meta.json +1 -0
  254. package/templates/behavior-shaping/iron-law-template.md +87 -0
  255. package/templates/behavior-shaping/rationalization-template.md +62 -0
  256. package/templates/behavior-shaping/red-flags-template.md +70 -0
  257. package/templates/bilingual-template.md +139 -0
  258. package/templates/config/default.yaml +47 -0
  259. package/templates/project/default/README.md +31 -0
  260. package/templates/project/frontend/README.md +46 -0
  261. package/templates/project/java/README.md +48 -0
@@ -0,0 +1,485 @@
1
+ // lib/token/budget-manager.js - Token Budget Manager
2
+ // 管理每次PDD执行的Token消耗,防止超预算
3
+
4
+ import { EventEmitter } from 'events';
5
+ import { BudgetAlert } from './budget-alert.js';
6
+
7
+ /**
8
+ * PDD执行阶段枚举
9
+ */
10
+ export const PHASES = {
11
+ ANALYSIS: 'analysis', // 业务分析阶段
12
+ DESIGN: 'design', // 设计规格阶段
13
+ IMPLEMENTATION: 'impl', // 代码实现阶段
14
+ REVIEW: 'review', // 代码审查阶段
15
+ VERIFICATION: 'verify' // 验证确认阶段
16
+ };
17
+
18
+ /**
19
+ * 默认的阶段Token分配比例
20
+ */
21
+ const DEFAULT_ALLOCATION = {
22
+ [PHASES.ANALYSIS]: 0.20, // 分析阶段占20%
23
+ [PHASES.DESIGN]: 0.15, // 设计阶段占15%
24
+ [PHASES.IMPLEMENTATION]: 0.40, // 实现阶段占40%
25
+ [PHASES.REVIEW]: 0.15, // 审查阶段占15%
26
+ [PHASES.VERIFICATION]: 0.10 // 验证阶段占10%
27
+ };
28
+
29
+ /**
30
+ * TokenBudgetManager - Token预算管理器
31
+ *
32
+ * 职责:
33
+ * - 管理PDD全流程的Token消耗预算
34
+ * - 按阶段分配和追踪Token使用情况
35
+ * - 提供预警和阻断机制
36
+ * - 与token-analyzer.js集成,记录详细的消耗历史
37
+ *
38
+ * 使用示例:
39
+ * ```js
40
+ * const manager = new TokenBudgetManager({ totalBudget: 100000 });
41
+ * manager.allocate(PHASES.ANALYSIS, 20000);
42
+ * const result = manager.consume(PHASES.ANALYSIS, 5000, '分析PRD文档');
43
+ * if (result.blocked) {
44
+ * console.log('超预算,操作被阻断');
45
+ * }
46
+ * ```
47
+ */
48
+ export class TokenBudgetManager extends EventEmitter {
49
+ /**
50
+ * 创建Token预算管理器实例
51
+ * @param {Object} config - 配置选项
52
+ * @param {number} config.totalBudget - 总Token预算(默认100000)
53
+ * @param {number} config.warningThreshold - 预警阈值比例(默认0.8即80%)
54
+ * @param {number} config.criticalThreshold - 阻断阈值比例(默认0.95即95%)
55
+ * @param {Object} config.allocation - 自定义阶段分配比例
56
+ * @param {boolean} config.autoAlert - 是否启用自动预警(默认true)
57
+ */
58
+ constructor(config = {}) {
59
+ super();
60
+
61
+ this.totalBudget = config.totalBudget || 100000;
62
+ this.warningThreshold = config.warningThreshold || 0.8;
63
+ this.criticalThreshold = config.criticalThreshold || 0.95;
64
+ this.currentUsage = 0;
65
+ this.sessionId = this._generateSessionId();
66
+ this.startTime = Date.now();
67
+
68
+ // 按阶段分配的预算(绝对值tokens)
69
+ this.allocation = {};
70
+ // 按阶段实际消耗
71
+ this.phaseUsage = {};
72
+ // 消耗历史记录
73
+ this.history = [];
74
+
75
+ // 初始化预警系统
76
+ this.alert = new BudgetAlert({
77
+ warningThreshold: this.warningThreshold,
78
+ criticalThreshold: this.criticalThreshold,
79
+ manager: this
80
+ });
81
+
82
+ // 应用默认或自定义分配
83
+ const allocationConfig = config.allocation || DEFAULT_ALLOCATION;
84
+ this._applyAllocation(allocationConfig);
85
+
86
+ // 自动预警监听
87
+ if (config.autoAlert !== false) {
88
+ this._setupAutoAlert();
89
+ }
90
+ }
91
+
92
+ /**
93
+ * 为指定阶段分配Token预算
94
+ * @param {string} phase - 阶段标识 (PHASES枚举)
95
+ * @param {number} tokens - 分配的Token数量(可选,不传则按比例计算)
96
+ * @returns {Object} 分配结果
97
+ */
98
+ allocate(phase, tokens) {
99
+ if (!this._isValidPhase(phase)) {
100
+ return { success: false, error: `无效的阶段标识: ${phase}` };
101
+ }
102
+
103
+ const allocatedTokens = tokens !== undefined
104
+ ? tokens
105
+ : Math.floor(this.totalBudget * (DEFAULT_ALLOCATION[phase] || 0.1));
106
+
107
+ // 检查总分配是否超预算
108
+ const currentTotalAllocated = Object.values(this.allocation).reduce((s, v) => s + v, 0);
109
+ if (currentTotalAllocated + allocatedTokens > this.totalBudget) {
110
+ return {
111
+ success: false,
112
+ error: `分配失败: 总分配(${currentTotalAllocated + allocatedTokens})超过总预算(${this.totalBudget})`,
113
+ remaining: this.totalBudget - currentTotalAllocated
114
+ };
115
+ }
116
+
117
+ this.allocation[phase] = allocatedTokens;
118
+ this.phaseUsage[phase] = 0;
119
+
120
+ this.emit('allocate', {
121
+ phase,
122
+ tokens: allocatedTokens,
123
+ timestamp: Date.now()
124
+ });
125
+
126
+ return {
127
+ success: true,
128
+ phase,
129
+ allocated: allocatedTokens,
130
+ totalAllocated: currentTotalAllocated + allocatedTokens
131
+ };
132
+ }
133
+
134
+ /**
135
+ * 记录Token消耗并检查是否超预算
136
+ * @param {string} phase - 消耗所属阶段
137
+ * @param {number} tokens - 消耗的Token数量
138
+ * @param {string} detail - 消耗详情描述
139
+ * @returns {Object} 消耗结果 { consumed, blocked, warning, remaining, usagePercent }
140
+ */
141
+ consume(phase, tokens, detail = '') {
142
+ if (!this._isValidPhase(phase)) {
143
+ return { success: false, error: `无效的阶段标识: ${phase}`, blocked: true };
144
+ }
145
+
146
+ if (typeof tokens !== 'number' || tokens <= 0) {
147
+ return { success: false, error: 'Token数量必须为正数', blocked: true };
148
+ }
149
+
150
+ const beforeUsage = this.currentUsage;
151
+ const afterUsage = beforeUsage + tokens;
152
+ const usagePercent = afterUsage / this.totalBudget;
153
+
154
+ // 检查是否达到阻断阈值
155
+ if (usagePercent >= this.criticalThreshold && beforeUsage < this.criticalThreshold * this.totalBudget) {
156
+ const result = {
157
+ success: false,
158
+ consumed: 0,
159
+ phase,
160
+ tokens,
161
+ detail,
162
+ blocked: true,
163
+ reason: 'CRITICAL_BUDGET_EXCEEDED',
164
+ usagePercent,
165
+ threshold: this.criticalThreshold,
166
+ remaining: this.getRemaining(),
167
+ alertLevel: 'critical'
168
+ };
169
+
170
+ this.emit('critical', result);
171
+ this.alert.handleCritical(result);
172
+ return result;
173
+ }
174
+
175
+ // 检查是否已处于阻断状态
176
+ if (beforeUsage >= this.criticalThreshold * this.totalBudget) {
177
+ return {
178
+ success: false,
179
+ consumed: 0,
180
+ phase,
181
+ tokens,
182
+ detail,
183
+ blocked: true,
184
+ reason: 'ALREADY_CRITICAL',
185
+ usagePercent: beforeUsage / this.totalBudget,
186
+ remaining: this.getRemaining(),
187
+ alertLevel: 'critical'
188
+ };
189
+ }
190
+
191
+ // 正常消耗
192
+ this.currentUsage = afterUsage;
193
+ this.phaseUsage[phase] = (this.phaseUsage[phase] || 0) + tokens;
194
+
195
+ // 记录历史
196
+ const record = {
197
+ id: this.history.length + 1,
198
+ sessionId: this.sessionId,
199
+ phase,
200
+ tokens,
201
+ detail,
202
+ timestamp: Date.now(),
203
+ cumulativeUsage: this.currentUsage,
204
+ usagePercent: Math.round(usagePercent * 10000) / 100
205
+ };
206
+ this.history.push(record);
207
+
208
+ // 判断预警状态
209
+ const isWarning = usagePercent >= this.warningThreshold;
210
+ const isCritical = usagePercent >= this.criticalThreshold;
211
+
212
+ const result = {
213
+ success: true,
214
+ consumed: tokens,
215
+ phase,
216
+ detail,
217
+ blocked: false,
218
+ warning: isWarning,
219
+ critical: isCritical,
220
+ usagePercent: Math.round(usagePercent * 10000) / 100,
221
+ remaining: this.getRemaining()
222
+ };
223
+
224
+ // 触发事件
225
+ this.emit('consume', record);
226
+
227
+ if (isCritical) {
228
+ this.emit('critical', result);
229
+ this.alert.handleCritical(result);
230
+ } else if (isWarning) {
231
+ this.emit('warning', result);
232
+ this.alert.handleWarning(result);
233
+ }
234
+
235
+ return result;
236
+ }
237
+
238
+ /**
239
+ * 获取剩余可用Token
240
+ * @returns {number}
241
+ */
242
+ getRemaining() {
243
+ return Math.max(0, this.totalBudget - this.currentUsage);
244
+ }
245
+
246
+ /**
247
+ * 获取当前使用率
248
+ * @returns {number} 0-1之间的小数
249
+ */
250
+ getUsagePercent() {
251
+ return this.currentUsage / this.totalBudget;
252
+ }
253
+
254
+ /**
255
+ * 获取指定阶段的已用Token数量
256
+ * @param {string} phase - 阶段标识
257
+ * @returns {number}
258
+ */
259
+ getPhaseUsage(phase) {
260
+ return this.phaseUsage[phase] || 0;
261
+ }
262
+
263
+ /**
264
+ * 获取指定阶段的预算分配
265
+ * @param {string} phase - 阶段标识
266
+ * @returns {number}
267
+ */
268
+ getPhaseAllocation(phase) {
269
+ return this.allocation[phase] || 0;
270
+ }
271
+
272
+ /**
273
+ * 获取指定阶段的使用率
274
+ * @param {string} phase - 阶段标识
275
+ * @returns {number}
276
+ */
277
+ getPhaseUsagePercent(phase) {
278
+ const allocated = this.allocation[phase];
279
+ if (!allocated || allocated === 0) return 0;
280
+ return (this.phaseUsage[phase] || 0) / allocated;
281
+ }
282
+
283
+ /**
284
+ * 判断是否进入预警状态
285
+ * @returns {boolean}
286
+ */
287
+ isWarning() {
288
+ return this.getUsagePercent() >= this.warningThreshold;
289
+ }
290
+
291
+ /**
292
+ * 判断是否进入阻断状态
293
+ * @returns {boolean}
294
+ */
295
+ isCritical() {
296
+ return this.getUsagePercent() >= this.criticalThreshold;
297
+ }
298
+
299
+ /**
300
+ * 获取完整的预算使用报告
301
+ * @returns {Object} 结构化报告数据
302
+ */
303
+ getReport() {
304
+ const durationMs = Date.now() - this.startTime;
305
+ const phaseReports = {};
306
+
307
+ for (const [phase, allocated] of Object.entries(this.allocation)) {
308
+ const used = this.phaseUsage[phase] || 0;
309
+ phaseReports[phase] = {
310
+ allocated,
311
+ used,
312
+ remaining: Math.max(0, allocated - used),
313
+ usagePercent: allocated > 0 ? Math.round((used / allocated) * 10000) / 100 : 0,
314
+ status: this._getPhaseStatus(phase)
315
+ };
316
+ }
317
+
318
+ return {
319
+ summary: {
320
+ sessionId: this.sessionId,
321
+ totalBudget: this.totalBudget,
322
+ currentUsage: this.currentUsage,
323
+ remaining: this.getRemaining(),
324
+ usagePercent: Math.round(this.getUsagePercent() * 10000) / 100,
325
+ status: this.isCritical() ? 'critical' : this.isWarning() ? 'warning' : 'normal',
326
+ startTime: new Date(this.startTime).toISOString(),
327
+ endTime: new Date().toISOString(),
328
+ durationSeconds: Math.round(durationMs / 1000),
329
+ totalOperations: this.history.length
330
+ },
331
+ phases: phaseReports,
332
+ thresholds: {
333
+ warning: this.warningThreshold,
334
+ critical: this.criticalThreshold,
335
+ warningTokens: Math.floor(this.totalBudget * this.warningThreshold),
336
+ criticalTokens: Math.floor(this.totalBudget * this.criticalThreshold)
337
+ },
338
+ history: this.history,
339
+ recommendations: this._generateRecommendations()
340
+ };
341
+ }
342
+
343
+ /**
344
+ * 重置所有计数器和历史记录
345
+ * @param {Object} options - 重置选项
346
+ * @param {boolean} options.keepAllocation - 是否保留阶段分配(默认false)
347
+ */
348
+ reset(options = {}) {
349
+ const oldSession = this.sessionId;
350
+
351
+ this.currentUsage = 0;
352
+ this.sessionId = this._generateSessionId();
353
+ this.startTime = Date.now();
354
+
355
+ if (!options.keepAllocation) {
356
+ this.allocation = {};
357
+ const allocationConfig = DEFAULT_ALLOCATION;
358
+ this._applyAllocation(allocationConfig);
359
+ }
360
+
361
+ this.phaseUsage = {};
362
+ this.history = [];
363
+
364
+ this.emit('reset', {
365
+ oldSession,
366
+ newSession: this.sessionId,
367
+ timestamp: Date.now()
368
+ });
369
+ }
370
+
371
+ /**
372
+ * 导出为JSON格式(用于持久化)
373
+ * @returns {string}
374
+ */
375
+ toJSON() {
376
+ return JSON.stringify(this.getReport(), null, 2);
377
+ }
378
+
379
+ // ==================== 私有方法 ====================
380
+
381
+ /**
382
+ * 生成会话ID
383
+ * @private
384
+ */
385
+ _generateSessionId() {
386
+ return `pdd-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
387
+ }
388
+
389
+ /**
390
+ * 验证阶段标识有效性
391
+ * @private
392
+ */
393
+ _isValidPhase(phase) {
394
+ return Object.values(PHASES).includes(phase);
395
+ }
396
+
397
+ /**
398
+ * 应用阶段分配配置
399
+ * @private
400
+ */
401
+ _applyAllocation(allocationConfig) {
402
+ if (typeof allocationConfig === 'object' && !Array.isArray(allocationConfig)) {
403
+ // 绝对值配置: { analysis: 20000, design: 15000, ... }
404
+ for (const [phase, tokens] of Object.entries(allocationConfig)) {
405
+ if (this._isValidPhase(phase) && typeof tokens === 'number') {
406
+ this.allocation[phase] = tokens;
407
+ this.phaseUsage[phase] = 0;
408
+ }
409
+ }
410
+ } else {
411
+ // 按默认比例分配
412
+ for (const [phase, ratio] of Object.entries(DEFAULT_ALLOCATION)) {
413
+ this.allocation[phase] = Math.floor(this.totalBudget * ratio);
414
+ this.phaseUsage[phase] = 0;
415
+ }
416
+ }
417
+ }
418
+
419
+ /**
420
+ * 获取阶段状态
421
+ * @private
422
+ */
423
+ _getPhaseStatus(phase) {
424
+ const percent = this.getPhaseUsagePercent(phase);
425
+ if (percent >= 1) return 'exceeded';
426
+ if (percent >= 0.9) return 'critical';
427
+ if (percent >= 0.75) return 'warning';
428
+ if (percent > 0) return 'active';
429
+ return 'idle';
430
+ }
431
+
432
+ /**
433
+ * 设置自动预警监听
434
+ * @private
435
+ */
436
+ _setupAutoAlert() {
437
+ this.on('warning', (data) => {
438
+ this.alert.handleWarning(data);
439
+ });
440
+ this.on('critical', (data) => {
441
+ this.alert.handleCritical(data);
442
+ });
443
+ }
444
+
445
+ /**
446
+ * 根据当前使用情况生成优化建议
447
+ * @private
448
+ */
449
+ _generateRecommendations() {
450
+ const recommendations = [];
451
+ const usagePercent = this.getUsagePercent();
452
+
453
+ if (usagePercent > 0.9) {
454
+ recommendations.push({
455
+ level: 'critical',
456
+ message: 'Token使用率超过90%,建议立即结束非关键操作'
457
+ });
458
+ }
459
+
460
+ // 检查各阶段是否有异常消耗
461
+ for (const [phase, usage] of Object.entries(this.phaseUsage)) {
462
+ const allocated = this.allocation[phase];
463
+ if (allocated && usage / allocated > 1.2) {
464
+ recommendations.push({
465
+ level: 'warning',
466
+ message: `${phase}阶段超预算${Math.round((usage / allocated - 1) * 100)}%,建议优化该阶段的Prompt策略`
467
+ });
468
+ }
469
+ }
470
+
471
+ // 检查是否有未使用的阶段
472
+ for (const phase of Object.keys(this.allocation)) {
473
+ if (!this.phaseUsage[phase] || this.phaseUsage[phase] === 0) {
474
+ recommendations.push({
475
+ level: 'info',
476
+ message: `${phase}阶段尚未使用`
477
+ });
478
+ }
479
+ }
480
+
481
+ return recommendations;
482
+ }
483
+ }
484
+
485
+ export default TokenBudgetManager;
package/lib/update.js ADDED
@@ -0,0 +1,54 @@
1
+ import chalk from 'chalk';
2
+ import { execSync } from 'child_process';
3
+ import { showVersion } from './version.js';
4
+
5
+ export async function updateSkills(options) {
6
+ console.log(chalk.blue('\n📦 检查更新...\n'));
7
+
8
+ const currentVersion = await showVersion(false);
9
+
10
+ try {
11
+ const latestVersion = execSync(
12
+ 'npm view pdd-skills version',
13
+ { encoding: 'utf-8', timeout: 10000 }
14
+ ).trim();
15
+
16
+ if (options.check) {
17
+ if (compareVersions(latestVersion, currentVersion) > 0) {
18
+ console.log(chalk.yellow(`📦 有新版本可用: ${latestVersion}`));
19
+ console.log(chalk.gray(` 当前版本: ${currentVersion}`));
20
+ } else {
21
+ console.log(chalk.green('✅ 已是最新版本'));
22
+ }
23
+ return;
24
+ }
25
+
26
+ if (compareVersions(latestVersion, currentVersion) <= 0 && !options.version) {
27
+ console.log(chalk.green('✅ 已是最新版本,无需更新'));
28
+ return;
29
+ }
30
+
31
+ const versionSpec = options.version || '@latest';
32
+ console.log(chalk.blue(`🔄 正在更新到 ${versionSpec}...`));
33
+
34
+ console.log(chalk.gray('\n提示: 运行以下命令手动更新:'));
35
+ console.log(chalk.gray(` npm install -g pdd-skills${versionSpec}`));
36
+ console.log(chalk.gray(` 或使用 npx: npx pdd-skills${versionSpec} <command>`));
37
+
38
+ } catch (e) {
39
+ console.log(chalk.red('❌ 无法检查更新,请检查网络连接'));
40
+ }
41
+ }
42
+
43
+ function compareVersions(a, b) {
44
+ const partsA = a.split('.').map(Number);
45
+ const partsB = b.split('.').map(Number);
46
+
47
+ for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
48
+ const numA = partsA[i] || 0;
49
+ const numB = partsB[i] || 0;
50
+ if (numA > numB) return 1;
51
+ if (numA < numB) return -1;
52
+ }
53
+ return 0;
54
+ }
@@ -0,0 +1,88 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import yaml from 'yaml';
5
+
6
+ export function log(level, message, data) {
7
+ const timestamp = new Date().toISOString();
8
+ const prefix = {
9
+ info: chalk.blue('ℹ'),
10
+ success: chalk.green('✅'),
11
+ warn: chalk.yellow('⚠️'),
12
+ error: chalk.red('❌'),
13
+ debug: chalk.gray('🔍')
14
+ };
15
+
16
+ const icon = prefix[level] || prefix.info;
17
+ const line = `[${timestamp}] ${icon} ${message}`;
18
+
19
+ if (level === 'error') {
20
+ console.error(line);
21
+ if (data) console.error(chalk.red(` ${JSON.stringify(data, null, 2)}`));
22
+ } else if (level === 'debug') {
23
+ console.debug(line);
24
+ } else {
25
+ console.log(line);
26
+ }
27
+ }
28
+
29
+ export function loadConfig(projectDir) {
30
+ const configPaths = [
31
+ path.join(projectDir, '.pdd', 'config.yaml'),
32
+ path.join(projectDir, '.pdd', 'config.json')
33
+ ];
34
+
35
+ for (const cfgPath of configPaths) {
36
+ if (fs.existsSync(cfgPath)) {
37
+ try {
38
+ const content = fs.readFileSync(cfgPath, 'utf-8');
39
+ if (cfgPath.endsWith('.yaml') || cfgPath.endsWith('.yml')) {
40
+ return yaml.parse(content);
41
+ }
42
+ return JSON.parse(content);
43
+ } catch (e) {
44
+ log('warn', `配置文件解析失败: ${cfgPath}`, e.message);
45
+ }
46
+ }
47
+ }
48
+
49
+ return getDefaultConfig();
50
+ }
51
+
52
+ function getDefaultConfig() {
53
+ return {
54
+ project: { name: '', version: '1.0.0' },
55
+ pdd: {
56
+ features: { output_dir: 'specs/features' },
57
+ spec: { output_dir: 'specs', include_tests: true },
58
+ verify: { dimensions: ['completeness', 'correctness', 'consistency'] }
59
+ },
60
+ linter: {
61
+ enabled: true,
62
+ types: ['code', 'prd', 'sql', 'activiti'],
63
+ fail_on_error: false,
64
+ report_format: 'markdown'
65
+ },
66
+ hooks: { enabled: true },
67
+ cache: { enabled: true, ttl: 3600 }
68
+ };
69
+ }
70
+
71
+ export function resolveConfigPath(projectDir, relativePath) {
72
+ const absolute = path.isAbsolute(relativePath)
73
+ ? relativePath
74
+ : path.join(projectDir, relativePath);
75
+ return absolute;
76
+ }
77
+
78
+ export async function findProjectRoot(startDir) {
79
+ let current = path.resolve(startDir);
80
+
81
+ while (current !== path.dirname(current)) {
82
+ const pddDir = path.join(current, '.pdd');
83
+ if (fs.existsSync(pddDir)) return current;
84
+ current = path.dirname(current);
85
+ }
86
+
87
+ return path.resolve(startDir);
88
+ }