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
@@ -0,0 +1,1084 @@
1
+ /**
2
+ * 需求拆解库:保存需求拆解生成的本地 XMind 文件及元数据。
3
+ *
4
+ * 文件:`<当前数据空间>/需求拆解库/*.xmind`
5
+ * 元数据:`<当前数据空间>/.lantern/local/requirement-breakdowns.json`
6
+ *
7
+ * 不保存原文结构/XMind 快照;文件本身就是唯一内容源,用户可在本机 XMind
8
+ * 客户端直接编辑保存。列表每次读取都会重新检查文件存在性、大小和 mtime。
9
+ */
10
+ import crypto from 'node:crypto';
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
15
+ import { resolveContentRoot, spaceLocalFile } from '../builtin/session/space-layout.mjs';
16
+ import { isPluginOnInSpace } from './plugin-prompts.mjs';
17
+ import { analysisRevision } from './req-analysis-revision.mjs';
18
+ import { openLocalPath, trashLocalPath } from './lh-project-docs.mjs';
19
+
20
+ const PREFIX = '/__tb_req_breakdowns';
21
+ const VERSION = 2;
22
+ const MAX_XMIND_BYTES = 25 * 1024 * 1024;
23
+ const APP_VERSION = JSON.parse(
24
+ fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
25
+ ).version;
26
+
27
+ export const REQ_BREAKDOWN_DIR_NAME = '需求拆解库';
28
+ export const REQ_BREAKDOWN_STORE_FILE = '需求拆解库.json';
29
+ export const REQ_BREAKDOWN_XMIND_DIR = 'XMind';
30
+ export const REQ_BREAKDOWN_LOCAL_STORE_FILE = 'requirement-breakdowns.json';
31
+
32
+ const text = (value, max = 2000) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
33
+ const now = () => new Date().toISOString();
34
+ const id = (prefix) => `${prefix}_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
35
+ const fileDigest = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex');
36
+
37
+ export function requirementBreakdownLibraryRoot(spaceDir) {
38
+ return resolveContentRoot(spaceDir, REQ_BREAKDOWN_DIR_NAME).abs;
39
+ }
40
+
41
+ export function requirementBreakdownStorePath(spaceDir) {
42
+ return spaceLocalFile(spaceDir, REQ_BREAKDOWN_LOCAL_STORE_FILE);
43
+ }
44
+
45
+ function readJson(file, fallback) {
46
+ try {
47
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
48
+ } catch {
49
+ return fallback;
50
+ }
51
+ }
52
+
53
+ function writeJson(file, value) {
54
+ fs.mkdirSync(path.dirname(file), { recursive: true });
55
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
56
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
57
+ fs.renameSync(tmp, file);
58
+ }
59
+
60
+ function emptyStore() {
61
+ return { version: VERSION, revision: 0, seq: 0, entries: [] };
62
+ }
63
+
64
+ function normalizeEntry(raw) {
65
+ if (!raw || typeof raw !== 'object') return null;
66
+ const entryId = text(raw.id, 80);
67
+ const title = text(raw.title, 300);
68
+ const fileName = path.basename(text(raw.fileName, 300));
69
+ const relativePath = text(raw.relativePath, 2000).replaceAll('\\', '/');
70
+ if (!entryId || !title || !fileName || !relativePath) return null;
71
+ return {
72
+ id: entryId,
73
+ title,
74
+ project: text(raw.project, 200) || '未分类',
75
+ iteration: text(raw.iteration, 100) || '未标注',
76
+ sourcePath: text(raw.sourcePath, 1000),
77
+ sourceTitle: text(raw.sourceTitle, 300),
78
+ sourceHash: text(raw.sourceHash, 64),
79
+ fileHash: text(raw.fileHash, 64),
80
+ analysisId: text(raw.analysisId, 80),
81
+ analysisRevision: text(raw.analysisRevision, 64),
82
+ sourceExportAt: text(raw.sourceExportAt, 80),
83
+ kind: raw.kind === 'uploaded' ? 'uploaded' : 'generated',
84
+ fileName,
85
+ relativePath,
86
+ size: Math.max(0, Number(raw.size) || 0),
87
+ mtime: text(raw.mtime, 80),
88
+ note: text(raw.note, 4000),
89
+ createdAt: text(raw.createdAt, 80) || now(),
90
+ updatedAt: text(raw.updatedAt, 80) || now(),
91
+ };
92
+ }
93
+
94
+ function normalizeStore(raw) {
95
+ const base = emptyStore();
96
+ if (!raw || typeof raw !== 'object') return base;
97
+ base.revision = Math.max(0, Number(raw.revision) || 0);
98
+ base.seq = Math.max(0, Number(raw.seq) || 0);
99
+ base.entries = (Array.isArray(raw.entries) ? raw.entries : [])
100
+ .map(normalizeEntry)
101
+ .filter(Boolean);
102
+ return base;
103
+ }
104
+
105
+ function legacyStorePath(root) {
106
+ return path.join(requirementBreakdownLibraryRoot(root), REQ_BREAKDOWN_STORE_FILE);
107
+ }
108
+
109
+ function cleanupLegacyLibraryDirs(root) {
110
+ const removeEmpty = (dir) => {
111
+ let entries = [];
112
+ try {
113
+ entries = fs.readdirSync(dir, { withFileTypes: true });
114
+ } catch {
115
+ return false;
116
+ }
117
+ let empty = true;
118
+ for (const entry of entries) {
119
+ if (!entry.isDirectory()) {
120
+ if (entry.name === '.DS_Store') {
121
+ fs.rmSync(path.join(dir, entry.name), { force: true });
122
+ continue;
123
+ }
124
+ empty = false;
125
+ continue;
126
+ }
127
+ const child = path.join(dir, entry.name);
128
+ if (!removeEmpty(child)) empty = false;
129
+ }
130
+ if (!empty) return false;
131
+ try {
132
+ fs.rmdirSync(dir);
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ }
137
+ };
138
+ removeEmpty(path.join(requirementBreakdownLibraryRoot(root), REQ_BREAKDOWN_XMIND_DIR));
139
+ }
140
+
141
+ function flattenLibraryFiles(root, store) {
142
+ const libraryRoot = requirementBreakdownLibraryRoot(root);
143
+ fs.mkdirSync(libraryRoot, { recursive: true });
144
+ const used = new Set();
145
+ let changed = false;
146
+ for (const entry of store.entries) {
147
+ const preferred = path.basename(entry.fileName || entry.title || '未命名需求.xmind');
148
+ let fileName = preferred;
149
+ const source = absoluteEntryFile(root, entry);
150
+ const exact = path.join(libraryRoot, preferred);
151
+ if (used.has(fileName) || (fs.existsSync(exact) && exact !== source)) {
152
+ fileName = uniqueFileName(libraryRoot, preferred, false);
153
+ }
154
+ while (used.has(fileName)) fileName = uniqueFileName(libraryRoot, preferred, false);
155
+ used.add(fileName);
156
+ const target = path.join(libraryRoot, fileName);
157
+ if (fs.existsSync(source) && source !== target) {
158
+ fs.renameSync(source, target);
159
+ changed = true;
160
+ }
161
+ const nextRelative = path.relative(libraryRoot, target).replaceAll('\\', '/');
162
+ if (entry.fileName !== fileName) {
163
+ entry.fileName = fileName;
164
+ changed = true;
165
+ }
166
+ if (entry.relativePath !== nextRelative) {
167
+ entry.relativePath = nextRelative;
168
+ changed = true;
169
+ }
170
+ if (fs.existsSync(target)) {
171
+ const stat = fs.statSync(target);
172
+ if (entry.size !== stat.size || entry.mtime !== stat.mtime.toISOString()) {
173
+ entry.size = stat.size;
174
+ entry.mtime = stat.mtime.toISOString();
175
+ changed = true;
176
+ }
177
+ const fileHash = fileDigest(fs.readFileSync(target));
178
+ if (entry.fileHash !== fileHash) {
179
+ entry.fileHash = fileHash;
180
+ changed = true;
181
+ }
182
+ }
183
+ }
184
+ return changed;
185
+ }
186
+
187
+ function reconcileExternalXMindFiles(root, store) {
188
+ const libraryRoot = requirementBreakdownLibraryRoot(root);
189
+ fs.mkdirSync(libraryRoot, { recursive: true });
190
+ const available = new Map();
191
+ for (const name of fs.readdirSync(libraryRoot)) {
192
+ if (!/\.xmind$/i.test(name) || name.startsWith('.')) continue;
193
+ const abs = path.join(libraryRoot, name);
194
+ try {
195
+ const stat = fs.statSync(abs);
196
+ if (stat.isFile()) available.set(abs, { abs, name, stat });
197
+ } catch {
198
+ // 单个文件消失时继续处理其它文件
199
+ }
200
+ }
201
+ let changed = false;
202
+ let revisionChanged = false;
203
+ const tracked = new Set();
204
+ for (const entry of store.entries) {
205
+ const abs = absoluteEntryFile(root, entry);
206
+ if (available.has(abs)) {
207
+ tracked.add(abs);
208
+ const file = available.get(abs);
209
+ if (file.stat.size !== entry.size || file.stat.mtime.toISOString() !== entry.mtime) {
210
+ entry.size = file.stat.size;
211
+ entry.mtime = file.stat.mtime.toISOString();
212
+ changed = true;
213
+ }
214
+ const fileHash = fileDigest(fs.readFileSync(abs));
215
+ if (entry.fileHash !== fileHash) {
216
+ entry.fileHash = fileHash;
217
+ changed = true;
218
+ }
219
+ }
220
+ }
221
+
222
+ for (const entry of store.entries) {
223
+ const current = absoluteEntryFile(root, entry);
224
+ if (fs.existsSync(current)) continue;
225
+ const expectedTime = Date.parse(entry.mtime);
226
+ let matchedAbs = '';
227
+ for (const [abs, file] of available) {
228
+ if (tracked.has(abs)) continue;
229
+ const sameHash = entry.fileHash && fileDigest(fs.readFileSync(abs)) === entry.fileHash;
230
+ const sameStat =
231
+ !entry.fileHash &&
232
+ file.stat.size === entry.size &&
233
+ Number.isFinite(expectedTime) &&
234
+ Math.abs(file.stat.mtimeMs - expectedTime) < 1000;
235
+ if (!sameHash && !sameStat) continue;
236
+ matchedAbs = abs;
237
+ break;
238
+ }
239
+ if (!matchedAbs) continue;
240
+ const file = available.get(matchedAbs);
241
+ tracked.add(matchedAbs);
242
+ entry.title = requirementBreakdownTitle(file.name);
243
+ entry.fileName = file.name;
244
+ entry.relativePath = path.relative(libraryRoot, matchedAbs).replaceAll('\\', '/');
245
+ entry.size = file.stat.size;
246
+ entry.mtime = file.stat.mtime.toISOString();
247
+ entry.fileHash = fileDigest(fs.readFileSync(matchedAbs));
248
+ entry.updatedAt = now();
249
+ changed = true;
250
+ revisionChanged = true;
251
+ }
252
+
253
+ for (const [abs, file] of available) {
254
+ if (tracked.has(abs)) continue;
255
+ const buffer = fs.readFileSync(abs);
256
+ const title = requirementBreakdownTitle(file.name);
257
+ const createdAt = new Date(
258
+ file.stat.birthtimeMs > 0 ? file.stat.birthtimeMs : file.stat.ctimeMs,
259
+ ).toISOString();
260
+ const entry = normalizeEntry({
261
+ id: id('rbl'),
262
+ title,
263
+ project: '手动上传',
264
+ iteration: requirementBreakdownIteration(file.name),
265
+ sourcePath: '',
266
+ sourceTitle: file.name,
267
+ sourceHash: '',
268
+ fileHash: fileDigest(buffer),
269
+ analysisId: '',
270
+ analysisRevision: '',
271
+ sourceExportAt: '',
272
+ kind: 'uploaded',
273
+ fileName: file.name,
274
+ relativePath: path.relative(libraryRoot, abs).replaceAll('\\', '/'),
275
+ size: file.stat.size,
276
+ mtime: file.stat.mtime.toISOString(),
277
+ note: '',
278
+ createdAt,
279
+ updatedAt: now(),
280
+ });
281
+ if (!entry) continue;
282
+ store.entries.push(entry);
283
+ store.seq += 1;
284
+ changed = true;
285
+ revisionChanged = true;
286
+ }
287
+ if (revisionChanged) touch(store);
288
+ return changed;
289
+ }
290
+
291
+ function readStore(root) {
292
+ const localFile = requirementBreakdownStorePath(root);
293
+ const legacyFile = legacyStorePath(root);
294
+ const local = readJson(localFile, null);
295
+ const legacyExists = fs.existsSync(legacyFile);
296
+ const legacy = local || !legacyExists ? null : readJson(legacyFile, null);
297
+ const store = normalizeStore(local || legacy);
298
+ if (!local && legacy) {
299
+ const backup = `${localFile}.v1.bak`;
300
+ try {
301
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
302
+ if (!fs.existsSync(backup)) fs.copyFileSync(legacyFile, backup);
303
+ } catch {
304
+ // 备份失败不阻断迁移;正式文件仍按无损重命名处理
305
+ }
306
+ }
307
+ const flattened = flattenLibraryFiles(root, store);
308
+ const reconciled = reconcileExternalXMindFiles(root, store);
309
+ if (!local || flattened || reconciled) writeJson(localFile, store);
310
+ if (legacyExists) fs.rmSync(legacyFile, { force: true });
311
+ cleanupLegacyLibraryDirs(root);
312
+ return store;
313
+ }
314
+
315
+ function writeStore(root, store) {
316
+ writeJson(requirementBreakdownStorePath(root), store);
317
+ return store;
318
+ }
319
+
320
+ function touch(store) {
321
+ store.revision += 1;
322
+ }
323
+
324
+ function safeSegment(value, fallback) {
325
+ const clean = String(value || '')
326
+ .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
327
+ .replace(/\s+/g, ' ')
328
+ .trim()
329
+ .slice(0, 120);
330
+ return clean || fallback;
331
+ }
332
+
333
+ function sourceFileName(doc) {
334
+ const raw = text(doc?.sourceTitle, 300) || text(doc?.sourcePath, 1000);
335
+ return path.basename(raw || text(doc?.title, 300) || '未命名需求');
336
+ }
337
+
338
+ function sourceStem(fileName) {
339
+ return path.basename(fileName, path.extname(fileName));
340
+ }
341
+
342
+ function breakdownPrefix(fileName) {
343
+ const stem = sourceStem(fileName).trim();
344
+ return (stem.split('_')[0] || stem || '未命名需求').trim();
345
+ }
346
+
347
+ export function requirementBreakdownTitle(fileName) {
348
+ return `${safeSegment(breakdownPrefix(fileName), '未命名需求')}_需求拆解.xmind`;
349
+ }
350
+
351
+ export function requirementBreakdownProject(sourcePath) {
352
+ const posix = String(sourcePath || '').replaceAll('\\', '/');
353
+ const parent = path.posix.dirname(posix);
354
+ if (!parent || parent === '.') return '未分类';
355
+ return path.posix.basename(parent) || '未分类';
356
+ }
357
+
358
+ export function requirementBreakdownIteration(fileName) {
359
+ const match = sourceStem(fileName).match(/(?:^|[^A-Za-z0-9])V(\d+(?:\.\d+)*)/i);
360
+ return match ? `V${match[1]}` : '未标注';
361
+ }
362
+
363
+ function stamp(date = new Date()) {
364
+ const pad = (value) => String(value).padStart(2, '0');
365
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
366
+ }
367
+
368
+ function uniqueFileName(dir, logicalTitle, allowExact = true, currentAbs = '') {
369
+ const ext = '.xmind';
370
+ const base = path.basename(logicalTitle, ext);
371
+ const exact = path.join(dir, logicalTitle);
372
+ if (allowExact && (exact === currentAbs || !fs.existsSync(exact))) {
373
+ return path.basename(exact);
374
+ }
375
+ let candidate = path.join(dir, `${base}_${stamp()}${ext}`);
376
+ let index = 2;
377
+ while (fs.existsSync(candidate)) {
378
+ candidate = path.join(dir, `${base}_${stamp()}-${index}${ext}`);
379
+ index += 1;
380
+ }
381
+ return path.basename(candidate);
382
+ }
383
+
384
+ function collisionSuffix(absPath) {
385
+ return path.basename(absPath, '.xmind').match(/_(\d{8}-\d{6}(?:-\d+)?)$/)?.[1] || '';
386
+ }
387
+
388
+ function renameFileName(dir, logicalTitle, currentAbs) {
389
+ const exact = path.join(dir, logicalTitle);
390
+ if (exact === currentAbs || !fs.existsSync(exact)) return path.basename(exact);
391
+ const suffix = collisionSuffix(currentAbs);
392
+ if (suffix) {
393
+ const base = path.basename(logicalTitle, '.xmind');
394
+ let candidate = path.join(dir, `${base}_${suffix}.xmind`);
395
+ let index = 2;
396
+ while (candidate !== currentAbs && fs.existsSync(candidate)) {
397
+ candidate = path.join(dir, `${base}_${suffix}-${index}.xmind`);
398
+ index += 1;
399
+ }
400
+ return path.basename(candidate);
401
+ }
402
+ return uniqueFileName(dir, logicalTitle, false, currentAbs);
403
+ }
404
+
405
+ const TAIL_FIELD_SRC =
406
+ '输入参数|输出参数|正常流程|扩展流程|补充说明|前置条件|优先级|提出人|附件|备注';
407
+ const TAIL_FIELD_CUT = new RegExp(
408
+ `(?:^|[||。;;\\s])(?:无\\s*)?(?:${TAIL_FIELD_SRC})(?=\\s*[||]|\\s*$)`,
409
+ );
410
+ const REQ_ID_RE = /(?:需求编号|编号)\s*[||::]\s*([A-Za-z]{1,8}(?:-\d+)+)/;
411
+ const STEP_MARK_RE = /(?:^|[\s。;;||])(\d{1,2}(?:[、.]|\.(?=\s)))/g;
412
+ const XMIND_LOGIC_RIGHT = 'org.xmind.ui.logic.right';
413
+ const XMIND_SHAPE_ROUNDED = 'org.xmind.topicShape.roundedRect';
414
+ const XMIND_LINE_ELBOW = 'org.xmind.branchConnection.elbow';
415
+ const XMIND_LINE = '#94a3b8';
416
+ const XMIND_BORDER = '#d0d5dd';
417
+ const XMIND_INK = '#1c3d5a';
418
+
419
+ function xmindTopicId(prefix, key) {
420
+ let h = 2166136261;
421
+ for (let i = 0; i < key.length; i += 1) {
422
+ h ^= key.charCodeAt(i);
423
+ h = Math.imul(h, 16777619);
424
+ }
425
+ const digest = (h >>> 0).toString(36);
426
+ const clean = key.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 24);
427
+ return clean ? `${prefix}-${clean}-${digest}` : `${prefix}-${digest}`;
428
+ }
429
+
430
+ function topicStyle(fill, color) {
431
+ return {
432
+ id: xmindTopicId('st', `${fill}-${color}`),
433
+ properties: {
434
+ 'shape-class': XMIND_SHAPE_ROUNDED,
435
+ 'line-class': XMIND_LINE_ELBOW,
436
+ 'line-color': XMIND_LINE,
437
+ 'line-width': '1',
438
+ 'svg:fill': fill,
439
+ 'fo:color': color,
440
+ 'border-line-color': XMIND_BORDER,
441
+ 'border-line-width': '1',
442
+ },
443
+ };
444
+ }
445
+
446
+ const STYLE_ROOT = topicStyle('#1c3d5a', '#ffffff');
447
+ const STYLE_GROUP = topicStyle('#4176e6', '#ffffff');
448
+ const STYLE_TOPIC = topicStyle('#ffffff', XMIND_INK);
449
+
450
+ function logicTheme() {
451
+ const level = (fill, color) => ({
452
+ properties: {
453
+ 'shape-class': XMIND_SHAPE_ROUNDED,
454
+ 'line-class': XMIND_LINE_ELBOW,
455
+ 'line-color': XMIND_LINE,
456
+ 'line-width': '1',
457
+ 'svg:fill': fill,
458
+ 'fo:color': color,
459
+ 'border-line-color': XMIND_BORDER,
460
+ 'border-line-width': '1',
461
+ },
462
+ });
463
+ return {
464
+ centralTopic: level('#1c3d5a', '#ffffff'),
465
+ mainTopic: level('#4176e6', '#ffffff'),
466
+ subTopic: {
467
+ properties: {
468
+ 'line-class': XMIND_LINE_ELBOW,
469
+ 'svg:fill': '#ffffff',
470
+ 'fo:color': XMIND_INK,
471
+ 'line-color': XMIND_LINE,
472
+ 'line-width': '1',
473
+ },
474
+ },
475
+ map: { properties: { 'svg:fill': '#ffffff', 'line-color': XMIND_LINE } },
476
+ };
477
+ }
478
+
479
+ function escapeRegExp(value) {
480
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
481
+ }
482
+
483
+ function stripReqIdPreamble(value, idValue) {
484
+ if (!idValue) return value.trim();
485
+ const re = new RegExp(
486
+ `(?:需求编号|编号)\\s*[||::]\\s*${escapeRegExp(idValue)}(?:\\s*功能名称\\s*[||][\\s\\S]*?功能描述\\s*[||]\\s*)?`,
487
+ );
488
+ return value
489
+ .replace(re, '')
490
+ .replace(/^[\s||::]+/, '')
491
+ .trim();
492
+ }
493
+
494
+ function stripTailFields(value) {
495
+ const match = TAIL_FIELD_CUT.exec(value);
496
+ if (!match || match.index == null) return value.trim();
497
+ let cut = match.index;
498
+ const sentence = match[0].match(/^[。;;]/);
499
+ if (sentence) cut += sentence[0].length;
500
+ return value
501
+ .slice(0, cut)
502
+ .replace(/[\s||]+$/, '')
503
+ .trim();
504
+ }
505
+
506
+ function sourceExportPieces(body) {
507
+ const source = String(body || '')
508
+ .replace(/\s+/g, ' ')
509
+ .trim();
510
+ if (!source) return { id: '', parts: [] };
511
+ const idValue = REQ_ID_RE.exec(source)?.[1] || '';
512
+ const marks = [];
513
+ for (const match of source.matchAll(STEP_MARK_RE)) {
514
+ const marker = match[1];
515
+ if (!marker || match.index == null) continue;
516
+ marks.push(match.index + match[0].length - marker.length);
517
+ }
518
+ const parts = [];
519
+ const push = (raw) => {
520
+ const cleaned = stripTailFields(stripReqIdPreamble(raw, idValue));
521
+ if (cleaned) parts.push(cleaned);
522
+ };
523
+ if (marks.length) {
524
+ push(source.slice(0, marks[0]));
525
+ marks.forEach((start, index) => push(source.slice(start, marks[index + 1] ?? source.length)));
526
+ } else {
527
+ push(idValue ? stripReqIdPreamble(source, idValue) : source);
528
+ }
529
+ return { id: idValue, parts };
530
+ }
531
+
532
+ function bodyTopics(prefix, parts) {
533
+ return parts.map((part, index) => ({
534
+ id: xmindTopicId('src', `${prefix}-${index + 1}`),
535
+ title: part,
536
+ }));
537
+ }
538
+
539
+ function titleTopic(title, body, key) {
540
+ const titleText = String(title || '')
541
+ .replace(/\s+/g, ' ')
542
+ .trim();
543
+ const { id: reqId, parts } = sourceExportPieces(body);
544
+ const bodies = bodyTopics(
545
+ `body-${key}`,
546
+ parts.filter((part) => part !== titleText && part !== reqId),
547
+ );
548
+ const children = reqId
549
+ ? [
550
+ {
551
+ id: xmindTopicId('src', `code-${key}`),
552
+ title: reqId,
553
+ structureClass: bodies.length ? XMIND_LOGIC_RIGHT : undefined,
554
+ style: STYLE_TOPIC,
555
+ ...(bodies.length ? { children: { attached: bodies } } : {}),
556
+ },
557
+ ]
558
+ : bodies;
559
+ return {
560
+ id: xmindTopicId('src', `title-${key}`),
561
+ title: titleText || body || '未命名需求',
562
+ structureClass: children.length ? XMIND_LOGIC_RIGHT : undefined,
563
+ style: STYLE_TOPIC,
564
+ ...(children.length ? { children: { attached: children } } : {}),
565
+ };
566
+ }
567
+
568
+ function buildXMindContent(sourceTitle, groups) {
569
+ const categories = (Array.isArray(groups) ? groups : []).map((group, groupIndex) => {
570
+ const attached = (Array.isArray(group.items) ? group.items : []).map((item, itemIndex) =>
571
+ titleTopic(
572
+ text(item.title, 200),
573
+ text(item.body, 4000),
574
+ `${groupIndex + 1}-${itemIndex + 1}`,
575
+ ),
576
+ );
577
+ return {
578
+ id: xmindTopicId('src', `cat-${groupIndex + 1}`),
579
+ title: text(group.category, 200) || '未分大类',
580
+ style: STYLE_GROUP,
581
+ structureClass: attached.length ? XMIND_LOGIC_RIGHT : undefined,
582
+ ...(attached.length ? { children: { attached } } : {}),
583
+ };
584
+ });
585
+ return [
586
+ {
587
+ id: 'sheet-1',
588
+ class: 'sheet',
589
+ title: sourceTitle,
590
+ theme: logicTheme(),
591
+ rootTopic: {
592
+ id: 'root-topic',
593
+ title: sourceTitle,
594
+ structureClass: XMIND_LOGIC_RIGHT,
595
+ style: STYLE_ROOT,
596
+ children: { attached: categories },
597
+ },
598
+ },
599
+ ];
600
+ }
601
+
602
+ async function packXMind(sourceTitle, groups) {
603
+ const { default: JSZip } = await import('jszip');
604
+ const zip = new JSZip();
605
+ zip.file('content.json', JSON.stringify(buildXMindContent(sourceTitle, groups)));
606
+ zip.file(
607
+ 'metadata.json',
608
+ JSON.stringify({
609
+ creator: { name: 'Lantern Harness', version: APP_VERSION },
610
+ activeSheetId: 'sheet-1',
611
+ }),
612
+ );
613
+ zip.file(
614
+ 'manifest.json',
615
+ JSON.stringify({ 'file-entries': { 'content.json': {}, 'metadata.json': {} } }),
616
+ );
617
+ return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
618
+ }
619
+
620
+ function decodeXml(value) {
621
+ return String(value)
622
+ .replace(/&lt;/g, '<')
623
+ .replace(/&gt;/g, '>')
624
+ .replace(/&quot;/g, '"')
625
+ .replace(/&#39;|&apos;/g, "'")
626
+ .replace(/&amp;/g, '&');
627
+ }
628
+
629
+ export async function readRequirementBreakdownXMind(absPath) {
630
+ const { default: JSZip } = await import('jszip');
631
+ const zip = await JSZip.loadAsync(fs.readFileSync(absPath));
632
+ const content = zip.file('content.json');
633
+ if (content) {
634
+ const sheets = JSON.parse(await content.async('string'));
635
+ const tree = [];
636
+ const lines = [];
637
+ const walk = (topic, depth = 0) => {
638
+ if (!topic || typeof topic !== 'object') return;
639
+ const title = String(topic.title || '').trim();
640
+ if (title) {
641
+ lines.push(`${' '.repeat(depth)}- ${title}`);
642
+ tree.push({ title, depth });
643
+ }
644
+ const attached = topic.children?.attached;
645
+ if (Array.isArray(attached)) attached.forEach((child) => walk(child, depth + 1));
646
+ };
647
+ for (const sheet of Array.isArray(sheets) ? sheets : []) {
648
+ const root = sheet?.rootTopic || sheet?.topic;
649
+ if (root) walk(root);
650
+ }
651
+ if (lines.length) return { text: lines.join('\n'), tree };
652
+ }
653
+ const legacy = zip.file('content.xml');
654
+ if (legacy) {
655
+ const xml = await legacy.async('string');
656
+ const titles = [...xml.matchAll(/<title[^>]*>([\s\S]*?)<\/title>/gi)]
657
+ .map((match) => decodeXml(match[1]).trim())
658
+ .filter(Boolean);
659
+ return {
660
+ text: titles.map((title) => `- ${title}`).join('\n'),
661
+ tree: titles.map((title) => ({ title, depth: 0 })),
662
+ };
663
+ }
664
+ throw new Error('XMind 文件里没有 content.json/content.xml');
665
+ }
666
+
667
+ function absoluteEntryFile(root, entry) {
668
+ const base = path.resolve(requirementBreakdownLibraryRoot(root));
669
+ const abs = path.resolve(base, entry.relativePath);
670
+ if (abs !== base && !abs.startsWith(base + path.sep)) throw new Error('XMind 文件路径越界');
671
+ return abs;
672
+ }
673
+
674
+ function withFileState(root, entry) {
675
+ const abs = absoluteEntryFile(root, entry);
676
+ try {
677
+ const stat = fs.statSync(abs);
678
+ return {
679
+ ...entry,
680
+ localPath: abs,
681
+ exists: stat.isFile(),
682
+ size: stat.size,
683
+ fileMtime: stat.mtime.toISOString(),
684
+ };
685
+ } catch {
686
+ return { ...entry, localPath: abs, exists: false, size: 0, fileMtime: '' };
687
+ }
688
+ }
689
+
690
+ function findEntry(store, entryId) {
691
+ return store.entries.find((entry) => entry.id === entryId) || null;
692
+ }
693
+
694
+ function requireRevision(store, expectedRevision) {
695
+ const expected = Number(expectedRevision);
696
+ if (!Number.isFinite(expected)) {
697
+ throw Object.assign(new Error('修改需求拆解库必须提供 expectedRevision'), {
698
+ statusCode: 428,
699
+ currentRevision: store.revision,
700
+ });
701
+ }
702
+ if (expected !== store.revision) {
703
+ throw Object.assign(new Error('需求拆解库已被其他页面修改,请刷新后重试'), {
704
+ statusCode: 409,
705
+ currentRevision: store.revision,
706
+ });
707
+ }
708
+ }
709
+
710
+ function addEntry(root, store, data, buffer, allowExact) {
711
+ const dir = requirementBreakdownLibraryRoot(root);
712
+ fs.mkdirSync(dir, { recursive: true });
713
+ const fileName = uniqueFileName(dir, data.title, allowExact);
714
+ const abs = path.join(dir, fileName);
715
+ const tmp = `${abs}.${process.pid}.${Date.now()}.tmp`;
716
+ fs.writeFileSync(tmp, buffer);
717
+ fs.renameSync(tmp, abs);
718
+ const stat = fs.statSync(abs);
719
+ const createdAt = now();
720
+ const entry = normalizeEntry({
721
+ id: id('rbl'),
722
+ ...data,
723
+ fileName,
724
+ relativePath: path.relative(requirementBreakdownLibraryRoot(root), abs).replaceAll('\\', '/'),
725
+ size: stat.size,
726
+ mtime: stat.mtime.toISOString(),
727
+ createdAt,
728
+ updatedAt: createdAt,
729
+ });
730
+ store.seq += 1;
731
+ store.entries.push(entry);
732
+ touch(store);
733
+ writeStore(root, store);
734
+ return entry;
735
+ }
736
+
737
+ function normalizeGroups(groups) {
738
+ return (Array.isArray(groups) ? groups : [])
739
+ .map((group) => ({
740
+ category: text(group?.category, 200) || '未分大类',
741
+ items: (Array.isArray(group?.items) ? group.items : [])
742
+ .map((item) => ({
743
+ title: text(item?.title, 200),
744
+ body: text(item?.body, 4000),
745
+ }))
746
+ .filter((item) => item.title || item.body),
747
+ }))
748
+ .filter((group) => group.items.length);
749
+ }
750
+
751
+ export async function recordRequirementBreakdown(root, doc) {
752
+ if (!isPluginOnInSpace('reqBreakdowns', root)) return null;
753
+ const groups = normalizeGroups(doc?.sourceExport?.groups);
754
+ if (!groups.length) return null;
755
+ const sourceExportAt = text(doc?.sourceExport?.at, 80) || text(doc?.updatedAt, 80);
756
+ const analysisId = text(doc?.id, 80);
757
+ const store = readStore(root);
758
+ const existing = store.entries.find(
759
+ (entry) =>
760
+ entry.analysisId === analysisId &&
761
+ entry.sourceExportAt === sourceExportAt &&
762
+ entry.kind === 'generated',
763
+ );
764
+ if (existing) return withFileState(root, existing);
765
+ const fileName = sourceFileName(doc);
766
+ const buffer = await packXMind(fileName, groups);
767
+ const sameTitleCount = store.entries.filter(
768
+ (entry) => entry.title === requirementBreakdownTitle(fileName),
769
+ ).length;
770
+ return withFileState(
771
+ root,
772
+ addEntry(
773
+ root,
774
+ store,
775
+ {
776
+ title: requirementBreakdownTitle(fileName),
777
+ project: requirementBreakdownProject(doc?.sourcePath),
778
+ iteration: requirementBreakdownIteration(fileName),
779
+ sourcePath: text(doc?.sourcePath, 1000),
780
+ sourceTitle: fileName,
781
+ sourceHash: text(doc?.sourceHash, 64),
782
+ analysisId,
783
+ analysisRevision: analysisRevision(doc),
784
+ sourceExportAt,
785
+ kind: 'generated',
786
+ note: '',
787
+ },
788
+ buffer,
789
+ sameTitleCount === 0,
790
+ ),
791
+ );
792
+ }
793
+
794
+ function listEntries(root, store) {
795
+ return store.entries
796
+ .map((entry) => withFileState(root, entry))
797
+ .sort((left, right) => right.createdAt.localeCompare(left.createdAt));
798
+ }
799
+
800
+ function reqAnalysisDocs(root) {
801
+ const file = path.join(resolveContentRoot(root, '需求分析').abs, '需求分析.json');
802
+ const raw = readJson(file, { docs: [] });
803
+ return Array.isArray(raw) ? raw : Array.isArray(raw.docs) ? raw.docs : [];
804
+ }
805
+
806
+ function backfillCandidates(root, store) {
807
+ return reqAnalysisDocs(root)
808
+ .filter((doc) => normalizeGroups(doc?.sourceExport?.groups).length)
809
+ .map((doc) => {
810
+ const sourceExportAt = text(doc?.sourceExport?.at, 80) || text(doc?.updatedAt, 80);
811
+ const recorded = store.entries.some(
812
+ (entry) =>
813
+ entry.analysisId === text(doc?.id, 80) &&
814
+ entry.sourceExportAt === sourceExportAt &&
815
+ entry.kind === 'generated',
816
+ );
817
+ return {
818
+ analysisId: text(doc.id, 80),
819
+ title: text(doc.title, 200),
820
+ sourcePath: text(doc.sourcePath, 1000),
821
+ sourceTitle: text(doc.sourceTitle, 300),
822
+ sourceExportAt,
823
+ updatedAt: text(doc.updatedAt, 80),
824
+ recorded,
825
+ };
826
+ });
827
+ }
828
+
829
+ function writeError(res, error) {
830
+ const status = Number(error?.statusCode) || 500;
831
+ return sendJson(res, status, {
832
+ ok: false,
833
+ error: error instanceof Error ? error.message : String(error),
834
+ ...(error?.currentRevision !== undefined ? { currentRevision: error.currentRevision } : {}),
835
+ });
836
+ }
837
+
838
+ function sendJson(res, status, value) {
839
+ res.statusCode = status;
840
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
841
+ res.setHeader('Cache-Control', 'no-store');
842
+ res.end(JSON.stringify(value));
843
+ }
844
+
845
+ async function readBody(req) {
846
+ const chunks = [];
847
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
848
+ return Buffer.concat(chunks).toString('utf8');
849
+ }
850
+
851
+ function enabled(root) {
852
+ return isPluginOnInSpace('reqBreakdowns', root);
853
+ }
854
+
855
+ export function lhReqBreakdownLibraryPlugin(dependencies = {}) {
856
+ const openPath = dependencies.openLocalPath || openLocalPath;
857
+ const trashPath = dependencies.trashLocalPath || trashLocalPath;
858
+ return {
859
+ name: 'lh-req-breakdown-library',
860
+ configureServer(server) {
861
+ server.middlewares.use(async (req, res, next) => {
862
+ const parsed = new URL(req.url || '/', 'http://127.0.0.1');
863
+ if (!parsed.pathname.startsWith(PREFIX)) return next();
864
+ const root = getDataRoot();
865
+ const tail = parsed.pathname.slice(PREFIX.length).replace(/^\/+|\/+$/g, '');
866
+ const parts = tail ? tail.split('/') : [];
867
+ const method = req.method || 'GET';
868
+ try {
869
+ if (method === 'GET' && parsed.searchParams.get('health') === '1') {
870
+ return sendJson(res, 200, {
871
+ ok: true,
872
+ file: requirementBreakdownStorePath(root),
873
+ version: VERSION,
874
+ });
875
+ }
876
+ if (!enabled(root))
877
+ return sendJson(res, 403, { ok: false, error: '请先开启需求拆解库插件' });
878
+ if (method === 'GET' && tail === 'list') {
879
+ const store = readStore(root);
880
+ return sendJson(res, 200, {
881
+ ok: true,
882
+ revision: store.revision,
883
+ entries: listEntries(root, store),
884
+ });
885
+ }
886
+ if (method === 'GET' && tail === 'backfill') {
887
+ const store = readStore(root);
888
+ return sendJson(res, 200, {
889
+ ok: true,
890
+ revision: store.revision,
891
+ candidates: backfillCandidates(root, store),
892
+ });
893
+ }
894
+ if (method === 'GET' && parts[0] === 'entries' && parts[1]) {
895
+ const store = readStore(root);
896
+ const entry = findEntry(store, parts[1]);
897
+ if (!entry) return sendJson(res, 404, { ok: false, error: '拆解条目不存在' });
898
+ const state = withFileState(root, entry);
899
+ let content = null;
900
+ if (parsed.searchParams.get('includeContent') === '1' && state.exists) {
901
+ content = await readRequirementBreakdownXMind(state.localPath);
902
+ }
903
+ return sendJson(res, 200, {
904
+ ok: true,
905
+ revision: store.revision,
906
+ entry: state,
907
+ content,
908
+ });
909
+ }
910
+ if (method === 'POST' && tail === 'import') {
911
+ const body = JSON.parse((await readBody(req)) || '{}');
912
+ const buffer = Buffer.from(String(body.contentBase64 || ''), 'base64');
913
+ if (!buffer.length) return sendJson(res, 400, { ok: false, error: 'XMind 文件为空' });
914
+ if (buffer.length > MAX_XMIND_BYTES)
915
+ return sendJson(res, 413, { ok: false, error: 'XMind 文件超过 25MB' });
916
+ const name = text(body.name, 300) || '未命名.xmind';
917
+ if (!/\.xmind$/i.test(name))
918
+ return sendJson(res, 400, { ok: false, error: '只支持 .xmind 文件' });
919
+ const tmp = path.join(
920
+ requirementBreakdownLibraryRoot(root),
921
+ `.verify-${crypto.randomUUID()}.xmind`,
922
+ );
923
+ fs.mkdirSync(path.dirname(tmp), { recursive: true });
924
+ fs.writeFileSync(tmp, buffer);
925
+ try {
926
+ await readRequirementBreakdownXMind(tmp);
927
+ } catch (error) {
928
+ fs.rmSync(tmp, { force: true });
929
+ return sendJson(res, 400, {
930
+ ok: false,
931
+ error: `XMind 文件无效:${error instanceof Error ? error.message : error}`,
932
+ });
933
+ } finally {
934
+ fs.rmSync(tmp, { force: true });
935
+ }
936
+ const store = readStore(root);
937
+ requireRevision(store, body.expectedRevision);
938
+ const project = text(body.project, 200) || '手动上传';
939
+ const iteration = text(body.iteration, 100) || requirementBreakdownIteration(name);
940
+ const title = requirementBreakdownTitle(name);
941
+ const entry = withFileState(
942
+ root,
943
+ addEntry(
944
+ root,
945
+ store,
946
+ {
947
+ title,
948
+ project,
949
+ iteration,
950
+ sourcePath: '',
951
+ sourceTitle: name,
952
+ sourceHash: '',
953
+ analysisId: '',
954
+ analysisRevision: '',
955
+ sourceExportAt: '',
956
+ kind: 'uploaded',
957
+ note: text(body.note, 4000),
958
+ },
959
+ buffer,
960
+ true,
961
+ ),
962
+ );
963
+ return sendJson(res, 200, { ok: true, revision: store.revision, entry });
964
+ }
965
+ if (method === 'POST' && tail === 'backfill') {
966
+ const body = JSON.parse((await readBody(req)) || '{}');
967
+ const store = readStore(root);
968
+ requireRevision(store, body.expectedRevision);
969
+ const ids = new Set(
970
+ (Array.isArray(body.analysisIds) ? body.analysisIds : [])
971
+ .map((item) => text(item, 80))
972
+ .filter(Boolean),
973
+ );
974
+ const docs = reqAnalysisDocs(root).filter((doc) => ids.has(text(doc.id, 80)));
975
+ const created = [];
976
+ const failed = [];
977
+ for (const doc of docs) {
978
+ try {
979
+ const entry = await recordRequirementBreakdown(root, doc);
980
+ if (entry) created.push(entry);
981
+ } catch (error) {
982
+ failed.push({
983
+ analysisId: text(doc.id, 80),
984
+ error: error instanceof Error ? error.message : String(error),
985
+ });
986
+ }
987
+ }
988
+ return sendJson(res, 200, {
989
+ ok: true,
990
+ revision: readStore(root).revision,
991
+ created,
992
+ failed,
993
+ });
994
+ }
995
+ if (parts[0] === 'entries' && parts[1] && parts[2] === 'retry' && method === 'POST') {
996
+ const body = JSON.parse((await readBody(req)) || '{}');
997
+ const store = readStore(root);
998
+ requireRevision(store, body.expectedRevision);
999
+ const entry = findEntry(store, parts[1]);
1000
+ if (!entry) return sendJson(res, 404, { ok: false, error: '拆解条目不存在' });
1001
+ const doc = reqAnalysisDocs(root).find((item) => item.id === entry.analysisId);
1002
+ if (!doc) return sendJson(res, 404, { ok: false, error: '原需求分析记录不存在' });
1003
+ const groups = normalizeGroups(doc.sourceExport?.groups);
1004
+ if (!groups.length)
1005
+ return sendJson(res, 400, { ok: false, error: '原需求分析没有可生成的原文结构' });
1006
+ const buffer = await packXMind(sourceFileName(doc), groups);
1007
+ const abs = absoluteEntryFile(root, entry);
1008
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1009
+ fs.writeFileSync(abs, buffer);
1010
+ const stat = fs.statSync(abs);
1011
+ entry.size = stat.size;
1012
+ entry.mtime = stat.mtime.toISOString();
1013
+ entry.updatedAt = now();
1014
+ touch(store);
1015
+ writeStore(root, store);
1016
+ return sendJson(res, 200, {
1017
+ ok: true,
1018
+ revision: store.revision,
1019
+ entry: withFileState(root, entry),
1020
+ });
1021
+ }
1022
+ if (parts[0] === 'entries' && parts[1] && parts[2] === 'open' && method === 'POST') {
1023
+ const store = readStore(root);
1024
+ const entry = findEntry(store, parts[1]);
1025
+ if (!entry) return sendJson(res, 404, { ok: false, error: '拆解条目不存在' });
1026
+ const abs = absoluteEntryFile(root, entry);
1027
+ if (!fs.existsSync(abs))
1028
+ return sendJson(res, 404, { ok: false, error: 'XMind 文件不存在' });
1029
+ await openPath(abs);
1030
+ return sendJson(res, 200, { ok: true });
1031
+ }
1032
+ if (parts[0] === 'entries' && parts[1] && method === 'PUT') {
1033
+ const body = JSON.parse((await readBody(req)) || '{}');
1034
+ const store = readStore(root);
1035
+ requireRevision(store, body.expectedRevision);
1036
+ const entry = findEntry(store, parts[1]);
1037
+ if (!entry) return sendJson(res, 404, { ok: false, error: '拆解条目不存在' });
1038
+ if (typeof body.note === 'string') entry.note = text(body.note, 4000);
1039
+ const nextTitle = text(body.title, 300);
1040
+ if (nextTitle) {
1041
+ const title = requirementBreakdownTitle(nextTitle);
1042
+ if (title !== entry.title) {
1043
+ const abs = absoluteEntryFile(root, entry);
1044
+ const dir = path.dirname(abs);
1045
+ const newName = renameFileName(dir, title, abs);
1046
+ const nextAbs = path.join(dir, newName);
1047
+ if (fs.existsSync(abs)) fs.renameSync(abs, nextAbs);
1048
+ entry.fileName = newName;
1049
+ entry.relativePath = path
1050
+ .relative(requirementBreakdownLibraryRoot(root), nextAbs)
1051
+ .replaceAll('\\', '/');
1052
+ }
1053
+ entry.title = title;
1054
+ }
1055
+ entry.updatedAt = now();
1056
+ touch(store);
1057
+ writeStore(root, store);
1058
+ return sendJson(res, 200, {
1059
+ ok: true,
1060
+ revision: store.revision,
1061
+ entry: withFileState(root, entry),
1062
+ });
1063
+ }
1064
+ if (parts[0] === 'entries' && parts[1] && method === 'DELETE') {
1065
+ const body = JSON.parse((await readBody(req)) || '{}');
1066
+ const store = readStore(root);
1067
+ requireRevision(store, body.expectedRevision);
1068
+ const entry = findEntry(store, parts[1]);
1069
+ if (!entry) return sendJson(res, 404, { ok: false, error: '拆解条目不存在' });
1070
+ const abs = absoluteEntryFile(root, entry);
1071
+ if (fs.existsSync(abs)) await trashPath(abs);
1072
+ store.entries = store.entries.filter((item) => item.id !== entry.id);
1073
+ touch(store);
1074
+ writeStore(root, store);
1075
+ return sendJson(res, 200, { ok: true, revision: store.revision });
1076
+ }
1077
+ return sendJson(res, 404, { ok: false, error: '需求拆解库接口不存在' });
1078
+ } catch (error) {
1079
+ return writeError(res, error);
1080
+ }
1081
+ });
1082
+ },
1083
+ };
1084
+ }