lantern-harness 0.1.45 → 0.2.2

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 (244) hide show
  1. package/CHANGELOG.md +215 -0
  2. package/README.md +25 -8
  3. package/builtin/session/lh-fs.mjs +93 -4
  4. package/builtin/session/lh-nav-groups.mjs +3 -0
  5. package/builtin/session/mcp-client.mjs +7 -3
  6. package/builtin/session/session-runs.mjs +5 -1
  7. package/builtin/session/skill-validation.mjs +72 -0
  8. package/builtin/session/space-skills.mjs +751 -0
  9. package/cli/data-root.mjs +21 -4
  10. package/cli/lantern.mjs +26 -1
  11. package/cli/mcp-server.mjs +2779 -0
  12. package/cli/server.mjs +8 -2
  13. package/config/app.defaults.json +4 -2
  14. package/dist/500.html +9 -6
  15. package/dist/_astro/Base.Du_-4L-4.css +1 -0
  16. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js +2 -0
  17. package/dist/_astro/BusinessMapBoard.mRxl2G3D.js +5 -0
  18. package/dist/_astro/CaseExecBoard.Cqkxuf5c.js +1 -0
  19. package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +5 -0
  20. package/dist/_astro/CaseGenerateApp.acgnxl79.js +10 -0
  21. package/dist/_astro/CasesLibrary.zmzOQwdn.js +21 -0
  22. package/dist/_astro/ChatApp.Ben9LFra.js +1 -0
  23. package/dist/_astro/ChatApp.DBi6q7Qv.js +262 -0
  24. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  25. package/dist/_astro/DashboardBoard.CAJVE2G4.js +5 -0
  26. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  27. package/dist/_astro/DefectSubmitEntry.BzKXJ-zq.js +2 -0
  28. package/dist/_astro/DocsFileBrowser.apKMbGVf.js +1 -0
  29. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.DMN9-Tjg.js} +1 -1
  30. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  31. package/dist/_astro/KnowledgeLibrary.BcoMQeUd.js +1 -0
  32. package/dist/_astro/LifeKrTasksBoard.DJU0-QI-.js +1 -0
  33. package/dist/_astro/LifeKrTodosBoard.GK7KRAO3.js +1 -0
  34. package/dist/_astro/LifeObjectivesBoard.DuKa6Q3k.js +1 -0
  35. package/dist/_astro/LifePlanTypeSelect.Cm2lUmnH.js +1 -0
  36. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.BWOOVMtz.js} +3 -3
  37. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.bY2l01Ha.js} +2 -2
  38. package/dist/_astro/LifeStagesBoard.CIzxPOJB.js +1 -0
  39. package/dist/_astro/LifeYearCycleSelect.BlsyPmmI.js +1 -0
  40. package/dist/_astro/LifeYearPlansBoard.DaA9O08j.js +1 -0
  41. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  42. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  43. package/dist/_astro/NavLibraries.DVR5Ua-S.js +1 -0
  44. package/dist/_astro/PluginsPage.B063QIlQ.js +18 -0
  45. package/dist/_astro/PmBugsBoard.Cu-v0Gfd.js +1 -0
  46. package/dist/_astro/PmIterationsBoard.CgRzkP-j.js +1 -0
  47. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.DVCEh0Lm.js} +1 -1
  48. package/dist/_astro/PmProjectsBoard.z-bQa98r.js +1 -0
  49. package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +1 -0
  50. package/dist/_astro/PmRequirementsBoard.CyfBI0u_.js +1 -0
  51. package/dist/_astro/PmShared.BQVzwsiz.js +1 -0
  52. package/dist/_astro/ReportsPage.najSzJeT.js +1 -0
  53. package/dist/_astro/ReqAnalysisBoard.BQb8dHFD.js +39 -0
  54. package/dist/_astro/RequirementBreakdownLibrary.Cn6OV6xt.js +2 -0
  55. package/dist/_astro/RequirementsLibrary.CqKNFVsP.js +1 -0
  56. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  57. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  58. package/dist/_astro/SettingsDialog.db3BpFw0.js +1 -0
  59. package/dist/_astro/SlideOverDrawer.BMg2tce6.js +1 -0
  60. package/dist/_astro/SpaceSwitcher.DSUVAPOi.js +7 -0
  61. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.72AL-8p-.js} +1 -1
  62. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  63. package/dist/_astro/TasksBoard.CCDhCSR7.js +1 -0
  64. package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +1 -0
  65. package/dist/_astro/TestReportsLibrary.fWiEyCRx.js +1 -0
  66. package/dist/_astro/TestStatsBoard.BSUBsWSu.js +1 -0
  67. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  68. package/dist/_astro/TodosBoard.By5YdlUe.js +1 -0
  69. package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +3 -0
  70. package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +10 -0
  71. package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +12 -0
  72. package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +3 -0
  73. package/dist/_astro/app-config.Dvfzl5_N.js +1 -0
  74. package/dist/_astro/app-version.CNpnKIb9.js +1 -0
  75. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.CS2w8LOb.js} +1 -1
  76. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  77. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  78. package/dist/_astro/case-gen-run.Cvvdv_kv.js +26 -0
  79. package/dist/_astro/case-prompt.CZ3vWUju.js +2 -0
  80. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.DFWZkoR9.js} +1 -1
  81. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.Clb7HrDB.js} +1 -1
  82. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  83. package/dist/_astro/defect-workbench.CjTb4FDv.js +6 -0
  84. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  85. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  86. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.O4CIma9y.js} +1 -1
  87. package/dist/_astro/i18n.Cp4so7KR.js +7 -0
  88. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  89. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  90. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BpcAcBSI.js} +1 -1
  91. package/dist/_astro/plugins.Db9xoFZb.js +1 -0
  92. package/dist/_astro/project-docs.bB9lQ1Ki.js +1 -0
  93. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  94. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  95. package/dist/_astro/req-analysis.C_gARMrB.js +31 -0
  96. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  97. package/dist/_astro/{settings.38J2uD5M.js → settings.D02wZj3w.js} +2 -2
  98. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  99. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.BAtG6PkW.js} +1 -1
  100. package/dist/_astro/story-review.DTN91Vl9.js +7 -0
  101. package/dist/_astro/test-points.C7ZgggQT.js +8 -0
  102. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  103. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  104. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.COAKEQtZ.js} +1 -1
  105. package/dist/business-map/index.html +983 -0
  106. package/dist/case-exec/index.html +10 -7
  107. package/dist/{prompts → case-execution}/index.html +12 -9
  108. package/dist/cases/generate/index.html +9 -6
  109. package/dist/cases/library/index.html +10 -7
  110. package/dist/dashboard/index.html +10 -7
  111. package/dist/defect-rules/index.html +690 -0
  112. package/dist/defect-submit/index.html +690 -0
  113. package/dist/defect-submit/templates/index.html +690 -0
  114. package/dist/docs/changelog/index.html +259 -52
  115. package/dist/docs/install/index.html +44 -12
  116. package/dist/docs/manual/index.html +212 -75
  117. package/dist/knowledge/index.html +10 -7
  118. package/dist/life/kr-tasks/index.html +10 -7
  119. package/dist/life/kr-todos/index.html +10 -7
  120. package/dist/life/objectives/index.html +10 -7
  121. package/dist/life/reviews/index.html +10 -7
  122. package/dist/life/stages/index.html +10 -7
  123. package/dist/life/year-plans/index.html +10 -7
  124. package/dist/plugins/index.html +10 -7
  125. package/dist/pm/bugs/index.html +10 -7
  126. package/dist/pm/iterations/index.html +10 -7
  127. package/dist/pm/projects/detail/index.html +10 -7
  128. package/dist/pm/projects/index.html +10 -7
  129. package/dist/pm/requirements/index.html +10 -7
  130. package/dist/reports/index.html +10 -7
  131. package/dist/requirement-analysis/index.html +10 -7
  132. package/dist/requirement-breakdowns/index.html +983 -0
  133. package/dist/requirements/index.html +10 -7
  134. package/dist/tasks/index.html +10 -7
  135. package/dist/templates/index.html +10 -7
  136. package/dist/test-automation/index.html +10 -7
  137. package/dist/test-automation/projects/index.html +10 -7
  138. package/dist/test-reports/index.html +10 -7
  139. package/dist/test-stats/index.html +10 -7
  140. package/dist/todos/index.html +10 -7
  141. package/dist/workbench/index.html +9 -6
  142. package/docs/Codex-MCP/351/233/206/346/210/220.md +296 -0
  143. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  144. 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
  145. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +22 -3
  146. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  147. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +63 -17
  148. 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
  149. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +207 -69
  150. package/lh-plugins/business-map/assistant.mjs +958 -0
  151. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  152. package/lh-plugins/business-map/jobs.mjs +749 -0
  153. package/lh-plugins/business-map/login.mjs +295 -0
  154. package/lh-plugins/business-map/sources.mjs +1014 -0
  155. package/lh-plugins/case-execution/files.mjs +777 -0
  156. package/lh-plugins/case-execution/service.mjs +959 -0
  157. package/lh-plugins/case-execution-prompt.mjs +33 -0
  158. package/lh-plugins/lh-business-map.mjs +2431 -0
  159. package/lh-plugins/lh-case-execution.mjs +304 -0
  160. package/lh-plugins/lh-config.mjs +13 -0
  161. package/lh-plugins/lh-defect-submit.mjs +989 -0
  162. package/lh-plugins/lh-project-docs.mjs +31 -140
  163. package/lh-plugins/lh-reports.mjs +29 -57
  164. package/lh-plugins/lh-req-analysis.mjs +32 -3
  165. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  166. package/lh-plugins/lh-uiauto.mjs +514 -22
  167. package/lh-plugins/plugin-prompts.mjs +19 -15
  168. package/lh-plugins/req-analysis-revision.mjs +24 -0
  169. package/lh-plugins/test-points-prompt.mjs +2 -3
  170. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  171. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  172. package/lh-plugins/uiauto-explorer/runner.mjs +15 -2
  173. package/lh-plugins/uiauto-explorer/sessions.mjs +305 -17
  174. package/lh-plugins/uiauto-node.mjs +102 -11
  175. package/lh-plugins/uiauto-prompt.mjs +20 -15
  176. package/lh-plugins/uiauto-sso.mjs +407 -0
  177. package/package.json +5 -2
  178. package/skills/case-execution/SKILL.md +30 -0
  179. package/skills/lantern-defect-submit/SKILL.md +15 -0
  180. package/skills/lantern-workflow/SKILL.md +57 -0
  181. package/skills/office/SKILL.md +26 -0
  182. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  183. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  184. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  185. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  186. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  187. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  188. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  189. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  190. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  191. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  192. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  193. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  194. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  195. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  196. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  197. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  198. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  199. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  200. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  201. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  202. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  203. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  204. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  205. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  206. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  207. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  208. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  209. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  210. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  211. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  212. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  213. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  214. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  215. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  216. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  217. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  218. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  219. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  220. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  221. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  222. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  223. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  224. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  225. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  226. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  227. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  228. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  229. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  230. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  231. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  232. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  233. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  234. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  235. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  236. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  237. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  238. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  239. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  240. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  241. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  242. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  243. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  244. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -0,0 +1,2431 @@
1
+ /**
2
+ * 业务地图(空间级)
3
+ *
4
+ * 数据:`<当前数据空间>/业务地图/业务地图.json`
5
+ * 关联技能:业务地图识别(旧规则文件仅用于技能迁移兼容)
6
+ *
7
+ * 地图由多个业务系统组成。一个系统内保存功能、流程和待审核的 AI 提案;
8
+ * 低风险新增可自动进入待发布草稿,其他提案由用户确认;人工写请求携带 revision,
9
+ * 用于避免旧页面覆盖新地图。
10
+ */
11
+ import crypto from 'node:crypto';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import { createAnalysisService } from './business-map/jobs.mjs';
16
+ import { createBusinessAssistantService } from './business-map/assistant.mjs';
17
+ import { createBusinessLoginService } from './business-map/login.mjs';
18
+ import {
19
+ BUSINESS_MATERIAL_MAX_BYTES,
20
+ businessMaterialCatalog,
21
+ businessMaterialDir,
22
+ collectPages,
23
+ documentCatalog,
24
+ hash,
25
+ removeBusinessMaterial,
26
+ saveBusinessMaterial,
27
+ } from './business-map/sources.mjs';
28
+ import { pickDirectoryResult } from '../builtin/session/lh-fs.mjs';
29
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
30
+ import { resolveContentRoot } from '../builtin/session/space-layout.mjs';
31
+ import { ensurePluginPrompt, isPluginOnInSpace, readPluginPrompt } from './plugin-prompts.mjs';
32
+
33
+ const PREFIX = '/__tb_business_map';
34
+ const VERSION = 2;
35
+ const DIR_NAME = '业务地图';
36
+ const FILE_NAME = '业务地图.json';
37
+
38
+ function sameOrigin(left, right) {
39
+ try {
40
+ return new URL(left).origin === new URL(right).origin;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ export const BUSINESS_MAP_PROMPT_FILE = '业务地图识别提示词.md';
47
+ export const BUSINESS_MAP_PROMPT_TEMPLATE = `# 业务地图识别技能
48
+
49
+ 你是业务地图 AI 助手。工作区只包含“功能目录”和“业务流程”,必须按两个阶段工作,不能跳过目录确认直接编造流程。
50
+
51
+ ## 第一阶段:功能目录
52
+
53
+ 1. 只读抓取系统菜单、子菜单、页面标题、页面状态和可点击路径,保留完整 menuPath。
54
+ 2. 菜单层级作为目录骨架;可以合并重复菜单、修改目录名称、调整目录层级,但不能丢失来源菜单路径。
55
+ 3. 菜单名不等于功能。只有能在页面、文档或用户明确说明中找到依据的业务能力,才能成为功能。
56
+ 4. 功能必须归属一个目录;每个功能至少保留一条可验证证据,证据引用必须逐字来自真实来源。
57
+ 5. 输出目录和功能草案,交给用户继续对话修改;用户确认“应用为功能目录”后才进入下一阶段。
58
+ 6. 不删除已有功能,不覆盖人工锁定字段,不把无法读取的页面当作不存在。
59
+
60
+ ## 第二阶段:业务流程
61
+
62
+ 1. 只基于已经应用的功能目录和真实页面证据识别流程。
63
+ 2. 默认覆盖全部已确认功能;用户在会话里指定目录、功能或业务范围时,严格缩小到该范围。
64
+ 3. 流程按实际执行顺序纵向排列,每一步写明执行角色、参与系统、承载功能、输入、输出和下一步。
65
+ 4. 纯人工动作可以标记 manual=true 且不关联功能;系统动作必须关联已存在的功能 ID。
66
+ 5. 异常分支要说明触发条件、目标步骤和未连接原因,无法验证时列为待确认。
67
+ 6. 不删除已有流程,不虚构不存在的系统动作。
68
+
69
+ ## 安全边界
70
+
71
+ - 不执行提交、审批、删除、发送、支付等写操作。
72
+ - 不读取配置源码目录以外的文件。
73
+ - 在线文档只执行只读访问;本地资料只读取用户主动上传的文件。
74
+ - 不把页面上的内容直接视为业务事实,冲突内容必须列成待确认项。
75
+ - 模型凭证只在当前运行内存中使用,不写入会话、日志或业务地图。
76
+
77
+ ## 输出要求
78
+
79
+ - 每次输出“给用户的简明说明 + 可预览草案 + 待确认项”。
80
+ - 草案不直接写入正式地图,必须等待用户点击应用。
81
+ - 目录与流程均保留证据来源、菜单路径和无法确认的原因。
82
+ `;
83
+
84
+ const FUNCTION_STATUSES = ['在用', '停用', '草稿'];
85
+ const PROPOSAL_STATUSES = ['pending', 'applied', 'ignored'];
86
+ const PROPOSAL_RISKS = ['低', '中', '高'];
87
+
88
+ function sendJson(res, status, body) {
89
+ res.statusCode = status;
90
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
91
+ res.end(JSON.stringify(body));
92
+ }
93
+
94
+ function readBody(req, limit = 2 * 1024 * 1024) {
95
+ return new Promise((resolve, reject) => {
96
+ const chunks = [];
97
+ let size = 0;
98
+ req.on('data', (chunk) => {
99
+ size += chunk.length;
100
+ if (size > limit) {
101
+ reject(Object.assign(new Error('请求内容过大'), { statusCode: 413 }));
102
+ req.destroy();
103
+ return;
104
+ }
105
+ chunks.push(chunk);
106
+ });
107
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
108
+ req.on('error', reject);
109
+ });
110
+ }
111
+
112
+ function readBodyBuffer(req, limit = BUSINESS_MATERIAL_MAX_BYTES) {
113
+ return new Promise((resolve, reject) => {
114
+ const chunks = [];
115
+ let size = 0;
116
+ req.on('data', (chunk) => {
117
+ size += chunk.length;
118
+ if (size > limit) {
119
+ reject(Object.assign(new Error('请求内容过大'), { statusCode: 413 }));
120
+ req.destroy();
121
+ return;
122
+ }
123
+ chunks.push(chunk);
124
+ });
125
+ req.on('end', () => resolve(Buffer.concat(chunks)));
126
+ req.on('error', reject);
127
+ });
128
+ }
129
+
130
+ function text(value, max = 4000) {
131
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
132
+ }
133
+
134
+ function oneOf(value, allowed, fallback) {
135
+ const v = text(value, 40);
136
+ return allowed.includes(v) ? v : fallback;
137
+ }
138
+
139
+ function stringList(value, maxItems = 80, maxLength = 500) {
140
+ if (!Array.isArray(value)) return [];
141
+ const seen = new Set();
142
+ const out = [];
143
+ for (const item of value.slice(0, maxItems)) {
144
+ const v = text(item, maxLength);
145
+ if (!v || seen.has(v)) continue;
146
+ seen.add(v);
147
+ out.push(v);
148
+ }
149
+ return out;
150
+ }
151
+
152
+ function newId(prefix) {
153
+ return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
154
+ }
155
+
156
+ function nowIso() {
157
+ return new Date().toISOString();
158
+ }
159
+
160
+ export function businessMapFilePath(spaceDir) {
161
+ const root = resolveContentRoot(spaceDir, DIR_NAME).abs;
162
+ return path.join(root, FILE_NAME);
163
+ }
164
+
165
+ function readStore(spaceDir) {
166
+ const file = businessMapFilePath(spaceDir);
167
+ try {
168
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
169
+ if (raw && typeof raw === 'object' && Number(raw.version || 1) < VERSION) {
170
+ const backup = `${file}.v${Number(raw.version || 1)}.bak`;
171
+ if (!fs.existsSync(backup)) fs.copyFileSync(file, backup);
172
+ return writeStore(spaceDir, raw);
173
+ }
174
+ return normalizeStore(raw);
175
+ } catch {
176
+ return emptyStore();
177
+ }
178
+ }
179
+
180
+ function writeStore(spaceDir, store) {
181
+ const file = businessMapFilePath(spaceDir);
182
+ fs.mkdirSync(path.dirname(file), { recursive: true });
183
+ const next = {
184
+ ...normalizeStore(store),
185
+ revision: Math.max(1, Number(store?.revision) || 0) + 1,
186
+ updatedAt: nowIso(),
187
+ };
188
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
189
+ fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
190
+ fs.renameSync(tmp, file);
191
+ return next;
192
+ }
193
+
194
+ function emptyStore() {
195
+ return {
196
+ version: VERSION,
197
+ revision: 0,
198
+ systems: [],
199
+ createdAt: '',
200
+ updatedAt: '',
201
+ };
202
+ }
203
+
204
+ function normalizeEvidence(raw) {
205
+ if (!raw || typeof raw !== 'object') return null;
206
+ const title = text(raw.title ?? raw.label, 300);
207
+ const ref = text(raw.ref ?? raw.path ?? raw.url, 1200);
208
+ if (!title && !ref) return null;
209
+ return {
210
+ id: text(raw.id, 64) || newId('ev'),
211
+ type: oneOf(raw.type, ['page', 'doc', 'code', 'manual'], 'manual'),
212
+ title: title || ref,
213
+ ref,
214
+ note: text(raw.note, 1000),
215
+ confidence: oneOf(raw.confidence, ['high', 'medium', 'low'], 'medium'),
216
+ };
217
+ }
218
+
219
+ function normalizeDirectory(raw, index = 0) {
220
+ if (!raw || typeof raw !== 'object') return null;
221
+ const name = text(raw.name, 200);
222
+ if (!name) return null;
223
+ const now = nowIso();
224
+ return {
225
+ id: text(raw.id, 64) || newId('dir'),
226
+ parentId: text(raw.parentId, 64),
227
+ name,
228
+ order: Number.isFinite(Number(raw.order)) ? Math.max(0, Math.round(Number(raw.order))) : index,
229
+ source: oneOf(raw.source, ['menu', 'ai', 'manual'], 'manual'),
230
+ menuPath: stringList(raw.menuPath, 20, 200),
231
+ entryUrl: text(raw.entryUrl, 2000),
232
+ evidence: (Array.isArray(raw.evidence) ? raw.evidence : [])
233
+ .map(normalizeEvidence)
234
+ .filter(Boolean)
235
+ .slice(0, 30),
236
+ createdAt: text(raw.createdAt, 40) || now,
237
+ updatedAt: text(raw.updatedAt, 40) || now,
238
+ };
239
+ }
240
+
241
+ function normalizeFunction(raw, index = 0) {
242
+ if (!raw || typeof raw !== 'object') return null;
243
+ const name = text(raw.name, 200);
244
+ if (!name) return null;
245
+ const now = nowIso();
246
+ return {
247
+ id: text(raw.id, 64) || newId('fn'),
248
+ code: text(raw.code, 32) || `F-${String(index + 1).padStart(3, '0')}`,
249
+ name,
250
+ directoryId: text(raw.directoryId, 64),
251
+ order: Number.isFinite(Number(raw.order)) ? Math.max(0, Math.round(Number(raw.order))) : index,
252
+ domain: text(raw.domain, 100) || '未归类',
253
+ module: text(raw.module, 100) || '未归类',
254
+ status: oneOf(raw.status, FUNCTION_STATUSES, '在用'),
255
+ purpose: text(raw.purpose, 2000),
256
+ roles: stringList(raw.roles ?? (raw.rolesText ? [raw.rolesText] : [])),
257
+ entry: text(raw.entry, 1000),
258
+ inputs: stringList(raw.inputs),
259
+ outputs: stringList(raw.outputs),
260
+ rules: stringList(raw.rules),
261
+ writes: stringList(raw.writes),
262
+ exceptions: stringList(raw.exceptions),
263
+ implementation: stringList(raw.implementation),
264
+ evidence: (Array.isArray(raw.evidence) ? raw.evidence : [])
265
+ .map(normalizeEvidence)
266
+ .filter(Boolean)
267
+ .slice(0, 80),
268
+ confidence: oneOf(raw.confidence, ['high', 'medium', 'low'], 'medium'),
269
+ source: oneOf(raw.source, ['ai', 'manual', 'mixed'], 'manual'),
270
+ confirmed: raw.confirmed === true,
271
+ lockedFields: stringList(raw.lockedFields, 40, 80),
272
+ createdAt: text(raw.createdAt, 40) || now,
273
+ updatedAt: text(raw.updatedAt, 40) || now,
274
+ };
275
+ }
276
+
277
+ function normalizeDirectories(rawDirectories, functions) {
278
+ const directories = [];
279
+ const byId = new Map();
280
+ for (const [index, raw] of (Array.isArray(rawDirectories) ? rawDirectories : []).entries()) {
281
+ const directory = normalizeDirectory(raw, index);
282
+ if (!directory || byId.has(directory.id)) continue;
283
+ byId.set(directory.id, directory);
284
+ directories.push(directory);
285
+ }
286
+ for (const directory of directories) {
287
+ if (directory.parentId && !byId.has(directory.parentId)) directory.parentId = '';
288
+ }
289
+
290
+ const orderedSibling = (parentId) =>
291
+ directories
292
+ .filter((item) => item.parentId === parentId)
293
+ .reduce((max, item) => Math.max(max, item.order + 1), 0);
294
+ const ensure = (name, parentId, menuPath) => {
295
+ const normalizedName = text(name, 200) || '未归类';
296
+ const found = directories.find(
297
+ (item) => item.parentId === parentId && item.name === normalizedName,
298
+ );
299
+ if (found) return found;
300
+ const now = nowIso();
301
+ const directory = {
302
+ id: `dir_${hash(`${parentId}\0${normalizedName}`).slice(0, 16)}`,
303
+ parentId,
304
+ name: normalizedName,
305
+ order: orderedSibling(parentId),
306
+ source: 'manual',
307
+ menuPath,
308
+ entryUrl: '',
309
+ evidence: [],
310
+ createdAt: now,
311
+ updatedAt: now,
312
+ };
313
+ directories.push(directory);
314
+ byId.set(directory.id, directory);
315
+ return directory;
316
+ };
317
+
318
+ for (const fn of functions) {
319
+ if (fn.directoryId && byId.has(fn.directoryId)) continue;
320
+ const domain = ensure(fn.domain || '未归类', '', [fn.domain || '未归类']);
321
+ const moduleName = fn.module || '未归类';
322
+ const moduleDirectory =
323
+ domain.name === moduleName
324
+ ? domain
325
+ : ensure(moduleName, domain.id, [domain.name, moduleName]);
326
+ fn.directoryId = moduleDirectory.id;
327
+ }
328
+ const usedIds = new Set(directories.map((item) => item.id));
329
+ for (const directory of directories) {
330
+ if (directory.parentId && !usedIds.has(directory.parentId)) directory.parentId = '';
331
+ if (!directory.menuPath.length) {
332
+ const pathNames = [];
333
+ let current = directory;
334
+ const visited = new Set();
335
+ while (current && !visited.has(current.id)) {
336
+ visited.add(current.id);
337
+ pathNames.unshift(current.name);
338
+ current = current.parentId ? byId.get(current.parentId) : null;
339
+ }
340
+ directory.menuPath = pathNames;
341
+ }
342
+ }
343
+ for (const parentId of new Set(directories.map((item) => item.parentId))) {
344
+ directories
345
+ .filter((item) => item.parentId === parentId)
346
+ .sort((left, right) => left.order - right.order || left.name.localeCompare(right.name))
347
+ .forEach((item, index) => {
348
+ item.order = index;
349
+ });
350
+ }
351
+ for (const directoryId of new Set(functions.map((item) => item.directoryId))) {
352
+ functions
353
+ .filter((item) => item.directoryId === directoryId)
354
+ .sort((left, right) => left.order - right.order || left.code.localeCompare(right.code))
355
+ .forEach((item, index) => {
356
+ item.order = index;
357
+ });
358
+ }
359
+ return directories.sort(
360
+ (left, right) =>
361
+ left.parentId.localeCompare(right.parentId) ||
362
+ left.order - right.order ||
363
+ left.name.localeCompare(right.name),
364
+ );
365
+ }
366
+
367
+ function normalizeDependency(raw) {
368
+ if (!raw || typeof raw !== 'object') return null;
369
+ const label = text(raw.label, 500);
370
+ const system = text(raw.system, 200);
371
+ if (!label && !system) return null;
372
+ return { system: system || '外部系统', label };
373
+ }
374
+
375
+ function normalizeStep(raw, index = 0) {
376
+ if (!raw || typeof raw !== 'object') return null;
377
+ const title = text(raw.title, 500);
378
+ if (!title) return null;
379
+ return {
380
+ id: text(raw.id, 64) || newId('st'),
381
+ n: Number.isFinite(Number(raw.n)) ? Math.max(1, Math.round(Number(raw.n))) : index + 1,
382
+ title,
383
+ role: text(raw.role, 200),
384
+ system: text(raw.system, 200) || '工单系统',
385
+ functionId: text(raw.functionId, 64),
386
+ input: text(raw.input ?? raw.io, 1200),
387
+ output: text(raw.output, 1200),
388
+ next: text(raw.next, 100),
389
+ branch: text(raw.branch, 1000),
390
+ branchBroken: raw.branchBroken === true || raw.broken === true,
391
+ manual: raw.manual === true,
392
+ dependencies: (Array.isArray(raw.dependencies) ? raw.dependencies : [])
393
+ .map(normalizeDependency)
394
+ .filter(Boolean)
395
+ .slice(0, 30),
396
+ evidence: (Array.isArray(raw.evidence) ? raw.evidence : [])
397
+ .map(normalizeEvidence)
398
+ .filter(Boolean)
399
+ .slice(0, 30),
400
+ };
401
+ }
402
+
403
+ function normalizeFlow(raw, index = 0) {
404
+ if (!raw || typeof raw !== 'object') return null;
405
+ const name = text(raw.name, 300);
406
+ if (!name) return null;
407
+ const steps = (Array.isArray(raw.steps) ? raw.steps : [])
408
+ .map(normalizeStep)
409
+ .filter(Boolean)
410
+ .slice(0, 200)
411
+ .map((step, i) => ({ ...step, n: i + 1 }));
412
+ const now = nowIso();
413
+ return {
414
+ id: text(raw.id, 64) || newId('flow'),
415
+ code: text(raw.code, 32) || `P${index + 1}`,
416
+ name,
417
+ result: text(raw.result, 1000),
418
+ status: oneOf(
419
+ raw.status,
420
+ ['健康', '待补全', '草稿'],
421
+ steps.some((s) => s.branchBroken) ? '待补全' : '健康',
422
+ ),
423
+ steps,
424
+ evidence: (Array.isArray(raw.evidence) ? raw.evidence : [])
425
+ .map(normalizeEvidence)
426
+ .filter(Boolean)
427
+ .slice(0, 80),
428
+ createdAt: text(raw.createdAt, 40) || now,
429
+ updatedAt: text(raw.updatedAt, 40) || now,
430
+ };
431
+ }
432
+
433
+ function normalizeProposal(raw) {
434
+ if (!raw || typeof raw !== 'object') return null;
435
+ const title = text(raw.title, 500);
436
+ if (!title) return null;
437
+ return {
438
+ id: text(raw.id, 64) || newId('prop'),
439
+ action: oneOf(raw.action, ['add', 'update', 'delete'], 'add'),
440
+ targetType: oneOf(raw.targetType, ['function', 'flow'], 'function'),
441
+ targetId: text(raw.targetId, 64),
442
+ title,
443
+ detail: text(raw.detail, 3000),
444
+ source: text(raw.source, 1000),
445
+ risk: oneOf(raw.risk, PROPOSAL_RISKS, '低'),
446
+ confidence: oneOf(raw.confidence, ['high', 'medium', 'low'], 'medium'),
447
+ evidence: (Array.isArray(raw.evidence) ? raw.evidence : [])
448
+ .map(normalizeEvidence)
449
+ .filter(Boolean)
450
+ .slice(0, 30),
451
+ payload: raw.payload && typeof raw.payload === 'object' ? raw.payload : {},
452
+ status: oneOf(raw.status, PROPOSAL_STATUSES, 'pending'),
453
+ createdAt: text(raw.createdAt, 40) || nowIso(),
454
+ appliedAt: text(raw.appliedAt, 40),
455
+ analysisId: text(raw.analysisId, 64),
456
+ fingerprint: text(raw.fingerprint, 64),
457
+ };
458
+ }
459
+
460
+ function normalizeSystem(raw) {
461
+ if (!raw || typeof raw !== 'object') return null;
462
+ const name = text(raw.name, 200);
463
+ if (!name) return null;
464
+ const now = nowIso();
465
+ const functions = (Array.isArray(raw.functions) ? raw.functions : [])
466
+ .map(normalizeFunction)
467
+ .filter(Boolean);
468
+ const directories = normalizeDirectories(raw.directories, functions);
469
+ const ids = new Set(functions.map((item) => item.id));
470
+ const flows = (Array.isArray(raw.flows) ? raw.flows : [])
471
+ .map(normalizeFlow)
472
+ .filter(Boolean)
473
+ .map((flow) => ({
474
+ ...flow,
475
+ steps: flow.steps.map((step) => ({
476
+ ...step,
477
+ functionId: ids.has(step.functionId) ? step.functionId : '',
478
+ })),
479
+ }));
480
+ return {
481
+ id: text(raw.id, 64) || newId('sys'),
482
+ name,
483
+ description: text(raw.description, 2000),
484
+ entryUrl: text(raw.entryUrl, 2000),
485
+ sourceDir: text(raw.sourceDir, 2000),
486
+ loginState: text(raw.loginState, 2000),
487
+ docs: {
488
+ requirements: raw.docs?.requirements !== false,
489
+ knowledge: raw.docs?.knowledge !== false,
490
+ scope: text(raw.docs?.scope, 500) || '当前系统关联文档',
491
+ },
492
+ analysisScope: text(raw.analysisScope, 1000) || '全部菜单',
493
+ status: oneOf(raw.status, ['draft', 'published'], 'draft'),
494
+ publishedRevision: Math.max(0, Number(raw.publishedRevision) || 0),
495
+ lastAnalysis:
496
+ raw.lastAnalysis && typeof raw.lastAnalysis === 'object'
497
+ ? {
498
+ at: text(raw.lastAnalysis.at, 40),
499
+ status: text(raw.lastAnalysis.status, 40),
500
+ pageCount: Math.max(0, Number(raw.lastAnalysis.pageCount) || 0),
501
+ docCount: Math.max(0, Number(raw.lastAnalysis.docCount) || 0),
502
+ codeFileCount: Math.max(0, Number(raw.lastAnalysis.codeFileCount) || 0),
503
+ summary: text(raw.lastAnalysis.summary, 2000),
504
+ }
505
+ : null,
506
+ directories,
507
+ functions,
508
+ flows,
509
+ proposals: (Array.isArray(raw.proposals) ? raw.proposals : [])
510
+ .map(normalizeProposal)
511
+ .filter(Boolean),
512
+ createdAt: text(raw.createdAt, 40) || now,
513
+ updatedAt: text(raw.updatedAt, 40) || now,
514
+ };
515
+ }
516
+
517
+ export function normalizeBusinessMapStore(raw) {
518
+ const base = emptyStore();
519
+ if (!raw || typeof raw !== 'object') return base;
520
+ return {
521
+ version: VERSION,
522
+ revision: Math.max(0, Number(raw.revision) || 0),
523
+ systems: (Array.isArray(raw.systems) ? raw.systems : []).map(normalizeSystem).filter(Boolean),
524
+ createdAt: text(raw.createdAt, 40),
525
+ updatedAt: text(raw.updatedAt, 40),
526
+ };
527
+ }
528
+
529
+ function normalizeStore(raw) {
530
+ return normalizeBusinessMapStore(raw);
531
+ }
532
+
533
+ function requireRevision(store, expectedRevision) {
534
+ if (expectedRevision === undefined || expectedRevision === null) return;
535
+ if (Number(expectedRevision) !== store.revision) {
536
+ const error = new Error('业务地图已被其他页面修改,请刷新后再试');
537
+ error.statusCode = 409;
538
+ error.code = 'revision_conflict';
539
+ throw error;
540
+ }
541
+ }
542
+
543
+ function markSystemDirty(system) {
544
+ system.status = 'draft';
545
+ system.updatedAt = nowIso();
546
+ }
547
+
548
+ function findSystem(store, id) {
549
+ return store.systems.find((item) => item.id === id);
550
+ }
551
+
552
+ function requireSystem(store, id) {
553
+ const system = findSystem(store, id);
554
+ if (!system) {
555
+ const error = new Error('业务系统不存在');
556
+ error.statusCode = 404;
557
+ throw error;
558
+ }
559
+ return system;
560
+ }
561
+
562
+ function touchStore(store) {
563
+ const now = nowIso();
564
+ if (!store.createdAt) store.createdAt = now;
565
+ store.updatedAt = now;
566
+ }
567
+
568
+ function nextFunctionCode(system) {
569
+ const used = new Set(system.functions.map((item) => item.code));
570
+ let n = 1;
571
+ while (used.has(`F-${String(n).padStart(3, '0')}`)) n += 1;
572
+ return `F-${String(n).padStart(3, '0')}`;
573
+ }
574
+
575
+ function nextFlowCode(system) {
576
+ const used = new Set(system.flows.map((item) => item.code));
577
+ let n = 1;
578
+ while (used.has(`P${n}`)) n += 1;
579
+ return `P${n}`;
580
+ }
581
+
582
+ function makeFunction(system, raw) {
583
+ const normalized = normalizeFunction(
584
+ {
585
+ ...raw,
586
+ id: '',
587
+ code: text(raw?.code, 32) || nextFunctionCode(system),
588
+ source: raw?.source === 'ai' ? 'ai' : 'manual',
589
+ confirmed: raw?.confirmed === true,
590
+ },
591
+ system.functions.length,
592
+ );
593
+ if (!normalized) {
594
+ const error = new Error('功能名称不能为空');
595
+ error.statusCode = 400;
596
+ throw error;
597
+ }
598
+ if (normalized.directoryId && !findDirectory(system, normalized.directoryId)) {
599
+ throw Object.assign(new Error('所属目录不存在'), { statusCode: 400 });
600
+ }
601
+ if (!Number.isFinite(Number(raw?.order))) {
602
+ normalized.order = system.functions.filter(
603
+ (item) => item.directoryId === normalized.directoryId,
604
+ ).length;
605
+ }
606
+ return normalized;
607
+ }
608
+
609
+ function makeFlow(system, raw) {
610
+ const normalized = normalizeFlow(
611
+ {
612
+ ...raw,
613
+ id: '',
614
+ code: text(raw?.code, 32) || nextFlowCode(system),
615
+ },
616
+ system.flows.length,
617
+ );
618
+ if (!normalized) {
619
+ const error = new Error('流程名称不能为空');
620
+ error.statusCode = 400;
621
+ throw error;
622
+ }
623
+ return normalized;
624
+ }
625
+
626
+ function applyFunctionPatch(current, patch, manual) {
627
+ const normalized = normalizeFunction({ ...current, ...patch, id: current.id }, 0);
628
+ if (!normalized) throw Object.assign(new Error('功能名称不能为空'), { statusCode: 400 });
629
+ const locked = new Set(current.lockedFields || []);
630
+ const next = { ...current };
631
+ const fields = [
632
+ 'name',
633
+ 'directoryId',
634
+ 'order',
635
+ 'domain',
636
+ 'module',
637
+ 'status',
638
+ 'purpose',
639
+ 'roles',
640
+ 'entry',
641
+ 'inputs',
642
+ 'outputs',
643
+ 'rules',
644
+ 'writes',
645
+ 'exceptions',
646
+ 'implementation',
647
+ 'evidence',
648
+ 'confidence',
649
+ ];
650
+ for (const field of fields) {
651
+ if (manual || !locked.has(field)) next[field] = normalized[field];
652
+ }
653
+ if (manual) {
654
+ next.confirmed = true;
655
+ next.source = current.source === 'ai' ? 'mixed' : 'manual';
656
+ next.lockedFields = [...new Set([...locked, ...Object.keys(patch || {})])];
657
+ }
658
+ next.updatedAt = nowIso();
659
+ return next;
660
+ }
661
+
662
+ function findDirectory(system, id) {
663
+ return (system.directories || []).find((item) => item.id === id) || null;
664
+ }
665
+
666
+ function directoryDescendantIds(system, id) {
667
+ const descendants = new Set();
668
+ const queue = [id];
669
+ while (queue.length) {
670
+ const parentId = queue.shift();
671
+ for (const directory of system.directories || []) {
672
+ if (directory.parentId !== parentId || descendants.has(directory.id)) continue;
673
+ descendants.add(directory.id);
674
+ queue.push(directory.id);
675
+ }
676
+ }
677
+ return descendants;
678
+ }
679
+
680
+ function assertDirectoryParent(system, id, parentId) {
681
+ if (!parentId) return;
682
+ const parent = findDirectory(system, parentId);
683
+ if (!parent) throw Object.assign(new Error('目标目录不存在'), { statusCode: 400 });
684
+ if (id && (id === parentId || directoryDescendantIds(system, id).has(parentId))) {
685
+ throw Object.assign(new Error('目录不能移动到自身或其子目录下'), { statusCode: 400 });
686
+ }
687
+ }
688
+
689
+ function assertDirectoryNameAvailable(system, parentId, name, excludeId = '') {
690
+ const duplicate = (system.directories || []).find(
691
+ (item) =>
692
+ item.id !== excludeId &&
693
+ item.parentId === parentId &&
694
+ item.name.replace(/\s/g, '') === name.replace(/\s/g, ''),
695
+ );
696
+ if (duplicate) {
697
+ throw Object.assign(new Error('同级目录名称不能重复'), {
698
+ statusCode: 409,
699
+ code: 'directory_name_conflict',
700
+ });
701
+ }
702
+ }
703
+
704
+ function normalizeDirectoryOrders(system, parentId) {
705
+ (system.directories || [])
706
+ .filter((item) => item.parentId === parentId)
707
+ .sort((left, right) => left.order - right.order || left.name.localeCompare(right.name))
708
+ .forEach((item, index) => {
709
+ item.order = index;
710
+ });
711
+ }
712
+
713
+ function normalizeFunctionOrders(system, directoryId) {
714
+ system.functions
715
+ .filter((item) => item.directoryId === directoryId)
716
+ .sort((left, right) => left.order - right.order || left.code.localeCompare(right.code))
717
+ .forEach((item, index) => {
718
+ item.order = index;
719
+ });
720
+ }
721
+
722
+ function makeDirectory(system, raw) {
723
+ const parentId = text(raw?.parentId, 64);
724
+ assertDirectoryParent(system, '', parentId);
725
+ const name = text(raw?.name, 200);
726
+ if (!name) throw Object.assign(new Error('目录名称不能为空'), { statusCode: 400 });
727
+ assertDirectoryNameAvailable(system, parentId, name);
728
+ const siblings = system.directories.filter((item) => item.parentId === parentId);
729
+ const normalized = normalizeDirectory(
730
+ {
731
+ ...raw,
732
+ id: '',
733
+ parentId,
734
+ name,
735
+ source: raw?.source === 'ai' || raw?.source === 'menu' ? raw.source : 'manual',
736
+ order: Number.isFinite(Number(raw?.order))
737
+ ? Math.max(0, Math.round(Number(raw.order)))
738
+ : siblings.length,
739
+ },
740
+ siblings.length,
741
+ );
742
+ return normalized;
743
+ }
744
+
745
+ function applyDirectoryPatch(system, current, patch) {
746
+ const parentId = patch?.parentId === undefined ? current.parentId : text(patch.parentId, 64);
747
+ assertDirectoryParent(system, current.id, parentId);
748
+ const normalized = normalizeDirectory(
749
+ {
750
+ ...current,
751
+ ...patch,
752
+ id: current.id,
753
+ parentId,
754
+ name: text(patch?.name, 200) || current.name,
755
+ order:
756
+ patch?.order === undefined
757
+ ? current.order
758
+ : Math.max(0, Math.round(Number(patch.order) || 0)),
759
+ },
760
+ 0,
761
+ );
762
+ assertDirectoryNameAvailable(system, normalized.parentId, normalized.name, current.id);
763
+ normalized.updatedAt = nowIso();
764
+ return normalized;
765
+ }
766
+
767
+ function directoryDeleteImpact(system, id) {
768
+ const ids = new Set([id, ...directoryDescendantIds(system, id)]);
769
+ const functions = system.functions.filter((item) => ids.has(item.directoryId));
770
+ const functionIds = new Set(functions.map((item) => item.id));
771
+ const flows = system.flows.filter((flow) =>
772
+ flow.steps.some((step) => functionIds.has(step.functionId)),
773
+ );
774
+ return {
775
+ directories: ids.size,
776
+ functions: functions.length,
777
+ flows: flows.length,
778
+ directoryIds: ids,
779
+ functionIds,
780
+ };
781
+ }
782
+
783
+ function applyFlowPatch(current, patch) {
784
+ const normalized = normalizeFlow({ ...current, ...patch, id: current.id }, 0);
785
+ if (!normalized) throw Object.assign(new Error('流程名称不能为空'), { statusCode: 400 });
786
+ return { ...normalized, id: current.id, updatedAt: nowIso() };
787
+ }
788
+
789
+ function inspectTextFiles(dir, limit = 600) {
790
+ let count = 0;
791
+ const examples = [];
792
+ const stack = [path.resolve(dir)];
793
+ while (stack.length && count < limit) {
794
+ const current = stack.pop();
795
+ let entries;
796
+ try {
797
+ entries = fs.readdirSync(current, { withFileTypes: true });
798
+ } catch {
799
+ continue;
800
+ }
801
+ for (const entry of entries) {
802
+ if (entry.name === '.git' || entry.name === 'node_modules' || entry.name === 'dist') continue;
803
+ const abs = path.join(current, entry.name);
804
+ if (entry.isDirectory()) {
805
+ stack.push(abs);
806
+ continue;
807
+ }
808
+ if (!entry.isFile()) continue;
809
+ if (!/\.(md|mdx|txt|json|ya?ml|ts|tsx|js|jsx|vue|java|kt|py|go|cs)$/i.test(entry.name)) {
810
+ continue;
811
+ }
812
+ count += 1;
813
+ if (examples.length < 5) examples.push(path.relative(dir, abs));
814
+ if (count >= limit) break;
815
+ }
816
+ }
817
+ return { count, examples };
818
+ }
819
+
820
+ function inspectDocSources(spaceDir) {
821
+ const dirs = [
822
+ resolveContentRoot(spaceDir, '需求文档库').abs,
823
+ resolveContentRoot(spaceDir, '知识库管理').abs,
824
+ ];
825
+ const items = [];
826
+ for (const dir of dirs) {
827
+ const found = inspectTextFiles(dir, 300);
828
+ items.push(...found.examples.map((name) => ({ dir: path.basename(dir), name })));
829
+ }
830
+ return { count: items.length, items: items.slice(0, 8) };
831
+ }
832
+
833
+ function demoSystem() {
834
+ const now = nowIso();
835
+ const functions = [
836
+ [
837
+ 'F-001',
838
+ '来电受理登记',
839
+ '受理域',
840
+ '工单受理',
841
+ '把市民来电登记为来电记录,按需转为工单。',
842
+ '话务员',
843
+ '受理页 / 来电登记区',
844
+ ['诉求要素不全不得建单'],
845
+ ['写入来电记录与工单主表'],
846
+ ],
847
+ [
848
+ 'F-002',
849
+ '诉求分类与归口判定',
850
+ '受理域',
851
+ '工单受理',
852
+ '判断诉求类型与归口方向,决定直答还是建单。',
853
+ '话务员',
854
+ '受理页 / 分类归口区',
855
+ ['按归口字典选择', '类型边界不清转班长复核'],
856
+ ['写入诉求类型与归口字段'],
857
+ ],
858
+ [
859
+ 'F-003',
860
+ '知识库检索与直答',
861
+ '受理域',
862
+ '知识支撑',
863
+ '检索知识库并按标准口径答复市民。',
864
+ '话务员',
865
+ '受理页 / 知识库检索',
866
+ ['无匹配时转建单'],
867
+ ['写入答复记录与引用条目'],
868
+ ],
869
+ [
870
+ 'F-004',
871
+ '工单派发',
872
+ '受理域',
873
+ '工单派发',
874
+ '按归口与负载选择承办单位并派发。',
875
+ '派单岗',
876
+ '待派发工单列表',
877
+ ['按归口字典选择承办单位'],
878
+ ['写入工单状态与派发记录'],
879
+ ],
880
+ [
881
+ 'F-005',
882
+ '工单签收',
883
+ '办理域',
884
+ '部门工作台',
885
+ '承办单位确认接收工单,进入办理。',
886
+ '承办单位经办人',
887
+ '部门工作台 / 待办',
888
+ ['拒收需走退回流程'],
889
+ ['写入签收记录与工单状态'],
890
+ ],
891
+ [
892
+ 'F-006',
893
+ '工单办理与结果回填',
894
+ '办理域',
895
+ '工单办理',
896
+ '记录核实与办理结果,上传佐证并送审。',
897
+ '承办单位经办人',
898
+ '工单详情 / 办理页',
899
+ ['办理结果必填', '佐证缺失不得送审'],
900
+ ['写入办理记录、附件与状态'],
901
+ ],
902
+ [
903
+ 'F-007',
904
+ '工单退回与申请改派',
905
+ '办理域',
906
+ '退回与改派',
907
+ '说明退回理由并申请改派给其他单位。',
908
+ '承办单位经办人、派单岗',
909
+ '工单详情 / 退回入口',
910
+ ['退回理由必填'],
911
+ ['写入退回原因与改派记录'],
912
+ ],
913
+ [
914
+ 'F-008',
915
+ '办理延期申请',
916
+ '办理域',
917
+ '时限管理',
918
+ '提交延期理由与拟新时限,暂停计时。',
919
+ '承办单位经办人',
920
+ '工单 / 时限区',
921
+ ['延期理由必填'],
922
+ ['写入延期申请和时限状态'],
923
+ ],
924
+ [
925
+ 'F-009',
926
+ '工单审核办结',
927
+ '办理域',
928
+ '审核办结',
929
+ '审核办理结果与佐证,合规后办结归档。',
930
+ '审核岗',
931
+ '待审核列表',
932
+ ['佐证齐全才可办结'],
933
+ ['写入审核记录与办结状态'],
934
+ ],
935
+ [
936
+ 'F-010',
937
+ '督办催办',
938
+ '监督评价域',
939
+ '督办管理',
940
+ '时限预警、发起督办并登记督办结果。',
941
+ '督办岗',
942
+ '时限预警 / 督办单',
943
+ ['本系统只登记督办结果'],
944
+ ['写入督办结果与计时信息'],
945
+ ],
946
+ [
947
+ 'F-011',
948
+ '办结回访与满意度评价',
949
+ '监督评价域',
950
+ '回访评价',
951
+ '创建回访任务、记录满意度并完成闭环。',
952
+ '回访岗',
953
+ '待回访队列',
954
+ ['三次未接通标记失联'],
955
+ ['写入回访任务与满意度'],
956
+ ],
957
+ [
958
+ 'F-012',
959
+ '不满意重办',
960
+ '监督评价域',
961
+ '回访评价',
962
+ '认定不满意并创建重办工单重新派发。',
963
+ '回访岗',
964
+ '回访记录',
965
+ ['不满意需有具体理由'],
966
+ ['写入重办工单与认定依据'],
967
+ ],
968
+ ].map(([code, name, domain, module, purpose, role, entry, rules, writes], index) => ({
969
+ id: `demo_fn_${index + 1}`,
970
+ code,
971
+ name,
972
+ domain,
973
+ module,
974
+ status: '在用',
975
+ purpose,
976
+ roles: [role],
977
+ entry,
978
+ inputs: [],
979
+ outputs: [],
980
+ rules,
981
+ writes,
982
+ exceptions: [],
983
+ implementation: [],
984
+ evidence: [
985
+ {
986
+ type: index % 2 ? 'doc' : 'page',
987
+ title: index % 2 ? '示例需求文档与知识条目' : '示例系统页面',
988
+ confidence: index === 7 || index === 11 ? 'low' : 'medium',
989
+ },
990
+ ],
991
+ confidence: index === 7 || index === 11 ? 'low' : 'medium',
992
+ source: index === 0 || index === 3 || index === 5 ? 'mixed' : 'ai',
993
+ confirmed: index === 0 || index === 3 || index === 5,
994
+ lockedFields: index === 0 || index === 3 || index === 5 ? ['purpose', 'rules', 'writes'] : [],
995
+ createdAt: now,
996
+ updatedAt: now,
997
+ }));
998
+ const flowDefs = [
999
+ [
1000
+ 'P1',
1001
+ '咨询类来电直答',
1002
+ '答复完成并归档,不生成工单',
1003
+ [
1004
+ ['接听并确认诉求', '话务员', '示例系统', 'F-001'],
1005
+ ['判定咨询类型', '话务员', '示例系统', 'F-002'],
1006
+ ['检索知识库并答复', '话务员', '示例知识库', 'F-003', '无匹配 → 转 P2 建单'],
1007
+ ['答复归档、不建单', '系统', '示例系统', 'F-001'],
1008
+ ],
1009
+ ],
1010
+ [
1011
+ 'P2',
1012
+ '投诉受理到派发签收',
1013
+ '工单状态为已签收,承办单位明确',
1014
+ [
1015
+ ['接听并记录诉求', '话务员', '示例系统', 'F-001'],
1016
+ ['判定类型与归口', '话务员', '示例系统', 'F-002'],
1017
+ ['建立工单', '话务员', '示例系统', 'F-001'],
1018
+ ['选择承办单位并派发', '派单岗', '示例系统', 'F-004'],
1019
+ ['确认签收', '承办单位经办人', '示例工作台', 'F-005'],
1020
+ ['告知诉求人', '话务员', '示例系统', 'F-001', '', true],
1021
+ ],
1022
+ ],
1023
+ [
1024
+ 'P3',
1025
+ '承办办理到审核办结',
1026
+ '工单已办结,有办理结果与佐证',
1027
+ [
1028
+ ['领取工单', '承办单位经办人', '示例工作台', 'F-006'],
1029
+ ['调查核实诉求', '承办单位经办人', '示例工作台', 'F-006', '', true],
1030
+ ['回填办理结果', '承办单位经办人', '示例工作台', 'F-006'],
1031
+ ['提交审核', '承办单位经办人', '示例系统', 'F-006'],
1032
+ ['审核办理结果', '审核岗', '示例系统', 'F-009', '不通过 → 回第 3 步'],
1033
+ ['确认办结', '审核岗', '示例系统', 'F-009'],
1034
+ ],
1035
+ ],
1036
+ [
1037
+ 'P4',
1038
+ '超期督办与延期',
1039
+ '延期获批或督办后按期办结',
1040
+ [
1041
+ ['识别临期与超期', '系统', '示例配置中心', 'F-010'],
1042
+ ['提交延期申请', '承办单位经办人', '示例系统', 'F-008'],
1043
+ ['审批延期', '督办岗', '示例系统', 'F-010'],
1044
+ ['发起督办', '督办岗', '示例系统', 'F-010'],
1045
+ ['响应督办', '承办单位经办人', '示例工作台', 'F-010', '', true],
1046
+ ['记录结果并结算计时', '督办岗', '示例系统', 'F-010'],
1047
+ ],
1048
+ ],
1049
+ [
1050
+ 'P5',
1051
+ '办结回访与不满意重办',
1052
+ '满意闭环或转不满意重办',
1053
+ [
1054
+ ['生成回访任务', '系统', '示例系统', 'F-011'],
1055
+ ['电话回访', '回访岗', '示例系统', 'F-011', '', true],
1056
+ ['记录满意度', '回访岗', '示例系统', 'F-011', '不满意 → 第 4 步', false, true],
1057
+ ['认定不满意并重办', '回访岗', '示例系统', 'F-012'],
1058
+ ['派发重办工单', '派单岗', '示例系统', 'F-004'],
1059
+ ['归档满意评价', '回访岗', '示例系统', 'F-011'],
1060
+ ],
1061
+ ],
1062
+ ];
1063
+ const flows = flowDefs.map(([code, name, result, steps]) => ({
1064
+ id: `demo_flow_${code}`,
1065
+ code,
1066
+ name,
1067
+ result,
1068
+ status: code === 'P5' ? '待补全' : '健康',
1069
+ steps: steps.map(
1070
+ (
1071
+ [title, role, system, fnCode, branch = '', manual = false, branchBroken = false],
1072
+ index,
1073
+ ) => ({
1074
+ id: `demo_step_${code}_${index + 1}`,
1075
+ n: index + 1,
1076
+ title,
1077
+ role,
1078
+ system,
1079
+ functionId: functions.find((item) => item.code === fnCode)?.id || '',
1080
+ input: '',
1081
+ output: '',
1082
+ next: index === steps.length - 1 ? '结束' : String(index + 2),
1083
+ branch,
1084
+ branchBroken,
1085
+ manual,
1086
+ dependencies:
1087
+ system === '示例系统' && title.includes('归口')
1088
+ ? [{ system: '示例配置中心', label: '读取归口与派单字典' }]
1089
+ : system === '示例知识库'
1090
+ ? [{ system: '示例知识库', label: '查询知识条目' }]
1091
+ : [],
1092
+ evidence: [{ type: 'page', title: '示例系统页面', confidence: 'medium' }],
1093
+ }),
1094
+ ),
1095
+ evidence: [{ type: 'page', title: '示例系统菜单与页面', confidence: 'medium' }],
1096
+ createdAt: now,
1097
+ updatedAt: now,
1098
+ }));
1099
+ return normalizeSystem({
1100
+ id: 'demo_work_order',
1101
+ name: '示例系统',
1102
+ description: '虚构业务数据,仅用于演示功能目录、业务流程与证据维护。',
1103
+ entryUrl: 'https://example.com',
1104
+ sourceDir: '',
1105
+ loginState: '',
1106
+ status: 'draft',
1107
+ functions,
1108
+ flows,
1109
+ proposals: [],
1110
+ createdAt: now,
1111
+ updatedAt: now,
1112
+ });
1113
+ }
1114
+
1115
+ function validateForPublish(system) {
1116
+ const items = [];
1117
+ const pending = system.proposals.filter((item) => item.status === 'pending').length;
1118
+ if (pending) {
1119
+ items.push({
1120
+ level: 'block',
1121
+ code: 'pending_proposals',
1122
+ title: `${pending} 项 AI 识别结果未审核`,
1123
+ ref: 'proposals',
1124
+ });
1125
+ }
1126
+ const noPurpose = system.functions.filter((item) => !item.purpose).length;
1127
+ if (noPurpose) {
1128
+ items.push({
1129
+ level: 'warn',
1130
+ code: 'function_purpose',
1131
+ title: `${noPurpose} 个功能缺少作用说明`,
1132
+ ref: 'functions',
1133
+ });
1134
+ }
1135
+ let brokenBranches = 0;
1136
+ let missingFunctions = 0;
1137
+ for (const flow of system.flows) {
1138
+ brokenBranches += flow.steps.filter((step) => step.branchBroken).length;
1139
+ missingFunctions += flow.steps.filter(
1140
+ (step) => !step.manual && !system.functions.some((item) => item.id === step.functionId),
1141
+ ).length;
1142
+ }
1143
+ const emptyFlows = system.flows.filter((flow) => !flow.steps.length).length;
1144
+ if (emptyFlows)
1145
+ items.push({
1146
+ level: 'block',
1147
+ code: 'empty_flows',
1148
+ title: `${emptyFlows} 条流程还没有步骤`,
1149
+ ref: 'flows',
1150
+ });
1151
+ if (brokenBranches) {
1152
+ items.push({
1153
+ level: 'block',
1154
+ code: 'broken_branch',
1155
+ title: `${brokenBranches} 个流程分支未连接`,
1156
+ ref: 'flows',
1157
+ });
1158
+ }
1159
+ if (missingFunctions) {
1160
+ items.push({
1161
+ level: 'block',
1162
+ code: 'missing_function',
1163
+ title: `${missingFunctions} 个步骤没有承载功能`,
1164
+ ref: 'flows',
1165
+ });
1166
+ }
1167
+ if (!system.functions.length) {
1168
+ items.push({
1169
+ level: 'block',
1170
+ code: 'empty_map',
1171
+ title: '业务地图还没有功能',
1172
+ ref: 'functions',
1173
+ });
1174
+ }
1175
+ if (!items.some((item) => item.level === 'block')) {
1176
+ items.push({ level: 'ok', code: 'structure', title: '功能与流程结构完整', ref: '' });
1177
+ }
1178
+ return {
1179
+ ok: !items.some((item) => item.level === 'block'),
1180
+ items,
1181
+ score: Math.max(
1182
+ 40,
1183
+ 100 -
1184
+ items.filter((item) => item.level === 'block').length * 18 -
1185
+ items.filter((item) => item.level === 'warn').length * 5,
1186
+ ),
1187
+ };
1188
+ }
1189
+
1190
+ function analysisProposals(system, sources) {
1191
+ const createdAt = nowIso();
1192
+ const docCount = Number(sources?.stats?.docCount) || 0;
1193
+ const codeCount = Number(sources?.stats?.codeFileCount) || 0;
1194
+ const pageScope = text(sources?.page?.scope, 200) || system.analysisScope;
1195
+ const output = [];
1196
+ output.push({
1197
+ id: newId('prop'),
1198
+ action: 'add',
1199
+ targetType: 'function',
1200
+ targetId: '',
1201
+ title: '补充“工单附件预览”功能',
1202
+ detail: '办理页面存在附件与预览动作,当前地图只登记了结果回填。',
1203
+ source: `页面 · ${pageScope}`,
1204
+ risk: '低',
1205
+ confidence: 'medium',
1206
+ evidence: [{ type: 'page', title: '办理页 / 附件预览', confidence: 'medium' }],
1207
+ payload: {
1208
+ name: '工单附件预览',
1209
+ domain: '办理域',
1210
+ module: '工单办理',
1211
+ purpose: '在工单详情中预览图片和 PDF 佐证,避免下载后重复打开。',
1212
+ roles: ['承办单位经办人', '审核岗'],
1213
+ entry: '工单办理页 / 附件区',
1214
+ rules: ['仅允许预览当前工单附件'],
1215
+ writes: [],
1216
+ source: 'ai',
1217
+ confidence: 'medium',
1218
+ },
1219
+ status: 'pending',
1220
+ createdAt,
1221
+ appliedAt: '',
1222
+ });
1223
+ output.push({
1224
+ id: newId('prop'),
1225
+ action: 'add',
1226
+ targetType: 'function',
1227
+ targetId: '',
1228
+ title: '补充“处理时限变更记录”功能',
1229
+ detail: '详情面板存在只读变更记录,可作为独立查询能力维护。',
1230
+ source: `源码 · ${codeCount} 个文本文件`,
1231
+ risk: '低',
1232
+ confidence: 'low',
1233
+ evidence: [{ type: 'code', title: 'time-limit / history', confidence: 'low' }],
1234
+ payload: {
1235
+ name: '处理时限变更记录',
1236
+ domain: '办理域',
1237
+ module: '时限管理',
1238
+ purpose: '查看工单时限、延期和督办产生的历史变更。',
1239
+ roles: ['督办岗', '审核岗'],
1240
+ entry: '工单详情 / 时限记录',
1241
+ rules: ['变更记录只读'],
1242
+ writes: [],
1243
+ source: 'ai',
1244
+ confidence: 'low',
1245
+ },
1246
+ status: 'pending',
1247
+ createdAt,
1248
+ appliedAt: '',
1249
+ });
1250
+ const mergeCandidate = system.functions.find((item) => item.name.includes('满意度'));
1251
+ if (mergeCandidate) {
1252
+ output.push({
1253
+ id: newId('prop'),
1254
+ action: 'delete',
1255
+ targetType: 'function',
1256
+ targetId: mergeCandidate.id,
1257
+ title: '合并重复的满意度归档动作',
1258
+ detail:
1259
+ '“记录满意度”和“归档满意评价”指向同一回访页与同一落库对象,建议确认后合并,删除单独维护的功能项。',
1260
+ source: '页面动作 · 流程引用 · 源码对象',
1261
+ risk: '高',
1262
+ confidence: 'medium',
1263
+ evidence: [{ type: 'page', title: '回访结果 / 满意评价', confidence: 'medium' }],
1264
+ payload: {},
1265
+ status: 'pending',
1266
+ createdAt,
1267
+ appliedAt: '',
1268
+ });
1269
+ }
1270
+ const defer = system.functions.find((item) => item.name.includes('延期'));
1271
+ if (defer) {
1272
+ output.push({
1273
+ id: newId('prop'),
1274
+ action: 'update',
1275
+ targetType: 'function',
1276
+ targetId: defer.id,
1277
+ title: '延期申请补充审批角色',
1278
+ detail: '页面存在“延期审批”动作,原规则只记录了申请人。',
1279
+ source: docCount ? `文档 · ${docCount} 份关联资料` : '页面 · 时限区',
1280
+ risk: '中',
1281
+ confidence: 'medium',
1282
+ evidence: [{ type: 'page', title: '工单 / 延期审批', confidence: 'medium' }],
1283
+ payload: {
1284
+ roles: [...new Set([...(defer.roles || []), '督办岗'])],
1285
+ rules: [...new Set([...(defer.rules || []), '延期通过后才更新时限'])],
1286
+ source: 'ai',
1287
+ },
1288
+ status: 'pending',
1289
+ createdAt,
1290
+ appliedAt: '',
1291
+ });
1292
+ }
1293
+ output.push({
1294
+ id: newId('prop'),
1295
+ action: 'add',
1296
+ targetType: 'flow',
1297
+ targetId: '',
1298
+ title: '新增候选流程:延期审批',
1299
+ detail: '根据“申请 → 审批 → 更新时限”动作推断出候选流程。',
1300
+ source: '页面动作 · 源码路由',
1301
+ risk: '中',
1302
+ confidence: 'medium',
1303
+ evidence: [
1304
+ { type: 'page', title: '时限区' },
1305
+ { type: 'code', title: 'extend 路由' },
1306
+ ],
1307
+ payload: {
1308
+ name: '延期审批',
1309
+ result: '延期审批完成并更新工单时限',
1310
+ steps: [
1311
+ {
1312
+ title: '提交延期申请',
1313
+ role: '承办单位经办人',
1314
+ system: system.name,
1315
+ functionId: defer?.id || '',
1316
+ input: '工单',
1317
+ output: '延期申请',
1318
+ next: '2',
1319
+ },
1320
+ {
1321
+ title: '审批延期',
1322
+ role: '督办岗',
1323
+ system: system.name,
1324
+ functionId: defer?.id || '',
1325
+ input: '延期申请',
1326
+ output: '审批结果',
1327
+ next: '3',
1328
+ },
1329
+ {
1330
+ title: '更新处理时限',
1331
+ role: '系统',
1332
+ system: '系统设置',
1333
+ functionId: defer?.id || '',
1334
+ input: '审批结果',
1335
+ output: '新时限',
1336
+ next: '结束',
1337
+ },
1338
+ ],
1339
+ },
1340
+ status: 'pending',
1341
+ createdAt,
1342
+ appliedAt: '',
1343
+ });
1344
+ output.push({
1345
+ id: newId('prop'),
1346
+ action: 'update',
1347
+ targetType: 'flow',
1348
+ targetId: system.flows.find((flow) => flow.code === 'P5')?.id || '',
1349
+ title: '修复 P5 不满意分支连接',
1350
+ detail: '页面和源码都表明不满意后进入“认定并重办”,建议连接到第 4 步。',
1351
+ source: '页面 · 源码 · 当前地图',
1352
+ risk: '高',
1353
+ confidence: 'high',
1354
+ evidence: [
1355
+ { type: 'page', title: '回访记录' },
1356
+ { type: 'code', title: 'visit/rework' },
1357
+ ],
1358
+ payload: {},
1359
+ status: 'pending',
1360
+ createdAt,
1361
+ appliedAt: '',
1362
+ });
1363
+ return output.filter(
1364
+ (item) => item.targetType !== 'flow' || item.targetId || item.action === 'add',
1365
+ );
1366
+ }
1367
+
1368
+ function applyProposal(system, proposal) {
1369
+ if (proposal.status !== 'pending') return;
1370
+ if (proposal.targetType === 'function') {
1371
+ if (proposal.action === 'add') {
1372
+ const created = makeFunction(system, {
1373
+ ...proposal.payload,
1374
+ source: 'ai',
1375
+ confidence: proposal.confidence,
1376
+ evidence: proposal.evidence,
1377
+ });
1378
+ system.functions.push(created);
1379
+ } else {
1380
+ const index = system.functions.findIndex((item) => item.id === proposal.targetId);
1381
+ if (index < 0)
1382
+ throw Object.assign(new Error(`找不到提案目标:${proposal.title}`), { statusCode: 409 });
1383
+ if (proposal.action === 'update') {
1384
+ system.functions[index] = applyFunctionPatch(
1385
+ system.functions[index],
1386
+ proposal.payload,
1387
+ false,
1388
+ );
1389
+ } else if (proposal.action === 'delete') {
1390
+ system.functions.splice(index, 1);
1391
+ for (const flow of system.flows) {
1392
+ for (const step of flow.steps) {
1393
+ if (step.functionId === proposal.targetId) step.functionId = '';
1394
+ }
1395
+ }
1396
+ }
1397
+ }
1398
+ } else {
1399
+ if (proposal.action === 'add') {
1400
+ const steps = (proposal.payload.steps || []).map((step) => ({
1401
+ ...step,
1402
+ functionId:
1403
+ step.functionId || system.functions.find((fn) => fn.name === step.functionName)?.id || '',
1404
+ }));
1405
+ system.flows.push(
1406
+ makeFlow(system, { ...proposal.payload, steps, evidence: proposal.evidence }),
1407
+ );
1408
+ } else {
1409
+ const index = system.flows.findIndex((item) => item.id === proposal.targetId);
1410
+ if (index < 0)
1411
+ throw Object.assign(new Error(`找不到提案目标:${proposal.title}`), { statusCode: 409 });
1412
+ if (proposal.action === 'update') {
1413
+ const patch = { ...proposal.payload };
1414
+ const current = system.flows[index];
1415
+ if (
1416
+ system.id === 'demo_work_order' &&
1417
+ current.code === 'P5' &&
1418
+ !Object.keys(patch).length
1419
+ ) {
1420
+ patch.steps = current.steps.map((step) =>
1421
+ step.branchBroken
1422
+ ? {
1423
+ ...step,
1424
+ branchBroken: false,
1425
+ branch: step.branch.replace('(尚未连到步骤)', ''),
1426
+ }
1427
+ : step,
1428
+ );
1429
+ patch.status = '健康';
1430
+ }
1431
+ system.flows[index] = applyFlowPatch(current, patch);
1432
+ } else {
1433
+ system.flows.splice(index, 1);
1434
+ }
1435
+ }
1436
+ }
1437
+ proposal.status = 'applied';
1438
+ proposal.appliedAt = nowIso();
1439
+ }
1440
+
1441
+ function applyAssistantDirectoryProposal(root, systemId, proposal, expectedRevision) {
1442
+ const store = readStore(root);
1443
+ requireRevision(store, expectedRevision);
1444
+ const system = requireSystem(store, systemId);
1445
+ const keyToId = new Map();
1446
+ const proposedDirectories = Array.isArray(proposal.directories) ? proposal.directories : [];
1447
+ const directoryOrderByKey = new Map();
1448
+ const siblingCounts = new Map();
1449
+ for (const raw of proposedDirectories) {
1450
+ const parentKey = String(raw.parentKey || '');
1451
+ const order = siblingCounts.get(parentKey) || 0;
1452
+ directoryOrderByKey.set(raw.key, order);
1453
+ siblingCounts.set(parentKey, order + 1);
1454
+ }
1455
+ const remaining = [...proposedDirectories];
1456
+ let directoriesApplied = 0;
1457
+ while (remaining.length) {
1458
+ let progressed = false;
1459
+ for (let index = remaining.length - 1; index >= 0; index -= 1) {
1460
+ const raw = remaining[index];
1461
+ if (raw.parentKey && !keyToId.has(raw.parentKey)) continue;
1462
+ const parentId = raw.parentKey ? keyToId.get(raw.parentKey) : '';
1463
+ const existing = system.directories.find(
1464
+ (item) =>
1465
+ item.parentId === parentId &&
1466
+ item.name.replace(/\s/g, '') === raw.name.replace(/\s/g, ''),
1467
+ );
1468
+ if (existing) {
1469
+ existing.menuPath = Array.isArray(raw.menuPath) ? raw.menuPath : existing.menuPath;
1470
+ existing.entryUrl = text(raw.entryUrl, 2000) || existing.entryUrl;
1471
+ existing.source = 'ai';
1472
+ existing.order = directoryOrderByKey.get(raw.key) || 0;
1473
+ existing.updatedAt = nowIso();
1474
+ keyToId.set(raw.key, existing.id);
1475
+ } else {
1476
+ const created = normalizeDirectory(
1477
+ {
1478
+ id: '',
1479
+ parentId,
1480
+ name: raw.name,
1481
+ order: directoryOrderByKey.get(raw.key) || 0,
1482
+ source: 'ai',
1483
+ menuPath: raw.menuPath,
1484
+ entryUrl: raw.entryUrl,
1485
+ evidence: [],
1486
+ },
1487
+ system.directories.length,
1488
+ );
1489
+ if (created) {
1490
+ system.directories.push(created);
1491
+ keyToId.set(raw.key, created.id);
1492
+ }
1493
+ }
1494
+ directoriesApplied += 1;
1495
+ remaining.splice(index, 1);
1496
+ progressed = true;
1497
+ }
1498
+ if (!progressed) {
1499
+ for (const raw of remaining.splice(0)) {
1500
+ const created = normalizeDirectory(
1501
+ {
1502
+ id: '',
1503
+ parentId: '',
1504
+ name: raw.name,
1505
+ order: directoryOrderByKey.get(raw.key) || 0,
1506
+ source: 'ai',
1507
+ menuPath: raw.menuPath,
1508
+ entryUrl: raw.entryUrl,
1509
+ evidence: [],
1510
+ },
1511
+ system.directories.length,
1512
+ );
1513
+ if (!created) continue;
1514
+ system.directories.push(created);
1515
+ keyToId.set(raw.key, created.id);
1516
+ directoriesApplied += 1;
1517
+ }
1518
+ }
1519
+ }
1520
+ const proposedIdsByParent = new Map();
1521
+ for (const raw of proposedDirectories) {
1522
+ const id = keyToId.get(raw.key);
1523
+ if (!id) continue;
1524
+ const parentKey = String(raw.parentKey || '');
1525
+ const list = proposedIdsByParent.get(parentKey) || [];
1526
+ list.push(id);
1527
+ proposedIdsByParent.set(parentKey, list);
1528
+ }
1529
+ for (const [parentKey, ids] of proposedIdsByParent) {
1530
+ const parentId = parentKey ? keyToId.get(parentKey) || '' : '';
1531
+ const ordered = ids.map((id) => findDirectory(system, id)).filter(Boolean);
1532
+ const proposedIds = new Set(ordered.map((item) => item.id));
1533
+ ordered.push(
1534
+ ...system.directories
1535
+ .filter((item) => item.parentId === parentId && !proposedIds.has(item.id))
1536
+ .sort((left, right) => left.order - right.order || left.name.localeCompare(right.name)),
1537
+ );
1538
+ ordered.forEach((item, order) => {
1539
+ item.order = order;
1540
+ });
1541
+ }
1542
+ let functionsApplied = 0;
1543
+ const proposedFunctions = Array.isArray(proposal.functions) ? proposal.functions : [];
1544
+ const functionOrderByDirectory = new Map();
1545
+ for (const raw of proposedFunctions) {
1546
+ const directoryKey = String(raw.directoryKey || '');
1547
+ const order = functionOrderByDirectory.get(directoryKey) || 0;
1548
+ raw.order = order;
1549
+ functionOrderByDirectory.set(directoryKey, order + 1);
1550
+ }
1551
+ for (const raw of proposedFunctions) {
1552
+ const directoryId = keyToId.get(raw.directoryKey) || '';
1553
+ const pathNames = directoryId
1554
+ ? (() => {
1555
+ const result = [];
1556
+ let current = findDirectory(system, directoryId);
1557
+ const visited = new Set();
1558
+ while (current && !visited.has(current.id)) {
1559
+ visited.add(current.id);
1560
+ result.unshift(current.name);
1561
+ current = current.parentId ? findDirectory(system, current.parentId) : null;
1562
+ }
1563
+ return result;
1564
+ })()
1565
+ : ['未归类'];
1566
+ const existing = system.functions.find(
1567
+ (item) =>
1568
+ item.directoryId === directoryId &&
1569
+ item.name.replace(/\s/g, '') === String(raw.name || '').replace(/\s/g, ''),
1570
+ );
1571
+ if (existing) {
1572
+ system.functions[system.functions.indexOf(existing)] = applyFunctionPatch(
1573
+ existing,
1574
+ {
1575
+ directoryId,
1576
+ purpose: raw.purpose,
1577
+ entry: raw.entry,
1578
+ evidence: raw.evidence,
1579
+ domain: pathNames[0] || '未归类',
1580
+ module: pathNames.at(-1) || '未归类',
1581
+ order: raw.order,
1582
+ },
1583
+ false,
1584
+ );
1585
+ } else {
1586
+ system.functions.push(
1587
+ makeFunction(system, {
1588
+ name: raw.name,
1589
+ directoryId,
1590
+ purpose: raw.purpose,
1591
+ entry: raw.entry,
1592
+ evidence: raw.evidence,
1593
+ domain: pathNames[0] || '未归类',
1594
+ module: pathNames.at(-1) || '未归类',
1595
+ order: raw.order,
1596
+ source: 'ai',
1597
+ confidence: 'medium',
1598
+ }),
1599
+ );
1600
+ }
1601
+ functionsApplied += 1;
1602
+ }
1603
+ const proposedFunctionsByDirectory = new Map();
1604
+ for (const raw of proposedFunctions) {
1605
+ const directoryId = keyToId.get(raw.directoryKey) || '';
1606
+ const list = proposedFunctionsByDirectory.get(directoryId) || [];
1607
+ list.push(String(raw.name || '').replace(/\s/g, ''));
1608
+ proposedFunctionsByDirectory.set(directoryId, list);
1609
+ }
1610
+ for (const [directoryId, names] of proposedFunctionsByDirectory) {
1611
+ const rank = new Map(names.map((name, order) => [name, order]));
1612
+ system.functions
1613
+ .filter((item) => item.directoryId === directoryId)
1614
+ .sort((left, right) => {
1615
+ const leftOrder = rank.get(left.name.replace(/\s/g, ''));
1616
+ const rightOrder = rank.get(right.name.replace(/\s/g, ''));
1617
+ if (leftOrder !== undefined || rightOrder !== undefined)
1618
+ return (leftOrder ?? Number.MAX_SAFE_INTEGER) - (rightOrder ?? Number.MAX_SAFE_INTEGER);
1619
+ return left.order - right.order || left.code.localeCompare(right.code);
1620
+ })
1621
+ .forEach((item, order) => {
1622
+ item.order = order;
1623
+ });
1624
+ }
1625
+ markSystemDirty(system);
1626
+ touchStore(store);
1627
+ const saved = writeStore(root, store);
1628
+ return {
1629
+ store: saved,
1630
+ applied: { directories: directoriesApplied, functions: functionsApplied, flows: 0 },
1631
+ };
1632
+ }
1633
+
1634
+ function applyAssistantFlowProposal(root, systemId, proposal, expectedRevision) {
1635
+ const store = readStore(root);
1636
+ requireRevision(store, expectedRevision);
1637
+ const system = requireSystem(store, systemId);
1638
+ let flowsApplied = 0;
1639
+ for (const raw of Array.isArray(proposal.flows) ? proposal.flows : []) {
1640
+ const steps = (Array.isArray(raw.steps) ? raw.steps : []).map((step) => ({
1641
+ ...step,
1642
+ functionId: system.functions.some((item) => item.id === step.functionId)
1643
+ ? step.functionId
1644
+ : '',
1645
+ }));
1646
+ const existing = system.flows.find(
1647
+ (item) => item.name.replace(/\s/g, '') === String(raw.name || '').replace(/\s/g, ''),
1648
+ );
1649
+ if (existing) {
1650
+ system.flows[system.flows.indexOf(existing)] = applyFlowPatch(existing, {
1651
+ name: raw.name,
1652
+ result: raw.result,
1653
+ steps,
1654
+ evidence: raw.evidence,
1655
+ status: steps.some((step) => step.branchBroken) ? '待补全' : '健康',
1656
+ });
1657
+ } else {
1658
+ system.flows.push(
1659
+ makeFlow(system, {
1660
+ name: raw.name,
1661
+ result: raw.result,
1662
+ steps,
1663
+ evidence: raw.evidence,
1664
+ }),
1665
+ );
1666
+ }
1667
+ flowsApplied += 1;
1668
+ }
1669
+ markSystemDirty(system);
1670
+ touchStore(store);
1671
+ const saved = writeStore(root, store);
1672
+ return { store: saved, applied: { directories: 0, functions: 0, flows: flowsApplied } };
1673
+ }
1674
+
1675
+ function parseSystemPayload(raw) {
1676
+ const name = text(raw?.name, 200);
1677
+ if (!name) throw Object.assign(new Error('系统名称不能为空'), { statusCode: 400 });
1678
+ return normalizeSystem({
1679
+ ...raw,
1680
+ id: '',
1681
+ name,
1682
+ functions: [],
1683
+ flows: [],
1684
+ proposals: [],
1685
+ createdAt: nowIso(),
1686
+ updatedAt: nowIso(),
1687
+ });
1688
+ }
1689
+
1690
+ function copySystemConfiguration(store, source) {
1691
+ const usedNames = new Set(store.systems.map((item) => item.name));
1692
+ const baseName = `${source.name}(副本)`;
1693
+ let name = baseName;
1694
+ let index = 2;
1695
+ while (usedNames.has(name)) {
1696
+ name = `${source.name}(副本 ${index})`;
1697
+ index += 1;
1698
+ }
1699
+ return normalizeSystem({
1700
+ name,
1701
+ description: source.description,
1702
+ entryUrl: source.entryUrl,
1703
+ sourceDir: source.sourceDir,
1704
+ loginState: '',
1705
+ docs: { ...source.docs },
1706
+ analysisScope: source.analysisScope,
1707
+ status: 'draft',
1708
+ publishedRevision: 0,
1709
+ lastAnalysis: null,
1710
+ directories: [],
1711
+ functions: [],
1712
+ flows: [],
1713
+ proposals: [],
1714
+ createdAt: nowIso(),
1715
+ updatedAt: nowIso(),
1716
+ });
1717
+ }
1718
+
1719
+ export function createBusinessAnalysisService(options = {}) {
1720
+ return createAnalysisService({
1721
+ readSystem(root, id) {
1722
+ return requireSystem(readStore(root), id);
1723
+ },
1724
+ prompt(root) {
1725
+ // 关联技能即使停用,也继续用已保存正文启动业务地图识别,避免任务因技能开关不可调用。
1726
+ return readPluginPrompt(BUSINESS_MAP_PROMPT_FILE, root);
1727
+ },
1728
+ commit(root, id, candidates, job) {
1729
+ const store = readStore(root),
1730
+ system = requireSystem(store, id);
1731
+ const result = { autoApplied: [], pending: 0, duplicates: 0 };
1732
+ const currentSignatures = new Set(
1733
+ system.proposals.map((item) => item.fingerprint).filter(Boolean),
1734
+ );
1735
+ for (const candidate of candidates) {
1736
+ if (currentSignatures.has(candidate.fingerprint)) {
1737
+ result.duplicates++;
1738
+ continue;
1739
+ }
1740
+ const name = text(candidate.payload?.name, 300);
1741
+ const existing = (
1742
+ candidate.targetType === 'function' ? system.functions : system.flows
1743
+ ).find((item) => item.name.replace(/\s/g, '') === name.replace(/\s/g, ''));
1744
+ let action = candidate.action,
1745
+ targetId = candidate.targetId;
1746
+ const currentTarget = (
1747
+ candidate.targetType === 'function' ? system.functions : system.flows
1748
+ ).find((item) => item.id === targetId);
1749
+ if (
1750
+ action === 'update' &&
1751
+ currentTarget &&
1752
+ Object.entries(candidate.payload).every(
1753
+ ([field, value]) => JSON.stringify(currentTarget[field]) === JSON.stringify(value),
1754
+ ) &&
1755
+ candidate.evidence.every((ref) =>
1756
+ currentTarget.evidence.some((item) => item.ref === ref.ref && item.note === ref.note),
1757
+ )
1758
+ ) {
1759
+ result.duplicates++;
1760
+ continue;
1761
+ }
1762
+
1763
+ if (action === 'add' && existing) {
1764
+ const sameEvidence = candidate.evidence.every((ref) =>
1765
+ existing.evidence.some((item) => item.ref === ref.ref && item.note === ref.note),
1766
+ );
1767
+ const samePayload = Object.entries(candidate.payload).every(
1768
+ ([field, value]) => JSON.stringify(existing[field]) === JSON.stringify(value),
1769
+ );
1770
+ if (sameEvidence && samePayload) {
1771
+ result.duplicates++;
1772
+ continue;
1773
+ }
1774
+ action = 'update';
1775
+ targetId = existing.id;
1776
+ }
1777
+ const proposal = normalizeProposal({
1778
+ ...candidate,
1779
+ action,
1780
+ targetId,
1781
+ analysisId: job.id,
1782
+ fingerprint: candidate.fingerprint,
1783
+ });
1784
+ if (!proposal) continue;
1785
+ if (
1786
+ candidate.autoEligible &&
1787
+ job.config.autoDraft &&
1788
+ action === 'add' &&
1789
+ candidate.targetType === 'function'
1790
+ ) {
1791
+ const created = makeFunction(system, {
1792
+ ...candidate.payload,
1793
+ source: 'ai',
1794
+ confirmed: false,
1795
+ evidence: candidate.evidence,
1796
+ confidence: 'high',
1797
+ });
1798
+ system.functions.push(created);
1799
+ proposal.status = 'applied';
1800
+ proposal.targetId = created.id;
1801
+ proposal.appliedAt = nowIso();
1802
+ result.autoApplied.push({ id: created.id, signature: hash(JSON.stringify(created)) });
1803
+ } else result.pending++;
1804
+ currentSignatures.add(candidate.fingerprint);
1805
+ system.proposals.push(proposal);
1806
+ }
1807
+ system.lastAnalysis = {
1808
+ at: nowIso(),
1809
+ status: job.issues.length ? 'partial' : 'done',
1810
+ pageCount: job.coverage.pages,
1811
+ docCount: job.coverage.documents,
1812
+ codeFileCount: job.coverage.codeFiles,
1813
+ summary: `实际采集 ${job.coverage.pages} 个页面、${job.coverage.documents} 份文档、${job.coverage.codeFiles} 个源码文件;自动新增 ${result.autoApplied.length} 个功能,${result.pending} 项待审核。`,
1814
+ };
1815
+ markSystemDirty(system);
1816
+ const saved = writeStore(root, store);
1817
+ const savedSystem = saved.systems.find((item) => item.id === id);
1818
+ for (const applied of result.autoApplied) {
1819
+ const created = savedSystem?.functions.find((item) => item.id === applied.id);
1820
+ if (created) applied.signature = hash(JSON.stringify(created));
1821
+ }
1822
+ return result;
1823
+ },
1824
+ rollback(root, id, job) {
1825
+ const store = readStore(root),
1826
+ system = requireSystem(store, id),
1827
+ removed = [],
1828
+ skipped = [];
1829
+ for (const item of job.result.autoApplied) {
1830
+ const fn = system.functions.find((fn) => fn.id === item.id);
1831
+ if (!fn) continue;
1832
+ if (
1833
+ hash(JSON.stringify(fn)) !== item.signature ||
1834
+ system.flows.some((flow) => flow.steps.some((step) => step.functionId === fn.id))
1835
+ ) {
1836
+ skipped.push(fn.id);
1837
+ continue;
1838
+ }
1839
+ system.functions = system.functions.filter((fn) => fn.id !== item.id);
1840
+ removed.push(item.id);
1841
+ for (const proposal of system.proposals)
1842
+ if (proposal.analysisId === job.id && proposal.targetId === item.id)
1843
+ proposal.status = 'ignored';
1844
+ }
1845
+ if (removed.length) {
1846
+ markSystemDirty(system);
1847
+ writeStore(root, store);
1848
+ }
1849
+ return { removed, skipped };
1850
+ },
1851
+ ...options,
1852
+ });
1853
+ }
1854
+
1855
+ /**
1856
+ * @returns {import('vite').Plugin}
1857
+ */
1858
+ export function lhBusinessMapPlugin(options = {}) {
1859
+ const analyses = createBusinessAnalysisService(options);
1860
+ const assistant = createBusinessAssistantService({
1861
+ pages: collectPages,
1862
+ applyDirectoryProposal: applyAssistantDirectoryProposal,
1863
+ applyFlowProposal: applyAssistantFlowProposal,
1864
+ });
1865
+ const login = createBusinessLoginService(options.login);
1866
+ const pickDirectory =
1867
+ typeof options.pickDirectory === 'function' ? options.pickDirectory : pickDirectoryResult;
1868
+ return {
1869
+ name: 'lh-business-map',
1870
+ configureServer(server) {
1871
+ server.httpServer?.once('close', () => {
1872
+ analyses.close();
1873
+ assistant.close();
1874
+ void login.close();
1875
+ });
1876
+ server.middlewares.use(async (req, res, next) => {
1877
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
1878
+ if (!parsed.pathname.startsWith(PREFIX)) return next();
1879
+ const root = getDataRoot();
1880
+ try {
1881
+ const tail = parsed.pathname.slice(PREFIX.length).replace(/^\/+|\/+$/g, '');
1882
+ const parts = tail ? tail.split('/') : [];
1883
+ const method = req.method || 'GET';
1884
+
1885
+ if (method === 'GET' && parsed.searchParams.get('health') === '1') {
1886
+ return sendJson(res, 200, {
1887
+ ok: true,
1888
+ file: businessMapFilePath(root),
1889
+ promptFile: BUSINESS_MAP_PROMPT_FILE,
1890
+ });
1891
+ }
1892
+
1893
+ if (method === 'GET' && tail === 'documents')
1894
+ return sendJson(res, 200, { ok: true, documents: documentCatalog(root) });
1895
+
1896
+ if (method === 'POST' && tail === 'pick-directory') {
1897
+ if (!isPluginOnInSpace('businessMap', root)) {
1898
+ return sendJson(res, 403, { ok: false, error: '请先开启业务地图插件' });
1899
+ }
1900
+ if (req.headers.origin && new URL(req.headers.origin).host !== req.headers.host) {
1901
+ return sendJson(res, 403, {
1902
+ ok: false,
1903
+ error: '选目录请求必须来自当前 Lantern 页面',
1904
+ });
1905
+ }
1906
+ const picked = await pickDirectory('选择业务系统源码目录');
1907
+ if (picked.error) return sendJson(res, 400, { ok: false, error: picked.error });
1908
+ if (picked.canceled) return sendJson(res, 200, { ok: true, canceled: true, dir: '' });
1909
+ return sendJson(res, 200, { ok: true, dir: picked.path || '' });
1910
+ }
1911
+
1912
+ if (method === 'GET' && tail === 'prompt') {
1913
+ if (isPluginOnInSpace('businessMap', root)) {
1914
+ ensurePluginPrompt(BUSINESS_MAP_PROMPT_FILE, BUSINESS_MAP_PROMPT_TEMPLATE, root);
1915
+ }
1916
+ const content = readPluginPrompt(BUSINESS_MAP_PROMPT_FILE, root);
1917
+ return sendJson(res, 200, {
1918
+ ok: true,
1919
+ file: BUSINESS_MAP_PROMPT_FILE,
1920
+ exists: Boolean(content.trim()),
1921
+ content,
1922
+ });
1923
+ }
1924
+
1925
+ if (method === 'POST' && tail === 'prompt/sync') {
1926
+ const body = JSON.parse((await readBody(req)) || '{}');
1927
+ if (body.enabled !== true) {
1928
+ return sendJson(res, 200, {
1929
+ ok: true,
1930
+ enabled: false,
1931
+ removed: false,
1932
+ file: BUSINESS_MAP_PROMPT_FILE,
1933
+ exists: Boolean(readPluginPrompt(BUSINESS_MAP_PROMPT_FILE, root).trim()),
1934
+ });
1935
+ }
1936
+ const out = ensurePluginPrompt(
1937
+ BUSINESS_MAP_PROMPT_FILE,
1938
+ BUSINESS_MAP_PROMPT_TEMPLATE,
1939
+ root,
1940
+ );
1941
+ return sendJson(res, 200, { ok: true, enabled: true, ...out });
1942
+ }
1943
+
1944
+ if (method === 'GET' && !tail) {
1945
+ return sendJson(res, 200, { ok: true, store: readStore(root) });
1946
+ }
1947
+
1948
+ if (method === 'POST' && tail === 'demo') {
1949
+ const store = readStore(root);
1950
+ requireRevision(store, Number(JSON.parse((await readBody(req)) || '{}').revision));
1951
+ const system = demoSystem();
1952
+ const existing = store.systems.findIndex((item) => item.name === system.name);
1953
+ if (existing >= 0) store.systems[existing] = system;
1954
+ else store.systems.push(system);
1955
+ touchStore(store);
1956
+ const saved = writeStore(root, store);
1957
+ return sendJson(res, 200, { ok: true, store: saved, systemId: system.id });
1958
+ }
1959
+
1960
+ if (method === 'POST' && tail === 'systems') {
1961
+ const body = JSON.parse((await readBody(req)) || '{}');
1962
+ const store = readStore(root);
1963
+ requireRevision(store, body.revision);
1964
+ const system = parseSystemPayload(body.system || body);
1965
+ store.systems.push(system);
1966
+ touchStore(store);
1967
+ const saved = writeStore(root, store);
1968
+ return sendJson(res, 200, { ok: true, store: saved, systemId: system.id });
1969
+ }
1970
+
1971
+ if (parts[0] !== 'systems' || !parts[1]) {
1972
+ return sendJson(res, 404, { ok: false, error: '接口不存在' });
1973
+ }
1974
+
1975
+ const systemId = parts[1];
1976
+ const store = readStore(root);
1977
+ const system = requireSystem(store, systemId);
1978
+ if (parts[2] === 'materials') {
1979
+ if (!isPluginOnInSpace('businessMap', root))
1980
+ return sendJson(res, 403, { ok: false, error: '请先开启业务地图插件' });
1981
+ if (req.headers.origin && new URL(req.headers.origin).host !== req.headers.host)
1982
+ return sendJson(res, 403, {
1983
+ ok: false,
1984
+ error: '资料上传必须来自当前 Lantern 页面',
1985
+ });
1986
+ if (method === 'GET' && parts.length === 3)
1987
+ return sendJson(res, 200, {
1988
+ ok: true,
1989
+ materials: businessMaterialCatalog(root, systemId),
1990
+ });
1991
+ if (method === 'POST' && parts.length === 3) {
1992
+ const name = String(parsed.searchParams.get('name') || '').trim();
1993
+ const buffer = await readBodyBuffer(req);
1994
+ const item = saveBusinessMaterial(root, systemId, name, buffer);
1995
+ return sendJson(res, 201, { ok: true, material: item });
1996
+ }
1997
+ if (method === 'DELETE' && parts.length === 3) {
1998
+ const name = String(parsed.searchParams.get('name') || '').trim();
1999
+ removeBusinessMaterial(root, systemId, name);
2000
+ return sendJson(res, 200, { ok: true });
2001
+ }
2002
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
2003
+ }
2004
+ const body = ['POST', 'PUT', 'DELETE'].includes(method)
2005
+ ? JSON.parse((await readBody(req)) || '{}')
2006
+ : {};
2007
+ if (method === 'POST' && parts[2] === 'copy' && parts.length === 3) {
2008
+ requireRevision(store, body.revision);
2009
+ const loginCopyMode = body.loginCopyMode || 'credentials';
2010
+ if (!['credentials', 'configuration', 'none'].includes(loginCopyMode))
2011
+ throw Object.assign(new Error('登录配置复制方式无效'), { statusCode: 400 });
2012
+ const copy = copySystemConfiguration(store, system);
2013
+ if (loginCopyMode !== 'none') {
2014
+ login.copyConfig(root, system, copy, {
2015
+ copyCredentials: loginCopyMode === 'credentials',
2016
+ });
2017
+ }
2018
+ let saved;
2019
+ try {
2020
+ store.systems.push(copy);
2021
+ touchStore(store);
2022
+ saved = writeStore(root, store);
2023
+ } catch (error) {
2024
+ await login.remove(root, copy);
2025
+ throw error;
2026
+ }
2027
+ return sendJson(res, 200, { ok: true, store: saved, systemId: copy.id });
2028
+ }
2029
+ if (parts[2] === 'login') {
2030
+ if (!isPluginOnInSpace('businessMap', root))
2031
+ return sendJson(res, 403, { ok: false, error: '请先开启业务地图插件' });
2032
+ if (req.headers.origin && new URL(req.headers.origin).host !== req.headers.host)
2033
+ return sendJson(res, 403, { ok: false, error: '登录请求必须来自当前 Lantern 页面' });
2034
+ res.setHeader('Cache-Control', 'no-store');
2035
+ const action = parts[3];
2036
+ if (method === 'GET' && !action)
2037
+ return sendJson(res, 200, { ok: true, ...login.status(root, system) });
2038
+ if (method === 'PUT' && !action)
2039
+ return sendJson(res, 200, { ok: true, ...login.save(root, system, body) });
2040
+ if (method === 'POST' && ['start', 'complete', 'cancel'].includes(action))
2041
+ return sendJson(res, 200, { ok: true, ...(await login[action](root, system, body)) });
2042
+ return sendJson(res, 404, { ok: false, error: '登录接口不存在' });
2043
+ }
2044
+ if (parts[2] === 'assistant') {
2045
+ const action = parts[3];
2046
+ if (method === 'GET' && !action)
2047
+ return sendJson(res, 200, { ok: true, session: assistant.get(root, system) });
2048
+ if (method === 'GET' && action === 'events') {
2049
+ const after = Number(parsed.searchParams.get('after') || 0);
2050
+ return assistant.subscribe(root, system, after, res);
2051
+ }
2052
+ if (method === 'POST' && action === 'messages') {
2053
+ requireRevision(store, body.revision);
2054
+ return sendJson(res, 202, {
2055
+ ok: true,
2056
+ session: assistant.start(root, system, body, body.settings),
2057
+ });
2058
+ }
2059
+ if (method === 'POST' && action === 'stop')
2060
+ return sendJson(res, 200, { ok: true, session: assistant.stop(root, system) });
2061
+ if (method === 'POST' && action === 'reset')
2062
+ return sendJson(res, 200, { ok: true, session: assistant.reset(root, system) });
2063
+ if (method === 'POST' && action === 'apply') {
2064
+ requireRevision(store, body.revision);
2065
+ const result = await assistant.apply(root, system, body);
2066
+ return sendJson(res, 200, { ok: true, ...result });
2067
+ }
2068
+ return sendJson(res, 404, { ok: false, error: 'AI 会话接口不存在' });
2069
+ }
2070
+ if (parts[2] === 'analyses') {
2071
+ const id = parts[3],
2072
+ command = parts[4];
2073
+ if (method === 'GET' && !id)
2074
+ return sendJson(res, 200, { ok: true, jobs: analyses.list(root, systemId) });
2075
+ if (method === 'GET' && id)
2076
+ return sendJson(res, 200, { ok: true, job: analyses.get(root, systemId, id) });
2077
+ if (method === 'POST' && !id) {
2078
+ requireRevision(store, body.revision);
2079
+ return sendJson(res, 202, {
2080
+ ok: true,
2081
+ job: analyses.start(root, system, body.config || {}, body.settings),
2082
+ });
2083
+ }
2084
+ if (method === 'POST' && id && command === 'cancel')
2085
+ return sendJson(res, 200, { ok: true, job: analyses.cancel(root, systemId, id) });
2086
+ if (method === 'POST' && id && command === 'retry')
2087
+ return sendJson(res, 202, {
2088
+ ok: true,
2089
+ job: analyses.retry(root, systemId, id, body.settings),
2090
+ });
2091
+ if (method === 'POST' && id && command === 'rollback')
2092
+ return sendJson(res, 200, { ok: true, job: analyses.rollback(root, systemId, id) });
2093
+ return sendJson(res, 404, { ok: false, error: '任务接口不存在' });
2094
+ }
2095
+ requireRevision(store, body.revision);
2096
+
2097
+ if (method === 'PUT' && parts.length === 2) {
2098
+ const patch = body.system || body;
2099
+ if (
2100
+ patch.entryUrl !== undefined &&
2101
+ patch.entryUrl !== system.entryUrl &&
2102
+ !sameOrigin(patch.entryUrl, system.entryUrl)
2103
+ )
2104
+ await login.invalidate(root, system);
2105
+ const normalized = normalizeSystem({ ...system, ...patch, id: system.id });
2106
+ Object.assign(system, normalized, {
2107
+ directories: system.directories,
2108
+ functions: system.functions,
2109
+ flows: system.flows,
2110
+ proposals: system.proposals,
2111
+ });
2112
+ markSystemDirty(system);
2113
+ touchStore(store);
2114
+ const saved = writeStore(root, store);
2115
+ return sendJson(res, 200, { ok: true, store: saved, systemId });
2116
+ }
2117
+
2118
+ if (method === 'DELETE' && parts.length === 2) {
2119
+ await login.remove(root, system);
2120
+ assistant.remove(root, systemId);
2121
+ fs.rmSync(businessMaterialDir(root, systemId), { recursive: true, force: true });
2122
+ store.systems = store.systems.filter((item) => item.id !== systemId);
2123
+ touchStore(store);
2124
+ const saved = writeStore(root, store);
2125
+ return sendJson(res, 200, { ok: true, store: saved });
2126
+ }
2127
+
2128
+ if (parts[2] === 'directories') {
2129
+ if (method === 'POST' && parts.length === 3) {
2130
+ const directory = makeDirectory(system, body.directory || body);
2131
+ system.directories.push(directory);
2132
+ normalizeDirectoryOrders(system, directory.parentId);
2133
+ markSystemDirty(system);
2134
+ touchStore(store);
2135
+ return sendJson(res, 200, {
2136
+ ok: true,
2137
+ store: writeStore(root, store),
2138
+ directory,
2139
+ });
2140
+ }
2141
+ const directoryId = parts[3];
2142
+ const directory = findDirectory(system, directoryId);
2143
+ if (!directory) return sendJson(res, 404, { ok: false, error: '目录不存在' });
2144
+ if (method === 'PUT') {
2145
+ const previousParentId = directory.parentId;
2146
+ const updated = applyDirectoryPatch(system, directory, body.directory || body);
2147
+ const index = system.directories.findIndex((item) => item.id === directory.id);
2148
+ system.directories[index] = updated;
2149
+ normalizeDirectoryOrders(system, previousParentId);
2150
+ normalizeDirectoryOrders(system, updated.parentId);
2151
+ markSystemDirty(system);
2152
+ touchStore(store);
2153
+ return sendJson(res, 200, {
2154
+ ok: true,
2155
+ store: writeStore(root, store),
2156
+ directory: updated,
2157
+ });
2158
+ }
2159
+ if (method === 'DELETE') {
2160
+ const impact = directoryDeleteImpact(system, directoryId);
2161
+ if (impact.directories > 1 || impact.functions > 0) {
2162
+ if (body.cascade !== true) {
2163
+ return sendJson(res, 409, {
2164
+ ok: false,
2165
+ code: 'directory_not_empty',
2166
+ error: '目录下仍有子目录或功能,确认后需显式级联删除',
2167
+ impact: {
2168
+ directories: impact.directories,
2169
+ functions: impact.functions,
2170
+ flows: impact.flows,
2171
+ },
2172
+ });
2173
+ }
2174
+ }
2175
+ system.directories = system.directories.filter(
2176
+ (item) => !impact.directoryIds.has(item.id),
2177
+ );
2178
+ system.functions = system.functions.filter(
2179
+ (item) => !impact.functionIds.has(item.id),
2180
+ );
2181
+ for (const flow of system.flows) {
2182
+ for (const step of flow.steps) {
2183
+ if (impact.functionIds.has(step.functionId)) step.functionId = '';
2184
+ }
2185
+ }
2186
+ normalizeDirectoryOrders(system, directory.parentId);
2187
+ markSystemDirty(system);
2188
+ touchStore(store);
2189
+ return sendJson(res, 200, {
2190
+ ok: true,
2191
+ store: writeStore(root, store),
2192
+ impact: {
2193
+ directories: impact.directories,
2194
+ functions: impact.functions,
2195
+ flows: impact.flows,
2196
+ },
2197
+ });
2198
+ }
2199
+ }
2200
+
2201
+ if (method === 'POST' && parts[2] === 'tree' && parts[3] === 'move') {
2202
+ const kind = body.kind === 'function' ? 'function' : 'directory';
2203
+ const id = text(body.id, 64);
2204
+ const parentId = text(body.parentId, 64);
2205
+ const beforeId = text(body.beforeId, 64);
2206
+ if (kind === 'directory') {
2207
+ const directory = findDirectory(system, id);
2208
+ if (!directory) return sendJson(res, 404, { ok: false, error: '目录不存在' });
2209
+ assertDirectoryParent(system, id, parentId);
2210
+ const previousParentId = directory.parentId;
2211
+ directory.parentId = parentId;
2212
+ const siblings = system.directories
2213
+ .filter((item) => item.parentId === parentId && item.id !== id)
2214
+ .sort((left, right) => left.order - right.order);
2215
+ const beforeIndex = beforeId
2216
+ ? siblings.findIndex((item) => item.id === beforeId)
2217
+ : -1;
2218
+ siblings.splice(beforeIndex >= 0 ? beforeIndex : siblings.length, 0, directory);
2219
+ siblings.forEach((item, index) => {
2220
+ item.order = index;
2221
+ });
2222
+ normalizeDirectoryOrders(system, previousParentId);
2223
+ normalizeDirectoryOrders(system, parentId);
2224
+ } else {
2225
+ const fn = system.functions.find((item) => item.id === id);
2226
+ if (!fn) return sendJson(res, 404, { ok: false, error: '功能不存在' });
2227
+ if (parentId && !findDirectory(system, parentId)) {
2228
+ return sendJson(res, 400, { ok: false, error: '目标目录不存在' });
2229
+ }
2230
+ const previousDirectoryId = fn.directoryId;
2231
+ fn.directoryId = parentId;
2232
+ const siblings = system.functions
2233
+ .filter((item) => item.directoryId === parentId && item.id !== id)
2234
+ .sort(
2235
+ (left, right) => left.order - right.order || left.code.localeCompare(right.code),
2236
+ );
2237
+ const beforeIndex = beforeId
2238
+ ? siblings.findIndex((item) => item.id === beforeId)
2239
+ : -1;
2240
+ siblings.splice(beforeIndex >= 0 ? beforeIndex : siblings.length, 0, fn);
2241
+ siblings.forEach((item, index) => {
2242
+ item.order = index;
2243
+ });
2244
+ normalizeFunctionOrders(system, previousDirectoryId);
2245
+ normalizeFunctionOrders(system, parentId);
2246
+ }
2247
+ markSystemDirty(system);
2248
+ touchStore(store);
2249
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store) });
2250
+ }
2251
+
2252
+ if (parts[2] === 'functions') {
2253
+ if (method === 'POST' && parts.length === 3) {
2254
+ const fn = makeFunction(system, body.function || body);
2255
+ system.functions.push(fn);
2256
+ normalizeFunctionOrders(system, fn.directoryId);
2257
+ markSystemDirty(system);
2258
+ touchStore(store);
2259
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store), item: fn });
2260
+ }
2261
+ const functionId = parts[3];
2262
+ const index = system.functions.findIndex((item) => item.id === functionId);
2263
+ if (index < 0) return sendJson(res, 404, { ok: false, error: '功能不存在' });
2264
+ if (method === 'PUT') {
2265
+ const current = system.functions[index];
2266
+ const patch = body.function || body;
2267
+ const nextDirectoryId =
2268
+ patch.directoryId === undefined ? current.directoryId : text(patch.directoryId, 64);
2269
+ if (nextDirectoryId && !findDirectory(system, nextDirectoryId)) {
2270
+ return sendJson(res, 400, { ok: false, error: '所属目录不存在' });
2271
+ }
2272
+ const oldDirectoryId = current.directoryId;
2273
+ const nextPatch = { ...patch };
2274
+ if (nextDirectoryId !== oldDirectoryId && nextPatch.order === undefined) {
2275
+ nextPatch.order = system.functions.filter(
2276
+ (item) => item.id !== current.id && item.directoryId === nextDirectoryId,
2277
+ ).length;
2278
+ }
2279
+ system.functions[index] = applyFunctionPatch(current, nextPatch, true);
2280
+ normalizeFunctionOrders(system, oldDirectoryId);
2281
+ normalizeFunctionOrders(system, nextDirectoryId);
2282
+ markSystemDirty(system);
2283
+ touchStore(store);
2284
+ return sendJson(res, 200, {
2285
+ ok: true,
2286
+ store: writeStore(root, store),
2287
+ item: system.functions[index],
2288
+ });
2289
+ }
2290
+ if (method === 'DELETE') {
2291
+ system.functions.splice(index, 1);
2292
+ for (const flow of system.flows) {
2293
+ for (const step of flow.steps) {
2294
+ if (step.functionId === functionId) step.functionId = '';
2295
+ }
2296
+ }
2297
+ markSystemDirty(system);
2298
+ touchStore(store);
2299
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store) });
2300
+ }
2301
+ }
2302
+
2303
+ if (parts[2] === 'flows') {
2304
+ if (method === 'POST' && parts.length === 3) {
2305
+ const flow = makeFlow(system, body.flow || body);
2306
+ system.flows.push(flow);
2307
+ markSystemDirty(system);
2308
+ touchStore(store);
2309
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store), item: flow });
2310
+ }
2311
+ const flowId = parts[3];
2312
+ const index = system.flows.findIndex((item) => item.id === flowId);
2313
+ if (index < 0) return sendJson(res, 404, { ok: false, error: '流程不存在' });
2314
+ if (method === 'PUT') {
2315
+ system.flows[index] = applyFlowPatch(system.flows[index], body.flow || body);
2316
+ markSystemDirty(system);
2317
+ touchStore(store);
2318
+ return sendJson(res, 200, {
2319
+ ok: true,
2320
+ store: writeStore(root, store),
2321
+ item: system.flows[index],
2322
+ });
2323
+ }
2324
+ if (method === 'DELETE') {
2325
+ system.flows.splice(index, 1);
2326
+ markSystemDirty(system);
2327
+ touchStore(store);
2328
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store) });
2329
+ }
2330
+ }
2331
+
2332
+ if (method === 'POST' && parts[2] === 'analyze') {
2333
+ if (system.id !== 'demo_work_order') {
2334
+ return sendJson(res, 501, {
2335
+ ok: false,
2336
+ code: 'use_analysis_tasks',
2337
+ error: '请使用 /analyses 后台识别任务接口;旧 /analyze 仅保留工单示例兼容演示。',
2338
+ });
2339
+ }
2340
+ const sources = body.sources && typeof body.sources === 'object' ? body.sources : {};
2341
+ const requestedSourceDir = text(sources.code?.sourceDir, 2000);
2342
+ const requestedPageScope = text(sources.page?.scope, 1000);
2343
+ if (requestedSourceDir) system.sourceDir = requestedSourceDir;
2344
+ if (requestedPageScope) system.analysisScope = requestedPageScope;
2345
+ const docs = sources.doc?.enabled ? inspectDocSources(root) : { count: 0, items: [] };
2346
+ const code =
2347
+ sources.code?.enabled && system.sourceDir
2348
+ ? inspectTextFiles(system.sourceDir)
2349
+ : { count: 0, examples: [] };
2350
+ // 尚未接通页面采集,不把客户端传入的数量当作真实读取结果。
2351
+ const pageCount = 0;
2352
+ system.proposals = [
2353
+ ...system.proposals.filter((item) => item.status === 'pending'),
2354
+ ...analysisProposals(system, {
2355
+ page: sources.page,
2356
+ stats: { docCount: docs.count, codeFileCount: code.count },
2357
+ }),
2358
+ ];
2359
+ system.lastAnalysis = {
2360
+ at: nowIso(),
2361
+ status: 'demo',
2362
+ pageCount,
2363
+ docCount: docs.count,
2364
+ codeFileCount: code.count,
2365
+ summary: `示例演示:发现 ${docs.count} 份文档和 ${code.count} 个源码文件,生成 ${system.proposals.filter((item) => item.status === 'pending').length} 项固定示例提案,未执行页面探索或模型分析。`,
2366
+ };
2367
+ markSystemDirty(system);
2368
+ touchStore(store);
2369
+ return sendJson(res, 200, {
2370
+ ok: true,
2371
+ store: writeStore(root, store),
2372
+ system,
2373
+ sourceStats: { docs, code },
2374
+ });
2375
+ }
2376
+
2377
+ if (method === 'POST' && parts[2] === 'proposals' && parts[3] === 'apply') {
2378
+ const ids = new Set(stringList(body.ids, 200, 64));
2379
+ if (!ids.size) return sendJson(res, 400, { ok: false, error: '至少选择一项提案' });
2380
+ for (const proposal of system.proposals) {
2381
+ if (ids.has(proposal.id) && proposal.status === 'pending')
2382
+ applyProposal(system, proposal);
2383
+ }
2384
+ markSystemDirty(system);
2385
+ touchStore(store);
2386
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store), system });
2387
+ }
2388
+
2389
+ if (method === 'POST' && parts[2] === 'proposals' && parts[3] === 'ignore') {
2390
+ const ids = new Set(stringList(body.ids, 200, 64));
2391
+ for (const proposal of system.proposals) {
2392
+ if (ids.has(proposal.id) && proposal.status === 'pending')
2393
+ proposal.status = 'ignored';
2394
+ }
2395
+ markSystemDirty(system);
2396
+ touchStore(store);
2397
+ return sendJson(res, 200, { ok: true, store: writeStore(root, store), system });
2398
+ }
2399
+
2400
+ if (method === 'POST' && parts[2] === 'publish') {
2401
+ const check = validateForPublish(system);
2402
+ if (!check.ok) return sendJson(res, 409, { ok: false, error: '发布检查未通过', check });
2403
+ system.status = 'published';
2404
+ system.publishedRevision = store.revision + 1;
2405
+ system.updatedAt = nowIso();
2406
+ touchStore(store);
2407
+ const saved = writeStore(root, store);
2408
+ return sendJson(res, 200, { ok: true, store: saved, check });
2409
+ }
2410
+
2411
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
2412
+ } catch (error) {
2413
+ return sendJson(res, Number(error?.statusCode) || 500, {
2414
+ ok: false,
2415
+ code: text(error?.code, 80),
2416
+ error: String(error?.message ?? error),
2417
+ });
2418
+ }
2419
+ });
2420
+ },
2421
+ };
2422
+ }
2423
+
2424
+ export const BUSINESS_MAP_FILE = `${DIR_NAME}/${FILE_NAME}`;
2425
+ export function businessMapPromptPath(spaceDir) {
2426
+ const dir = resolveContentRoot(spaceDir, '提示词管理').abs;
2427
+ return path.join(dir, BUSINESS_MAP_PROMPT_FILE);
2428
+ }
2429
+ export function validateBusinessMapSystem(system) {
2430
+ return validateForPublish(normalizeSystem(system));
2431
+ }