lantern-harness 0.1.45 → 0.2.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 (274) hide show
  1. package/CHANGELOG.md +242 -0
  2. package/README.md +25 -8
  3. package/builtin/case-backup-contract.mjs +27 -0
  4. package/builtin/case-workflow-contract.mjs +158 -0
  5. package/builtin/session/lh-fs.mjs +93 -4
  6. package/builtin/session/lh-nav-groups.mjs +36 -1
  7. package/builtin/session/mcp-client.mjs +7 -3
  8. package/builtin/session/session-runs.mjs +5 -1
  9. package/builtin/session/skill-validation.mjs +72 -0
  10. package/builtin/session/space-layout.mjs +8 -1
  11. package/builtin/session/space-skills.mjs +758 -0
  12. package/cli/data-root.mjs +21 -4
  13. package/cli/lantern.mjs +26 -1
  14. package/cli/mcp-server.mjs +3733 -0
  15. package/cli/server.mjs +10 -2
  16. package/config/app.defaults.json +4 -2
  17. package/dist/500.html +14 -6
  18. package/dist/_astro/Base.BQf1tZMl.css +1 -0
  19. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js +2 -0
  20. package/dist/_astro/BusinessMapBoard.CYxHcku_.js +5 -0
  21. package/dist/_astro/CaseExecBoard.CK9aGPmH.js +1 -0
  22. package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
  23. package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
  24. package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
  25. package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
  26. package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
  27. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  28. package/dist/_astro/DashboardBoard.qgc1s7pG.js +5 -0
  29. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  30. package/dist/_astro/DefectSubmitEntry.JI85N1-i.js +2 -0
  31. package/dist/_astro/DocsFileBrowser.z5JZ74cy.js +1 -0
  32. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.Dg765uHW.js} +1 -1
  33. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  34. package/dist/_astro/KnowledgeLibrary.mkShtVun.js +1 -0
  35. package/dist/_astro/LifeKrTasksBoard.DpAwQffE.js +1 -0
  36. package/dist/_astro/LifeKrTodosBoard.BIjPiZ8H.js +1 -0
  37. package/dist/_astro/LifeObjectivesBoard.DYwLHPEG.js +1 -0
  38. package/dist/_astro/LifePlanTypeSelect.CYaziESp.js +1 -0
  39. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.DIxoWBDA.js} +3 -3
  40. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.DuFQsMEx.js} +2 -2
  41. package/dist/_astro/LifeStagesBoard.DtOri9EW.js +1 -0
  42. package/dist/_astro/LifeYearCycleSelect.ByJ9-PGg.js +1 -0
  43. package/dist/_astro/LifeYearPlansBoard.BQN07wcv.js +1 -0
  44. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  45. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  46. package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
  47. package/dist/_astro/PluginsPage.B1VeDtLx.js +18 -0
  48. package/dist/_astro/PmBugsBoard.Ddl3kqqt.js +1 -0
  49. package/dist/_astro/PmIterationsBoard.BJN7disI.js +1 -0
  50. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.D78gWhqk.js} +1 -1
  51. package/dist/_astro/PmProjectsBoard.Bf8VB3t6.js +1 -0
  52. package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
  53. package/dist/_astro/PmRequirementsBoard.DarfGIrL.js +1 -0
  54. package/dist/_astro/PmShared.TOjBbtV8.js +1 -0
  55. package/dist/_astro/ReportsPage.BXGduuY3.js +1 -0
  56. package/dist/_astro/ReqAnalysisBoard.WLtIfBg8.js +39 -0
  57. package/dist/_astro/RequirementBreakdownLibrary.DMoeTeqX.js +2 -0
  58. package/dist/_astro/RequirementsLibrary.Iv7zOqWe.js +1 -0
  59. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  60. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  61. package/dist/_astro/SettingsDialog.BvDU9EU6.js +1 -0
  62. package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
  63. package/dist/_astro/SpaceSwitcher.D9bBNQBZ.js +7 -0
  64. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.DHj25OKN.js} +1 -1
  65. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  66. package/dist/_astro/TasksBoard.CXmGdylV.js +1 -0
  67. package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
  68. package/dist/_astro/TestReportsLibrary.BBC1TYgP.js +1 -0
  69. package/dist/_astro/TestStatsBoard.VXjP4hu6.js +1 -0
  70. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  71. package/dist/_astro/TodosBoard.-yKgp06M.js +1 -0
  72. package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
  73. package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
  74. package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
  75. package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
  76. package/dist/_astro/app-config.BSO5r82v.js +1 -0
  77. package/dist/_astro/app-version.CkDFkv4s.js +1 -0
  78. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.C4DJiRJs.js} +1 -1
  79. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  80. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  81. package/dist/_astro/case-fields.C03NY3zC.js +148 -0
  82. package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
  83. package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
  84. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.BodP2jKm.js} +2 -2
  85. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.CC2eXegU.js} +2 -2
  86. package/dist/_astro/case-types.BjF1BivA.js +1 -0
  87. package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
  88. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  89. package/dist/_astro/defect-workbench.DBmohR-y.js +6 -0
  90. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  91. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  92. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.CMMErx63.js} +1 -1
  93. package/dist/_astro/i18n.CEWjL5GX.js +7 -0
  94. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  95. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  96. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BoyV6R2A.js} +1 -1
  97. package/dist/_astro/plugins.ChGmBEkF.js +1 -0
  98. package/dist/_astro/project-docs.BRgNjXhG.js +1 -0
  99. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  100. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  101. package/dist/_astro/req-analysis.BLvcktvQ.js +31 -0
  102. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  103. package/dist/_astro/{settings.38J2uD5M.js → settings.BojKNwUC.js} +2 -2
  104. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  105. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.B28rzu8J.js} +1 -1
  106. package/dist/_astro/story-review.dEBWTeOW.js +7 -0
  107. package/dist/_astro/test-points.BuNgdNcU.js +8 -0
  108. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  109. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  110. package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
  111. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.CWc5cQ2q.js} +1 -1
  112. package/dist/business-map/index.html +988 -0
  113. package/dist/case-exec/index.html +15 -7
  114. package/dist/{prompts → case-execution}/index.html +17 -9
  115. package/dist/cases/api/index.html +988 -0
  116. package/dist/cases/automation/index.html +988 -0
  117. package/dist/cases/functional/index.html +988 -0
  118. package/dist/cases/generate/index.html +14 -6
  119. package/dist/cases/index.html +1 -1
  120. package/dist/cases/library/index.html +1 -980
  121. package/dist/cases/other/index.html +988 -0
  122. package/dist/cases/performance/index.html +988 -0
  123. package/dist/dashboard/index.html +15 -7
  124. package/dist/defect-rules/index.html +695 -0
  125. package/dist/defect-submit/index.html +695 -0
  126. package/dist/defect-submit/templates/index.html +695 -0
  127. package/dist/docs/changelog/index.html +289 -52
  128. package/dist/docs/install/index.html +50 -12
  129. package/dist/docs/manual/index.html +230 -82
  130. package/dist/knowledge/index.html +15 -7
  131. package/dist/life/kr-tasks/index.html +15 -7
  132. package/dist/life/kr-todos/index.html +15 -7
  133. package/dist/life/objectives/index.html +15 -7
  134. package/dist/life/reviews/index.html +15 -7
  135. package/dist/life/stages/index.html +15 -7
  136. package/dist/life/year-plans/index.html +15 -7
  137. package/dist/plugins/index.html +15 -7
  138. package/dist/pm/bugs/index.html +15 -7
  139. package/dist/pm/iterations/index.html +15 -7
  140. package/dist/pm/projects/detail/index.html +15 -7
  141. package/dist/pm/projects/index.html +15 -7
  142. package/dist/pm/requirements/index.html +15 -7
  143. package/dist/reports/index.html +15 -7
  144. package/dist/requirement-analysis/index.html +15 -7
  145. package/dist/requirement-breakdowns/index.html +988 -0
  146. package/dist/requirements/index.html +15 -7
  147. package/dist/tasks/index.html +15 -7
  148. package/dist/templates/index.html +15 -7
  149. package/dist/test-automation/index.html +15 -7
  150. package/dist/test-automation/projects/index.html +15 -7
  151. package/dist/test-reports/index.html +15 -7
  152. package/dist/test-stats/index.html +15 -7
  153. package/dist/todos/index.html +15 -7
  154. package/dist/workbench/index.html +14 -6
  155. package/docs/Codex-MCP/351/233/206/346/210/220.md +340 -0
  156. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  157. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/206/345/210/253/351/207/215/346/236/204/346/226/271/346/241/210.md +88 -0
  158. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +28 -3
  159. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  160. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +65 -17
  161. package/docs//346/217/222/344/273/266/344/273/223/345/272/223/344/270/216/346/212/200/350/203/275/346/225/264/345/220/210/346/226/271/346/241/210.md +187 -0
  162. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +219 -74
  163. package/lh-plugins/business-map/assistant.mjs +958 -0
  164. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  165. package/lh-plugins/business-map/jobs.mjs +749 -0
  166. package/lh-plugins/business-map/login.mjs +295 -0
  167. package/lh-plugins/business-map/sources.mjs +1014 -0
  168. package/lh-plugins/case-automation/service.mjs +921 -0
  169. package/lh-plugins/case-automation/store.mjs +231 -0
  170. package/lh-plugins/case-automation/tables.mjs +115 -0
  171. package/lh-plugins/case-automation-prompt.mjs +57 -0
  172. package/lh-plugins/case-execution/assets.mjs +180 -0
  173. package/lh-plugins/case-execution/files.mjs +829 -0
  174. package/lh-plugins/case-execution/plans.mjs +318 -0
  175. package/lh-plugins/case-execution/service.mjs +1026 -0
  176. package/lh-plugins/case-execution-prompt.mjs +36 -0
  177. package/lh-plugins/lh-business-map.mjs +2431 -0
  178. package/lh-plugins/lh-case-automation.mjs +169 -0
  179. package/lh-plugins/lh-case-design.mjs +456 -0
  180. package/lh-plugins/lh-case-execution.mjs +356 -0
  181. package/lh-plugins/lh-case-review.mjs +29 -11
  182. package/lh-plugins/lh-config.mjs +13 -0
  183. package/lh-plugins/lh-defect-submit.mjs +989 -0
  184. package/lh-plugins/lh-project-docs.mjs +55 -140
  185. package/lh-plugins/lh-reports.mjs +29 -57
  186. package/lh-plugins/lh-req-analysis.mjs +32 -3
  187. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  188. package/lh-plugins/lh-uiauto.mjs +625 -24
  189. package/lh-plugins/plugin-prompts.mjs +20 -15
  190. package/lh-plugins/req-analysis-revision.mjs +24 -0
  191. package/lh-plugins/test-points-prompt.mjs +2 -3
  192. package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
  193. package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
  194. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  195. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  196. package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
  197. package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
  198. package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
  199. package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
  200. package/lh-plugins/uiauto-explorer/runner.mjs +80 -5
  201. package/lh-plugins/uiauto-explorer/sessions.mjs +334 -18
  202. package/lh-plugins/uiauto-node.mjs +102 -11
  203. package/lh-plugins/uiauto-prompt.mjs +20 -15
  204. package/lh-plugins/uiauto-sso.mjs +407 -0
  205. package/package.json +5 -2
  206. package/skills/case-automation-bridge/SKILL.md +27 -0
  207. package/skills/case-execution/SKILL.md +41 -0
  208. package/skills/lantern-defect-submit/SKILL.md +15 -0
  209. package/skills/lantern-workflow/SKILL.md +95 -0
  210. package/skills/office/SKILL.md +26 -0
  211. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  212. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  213. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  214. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  215. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  216. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  217. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  218. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  219. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  220. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  221. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  222. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  223. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  224. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  225. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  226. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  227. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  228. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  229. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  230. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  231. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  232. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  233. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  234. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  235. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  236. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  237. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  238. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  239. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  240. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  241. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  242. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  243. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  244. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  245. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  246. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  247. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  248. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  249. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  250. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  251. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  252. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  253. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  254. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  255. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  256. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  257. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  258. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  259. package/dist/_astro/case-fields.CmePqYfh.js +0 -148
  260. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  261. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  262. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  263. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  264. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  265. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  266. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  267. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  268. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  269. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  270. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  271. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  272. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  273. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  274. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -2,7 +2,8 @@
2
2
  * 生成会话:浏览器子进程管理 + 会话落盘 + 试跑 / 写盘。
3
3
  *
4
4
  * 会话数据放在本机缓存目录 `<空间>/.lantern/local/uiauto/sessions/<id>.json`,
5
- * 截图在旁边 `<id>/shots/`。
5
+ * 截图在旁边 `<id>/shots/`。未绑定工作台编排的会话超过 SESSION_TTL_MS(默认 7 天)
6
+ * 会由 cleanupStaleSessions 清掉;已写 chatSessionId 的跳过。
6
7
  * 试跑草稿写进项目的 `.lantern-ai/<会话>/`(目录自带 .gitignore),失败保留现场,
7
8
  * 可打开 / 重跑 / 看 trace;最终落盘由用户点击确认,写入后还能按项目配置验收。
8
9
  */
@@ -21,10 +22,15 @@ import { mergeGeneratedFile } from './merge.mjs';
21
22
  import { normalizePlan } from './plan.mjs';
22
23
 
23
24
  const RUNNER_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'runner.mjs');
24
- const MAX_VERIFY_LOG = 64 * 1024;
25
+ const MAX_VERIFY_LOG = 256 * 1024;
25
26
  const DEFAULT_VERIFY_TIMEOUT = 180000;
26
27
  /** 草稿保留天数:超过就没人再看了,留着只是占目录 */
27
28
  const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
29
+ /**
30
+ * 生成会话本机缓存保留多久。
31
+ * 未绑定工作台编排(无 chatSessionId)的会话过期会清掉;已绑定的长留。
32
+ */
33
+ export const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
28
34
  const MAX_LEDGER_FILE_BYTES = 400 * 1024;
29
35
 
30
36
  /** Playwright 的 line reporter 会写光标控制符,日志里留着很难看 */
@@ -144,6 +150,7 @@ export function saveGeneratedSession(baseDir, rawPatch = {}) {
144
150
  storageState: existing.storageState,
145
151
  source: existing.source,
146
152
  target: existing.target,
153
+ automationCaseId: existing.automationCaseId,
147
154
  })
148
155
  : null;
149
156
  const record = {
@@ -187,13 +194,16 @@ export function listGeneratedSessions(baseDir, projectId = '') {
187
194
  if (record.status === 'exploring' && !RUNNING.has(record.id)) {
188
195
  record.status = 'draft';
189
196
  }
197
+ // 规划阶段步骤在 plan;探索后才有 ir.steps。列表只回摘要,步数两边都要认。
198
+ const planLen = Array.isArray(record.plan) ? record.plan.length : 0;
199
+ const irLen = Array.isArray(record.ir?.steps) ? record.ir.steps.length : 0;
190
200
  items.push({
191
201
  id: record.id,
192
202
  projectId: record.projectId || '',
193
203
  title: record.title || '未命名流程',
194
204
  target: record.target === 'python' ? 'python' : 'ts',
195
205
  status: record.status || 'draft',
196
- stepCount: Array.isArray(record.ir?.steps) ? record.ir.steps.length : 0,
206
+ stepCount: irLen || planLen,
197
207
  createdAt: record.createdAt || '',
198
208
  updatedAt: record.updatedAt || '',
199
209
  });
@@ -201,15 +211,124 @@ export function listGeneratedSessions(baseDir, projectId = '') {
201
211
  return items.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)).slice(0, 50);
202
212
  }
203
213
 
214
+ /** 按自动化用例 ID 查找已绑定会话,重复评估时继续更新同一份 Plan。 */
215
+ export function findGeneratedSessionByAutomationCaseId(baseDir, automationCaseId) {
216
+ const id = String(automationCaseId || '').trim();
217
+ if (!id) return null;
218
+ const dir = sessionsDir(baseDir);
219
+ if (!fs.existsSync(dir)) return null;
220
+ for (const name of fs.readdirSync(dir)) {
221
+ if (!name.endsWith('.json')) continue;
222
+ const record = readJson(path.join(dir, name));
223
+ if (record?.automationCaseId === id) return record;
224
+ }
225
+ return null;
226
+ }
227
+
228
+ /** 删掉生成会话 JSON 与旁边的 shots 目录;不负责停浏览器(调用方先停) */
204
229
  export function deleteGeneratedSession(baseDir, id) {
205
230
  if (!id) return false;
206
231
  const file = sessionFilePath(baseDir, id);
207
- if (!fs.existsSync(file)) return false;
208
- fs.rmSync(file, { force: true });
209
- fs.rmSync(path.join(sessionsDir(baseDir), id), { recursive: true, force: true });
232
+ const shotRoot = path.join(sessionsDir(baseDir), id);
233
+ const hadFile = fs.existsSync(file);
234
+ const hadDir = fs.existsSync(shotRoot);
235
+ if (!hadFile && !hadDir) return false;
236
+ if (hadFile) fs.rmSync(file, { force: true });
237
+ if (hadDir) fs.rmSync(shotRoot, { recursive: true, force: true });
210
238
  return true;
211
239
  }
212
240
 
241
+ function sessionAgeMs(record, filePath, now) {
242
+ const stamp = Date.parse(String(record?.updatedAt || record?.createdAt || ''));
243
+ if (Number.isFinite(stamp)) return now - stamp;
244
+ try {
245
+ return now - fs.statSync(filePath).mtimeMs;
246
+ } catch {
247
+ // 读不到时间就先留着,别误删
248
+ return 0;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * 清掉过期的生成会话及其截图。
254
+ *
255
+ * - 按 `updatedAt`(没有就用 `createdAt` / 文件 mtime)判断是否超过 SESSION_TTL_MS
256
+ * - 正在跑浏览器或调试的会话跳过
257
+ * - 没有对应 JSON 的孤儿 shots 目录一并清
258
+ * - 返回删掉的会话 id,方便自测与日志
259
+ */
260
+ export function cleanupStaleSessions(baseDir, opts = {}) {
261
+ const dir = sessionsDir(baseDir);
262
+ if (!fs.existsSync(dir)) return { removed: [] };
263
+ const ttl = Number.isFinite(opts.ttlMs) ? Number(opts.ttlMs) : SESSION_TTL_MS;
264
+ const now = Number.isFinite(opts.now) ? Number(opts.now) : Date.now();
265
+ const removed = [];
266
+
267
+ let names = [];
268
+ try {
269
+ names = fs.readdirSync(dir);
270
+ } catch {
271
+ return { removed };
272
+ }
273
+
274
+ const jsonIds = new Set();
275
+ for (const name of names) {
276
+ if (!name.endsWith('.json')) continue;
277
+ const id = name.slice(0, -'.json'.length);
278
+ jsonIds.add(id);
279
+ const file = path.join(dir, name);
280
+ const record = readJson(file);
281
+
282
+ // 坏文件 / 空壳:按文件 mtime 过期就清
283
+ if (!record || !record.id) {
284
+ try {
285
+ if (now - fs.statSync(file).mtimeMs > ttl) {
286
+ fs.rmSync(file, { force: true });
287
+ fs.rmSync(path.join(dir, id), { recursive: true, force: true });
288
+ removed.push(id);
289
+ }
290
+ } catch {
291
+ // 并发删除略过
292
+ }
293
+ continue;
294
+ }
295
+
296
+ // 还在探索 / 调试的别动,哪怕时间戳偏旧
297
+ if (RUNNING.has(record.id) || hasDebugSession(record.id)) continue;
298
+ // 已关联工作台编排会话:跳过 TTL,避免侧栏点开域状态已空
299
+ if (String(record.chatSessionId || '').trim()) continue;
300
+ // 功能用例自动化关联必须长期可恢复,直到用户显式删除关联或会话。
301
+ if (record.keepAlive === true || String(record.automationCaseId || '').trim()) continue;
302
+ if (sessionAgeMs(record, file, now) <= ttl) continue;
303
+
304
+ stopExplorer(record.id);
305
+ stopDebugSession(record.id);
306
+ if (deleteGeneratedSession(baseDir, record.id)) removed.push(record.id);
307
+ }
308
+
309
+ // 孤儿截图目录:JSON 已经没了,shots 还挂着
310
+ for (const name of names) {
311
+ if (name.endsWith('.json')) continue;
312
+ const abs = path.join(dir, name);
313
+ try {
314
+ if (!fs.statSync(abs).isDirectory()) continue;
315
+ } catch {
316
+ continue;
317
+ }
318
+ if (jsonIds.has(name) || RUNNING.has(name) || hasDebugSession(name)) continue;
319
+ try {
320
+ if (now - fs.statSync(abs).mtimeMs > ttl) {
321
+ fs.rmSync(abs, { recursive: true, force: true });
322
+ removed.push(name);
323
+ }
324
+ } catch {
325
+ // 并发删除略过
326
+ }
327
+ }
328
+
329
+ return { removed };
330
+ }
331
+
213
332
  function respondError(entry, id, message) {
214
333
  const pending = entry.pending.get(id);
215
334
  if (!pending) return;
@@ -219,7 +338,15 @@ function respondError(entry, id, message) {
219
338
  }
220
339
 
221
340
  /** 拉起浏览器子进程,等到 ready 再返回 */
222
- export function startExplorer({ baseDir, project, sessionId, baseURL, headed, storageState }) {
341
+ export function startExplorer({
342
+ baseDir,
343
+ project,
344
+ sessionId,
345
+ baseURL,
346
+ headed,
347
+ storageState,
348
+ allowedOrigins,
349
+ }) {
223
350
  const existing = RUNNING.get(sessionId);
224
351
  if (existing) return Promise.resolve(existing);
225
352
 
@@ -232,6 +359,7 @@ export function startExplorer({ baseDir, project, sessionId, baseURL, headed, st
232
359
  baseURL: baseURL || '',
233
360
  headed: Boolean(headed),
234
361
  storageState: storageState || '',
362
+ ...(allowedOrigins ? { allowedOrigins } : {}),
235
363
  };
236
364
 
237
365
  const child = spawn(process.execPath, [RUNNER_PATH, JSON.stringify(payload)], {
@@ -361,18 +489,29 @@ export function stopExplorer(sessionId) {
361
489
  const entry = RUNNING.get(sessionId);
362
490
  if (!entry) return false;
363
491
  RUNNING.delete(sessionId);
492
+ // 用正数 seq,避免子进程把假值 id 当成无效命令丢掉
493
+ entry.seq += 1;
494
+ const closeId = entry.seq;
364
495
  try {
365
- entry.child.stdin.write(`${JSON.stringify({ id: -1, cmd: 'close', args: {} })}\n`);
496
+ entry.child.stdin.write(`${JSON.stringify({ id: closeId, cmd: 'close', args: {} })}\n`);
366
497
  } catch {
367
498
  // ignore
368
499
  }
500
+ // 有头 Chromium 偶发不跟 node 一起退:先 SIGTERM,再 SIGKILL
369
501
  setTimeout(() => {
370
502
  try {
371
503
  entry.child.kill('SIGTERM');
372
504
  } catch {
373
505
  // ignore
374
506
  }
375
- }, 1200).unref?.();
507
+ }, 400).unref?.();
508
+ setTimeout(() => {
509
+ try {
510
+ entry.child.kill('SIGKILL');
511
+ } catch {
512
+ // ignore
513
+ }
514
+ }, 1600).unref?.();
376
515
  for (const [id] of entry.pending) respondError(entry, id, '会话已关闭');
377
516
  return true;
378
517
  }
@@ -525,6 +664,8 @@ function pickBaseURLLiteral(content) {
525
664
  const STORAGE_STATE_NAMES = [
526
665
  'auth-admin.json',
527
666
  'auth-user.json',
667
+ 'auth-test.json',
668
+ 'auth-unit-test.json',
528
669
  'auth.json',
529
670
  'storage-state.json',
530
671
  'state.json',
@@ -696,7 +837,8 @@ function writeDraftConfig({ projectDir, sessionId, baseConfig, storageState, bas
696
837
  ' ...config,\n' +
697
838
  " testDir: './draft',\n" +
698
839
  " outputDir: './results',\n" +
699
- " reporter: [['line']],\n" +
840
+ // list 比 line 可读:逐步结果 + 失败断言片段;line 会刷光标控制符,落盘后几乎只剩摘要
841
+ " reporter: [['list']],\n" +
700
842
  ' use: {\n' +
701
843
  `${useLines.join('\n')}\n` +
702
844
  ' },\n' +
@@ -888,30 +1030,91 @@ export function draftSummary({ project, session }) {
888
1030
  };
889
1031
  }
890
1032
 
891
- function tailLog(output, lines = 120) {
1033
+ function tailLog(output, lines = 400) {
892
1034
  const clean = stripAnsi(output);
893
1035
  return clean
894
1036
  .split(/\r?\n/)
895
1037
  .filter((line) => line.trim())
896
1038
  .slice(-lines)
897
1039
  .join('\n')
898
- .slice(-12000);
1040
+ .slice(-48000);
1041
+ }
1042
+
1043
+ /** 试跑日志抬头:说明「在项目里跑、跑的是草稿」 */
1044
+ function formatVerifyLog({ command, args, cwd, draftRel, output }) {
1045
+ const header = [
1046
+ `$ ${[command, ...(args || [])].join(' ')}`,
1047
+ `cwd: ${cwd}`,
1048
+ draftRel ? `draft: ${draftRel}` : '',
1049
+ '(用项目内 Playwright,配置指向本会话 .lantern-ai 草稿,不是正式 tests/)',
1050
+ '─'.repeat(48),
1051
+ ]
1052
+ .filter(Boolean)
1053
+ .join('\n');
1054
+ return `${header}\n${tailLog(output)}`;
1055
+ }
1056
+
1057
+ /**
1058
+ * 把手改出码清单落到会话草稿区(与试跑同一布局)。
1059
+ * spec → draft/;page/fixture → 会话根或 draft 下,保证相对 import 能解析。
1060
+ */
1061
+ export function applyDraftFileOverlay(prepared, draftFiles) {
1062
+ if (!prepared || !Array.isArray(draftFiles) || !draftFiles.length) return prepared;
1063
+ const { paths, emitted } = prepared;
1064
+ for (const item of draftFiles) {
1065
+ const rel = String(item?.path || '')
1066
+ .replace(/\\/g, '/')
1067
+ .replace(/^\/+/, '');
1068
+ const content = typeof item?.content === 'string' ? item.content : '';
1069
+ if (!rel) continue;
1070
+ const role = String(item?.role || '');
1071
+ const isSpec = role === 'spec' || /\.(spec|test)\.(ts|js|py)$/i.test(rel);
1072
+ let abs;
1073
+ if (isSpec) {
1074
+ abs = path.join(paths.draftDir, path.basename(rel));
1075
+ if (emitted) emitted.code = content;
1076
+ } else if (/^(tests|e2e|src\/tests)\//.test(rel)) {
1077
+ const under = rel.replace(/^(tests|e2e|src\/tests)\//, '');
1078
+ abs = path.join(paths.draftDir, under);
1079
+ } else {
1080
+ abs = path.join(paths.root, rel);
1081
+ }
1082
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1083
+ fs.writeFileSync(abs, content);
1084
+ }
1085
+ return prepared;
1086
+ }
1087
+
1088
+ /** 只写草稿、不跑用例(代码页手改落盘) */
1089
+ export function writeSessionDraftFiles({ project, session, draftFiles }) {
1090
+ const prepared = prepareDraft({ project, session });
1091
+ if (prepared.error) return { ok: false, error: prepared.error };
1092
+ applyDraftFileOverlay(prepared, draftFiles);
1093
+ return { ok: true, ...prepared.draftInfo };
899
1094
  }
900
1095
 
901
1096
  /**
902
1097
  * 试跑:草稿写到 `.lantern-ai/<会话>/draft/`,**跑完不删**。
903
1098
  * 失败现场要能打开看、能重跑、能回放 trace;正式文件只在用户确认后写。
1099
+ * `draftFiles`:前端手改后的出码清单;有则用其覆盖草稿。
904
1100
  */
905
- export async function verifySession({ project, session, timeoutMs = DEFAULT_VERIFY_TIMEOUT }) {
1101
+ export async function verifySession({
1102
+ project,
1103
+ session,
1104
+ timeoutMs = DEFAULT_VERIFY_TIMEOUT,
1105
+ draftFiles,
1106
+ }) {
906
1107
  const prepared = prepareDraft({ project, session });
907
1108
  if (prepared.error) return { ok: false, passed: false, error: prepared.error };
1109
+ applyDraftFileOverlay(prepared, draftFiles);
908
1110
  const { isPython, paths, relDraft, configRel, draftInfo, emitted } = prepared;
909
1111
 
910
1112
  let command;
911
1113
  let args;
912
1114
  if (isPython) {
913
1115
  command = detectPython(project.dir);
914
- args = ['-m', 'pytest', relDraft, '-q'];
1116
+ // -v 打出每条用例名;默认 -q 几乎只有点号
1117
+ args = ['-m', 'pytest', relDraft, '-v', '--tb=short'];
915
1118
  } else {
916
1119
  const runner = playwrightRunner(project.dir);
917
1120
  command = runner.command;
@@ -920,7 +1123,7 @@ export async function verifySession({ project, session, timeoutMs = DEFAULT_VERI
920
1123
  'test',
921
1124
  '--config',
922
1125
  configRel,
923
- '--reporter=line',
1126
+ '--reporter=list',
924
1127
  '--workers=1',
925
1128
  '--timeout=30000',
926
1129
  ];
@@ -934,7 +1137,26 @@ export async function verifySession({ project, session, timeoutMs = DEFAULT_VERI
934
1137
  env: { PLAYWRIGHT_HTML_OPEN: 'never', LANTERN_AI_DRAFT: '1' },
935
1138
  });
936
1139
 
1140
+ // 完整 stdout 落盘,面板只展示裁剪后的;需要时可「打开目录」看 last-run.log
1141
+ try {
1142
+ fs.mkdirSync(paths.resultsDir, { recursive: true });
1143
+ fs.writeFileSync(
1144
+ path.join(paths.resultsDir, 'last-run.log'),
1145
+ stripAnsi(result.output || ''),
1146
+ 'utf8',
1147
+ );
1148
+ } catch {
1149
+ // 落盘失败不影响试跑结果
1150
+ }
1151
+
937
1152
  const traceAbs = isPython ? '' : findTrace(paths.resultsDir);
1153
+ const log = formatVerifyLog({
1154
+ command,
1155
+ args,
1156
+ cwd: project.dir,
1157
+ draftRel: relDraft,
1158
+ output: result.output,
1159
+ });
938
1160
  return {
939
1161
  ok: true,
940
1162
  passed: result.exitCode === 0,
@@ -942,10 +1164,11 @@ export async function verifySession({ project, session, timeoutMs = DEFAULT_VERI
942
1164
  timedOut: result.timedOut,
943
1165
  durationMs: result.durationMs,
944
1166
  command: [command, ...args].join(' '),
945
- code: emitted.code,
946
- log: tailLog(result.output),
1167
+ code: emitted?.code || '',
1168
+ log,
947
1169
  ...draftInfo,
948
1170
  tracePath: traceAbs ? toPosix(path.relative(project.dir, traceAbs)) : '',
1171
+ logPath: toPosix(path.relative(project.dir, path.join(paths.resultsDir, 'last-run.log'))),
949
1172
  };
950
1173
  }
951
1174
 
@@ -1039,7 +1262,7 @@ export async function debugSession({ project, session, mode = 'headed' }) {
1039
1262
 
1040
1263
  const result = await runProcess({
1041
1264
  command: runner.command,
1042
- args: [...baseArgs, '--headed', '--trace=on', '--reporter=line'],
1265
+ args: [...baseArgs, '--headed', '--trace=on', '--reporter=list'],
1043
1266
  cwd: project.dir,
1044
1267
  timeoutMs: DEFAULT_VERIFY_TIMEOUT,
1045
1268
  env: { PLAYWRIGHT_HTML_OPEN: 'never', LANTERN_AI_DRAFT: '1' },
@@ -1252,6 +1475,97 @@ export function writeGeneratedFiles(params) {
1252
1475
  };
1253
1476
  }
1254
1477
 
1478
+ /**
1479
+ * 按会话变更账本撤销已写入项目的文件(多选)。
1480
+ * create → 删文件;merge/update → 写回 before;无账本则跳过。
1481
+ */
1482
+ export function revertGeneratedFiles({ project, session, paths }) {
1483
+ const wanted = Array.isArray(paths)
1484
+ ? [...new Set(paths.map((item) => normalizeRelPath(item)).filter(Boolean))]
1485
+ : [];
1486
+ if (!wanted.length) return { ok: false, error: '没有要移除的文件' };
1487
+
1488
+ const ledger = Array.isArray(session?.changes) ? session.changes.slice() : [];
1489
+ const byPath = new Map(ledger.map((entry) => [normalizeRelPath(entry.path), entry]));
1490
+ const reverted = [];
1491
+ const skipped = [];
1492
+
1493
+ for (const target of wanted) {
1494
+ const bad = checkRelPath(project, target);
1495
+ if (bad) {
1496
+ skipped.push({ path: target, reason: bad });
1497
+ continue;
1498
+ }
1499
+ const entry = byPath.get(target);
1500
+ if (!entry) {
1501
+ skipped.push({ path: target, reason: '本会话没有写入记录' });
1502
+ continue;
1503
+ }
1504
+ const abs = path.join(project.dir, target);
1505
+ try {
1506
+ if (entry.kind === 'create') {
1507
+ if (fs.existsSync(abs)) fs.rmSync(abs, { force: true });
1508
+ } else {
1509
+ // merge / update:还原写入前内容;before 为空且文件在则清空为 before
1510
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1511
+ fs.writeFileSync(abs, String(entry.before ?? ''));
1512
+ }
1513
+ reverted.push({
1514
+ path: target,
1515
+ kind: entry.kind === 'create' ? 'deleted' : 'restored',
1516
+ role: entry.role || '',
1517
+ });
1518
+ byPath.delete(target);
1519
+ } catch (err) {
1520
+ return {
1521
+ ok: false,
1522
+ error: err instanceof Error ? err.message : String(err),
1523
+ reverted,
1524
+ skipped,
1525
+ };
1526
+ }
1527
+ }
1528
+
1529
+ if (!reverted.length) {
1530
+ return {
1531
+ ok: false,
1532
+ error: skipped[0]?.reason || '没有可撤销的写入',
1533
+ reverted,
1534
+ skipped,
1535
+ };
1536
+ }
1537
+
1538
+ const nextChanges = ledger.filter((entry) => byPath.has(normalizeRelPath(entry.path)));
1539
+ const revertedSet = new Set(reverted.map((item) => item.path));
1540
+ const prevSaved = Array.isArray(session?.savedPaths)
1541
+ ? session.savedPaths.map((item) => normalizeRelPath(item)).filter(Boolean)
1542
+ : [];
1543
+ const nextSaved = prevSaved.filter((item) => !revertedSet.has(item));
1544
+ // 主用例:优先保留仍在的 spec;否则取剩余第一条
1545
+ let nextSavedPath = normalizeRelPath(session?.savedPath || '');
1546
+ if (!nextSavedPath || revertedSet.has(nextSavedPath)) {
1547
+ const fromLedger = nextChanges.find((entry) => entry.role === 'spec')?.path;
1548
+ nextSavedPath = normalizeRelPath(fromLedger || nextSaved[0] || '');
1549
+ }
1550
+ const nextStatus =
1551
+ nextSaved.length || nextChanges.length
1552
+ ? 'written'
1553
+ : session?.lastVerify?.passed
1554
+ ? 'verified'
1555
+ : 'explored';
1556
+
1557
+ return {
1558
+ ok: true,
1559
+ reverted,
1560
+ skipped,
1561
+ paths: reverted.map((item) => item.path),
1562
+ changes: nextChanges,
1563
+ savedPaths: nextSaved,
1564
+ savedPath: nextSavedPath,
1565
+ status: nextStatus,
1566
+ };
1567
+ }
1568
+
1255
1569
  /** 写进项目(用户确认后才调用);返回 before/after 供「变更」面板出 diff */
1256
1570
  export function writeGeneratedFile({ project, session, relPath, force = false }) {
1257
1571
  const ir = normalizeIr(session.ir || {}, { target: session.target, title: session.title });
@@ -1401,6 +1715,8 @@ export async function gitStatusSummary(projectDir) {
1401
1715
  }
1402
1716
 
1403
1717
  export function suggestedPath({ project, session }) {
1718
+ const pinned = normalizeRelPath(session?.iterationFile || '');
1719
+ if (pinned) return pinned;
1404
1720
  const ir = normalizeIr(session.ir || {}, { target: session.target, title: session.title });
1405
1721
  const emitted = emitCode(ir, session.target);
1406
1722
  return `${detectPlaywrightTestDir(project.dir)}/${emitted.filename}`;
@@ -1,6 +1,9 @@
1
1
  /**
2
- * Node 版本:读项目约定的版本(`.nvmrc` / `package.json` 的 engines),
3
- * 再扫本机 nvm / fnm / volta 里已装好的版本。
2
+ * Node 版本:读项目约定的版本,再扫本机 nvm / fnm / volta 里已装好的版本。
3
+ *
4
+ * 声明优先级(有就停):
5
+ * `.nvmrc` → `.node-version` → `.tool-versions`(asdf/mise) →
6
+ * `package.json` volta.node → engines.node → `package-lock.json` 根 engines
4
7
  *
5
8
  * 只做两件事:把「项目要哪个 Node」查出来、把跑用例时的 PATH 指到那个 Node 的 bin。
6
9
  * 不去改用户 shell 的版本——`nvm use` 是 shell 函数,子进程里切了也不影响用户的终端;
@@ -144,27 +147,114 @@ export function listNodeInstallations() {
144
147
  });
145
148
  }
146
149
 
147
- /** 项目声明的 Node:`.nvmrc` 优先,其次 `.node-version`(fnm / asdf 也认这个),最后 engines */
150
+ /**
151
+ * 读版本文件里第一条有效版本行:跳过空行与 `#` 注释。
152
+ * 常见写法是文件头注释 + 下一行 `v22.23.0`;只读第一行会把「# nodejs 版本」当成要求。
153
+ */
154
+ export function readVersionFileLine(content) {
155
+ for (const raw of String(content ?? '').split(/\r?\n/)) {
156
+ const line = raw.trim();
157
+ if (!line || line.startsWith('#')) continue;
158
+ return line.replace(/^v/i, '');
159
+ }
160
+ return '';
161
+ }
162
+
163
+ /** asdf / mise:`.tool-versions` 里 `nodejs 22.23.0` 或 `node 22.23.0` */
164
+ export function readToolVersionsNode(content) {
165
+ for (const raw of String(content ?? '').split(/\r?\n/)) {
166
+ const line = raw.trim();
167
+ if (!line || line.startsWith('#')) continue;
168
+ const matched = /^(nodejs|node)\s+(\S+)/i.exec(line);
169
+ if (matched) return matched[2].replace(/^v/i, '');
170
+ }
171
+ return '';
172
+ }
173
+
174
+ /** package-lock.json 根包 engines.node(npm 装出来时常有) */
175
+ export function readLockfileNodeEngines(content) {
176
+ try {
177
+ const lock = JSON.parse(String(content ?? ''));
178
+ const root = lock?.packages?.[''] || lock?.packages?.['.'] || null;
179
+ const fromRoot = String(root?.engines?.node ?? '').trim();
180
+ if (fromRoot) return fromRoot;
181
+ return String(lock?.engines?.node ?? '').trim();
182
+ } catch {
183
+ return '';
184
+ }
185
+ }
186
+
187
+ /**
188
+ * 项目声明的 Node。
189
+ * 返回各来源字段 + `required`(实际生效)+ `source`(生效来源,便于面板展示)。
190
+ */
148
191
  export function readNodeRequirement(dir) {
149
192
  const root = path.resolve(dir);
150
- const readFirstLine = (name) => {
193
+ const readVersionFile = (name) => {
194
+ try {
195
+ return readVersionFileLine(fs.readFileSync(path.join(root, name), 'utf8'));
196
+ } catch {
197
+ return '';
198
+ }
199
+ };
200
+ const readText = (name) => {
151
201
  try {
152
- const first = fs.readFileSync(path.join(root, name), 'utf8').split(/\r?\n/)[0] ?? '';
153
- return first.trim().replace(/^v/i, '');
202
+ return fs.readFileSync(path.join(root, name), 'utf8');
154
203
  } catch {
155
204
  return '';
156
205
  }
157
206
  };
158
- const nvmrc = readFirstLine('.nvmrc');
159
- const nodeVersion = nvmrc ? '' : readFirstLine('.node-version');
207
+
208
+ const nvmrc = readVersionFile('.nvmrc');
209
+ const nodeVersion = readVersionFile('.node-version');
210
+ const toolVersions = readToolVersionsNode(readText('.tool-versions'));
211
+
212
+ let volta = '';
160
213
  let engines = '';
161
214
  try {
162
215
  const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
216
+ volta = String(pkg?.volta?.node ?? '')
217
+ .trim()
218
+ .replace(/^v/i, '');
163
219
  engines = String(pkg?.engines?.node ?? '').trim();
164
220
  } catch {
165
- engines = '';
221
+ // ignore
222
+ }
223
+
224
+ const lockfile = readLockfileNodeEngines(readText('package-lock.json'));
225
+
226
+ let required = '';
227
+ let source = '';
228
+ if (nvmrc) {
229
+ required = nvmrc;
230
+ source = 'nvmrc';
231
+ } else if (nodeVersion) {
232
+ required = nodeVersion;
233
+ source = 'node-version';
234
+ } else if (toolVersions) {
235
+ required = toolVersions;
236
+ source = 'tool-versions';
237
+ } else if (volta) {
238
+ required = volta;
239
+ source = 'volta';
240
+ } else if (engines) {
241
+ required = engines;
242
+ source = 'engines';
243
+ } else if (lockfile) {
244
+ required = lockfile;
245
+ source = 'lockfile';
166
246
  }
167
- return { nvmrc, nodeVersion, engines, required: nvmrc || nodeVersion || engines };
247
+
248
+ return {
249
+ nvmrc,
250
+ nodeVersion,
251
+ toolVersions,
252
+ volta,
253
+ engines,
254
+ lockfile,
255
+ required,
256
+ source,
257
+ };
168
258
  }
169
259
 
170
260
  /**
@@ -175,9 +265,10 @@ export function nodeStatus(dir) {
175
265
  const requirement = readNodeRequirement(dir);
176
266
  const running = process.versions.node;
177
267
  const installations = listNodeInstallations();
268
+ // 没声明版本时:尽量对齐本机已装、且等于当前进程的那一份,跑用例 PATH 更稳
178
269
  const match = requirement.required
179
270
  ? (installations.find((item) => satisfiesNode(item.version, requirement.required)) ?? null)
180
- : null;
271
+ : (installations.find((item) => satisfiesNode(item.version, running)) ?? null);
181
272
  return {
182
273
  ...requirement,
183
274
  running,