@ohos-cpf/3rdloop 0.0.1 → 0.0.3

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 (393) hide show
  1. package/README.md +245 -425
  2. package/bin/3rdloop.mjs +46 -46
  3. package/lib/cli.js +781 -740
  4. package/lib/config-cmd.js +452 -0
  5. package/lib/config.js +318 -317
  6. package/lib/doctor.js +113 -113
  7. package/lib/exit-codes.js +30 -30
  8. package/lib/opencode.js +155 -155
  9. package/lib/orch.js +426 -426
  10. package/lib/queries.js +263 -263
  11. package/lib/step.js +325 -325
  12. package/lib/ui.js +222 -222
  13. package/lib/update.js +280 -0
  14. package/lib/workflow.js +308 -290
  15. package/lib/workflows.js +131 -131
  16. package/package.json +50 -50
  17. package/vendor/Server/Agent/SkillSelector/README.md +343 -343
  18. package/vendor/Server/Agent/SkillSelector/core/Agent.js +207 -207
  19. package/vendor/Server/Agent/SkillSelector/index.js +14 -14
  20. package/vendor/Server/Agent/SkillSelector/llm/llmClient.js +313 -313
  21. package/vendor/Server/Agent/SkillSelector/llm/prompts.js +161 -161
  22. package/vendor/Server/Agent/SkillSelector/llm/reactSteps.js +144 -144
  23. package/vendor/Server/Agent/SkillSelector/matcher/fuzzyMatcher.js +433 -433
  24. package/vendor/Server/Agent/SkillSelector/scanner/skillScanner.js +382 -382
  25. package/vendor/Server/Agent/SkillSelector/utils/actionWords.js +59 -59
  26. package/vendor/Server/Brain/AnalysisStrategies.js +422 -422
  27. package/vendor/Server/Brain/Brain.js +686 -686
  28. package/vendor/Server/Brain/DecompositionStrategies.js +621 -621
  29. package/vendor/Server/Brain/PlanPersistence.js +196 -196
  30. package/vendor/Server/Brain/SkillExecutor.js +251 -251
  31. package/vendor/Server/Brain/index.js +11 -11
  32. package/vendor/Server/CLI/cli.js +275 -243
  33. package/vendor/Server/CLI/deveco-code/index.js +71 -0
  34. package/vendor/Server/CLI/deveco-code.js +5 -0
  35. package/vendor/Server/CLI/opencode/index.js +817 -804
  36. package/vendor/Server/CLI/opencode.js +5 -5
  37. package/vendor/Server/DbUse/MessageArchive.js +61 -61
  38. package/vendor/Server/DbUse/StorageManager.js +107 -107
  39. package/vendor/Server/DbUse/adapters/BaseAdapter.js +94 -94
  40. package/vendor/Server/DbUse/adapters/FileAdapter.js +138 -138
  41. package/vendor/Server/DbUse/adapters/JsonAdapter.js +138 -138
  42. package/vendor/Server/DbUse/adapters/JsonlAdapter.js +114 -114
  43. package/vendor/Server/DbUse/adapters/SqliteAdapter.js +157 -157
  44. package/vendor/Server/DbUse/index.js +160 -160
  45. package/vendor/Server/DbUse/stores/SessionStore.js +279 -279
  46. package/vendor/Server/DbUse/stores/TaskExecutionStore.js +133 -133
  47. package/vendor/Server/DbUse/stores/TaskRegistryStore.js +262 -262
  48. package/vendor/Server/DbUse/stores/TaskStepStore.js +279 -279
  49. package/vendor/Server/FlexRunner/FlexRunner.js +1759 -1759
  50. package/vendor/Server/FlexRunner/index.js +12 -12
  51. package/vendor/Server/Knowledge/KnowledgeImporter.js +523 -523
  52. package/vendor/Server/Knowledge/KnowledgeManager.js +341 -341
  53. package/vendor/Server/Knowledge/index.js +33 -33
  54. package/vendor/Server/LoopEngine/LoopEngine.js +1133 -1133
  55. package/vendor/Server/LoopEngine/index.js +11 -11
  56. package/vendor/Server/Orchestrator/Orchestrator.js +0 -3
  57. package/vendor/Server/Orchestrator/StepNode.js +312 -312
  58. package/vendor/Server/Orchestrator/index.js +13 -13
  59. package/vendor/Server/Routes/controllers/BrainController.js +241 -241
  60. package/vendor/Server/Routes/controllers/FlexRunnerController.js +1125 -1125
  61. package/vendor/Server/Routes/controllers/HealthController.js +44 -44
  62. package/vendor/Server/Routes/controllers/KnowledgeImportController.js +355 -355
  63. package/vendor/Server/Routes/controllers/LoopEngineController.js +788 -788
  64. package/vendor/Server/Routes/controllers/StatsController.js +57 -57
  65. package/vendor/Server/Routes/controllers/StreamController.js +67 -67
  66. package/vendor/Server/Routes/library/logger.js +179 -179
  67. package/vendor/Server/Routes/library/zipArchive.js +172 -172
  68. package/vendor/Server/Routes/router/Router.js +204 -204
  69. package/vendor/Server/Routes/routes/brain.js +47 -47
  70. package/vendor/Server/Routes/routes/flexrunner.js +72 -72
  71. package/vendor/Server/Routes/routes/health.js +28 -28
  72. package/vendor/Server/Routes/routes/index.js +57 -57
  73. package/vendor/Server/Routes/routes/knowledge.js +55 -55
  74. package/vendor/Server/Routes/routes/loopengine.js +58 -58
  75. package/vendor/Server/Routes/routes/orchestrator.js +61 -61
  76. package/vendor/Server/Routes/routes/registry.js +97 -97
  77. package/vendor/Server/Routes/routes/stats.js +23 -23
  78. package/vendor/Server/Routes/routes/stream.js +30 -30
  79. package/vendor/Server/Routes/server.js +203 -202
  80. package/vendor/Server/Routes/sse/SseHub.js +308 -308
  81. package/vendor/Server/Skills/acceptance-check/SKILL.md +191 -174
  82. package/vendor/Server/Skills/acceptance-check/references/PHASE1_ARTIFACT_COLLECTION.md +52 -52
  83. package/vendor/Server/Skills/acceptance-check/references/PHASE2_CRITERIA_EVALUATION.md +77 -77
  84. package/vendor/Server/Skills/acceptance-check/references/PHASE2_EVIDENCE_VERIFICATION.md +70 -0
  85. package/vendor/Server/Skills/arkts-code-check/SKILL.md +320 -313
  86. package/vendor/Server/Skills/arkts-code-check/references/CODE_CHECK_GUIDE.md +210 -159
  87. package/vendor/Server/Skills/arkts-code-check/references/FILE_TYPE_GUIDE.md +28 -28
  88. package/vendor/Server/Skills/arkts-code-check/references/PHASE1_INFO_COLLECTION.md +233 -222
  89. package/vendor/Server/Skills/arkts-code-check/references/REPORT_TEMPLATE.md +219 -219
  90. package/vendor/Server/Skills/arkts-library-compile-validate/SKILL.md +328 -328
  91. package/vendor/Server/Skills/arkts-library-compile-validate/scripts/build.ps1 +93 -93
  92. package/vendor/Server/Skills/arkts-library-compile-validate/scripts/code-linter.cjs +432 -432
  93. package/vendor/Server/Skills/arkts-library-compile-validate/scripts/migrate.cjs +851 -851
  94. package/vendor/Server/Skills/arkts-library-compile-validate/scripts/ohpm-switch.cjs +788 -788
  95. package/vendor/Server/Skills/arkts-library-demo-code/SKILL.md +291 -291
  96. package/vendor/Server/Skills/arkts-library-demo-code/references/API_SIGNATURE_CHECKS.md +68 -68
  97. package/vendor/Server/Skills/arkts-library-demo-code/references/BUILD_VALIDATION.md +184 -184
  98. package/vendor/Server/Skills/arkts-library-demo-code/references/CODE_STANDARDS.md +337 -337
  99. package/vendor/Server/Skills/arkts-library-demo-code/references/EXAMPLES.md +400 -400
  100. package/vendor/Server/Skills/arkts-library-demo-code/references/SYSTEM_API_LOOKUP.md +98 -98
  101. package/vendor/Server/Skills/arkts-library-demo-code/references/TEMPLATE.md +544 -544
  102. package/vendor/Server/Skills/arkts-library-demo-code/scripts/build.ps1 +93 -93
  103. package/vendor/Server/Skills/arkts-library-demo-code/scripts/code-linter.cjs +432 -432
  104. package/vendor/Server/Skills/arkts-library-demo-code/scripts/migrate.cjs +851 -851
  105. package/vendor/Server/Skills/arkts-library-demo-code/scripts/ohpm-switch.cjs +788 -788
  106. package/vendor/Server/Skills/arkts-library-demo-coverage/SKILL.md +174 -174
  107. package/vendor/Server/Skills/arkts-library-demo-scenario/SKILL.md +321 -321
  108. package/vendor/Server/Skills/arkts-library-demo-scenario/references/EXAMPLES.md +100 -100
  109. package/vendor/Server/Skills/arkts-library-demo-scenario/references/TEMPLATE.md +185 -185
  110. package/vendor/Server/Skills/arkts-library-documentation-quality-check/SKILL.md +233 -233
  111. package/vendor/Server/Skills/arkts-library-documentation-quality-check/assets/REPORT_TEMPLATE.md +102 -102
  112. package/vendor/Server/Skills/arkts-library-documentation-quality-check/references/CHECK_DIMENSIONS.md +89 -89
  113. package/vendor/Server/Skills/arkts-library-documentation-quality-check/references/COMPLIANCE_CHECKLIST.md +62 -62
  114. package/vendor/Server/Skills/arkts-library-documentation-quality-check/references/KB_QUERY_GUIDE.md +107 -107
  115. package/vendor/Server/Skills/arkts-library-documentation-quality-check/references/MCP_TOOL_DISCOVERY.md +124 -124
  116. package/vendor/Server/Skills/arkts-library-documentation-quality-check/references/REPORT_TEMPLATE.md +90 -90
  117. package/vendor/Server/Skills/arkts-library-documentation-quality-check/references/SCORING_FORMULA.md +57 -57
  118. package/vendor/Server/Skills/arkts-library-documentation-quality-check/scripts/validate-skill.cjs +259 -259
  119. package/vendor/Server/Skills/arkts-library-interface-spec/SKILL.md +97 -97
  120. package/vendor/Server/Skills/arkts-library-memory-leak-check/SKILL.md +391 -391
  121. package/vendor/Server/Skills/arkts-library-source-clone/SKILL.md +113 -113
  122. package/vendor/Server/Skills/arkts-library-stability-check/SKILL.md +312 -312
  123. package/vendor/Server/Skills/arkts-library-stability-check/assets/REPORT_TEMPLATE.md +154 -154
  124. package/vendor/Server/Skills/arkts-library-stability-check/references/CHECKLIST.md +165 -165
  125. package/vendor/Server/Skills/arkts-library-stability-check/references/CODE_EXAMPLES.md +308 -308
  126. package/vendor/Server/Skills/arkts-library-stability-check/references/SCORING_RULES.md +90 -90
  127. package/vendor/Server/Skills/arkts-library-stability-check/scripts/validate-skill.cjs +282 -282
  128. package/vendor/Server/Skills/arkts-library-test-coverage-check/SKILL.md +360 -360
  129. package/vendor/Server/Skills/arkts-library-test-coverage-check/assets/REPORT_TEMPLATE.md +145 -145
  130. package/vendor/Server/Skills/arkts-library-test-coverage-check/references/CHECKLIST.md +252 -252
  131. package/vendor/Server/Skills/arkts-library-test-coverage-check/references/MCP_TOOL_USAGE.md +114 -114
  132. package/vendor/Server/Skills/arkts-library-test-coverage-check/scripts/validate-skill.cjs +262 -262
  133. package/vendor/Server/Skills/arkts-library-xts-code/SKILL.md +455 -455
  134. package/vendor/Server/Skills/arkts-library-xts-code/assets/report-template.md +60 -60
  135. package/vendor/Server/Skills/arkts-library-xts-code/references/ACCESS_MODIFIER_PRECHECK.md +76 -76
  136. package/vendor/Server/Skills/arkts-library-xts-code/references/BUILD_VERIFICATION.md +200 -200
  137. package/vendor/Server/Skills/arkts-library-xts-code/references/CODE_STANDARDS.md +518 -518
  138. package/vendor/Server/Skills/arkts-library-xts-code/references/SUBAGENT_PROMPT_TEMPLATE.md +276 -276
  139. package/vendor/Server/Skills/arkts-library-xts-code/references/SYSTEM_API_LOOKUP.md +92 -92
  140. package/vendor/Server/Skills/arkts-library-xts-code/references/XTS_TEMPLATE.md +767 -767
  141. package/vendor/Server/Skills/arkts-library-xts-code/scripts/build.ps1 +93 -93
  142. package/vendor/Server/Skills/arkts-library-xts-code/scripts/code-linter.cjs +432 -432
  143. package/vendor/Server/Skills/arkts-library-xts-code/scripts/migrate.cjs +851 -851
  144. package/vendor/Server/Skills/arkts-library-xts-code/scripts/ohpm-switch.cjs +788 -788
  145. package/vendor/Server/Skills/arkts-library-xts-code/scripts/precheck-access-modifiers.cjs +221 -221
  146. package/vendor/Server/Skills/arkts-library-xts-code-fix/SKILL.md +228 -228
  147. package/vendor/Server/Skills/arkts-library-xts-coverage/SKILL.md +97 -97
  148. package/vendor/Server/Skills/arkts-library-xts-doc/SKILL.md +194 -194
  149. package/vendor/Server/Skills/arkts-library-xts-doc/references/EXAMPLES.md +575 -575
  150. package/vendor/Server/Skills/arkts-library-xts-doc/references/TEMPLATE.md +574 -574
  151. package/vendor/Server/Skills/arkts-library-xts-doc/references/TESTABILITY_GUIDE.md +182 -182
  152. package/vendor/Server/Skills/arkts-library-xts-execution/SKILL.md +490 -490
  153. package/vendor/Server/Skills/arkts-library-xts-execution/references/error-fixing-examples.md +217 -217
  154. package/vendor/Server/Skills/arkts-library-xts-execution/scripts/build.ps1 +93 -93
  155. package/vendor/Server/Skills/arkts-library-xts-execution/scripts/code-linter.cjs +432 -432
  156. package/vendor/Server/Skills/arkts-library-xts-execution/scripts/migrate.cjs +851 -851
  157. package/vendor/Server/Skills/arkts-library-xts-execution/scripts/ohpm-switch.cjs +788 -788
  158. package/vendor/Server/Skills/flutter-code-check/SKILL.md +299 -299
  159. package/vendor/Server/Skills/flutter-code-check/assets/OUTPUT_TEMPLATE.md +311 -311
  160. package/vendor/Server/Skills/flutter-code-check/references/CHECKLIST.md +190 -190
  161. package/vendor/Server/Skills/flutter-code-check/references/PLATFORMS.md +133 -133
  162. package/vendor/Server/Skills/flutter-code-check/scripts/validate-skill.cjs +259 -259
  163. package/vendor/Server/Skills/flutter-interface/README.md +75 -75
  164. package/vendor/Server/Skills/flutter-interface/SKILL.md +291 -291
  165. package/vendor/Server/Skills/flutter-interface/references/EXAMPLES.md +336 -336
  166. package/vendor/Server/Skills/flutter-interface/references/GIT_CLONE_GUIDE.md +190 -190
  167. package/vendor/Server/Skills/flutter-interface/references/SCRIPT_REFERENCE.md +258 -258
  168. package/vendor/Server/Skills/flutter-interface/references/TEMPLATE.md +254 -254
  169. package/vendor/Server/Skills/flutter-library-consistency-check/SKILL.md +517 -517
  170. package/vendor/Server/Skills/flutter-library-consistency-check/references/CHECKLIST.md +381 -381
  171. package/vendor/Server/Skills/flutter-library-consistency-check/references/FUNCTION_COMPARISON_GUIDE.md +341 -341
  172. package/vendor/Server/Skills/flutter-library-consistency-check/references/PLATFORM_LIMITATION_GUIDE.md +71 -71
  173. package/vendor/Server/Skills/flutter-library-documentation-quality-check/SKILL.md +518 -518
  174. package/vendor/Server/Skills/flutter-library-documentation-quality-check/references/CHECKLIST.md +406 -406
  175. package/vendor/Server/Skills/flutter-library-memory-leak-check/SKILL.md +652 -652
  176. package/vendor/Server/Skills/flutter-library-memory-leak-check/references/CHECKLIST.md +396 -396
  177. package/vendor/Server/Skills/flutter-library-stability-check/SKILL.md +744 -744
  178. package/vendor/Server/Skills/flutter-library-stability-check/references/CHECKLIST.md +720 -720
  179. package/vendor/Server/Skills/flutter-library-test-coverage-check/SKILL.md +414 -414
  180. package/vendor/Server/Skills/flutter-library-test-coverage-check/assets/REPORT_TEMPLATE.md +150 -150
  181. package/vendor/Server/Skills/flutter-library-test-coverage-check/references/CHECKLIST.md +304 -304
  182. package/vendor/Server/Skills/flutter-library-test-coverage-check/references/SCORING_RULES.md +265 -265
  183. package/vendor/Server/Skills/flutter-library-test-coverage-check/references/SCRIPT_USAGE.md +286 -286
  184. package/vendor/Server/Skills/knowledge-import/SKILL.md +383 -383
  185. package/vendor/Server/Skills/knowledge-import/references/MCP_TOOL_USAGE.md +165 -165
  186. package/vendor/Server/Skills/knowledge-import/references/SKILL_LOCATOR_GUIDE.md +91 -91
  187. package/vendor/Server/Skills/knowledge-import/references/SKILL_OPTIMIZATION_GUIDE.md +127 -127
  188. package/vendor/Server/Skills/ohos-lib-pr-push/SKILL.md +453 -301
  189. package/vendor/Server/Skills/ohos-lib-pr-push/assets/PR_CHECKLIST.md +151 -0
  190. package/vendor/Server/Skills/ohos-lib-pr-push/assets/PR_ISSUE_TEMPLATE.md +257 -105
  191. package/vendor/Server/Skills/ohos-lib-pr-push/references/GITCODE_API.md +191 -127
  192. package/vendor/Server/Skills/ohos-lib-pr-push/scripts/gitcode-api.cjs +317 -208
  193. package/vendor/Server/Skills/rn-code-check/SKILL.md +320 -320
  194. package/vendor/Server/Skills/rn-code-check/references/API-GUIDE.md +234 -234
  195. package/vendor/Server/Skills/rn-code-check/references/CHECKLIST.md +188 -188
  196. package/vendor/Server/Skills/rn-code-check/references/REPORT-TEMPLATE.md +246 -246
  197. package/vendor/Server/Skills/rn-lib-add-example/SKILL.md +198 -198
  198. package/vendor/Server/Skills/rn-lib-add-example/references/APP_RENAME_GUIDE.md +40 -40
  199. package/vendor/Server/Skills/rn-lib-add-example/references/SHELL_ADAPTATION_CHECKLIST.md +78 -78
  200. package/vendor/Server/Skills/rn-lib-add-example/references/TEMPLATE_REPO_GUIDE.md +70 -70
  201. package/vendor/Server/Skills/rn-lib-add-example/references/VERIFICATION_GUIDE.md +47 -47
  202. package/vendor/Server/Skills/rn-lib-add-example/scripts/create-example.cjs +252 -252
  203. package/vendor/Server/Skills/rn-lib-update-doc/SKILL.md +176 -176
  204. package/vendor/Server/Skills/rn-lib-update-doc/config.json +5 -5
  205. package/vendor/Server/Skills/rn-lib-update-doc/references/changelog-template.md +35 -35
  206. package/vendor/Server/Skills/rn-lib-update-doc/references/format-diff.md +137 -137
  207. package/vendor/Server/Skills/rn-lib-update-doc/references/link-registry.json +33 -33
  208. package/vendor/Server/Skills/rn-lib-update-doc/references/model-0.4.2-overview.md +40 -40
  209. package/vendor/Server/Skills/rn-lib-update-doc/references/model-0.4.2.md +429 -429
  210. package/vendor/Server/Skills/rn-lib-update-doc/scripts/detect-readme-format.cjs +105 -105
  211. package/vendor/Server/Skills/rn-lib-update-doc/scripts/find-usage-doc.cjs +90 -90
  212. package/vendor/Server/Skills/rn-lib-update-doc/scripts/link-verify.cjs +213 -213
  213. package/vendor/Server/Skills/rn-lib-update-doc/scripts/normalize-changelog.cjs +73 -73
  214. package/vendor/Server/Skills/rn-lib-update-doc/scripts/normalize-package-meta.cjs +258 -258
  215. package/vendor/Server/Skills/rn-lib-update-doc/scripts/normalize-readme-links.cjs +341 -341
  216. package/vendor/Server/Skills/rn-lib-update-doc/scripts/resolve-usage-docs.cjs +67 -67
  217. package/vendor/Server/Skills/rn-library-consistency-check/SKILL.md +299 -299
  218. package/vendor/Server/Skills/rn-library-consistency-check/assets/REPORT_TEMPLATE.md +293 -293
  219. package/vendor/Server/Skills/rn-library-consistency-check/references/ARKTS_COMPONENT_CHECK_GUIDE.md +857 -857
  220. package/vendor/Server/Skills/rn-library-consistency-check/references/ARKTS_TURBOMODULE_CHECK_GUIDE.md +856 -856
  221. package/vendor/Server/Skills/rn-library-consistency-check/references/CHECKLIST.md +157 -157
  222. package/vendor/Server/Skills/rn-library-consistency-check/references/CPP_COMPONENT_CHECK_GUIDE.md +801 -801
  223. package/vendor/Server/Skills/rn-library-consistency-check/references/CPP_TURBOMODULE_CHECK_GUIDE.md +683 -683
  224. package/vendor/Server/Skills/rn-library-consistency-check/references/FUNCTION_COMPARISON_GUIDE.md +233 -233
  225. package/vendor/Server/Skills/rn-library-consistency-check/references/NATIVE_COMPONENT_IDENTIFICATION.md +1373 -1373
  226. package/vendor/Server/Skills/rn-library-consistency-check/references/SCORING_STANDARD.md +220 -220
  227. package/vendor/Server/Skills/rn-library-consistency-check/scripts/validate-skill.py +245 -245
  228. package/vendor/Server/Skills/rn-library-documentation-quality-check/SKILL.md +263 -263
  229. package/vendor/Server/Skills/rn-library-documentation-quality-check/assets/MODEL.md +414 -414
  230. package/vendor/Server/Skills/rn-library-documentation-quality-check/assets/MODEL_en.md +413 -413
  231. package/vendor/Server/Skills/rn-library-documentation-quality-check/assets/REPORT_TEMPLATE.md +311 -311
  232. package/vendor/Server/Skills/rn-library-documentation-quality-check/references/CHECK_CHECKLIST.md +355 -355
  233. package/vendor/Server/Skills/rn-library-documentation-quality-check/references/CROSS_VALIDATION_GUIDE.md +115 -115
  234. package/vendor/Server/Skills/rn-library-documentation-quality-check/references/DOC_COLLECTION_GUIDE.md +139 -139
  235. package/vendor/Server/Skills/rn-library-documentation-quality-check/references/EXAMPLES.md +586 -586
  236. package/vendor/Server/Skills/rn-library-documentation-quality-check/references/GOTCHAS.md +57 -57
  237. package/vendor/Server/Skills/rn-library-documentation-quality-check/scripts/validate-skill.py +259 -259
  238. package/vendor/Server/Skills/rn-library-interface-analyzer/SKILL.md +301 -301
  239. package/vendor/Server/Skills/rn-library-interface-analyzer/assets/REPORT_TEMPLATE.md +148 -148
  240. package/vendor/Server/Skills/rn-library-interface-analyzer/references/DOC_ANNOTATION_GUIDE.md +118 -118
  241. package/vendor/Server/Skills/rn-library-interface-analyzer/references/SCRIPT_USAGE_GUIDE.md +168 -168
  242. package/vendor/Server/Skills/rn-library-interface-analyzer/references/URL_PARSING_RULES.md +176 -176
  243. package/vendor/Server/Skills/rn-library-issue-generalizer/SKILL.md +274 -274
  244. package/vendor/Server/Skills/rn-library-issue-generalizer/assets/case-template.md +45 -45
  245. package/vendor/Server/Skills/rn-library-issue-generalizer/assets/rule-template.md +25 -25
  246. package/vendor/Server/Skills/rn-library-issue-generalizer/references/PR_FETCH_GUIDE.md +61 -61
  247. package/vendor/Server/Skills/rn-library-issue-generalizer/references/RULE_TEMPLATE_GUIDE.md +165 -165
  248. package/vendor/Server/Skills/rn-library-issue-generalizer/scripts/fetch-pr-info.py +239 -239
  249. package/vendor/Server/Skills/rn-library-known-issue-check/SKILL.md +263 -263
  250. package/vendor/Server/Skills/rn-library-known-issue-check/assets/REPORT_TEMPLATE.md +96 -96
  251. package/vendor/Server/Skills/rn-library-known-issue-check/references/COMPLIANCE_CHECKLIST.md +57 -57
  252. package/vendor/Server/Skills/rn-library-known-issue-check/references/INSPECTION_GUIDE.md +99 -99
  253. package/vendor/Server/Skills/rn-library-known-issue-check/references/PRESCREEN_GUIDE.md +64 -64
  254. package/vendor/Server/Skills/rn-library-known-issue-check/references/SOURCE_PREP_GUIDE.md +74 -74
  255. package/vendor/Server/Skills/rn-library-known-issue-check/scripts/validate-known-issue-report.py +164 -164
  256. package/vendor/Server/Skills/rn-library-memory-leak-check/SKILL.md +356 -339
  257. package/vendor/Server/Skills/rn-library-memory-leak-check/assets/REPORT_TEMPLATE.md +85 -83
  258. package/vendor/Server/Skills/rn-library-memory-leak-check/references/CHECKLIST.md +905 -859
  259. package/vendor/Server/Skills/rn-library-memory-leak-check/references/HARMONY_CODE_PATTERNS.md +124 -122
  260. package/vendor/Server/Skills/rn-library-memory-leak-check/scripts/scan_harmony_code.py +287 -279
  261. package/vendor/Server/Skills/rn-library-stability-check/SKILL.md +273 -273
  262. package/vendor/Server/Skills/rn-library-stability-check/assets/REPORT_TEMPLATE.md +129 -129
  263. package/vendor/Server/Skills/rn-library-stability-check/references/CHECKLIST.md +581 -581
  264. package/vendor/Server/Skills/rn-library-stability-check/references/SCORING_RULES.md +138 -138
  265. package/vendor/Server/Skills/rn-library-stability-check/scripts/scan-harmony-code.py +168 -168
  266. package/vendor/Server/Skills/rn-library-test-coverage-check/SKILL.md +526 -506
  267. package/vendor/Server/Skills/rn-library-test-coverage-check/references/CHECKLIST.md +321 -280
  268. package/vendor/Server/Skills/rn-library-test-coverage-check/references/DEMO_LOCATION.md +221 -221
  269. package/vendor/Server/Skills/rn-library-test-coverage-check/references/REPORT_TEMPLATE.md +220 -209
  270. package/vendor/Server/Skills/rn-library-test-coverage-check/references/SCRIPT_USAGE.md +325 -325
  271. package/vendor/Server/Skills/rn-ohos-xts-generator/SKILL.md +279 -279
  272. package/vendor/Server/Skills/rn-ohos-xts-generator/assets/TEST_FILE_TEMPLATES.md +404 -404
  273. package/vendor/Server/Skills/rn-ohos-xts-generator/references/BUILD_TROUBLESHOOTING.md +185 -185
  274. package/vendor/Server/Skills/rn-ohos-xts-generator/references/BUILD_WORKFLOW.md +265 -265
  275. package/vendor/Server/Skills/rn-ohos-xts-generator/references/COMMON_CONFIG.md +189 -189
  276. package/vendor/Server/Skills/rn-ohos-xts-generator/references/CONFIG_GUIDE.md +203 -203
  277. package/vendor/Server/Skills/rn-ohos-xts-generator/references/COVERAGE_ANALYZER.md +147 -147
  278. package/vendor/Server/Skills/rn-ohos-xts-generator/references/DESIGN_DOC_GUIDE.md +148 -148
  279. package/vendor/Server/Skills/rn-ohos-xts-generator/references/GENERATION_FLOW.md +165 -165
  280. package/vendor/Server/Skills/rn-ohos-xts-generator/references/GENERATION_STRATEGY.md +195 -195
  281. package/vendor/Server/Skills/rn-ohos-xts-generator/references/HARMONY_SCANNER.md +249 -249
  282. package/vendor/Server/Skills/rn-ohos-xts-generator/references/JEST_FRAMEWORK.md +235 -235
  283. package/vendor/Server/Skills/rn-ohos-xts-generator/references/PLATFORM_COMPAT.md +161 -161
  284. package/vendor/Server/Skills/rn-ohos-xts-generator/references/RN_TEST_PATTERNS.md +413 -413
  285. package/vendor/Server/Skills/rn-ohos-xts-generator/references/SOURCE_PARSER.md +235 -235
  286. package/vendor/Server/Skills/rn-ohos-xts-generator/references/TEST_CONVENTIONS.md +245 -245
  287. package/vendor/Server/Skills/rn-ohos-xts-generator/references/TROUBLESHOOTING.md +282 -282
  288. package/vendor/Server/Skills/rn-ohos-xts-generator/references/USAGE_GUIDE.md +251 -251
  289. package/vendor/Server/Skills/rnoh-cptf-api-test/SKILL.md +469 -469
  290. package/vendor/Server/Skills/rnoh-cptf-api-test/assets/CPTF_TEST_TEMPLATE.md +310 -310
  291. package/vendor/Server/Skills/rnoh-cptf-api-test/assets/DEMO_PAGE_TEMPLATE.md +303 -303
  292. package/vendor/Server/Skills/rnoh-cptf-api-test/references/CPTF_TEST_GENERATION_GUIDE.md +421 -421
  293. package/vendor/Server/Skills/rnoh-cptf-api-test/references/DEMO_GENERATION_GUIDE.md +358 -358
  294. package/vendor/Server/Skills/rnoh-cptf-api-test/references/QUALITY_CHECKLIST.md +114 -114
  295. package/vendor/Server/Skills/rnoh-cptf-api-test/references/SPEC_PARSING_GUIDE.md +274 -274
  296. package/vendor/Server/Skills/rnoh-cptf-api-test/scripts/validate-rnoh-cptf-api-test.sh +185 -185
  297. package/vendor/Server/Skills/rnoh-cptf-demo-test/SKILL.md +191 -191
  298. package/vendor/Server/Skills/rnoh-cptf-demo-test/assets/TEST_TEMPLATE.md +216 -216
  299. package/vendor/Server/Skills/rnoh-cptf-demo-test/references/CPTF_SETUP.md +107 -107
  300. package/vendor/Server/Skills/rnoh-cptf-demo-test/references/DEMO_ANALYSIS.md +120 -120
  301. package/vendor/Server/Skills/rnoh-cptf-demo-test/scripts/validate-rnoh-cptf-test.sh +108 -108
  302. package/vendor/Server/Skills/rnoh-cptf-test-run/SKILL.md +237 -237
  303. package/vendor/Server/Skills/rnoh-cptf-test-run/references/DEBUG_PLAYBOOK.md +261 -261
  304. package/vendor/Server/Skills/rnoh-cptf-test-run/scripts/validate-run-env.sh +112 -112
  305. package/vendor/Server/Skills/rnoh-lib-code-adapt/SKILL.md +497 -497
  306. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/adapt-checklist.md +270 -270
  307. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/api-migration-checklist.md +164 -164
  308. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/common-compile-errors.md +556 -556
  309. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/deveco-cli-tools.md +459 -459
  310. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/edge-cases.md +65 -65
  311. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/har-tgz-build.md +512 -512
  312. package/vendor/Server/Skills/rnoh-lib-code-adapt/references/version-compat-matrix.md +132 -132
  313. package/vendor/Server/Skills/rnoh-lib-code-adapt/scripts/auto-integrate.sh +424 -424
  314. package/vendor/Server/Skills/rnoh-lib-demo-coverage/SKILL.md +137 -137
  315. package/vendor/Server/Skills/rnoh-lib-demo-create/SKILL.md +306 -306
  316. package/vendor/Server/Skills/rnoh-lib-demo-create/assets/DEMO_PAGE_TEMPLATE.md +485 -485
  317. package/vendor/Server/Skills/rnoh-lib-demo-create/assets/INDEX_TEMPLATE.md +172 -172
  318. package/vendor/Server/Skills/rnoh-lib-demo-create/references/DEMO_CODE_RULES.md +422 -422
  319. package/vendor/Server/Skills/rnoh-lib-demo-create/references/QUALITY_CHECKLIST.md +95 -95
  320. package/vendor/Server/Skills/rnoh-lib-demo-create/references/SOURCE_EXPLORATION.md +169 -169
  321. package/vendor/Server/Skills/rnoh-lib-demo-doc/SKILL.md +554 -554
  322. package/vendor/Server/Skills/rnoh-lib-demo-doc/assets/DEMO_DOC_TEMPLATE.md +106 -106
  323. package/vendor/Server/Skills/rnoh-lib-demo-doc/references/COVERAGE_INCREMENTAL.md +216 -216
  324. package/vendor/Server/Skills/rnoh-lib-demo-doc/references/DEMO_DESIGN_RULES.md +413 -413
  325. package/vendor/Server/Skills/rnoh-lib-demo-doc/references/OUTPUT_FORMAT.md +269 -269
  326. package/vendor/Server/Skills/rnoh-lib-demo-doc/references/QUALITY_CHECKLIST.md +98 -98
  327. package/vendor/Server/Skills/rnoh-lib-func-test/SKILL.md +337 -337
  328. package/vendor/Server/Skills/rnoh-lib-rnt-search/SKILL.md +722 -722
  329. package/vendor/Server/Skills/rnoh-lib-rnt-search/assets/PORT_REPORT_TEMPLATE.md +219 -219
  330. package/vendor/Server/Skills/rnoh-lib-rnt-search/references/DEMO_PORTING_GUIDE.md +345 -345
  331. package/vendor/Server/Skills/rnoh-lib-rnt-search/references/PORT_VERIFICATION.md +269 -269
  332. package/vendor/Server/Skills/rnoh-lib-rnt-search/references/RNT_PROJECT_STRUCTURE.md +173 -173
  333. package/vendor/Server/Skills/rnoh-lib-rnt-search/scripts/analyze-demo-deps.cjs +267 -267
  334. package/vendor/Server/Skills/rnoh-lib-rnt-search/scripts/detect-rnoh-version.cjs +174 -174
  335. package/vendor/Server/Skills/rnoh-lib-rnt-search/scripts/find-rnt-demo.sh +111 -111
  336. package/vendor/Server/Skills/rnoh-lib-rnt-search/scripts/port-demo.sh +186 -186
  337. package/vendor/Server/Skills/rnoh-lib-rnt-search/scripts/read-lib-meta.cjs +150 -150
  338. package/vendor/Server/Skills/rnoh-lib-test-align/SKILL.md +296 -296
  339. package/vendor/Server/Skills/rnoh-lib-test-align/references/jest-troubleshooting.md +371 -371
  340. package/vendor/Server/Skills/rnoh-lib-test-align/references/port-test-demo-guide.md +212 -212
  341. package/vendor/Server/Skills/rnoh-lib-test-align/references/runtime-troubleshooting.md +345 -345
  342. package/vendor/Server/Skills/rnoh-lib-test-align/references/unit-test-template.md +223 -223
  343. package/vendor/Server/Skills/rnoh-lib-test-align/scripts/port-test-demo.sh +1053 -1053
  344. package/vendor/Server/Skills/rnoh-lib-version-diff/SKILL.md +295 -255
  345. package/vendor/Server/Skills/rnoh-lib-version-diff/references/OHOS_ADAPTATION.md +82 -77
  346. package/vendor/Server/Skills/rnoh-lib-version-diff/references/OHOS_API_LOOKUP.md +224 -224
  347. package/vendor/Server/Skills/rnoh-lib-version-diff/references/script-reference.md +175 -174
  348. package/vendor/Server/Skills/rnoh-lib-version-diff/scripts/detect-upstream-version.js +967 -967
  349. package/vendor/Server/Skills/rnoh-lib-version-diff/scripts/generate-diff.js +1798 -1798
  350. package/vendor/Server/Skills/rnoh-lib-version-diff/scripts/package.json +5 -5
  351. package/vendor/Server/Skills/rnoh-lib-version-diff/templates/report-template.md +180 -137
  352. package/vendor/Server/Skills/rnoh-lib-xts-coverage/SKILL.md +145 -145
  353. package/vendor/Server/Skills/skill-generator/SKILL.md +365 -365
  354. package/vendor/Server/Skills/skill-generator/assets/SKILL_TEMPLATE.md +183 -183
  355. package/vendor/Server/Skills/skill-generator/references/COMPLIANCE_CHECKLIST.md +82 -82
  356. package/vendor/Server/Skills/skill-generator/references/KB_QUERY_GUIDE.md +110 -110
  357. package/vendor/Server/Skills/skill-generator/references/MCP_TOOL_DISCOVERY.md +122 -122
  358. package/vendor/Server/Skills/skill-generator/references/SKILL_SPEC.md +121 -121
  359. package/vendor/Server/Skills/skill-generator/scripts/validate-skill.cjs +259 -259
  360. package/vendor/Server/Skills/task-analysis/SKILL.md +234 -234
  361. package/vendor/Server/Skills/task-analysis/assets/OUTPUT_EXAMPLES.md +160 -160
  362. package/vendor/Server/Skills/task-analysis/references/ACCEPTANCE_CRITERIA_GUIDE.md +190 -190
  363. package/vendor/Server/Skills/task-analysis/references/ANALYSIS_SCHEMA.md +224 -224
  364. package/vendor/Server/Skills/task-analysis/references/INTEGRATION_CONTEXT.md +162 -162
  365. package/vendor/Server/Skills/task-analysis/references/LESSONS_LEARNED.md +55 -55
  366. package/vendor/Server/Skills/task-analysis/references/REPLAN_CONTEXT_GUIDE.md +126 -126
  367. package/vendor/Server/Skills/task-analysis/scripts/validate-analysis-output.sh +256 -256
  368. package/vendor/Server/Skills/task-decomposition/SKILL.md +528 -528
  369. package/vendor/Server/Skills/task-decomposition/assets/OUTPUT_EXAMPLES.md +451 -451
  370. package/vendor/Server/Skills/task-decomposition/references/ACCEPTANCE_CRITERIA_GUIDE.md +179 -179
  371. package/vendor/Server/Skills/task-decomposition/references/DEPENDENCY_GRAPH_GUIDE.md +152 -152
  372. package/vendor/Server/Skills/task-decomposition/references/INTEGRATION_CONTEXT.md +175 -175
  373. package/vendor/Server/Skills/task-decomposition/references/REPLAN_CONTEXT_GUIDE.md +195 -195
  374. package/vendor/Server/Skills/task-decomposition/references/TASK_DECOMPOSITION_TEMPLATES.md +226 -226
  375. package/vendor/Server/Skills/task-decomposition/scripts/list-available-skills.cjs +263 -263
  376. package/vendor/Server/Skills/task-decomposition/scripts/skill-blacklist.json +29 -29
  377. package/vendor/Server/Skills/task-decomposition/scripts/validate-decomposition-output.cjs +376 -376
  378. package/vendor/Server/Skills/task-decomposition/scripts/validate-param-consistency.cjs +259 -259
  379. package/vendor/Server/Skills/task-decomposition/scripts/validate-specified-skills.cjs +216 -216
  380. package/vendor/Server/Skills/task-decomposition/scripts/validate-step-graph.cjs +424 -424
  381. package/vendor/Server/Skills/tpc-cpp-check/SKILL.md +427 -427
  382. package/vendor/Server/Skills/tpc-cpp-check/references/CHECKLIST.md +214 -214
  383. package/vendor/Server/Skills/tpc-cpp-check/references/HPKBUILD_GUIDE.md +235 -235
  384. package/vendor/Server/Skills/tpc-cpp-check/references/REPORT_TEMPLATE.md +250 -250
  385. package/vendor/Server/TestCheck/TestCheck.js +775 -775
  386. package/vendor/Server/TestCheck/index.js +11 -11
  387. package/vendor/Server/library/McpToolGuide.js +280 -280
  388. package/vendor/Server/library/StatsService.js +126 -126
  389. package/vendor/Server/library/cstTime.js +16 -16
  390. package/vendor/VERSION +3 -3
  391. package/workflows/pr-check.mjs +105 -105
  392. package/workflows/pr-push.mjs +193 -0
  393. package/vendor/Server/Agent/SkillSelector/types.js +0 -63
@@ -1,1759 +1,1759 @@
1
- /**
2
- * FlexRunner —— 通用执行模块
3
- *
4
- * 接收一个具体事项,将其拆解为多个步骤,并对每个步骤进行执行和追踪。
5
- *
6
- * 核心职责:
7
- * 1. initContext — 初始化任务上下文(工作目录、报告路径等)
8
- * 2. matchSkill — 基于语义拆解与重排序机制匹配最佳 Skill
9
- * 3. invokeSkill — 通过 opencode cli 执行选定的 Skill
10
- * 4. executeStart — 驱动完整执行流程(匹配 → 执行 → 检查 → 持久化)
11
- * 5. controlExecution — 控制执行步骤(暂停 / 继续 / 终止)
12
- * 6. persistKnowledge — 将有效经验存入任务
13
- * 7. getSessionContent / checkResult — 辅助查询
14
- *
15
- * 依赖:
16
- * - CLIController (opencode) 用于执行 Skill
17
- * - SkillSelector Agent 用于语义匹配 Skill
18
- * - TaskStepStore (SQLite) 用于步骤持久化
19
- *
20
- * @example
21
- * import { FlexRunner } from './FlexRunner/FlexRunner.js';
22
- *
23
- * const runner = new FlexRunner();
24
- * await runner.initContext({
25
- * taskId: 'task-001',
26
- * taskDir: '/workspace/tasks/task-001',
27
- * skillDirectory: '/workspace/Server/Skills',
28
- * taskDescription: '分析 libcurl 的鸿蒙化可行性',
29
- * maxRetries: 3
30
- * });
31
- * const ok = await runner.executeStart();
32
- */
33
-
34
- import path from 'node:path';
35
- import { fileURLToPath } from 'node:url';
36
- import fs from 'node:fs/promises';
37
-
38
- import { nowCST } from '../library/cstTime.js';
39
- import { createLogger } from '../Routes/library/logger.js';
40
-
41
- // dotenv 为可选依赖:生产环境加载 .env,未安装时跳过(如纯 mock 测试场景)
42
- try {
43
- const dotenv = (await import('dotenv')).default;
44
- dotenv.config({ path: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '.env') });
45
- } catch {
46
- // dotenv 未安装,跳过 .env 加载
47
- }
48
-
49
- // CLIController / SkillSelectorAgent / createStorage 为惰性加载:
50
- // 测试中通过 initContext 注入 mock 时不需要加载这些模块及其重依赖(@opencode-ai/sdk、openai 等)。
51
- // 仅在未注入对应实例时才动态 import。
52
- let _CLIController = null;
53
- let _SkillSelectorAgent = null;
54
- let _createStorage = null;
55
- let _KnowledgeManager = null;
56
- let _McpToolGuide = null;
57
-
58
- async function _loadCLIController() {
59
- if (!_CLIController) {
60
- const mod = await import('../CLI/cli.js');
61
- _CLIController = mod.CLIController;
62
- }
63
- return _CLIController;
64
- }
65
-
66
- async function _loadSkillSelectorAgent() {
67
- if (!_SkillSelectorAgent) {
68
- const mod = await import('../Agent/SkillSelector/index.js');
69
- _SkillSelectorAgent = mod.Agent;
70
- }
71
- return _SkillSelectorAgent;
72
- }
73
-
74
- async function _loadCreateStorage() {
75
- if (!_createStorage) {
76
- const mod = await import('../DbUse/index.js');
77
- _createStorage = mod.createStorage;
78
- }
79
- return _createStorage;
80
- }
81
-
82
- async function _loadKnowledgeManager() {
83
- if (!_KnowledgeManager) {
84
- const mod = await import('../Knowledge/index.js');
85
- _KnowledgeManager = mod.KnowledgeManager;
86
- }
87
- return _KnowledgeManager;
88
- }
89
-
90
- async function _loadMcpToolGuide() {
91
- if (!_McpToolGuide) {
92
- const mod = await import('../library/McpToolGuide.js');
93
- _McpToolGuide = mod.McpToolGuide;
94
- }
95
- return _McpToolGuide;
96
- }
97
-
98
- // ─── 常量 ────────────────────────────────────────────────────────────────────
99
-
100
- /** 执行控制类型 */
101
- const ControlType = Object.freeze({
102
- PAUSE: 'pause',
103
- RESUME: 'resume',
104
- ABORT: 'abort'
105
- });
106
-
107
- /** 步骤状态 */
108
- const StepStatus = Object.freeze({
109
- PENDING: 'pending',
110
- RUNNING: 'running',
111
- COMPLETED: 'completed',
112
- ERROR: 'error',
113
- SKIPPED: 'skipped'
114
- });
115
-
116
- /** 默认最大重试次数 */
117
- const DEFAULT_MAX_RETRIES = 3;
118
-
119
- /** 经验总结环节等待文件生成超时(ms),默认 5 分钟 */
120
- const SUMMARY_TIMEOUT_MS = 5 * 60 * 1000;
121
-
122
- /** 轮询间隔(ms),用于等待 opencode session 执行完成 */
123
- const POLL_INTERVAL_MS = 5000;
124
-
125
- /** 轮询超时(ms),单个步骤最多等待 1.5 小时 */
126
- const POLL_TIMEOUT_MS = 90 * 60 * 1000;
127
-
128
- // ─── FlexRunner 类 ──────────────────────────────────────────────────────────
129
-
130
- class FlexRunner {
131
- // ─── 私有变量(通过 # 前缀约定,配合 getter 暴露只读访问) ──────────────────
132
-
133
- /** @type {string} 任务 ID */
134
- #taskId = '';
135
-
136
- /** @type {string} 工作目录 */
137
- #taskDir = '';
138
-
139
- /** @type {number} 最大重试次数 */
140
- #maxRetries = DEFAULT_MAX_RETRIES;
141
-
142
- /** @type {number} 已循环次数 */
143
- #retryTimes = 0;
144
-
145
- /** @type {string|null} 执行开始时间 */
146
- #startTime = null;
147
-
148
- /** @type {string|null} 执行结束时间 */
149
- #endTime = null;
150
-
151
- /** @type {string} 输入报告路径 */
152
- #inputReport = '';
153
-
154
- /** @type {string} SKILL 目录路径 */
155
- #skillDirectory = '';
156
-
157
- /** @type {string} 指定 SKILL(name 或目录名);非空时跳过自动匹配直接使用 */
158
- #specifiedSkill = '';
159
-
160
- /** @type {string} 任务描述 */
161
- #taskDescription = '';
162
-
163
- /** @type {number} 当前步骤 ID(正整数) */
164
- #stepId = 0;
165
-
166
- /** @type {number} 依赖步骤 ID(0 = 无依赖) */
167
- #dependId = 0;
168
-
169
- /** @type {number} 下一步骤 ID(0 = 无下一步) */
170
- #nextStepId = 0;
171
-
172
- /** @type {number} 失败跳转步骤 ID(0 = 失败即终止) */
173
- #failStepId = 0;
174
-
175
- /** @type {number} 大循环索引(0=首轮),由 LoopEngine 传递 */
176
- #bigLoopIndex = 0;
177
-
178
- /** @type {number} 当前已执行到的步骤序号(单步内重试计数) */
179
- #executeStep = 0;
180
-
181
- /** @type {string} 最新结果文件路径 */
182
- #resultPath = '';
183
-
184
- /** @type {string} 会话 ID */
185
- #sessionId = '';
186
-
187
- // ─── 内部依赖(注入或懒加载) ──────────────────────────────────────────────
188
-
189
- /** @type {CLIController|null} */
190
- #cli = null;
191
-
192
- /** @type {SkillSelectorAgent|null} */
193
- #skillSelector = null;
194
-
195
- /** @type {ReturnType<createStorage>|null} */
196
- #storage = null;
197
-
198
- /** @type {import('../Knowledge/KnowledgeManager.js').default|null} */
199
- #knowledgeManager = null;
200
-
201
- /** @type {import('../library/McpToolGuide.js').default|null} */
202
- #mcpToolGuide = null;
203
-
204
- /** @type {boolean} 是否已初始化 */
205
- #initialized = false;
206
-
207
- /** @type {boolean} 是否暂停 */
208
- #paused = false;
209
-
210
- /** @type {boolean} 是否已终止 */
211
- #aborted = false;
212
-
213
- /** @type {string|null} 匹配到的最佳 SKILL 目录 */
214
- #matchedSkillDir = null;
215
-
216
- /** @type {object|null} 本次执行收割的结构化指标(来自 meta .json 旁车文件,通用键值对) */
217
- #metrics = null;
218
-
219
- /** @type {((sessionId: string) => void)|null} Session 创建后的回调(用于实时同步 sessionId 到编排层) */
220
- #onSessionCreated = null;
221
-
222
- /** @type {number} 轮询间隔(ms) */
223
- #pollIntervalMs = POLL_INTERVAL_MS;
224
-
225
- /**
226
- * 构造函数 — 创建 FlexRunner 实例。
227
- *
228
- * 支持两种使用方式:
229
- * 1. 无参构造 + 后续调用 initContext()
230
- * 2. 构造时传入配置对象,自动完成初始化
231
- *
232
- * @param {object} [config] - 可选的初始化配置(同 initContext 入参)
233
- */
234
- constructor(config) {
235
- if (config && typeof config === 'object') {
236
- // 延迟到 initContext 中处理,避免构造函数中执行异步逻辑
237
- this._pendingConfig = config;
238
- }
239
- }
240
-
241
- // ─── 只读 getter ───────────────────────────────────────────────────────────
242
-
243
- /** @returns {string} */
244
- get taskId() { return this.#taskId; }
245
- /** @returns {string} */
246
- get taskDir() { return this.#taskDir; }
247
- /** @returns {number} */
248
- get maxRetries() { return this.#maxRetries; }
249
- /** @returns {number} */
250
- get retryTimes() { return this.#retryTimes; }
251
- /** @returns {string|null} */
252
- get startTime() { return this.#startTime; }
253
- /** @returns {string|null} */
254
- get endTime() { return this.#endTime; }
255
- /** @returns {string} */
256
- get inputReport() { return this.#inputReport; }
257
- /** @returns {string} */
258
- get skillDirectory() { return this.#skillDirectory; }
259
- /** @returns {string} 指定 SKILL(name 或目录名),未指定时为空串 */
260
- get specifiedSkill() { return this.#specifiedSkill; }
261
- /** @returns {string} */
262
- get taskDescription() { return this.#taskDescription; }
263
- /** @returns {number} */
264
- get stepId() { return this.#stepId; }
265
- /** @returns {number} */
266
- get dependId() { return this.#dependId; }
267
- /** @returns {number} */
268
- get nextStepId() { return this.#nextStepId; }
269
- /** @returns {number} */
270
- get failStepId() { return this.#failStepId; }
271
- /** @returns {number} 大循环索引(0=首轮) */
272
- get bigLoopIndex() { return this.#bigLoopIndex; }
273
- /** @returns {number} */
274
- get executeStep() { return this.#executeStep; }
275
- /** @returns {string} */
276
- get resultPath() { return this.#resultPath; }
277
- /** @returns {string} */
278
- get sessionId() { return this.#sessionId; }
279
- /** @returns {boolean} */
280
- get initialized() { return this.#initialized; }
281
- /** @returns {object|null} 本次执行收割的结构化指标(无则 null) */
282
- get metrics() { return this.#metrics; }
283
-
284
- /**
285
- * 设置 Session 创建后的回调(可在 initContext 之后注入)。
286
- * @param {((sessionId: string) => void|Promise<void>)|null} fn
287
- */
288
- set onSessionCreated(fn) {
289
- this.#onSessionCreated = typeof fn === 'function' ? fn : null;
290
- }
291
-
292
- // ─── 公开方法 ─────────────────────────────────────────────────────────────
293
-
294
- /**
295
- * initContext — 初始化任务上下文。
296
- *
297
- * 解析入参 JSON 对象,设置任务 ID、工作目录、SKILL 目录、任务描述等,
298
- * 并懒初始化 CLI 控制器、Skill 选择器、存储层等内部依赖。
299
- *
300
- * @param {object} params - 初始化参数
301
- * @param {string} params.taskId - 任务 ID(必填)
302
- * @param {string} [params.taskDir] - 工作目录(默认基于 taskId 推导)
303
- * @param {string} [params.skillDirectory] - SKILL 目录路径
304
- * @param {string} [params.specifiedSkill] - 指定 SKILL(name 或目录名);
305
- * 非空时跳过 matchSkill 自动匹配,直接解析并使用该 SKILL
306
- * @param {string} [params.taskDescription] - 任务描述
307
- * @param {string} [params.inputReport] - 输入报告路径
308
- * @param {number} [params.maxRetries] - 最大重试次数(默认 3)
309
- * @param {number} [params.stepId] - 当前步骤 ID(正整数,必填)
310
- * @param {number} [params.dependId] - 依赖步骤 ID(0 = 无依赖)
311
- * @param {number} [params.nextStepId] - 下一步骤 ID(0 = 无下一步)
312
- * @param {number} [params.failStepId] - 失败跳转步骤 ID(0 = 失败即终止)
313
- * @param {CLIController} [params.cli] - 注入自定义 CLI 控制器(测试用)
314
- * @param {SkillSelectorAgent} [params.skillSelector] - 注入自定义 Skill 选择器
315
- * @param {ReturnType<createStorage>} [params.storage] - 注入自定义存储层
316
- * @param {number} [params.pollIntervalMs] - 轮询间隔 ms(默认 3000)
317
- * @param {string} [params.mcpConfigPath] - MCP config.json 路径(默认自动推导)
318
- * @param {((sessionId: string) => void|Promise<void>)} [params.onSessionCreated] - Session 创建后的回调
319
- * @returns {Promise<void>}
320
- */
321
- async initContext(params = {}) {
322
- if (!params || typeof params !== 'object') {
323
- throw new Error('FlexRunner.initContext: 入参必须是一个 JSON 对象');
324
- }
325
-
326
- const {
327
- taskId,
328
- taskDir,
329
- skillDirectory,
330
- specifiedSkill,
331
- taskDescription,
332
- inputReport,
333
- maxRetries,
334
- stepId,
335
- dependId,
336
- nextStepId,
337
- failStepId,
338
- bigLoopIndex,
339
- cli,
340
- skillSelector,
341
- storage,
342
- knowledgeManager,
343
- pollIntervalMs,
344
- mcpConfigPath,
345
- onSessionCreated
346
- } = params;
347
-
348
- if (!taskId) {
349
- throw new Error('FlexRunner.initContext: taskId 为必填项');
350
- }
351
-
352
- // stepId 必须为正整数
353
- const numStepId = Number(stepId);
354
- if (!Number.isInteger(numStepId) || numStepId <= 0) {
355
- throw new Error(`FlexRunner.initContext: stepId 必须为正整数,当前值: ${stepId}`);
356
- }
357
-
358
- // ── 初始化内部依赖(支持注入,便于测试;未注入时惰性加载) ──
359
- // 先初始化 storage,因为 taskDir 的 fallback 需要用到 storage.manager.rootDir
360
- if (storage) {
361
- this.#storage = storage;
362
- } else {
363
- const createStorage = await _loadCreateStorage();
364
- this.#storage = createStorage();
365
- }
366
-
367
- // ── 设置私有变量 ──
368
- this.#taskId = String(taskId);
369
- // taskDir 默认为 db/task/{taskId}(与 storage.json('task') 同目录)
370
- const _rootDir = this.#storage?.manager?.rootDir;
371
- this.#taskDir = taskDir ||
372
- (_rootDir
373
- ? path.resolve(_rootDir, 'task', this.#taskId)
374
- : path.resolve(process.cwd(), 'db', 'task', this.#taskId));
375
- this.#skillDirectory = skillDirectory || '';
376
- this.#specifiedSkill = String(specifiedSkill || '').trim();
377
- this.#taskDescription = taskDescription || '';
378
- this.#inputReport = inputReport || '';
379
- this.#maxRetries = typeof maxRetries === 'number' ? maxRetries : DEFAULT_MAX_RETRIES;
380
- this.#stepId = numStepId;
381
- // dependId 支持数组(fan-in 聚合),此处仅取第一个作为回退锚点语义
382
- this.#dependId = Number(Array.isArray(dependId) ? dependId[0] : dependId) || 0;
383
- this.#nextStepId = Number(nextStepId) || 0;
384
- this.#failStepId = Number(failStepId) || 0;
385
- this.#bigLoopIndex = Number(bigLoopIndex) || 0;
386
- this.#executeStep = 0;
387
- this.#retryTimes = 0;
388
- this.#startTime = null;
389
- this.#endTime = null;
390
- this.#resultPath = '';
391
- this.#sessionId = '';
392
- this.#paused = false;
393
- this.#aborted = false;
394
- this.#matchedSkillDir = null;
395
- this.#onSessionCreated = typeof onSessionCreated === 'function' ? onSessionCreated : null;
396
- this.#pollIntervalMs = typeof pollIntervalMs === 'number' && pollIntervalMs > 0
397
- ? pollIntervalMs
398
- : POLL_INTERVAL_MS;
399
-
400
- // ── 初始化其他内部依赖(支持注入,便于测试;未注入时惰性加载) ──
401
- if (cli) {
402
- this.#cli = cli;
403
- } else {
404
- const CLIController = await _loadCLIController();
405
- this.#cli = new CLIController('opencode', {});
406
- }
407
-
408
- if (skillSelector) {
409
- this.#skillSelector = skillSelector;
410
- } else {
411
- const SkillSelectorAgent = await _loadSkillSelectorAgent();
412
- this.#skillSelector = new SkillSelectorAgent();
413
- }
414
-
415
- // 知识沉淀管理器(支持注入,便于测试;未注入时惰性加载 + init)
416
- if (knowledgeManager) {
417
- this.#knowledgeManager = knowledgeManager;
418
- } else {
419
- const KnowledgeManager = await _loadKnowledgeManager();
420
- this.#knowledgeManager = new KnowledgeManager();
421
- await this.#knowledgeManager.init();
422
- }
423
-
424
- // MCP 工具引导(支持注入;未注入时惰性加载,用 mcpConfigPath 或默认路径)
425
- const McpToolGuide = await _loadMcpToolGuide();
426
- this.#mcpToolGuide = new McpToolGuide(mcpConfigPath);
427
-
428
- this.#initialized = true;
429
- }
430
-
431
- /**
432
- * executeStart — 驱动单次执行流程(6 步)。
433
- *
434
- * 本方法为**单次执行**,不内部循环。外部执行机构根据返回值决定是否
435
- * 再次调用本方法进行重试。每次调用 #executeStep 递增,生成的文件
436
- * 以 loopCount 区分。
437
- *
438
- * 流程:
439
- * 1. matchSkill → 匹配最佳 Skill(未匹配到时返回 null,降级为无 SKILL 模式)
440
- * 2. invokeSkill → 通过 opencode 执行 Skill,生成 result .md 文件
441
- * (skillDir 为 null 时,基于任务描述本身直接执行,不使用 SKILL)
442
- * (第 N 次执行时,自动收集历史 result/summary .md 作为上下文)
443
- * (初始 prompt 仅负责执行任务 + 生成 result .md,不包含经验总结指令)
444
- * 3. checkResult → 读取 result .md,判断成功/失败
445
- * 4. 返回 { resultPath, success, nextStepId }
446
- * 5.(后台异步)_summarizeAndPersist → 仅在成功后,向同一 Session 追加经验总结 prompt
447
- * (通过 sendAndWaitMessage 等待 AI 生成 Summary .md,再 persistKnowledge)
448
- * (fire-and-forget:不阻塞 executeStart 返回,不影响步骤流转)
449
- * (失败/超时降级:不影响步骤成功状态,仅记录 warn 日志)
450
- *
451
- * 文件命名(按大循环轮次 + 步骤内重试次数区分):
452
- * - 结果文件: stepId{actualStepId}_loop{bigLoopIndex}_result_{retryCount}.md
453
- * - 经验文件: stepId{actualStepId}_loop{bigLoopIndex}_Summary_{retryCount}.md
454
- * - 指标文件: stepId{actualStepId}_loop{bigLoopIndex}_meta_{retryCount}.json(可选,SKILL 约定的结构化结论)
455
- *
456
- * 控制信号(pause/resume/abort)在步骤边界检查,非实时。
457
- *
458
- * @returns {Promise<{resultPath: string, success: boolean, nextStepId: number}>}}
459
- */
460
- async executeStart() {
461
- this._ensureInitialized();
462
- if (this.#aborted) {
463
- throw new Error('FlexRunner.executeStart: 任务已被终止,无法启动');
464
- }
465
-
466
- const loopCount = this.#executeStep;
467
- this.#startTime = nowCST();
468
- let resultPath = '';
469
- let success = false;
470
-
471
- this._log('info', `── 第 ${loopCount + 1} 次执行(loopCount=${loopCount})──`);
472
-
473
- // 写入初始步骤记录
474
- await this._persistStep({
475
- status: StepStatus.RUNNING,
476
- startTime: this.#startTime,
477
- executeStep: loopCount
478
- });
479
-
480
- try {
481
- // ── 步骤 1:matchSkill ──
482
- // 指定 SKILL(specifiedSkill 非空)时跳过自动匹配,直接解析使用
483
- await this._waitIfPaused();
484
- if (this.#aborted) {
485
- this._log('warn', `任务在 matchSkill 前被终止`);
486
- } else if (this.#specifiedSkill) {
487
- this.#matchedSkillDir = await this._resolveSpecifiedSkill(
488
- this.#specifiedSkill,
489
- this.#skillDirectory
490
- );
491
- await this._persistStep({
492
- matchedSkillDir: this.#matchedSkillDir,
493
- executeStep: loopCount
494
- });
495
- } else {
496
- this.#matchedSkillDir = await this.matchSkill(
497
- this.#taskDescription,
498
- this.#skillDirectory
499
- );
500
- await this._persistStep({
501
- matchedSkillDir: this.#matchedSkillDir,
502
- executeStep: loopCount
503
- });
504
- }
505
-
506
- // ── 构建文件路径(按大循环轮次区分,避免跨轮覆盖) ──
507
- resultPath = path.join(
508
- this.#taskDir,
509
- `stepId${this.#stepId}_loop${this.#bigLoopIndex}_result_${loopCount}.md`
510
- );
511
- const summaryFilePath = path.join(
512
- this.#taskDir,
513
- `stepId${this.#stepId}_loop${this.#bigLoopIndex}_Summary_${loopCount}.md`
514
- );
515
- const metaFilePath = path.join(
516
- this.#taskDir,
517
- `stepId${this.#stepId}_loop${this.#bigLoopIndex}_meta_${loopCount}.json`
518
- );
519
-
520
- // ── 收集历史执行文档(第 N 次执行时传入之前的结果/经验) ──
521
- const historyDocs = await this._collectHistoryDocs(loopCount);
522
-
523
- // ── 步骤 2:invokeSkill(生成 result .md) ──
524
- await this._waitIfPaused();
525
- if (!this.#aborted) {
526
- const invoked = await this.invokeSkill(
527
- this.#taskDescription,
528
- this.#matchedSkillDir,
529
- this.#inputReport || undefined,
530
- { resultFilePath: resultPath, metaFilePath, historyDocs }
531
- );
532
-
533
- if (!invoked) {
534
- throw new Error('invokeSkill 返回 false,执行失败');
535
- }
536
-
537
- if (this.#sessionId) {
538
- await this._persistStep({
539
- sessionId: this.#sessionId,
540
- executeStep: loopCount
541
- });
542
- }
543
-
544
- // ── 步骤 3:checkResult(读取 result .md 判断成功/失败) ──
545
- await this._waitIfPaused();
546
- const ok = await this.checkResult(resultPath);
547
-
548
- if (ok) {
549
- success = true;
550
- // ── 收割结构化指标(meta .json 旁车文件,通用键值对,后端不解释语义) ──
551
- this.#metrics = await this._harvestMetrics(metaFilePath);
552
- this._log('info', '✅ 执行成功,经验总结将在后台异步进行');
553
- // ── 后台异步:经验总结 + 知识持久化(不阻塞 executeStart 返回) ──
554
- // capture sessionId 防止实例复用时被覆盖
555
- const sid = this.#sessionId;
556
- const skillDir = this.#matchedSkillDir;
557
- this._summarizeAndPersist(summaryFilePath, skillDir, sid).catch((err) => {
558
- this._log('warn', `后台经验总结/持久化异常: ${err.message}`);
559
- });
560
- } else {
561
- this._log('warn', `checkResult 未通过(loopCount=${loopCount})`);
562
- }
563
- }
564
- } catch (err) {
565
- this._log('error', `执行异常: ${err.message}`);
566
- }
567
-
568
- this.#endTime = nowCST();
569
- this.#resultPath = resultPath;
570
-
571
- // 更新步骤记录:成功 / 失败 / 终止
572
- const finalStatus = this.#aborted
573
- ? StepStatus.SKIPPED
574
- : (success ? StepStatus.COMPLETED : StepStatus.ERROR);
575
- await this._persistStep({
576
- status: finalStatus,
577
- endTime: this.#endTime,
578
- executeStep: loopCount,
579
- resultPath,
580
- retryTimes: loopCount,
581
- metrics: this.#metrics
582
- });
583
-
584
- // 递增执行计数,供下一次调用使用
585
- this.#executeStep++;
586
-
587
- // 成功 → nextStepId;失败 → failStepId(与 Orchestrator 的失败流转语义对齐)
588
- const nextStepId = success ? this.#nextStepId : this.#failStepId;
589
-
590
- return { resultPath, success, nextStepId, metrics: this.#metrics };
591
- }
592
-
593
- /**
594
- * canRetry — 判断当前步骤是否还可以继续重试。
595
- *
596
- * 供外部执行机构在调用 executeStart() 前检查:
597
- * - 若返回 false,表示已达最大重试次数,不应再次调用。
598
- * - 若返回 true,可以继续调用 executeStart() 进行重试。
599
- *
600
- * @returns {boolean} 是否还能重试
601
- */
602
- canRetry() {
603
- return this.#executeStep <= this.#maxRetries && !this.#aborted;
604
- }
605
-
606
- /**
607
- * matchSkill — 基于语义拆解与重排序机制匹配最佳 Skill。
608
- *
609
- * 委托 SkillSelector Agent(ReAct 模式):
610
- * Reason #1: LLM 拆解任务 → 生成关键词/意图/技术栈
611
- * Act: 模糊匹配召回 topK 候选
612
- * Reason #2: LLM 评分排序 → 选出最佳
613
- *
614
- * 匹配失败时的策略:
615
- * - SKILL 目录为空或未找到任何 SKILL → 返回 null(降级为无 SKILL 执行)
616
- * - 模糊匹配未召回任何候选 → 返回 null
617
- * - top1 分数低于命中阈值 → 返回 null
618
- * - 匹配结果缺少目录路径 → 返回 null
619
- * 调用方(executeStart)收到 null 后将以无 SKILL 模式继续向下执行。
620
- *
621
- * @param {string} taskDescription - 任务描述字符串
622
- * @param {string} skillDirectory - SKILL 目录路径
623
- * @returns {Promise<string|null>} 最适合的 SKILL 目录绝对路径;未匹配到时返回 null
624
- */
625
- async matchSkill(taskDescription, skillDirectory) {
626
- this._ensureInitialized();
627
-
628
- if (!taskDescription) {
629
- throw new Error('FlexRunner.matchSkill: taskDescription 不能为空');
630
- }
631
- if (!skillDirectory) {
632
- this._log('warn', 'matchSkill: skillDirectory 为空,将以无 SKILL 模式执行');
633
- return null;
634
- }
635
-
636
- this._log('info', `matchSkill 开始 — task: "${taskDescription.slice(0, 80)}…"`);
637
-
638
- let selection;
639
- try {
640
- selection = await this.#skillSelector.selectSkill(taskDescription, skillDirectory);
641
- } catch (err) {
642
- this._log('warn', `matchSkill: SkillSelector 执行异常 — ${err.message},将以无 SKILL 模式执行`);
643
- return null;
644
- }
645
-
646
- if (!selection || !selection.best) {
647
- this._log('warn', `matchSkill: 未匹配到任何合适的 Skill(topScore=${selection?.topScore ?? 0}),将以无 SKILL 模式执行`);
648
- return null;
649
- }
650
-
651
- // 优先使用 SkillSelection.skillPath,回退到 SkillMeta.skillPath
652
- const bestDir = selection.skillPath || selection.best.skillPath;
653
- if (!bestDir) {
654
- this._log('warn', 'matchSkill: 匹配结果缺少 Skill 目录路径,将以无 SKILL 模式执行');
655
- return null;
656
- }
657
-
658
- this._log('info', `matchSkill 完成 — 最佳 Skill: ${selection.best.name} (${bestDir})`);
659
- return bestDir;
660
- }
661
-
662
- /**
663
- * _resolveSpecifiedSkill — 解析用户指定的 SKILL(跳过自动匹配)。
664
- *
665
- * 解析顺序(在 skillDirectory 下):
666
- * 1. 目录名精确匹配 → {skillDirectory}/{specifiedSkill}
667
- * 2. SKILL name 匹配 → 扫描所有 SKILL.md frontmatter 的 name 字段
668
- *
669
- * 解析失败时的策略:
670
- * - skillDirectory 为空 / 目录不存在 / 未找到匹配 SKILL → 返回 null(降级为无 SKILL 模式)
671
- * - 仅记录 warn 日志,不抛异常,保证执行流程不中断
672
- *
673
- * @param {string} specifiedSkill - 指定的 SKILL name 或目录名
674
- * @param {string} skillDirectory - SKILL 根目录路径
675
- * @returns {Promise<string|null>} SKILL 目录绝对路径;解析失败时返回 null
676
- */
677
- async _resolveSpecifiedSkill(specifiedSkill, skillDirectory) {
678
- this._ensureInitialized();
679
-
680
- if (!specifiedSkill) {
681
- return null;
682
- }
683
- if (!skillDirectory) {
684
- this._log('warn', `specifiedSkill: skillDirectory 为空,无法解析指定 SKILL "${specifiedSkill}",将以无 SKILL 模式执行`);
685
- return null;
686
- }
687
-
688
- this._log('info', `specifiedSkill 开始 — 指定 Skill: "${specifiedSkill}"`);
689
-
690
- try {
691
- // ── 1. 目录名精确匹配 ──
692
- const directDir = path.resolve(skillDirectory, specifiedSkill);
693
- const directSkillMd = path.join(directDir, 'SKILL.md');
694
- try {
695
- const stat = await fs.stat(directSkillMd);
696
- if (stat.isFile()) {
697
- this._log('info', `specifiedSkill 完成 — 目录名匹配: ${directDir}`);
698
- return directDir;
699
- }
700
- } catch {
701
- // 直接路径不存在 SKILL.md,继续尝试 name 匹配
702
- }
703
-
704
- // ── 2. 扫描 SKILL name 匹配(frontmatter 的 name 字段) ──
705
- let entries;
706
- try {
707
- entries = await fs.readdir(skillDirectory, { withFileTypes: true });
708
- } catch (err) {
709
- this._log('warn', `specifiedSkill: 无法读取 SKILL 目录 ${skillDirectory} — ${err.message},将以无 SKILL 模式执行`);
710
- return null;
711
- }
712
-
713
- const target = specifiedSkill.toLowerCase();
714
- for (const entry of entries) {
715
- if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
716
- const dirPath = path.join(skillDirectory, entry.name);
717
- const skillMdPath = path.join(dirPath, 'SKILL.md');
718
- try {
719
- const md = await fs.readFile(skillMdPath, 'utf-8');
720
- // 解析 frontmatter 中的 name 字段(--- 包围的 YAML 头)
721
- const fmMatch = md.match(/^---\r?\n([\s\S]*?)\r?\n---/);
722
- if (fmMatch) {
723
- const nameMatch = fmMatch[1].match(/^name:\s*(.+)$/m);
724
- if (nameMatch) {
725
- const name = nameMatch[1].trim().replace(/^['"]|['"]$/g, '');
726
- if (name.toLowerCase() === target) {
727
- this._log('info', `specifiedSkill 完成 — name 匹配: ${name} (${dirPath})`);
728
- return dirPath;
729
- }
730
- }
731
- }
732
- } catch {
733
- // 读取失败跳过该目录
734
- }
735
- }
736
-
737
- this._log('warn', `specifiedSkill: 在 ${skillDirectory} 下未找到名为 "${specifiedSkill}" 的 SKILL(目录名/name 均未命中),将以无 SKILL 模式执行`);
738
- return null;
739
- } catch (err) {
740
- this._log('warn', `specifiedSkill: 解析异常 — ${err.message},将以无 SKILL 模式执行`);
741
- return null;
742
- }
743
- }
744
-
745
- /**
746
- * _harvestMetrics — 收割结构化指标(meta .json 旁车文件)。
747
- *
748
- * 通用契约:初始 prompt 中下发 meta 文件路径,SKILL 若定义了结构化结论指标
749
- * (如 code-check 的 mergeLevel、仓库检查的 score),由 AI 以 JSON 对象写入该路径。
750
- * 后端不解释键的语义,仅校验 JSON 合法性后原样透传(键名由各 SKILL 自行约定)。
751
- *
752
- * 降级策略(均不影响执行状态):
753
- * - 文件不存在 → 返回 null(SKILL 未约定指标,正常情况)
754
- * - JSON 解析失败 / 非对象 → 返回 null,记录 warn
755
- *
756
- * @param {string} metaFilePath - 指标文件路径
757
- * @returns {Promise<object|null>} 结构化指标对象;无/非法时返回 null
758
- */
759
- async _harvestMetrics(metaFilePath) {
760
- if (!metaFilePath) return null;
761
- try {
762
- let raw = await fs.readFile(metaFilePath, 'utf-8');
763
- if (raw.charCodeAt(0) === 0xFEFF) raw = raw.slice(1);
764
- const parsed = JSON.parse(raw);
765
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
766
- this._log('info', `metrics 已收割 — ${Object.keys(parsed).join(', ')}`);
767
- return parsed;
768
- }
769
- this._log('warn', 'metrics: meta 文件内容非 JSON 对象,忽略');
770
- return null;
771
- } catch (err) {
772
- if (err.code === 'ENOENT') {
773
- // SKILL 未约定指标文件,正常情况,不打日志
774
- return null;
775
- }
776
- this._log('warn', `metrics: 读取/解析 meta 文件失败 — ${err.message},忽略`);
777
- return null;
778
- }
779
- }
780
-
781
- /**
782
- * invokeSkill — 通过 opencode cli 执行选定的 Skill(或无 SKILL 直接执行)。
783
- *
784
- * 流程:
785
- * 1. 创建 opencode Session(标题=taskId+stepId+loopCount)
786
- * 2. 发送初始 prompt(任务描述 + SKILL 目录 + 报告路径 + 结果文件路径)
787
- * — skillDir 为 null 时,prompt 不包含 SKILL 目录,改为基于任务描述直接执行
788
- * — 初始 prompt 仅负责执行任务 + 生成 result .md,**不包含经验总结指令**
789
- * — 经验总结在 checkResult 成功后由 _summarizeExperience 独立追加
790
- * 3. 轮询 Session 状态直到完成或超时
791
- * 4. 记录 sessionId
792
- *
793
- * opencode 执行过程中会固定生成:
794
- * - resultFilePath: stepId{actualStepId}_loop{bigLoopIndex}_result_{retryCount}.md
795
- *
796
- * @param {string} taskDescription - 任务描述字符串
797
- * @param {string|null} skillDir - 选定的 SKILL 目录路径;null 表示无 SKILL 模式
798
- * @param {string} [reportPath] - 输入报告路径(可选)
799
- * @param {object} [filePaths] - 文件路径
800
- * @param {string} [filePaths.resultFilePath] - 结果文件输出路径
801
- * @returns {Promise<boolean>} 是否成功
802
- */
803
- async invokeSkill(taskDescription, skillDir, reportPath, filePaths = {}) {
804
- this._ensureInitialized();
805
-
806
- if (!taskDescription) {
807
- throw new Error('FlexRunner.invokeSkill: taskDescription 不能为空');
808
- }
809
- // skillDir 允许为 null:未匹配到 SKILL 时以无 SKILL 模式执行
810
-
811
- const modeLabel = skillDir ? 'SKILL 模式' : '无 SKILL 模式';
812
- this._log('info', `invokeSkill 开始 — ${modeLabel}${skillDir ? `: ${skillDir}` : ''}`);
813
-
814
- try {
815
- // ── 1. 健康检查 ──
816
- const health = await this.#cli.checkHealth();
817
- if (health.status !== 'ok') {
818
- this._log('error', `opencode 服务不可用: ${health.message}`);
819
- return false;
820
- }
821
-
822
- // ── 2. 构建 prompt(含历史执行文档) ──
823
- const title = `task=${this.#taskId}|step=${this.#stepId}|bigLoop=${this.#bigLoopIndex}|retry=${this.#executeStep}`;
824
- const prompt = this._buildPrompt(taskDescription, skillDir, reportPath, filePaths);
825
-
826
- // ── 3. 创建 Session 并发送初始 prompt ──
827
- // 指定工作目录为 taskDir,确保 opencode session 的文件操作(git clone 等)在 db/task/{taskId}/ 下执行
828
- // const { sessionId } = await this.#cli.startSession(title, prompt, { cwd: this.#taskDir });
829
- const { sessionId } = await this.#cli.startSession(title, prompt);
830
- this.#sessionId = sessionId
831
- this._log('info', `Session 已创建: ${sessionId}`);
832
-
833
- // 实时通知编排层(静默失败,不影响主流程)
834
- if (this.#onSessionCreated) {
835
- try {
836
- await this.#onSessionCreated(sessionId);
837
- } catch (err) {
838
- this._log('warn', `onSessionCreated 回调异常: ${err.message}`);
839
- }
840
- }
841
-
842
- // ── 4. 轮询等待执行完成 ──
843
- const completed = await this._pollSession(sessionId);
844
- if (!completed) {
845
- this._log('warn', `Session ${sessionId} 未在超时时间内完成`);
846
- return false;
847
- }
848
-
849
- this._log('info', `invokeSkill 完成 — sessionId: ${sessionId}`);
850
- return true;
851
- } catch (err) {
852
- this._log('error', `invokeSkill 异常: ${err.message}`);
853
- return false;
854
- }
855
- }
856
-
857
- /**
858
- * persistKnowledge — 读取经验文件,将有效经验存入任务。
859
- *
860
- * 读取 Summary .md 文件内容,将其作为经验知识记录到 TaskStepStore,
861
- * 并登记到知识沉淀系统(KnowledgeManager)。
862
- *
863
- * 调用时序(由 executeStart 驱动):
864
- * 1. invokeSkill 执行任务(生成 result .md)
865
- * 2. checkResult 判断成功
866
- * 3. _summarizeExperience 追加经验总结 prompt(AI 生成 Summary .md)
867
- * 4. persistKnowledge(本方法)读取 Summary .md 并持久化
868
- *
869
- * 判断逻辑:
870
- * - _summarizeExperience 成功后,Summary .md 通常已生成。
871
- * - AI 可能判断无有价值经验而不生成文件(沉淀类型 = 无),此时跳过登记。
872
- * - 文件不存在时静默跳过,返回 false。
873
- *
874
- * 流程:
875
- * 1. 检查 summaryFilePath 对应的文件是否存在(不存在 → 跳过,返回 false)
876
- * 2. 读取文件内容,持久化到步骤记录(knowledgeSummary 字段)
877
- * 3. 调用 KnowledgeManager.addExperience() 登记到知识沉淀系统
878
- *
879
- * 静默失败:持久化失败不影响主流程。
880
- *
881
- * @param {string} summaryFilePath - 经验文件路径
882
- * @returns {Promise<boolean>} 是否成功
883
- */
884
- async persistKnowledge(summaryFilePath) {
885
- this._ensureInitialized();
886
-
887
- if (!summaryFilePath) {
888
- this._log('warn', 'persistKnowledge: summaryFilePath 为空');
889
- return false;
890
- }
891
-
892
- // ── 检查经验文档是否存在 ──
893
- // 无 SKILL 模式下,AI 可能判断无有价值经验而不生成 Summary 文件,
894
- // 此时跳过知识沉淀登记。
895
- let exists = false;
896
- try {
897
- await fs.access(summaryFilePath);
898
- exists = true;
899
- } catch {
900
- exists = false;
901
- }
902
-
903
- if (!exists) {
904
- this._log('info', `persistKnowledge: 经验文档不存在,跳过知识沉淀登记 — ${summaryFilePath}`);
905
- return false;
906
- }
907
-
908
- try {
909
- const content = await fs.readFile(summaryFilePath, 'utf-8');
910
- this._log('info', `persistKnowledge: 已读取经验文件 (${content.length} 字符)`);
911
-
912
- // 1. 将经验内容持久化到步骤记录
913
- await this._persistStep({ knowledgeSummary: content });
914
- this._log('info', 'persistKnowledge: 经验已持久化到步骤记录');
915
-
916
- // 2. 登记到知识沉淀系统
917
- if (this.#knowledgeManager) {
918
- // 避免重复登记:先检查是否已存在
919
- const existing = await this.#knowledgeManager.findByDocPath(summaryFilePath);
920
- if (existing) {
921
- this._log('info', `persistKnowledge: 经验已登记过,跳重复登记 — id: ${existing.id}`);
922
- } else {
923
- const record = await this.#knowledgeManager.addExperience({
924
- docPath: summaryFilePath,
925
- taskId: this.#taskId,
926
- stepId: this.#stepId,
927
- bigLoopIndex: this.#bigLoopIndex,
928
- retryCount: this.#executeStep,
929
- skillDir: this.#matchedSkillDir,
930
- taskDescription: this.#taskDescription
931
- });
932
- this._log('info', `persistKnowledge: 经验已登记到知识沉淀系统 — id: ${record.id}`);
933
- }
934
- } else {
935
- this._log('warn', 'persistKnowledge: KnowledgeManager 未初始化,跳过知识沉淀登记');
936
- }
937
-
938
- return true;
939
- } catch (err) {
940
- this._log('warn', `persistKnowledge: 处理经验文件失败: ${summaryFilePath} — ${err.message}`);
941
- return false;
942
- }
943
- }
944
-
945
- /**
946
- * controlExecution — 控制执行步骤。
947
- *
948
- * @param {string} type - 控制类型:'pause' | 'resume' | 'abort'
949
- * @returns {Promise<boolean>} 是否成功
950
- */
951
- async controlExecution(type) {
952
- this._ensureInitialized();
953
-
954
- switch (type) {
955
- case ControlType.PAUSE:
956
- this.#paused = true;
957
- this._log('info', '⏸ 执行已暂停');
958
- await this._persistStep({ status: 'paused' });
959
- return true;
960
-
961
- case ControlType.RESUME:
962
- this.#paused = false;
963
- this._log('info', '▶ 执行已继续');
964
- await this._persistStep({ status: StepStatus.RUNNING });
965
- return true;
966
-
967
- case ControlType.ABORT:
968
- this.#aborted = true;
969
- this.#paused = false;
970
- this._log('warn', '⏹ 执行已终止');
971
- // 若有活跃 session,尝试中止
972
- if (this.#sessionId) {
973
- try {
974
- await this.#cli.abortSession(this.#sessionId);
975
- this._log('info', `已中止 Session: ${this.#sessionId}`);
976
- } catch (err) {
977
- this._log('warn', `中止 Session 失败: ${err.message}`);
978
- }
979
- }
980
- await this._persistStep({
981
- status: StepStatus.SKIPPED,
982
- endTime: nowCST()
983
- });
984
- return true;
985
-
986
- default:
987
- this._log('warn', `未知的控制类型: "${type}",支持: pause | resume | abort`);
988
- return false;
989
- }
990
- }
991
-
992
- /**
993
- * getSessionContent — 获取当前会话的内容。
994
- *
995
- * 通过读取 db/Session/ 目录下的归档文件获取会话内容:
996
- * - <sessionId>.jsonl — 消息流(每行一条消息)
997
- * - <sessionId>.meta.json — 会话元信息
998
- *
999
- * 返回合并后的 JSON 文本字符串,结构为:
1000
- * { "meta": {...}, "messages": [{...}, ...] }
1001
- *
1002
- * @returns {Promise<string>} JSON 文本(包含 meta 和 messages)
1003
- */
1004
- async getSessionContent() {
1005
- this._ensureInitialized();
1006
-
1007
- if (!this.#sessionId) {
1008
- this._log('warn', 'getSessionContent: 当前无活跃会话');
1009
- return JSON.stringify({ meta: null, messages: [] });
1010
- }
1011
-
1012
- try {
1013
- const sessionStore = this.#storage.sessionStore();
1014
-
1015
- // 并行读取元信息与消息流
1016
- const [meta, messages] = await Promise.all([
1017
- sessionStore.readMeta(this.#sessionId).catch(() => null),
1018
- sessionStore.readMessages(this.#sessionId).catch(() => [])
1019
- ]);
1020
-
1021
- this._log(
1022
- 'info',
1023
- `getSessionContent: 读取 session ${this.#sessionId},共 ${messages.length} 条消息`
1024
- );
1025
-
1026
- return JSON.stringify({ meta, messages }, null, 2);
1027
- } catch (err) {
1028
- this._log('error', `getSessionContent: 读取失败: ${err.message}`);
1029
- return JSON.stringify({ meta: null, messages: [], error: err.message });
1030
- }
1031
- }
1032
-
1033
- /**
1034
- * checkResult — 读取结果文件,判断执行是否成功。
1035
- *
1036
- * 兼容 SKILL 产物中多种执行状态标记格式(按优先级匹配):
1037
- * 1. 标题下独立行:`## 执行状态` 下一行为 `成功` / `失败`
1038
- * 2. 标题内联:`## 执行状态: 成功` / `## 执行状态:失败`
1039
- * 3. 末尾 `状态:` 行:文件末尾附近 `状态: 成功` / `状态: 失败`
1040
- * (如 ArkTsLibraryInterfaceSpecSkill 的 count-report.cjs 写回格式)
1041
- *
1042
- * 状态值归一化:`成功` 判 true;`失败` 判 false;
1043
- * 已知中间态(`部分通过` / `源库构建问题` / `环境不可用` / `设备不可用`)
1044
- * 视为成功(产物已完成,非失败),记录 warn 日志;
1045
- * 其他未知状态值视为无法解析 → false。
1046
- *
1047
- * @param {string} resultFilePath - 结果文件路径
1048
- * @returns {Promise<boolean>} 执行是否成功
1049
- */
1050
- async checkResult(resultFilePath) {
1051
- this._ensureInitialized();
1052
-
1053
- if (!resultFilePath) {
1054
- this._log('warn', 'checkResult: resultFilePath 为空');
1055
- return false;
1056
- }
1057
-
1058
- try {
1059
- let content = await fs.readFile(resultFilePath, 'utf-8');
1060
- if (content.charCodeAt(0) === 0xFEFF) content = content.slice(1);
1061
-
1062
- // 1. 标题下独立行:`## 执行状态` 下一行为状态值(可能带 - / * / > 列表前缀)
1063
- let match = content.match(/^#{1,6}\s*执行状态\s*$\n\s*(.+)$/m);
1064
- if (match) {
1065
- return this._parseStatusValue(match[1].trim(), resultFilePath);
1066
- }
1067
-
1068
- // 2. 标题内联:`## 执行状态: 成功` / `## 执行状态:失败`
1069
- match = content.match(/^#{1,6}\s*执行状态\s*[::]\s*([^\n]+)/m);
1070
- if (match) {
1071
- return this._parseStatusValue(match[1].trim(), resultFilePath);
1072
- }
1073
-
1074
- // 3. 末尾 `状态:` 行:仅取文件最后 10 行,避免正文中误出现"状态:"字样
1075
- const tailLines = content.split('\n').slice(-10);
1076
- for (const line of tailLines) {
1077
- const tailMatch = line.match(/^\s*状态\s*[::]\s*(.+)$/);
1078
- if (tailMatch) {
1079
- return this._parseStatusValue(tailMatch[1].trim(), resultFilePath);
1080
- }
1081
- }
1082
-
1083
- this._log('warn', `checkResult: 结果文件中未找到有效的执行状态字段: ${resultFilePath}`);
1084
- return false;
1085
- } catch (err) {
1086
- this._log('warn', `checkResult: 读取结果文件失败: ${resultFilePath} — ${err.message}`);
1087
- return false;
1088
- }
1089
- }
1090
-
1091
- /**
1092
- * 解析结果文件中的状态值。
1093
- *
1094
- * 状态判定规则:
1095
- * - `成功` → true
1096
- * - `失败` → false
1097
- * - 已知中间态(`部分通过` / `源库构建问题` / `环境不可用` / `设备不可用`)
1098
- * 视为成功(产物已完成,非失败),记录 warn 日志
1099
- * - 其他未知状态值 → false(视为无法解析,避免误判成功)
1100
- *
1101
- * @param {string} raw - 状态值原始文本
1102
- * @param {string} resultFilePath - 结果文件路径(仅用于日志)
1103
- * @returns {boolean} 执行是否成功
1104
- * @private
1105
- */
1106
- _parseStatusValue(raw, resultFilePath) {
1107
- if (!raw) {
1108
- this._log('warn', `checkResult: 执行状态值解析为空: ${resultFilePath}`);
1109
- return false;
1110
- }
1111
-
1112
- const value = raw.replace(/^[#>*\-\s]+/, '').trim();
1113
-
1114
- if (value === '成功') {
1115
- this._log('info', `checkResult: 执行状态 = 成功 (${resultFilePath})`);
1116
- return true;
1117
- }
1118
-
1119
- if (value === '失败') {
1120
- this._log('info', `checkResult: 执行状态 = 失败 (${resultFilePath})`);
1121
- return false;
1122
- }
1123
-
1124
- // 已知中间态:产物已完成但非完全成功,视为成功(记录 warn 提示)
1125
- const KNOWN_MIDDLE_STATES = ['部分通过', '源库构建问题', '环境不可用', '设备不可用'];
1126
- if (KNOWN_MIDDLE_STATES.includes(value)) {
1127
- this._log('warn', `checkResult: 识别到中间态状态「${value}」,视为成功 (${resultFilePath})`);
1128
- return true;
1129
- }
1130
-
1131
- this._log('warn', `checkResult: 无法识别的执行状态「${value}」,视为失败 (${resultFilePath})`);
1132
- return false;
1133
- }
1134
-
1135
- /**
1136
- * getLiveMessages — 获取当前会话的实时对话消息。
1137
- *
1138
- * 委托 CLI 的 getLiveMessages,从远端拉取当前已有消息并返回精简格式。
1139
- * 运行中安全调用,不写入本地存档,不影响后续归档去重。
1140
- *
1141
- * 如果当前无活跃会话,返回空数组。
1142
- *
1143
- * @returns {Promise<Array<{id,role,content,finish,timestamp}>>}
1144
- */
1145
- async getLiveMessages() {
1146
- this._ensureInitialized();
1147
-
1148
- if (!this.#sessionId) {
1149
- this._log('warn', 'getLiveMessages: 当前无活跃会话');
1150
- return [];
1151
- }
1152
-
1153
- if (typeof this.#cli.getLiveMessages !== 'function') {
1154
- this._log('warn', `getLiveMessages: CLI 不支持 getLiveMessages 方法`);
1155
- return [];
1156
- }
1157
-
1158
- return this.#cli.getLiveMessages(this.#sessionId);
1159
- }
1160
-
1161
- /**
1162
- * injectPrompt — 向当前会话注入提示词/上下文(不触发 AI 回复)。
1163
- *
1164
- * 利用 CLI 的 injectPrompt 能力,将文本注入对话历史但不触发 AI 生成回复。
1165
- * 适用于对话过程中动态补充上下文、规则、指令。
1166
- *
1167
- * 如果当前无活跃会话,返回失败。
1168
- *
1169
- * @param {string} message - 要注入的提示词/上下文
1170
- * @returns {Promise<{ success: boolean }>}
1171
- */
1172
- async injectPrompt(message) {
1173
- this._ensureInitialized();
1174
-
1175
- if (!message || typeof message !== 'string') {
1176
- throw new Error('injectPrompt: message 为必填项且必须为字符串');
1177
- }
1178
-
1179
- if (!this.#sessionId) {
1180
- this._log('warn', 'injectPrompt: 当前无活跃会话');
1181
- return { success: false };
1182
- }
1183
-
1184
- if (typeof this.#cli.injectPrompt !== 'function') {
1185
- this._log('warn', `injectPrompt: CLI 不支持 injectPrompt 方法`);
1186
- return { success: false };
1187
- }
1188
-
1189
- try {
1190
- const result = await this.#cli.injectPrompt(this.#sessionId, message);
1191
- this._log(
1192
- 'info',
1193
- `injectPrompt: 已向 session ${this.#sessionId} 注入 ${message.length} 字符提示词`
1194
- );
1195
- return result;
1196
- } catch (err) {
1197
- this._log('error', `injectPrompt: 注入失败: ${err.message}`);
1198
- return { success: false };
1199
- }
1200
- }
1201
-
1202
- /**
1203
- * sendAndWaitMessage — 向当前会话发送消息并同步等待 AI 回复完成。
1204
- *
1205
- * 发送消息后阻塞等待 AI 生成完整回复,然后返回回复内容。
1206
- * 与普通的 fire-and-forget 发送不同,此方法会等到 AI 回复完成才返回。
1207
- *
1208
- * 如果当前无活跃会话,返回失败。
1209
- *
1210
- * @param {string} message - 要发送的消息
1211
- * @returns {Promise<{ success: boolean, response: object|string, content: string }>}
1212
- */
1213
- async sendAndWaitMessage(message) {
1214
- this._ensureInitialized();
1215
-
1216
- if (!message || typeof message !== 'string') {
1217
- throw new Error('sendAndWaitMessage: message 为必填项且必须为字符串');
1218
- }
1219
-
1220
- if (!this.#sessionId) {
1221
- this._log('warn', 'sendAndWaitMessage: 当前无活跃会话');
1222
- return { success: false, response: '', content: '' };
1223
- }
1224
-
1225
- if (typeof this.#cli.sendAndWaitMessage !== 'function') {
1226
- this._log('warn', `sendAndWaitMessage: CLI 不支持 sendAndWaitMessage 方法`);
1227
- return { success: false, response: '', content: '' };
1228
- }
1229
-
1230
- try {
1231
- const result = await this.#cli.sendAndWaitMessage(this.#sessionId, message);
1232
- this._log(
1233
- 'info',
1234
- `sendAndWaitMessage: session ${this.#sessionId} 已收到回复,` +
1235
- `content 长度 ${result?.content?.length || 0}`
1236
- );
1237
- return result;
1238
- } catch (err) {
1239
- this._log('error', `sendAndWaitMessage: 发送并等待失败: ${err.message}`);
1240
- return { success: false, response: '', content: '' };
1241
- }
1242
- }
1243
-
1244
- // ─── 私有方法 ─────────────────────────────────────────────────────────────
1245
-
1246
- /**
1247
- * 确保已调用 initContext 完成初始化。
1248
- * @private
1249
- */
1250
- _ensureInitialized() {
1251
- if (!this.#initialized) {
1252
- throw new Error('FlexRunner 尚未初始化,请先调用 initContext()');
1253
- }
1254
- }
1255
-
1256
- /**
1257
- * 将当前步骤的执行状态持久化到 db/task/{taskId}/stepid_{stepId}_loop{L}.json。
1258
- *
1259
- * 在执行过程的关键节点(开始、匹配后、会话创建后、结束、终止)被调用,
1260
- * 增量更新记录文件,方便外部追踪任务执行进度。
1261
- * 按大循环轮次独立存储,避免跨轮覆盖。
1262
- *
1263
- * 静默失败:持久化不影响主流程,仅记录 warn 日志。
1264
- *
1265
- * @param {object} patch - 要合并的字段
1266
- * @private
1267
- */
1268
- async _persistStep(patch) {
1269
- try {
1270
- if (!this.#taskId || this.#stepId <= 0) return;
1271
- const store = this.#storage.taskExecStore();
1272
- await store.patchStep(this.#taskId, this.#stepId, {
1273
- taskId: this.#taskId,
1274
- stepId: this.#stepId,
1275
- dependId: this.#dependId,
1276
- nextStepId: this.#nextStepId,
1277
- failStepId: this.#failStepId,
1278
- bigLoopIndex: this.#bigLoopIndex,
1279
- taskDescription: this.#taskDescription,
1280
- skillDirectory: this.#skillDirectory,
1281
- specifiedSkill: this.#specifiedSkill,
1282
- inputReport: this.#inputReport,
1283
- matchedSkillDir: this.#matchedSkillDir,
1284
- sessionId: this.#sessionId,
1285
- executeStep: this.#executeStep,
1286
- retryTimes: this.#retryTimes,
1287
- maxRetries: this.#maxRetries,
1288
- startTime: this.#startTime,
1289
- endTime: this.#endTime,
1290
- ...patch
1291
- }, this.#bigLoopIndex);
1292
- } catch (err) {
1293
- this._log('warn', `_persistStep: 步骤记录持久化失败: ${err.message}`);
1294
- }
1295
- }
1296
-
1297
- /**
1298
- * 构建 opencode 初始执行 prompt。
1299
- *
1300
- * 仅负责任务执行 + 生成 result .md,**不包含经验总结指令**。
1301
- * 经验总结在 checkResult 成功后由 _buildSummaryPrompt 独立构建。
1302
- *
1303
- * @param {string} taskDescription - 任务描述
1304
- * @param {string|null} skillDir - SKILL 目录(null 表示无 SKILL 模式)
1305
- * @param {string} [reportPath] - 输入报告路径
1306
- * @param {object} [filePaths] - 文件路径
1307
- * @param {string} [filePaths.resultFilePath] - 结果文件输出路径
1308
- * @param {string} [filePaths.metaFilePath] - 结构化指标文件输出路径(可选)
1309
- * @returns {string} 拼接后的 prompt 文本
1310
- * @private
1311
- */
1312
- _buildPrompt(taskDescription, skillDir, reportPath, filePaths = {}) {
1313
- const parts = [
1314
- `## 任务描述\n${taskDescription}`
1315
- ];
1316
-
1317
- // 工作目录:告知 AI 当前工作目录路径,所有文件操作(git clone、读写文件等)均在此目录下执行
1318
- if (this.#taskDir) {
1319
- parts.push(`## 工作目录\n${this.#taskDir}\n\n所有文件操作(git clone、读写文件等)请在此目录下执行。`);
1320
- }
1321
-
1322
- if (skillDir) {
1323
- // ── 有 SKILL:按照 SKILL 指令执行 ──
1324
- parts.push(`## SKILL 目录\n${skillDir}`);
1325
- if (reportPath) {
1326
- parts.push(`## 输入报告路径\n${reportPath}`);
1327
- }
1328
- if (filePaths.resultFilePath) {
1329
- parts.push(`## 结果文件输出路径\n${filePaths.resultFilePath}`);
1330
- }
1331
- // 结构化指标文件路径(通用契约:SKILL 约定了结构化结论指标时写入)
1332
- if (filePaths.metaFilePath) {
1333
- parts.push(`## 结构化指标文件输出路径\n${filePaths.metaFilePath}`);
1334
- }
1335
- // 历史结果文档路径(第 N 次执行时传入之前的 result .md 路径,不传内容)
1336
- if (filePaths.historyDocs && filePaths.historyDocs.length > 0) {
1337
- const historyLines = filePaths.historyDocs.map(
1338
- (doc) => `- 本轮重试结果 (retry=${doc.loop}): ${doc.path}`
1339
- );
1340
- parts.push(
1341
- `## 历史执行文档路径\n\n以下为本轮大循环中之前重试的结果文件路径,请自行读取参考:\n${historyLines.join('\n')}`
1342
- );
1343
- }
1344
- parts.push(
1345
- '请按照 SKILL 中的指令执行任务。',
1346
- '执行完成后,请将结果写入上述"结果文件输出路径"。',
1347
- '结果文件需包含 `## 执行状态` 字段(值为 `成功` 或 `失败`),用于判断执行结果。'
1348
- );
1349
- if (filePaths.metaFilePath) {
1350
- parts.push(
1351
- '若本次使用的 SKILL 中定义了结构化结论指标(如合入等级、评分等),请在执行完成后,',
1352
- `将指标以 JSON 对象形式写入上述"结构化指标文件输出路径"(键名按 SKILL 约定,如 {"mergeLevel":"PASS"})。`,
1353
- '若 SKILL 未定义结构化指标,则无需创建该文件。'
1354
- );
1355
- }
1356
- } else {
1357
- // ── 无 SKILL:基于任务描述本身直接执行 ──
1358
- if (reportPath) {
1359
- parts.push(`## 输入报告路径\n${reportPath}`);
1360
- }
1361
- if (filePaths.resultFilePath) {
1362
- parts.push(`## 结果文件输出路径\n${filePaths.resultFilePath}`);
1363
- }
1364
- if (filePaths.metaFilePath) {
1365
- parts.push(`## 结构化指标文件输出路径\n${filePaths.metaFilePath}`);
1366
- }
1367
- // 历史结果文档路径(第 N 次执行时传入之前的 result .md 路径,不传内容)
1368
- if (filePaths.historyDocs && filePaths.historyDocs.length > 0) {
1369
- const historyLines = filePaths.historyDocs.map(
1370
- (doc) => `- 本轮重试结果 (retry=${doc.loop}): ${doc.path}`
1371
- );
1372
- parts.push(
1373
- `## 历史执行文档路径\n\n以下为本轮大循环中之前重试的结果文件路径,请自行读取参考:\n${historyLines.join('\n')}`
1374
- );
1375
- }
1376
- parts.push(
1377
- '本次任务未匹配到专用 SKILL,请直接基于上述任务描述执行任务。',
1378
- '执行完成后,请将结果写入上述"结果文件输出路径"。',
1379
- '结果文件需包含 `## 执行状态` 字段(值为 `成功` 或 `失败`),用于判断执行结果。'
1380
- );
1381
- }
1382
-
1383
- // ── MCP 工具引导:提醒 AI 主动使用 MCP Gateway 提供的工具 ──
1384
- if (this.#mcpToolGuide) {
1385
- const toolGuide = this.#mcpToolGuide.buildToolGuide();
1386
- if (toolGuide) {
1387
- parts.push(toolGuide);
1388
- }
1389
- }
1390
-
1391
- return parts.join('\n\n');
1392
- }
1393
-
1394
- /**
1395
- * _buildSummaryPrompt — 构建经验总结专用 prompt。
1396
- *
1397
- * 此 prompt 在 checkResult 成功后,通过 sendAndWaitMessage 向同一 Session
1398
- * 追加发送,要求 AI 基于已有的执行上下文生成 Summary .md 经验总结文件。
1399
- *
1400
- * 与初始执行 prompt 分离的原因:
1401
- * - 确保经验总结仅在执行成功后触发
1402
- * - AI 在总结时已有完整的执行上下文(同一 Session),总结质量更高
1403
- * - 初始 prompt 更简洁,AI 专注执行任务
1404
- *
1405
- * @param {string} summaryFilePath - 经验文件输出路径
1406
- * @param {string|null} skillDir - SKILL 目录路径(null 表示无 SKILL 模式)
1407
- * @returns {string} 拼接后的经验总结 prompt 文本
1408
- * @private
1409
- */
1410
- _buildSummaryPrompt(summaryFilePath, skillDir) {
1411
- const parts = [
1412
- '## 任务已执行成功,请进行经验总结',
1413
- '',
1414
- '以上任务已执行成功。请基于本次执行过程中的实际情况,评估是否产生了**有价值的、可复用的经验总结**。',
1415
- '',
1416
- '## 判断标准',
1417
- '- 本次执行中发现了关键的踩坑点、解决方案、最佳实践或可复用的模式',
1418
- '- 这些经验对未来类似的任务有明确的参考价值',
1419
- '- 不是简单的执行流水账或重复的通用知识',
1420
- '',
1421
- '## 处理方式',
1422
- '如果存在有价值的经验,请将经验总结写入以下路径:',
1423
- `经验文件输出路径:${summaryFilePath}`,
1424
- '',
1425
- '经验文件应包含:关键发现、踩坑记录、解决方案、可复用建议等。',
1426
- '',
1427
- '## 经验分类(必须在经验文件末尾输出)',
1428
- '在经验文件末尾附上以下经验分类块,用于标记本次经验的归属类型:',
1429
- '```',
1430
- '## 经验分类',
1431
- '- 沉淀类型: skill优化 | 知识库 | 无'
1432
- ];
1433
-
1434
- if (skillDir) {
1435
- parts.push(
1436
- `- 适用SKILL: ${skillDir}`,
1437
- '- 优化建议: <对当前SKILL的具体修改/新增点,skill优化类必填>'
1438
- );
1439
- } else {
1440
- parts.push(
1441
- '- 适用SKILL: <无,本次未匹配到SKILL>',
1442
- '- 优化建议: <skill优化类必填,但本次无SKILL,通常填"无">'
1443
- );
1444
- }
1445
-
1446
- parts.push(
1447
- '```',
1448
- '',
1449
- '字段说明:',
1450
- '- 沉淀类型:三选一。'
1451
- );
1452
-
1453
- if (skillDir) {
1454
- parts.push(
1455
- ' - skill优化 = 当前SKILL有可改进之处(检查项缺失/规则错误/可复用模式未被覆盖);',
1456
- ' - 知识库 = 通用领域经验,与具体SKILL逻辑无关;'
1457
- );
1458
- } else {
1459
- parts.push(
1460
- ' - skill优化 = 需为某个SKILL沉淀优化建议;',
1461
- ' - 知识库 = 通用领域经验,与具体SKILL逻辑无关;'
1462
- );
1463
- }
1464
-
1465
- parts.push(
1466
- ' - 无 = 无有价值经验,此时不生成经验文件。'
1467
- );
1468
-
1469
- if (skillDir) {
1470
- parts.push(
1471
- '- 适用SKILL:仅 skill优化 类必填,填上面注入的当前 step 调用 SKILL 的路径,原样保留不要改动。',
1472
- '- 优化建议:仅 skill优化 类必填,描述对当前SKILL的具体修改/新增点(如"新增 XX 检查项"、"修正 YY 规则")。'
1473
- );
1474
- } else {
1475
- parts.push(
1476
- '- 适用SKILL:本次未匹配到 SKILL,此处标记"无"。若沉淀类型为 skill优化,请在优化建议中注明建议沉淀到哪个 SKILL(如期望新增或修改的 SKILL 名称)。',
1477
- '- 优化建议:仅 skill优化 类必填,描述建议新建或修改的 SKILL 的具体点。'
1478
- );
1479
- }
1480
-
1481
- parts.push(
1482
- '',
1483
- '如果没有有价值的经验可沉淀(如任务过于简单、未发现新的经验),则**不需要生成经验文件**。',
1484
- '请勿创建空文件或无实质内容的经验文件。',
1485
- '',
1486
- '请现在进行经验总结。'
1487
- );
1488
-
1489
- return parts.join('\n');
1490
- }
1491
-
1492
- /**
1493
- * _summarizeAndPersist — 后台异步执行经验总结 + 知识持久化。
1494
- *
1495
- * 此方法为 fire-and-forget 入口,由 executeStart 在成功后以 `.catch()` 方式调用,
1496
- * **不阻塞 executeStart 返回**,不影响 Orchestrator 步骤流转。
1497
- *
1498
- * 内部流程:
1499
- * 1. _summarizeExperience → 向指定 Session 追加经验总结 prompt,等待 AI 回复 + 文件生成
1500
- * 2. persistKnowledge → 读取 Summary .md,持久化到步骤记录 + 知识沉淀系统
1501
- *
1502
- * 所有异常在方法内部 catch,仅记录日志,不向上抛出。
1503
- *
1504
- * @param {string} summaryFilePath - 经验文件输出路径
1505
- * @param {string|null} skillDir - SKILL 目录路径(null 表示无 SKILL 模式)
1506
- * @param {string} sessionId - 执行任务的 Session ID(显式传入,避免实例复用后被覆盖)
1507
- * @returns {Promise<void>}
1508
- * @private
1509
- */
1510
- async _summarizeAndPersist(summaryFilePath, skillDir, sessionId) {
1511
- // 终止已请求 → 不再向 session 追加经验总结 prompt(避免终止后又触发新的 AI 生成)
1512
- if (this.#aborted) {
1513
- this._log('info', '_summarizeAndPersist: 已终止,跳过后台经验总结');
1514
- return;
1515
- }
1516
- try {
1517
- const summarized = await this._summarizeExperience(summaryFilePath, skillDir, sessionId);
1518
- if (!summarized) {
1519
- this._log('warn', '后台经验总结未生成(超时/失败),跳过知识持久化');
1520
- return;
1521
- }
1522
- await this.persistKnowledge(summaryFilePath);
1523
- this._log('info', '✅ 后台经验总结完成,知识已持久化');
1524
- } catch (err) {
1525
- this._log('warn', `_summarizeAndPersist 异常: ${err.message}`);
1526
- }
1527
- }
1528
-
1529
- /**
1530
- * _summarizeExperience — 向指定 Session 追加经验总结 prompt 并等待文件生成。
1531
- *
1532
- * 通过 CLI 的 sendAndWaitMessage 向指定 Session 发送经验总结 prompt,
1533
- * 同步等待 AI 回复完成,然后验证 Summary .md 文件是否已生成。
1534
- *
1535
- * 降级策略(不影响步骤成功状态):
1536
- * - 无效 sessionId → 返回 false
1537
- * - sendAndWaitMessage 失败 → 返回 false
1538
- * - AI 回复完成但未生成 Summary .md → 等待超时后返回 false
1539
- * - 任何异常 → 返回 false
1540
- *
1541
- * @param {string} summaryFilePath - 经验文件输出路径
1542
- * @param {string|null} skillDir - SKILL 目录路径(null 表示无 SKILL 模式)
1543
- * @param {string} sessionId - 执行任务的 Session ID
1544
- * @returns {Promise<boolean>} 经验总结是否成功生成 Summary .md
1545
- * @private
1546
- */
1547
- async _summarizeExperience(summaryFilePath, skillDir, sessionId) {
1548
- if (!summaryFilePath) {
1549
- this._log('warn', '_summarizeExperience: summaryFilePath 为空');
1550
- return false;
1551
- }
1552
-
1553
- if (!sessionId) {
1554
- this._log('warn', '_summarizeExperience: sessionId 为空,无法追加经验总结');
1555
- return false;
1556
- }
1557
-
1558
- this._log('info', `经验总结开始 — session: ${sessionId}`);
1559
-
1560
- try {
1561
- // 终止检查:总结开始前已终止 → 跳过(不再向 session 发送新 prompt)
1562
- if (this.#aborted) {
1563
- this._log('info', '_summarizeExperience: 已终止,跳过经验总结');
1564
- return false;
1565
- }
1566
-
1567
- // 构建经验总结 prompt
1568
- const summaryPrompt = this._buildSummaryPrompt(summaryFilePath, skillDir);
1569
-
1570
- // 直接调用 CLI 的 sendAndWaitMessage,显式传入 sessionId
1571
- // (不经过 this.sendAndWaitMessage 包装,避免读取 this.#sessionId 被实例复用覆盖)
1572
- if (typeof this.#cli.sendAndWaitMessage !== 'function') {
1573
- this._log('warn', '_summarizeExperience: CLI 不支持 sendAndWaitMessage 方法');
1574
- return false;
1575
- }
1576
-
1577
- const result = await this.#cli.sendAndWaitMessage(sessionId, summaryPrompt);
1578
-
1579
- // 等待 AI 回复期间收到终止请求 → 不再等待文件生成(session 已被远程中止)
1580
- if (this.#aborted) {
1581
- this._log('info', '_summarizeExperience: 等待回复期间被终止,放弃经验总结');
1582
- return false;
1583
- }
1584
-
1585
- if (!result || !result.success) {
1586
- this._log('warn', '_summarizeExperience: sendAndWaitMessage 返回失败,经验总结未完成');
1587
- return false;
1588
- }
1589
-
1590
- this._log('info',
1591
- `_summarizeExperience: AI 回复完成,content 长度 ${result.content?.length || 0},` +
1592
- `等待 Summary 文件生成…`
1593
- );
1594
-
1595
- // AI 回复完成,但文件写入可能有延迟,轮询等待文件出现
1596
- const fileReady = await this._waitForFile(summaryFilePath, SUMMARY_TIMEOUT_MS);
1597
- if (!fileReady) {
1598
- this._log('warn',
1599
- `_summarizeExperience: 等待 Summary 文件超时(${SUMMARY_TIMEOUT_MS / 1000}s)— ${summaryFilePath}`
1600
- );
1601
- return false;
1602
- }
1603
-
1604
- this._log('info', `经验总结完成 — Summary 文件已生成: ${summaryFilePath}`);
1605
- return true;
1606
- } catch (err) {
1607
- this._log('error', `_summarizeExperience 异常: ${err.message}`);
1608
- return false;
1609
- }
1610
- }
1611
-
1612
- /**
1613
- * _waitForFile — 轮询等待文件出现。
1614
- *
1615
- * AI 回复完成后,文件写入可能有延迟(如工具调用尚未 flush),
1616
- * 此方法按固定间隔轮询文件是否存在,直到超时。
1617
- *
1618
- * @param {string} filePath - 等待的文件路径
1619
- * @param {number} timeoutMs - 超时时间(ms)
1620
- * @returns {Promise<boolean>} 文件是否在超时前出现
1621
- * @private
1622
- */
1623
- async _waitForFile(filePath, timeoutMs) {
1624
- const deadline = Date.now() + timeoutMs;
1625
- const interval = 3000; // 3s 轮询间隔
1626
-
1627
- while (Date.now() < deadline) {
1628
- if (this.#aborted) return false;
1629
-
1630
- try {
1631
- await fs.access(filePath);
1632
- return true;
1633
- } catch {
1634
- // 文件尚未出现,继续等待
1635
- }
1636
-
1637
- await this._sleep(interval);
1638
- }
1639
-
1640
- return false;
1641
- }
1642
-
1643
- /**
1644
- * 收集当前大循环内的历史结果文档路径,供 _buildPrompt 使用。
1645
- *
1646
- * 收集范围:仅当前大循环轮次内,本次执行之前的重试结果(retry < loopCount)
1647
- * 文件名: stepId{n}_loop{L}_result_{R}.md(R < loopCount)
1648
- *
1649
- * 注意:不再收集上一轮大循环的结果,且只收集文件路径不读取内容。
1650
- *
1651
- * 静默失败:文件不存在时跳过,不影响主流程。
1652
- *
1653
- * @param {number} loopCount - 当前步骤内重试次数(收集 R < loopCount 的文件)
1654
- * @returns {Promise<Array<{type: string, loop: number, path: string}>>}
1655
- * @private
1656
- */
1657
- async _collectHistoryDocs(loopCount) {
1658
- const docs = [];
1659
- const prefix = `stepId${this.#stepId}`;
1660
-
1661
- // ── 收集当前大循环内的重试历史(仅路径,不读取内容) ──
1662
- for (let n = 0; n < loopCount; n++) {
1663
- const resultPath = path.join(
1664
- this.#taskDir,
1665
- `${prefix}_loop${this.#bigLoopIndex}_result_${n}.md`
1666
- );
1667
- try {
1668
- await fs.access(resultPath);
1669
- docs.push({ type: 'result', loop: n, path: resultPath });
1670
- } catch {
1671
- // 文件不存在,跳过
1672
- }
1673
- }
1674
-
1675
- if (docs.length > 0) {
1676
- this._log('info', `_collectHistoryDocs: 收集到 ${docs.length} 份历史结果文档路径`);
1677
- }
1678
-
1679
- return docs;
1680
- }
1681
-
1682
- /**
1683
- * 轮询 opencode Session 状态,直到完成或超时。
1684
- *
1685
- * @param {string} sessionId
1686
- * @returns {Promise<boolean>} 是否完成
1687
- * @private
1688
- */
1689
- async _pollSession(sessionId) {
1690
- const deadline = Date.now() + POLL_TIMEOUT_MS;
1691
-
1692
- while (Date.now() < deadline) {
1693
- if (this.#aborted) return false;
1694
-
1695
- await this._sleep(this.#pollIntervalMs);
1696
-
1697
- try {
1698
- const { status } = await this.#cli.checkSessionStatus(sessionId);
1699
- if (status === 'completed') {
1700
- return true;
1701
- }
1702
- if (status === 'unknown') {
1703
- this._log('debug', `Session ${sessionId} 状态未知,继续等待…`);
1704
- }
1705
- } catch (err) {
1706
- this._log('warn', `轮询 Session 状态失败: ${err.message}`);
1707
- }
1708
- }
1709
-
1710
- return false;
1711
- }
1712
-
1713
- /**
1714
- * 若处于暂停状态则等待,直到被 resume。
1715
- * @private
1716
- */
1717
- async _waitIfPaused() {
1718
- while (this.#paused && !this.#aborted) {
1719
- await this._sleep(500);
1720
- }
1721
- }
1722
-
1723
- /**
1724
- * Promise 版 sleep。
1725
- * @param {number} ms
1726
- * @returns {Promise<void>}
1727
- * @private
1728
- */
1729
- _sleep(ms) {
1730
- return new Promise((resolve) => setTimeout(resolve, ms));
1731
- }
1732
-
1733
- /**
1734
- * 统一日志输出。
1735
- * @param {'info'|'warn'|'error'|'debug'} level
1736
- * @param {string} message
1737
- * @private
1738
- */
1739
- _log(level, message) {
1740
- const tag = `FlexRunner:${this.#taskId || 'uninit'}`;
1741
- const logger = createLogger(tag);
1742
- switch (level) {
1743
- case 'error':
1744
- logger.error(`❌ ${message}`);
1745
- break;
1746
- case 'warn':
1747
- logger.warn(`⚠ ${message}`);
1748
- break;
1749
- case 'debug':
1750
- logger.debug(`🔍 ${message}`);
1751
- break;
1752
- default:
1753
- logger.info(`ℹ ${message}`);
1754
- }
1755
- }
1756
- }
1757
-
1758
- export { FlexRunner, ControlType, StepStatus };
1759
- export default FlexRunner;
1
+ /**
2
+ * FlexRunner —— 通用执行模块
3
+ *
4
+ * 接收一个具体事项,将其拆解为多个步骤,并对每个步骤进行执行和追踪。
5
+ *
6
+ * 核心职责:
7
+ * 1. initContext — 初始化任务上下文(工作目录、报告路径等)
8
+ * 2. matchSkill — 基于语义拆解与重排序机制匹配最佳 Skill
9
+ * 3. invokeSkill — 通过 opencode cli 执行选定的 Skill
10
+ * 4. executeStart — 驱动完整执行流程(匹配 → 执行 → 检查 → 持久化)
11
+ * 5. controlExecution — 控制执行步骤(暂停 / 继续 / 终止)
12
+ * 6. persistKnowledge — 将有效经验存入任务
13
+ * 7. getSessionContent / checkResult — 辅助查询
14
+ *
15
+ * 依赖:
16
+ * - CLIController (opencode) 用于执行 Skill
17
+ * - SkillSelector Agent 用于语义匹配 Skill
18
+ * - TaskStepStore (SQLite) 用于步骤持久化
19
+ *
20
+ * @example
21
+ * import { FlexRunner } from './FlexRunner/FlexRunner.js';
22
+ *
23
+ * const runner = new FlexRunner();
24
+ * await runner.initContext({
25
+ * taskId: 'task-001',
26
+ * taskDir: '/workspace/tasks/task-001',
27
+ * skillDirectory: '/workspace/Server/Skills',
28
+ * taskDescription: '分析 libcurl 的鸿蒙化可行性',
29
+ * maxRetries: 3
30
+ * });
31
+ * const ok = await runner.executeStart();
32
+ */
33
+
34
+ import path from 'node:path';
35
+ import { fileURLToPath } from 'node:url';
36
+ import fs from 'node:fs/promises';
37
+
38
+ import { nowCST } from '../library/cstTime.js';
39
+ import { createLogger } from '../Routes/library/logger.js';
40
+
41
+ // dotenv 为可选依赖:生产环境加载 .env,未安装时跳过(如纯 mock 测试场景)
42
+ try {
43
+ const dotenv = (await import('dotenv')).default;
44
+ dotenv.config({ path: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '.env') });
45
+ } catch {
46
+ // dotenv 未安装,跳过 .env 加载
47
+ }
48
+
49
+ // CLIController / SkillSelectorAgent / createStorage 为惰性加载:
50
+ // 测试中通过 initContext 注入 mock 时不需要加载这些模块及其重依赖(@opencode-ai/sdk、openai 等)。
51
+ // 仅在未注入对应实例时才动态 import。
52
+ let _CLIController = null;
53
+ let _SkillSelectorAgent = null;
54
+ let _createStorage = null;
55
+ let _KnowledgeManager = null;
56
+ let _McpToolGuide = null;
57
+
58
+ async function _loadCLIController() {
59
+ if (!_CLIController) {
60
+ const mod = await import('../CLI/cli.js');
61
+ _CLIController = mod.CLIController;
62
+ }
63
+ return _CLIController;
64
+ }
65
+
66
+ async function _loadSkillSelectorAgent() {
67
+ if (!_SkillSelectorAgent) {
68
+ const mod = await import('../Agent/SkillSelector/index.js');
69
+ _SkillSelectorAgent = mod.Agent;
70
+ }
71
+ return _SkillSelectorAgent;
72
+ }
73
+
74
+ async function _loadCreateStorage() {
75
+ if (!_createStorage) {
76
+ const mod = await import('../DbUse/index.js');
77
+ _createStorage = mod.createStorage;
78
+ }
79
+ return _createStorage;
80
+ }
81
+
82
+ async function _loadKnowledgeManager() {
83
+ if (!_KnowledgeManager) {
84
+ const mod = await import('../Knowledge/index.js');
85
+ _KnowledgeManager = mod.KnowledgeManager;
86
+ }
87
+ return _KnowledgeManager;
88
+ }
89
+
90
+ async function _loadMcpToolGuide() {
91
+ if (!_McpToolGuide) {
92
+ const mod = await import('../library/McpToolGuide.js');
93
+ _McpToolGuide = mod.McpToolGuide;
94
+ }
95
+ return _McpToolGuide;
96
+ }
97
+
98
+ // ─── 常量 ────────────────────────────────────────────────────────────────────
99
+
100
+ /** 执行控制类型 */
101
+ const ControlType = Object.freeze({
102
+ PAUSE: 'pause',
103
+ RESUME: 'resume',
104
+ ABORT: 'abort'
105
+ });
106
+
107
+ /** 步骤状态 */
108
+ const StepStatus = Object.freeze({
109
+ PENDING: 'pending',
110
+ RUNNING: 'running',
111
+ COMPLETED: 'completed',
112
+ ERROR: 'error',
113
+ SKIPPED: 'skipped'
114
+ });
115
+
116
+ /** 默认最大重试次数 */
117
+ const DEFAULT_MAX_RETRIES = 3;
118
+
119
+ /** 经验总结环节等待文件生成超时(ms),默认 5 分钟 */
120
+ const SUMMARY_TIMEOUT_MS = 5 * 60 * 1000;
121
+
122
+ /** 轮询间隔(ms),用于等待 opencode session 执行完成 */
123
+ const POLL_INTERVAL_MS = 5000;
124
+
125
+ /** 轮询超时(ms),单个步骤最多等待 1.5 小时 */
126
+ const POLL_TIMEOUT_MS = 90 * 60 * 1000;
127
+
128
+ // ─── FlexRunner 类 ──────────────────────────────────────────────────────────
129
+
130
+ class FlexRunner {
131
+ // ─── 私有变量(通过 # 前缀约定,配合 getter 暴露只读访问) ──────────────────
132
+
133
+ /** @type {string} 任务 ID */
134
+ #taskId = '';
135
+
136
+ /** @type {string} 工作目录 */
137
+ #taskDir = '';
138
+
139
+ /** @type {number} 最大重试次数 */
140
+ #maxRetries = DEFAULT_MAX_RETRIES;
141
+
142
+ /** @type {number} 已循环次数 */
143
+ #retryTimes = 0;
144
+
145
+ /** @type {string|null} 执行开始时间 */
146
+ #startTime = null;
147
+
148
+ /** @type {string|null} 执行结束时间 */
149
+ #endTime = null;
150
+
151
+ /** @type {string} 输入报告路径 */
152
+ #inputReport = '';
153
+
154
+ /** @type {string} SKILL 目录路径 */
155
+ #skillDirectory = '';
156
+
157
+ /** @type {string} 指定 SKILL(name 或目录名);非空时跳过自动匹配直接使用 */
158
+ #specifiedSkill = '';
159
+
160
+ /** @type {string} 任务描述 */
161
+ #taskDescription = '';
162
+
163
+ /** @type {number} 当前步骤 ID(正整数) */
164
+ #stepId = 0;
165
+
166
+ /** @type {number} 依赖步骤 ID(0 = 无依赖) */
167
+ #dependId = 0;
168
+
169
+ /** @type {number} 下一步骤 ID(0 = 无下一步) */
170
+ #nextStepId = 0;
171
+
172
+ /** @type {number} 失败跳转步骤 ID(0 = 失败即终止) */
173
+ #failStepId = 0;
174
+
175
+ /** @type {number} 大循环索引(0=首轮),由 LoopEngine 传递 */
176
+ #bigLoopIndex = 0;
177
+
178
+ /** @type {number} 当前已执行到的步骤序号(单步内重试计数) */
179
+ #executeStep = 0;
180
+
181
+ /** @type {string} 最新结果文件路径 */
182
+ #resultPath = '';
183
+
184
+ /** @type {string} 会话 ID */
185
+ #sessionId = '';
186
+
187
+ // ─── 内部依赖(注入或懒加载) ──────────────────────────────────────────────
188
+
189
+ /** @type {CLIController|null} */
190
+ #cli = null;
191
+
192
+ /** @type {SkillSelectorAgent|null} */
193
+ #skillSelector = null;
194
+
195
+ /** @type {ReturnType<createStorage>|null} */
196
+ #storage = null;
197
+
198
+ /** @type {import('../Knowledge/KnowledgeManager.js').default|null} */
199
+ #knowledgeManager = null;
200
+
201
+ /** @type {import('../library/McpToolGuide.js').default|null} */
202
+ #mcpToolGuide = null;
203
+
204
+ /** @type {boolean} 是否已初始化 */
205
+ #initialized = false;
206
+
207
+ /** @type {boolean} 是否暂停 */
208
+ #paused = false;
209
+
210
+ /** @type {boolean} 是否已终止 */
211
+ #aborted = false;
212
+
213
+ /** @type {string|null} 匹配到的最佳 SKILL 目录 */
214
+ #matchedSkillDir = null;
215
+
216
+ /** @type {object|null} 本次执行收割的结构化指标(来自 meta .json 旁车文件,通用键值对) */
217
+ #metrics = null;
218
+
219
+ /** @type {((sessionId: string) => void)|null} Session 创建后的回调(用于实时同步 sessionId 到编排层) */
220
+ #onSessionCreated = null;
221
+
222
+ /** @type {number} 轮询间隔(ms) */
223
+ #pollIntervalMs = POLL_INTERVAL_MS;
224
+
225
+ /**
226
+ * 构造函数 — 创建 FlexRunner 实例。
227
+ *
228
+ * 支持两种使用方式:
229
+ * 1. 无参构造 + 后续调用 initContext()
230
+ * 2. 构造时传入配置对象,自动完成初始化
231
+ *
232
+ * @param {object} [config] - 可选的初始化配置(同 initContext 入参)
233
+ */
234
+ constructor(config) {
235
+ if (config && typeof config === 'object') {
236
+ // 延迟到 initContext 中处理,避免构造函数中执行异步逻辑
237
+ this._pendingConfig = config;
238
+ }
239
+ }
240
+
241
+ // ─── 只读 getter ───────────────────────────────────────────────────────────
242
+
243
+ /** @returns {string} */
244
+ get taskId() { return this.#taskId; }
245
+ /** @returns {string} */
246
+ get taskDir() { return this.#taskDir; }
247
+ /** @returns {number} */
248
+ get maxRetries() { return this.#maxRetries; }
249
+ /** @returns {number} */
250
+ get retryTimes() { return this.#retryTimes; }
251
+ /** @returns {string|null} */
252
+ get startTime() { return this.#startTime; }
253
+ /** @returns {string|null} */
254
+ get endTime() { return this.#endTime; }
255
+ /** @returns {string} */
256
+ get inputReport() { return this.#inputReport; }
257
+ /** @returns {string} */
258
+ get skillDirectory() { return this.#skillDirectory; }
259
+ /** @returns {string} 指定 SKILL(name 或目录名),未指定时为空串 */
260
+ get specifiedSkill() { return this.#specifiedSkill; }
261
+ /** @returns {string} */
262
+ get taskDescription() { return this.#taskDescription; }
263
+ /** @returns {number} */
264
+ get stepId() { return this.#stepId; }
265
+ /** @returns {number} */
266
+ get dependId() { return this.#dependId; }
267
+ /** @returns {number} */
268
+ get nextStepId() { return this.#nextStepId; }
269
+ /** @returns {number} */
270
+ get failStepId() { return this.#failStepId; }
271
+ /** @returns {number} 大循环索引(0=首轮) */
272
+ get bigLoopIndex() { return this.#bigLoopIndex; }
273
+ /** @returns {number} */
274
+ get executeStep() { return this.#executeStep; }
275
+ /** @returns {string} */
276
+ get resultPath() { return this.#resultPath; }
277
+ /** @returns {string} */
278
+ get sessionId() { return this.#sessionId; }
279
+ /** @returns {boolean} */
280
+ get initialized() { return this.#initialized; }
281
+ /** @returns {object|null} 本次执行收割的结构化指标(无则 null) */
282
+ get metrics() { return this.#metrics; }
283
+
284
+ /**
285
+ * 设置 Session 创建后的回调(可在 initContext 之后注入)。
286
+ * @param {((sessionId: string) => void|Promise<void>)|null} fn
287
+ */
288
+ set onSessionCreated(fn) {
289
+ this.#onSessionCreated = typeof fn === 'function' ? fn : null;
290
+ }
291
+
292
+ // ─── 公开方法 ─────────────────────────────────────────────────────────────
293
+
294
+ /**
295
+ * initContext — 初始化任务上下文。
296
+ *
297
+ * 解析入参 JSON 对象,设置任务 ID、工作目录、SKILL 目录、任务描述等,
298
+ * 并懒初始化 CLI 控制器、Skill 选择器、存储层等内部依赖。
299
+ *
300
+ * @param {object} params - 初始化参数
301
+ * @param {string} params.taskId - 任务 ID(必填)
302
+ * @param {string} [params.taskDir] - 工作目录(默认基于 taskId 推导)
303
+ * @param {string} [params.skillDirectory] - SKILL 目录路径
304
+ * @param {string} [params.specifiedSkill] - 指定 SKILL(name 或目录名);
305
+ * 非空时跳过 matchSkill 自动匹配,直接解析并使用该 SKILL
306
+ * @param {string} [params.taskDescription] - 任务描述
307
+ * @param {string} [params.inputReport] - 输入报告路径
308
+ * @param {number} [params.maxRetries] - 最大重试次数(默认 3)
309
+ * @param {number} [params.stepId] - 当前步骤 ID(正整数,必填)
310
+ * @param {number} [params.dependId] - 依赖步骤 ID(0 = 无依赖)
311
+ * @param {number} [params.nextStepId] - 下一步骤 ID(0 = 无下一步)
312
+ * @param {number} [params.failStepId] - 失败跳转步骤 ID(0 = 失败即终止)
313
+ * @param {CLIController} [params.cli] - 注入自定义 CLI 控制器(测试用)
314
+ * @param {SkillSelectorAgent} [params.skillSelector] - 注入自定义 Skill 选择器
315
+ * @param {ReturnType<createStorage>} [params.storage] - 注入自定义存储层
316
+ * @param {number} [params.pollIntervalMs] - 轮询间隔 ms(默认 3000)
317
+ * @param {string} [params.mcpConfigPath] - MCP config.json 路径(默认自动推导)
318
+ * @param {((sessionId: string) => void|Promise<void>)} [params.onSessionCreated] - Session 创建后的回调
319
+ * @returns {Promise<void>}
320
+ */
321
+ async initContext(params = {}) {
322
+ if (!params || typeof params !== 'object') {
323
+ throw new Error('FlexRunner.initContext: 入参必须是一个 JSON 对象');
324
+ }
325
+
326
+ const {
327
+ taskId,
328
+ taskDir,
329
+ skillDirectory,
330
+ specifiedSkill,
331
+ taskDescription,
332
+ inputReport,
333
+ maxRetries,
334
+ stepId,
335
+ dependId,
336
+ nextStepId,
337
+ failStepId,
338
+ bigLoopIndex,
339
+ cli,
340
+ skillSelector,
341
+ storage,
342
+ knowledgeManager,
343
+ pollIntervalMs,
344
+ mcpConfigPath,
345
+ onSessionCreated
346
+ } = params;
347
+
348
+ if (!taskId) {
349
+ throw new Error('FlexRunner.initContext: taskId 为必填项');
350
+ }
351
+
352
+ // stepId 必须为正整数
353
+ const numStepId = Number(stepId);
354
+ if (!Number.isInteger(numStepId) || numStepId <= 0) {
355
+ throw new Error(`FlexRunner.initContext: stepId 必须为正整数,当前值: ${stepId}`);
356
+ }
357
+
358
+ // ── 初始化内部依赖(支持注入,便于测试;未注入时惰性加载) ──
359
+ // 先初始化 storage,因为 taskDir 的 fallback 需要用到 storage.manager.rootDir
360
+ if (storage) {
361
+ this.#storage = storage;
362
+ } else {
363
+ const createStorage = await _loadCreateStorage();
364
+ this.#storage = createStorage();
365
+ }
366
+
367
+ // ── 设置私有变量 ──
368
+ this.#taskId = String(taskId);
369
+ // taskDir 默认为 db/task/{taskId}(与 storage.json('task') 同目录)
370
+ const _rootDir = this.#storage?.manager?.rootDir;
371
+ this.#taskDir = taskDir ||
372
+ (_rootDir
373
+ ? path.resolve(_rootDir, 'task', this.#taskId)
374
+ : path.resolve(process.cwd(), 'db', 'task', this.#taskId));
375
+ this.#skillDirectory = skillDirectory || '';
376
+ this.#specifiedSkill = String(specifiedSkill || '').trim();
377
+ this.#taskDescription = taskDescription || '';
378
+ this.#inputReport = inputReport || '';
379
+ this.#maxRetries = typeof maxRetries === 'number' ? maxRetries : DEFAULT_MAX_RETRIES;
380
+ this.#stepId = numStepId;
381
+ // dependId 支持数组(fan-in 聚合),此处仅取第一个作为回退锚点语义
382
+ this.#dependId = Number(Array.isArray(dependId) ? dependId[0] : dependId) || 0;
383
+ this.#nextStepId = Number(nextStepId) || 0;
384
+ this.#failStepId = Number(failStepId) || 0;
385
+ this.#bigLoopIndex = Number(bigLoopIndex) || 0;
386
+ this.#executeStep = 0;
387
+ this.#retryTimes = 0;
388
+ this.#startTime = null;
389
+ this.#endTime = null;
390
+ this.#resultPath = '';
391
+ this.#sessionId = '';
392
+ this.#paused = false;
393
+ this.#aborted = false;
394
+ this.#matchedSkillDir = null;
395
+ this.#onSessionCreated = typeof onSessionCreated === 'function' ? onSessionCreated : null;
396
+ this.#pollIntervalMs = typeof pollIntervalMs === 'number' && pollIntervalMs > 0
397
+ ? pollIntervalMs
398
+ : POLL_INTERVAL_MS;
399
+
400
+ // ── 初始化其他内部依赖(支持注入,便于测试;未注入时惰性加载) ──
401
+ if (cli) {
402
+ this.#cli = cli;
403
+ } else {
404
+ const CLIController = await _loadCLIController();
405
+ this.#cli = new CLIController();
406
+ }
407
+
408
+ if (skillSelector) {
409
+ this.#skillSelector = skillSelector;
410
+ } else {
411
+ const SkillSelectorAgent = await _loadSkillSelectorAgent();
412
+ this.#skillSelector = new SkillSelectorAgent();
413
+ }
414
+
415
+ // 知识沉淀管理器(支持注入,便于测试;未注入时惰性加载 + init)
416
+ if (knowledgeManager) {
417
+ this.#knowledgeManager = knowledgeManager;
418
+ } else {
419
+ const KnowledgeManager = await _loadKnowledgeManager();
420
+ this.#knowledgeManager = new KnowledgeManager();
421
+ await this.#knowledgeManager.init();
422
+ }
423
+
424
+ // MCP 工具引导(支持注入;未注入时惰性加载,用 mcpConfigPath 或默认路径)
425
+ const McpToolGuide = await _loadMcpToolGuide();
426
+ this.#mcpToolGuide = new McpToolGuide(mcpConfigPath);
427
+
428
+ this.#initialized = true;
429
+ }
430
+
431
+ /**
432
+ * executeStart — 驱动单次执行流程(6 步)。
433
+ *
434
+ * 本方法为**单次执行**,不内部循环。外部执行机构根据返回值决定是否
435
+ * 再次调用本方法进行重试。每次调用 #executeStep 递增,生成的文件
436
+ * 以 loopCount 区分。
437
+ *
438
+ * 流程:
439
+ * 1. matchSkill → 匹配最佳 Skill(未匹配到时返回 null,降级为无 SKILL 模式)
440
+ * 2. invokeSkill → 通过 opencode 执行 Skill,生成 result .md 文件
441
+ * (skillDir 为 null 时,基于任务描述本身直接执行,不使用 SKILL)
442
+ * (第 N 次执行时,自动收集历史 result/summary .md 作为上下文)
443
+ * (初始 prompt 仅负责执行任务 + 生成 result .md,不包含经验总结指令)
444
+ * 3. checkResult → 读取 result .md,判断成功/失败
445
+ * 4. 返回 { resultPath, success, nextStepId }
446
+ * 5.(后台异步)_summarizeAndPersist → 仅在成功后,向同一 Session 追加经验总结 prompt
447
+ * (通过 sendAndWaitMessage 等待 AI 生成 Summary .md,再 persistKnowledge)
448
+ * (fire-and-forget:不阻塞 executeStart 返回,不影响步骤流转)
449
+ * (失败/超时降级:不影响步骤成功状态,仅记录 warn 日志)
450
+ *
451
+ * 文件命名(按大循环轮次 + 步骤内重试次数区分):
452
+ * - 结果文件: stepId{actualStepId}_loop{bigLoopIndex}_result_{retryCount}.md
453
+ * - 经验文件: stepId{actualStepId}_loop{bigLoopIndex}_Summary_{retryCount}.md
454
+ * - 指标文件: stepId{actualStepId}_loop{bigLoopIndex}_meta_{retryCount}.json(可选,SKILL 约定的结构化结论)
455
+ *
456
+ * 控制信号(pause/resume/abort)在步骤边界检查,非实时。
457
+ *
458
+ * @returns {Promise<{resultPath: string, success: boolean, nextStepId: number}>}}
459
+ */
460
+ async executeStart() {
461
+ this._ensureInitialized();
462
+ if (this.#aborted) {
463
+ throw new Error('FlexRunner.executeStart: 任务已被终止,无法启动');
464
+ }
465
+
466
+ const loopCount = this.#executeStep;
467
+ this.#startTime = nowCST();
468
+ let resultPath = '';
469
+ let success = false;
470
+
471
+ this._log('info', `── 第 ${loopCount + 1} 次执行(loopCount=${loopCount})──`);
472
+
473
+ // 写入初始步骤记录
474
+ await this._persistStep({
475
+ status: StepStatus.RUNNING,
476
+ startTime: this.#startTime,
477
+ executeStep: loopCount
478
+ });
479
+
480
+ try {
481
+ // ── 步骤 1:matchSkill ──
482
+ // 指定 SKILL(specifiedSkill 非空)时跳过自动匹配,直接解析使用
483
+ await this._waitIfPaused();
484
+ if (this.#aborted) {
485
+ this._log('warn', `任务在 matchSkill 前被终止`);
486
+ } else if (this.#specifiedSkill) {
487
+ this.#matchedSkillDir = await this._resolveSpecifiedSkill(
488
+ this.#specifiedSkill,
489
+ this.#skillDirectory
490
+ );
491
+ await this._persistStep({
492
+ matchedSkillDir: this.#matchedSkillDir,
493
+ executeStep: loopCount
494
+ });
495
+ } else {
496
+ this.#matchedSkillDir = await this.matchSkill(
497
+ this.#taskDescription,
498
+ this.#skillDirectory
499
+ );
500
+ await this._persistStep({
501
+ matchedSkillDir: this.#matchedSkillDir,
502
+ executeStep: loopCount
503
+ });
504
+ }
505
+
506
+ // ── 构建文件路径(按大循环轮次区分,避免跨轮覆盖) ──
507
+ resultPath = path.join(
508
+ this.#taskDir,
509
+ `stepId${this.#stepId}_loop${this.#bigLoopIndex}_result_${loopCount}.md`
510
+ );
511
+ const summaryFilePath = path.join(
512
+ this.#taskDir,
513
+ `stepId${this.#stepId}_loop${this.#bigLoopIndex}_Summary_${loopCount}.md`
514
+ );
515
+ const metaFilePath = path.join(
516
+ this.#taskDir,
517
+ `stepId${this.#stepId}_loop${this.#bigLoopIndex}_meta_${loopCount}.json`
518
+ );
519
+
520
+ // ── 收集历史执行文档(第 N 次执行时传入之前的结果/经验) ──
521
+ const historyDocs = await this._collectHistoryDocs(loopCount);
522
+
523
+ // ── 步骤 2:invokeSkill(生成 result .md) ──
524
+ await this._waitIfPaused();
525
+ if (!this.#aborted) {
526
+ const invoked = await this.invokeSkill(
527
+ this.#taskDescription,
528
+ this.#matchedSkillDir,
529
+ this.#inputReport || undefined,
530
+ { resultFilePath: resultPath, metaFilePath, historyDocs }
531
+ );
532
+
533
+ if (!invoked) {
534
+ throw new Error('invokeSkill 返回 false,执行失败');
535
+ }
536
+
537
+ if (this.#sessionId) {
538
+ await this._persistStep({
539
+ sessionId: this.#sessionId,
540
+ executeStep: loopCount
541
+ });
542
+ }
543
+
544
+ // ── 步骤 3:checkResult(读取 result .md 判断成功/失败) ──
545
+ await this._waitIfPaused();
546
+ const ok = await this.checkResult(resultPath);
547
+
548
+ if (ok) {
549
+ success = true;
550
+ // ── 收割结构化指标(meta .json 旁车文件,通用键值对,后端不解释语义) ──
551
+ this.#metrics = await this._harvestMetrics(metaFilePath);
552
+ this._log('info', '✅ 执行成功,经验总结将在后台异步进行');
553
+ // ── 后台异步:经验总结 + 知识持久化(不阻塞 executeStart 返回) ──
554
+ // capture sessionId 防止实例复用时被覆盖
555
+ const sid = this.#sessionId;
556
+ const skillDir = this.#matchedSkillDir;
557
+ this._summarizeAndPersist(summaryFilePath, skillDir, sid).catch((err) => {
558
+ this._log('warn', `后台经验总结/持久化异常: ${err.message}`);
559
+ });
560
+ } else {
561
+ this._log('warn', `checkResult 未通过(loopCount=${loopCount})`);
562
+ }
563
+ }
564
+ } catch (err) {
565
+ this._log('error', `执行异常: ${err.message}`);
566
+ }
567
+
568
+ this.#endTime = nowCST();
569
+ this.#resultPath = resultPath;
570
+
571
+ // 更新步骤记录:成功 / 失败 / 终止
572
+ const finalStatus = this.#aborted
573
+ ? StepStatus.SKIPPED
574
+ : (success ? StepStatus.COMPLETED : StepStatus.ERROR);
575
+ await this._persistStep({
576
+ status: finalStatus,
577
+ endTime: this.#endTime,
578
+ executeStep: loopCount,
579
+ resultPath,
580
+ retryTimes: loopCount,
581
+ metrics: this.#metrics
582
+ });
583
+
584
+ // 递增执行计数,供下一次调用使用
585
+ this.#executeStep++;
586
+
587
+ // 成功 → nextStepId;失败 → failStepId(与 Orchestrator 的失败流转语义对齐)
588
+ const nextStepId = success ? this.#nextStepId : this.#failStepId;
589
+
590
+ return { resultPath, success, nextStepId, metrics: this.#metrics };
591
+ }
592
+
593
+ /**
594
+ * canRetry — 判断当前步骤是否还可以继续重试。
595
+ *
596
+ * 供外部执行机构在调用 executeStart() 前检查:
597
+ * - 若返回 false,表示已达最大重试次数,不应再次调用。
598
+ * - 若返回 true,可以继续调用 executeStart() 进行重试。
599
+ *
600
+ * @returns {boolean} 是否还能重试
601
+ */
602
+ canRetry() {
603
+ return this.#executeStep <= this.#maxRetries && !this.#aborted;
604
+ }
605
+
606
+ /**
607
+ * matchSkill — 基于语义拆解与重排序机制匹配最佳 Skill。
608
+ *
609
+ * 委托 SkillSelector Agent(ReAct 模式):
610
+ * Reason #1: LLM 拆解任务 → 生成关键词/意图/技术栈
611
+ * Act: 模糊匹配召回 topK 候选
612
+ * Reason #2: LLM 评分排序 → 选出最佳
613
+ *
614
+ * 匹配失败时的策略:
615
+ * - SKILL 目录为空或未找到任何 SKILL → 返回 null(降级为无 SKILL 执行)
616
+ * - 模糊匹配未召回任何候选 → 返回 null
617
+ * - top1 分数低于命中阈值 → 返回 null
618
+ * - 匹配结果缺少目录路径 → 返回 null
619
+ * 调用方(executeStart)收到 null 后将以无 SKILL 模式继续向下执行。
620
+ *
621
+ * @param {string} taskDescription - 任务描述字符串
622
+ * @param {string} skillDirectory - SKILL 目录路径
623
+ * @returns {Promise<string|null>} 最适合的 SKILL 目录绝对路径;未匹配到时返回 null
624
+ */
625
+ async matchSkill(taskDescription, skillDirectory) {
626
+ this._ensureInitialized();
627
+
628
+ if (!taskDescription) {
629
+ throw new Error('FlexRunner.matchSkill: taskDescription 不能为空');
630
+ }
631
+ if (!skillDirectory) {
632
+ this._log('warn', 'matchSkill: skillDirectory 为空,将以无 SKILL 模式执行');
633
+ return null;
634
+ }
635
+
636
+ this._log('info', `matchSkill 开始 — task: "${taskDescription.slice(0, 80)}…"`);
637
+
638
+ let selection;
639
+ try {
640
+ selection = await this.#skillSelector.selectSkill(taskDescription, skillDirectory);
641
+ } catch (err) {
642
+ this._log('warn', `matchSkill: SkillSelector 执行异常 — ${err.message},将以无 SKILL 模式执行`);
643
+ return null;
644
+ }
645
+
646
+ if (!selection || !selection.best) {
647
+ this._log('warn', `matchSkill: 未匹配到任何合适的 Skill(topScore=${selection?.topScore ?? 0}),将以无 SKILL 模式执行`);
648
+ return null;
649
+ }
650
+
651
+ // 优先使用 SkillSelection.skillPath,回退到 SkillMeta.skillPath
652
+ const bestDir = selection.skillPath || selection.best.skillPath;
653
+ if (!bestDir) {
654
+ this._log('warn', 'matchSkill: 匹配结果缺少 Skill 目录路径,将以无 SKILL 模式执行');
655
+ return null;
656
+ }
657
+
658
+ this._log('info', `matchSkill 完成 — 最佳 Skill: ${selection.best.name} (${bestDir})`);
659
+ return bestDir;
660
+ }
661
+
662
+ /**
663
+ * _resolveSpecifiedSkill — 解析用户指定的 SKILL(跳过自动匹配)。
664
+ *
665
+ * 解析顺序(在 skillDirectory 下):
666
+ * 1. 目录名精确匹配 → {skillDirectory}/{specifiedSkill}
667
+ * 2. SKILL name 匹配 → 扫描所有 SKILL.md frontmatter 的 name 字段
668
+ *
669
+ * 解析失败时的策略:
670
+ * - skillDirectory 为空 / 目录不存在 / 未找到匹配 SKILL → 返回 null(降级为无 SKILL 模式)
671
+ * - 仅记录 warn 日志,不抛异常,保证执行流程不中断
672
+ *
673
+ * @param {string} specifiedSkill - 指定的 SKILL name 或目录名
674
+ * @param {string} skillDirectory - SKILL 根目录路径
675
+ * @returns {Promise<string|null>} SKILL 目录绝对路径;解析失败时返回 null
676
+ */
677
+ async _resolveSpecifiedSkill(specifiedSkill, skillDirectory) {
678
+ this._ensureInitialized();
679
+
680
+ if (!specifiedSkill) {
681
+ return null;
682
+ }
683
+ if (!skillDirectory) {
684
+ this._log('warn', `specifiedSkill: skillDirectory 为空,无法解析指定 SKILL "${specifiedSkill}",将以无 SKILL 模式执行`);
685
+ return null;
686
+ }
687
+
688
+ this._log('debug', `specifiedSkill 开始 — 指定 Skill: "${specifiedSkill}"`);
689
+
690
+ try {
691
+ // ── 1. 目录名精确匹配 ──
692
+ const directDir = path.resolve(skillDirectory, specifiedSkill);
693
+ const directSkillMd = path.join(directDir, 'SKILL.md');
694
+ try {
695
+ const stat = await fs.stat(directSkillMd);
696
+ if (stat.isFile()) {
697
+ this._log('debug', `specifiedSkill 完成 — 目录名匹配: ${directDir}`);
698
+ return directDir;
699
+ }
700
+ } catch {
701
+ // 直接路径不存在 SKILL.md,继续尝试 name 匹配
702
+ }
703
+
704
+ // ── 2. 扫描 SKILL name 匹配(frontmatter 的 name 字段) ──
705
+ let entries;
706
+ try {
707
+ entries = await fs.readdir(skillDirectory, { withFileTypes: true });
708
+ } catch (err) {
709
+ this._log('warn', `specifiedSkill: 无法读取 SKILL 目录 ${skillDirectory} — ${err.message},将以无 SKILL 模式执行`);
710
+ return null;
711
+ }
712
+
713
+ const target = specifiedSkill.toLowerCase();
714
+ for (const entry of entries) {
715
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
716
+ const dirPath = path.join(skillDirectory, entry.name);
717
+ const skillMdPath = path.join(dirPath, 'SKILL.md');
718
+ try {
719
+ const md = await fs.readFile(skillMdPath, 'utf-8');
720
+ // 解析 frontmatter 中的 name 字段(--- 包围的 YAML 头)
721
+ const fmMatch = md.match(/^---\r?\n([\s\S]*?)\r?\n---/);
722
+ if (fmMatch) {
723
+ const nameMatch = fmMatch[1].match(/^name:\s*(.+)$/m);
724
+ if (nameMatch) {
725
+ const name = nameMatch[1].trim().replace(/^['"]|['"]$/g, '');
726
+ if (name.toLowerCase() === target) {
727
+ this._log('info', `specifiedSkill 完成 — name 匹配: ${name} (${dirPath})`);
728
+ return dirPath;
729
+ }
730
+ }
731
+ }
732
+ } catch {
733
+ // 读取失败跳过该目录
734
+ }
735
+ }
736
+
737
+ this._log('warn', `specifiedSkill: 在 ${skillDirectory} 下未找到名为 "${specifiedSkill}" 的 SKILL(目录名/name 均未命中),将以无 SKILL 模式执行`);
738
+ return null;
739
+ } catch (err) {
740
+ this._log('warn', `specifiedSkill: 解析异常 — ${err.message},将以无 SKILL 模式执行`);
741
+ return null;
742
+ }
743
+ }
744
+
745
+ /**
746
+ * _harvestMetrics — 收割结构化指标(meta .json 旁车文件)。
747
+ *
748
+ * 通用契约:初始 prompt 中下发 meta 文件路径,SKILL 若定义了结构化结论指标
749
+ * (如 code-check 的 mergeLevel、仓库检查的 score),由 AI 以 JSON 对象写入该路径。
750
+ * 后端不解释键的语义,仅校验 JSON 合法性后原样透传(键名由各 SKILL 自行约定)。
751
+ *
752
+ * 降级策略(均不影响执行状态):
753
+ * - 文件不存在 → 返回 null(SKILL 未约定指标,正常情况)
754
+ * - JSON 解析失败 / 非对象 → 返回 null,记录 warn
755
+ *
756
+ * @param {string} metaFilePath - 指标文件路径
757
+ * @returns {Promise<object|null>} 结构化指标对象;无/非法时返回 null
758
+ */
759
+ async _harvestMetrics(metaFilePath) {
760
+ if (!metaFilePath) return null;
761
+ try {
762
+ let raw = await fs.readFile(metaFilePath, 'utf-8');
763
+ if (raw.charCodeAt(0) === 0xFEFF) raw = raw.slice(1);
764
+ const parsed = JSON.parse(raw);
765
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
766
+ this._log('info', `metrics 已收割 — ${Object.keys(parsed).join(', ')}`);
767
+ return parsed;
768
+ }
769
+ this._log('warn', 'metrics: meta 文件内容非 JSON 对象,忽略');
770
+ return null;
771
+ } catch (err) {
772
+ if (err.code === 'ENOENT') {
773
+ // SKILL 未约定指标文件,正常情况,不打日志
774
+ return null;
775
+ }
776
+ this._log('warn', `metrics: 读取/解析 meta 文件失败 — ${err.message},忽略`);
777
+ return null;
778
+ }
779
+ }
780
+
781
+ /**
782
+ * invokeSkill — 通过 opencode cli 执行选定的 Skill(或无 SKILL 直接执行)。
783
+ *
784
+ * 流程:
785
+ * 1. 创建 opencode Session(标题=taskId+stepId+loopCount)
786
+ * 2. 发送初始 prompt(任务描述 + SKILL 目录 + 报告路径 + 结果文件路径)
787
+ * — skillDir 为 null 时,prompt 不包含 SKILL 目录,改为基于任务描述直接执行
788
+ * — 初始 prompt 仅负责执行任务 + 生成 result .md,**不包含经验总结指令**
789
+ * — 经验总结在 checkResult 成功后由 _summarizeExperience 独立追加
790
+ * 3. 轮询 Session 状态直到完成或超时
791
+ * 4. 记录 sessionId
792
+ *
793
+ * opencode 执行过程中会固定生成:
794
+ * - resultFilePath: stepId{actualStepId}_loop{bigLoopIndex}_result_{retryCount}.md
795
+ *
796
+ * @param {string} taskDescription - 任务描述字符串
797
+ * @param {string|null} skillDir - 选定的 SKILL 目录路径;null 表示无 SKILL 模式
798
+ * @param {string} [reportPath] - 输入报告路径(可选)
799
+ * @param {object} [filePaths] - 文件路径
800
+ * @param {string} [filePaths.resultFilePath] - 结果文件输出路径
801
+ * @returns {Promise<boolean>} 是否成功
802
+ */
803
+ async invokeSkill(taskDescription, skillDir, reportPath, filePaths = {}) {
804
+ this._ensureInitialized();
805
+
806
+ if (!taskDescription) {
807
+ throw new Error('FlexRunner.invokeSkill: taskDescription 不能为空');
808
+ }
809
+ // skillDir 允许为 null:未匹配到 SKILL 时以无 SKILL 模式执行
810
+
811
+ const modeLabel = skillDir ? 'SKILL 模式' : '无 SKILL 模式';
812
+ this._log('debug', `invokeSkill 开始 — ${modeLabel}${skillDir ? `: ${skillDir}` : ''}`);
813
+
814
+ try {
815
+ // ── 1. 健康检查 ──
816
+ const health = await this.#cli.checkHealth();
817
+ if (health.status !== 'ok') {
818
+ this._log('error', `CLI(${this.#cli.getType()}) 服务不可用: ${health.message}`);
819
+ return false;
820
+ }
821
+
822
+ // ── 2. 构建 prompt(含历史执行文档) ──
823
+ const title = `task=${this.#taskId}|step=${this.#stepId}|bigLoop=${this.#bigLoopIndex}|retry=${this.#executeStep}`;
824
+ const prompt = this._buildPrompt(taskDescription, skillDir, reportPath, filePaths);
825
+
826
+ // ── 3. 创建 Session 并发送初始 prompt ──
827
+ // 指定工作目录为 taskDir,确保 opencode session 的文件操作(git clone 等)在 db/task/{taskId}/ 下执行
828
+ // const { sessionId } = await this.#cli.startSession(title, prompt, { cwd: this.#taskDir });
829
+ const { sessionId } = await this.#cli.startSession(title, prompt);
830
+ this.#sessionId = sessionId
831
+ this._log('debug', `Session 已创建: ${sessionId}`);
832
+
833
+ // 实时通知编排层(静默失败,不影响主流程)
834
+ if (this.#onSessionCreated) {
835
+ try {
836
+ await this.#onSessionCreated(sessionId);
837
+ } catch (err) {
838
+ this._log('warn', `onSessionCreated 回调异常: ${err.message}`);
839
+ }
840
+ }
841
+
842
+ // ── 4. 轮询等待执行完成 ──
843
+ const completed = await this._pollSession(sessionId);
844
+ if (!completed) {
845
+ this._log('warn', `Session ${sessionId} 未在超时时间内完成`);
846
+ return false;
847
+ }
848
+
849
+ this._log('info', `invokeSkill 完成 — sessionId: ${sessionId}`);
850
+ return true;
851
+ } catch (err) {
852
+ this._log('error', `invokeSkill 异常: ${err.message}`);
853
+ return false;
854
+ }
855
+ }
856
+
857
+ /**
858
+ * persistKnowledge — 读取经验文件,将有效经验存入任务。
859
+ *
860
+ * 读取 Summary .md 文件内容,将其作为经验知识记录到 TaskStepStore,
861
+ * 并登记到知识沉淀系统(KnowledgeManager)。
862
+ *
863
+ * 调用时序(由 executeStart 驱动):
864
+ * 1. invokeSkill 执行任务(生成 result .md)
865
+ * 2. checkResult 判断成功
866
+ * 3. _summarizeExperience 追加经验总结 prompt(AI 生成 Summary .md)
867
+ * 4. persistKnowledge(本方法)读取 Summary .md 并持久化
868
+ *
869
+ * 判断逻辑:
870
+ * - _summarizeExperience 成功后,Summary .md 通常已生成。
871
+ * - AI 可能判断无有价值经验而不生成文件(沉淀类型 = 无),此时跳过登记。
872
+ * - 文件不存在时静默跳过,返回 false。
873
+ *
874
+ * 流程:
875
+ * 1. 检查 summaryFilePath 对应的文件是否存在(不存在 → 跳过,返回 false)
876
+ * 2. 读取文件内容,持久化到步骤记录(knowledgeSummary 字段)
877
+ * 3. 调用 KnowledgeManager.addExperience() 登记到知识沉淀系统
878
+ *
879
+ * 静默失败:持久化失败不影响主流程。
880
+ *
881
+ * @param {string} summaryFilePath - 经验文件路径
882
+ * @returns {Promise<boolean>} 是否成功
883
+ */
884
+ async persistKnowledge(summaryFilePath) {
885
+ this._ensureInitialized();
886
+
887
+ if (!summaryFilePath) {
888
+ this._log('warn', 'persistKnowledge: summaryFilePath 为空');
889
+ return false;
890
+ }
891
+
892
+ // ── 检查经验文档是否存在 ──
893
+ // 无 SKILL 模式下,AI 可能判断无有价值经验而不生成 Summary 文件,
894
+ // 此时跳过知识沉淀登记。
895
+ let exists = false;
896
+ try {
897
+ await fs.access(summaryFilePath);
898
+ exists = true;
899
+ } catch {
900
+ exists = false;
901
+ }
902
+
903
+ if (!exists) {
904
+ this._log('info', `persistKnowledge: 经验文档不存在,跳过知识沉淀登记 — ${summaryFilePath}`);
905
+ return false;
906
+ }
907
+
908
+ try {
909
+ const content = await fs.readFile(summaryFilePath, 'utf-8');
910
+ this._log('info', `persistKnowledge: 已读取经验文件 (${content.length} 字符)`);
911
+
912
+ // 1. 将经验内容持久化到步骤记录
913
+ await this._persistStep({ knowledgeSummary: content });
914
+ this._log('info', 'persistKnowledge: 经验已持久化到步骤记录');
915
+
916
+ // 2. 登记到知识沉淀系统
917
+ if (this.#knowledgeManager) {
918
+ // 避免重复登记:先检查是否已存在
919
+ const existing = await this.#knowledgeManager.findByDocPath(summaryFilePath);
920
+ if (existing) {
921
+ this._log('info', `persistKnowledge: 经验已登记过,跳重复登记 — id: ${existing.id}`);
922
+ } else {
923
+ const record = await this.#knowledgeManager.addExperience({
924
+ docPath: summaryFilePath,
925
+ taskId: this.#taskId,
926
+ stepId: this.#stepId,
927
+ bigLoopIndex: this.#bigLoopIndex,
928
+ retryCount: this.#executeStep,
929
+ skillDir: this.#matchedSkillDir,
930
+ taskDescription: this.#taskDescription
931
+ });
932
+ this._log('info', `persistKnowledge: 经验已登记到知识沉淀系统 — id: ${record.id}`);
933
+ }
934
+ } else {
935
+ this._log('warn', 'persistKnowledge: KnowledgeManager 未初始化,跳过知识沉淀登记');
936
+ }
937
+
938
+ return true;
939
+ } catch (err) {
940
+ this._log('warn', `persistKnowledge: 处理经验文件失败: ${summaryFilePath} — ${err.message}`);
941
+ return false;
942
+ }
943
+ }
944
+
945
+ /**
946
+ * controlExecution — 控制执行步骤。
947
+ *
948
+ * @param {string} type - 控制类型:'pause' | 'resume' | 'abort'
949
+ * @returns {Promise<boolean>} 是否成功
950
+ */
951
+ async controlExecution(type) {
952
+ this._ensureInitialized();
953
+
954
+ switch (type) {
955
+ case ControlType.PAUSE:
956
+ this.#paused = true;
957
+ this._log('info', '⏸ 执行已暂停');
958
+ await this._persistStep({ status: 'paused' });
959
+ return true;
960
+
961
+ case ControlType.RESUME:
962
+ this.#paused = false;
963
+ this._log('info', '▶ 执行已继续');
964
+ await this._persistStep({ status: StepStatus.RUNNING });
965
+ return true;
966
+
967
+ case ControlType.ABORT:
968
+ this.#aborted = true;
969
+ this.#paused = false;
970
+ this._log('warn', '⏹ 执行已终止');
971
+ // 若有活跃 session,尝试中止
972
+ if (this.#sessionId) {
973
+ try {
974
+ await this.#cli.abortSession(this.#sessionId);
975
+ this._log('info', `已中止 Session: ${this.#sessionId}`);
976
+ } catch (err) {
977
+ this._log('warn', `中止 Session 失败: ${err.message}`);
978
+ }
979
+ }
980
+ await this._persistStep({
981
+ status: StepStatus.SKIPPED,
982
+ endTime: nowCST()
983
+ });
984
+ return true;
985
+
986
+ default:
987
+ this._log('warn', `未知的控制类型: "${type}",支持: pause | resume | abort`);
988
+ return false;
989
+ }
990
+ }
991
+
992
+ /**
993
+ * getSessionContent — 获取当前会话的内容。
994
+ *
995
+ * 通过读取 db/Session/ 目录下的归档文件获取会话内容:
996
+ * - <sessionId>.jsonl — 消息流(每行一条消息)
997
+ * - <sessionId>.meta.json — 会话元信息
998
+ *
999
+ * 返回合并后的 JSON 文本字符串,结构为:
1000
+ * { "meta": {...}, "messages": [{...}, ...] }
1001
+ *
1002
+ * @returns {Promise<string>} JSON 文本(包含 meta 和 messages)
1003
+ */
1004
+ async getSessionContent() {
1005
+ this._ensureInitialized();
1006
+
1007
+ if (!this.#sessionId) {
1008
+ this._log('warn', 'getSessionContent: 当前无活跃会话');
1009
+ return JSON.stringify({ meta: null, messages: [] });
1010
+ }
1011
+
1012
+ try {
1013
+ const sessionStore = this.#storage.sessionStore();
1014
+
1015
+ // 并行读取元信息与消息流
1016
+ const [meta, messages] = await Promise.all([
1017
+ sessionStore.readMeta(this.#sessionId).catch(() => null),
1018
+ sessionStore.readMessages(this.#sessionId).catch(() => [])
1019
+ ]);
1020
+
1021
+ this._log(
1022
+ 'info',
1023
+ `getSessionContent: 读取 session ${this.#sessionId},共 ${messages.length} 条消息`
1024
+ );
1025
+
1026
+ return JSON.stringify({ meta, messages }, null, 2);
1027
+ } catch (err) {
1028
+ this._log('error', `getSessionContent: 读取失败: ${err.message}`);
1029
+ return JSON.stringify({ meta: null, messages: [], error: err.message });
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * checkResult — 读取结果文件,判断执行是否成功。
1035
+ *
1036
+ * 兼容 SKILL 产物中多种执行状态标记格式(按优先级匹配):
1037
+ * 1. 标题下独立行:`## 执行状态` 下一行为 `成功` / `失败`
1038
+ * 2. 标题内联:`## 执行状态: 成功` / `## 执行状态:失败`
1039
+ * 3. 末尾 `状态:` 行:文件末尾附近 `状态: 成功` / `状态: 失败`
1040
+ * (如 ArkTsLibraryInterfaceSpecSkill 的 count-report.cjs 写回格式)
1041
+ *
1042
+ * 状态值归一化:`成功` 判 true;`失败` 判 false;
1043
+ * 已知中间态(`部分通过` / `源库构建问题` / `环境不可用` / `设备不可用`)
1044
+ * 视为成功(产物已完成,非失败),记录 warn 日志;
1045
+ * 其他未知状态值视为无法解析 → false。
1046
+ *
1047
+ * @param {string} resultFilePath - 结果文件路径
1048
+ * @returns {Promise<boolean>} 执行是否成功
1049
+ */
1050
+ async checkResult(resultFilePath) {
1051
+ this._ensureInitialized();
1052
+
1053
+ if (!resultFilePath) {
1054
+ this._log('warn', 'checkResult: resultFilePath 为空');
1055
+ return false;
1056
+ }
1057
+
1058
+ try {
1059
+ let content = await fs.readFile(resultFilePath, 'utf-8');
1060
+ if (content.charCodeAt(0) === 0xFEFF) content = content.slice(1);
1061
+
1062
+ // 1. 标题下独立行:`## 执行状态` 下一行为状态值(可能带 - / * / > 列表前缀)
1063
+ let match = content.match(/^#{1,6}\s*执行状态\s*$\n\s*(.+)$/m);
1064
+ if (match) {
1065
+ return this._parseStatusValue(match[1].trim(), resultFilePath);
1066
+ }
1067
+
1068
+ // 2. 标题内联:`## 执行状态: 成功` / `## 执行状态:失败`
1069
+ match = content.match(/^#{1,6}\s*执行状态\s*[::]\s*([^\n]+)/m);
1070
+ if (match) {
1071
+ return this._parseStatusValue(match[1].trim(), resultFilePath);
1072
+ }
1073
+
1074
+ // 3. 末尾 `状态:` 行:仅取文件最后 10 行,避免正文中误出现"状态:"字样
1075
+ const tailLines = content.split('\n').slice(-10);
1076
+ for (const line of tailLines) {
1077
+ const tailMatch = line.match(/^\s*状态\s*[::]\s*(.+)$/);
1078
+ if (tailMatch) {
1079
+ return this._parseStatusValue(tailMatch[1].trim(), resultFilePath);
1080
+ }
1081
+ }
1082
+
1083
+ this._log('warn', `checkResult: 结果文件中未找到有效的执行状态字段: ${resultFilePath}`);
1084
+ return false;
1085
+ } catch (err) {
1086
+ this._log('warn', `checkResult: 读取结果文件失败: ${resultFilePath} — ${err.message}`);
1087
+ return false;
1088
+ }
1089
+ }
1090
+
1091
+ /**
1092
+ * 解析结果文件中的状态值。
1093
+ *
1094
+ * 状态判定规则:
1095
+ * - `成功` → true
1096
+ * - `失败` → false
1097
+ * - 已知中间态(`部分通过` / `源库构建问题` / `环境不可用` / `设备不可用`)
1098
+ * 视为成功(产物已完成,非失败),记录 warn 日志
1099
+ * - 其他未知状态值 → false(视为无法解析,避免误判成功)
1100
+ *
1101
+ * @param {string} raw - 状态值原始文本
1102
+ * @param {string} resultFilePath - 结果文件路径(仅用于日志)
1103
+ * @returns {boolean} 执行是否成功
1104
+ * @private
1105
+ */
1106
+ _parseStatusValue(raw, resultFilePath) {
1107
+ if (!raw) {
1108
+ this._log('warn', `checkResult: 执行状态值解析为空: ${resultFilePath}`);
1109
+ return false;
1110
+ }
1111
+
1112
+ const value = raw.replace(/^[#>*\-\s]+/, '').trim();
1113
+
1114
+ if (value === '成功') {
1115
+ this._log('info', `checkResult: 执行状态 = 成功 (${resultFilePath})`);
1116
+ return true;
1117
+ }
1118
+
1119
+ if (value === '失败') {
1120
+ this._log('info', `checkResult: 执行状态 = 失败 (${resultFilePath})`);
1121
+ return false;
1122
+ }
1123
+
1124
+ // 已知中间态:产物已完成但非完全成功,视为成功(记录 warn 提示)
1125
+ const KNOWN_MIDDLE_STATES = ['部分通过', '源库构建问题', '环境不可用', '设备不可用'];
1126
+ if (KNOWN_MIDDLE_STATES.includes(value)) {
1127
+ this._log('warn', `checkResult: 识别到中间态状态「${value}」,视为成功 (${resultFilePath})`);
1128
+ return true;
1129
+ }
1130
+
1131
+ this._log('warn', `checkResult: 无法识别的执行状态「${value}」,视为失败 (${resultFilePath})`);
1132
+ return false;
1133
+ }
1134
+
1135
+ /**
1136
+ * getLiveMessages — 获取当前会话的实时对话消息。
1137
+ *
1138
+ * 委托 CLI 的 getLiveMessages,从远端拉取当前已有消息并返回精简格式。
1139
+ * 运行中安全调用,不写入本地存档,不影响后续归档去重。
1140
+ *
1141
+ * 如果当前无活跃会话,返回空数组。
1142
+ *
1143
+ * @returns {Promise<Array<{id,role,content,finish,timestamp}>>}
1144
+ */
1145
+ async getLiveMessages() {
1146
+ this._ensureInitialized();
1147
+
1148
+ if (!this.#sessionId) {
1149
+ this._log('warn', 'getLiveMessages: 当前无活跃会话');
1150
+ return [];
1151
+ }
1152
+
1153
+ if (typeof this.#cli.getLiveMessages !== 'function') {
1154
+ this._log('warn', `getLiveMessages: CLI 不支持 getLiveMessages 方法`);
1155
+ return [];
1156
+ }
1157
+
1158
+ return this.#cli.getLiveMessages(this.#sessionId);
1159
+ }
1160
+
1161
+ /**
1162
+ * injectPrompt — 向当前会话注入提示词/上下文(不触发 AI 回复)。
1163
+ *
1164
+ * 利用 CLI 的 injectPrompt 能力,将文本注入对话历史但不触发 AI 生成回复。
1165
+ * 适用于对话过程中动态补充上下文、规则、指令。
1166
+ *
1167
+ * 如果当前无活跃会话,返回失败。
1168
+ *
1169
+ * @param {string} message - 要注入的提示词/上下文
1170
+ * @returns {Promise<{ success: boolean }>}
1171
+ */
1172
+ async injectPrompt(message) {
1173
+ this._ensureInitialized();
1174
+
1175
+ if (!message || typeof message !== 'string') {
1176
+ throw new Error('injectPrompt: message 为必填项且必须为字符串');
1177
+ }
1178
+
1179
+ if (!this.#sessionId) {
1180
+ this._log('warn', 'injectPrompt: 当前无活跃会话');
1181
+ return { success: false };
1182
+ }
1183
+
1184
+ if (typeof this.#cli.injectPrompt !== 'function') {
1185
+ this._log('warn', `injectPrompt: CLI 不支持 injectPrompt 方法`);
1186
+ return { success: false };
1187
+ }
1188
+
1189
+ try {
1190
+ const result = await this.#cli.injectPrompt(this.#sessionId, message);
1191
+ this._log(
1192
+ 'info',
1193
+ `injectPrompt: 已向 session ${this.#sessionId} 注入 ${message.length} 字符提示词`
1194
+ );
1195
+ return result;
1196
+ } catch (err) {
1197
+ this._log('error', `injectPrompt: 注入失败: ${err.message}`);
1198
+ return { success: false };
1199
+ }
1200
+ }
1201
+
1202
+ /**
1203
+ * sendAndWaitMessage — 向当前会话发送消息并同步等待 AI 回复完成。
1204
+ *
1205
+ * 发送消息后阻塞等待 AI 生成完整回复,然后返回回复内容。
1206
+ * 与普通的 fire-and-forget 发送不同,此方法会等到 AI 回复完成才返回。
1207
+ *
1208
+ * 如果当前无活跃会话,返回失败。
1209
+ *
1210
+ * @param {string} message - 要发送的消息
1211
+ * @returns {Promise<{ success: boolean, response: object|string, content: string }>}
1212
+ */
1213
+ async sendAndWaitMessage(message) {
1214
+ this._ensureInitialized();
1215
+
1216
+ if (!message || typeof message !== 'string') {
1217
+ throw new Error('sendAndWaitMessage: message 为必填项且必须为字符串');
1218
+ }
1219
+
1220
+ if (!this.#sessionId) {
1221
+ this._log('warn', 'sendAndWaitMessage: 当前无活跃会话');
1222
+ return { success: false, response: '', content: '' };
1223
+ }
1224
+
1225
+ if (typeof this.#cli.sendAndWaitMessage !== 'function') {
1226
+ this._log('warn', `sendAndWaitMessage: CLI 不支持 sendAndWaitMessage 方法`);
1227
+ return { success: false, response: '', content: '' };
1228
+ }
1229
+
1230
+ try {
1231
+ const result = await this.#cli.sendAndWaitMessage(this.#sessionId, message);
1232
+ this._log(
1233
+ 'info',
1234
+ `sendAndWaitMessage: session ${this.#sessionId} 已收到回复,` +
1235
+ `content 长度 ${result?.content?.length || 0}`
1236
+ );
1237
+ return result;
1238
+ } catch (err) {
1239
+ this._log('error', `sendAndWaitMessage: 发送并等待失败: ${err.message}`);
1240
+ return { success: false, response: '', content: '' };
1241
+ }
1242
+ }
1243
+
1244
+ // ─── 私有方法 ─────────────────────────────────────────────────────────────
1245
+
1246
+ /**
1247
+ * 确保已调用 initContext 完成初始化。
1248
+ * @private
1249
+ */
1250
+ _ensureInitialized() {
1251
+ if (!this.#initialized) {
1252
+ throw new Error('FlexRunner 尚未初始化,请先调用 initContext()');
1253
+ }
1254
+ }
1255
+
1256
+ /**
1257
+ * 将当前步骤的执行状态持久化到 db/task/{taskId}/stepid_{stepId}_loop{L}.json。
1258
+ *
1259
+ * 在执行过程的关键节点(开始、匹配后、会话创建后、结束、终止)被调用,
1260
+ * 增量更新记录文件,方便外部追踪任务执行进度。
1261
+ * 按大循环轮次独立存储,避免跨轮覆盖。
1262
+ *
1263
+ * 静默失败:持久化不影响主流程,仅记录 warn 日志。
1264
+ *
1265
+ * @param {object} patch - 要合并的字段
1266
+ * @private
1267
+ */
1268
+ async _persistStep(patch) {
1269
+ try {
1270
+ if (!this.#taskId || this.#stepId <= 0) return;
1271
+ const store = this.#storage.taskExecStore();
1272
+ await store.patchStep(this.#taskId, this.#stepId, {
1273
+ taskId: this.#taskId,
1274
+ stepId: this.#stepId,
1275
+ dependId: this.#dependId,
1276
+ nextStepId: this.#nextStepId,
1277
+ failStepId: this.#failStepId,
1278
+ bigLoopIndex: this.#bigLoopIndex,
1279
+ taskDescription: this.#taskDescription,
1280
+ skillDirectory: this.#skillDirectory,
1281
+ specifiedSkill: this.#specifiedSkill,
1282
+ inputReport: this.#inputReport,
1283
+ matchedSkillDir: this.#matchedSkillDir,
1284
+ sessionId: this.#sessionId,
1285
+ executeStep: this.#executeStep,
1286
+ retryTimes: this.#retryTimes,
1287
+ maxRetries: this.#maxRetries,
1288
+ startTime: this.#startTime,
1289
+ endTime: this.#endTime,
1290
+ ...patch
1291
+ }, this.#bigLoopIndex);
1292
+ } catch (err) {
1293
+ this._log('warn', `_persistStep: 步骤记录持久化失败: ${err.message}`);
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * 构建 opencode 初始执行 prompt。
1299
+ *
1300
+ * 仅负责任务执行 + 生成 result .md,**不包含经验总结指令**。
1301
+ * 经验总结在 checkResult 成功后由 _buildSummaryPrompt 独立构建。
1302
+ *
1303
+ * @param {string} taskDescription - 任务描述
1304
+ * @param {string|null} skillDir - SKILL 目录(null 表示无 SKILL 模式)
1305
+ * @param {string} [reportPath] - 输入报告路径
1306
+ * @param {object} [filePaths] - 文件路径
1307
+ * @param {string} [filePaths.resultFilePath] - 结果文件输出路径
1308
+ * @param {string} [filePaths.metaFilePath] - 结构化指标文件输出路径(可选)
1309
+ * @returns {string} 拼接后的 prompt 文本
1310
+ * @private
1311
+ */
1312
+ _buildPrompt(taskDescription, skillDir, reportPath, filePaths = {}) {
1313
+ const parts = [
1314
+ `## 任务描述\n${taskDescription}`
1315
+ ];
1316
+
1317
+ // 工作目录:告知 AI 当前工作目录路径,所有文件操作(git clone、读写文件等)均在此目录下执行
1318
+ if (this.#taskDir) {
1319
+ parts.push(`## 工作目录\n${this.#taskDir}\n\n所有文件操作(git clone、读写文件等)请在此目录下执行。`);
1320
+ }
1321
+
1322
+ if (skillDir) {
1323
+ // ── 有 SKILL:按照 SKILL 指令执行 ──
1324
+ parts.push(`## SKILL 目录\n${skillDir}`);
1325
+ if (reportPath) {
1326
+ parts.push(`## 输入报告路径\n${reportPath}`);
1327
+ }
1328
+ if (filePaths.resultFilePath) {
1329
+ parts.push(`## 结果文件输出路径\n${filePaths.resultFilePath}`);
1330
+ }
1331
+ // 结构化指标文件路径(通用契约:SKILL 约定了结构化结论指标时写入)
1332
+ if (filePaths.metaFilePath) {
1333
+ parts.push(`## 结构化指标文件输出路径\n${filePaths.metaFilePath}`);
1334
+ }
1335
+ // 历史结果文档路径(第 N 次执行时传入之前的 result .md 路径,不传内容)
1336
+ if (filePaths.historyDocs && filePaths.historyDocs.length > 0) {
1337
+ const historyLines = filePaths.historyDocs.map(
1338
+ (doc) => `- 本轮重试结果 (retry=${doc.loop}): ${doc.path}`
1339
+ );
1340
+ parts.push(
1341
+ `## 历史执行文档路径\n\n以下为本轮大循环中之前重试的结果文件路径,请自行读取参考:\n${historyLines.join('\n')}`
1342
+ );
1343
+ }
1344
+ parts.push(
1345
+ '请按照 SKILL 中的指令执行任务。',
1346
+ '执行完成后,请将结果写入上述"结果文件输出路径"。',
1347
+ '结果文件需包含 `## 执行状态` 字段(值为 `成功` 或 `失败`),用于判断执行结果。'
1348
+ );
1349
+ if (filePaths.metaFilePath) {
1350
+ parts.push(
1351
+ '若本次使用的 SKILL 中定义了结构化结论指标(如合入等级、评分等),请在执行完成后,',
1352
+ `将指标以 JSON 对象形式写入上述"结构化指标文件输出路径"(键名按 SKILL 约定,如 {"mergeLevel":"PASS"})。`,
1353
+ '若 SKILL 未定义结构化指标,则无需创建该文件。'
1354
+ );
1355
+ }
1356
+ } else {
1357
+ // ── 无 SKILL:基于任务描述本身直接执行 ──
1358
+ if (reportPath) {
1359
+ parts.push(`## 输入报告路径\n${reportPath}`);
1360
+ }
1361
+ if (filePaths.resultFilePath) {
1362
+ parts.push(`## 结果文件输出路径\n${filePaths.resultFilePath}`);
1363
+ }
1364
+ if (filePaths.metaFilePath) {
1365
+ parts.push(`## 结构化指标文件输出路径\n${filePaths.metaFilePath}`);
1366
+ }
1367
+ // 历史结果文档路径(第 N 次执行时传入之前的 result .md 路径,不传内容)
1368
+ if (filePaths.historyDocs && filePaths.historyDocs.length > 0) {
1369
+ const historyLines = filePaths.historyDocs.map(
1370
+ (doc) => `- 本轮重试结果 (retry=${doc.loop}): ${doc.path}`
1371
+ );
1372
+ parts.push(
1373
+ `## 历史执行文档路径\n\n以下为本轮大循环中之前重试的结果文件路径,请自行读取参考:\n${historyLines.join('\n')}`
1374
+ );
1375
+ }
1376
+ parts.push(
1377
+ '本次任务未匹配到专用 SKILL,请直接基于上述任务描述执行任务。',
1378
+ '执行完成后,请将结果写入上述"结果文件输出路径"。',
1379
+ '结果文件需包含 `## 执行状态` 字段(值为 `成功` 或 `失败`),用于判断执行结果。'
1380
+ );
1381
+ }
1382
+
1383
+ // ── MCP 工具引导:提醒 AI 主动使用 MCP Gateway 提供的工具 ──
1384
+ if (this.#mcpToolGuide) {
1385
+ const toolGuide = this.#mcpToolGuide.buildToolGuide();
1386
+ if (toolGuide) {
1387
+ parts.push(toolGuide);
1388
+ }
1389
+ }
1390
+
1391
+ return parts.join('\n\n');
1392
+ }
1393
+
1394
+ /**
1395
+ * _buildSummaryPrompt — 构建经验总结专用 prompt。
1396
+ *
1397
+ * 此 prompt 在 checkResult 成功后,通过 sendAndWaitMessage 向同一 Session
1398
+ * 追加发送,要求 AI 基于已有的执行上下文生成 Summary .md 经验总结文件。
1399
+ *
1400
+ * 与初始执行 prompt 分离的原因:
1401
+ * - 确保经验总结仅在执行成功后触发
1402
+ * - AI 在总结时已有完整的执行上下文(同一 Session),总结质量更高
1403
+ * - 初始 prompt 更简洁,AI 专注执行任务
1404
+ *
1405
+ * @param {string} summaryFilePath - 经验文件输出路径
1406
+ * @param {string|null} skillDir - SKILL 目录路径(null 表示无 SKILL 模式)
1407
+ * @returns {string} 拼接后的经验总结 prompt 文本
1408
+ * @private
1409
+ */
1410
+ _buildSummaryPrompt(summaryFilePath, skillDir) {
1411
+ const parts = [
1412
+ '## 任务已执行成功,请进行经验总结',
1413
+ '',
1414
+ '以上任务已执行成功。请基于本次执行过程中的实际情况,评估是否产生了**有价值的、可复用的经验总结**。',
1415
+ '',
1416
+ '## 判断标准',
1417
+ '- 本次执行中发现了关键的踩坑点、解决方案、最佳实践或可复用的模式',
1418
+ '- 这些经验对未来类似的任务有明确的参考价值',
1419
+ '- 不是简单的执行流水账或重复的通用知识',
1420
+ '',
1421
+ '## 处理方式',
1422
+ '如果存在有价值的经验,请将经验总结写入以下路径:',
1423
+ `经验文件输出路径:${summaryFilePath}`,
1424
+ '',
1425
+ '经验文件应包含:关键发现、踩坑记录、解决方案、可复用建议等。',
1426
+ '',
1427
+ '## 经验分类(必须在经验文件末尾输出)',
1428
+ '在经验文件末尾附上以下经验分类块,用于标记本次经验的归属类型:',
1429
+ '```',
1430
+ '## 经验分类',
1431
+ '- 沉淀类型: skill优化 | 知识库 | 无'
1432
+ ];
1433
+
1434
+ if (skillDir) {
1435
+ parts.push(
1436
+ `- 适用SKILL: ${skillDir}`,
1437
+ '- 优化建议: <对当前SKILL的具体修改/新增点,skill优化类必填>'
1438
+ );
1439
+ } else {
1440
+ parts.push(
1441
+ '- 适用SKILL: <无,本次未匹配到SKILL>',
1442
+ '- 优化建议: <skill优化类必填,但本次无SKILL,通常填"无">'
1443
+ );
1444
+ }
1445
+
1446
+ parts.push(
1447
+ '```',
1448
+ '',
1449
+ '字段说明:',
1450
+ '- 沉淀类型:三选一。'
1451
+ );
1452
+
1453
+ if (skillDir) {
1454
+ parts.push(
1455
+ ' - skill优化 = 当前SKILL有可改进之处(检查项缺失/规则错误/可复用模式未被覆盖);',
1456
+ ' - 知识库 = 通用领域经验,与具体SKILL逻辑无关;'
1457
+ );
1458
+ } else {
1459
+ parts.push(
1460
+ ' - skill优化 = 需为某个SKILL沉淀优化建议;',
1461
+ ' - 知识库 = 通用领域经验,与具体SKILL逻辑无关;'
1462
+ );
1463
+ }
1464
+
1465
+ parts.push(
1466
+ ' - 无 = 无有价值经验,此时不生成经验文件。'
1467
+ );
1468
+
1469
+ if (skillDir) {
1470
+ parts.push(
1471
+ '- 适用SKILL:仅 skill优化 类必填,填上面注入的当前 step 调用 SKILL 的路径,原样保留不要改动。',
1472
+ '- 优化建议:仅 skill优化 类必填,描述对当前SKILL的具体修改/新增点(如"新增 XX 检查项"、"修正 YY 规则")。'
1473
+ );
1474
+ } else {
1475
+ parts.push(
1476
+ '- 适用SKILL:本次未匹配到 SKILL,此处标记"无"。若沉淀类型为 skill优化,请在优化建议中注明建议沉淀到哪个 SKILL(如期望新增或修改的 SKILL 名称)。',
1477
+ '- 优化建议:仅 skill优化 类必填,描述建议新建或修改的 SKILL 的具体点。'
1478
+ );
1479
+ }
1480
+
1481
+ parts.push(
1482
+ '',
1483
+ '如果没有有价值的经验可沉淀(如任务过于简单、未发现新的经验),则**不需要生成经验文件**。',
1484
+ '请勿创建空文件或无实质内容的经验文件。',
1485
+ '',
1486
+ '请现在进行经验总结。'
1487
+ );
1488
+
1489
+ return parts.join('\n');
1490
+ }
1491
+
1492
+ /**
1493
+ * _summarizeAndPersist — 后台异步执行经验总结 + 知识持久化。
1494
+ *
1495
+ * 此方法为 fire-and-forget 入口,由 executeStart 在成功后以 `.catch()` 方式调用,
1496
+ * **不阻塞 executeStart 返回**,不影响 Orchestrator 步骤流转。
1497
+ *
1498
+ * 内部流程:
1499
+ * 1. _summarizeExperience → 向指定 Session 追加经验总结 prompt,等待 AI 回复 + 文件生成
1500
+ * 2. persistKnowledge → 读取 Summary .md,持久化到步骤记录 + 知识沉淀系统
1501
+ *
1502
+ * 所有异常在方法内部 catch,仅记录日志,不向上抛出。
1503
+ *
1504
+ * @param {string} summaryFilePath - 经验文件输出路径
1505
+ * @param {string|null} skillDir - SKILL 目录路径(null 表示无 SKILL 模式)
1506
+ * @param {string} sessionId - 执行任务的 Session ID(显式传入,避免实例复用后被覆盖)
1507
+ * @returns {Promise<void>}
1508
+ * @private
1509
+ */
1510
+ async _summarizeAndPersist(summaryFilePath, skillDir, sessionId) {
1511
+ // 终止已请求 → 不再向 session 追加经验总结 prompt(避免终止后又触发新的 AI 生成)
1512
+ if (this.#aborted) {
1513
+ this._log('info', '_summarizeAndPersist: 已终止,跳过后台经验总结');
1514
+ return;
1515
+ }
1516
+ try {
1517
+ const summarized = await this._summarizeExperience(summaryFilePath, skillDir, sessionId);
1518
+ if (!summarized) {
1519
+ this._log('warn', '后台经验总结未生成(超时/失败),跳过知识持久化');
1520
+ return;
1521
+ }
1522
+ await this.persistKnowledge(summaryFilePath);
1523
+ this._log('info', '✅ 后台经验总结完成,知识已持久化');
1524
+ } catch (err) {
1525
+ this._log('warn', `_summarizeAndPersist 异常: ${err.message}`);
1526
+ }
1527
+ }
1528
+
1529
+ /**
1530
+ * _summarizeExperience — 向指定 Session 追加经验总结 prompt 并等待文件生成。
1531
+ *
1532
+ * 通过 CLI 的 sendAndWaitMessage 向指定 Session 发送经验总结 prompt,
1533
+ * 同步等待 AI 回复完成,然后验证 Summary .md 文件是否已生成。
1534
+ *
1535
+ * 降级策略(不影响步骤成功状态):
1536
+ * - 无效 sessionId → 返回 false
1537
+ * - sendAndWaitMessage 失败 → 返回 false
1538
+ * - AI 回复完成但未生成 Summary .md → 等待超时后返回 false
1539
+ * - 任何异常 → 返回 false
1540
+ *
1541
+ * @param {string} summaryFilePath - 经验文件输出路径
1542
+ * @param {string|null} skillDir - SKILL 目录路径(null 表示无 SKILL 模式)
1543
+ * @param {string} sessionId - 执行任务的 Session ID
1544
+ * @returns {Promise<boolean>} 经验总结是否成功生成 Summary .md
1545
+ * @private
1546
+ */
1547
+ async _summarizeExperience(summaryFilePath, skillDir, sessionId) {
1548
+ if (!summaryFilePath) {
1549
+ this._log('warn', '_summarizeExperience: summaryFilePath 为空');
1550
+ return false;
1551
+ }
1552
+
1553
+ if (!sessionId) {
1554
+ this._log('warn', '_summarizeExperience: sessionId 为空,无法追加经验总结');
1555
+ return false;
1556
+ }
1557
+
1558
+ this._log('info', `经验总结开始 — session: ${sessionId}`);
1559
+
1560
+ try {
1561
+ // 终止检查:总结开始前已终止 → 跳过(不再向 session 发送新 prompt)
1562
+ if (this.#aborted) {
1563
+ this._log('info', '_summarizeExperience: 已终止,跳过经验总结');
1564
+ return false;
1565
+ }
1566
+
1567
+ // 构建经验总结 prompt
1568
+ const summaryPrompt = this._buildSummaryPrompt(summaryFilePath, skillDir);
1569
+
1570
+ // 直接调用 CLI 的 sendAndWaitMessage,显式传入 sessionId
1571
+ // (不经过 this.sendAndWaitMessage 包装,避免读取 this.#sessionId 被实例复用覆盖)
1572
+ if (typeof this.#cli.sendAndWaitMessage !== 'function') {
1573
+ this._log('warn', '_summarizeExperience: CLI 不支持 sendAndWaitMessage 方法');
1574
+ return false;
1575
+ }
1576
+
1577
+ const result = await this.#cli.sendAndWaitMessage(sessionId, summaryPrompt);
1578
+
1579
+ // 等待 AI 回复期间收到终止请求 → 不再等待文件生成(session 已被远程中止)
1580
+ if (this.#aborted) {
1581
+ this._log('info', '_summarizeExperience: 等待回复期间被终止,放弃经验总结');
1582
+ return false;
1583
+ }
1584
+
1585
+ if (!result || !result.success) {
1586
+ this._log('warn', '_summarizeExperience: sendAndWaitMessage 返回失败,经验总结未完成');
1587
+ return false;
1588
+ }
1589
+
1590
+ this._log('info',
1591
+ `_summarizeExperience: AI 回复完成,content 长度 ${result.content?.length || 0},` +
1592
+ `等待 Summary 文件生成…`
1593
+ );
1594
+
1595
+ // AI 回复完成,但文件写入可能有延迟,轮询等待文件出现
1596
+ const fileReady = await this._waitForFile(summaryFilePath, SUMMARY_TIMEOUT_MS);
1597
+ if (!fileReady) {
1598
+ this._log('warn',
1599
+ `_summarizeExperience: 等待 Summary 文件超时(${SUMMARY_TIMEOUT_MS / 1000}s)— ${summaryFilePath}`
1600
+ );
1601
+ return false;
1602
+ }
1603
+
1604
+ this._log('info', `经验总结完成 — Summary 文件已生成: ${summaryFilePath}`);
1605
+ return true;
1606
+ } catch (err) {
1607
+ this._log('error', `_summarizeExperience 异常: ${err.message}`);
1608
+ return false;
1609
+ }
1610
+ }
1611
+
1612
+ /**
1613
+ * _waitForFile — 轮询等待文件出现。
1614
+ *
1615
+ * AI 回复完成后,文件写入可能有延迟(如工具调用尚未 flush),
1616
+ * 此方法按固定间隔轮询文件是否存在,直到超时。
1617
+ *
1618
+ * @param {string} filePath - 等待的文件路径
1619
+ * @param {number} timeoutMs - 超时时间(ms)
1620
+ * @returns {Promise<boolean>} 文件是否在超时前出现
1621
+ * @private
1622
+ */
1623
+ async _waitForFile(filePath, timeoutMs) {
1624
+ const deadline = Date.now() + timeoutMs;
1625
+ const interval = 3000; // 3s 轮询间隔
1626
+
1627
+ while (Date.now() < deadline) {
1628
+ if (this.#aborted) return false;
1629
+
1630
+ try {
1631
+ await fs.access(filePath);
1632
+ return true;
1633
+ } catch {
1634
+ // 文件尚未出现,继续等待
1635
+ }
1636
+
1637
+ await this._sleep(interval);
1638
+ }
1639
+
1640
+ return false;
1641
+ }
1642
+
1643
+ /**
1644
+ * 收集当前大循环内的历史结果文档路径,供 _buildPrompt 使用。
1645
+ *
1646
+ * 收集范围:仅当前大循环轮次内,本次执行之前的重试结果(retry < loopCount)
1647
+ * 文件名: stepId{n}_loop{L}_result_{R}.md(R < loopCount)
1648
+ *
1649
+ * 注意:不再收集上一轮大循环的结果,且只收集文件路径不读取内容。
1650
+ *
1651
+ * 静默失败:文件不存在时跳过,不影响主流程。
1652
+ *
1653
+ * @param {number} loopCount - 当前步骤内重试次数(收集 R < loopCount 的文件)
1654
+ * @returns {Promise<Array<{type: string, loop: number, path: string}>>}
1655
+ * @private
1656
+ */
1657
+ async _collectHistoryDocs(loopCount) {
1658
+ const docs = [];
1659
+ const prefix = `stepId${this.#stepId}`;
1660
+
1661
+ // ── 收集当前大循环内的重试历史(仅路径,不读取内容) ──
1662
+ for (let n = 0; n < loopCount; n++) {
1663
+ const resultPath = path.join(
1664
+ this.#taskDir,
1665
+ `${prefix}_loop${this.#bigLoopIndex}_result_${n}.md`
1666
+ );
1667
+ try {
1668
+ await fs.access(resultPath);
1669
+ docs.push({ type: 'result', loop: n, path: resultPath });
1670
+ } catch {
1671
+ // 文件不存在,跳过
1672
+ }
1673
+ }
1674
+
1675
+ if (docs.length > 0) {
1676
+ this._log('info', `_collectHistoryDocs: 收集到 ${docs.length} 份历史结果文档路径`);
1677
+ }
1678
+
1679
+ return docs;
1680
+ }
1681
+
1682
+ /**
1683
+ * 轮询 opencode Session 状态,直到完成或超时。
1684
+ *
1685
+ * @param {string} sessionId
1686
+ * @returns {Promise<boolean>} 是否完成
1687
+ * @private
1688
+ */
1689
+ async _pollSession(sessionId) {
1690
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
1691
+
1692
+ while (Date.now() < deadline) {
1693
+ if (this.#aborted) return false;
1694
+
1695
+ await this._sleep(this.#pollIntervalMs);
1696
+
1697
+ try {
1698
+ const { status } = await this.#cli.checkSessionStatus(sessionId);
1699
+ if (status === 'completed') {
1700
+ return true;
1701
+ }
1702
+ if (status === 'unknown') {
1703
+ this._log('debug', `Session ${sessionId} 状态未知,继续等待…`);
1704
+ }
1705
+ } catch (err) {
1706
+ this._log('warn', `轮询 Session 状态失败: ${err.message}`);
1707
+ }
1708
+ }
1709
+
1710
+ return false;
1711
+ }
1712
+
1713
+ /**
1714
+ * 若处于暂停状态则等待,直到被 resume。
1715
+ * @private
1716
+ */
1717
+ async _waitIfPaused() {
1718
+ while (this.#paused && !this.#aborted) {
1719
+ await this._sleep(500);
1720
+ }
1721
+ }
1722
+
1723
+ /**
1724
+ * Promise 版 sleep。
1725
+ * @param {number} ms
1726
+ * @returns {Promise<void>}
1727
+ * @private
1728
+ */
1729
+ _sleep(ms) {
1730
+ return new Promise((resolve) => setTimeout(resolve, ms));
1731
+ }
1732
+
1733
+ /**
1734
+ * 统一日志输出。
1735
+ * @param {'info'|'warn'|'error'|'debug'} level
1736
+ * @param {string} message
1737
+ * @private
1738
+ */
1739
+ _log(level, message) {
1740
+ const tag = `FlexRunner:${this.#taskId || 'uninit'}`;
1741
+ const logger = createLogger(tag);
1742
+ switch (level) {
1743
+ case 'error':
1744
+ logger.error(`❌ ${message}`);
1745
+ break;
1746
+ case 'warn':
1747
+ logger.warn(`⚠ ${message}`);
1748
+ break;
1749
+ case 'debug':
1750
+ logger.debug(`🔍 ${message}`);
1751
+ break;
1752
+ default:
1753
+ logger.info(`ℹ ${message}`);
1754
+ }
1755
+ }
1756
+ }
1757
+
1758
+ export { FlexRunner, ControlType, StepStatus };
1759
+ export default FlexRunner;