lantern-harness 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +7 -7
  3. package/builtin/case-backup-contract.mjs +27 -0
  4. package/builtin/case-workflow-contract.mjs +158 -0
  5. package/builtin/session/lh-nav-groups.mjs +33 -1
  6. package/builtin/session/space-layout.mjs +8 -1
  7. package/builtin/session/space-skills.mjs +8 -1
  8. package/cli/mcp-server.mjs +986 -32
  9. package/cli/server.mjs +2 -0
  10. package/dist/500.html +9 -4
  11. package/dist/_astro/Base.BQf1tZMl.css +1 -0
  12. package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js → Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js} +1 -1
  13. package/dist/_astro/{BusinessMapBoard.mRxl2G3D.js → BusinessMapBoard.CYxHcku_.js} +1 -1
  14. package/dist/_astro/{CaseExecBoard.Cqkxuf5c.js → CaseExecBoard.CK9aGPmH.js} +1 -1
  15. package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
  16. package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
  17. package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
  18. package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
  19. package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
  20. package/dist/_astro/{DashboardBoard.CAJVE2G4.js → DashboardBoard.qgc1s7pG.js} +1 -1
  21. package/dist/_astro/{DefectSubmitEntry.BzKXJ-zq.js → DefectSubmitEntry.JI85N1-i.js} +1 -1
  22. package/dist/_astro/{DocsFileBrowser.apKMbGVf.js → DocsFileBrowser.z5JZ74cy.js} +1 -1
  23. package/dist/_astro/{DocsPager.DMN9-Tjg.js → DocsPager.Dg765uHW.js} +1 -1
  24. package/dist/_astro/{KnowledgeLibrary.BcoMQeUd.js → KnowledgeLibrary.mkShtVun.js} +1 -1
  25. package/dist/_astro/{LifeKrTasksBoard.DJU0-QI-.js → LifeKrTasksBoard.DpAwQffE.js} +1 -1
  26. package/dist/_astro/{LifeKrTodosBoard.GK7KRAO3.js → LifeKrTodosBoard.BIjPiZ8H.js} +1 -1
  27. package/dist/_astro/{LifeObjectivesBoard.DuKa6Q3k.js → LifeObjectivesBoard.DYwLHPEG.js} +1 -1
  28. package/dist/_astro/{LifePlanTypeSelect.Cm2lUmnH.js → LifePlanTypeSelect.CYaziESp.js} +1 -1
  29. package/dist/_astro/{LifeReviewsBoard.BWOOVMtz.js → LifeReviewsBoard.DIxoWBDA.js} +1 -1
  30. package/dist/_astro/{LifeShared.bY2l01Ha.js → LifeShared.DuFQsMEx.js} +1 -1
  31. package/dist/_astro/{LifeStagesBoard.CIzxPOJB.js → LifeStagesBoard.DtOri9EW.js} +1 -1
  32. package/dist/_astro/{LifeYearCycleSelect.BlsyPmmI.js → LifeYearCycleSelect.ByJ9-PGg.js} +1 -1
  33. package/dist/_astro/{LifeYearPlansBoard.DaA9O08j.js → LifeYearPlansBoard.BQN07wcv.js} +1 -1
  34. package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
  35. package/dist/_astro/{PluginsPage.B063QIlQ.js → PluginsPage.B1VeDtLx.js} +2 -2
  36. package/dist/_astro/{PmBugsBoard.Cu-v0Gfd.js → PmBugsBoard.Ddl3kqqt.js} +1 -1
  37. package/dist/_astro/{PmIterationsBoard.CgRzkP-j.js → PmIterationsBoard.BJN7disI.js} +1 -1
  38. package/dist/_astro/{PmProjectDetail.DVCEh0Lm.js → PmProjectDetail.D78gWhqk.js} +1 -1
  39. package/dist/_astro/{PmProjectsBoard.z-bQa98r.js → PmProjectsBoard.Bf8VB3t6.js} +1 -1
  40. package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
  41. package/dist/_astro/{PmRequirementsBoard.CyfBI0u_.js → PmRequirementsBoard.DarfGIrL.js} +1 -1
  42. package/dist/_astro/{PmShared.BQVzwsiz.js → PmShared.TOjBbtV8.js} +1 -1
  43. package/dist/_astro/{ReportsPage.najSzJeT.js → ReportsPage.BXGduuY3.js} +1 -1
  44. package/dist/_astro/{ReqAnalysisBoard.BQb8dHFD.js → ReqAnalysisBoard.WLtIfBg8.js} +1 -1
  45. package/dist/_astro/{RequirementBreakdownLibrary.Cn6OV6xt.js → RequirementBreakdownLibrary.DMoeTeqX.js} +1 -1
  46. package/dist/_astro/{RequirementsLibrary.CqKNFVsP.js → RequirementsLibrary.Iv7zOqWe.js} +1 -1
  47. package/dist/_astro/{SettingsDialog.db3BpFw0.js → SettingsDialog.BvDU9EU6.js} +1 -1
  48. package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
  49. package/dist/_astro/{SpaceSwitcher.DSUVAPOi.js → SpaceSwitcher.D9bBNQBZ.js} +1 -1
  50. package/dist/_astro/{TableFieldConfig.72AL-8p-.js → TableFieldConfig.DHj25OKN.js} +1 -1
  51. package/dist/_astro/{TasksBoard.CCDhCSR7.js → TasksBoard.CXmGdylV.js} +1 -1
  52. package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
  53. package/dist/_astro/{TestReportsLibrary.fWiEyCRx.js → TestReportsLibrary.BBC1TYgP.js} +1 -1
  54. package/dist/_astro/{TestStatsBoard.BSUBsWSu.js → TestStatsBoard.VXjP4hu6.js} +1 -1
  55. package/dist/_astro/{TodosBoard.By5YdlUe.js → TodosBoard.-yKgp06M.js} +1 -1
  56. package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
  57. package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
  58. package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
  59. package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
  60. package/dist/_astro/app-config.BSO5r82v.js +1 -0
  61. package/dist/_astro/app-version.CkDFkv4s.js +1 -0
  62. package/dist/_astro/{bash-tools.CS2w8LOb.js → bash-tools.C4DJiRJs.js} +1 -1
  63. package/dist/_astro/case-fields.C03NY3zC.js +148 -0
  64. package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
  65. package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
  66. package/dist/_astro/{case-review.DFWZkoR9.js → case-review.BodP2jKm.js} +1 -1
  67. package/dist/_astro/{case-template.Clb7HrDB.js → case-template.CC2eXegU.js} +2 -2
  68. package/dist/_astro/case-types.BjF1BivA.js +1 -0
  69. package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
  70. package/dist/_astro/{defect-workbench.CjTb4FDv.js → defect-workbench.DBmohR-y.js} +1 -1
  71. package/dist/_astro/{hydrate-cache.O4CIma9y.js → hydrate-cache.CMMErx63.js} +1 -1
  72. package/dist/_astro/{i18n.Cp4so7KR.js → i18n.CEWjL5GX.js} +2 -2
  73. package/dist/_astro/{open-docs-in-session.BpcAcBSI.js → open-docs-in-session.BoyV6R2A.js} +1 -1
  74. package/dist/_astro/plugins.ChGmBEkF.js +1 -0
  75. package/dist/_astro/{project-docs.bB9lQ1Ki.js → project-docs.BRgNjXhG.js} +1 -1
  76. package/dist/_astro/{req-analysis.C_gARMrB.js → req-analysis.BLvcktvQ.js} +1 -1
  77. package/dist/_astro/{settings.D02wZj3w.js → settings.BojKNwUC.js} +2 -2
  78. package/dist/_astro/{spaces-client.BAtG6PkW.js → spaces-client.B28rzu8J.js} +1 -1
  79. package/dist/_astro/{story-review.DTN91Vl9.js → story-review.dEBWTeOW.js} +1 -1
  80. package/dist/_astro/{test-points.C7ZgggQT.js → test-points.BuNgdNcU.js} +1 -1
  81. package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
  82. package/dist/_astro/{view-prefs.COAKEQtZ.js → view-prefs.CWc5cQ2q.js} +1 -1
  83. package/dist/business-map/index.html +10 -5
  84. package/dist/case-exec/index.html +10 -5
  85. package/dist/case-execution/index.html +10 -5
  86. package/dist/cases/api/index.html +988 -0
  87. package/dist/cases/automation/index.html +988 -0
  88. package/dist/cases/functional/index.html +988 -0
  89. package/dist/cases/generate/index.html +10 -5
  90. package/dist/cases/index.html +1 -1
  91. package/dist/cases/library/index.html +1 -983
  92. package/dist/cases/other/index.html +988 -0
  93. package/dist/cases/performance/index.html +988 -0
  94. package/dist/dashboard/index.html +10 -5
  95. package/dist/defect-rules/index.html +10 -5
  96. package/dist/defect-submit/index.html +10 -5
  97. package/dist/defect-submit/templates/index.html +10 -5
  98. package/dist/docs/changelog/index.html +88 -58
  99. package/dist/docs/install/index.html +12 -6
  100. package/dist/docs/manual/index.html +42 -31
  101. package/dist/knowledge/index.html +10 -5
  102. package/dist/life/kr-tasks/index.html +10 -5
  103. package/dist/life/kr-todos/index.html +10 -5
  104. package/dist/life/objectives/index.html +10 -5
  105. package/dist/life/reviews/index.html +10 -5
  106. package/dist/life/stages/index.html +10 -5
  107. package/dist/life/year-plans/index.html +10 -5
  108. package/dist/plugins/index.html +10 -5
  109. package/dist/pm/bugs/index.html +10 -5
  110. package/dist/pm/iterations/index.html +10 -5
  111. package/dist/pm/projects/detail/index.html +10 -5
  112. package/dist/pm/projects/index.html +10 -5
  113. package/dist/pm/requirements/index.html +10 -5
  114. package/dist/reports/index.html +10 -5
  115. package/dist/requirement-analysis/index.html +10 -5
  116. package/dist/requirement-breakdowns/index.html +10 -5
  117. package/dist/requirements/index.html +10 -5
  118. package/dist/tasks/index.html +10 -5
  119. package/dist/templates/index.html +10 -5
  120. package/dist/test-automation/index.html +10 -5
  121. package/dist/test-automation/projects/index.html +10 -5
  122. package/dist/test-reports/index.html +10 -5
  123. package/dist/test-stats/index.html +10 -5
  124. package/dist/todos/index.html +10 -5
  125. package/dist/workbench/index.html +10 -5
  126. package/docs/Codex-MCP/351/233/206/346/210/220.md +97 -53
  127. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +7 -1
  128. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +1 -1
  129. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +4 -2
  130. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +43 -36
  131. package/lh-plugins/case-automation/service.mjs +921 -0
  132. package/lh-plugins/case-automation/store.mjs +231 -0
  133. package/lh-plugins/case-automation/tables.mjs +115 -0
  134. package/lh-plugins/case-automation-prompt.mjs +57 -0
  135. package/lh-plugins/case-execution/assets.mjs +180 -0
  136. package/lh-plugins/case-execution/files.mjs +67 -15
  137. package/lh-plugins/case-execution/plans.mjs +318 -0
  138. package/lh-plugins/case-execution/service.mjs +80 -13
  139. package/lh-plugins/case-execution-prompt.mjs +4 -1
  140. package/lh-plugins/lh-case-automation.mjs +169 -0
  141. package/lh-plugins/lh-case-design.mjs +456 -0
  142. package/lh-plugins/lh-case-execution.mjs +53 -1
  143. package/lh-plugins/lh-case-review.mjs +29 -11
  144. package/lh-plugins/lh-project-docs.mjs +24 -0
  145. package/lh-plugins/lh-uiauto.mjs +111 -2
  146. package/lh-plugins/plugin-prompts.mjs +1 -0
  147. package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
  148. package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
  149. package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
  150. package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
  151. package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
  152. package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
  153. package/lh-plugins/uiauto-explorer/runner.mjs +65 -3
  154. package/lh-plugins/uiauto-explorer/sessions.mjs +29 -1
  155. package/package.json +1 -1
  156. package/skills/case-automation-bridge/SKILL.md +27 -0
  157. package/skills/case-execution/SKILL.md +11 -0
  158. package/skills/lantern-workflow/SKILL.md +39 -1
  159. package/dist/_astro/Base.Du_-4L-4.css +0 -1
  160. package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +0 -5
  161. package/dist/_astro/CaseGenerateApp.acgnxl79.js +0 -10
  162. package/dist/_astro/CasesLibrary.zmzOQwdn.js +0 -21
  163. package/dist/_astro/ChatApp.Ben9LFra.js +0 -1
  164. package/dist/_astro/ChatApp.DBi6q7Qv.js +0 -262
  165. package/dist/_astro/NavLibraries.DVR5Ua-S.js +0 -1
  166. package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +0 -1
  167. package/dist/_astro/SlideOverDrawer.BMg2tce6.js +0 -1
  168. package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +0 -1
  169. package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +0 -3
  170. package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +0 -10
  171. package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +0 -12
  172. package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +0 -3
  173. package/dist/_astro/app-config.Dvfzl5_N.js +0 -1
  174. package/dist/_astro/app-version.CNpnKIb9.js +0 -1
  175. package/dist/_astro/case-fields.CmePqYfh.js +0 -148
  176. package/dist/_astro/case-gen-run.Cvvdv_kv.js +0 -26
  177. package/dist/_astro/case-prompt.CZ3vWUju.js +0 -2
  178. package/dist/_astro/plugins.Db9xoFZb.js +0 -1
@@ -0,0 +1,169 @@
1
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
2
+ import {
3
+ CASE_AUTOMATION_PROMPT_FILE,
4
+ CASE_AUTOMATION_PROMPT_TEMPLATE,
5
+ } from './case-automation-prompt.mjs';
6
+ import {
7
+ assessCases,
8
+ applyAssessment,
9
+ getBatch,
10
+ listIterations,
11
+ projectSelection,
12
+ refreshAutomationFile,
13
+ startBatch,
14
+ sourceDocument,
15
+ statuses,
16
+ stopBatch,
17
+ } from './case-automation/service.mjs';
18
+ import { ensurePluginPrompt, isPluginOnInSpace } from './plugin-prompts.mjs';
19
+ import { automationSummaryForFile } from './case-automation/store.mjs';
20
+
21
+ const PREFIX = '/__tb_case_automation';
22
+
23
+ function sendJson(res, status, body) {
24
+ res.statusCode = status;
25
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
26
+ res.setHeader('Cache-Control', 'no-store');
27
+ res.end(JSON.stringify(body));
28
+ }
29
+
30
+ function readBody(req) {
31
+ return new Promise((resolve, reject) => {
32
+ const chunks = [];
33
+ let size = 0;
34
+ req.on('data', (chunk) => {
35
+ size += chunk.length;
36
+ if (size > 2 * 1024 * 1024) {
37
+ reject(Object.assign(new Error('请求内容过大'), { statusCode: 413 }));
38
+ req.destroy();
39
+ return;
40
+ }
41
+ chunks.push(Buffer.from(chunk));
42
+ });
43
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
44
+ req.on('error', reject);
45
+ });
46
+ }
47
+
48
+ function sameOrigin(req) {
49
+ if (!req.headers.origin) return true;
50
+ try {
51
+ return new URL(req.headers.origin).host === req.headers.host;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ export function lhCaseAutomationPlugin() {
58
+ return {
59
+ name: 'lh-case-automation',
60
+ configureServer(server) {
61
+ server.middlewares.use(async (req, res, next) => {
62
+ const parsed = new URL(req.url || '/', 'http://127.0.0.1');
63
+ if (!parsed.pathname.startsWith(PREFIX)) return next();
64
+ const tail = parsed.pathname.slice(PREFIX.length) || '/';
65
+ const method = req.method || 'GET';
66
+ try {
67
+ const root = getDataRoot();
68
+ const enabled = isPluginOnInSpace('cases', root) && isPluginOnInSpace('uiAuto', root);
69
+ if (parsed.pathname === `${PREFIX}/health`)
70
+ return sendJson(res, 200, {
71
+ ok: true,
72
+ enabled,
73
+ cases: isPluginOnInSpace('cases', root),
74
+ uiAuto: isPluginOnInSpace('uiAuto', root),
75
+ });
76
+ if (!enabled) {
77
+ return sendJson(res, 403, {
78
+ ok: false,
79
+ error: '功能用例转 UI 自动化需要开启「用例管理」和「自动化测试」',
80
+ });
81
+ }
82
+ if (method !== 'GET' && !sameOrigin(req)) {
83
+ return sendJson(res, 403, {
84
+ ok: false,
85
+ error: '请求必须来自当前 Lantern 页面',
86
+ });
87
+ }
88
+ ensurePluginPrompt(CASE_AUTOMATION_PROMPT_FILE, CASE_AUTOMATION_PROMPT_TEMPLATE, root);
89
+ if (method === 'GET' && tail === '/iterations') {
90
+ return sendJson(
91
+ res,
92
+ 200,
93
+ listIterations(
94
+ root,
95
+ parsed.searchParams.get('projectId') || '',
96
+ parsed.searchParams.get('casePath') || '',
97
+ ),
98
+ );
99
+ }
100
+ if (method === 'GET' && tail === '/cases') {
101
+ return sendJson(res, 200, {
102
+ ok: true,
103
+ document: await sourceDocument(root, parsed.searchParams.get('path') || ''),
104
+ });
105
+ }
106
+ if (method === 'GET' && tail === '/selection') {
107
+ return sendJson(res, 200, {
108
+ ok: true,
109
+ selection: projectSelection(root, parsed.searchParams.get('casePath') || ''),
110
+ });
111
+ }
112
+ if (method === 'GET' && tail === '/status') {
113
+ return sendJson(res, 200, {
114
+ ok: true,
115
+ statuses: await statuses(root, parsed.searchParams.get('casePath') || ''),
116
+ });
117
+ }
118
+ if (method === 'GET' && tail.startsWith('/runs/')) {
119
+ const id = tail.split('/')[2] || '';
120
+ return sendJson(res, 200, { ok: true, batch: getBatch(root, id) });
121
+ }
122
+ if (method === 'POST' && tail === '/assess') {
123
+ return sendJson(
124
+ res,
125
+ 200,
126
+ await assessCases(root, JSON.parse((await readBody(req)) || '{}')),
127
+ );
128
+ }
129
+ if (method === 'POST' && tail === '/summaries') {
130
+ const body = JSON.parse((await readBody(req)) || '{}');
131
+ const paths = Array.isArray(body.paths) ? body.paths.map(String) : [];
132
+ await Promise.all(paths.map((casePath) => refreshAutomationFile(root, casePath)));
133
+ return sendJson(res, 200, {
134
+ ok: true,
135
+ summaries: Object.fromEntries(
136
+ paths.map((casePath) => [casePath, automationSummaryForFile(root, casePath)]),
137
+ ),
138
+ });
139
+ }
140
+ if (method === 'POST' && tail === '/apply') {
141
+ return sendJson(
142
+ res,
143
+ 200,
144
+ await applyAssessment(root, JSON.parse((await readBody(req)) || '{}')),
145
+ );
146
+ }
147
+ if (method === 'POST' && tail === '/runs') {
148
+ return sendJson(res, 200, {
149
+ ok: true,
150
+ batch: startBatch(root, JSON.parse((await readBody(req)) || '{}')),
151
+ });
152
+ }
153
+ if (method === 'POST' && tail.endsWith('/stop') && tail.startsWith('/runs/')) {
154
+ return sendJson(res, 200, {
155
+ ok: true,
156
+ batch: stopBatch(root, tail.split('/')[2] || ''),
157
+ });
158
+ }
159
+ return sendJson(res, 404, { ok: false, error: '接口不存在' });
160
+ } catch (error) {
161
+ return sendJson(res, error.statusCode || 500, {
162
+ ok: false,
163
+ error: error instanceof Error ? error.message : String(error),
164
+ });
165
+ }
166
+ });
167
+ },
168
+ };
169
+ }
@@ -0,0 +1,456 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
5
+ import { resolveContentRoot } from '../builtin/session/space-layout.mjs';
6
+ import { executionHeaders, normalizeExecutionStatus } from '../builtin/case-workflow-contract.mjs';
7
+ import {
8
+ analysisSnapshot,
9
+ sourceFileHash,
10
+ linkCaseArtifact,
11
+ readWorkflowAssets,
12
+ caseContentFingerprint,
13
+ } from './case-execution/assets.mjs';
14
+ import { loadCaseDocument, caseExecutionFieldMap } from './case-execution/files.mjs';
15
+ import { analysisRevision } from './req-analysis-revision.mjs';
16
+ import { readReqSourceFile } from './lh-req-analysis.mjs';
17
+ import { isPluginOnInSpace, readPluginPrompt } from './plugin-prompts.mjs';
18
+
19
+ const PREFIX = '/__tb_case_design';
20
+ const defaultHeaders = [
21
+ '用例编号',
22
+ '需求编号',
23
+ '用例标题',
24
+ '前置条件',
25
+ '测试步骤',
26
+ '预期结果',
27
+ '优先级',
28
+ '引用需求点',
29
+ '备注',
30
+ ];
31
+ const fail = (message, statusCode = 400) => {
32
+ throw Object.assign(new Error(message), { statusCode });
33
+ };
34
+ const clean = (value) => (typeof value === 'string' ? value.trim() : '');
35
+ function flatten(items) {
36
+ return (items || []).flatMap((item) => [item, ...flatten(item.children)]);
37
+ }
38
+
39
+ export async function caseDesignContext(root, raw) {
40
+ const analysis = raw.analysisId ? analysisSnapshot(root, raw.analysisId) : null;
41
+ const sourcePath = analysis?.sourcePath || clean(raw.sourcePath);
42
+ const source = sourcePath ? await readReqSourceFile(root, sourcePath) : null;
43
+ if (!analysis && !source) fail('请选择需求分析或需求来源');
44
+ const skillPath = clean(raw.skillPath) || '功能测试用例提示词.md';
45
+ const skill = readPluginPrompt(skillPath, root).trim();
46
+ if (!skill) fail('请先在插件仓库准备对应的用例生成技能', 422);
47
+ return {
48
+ ok: true,
49
+ analysis,
50
+ revision: analysis ? analysisRevision(analysis) : '',
51
+ source,
52
+ sourcePath,
53
+ sourceFileHash: sourceFileHash(root, sourcePath),
54
+ skill,
55
+ headers: executionHeaders(raw.headers?.length ? raw.headers : defaultHeaders),
56
+ outputContract: {
57
+ rows: '数组:按 headers 输出字符串字段;需求编号使用 US,引用需求点使用 RO / TP,禁止编造引用',
58
+ finalStatus: '待验证;实际结果必须留空',
59
+ },
60
+ };
61
+ }
62
+
63
+ /** @param {any} raw @param {any} [analysis] */
64
+ export function validateCaseDesign(raw, analysis = null) {
65
+ const headers = executionHeaders(
66
+ Array.isArray(raw.headers) && raw.headers.length
67
+ ? [...new Set(raw.headers.map(String))]
68
+ : defaultHeaders,
69
+ );
70
+ const rows = Array.isArray(raw.rows) ? raw.rows : [];
71
+ const issues = [];
72
+ if (!rows.length || rows.length > 10000) issues.push('用例数量必须在 1 到 10000 条之间');
73
+ const outline = flatten(analysis?.outline);
74
+ const roAll = new Set(outline.map((item) => item.id));
75
+ const childTargets = outline.filter((item) => item.kind && item.parentId);
76
+ const ro = new Set(
77
+ (childTargets.length ? childTargets : outline.filter((item) => !item.parentId)).map(
78
+ (item) => item.id,
79
+ ),
80
+ );
81
+ const us = new Set((analysis?.stories || []).map((item) => item.id));
82
+ const tp = new Set((analysis?.testPoints?.points || []).map((item) => item.id));
83
+ const covered = { RO: new Set(), US: new Set(), TP: new Set() };
84
+ const mapped = caseExecutionFieldMap(headers);
85
+ const titleHeader = mapped.title,
86
+ stepsHeader = mapped.steps,
87
+ expectedHeader = mapped.expected;
88
+ rows.forEach((row, index) => {
89
+ for (const [label, header] of [
90
+ ['标题', titleHeader],
91
+ ['步骤', stepsHeader],
92
+ ['预期结果', expectedHeader],
93
+ ]) {
94
+ if (!header || !clean(row?.[header])) issues.push(`第 ${index + 1} 条缺少${label}`);
95
+ }
96
+ const cite = headers
97
+ .filter((h) => /需求编号|引用需求点|关联需求|需求id/i.test(h))
98
+ .map((h) => String(row?.[h] || ''))
99
+ .join(' ');
100
+ for (const match of cite.matchAll(/\b(RO-[A-Za-z0-9_-]+|US-\d+|TP-\d+)\b/g)) {
101
+ const id = match[1],
102
+ group = id.slice(0, 2),
103
+ valid = group === 'RO' ? roAll : group === 'US' ? us : tp;
104
+ if (analysis && !valid.has(id)) issues.push(`第 ${index + 1} 条引用了不存在的 ${id}`);
105
+ else covered[group].add(id);
106
+ }
107
+ });
108
+ const coverage = Object.fromEntries(
109
+ [
110
+ ['RO', ro],
111
+ ['US', us],
112
+ ['TP', tp],
113
+ ].map(([kind, ids]) => {
114
+ const missing = [...ids].filter((id) => !covered[kind].has(id));
115
+ return [
116
+ kind,
117
+ {
118
+ targets: [...ids],
119
+ total: ids.size,
120
+ covered: ids.size - missing.length,
121
+ rate: ids.size ? Math.round(((ids.size - missing.length) / ids.size) * 100) : null,
122
+ missing,
123
+ },
124
+ ];
125
+ }),
126
+ );
127
+ return { ok: !issues.length, headers, issues: issues.slice(0, 200), coverage };
128
+ }
129
+
130
+ export async function saveCaseDesign(root, raw) {
131
+ const analysis = raw.analysisId ? analysisSnapshot(root, raw.analysisId) : null;
132
+ if (analysis && raw.expectedRevision !== analysisRevision(analysis))
133
+ fail('需求分析已变化,请重新读取后生成', 409);
134
+ const sourcePath = analysis?.sourcePath || clean(raw.sourcePath);
135
+ if (raw.expectedSourceFileHash && raw.expectedSourceFileHash !== sourceFileHash(root, sourcePath))
136
+ fail('需求源文件已变化,请重新读取后生成', 409);
137
+ if (sourcePath && !raw.expectedSourceFileHash)
138
+ fail('保存前必须读取需求基线并携带 sourceFileHash', 409);
139
+ const checked = validateCaseDesign(raw, analysis);
140
+ if (!checked.ok) fail(checked.issues.join(';'), 422);
141
+ const headers = checked.headers;
142
+ const executionMap = caseExecutionFieldMap(headers);
143
+ const statusHeader = executionMap.status,
144
+ actualHeader = executionMap.actual;
145
+ const rows = raw.rows.map((row, index) =>
146
+ Object.fromEntries(
147
+ headers.map((h) => [
148
+ h,
149
+ h === statusHeader
150
+ ? '待验证'
151
+ : h === actualHeader
152
+ ? ''
153
+ : String(row[h] ?? (h === '用例编号' ? index + 1 : '')),
154
+ ]),
155
+ ),
156
+ );
157
+ const ext = ['xlsx', 'csv', 'md'].includes(raw.format) ? raw.format : 'xlsx';
158
+ const base = clean(raw.title || analysis?.title || '测试用例')
159
+ .replace(/[\\/:*?"<>|]/g, '_')
160
+ .slice(0, 100);
161
+ const folder = clean(raw.folder)
162
+ .replace(/[\\/:*?"<>|]/g, '_')
163
+ .replace(/^\.+|\.+$/g, '')
164
+ .slice(0, 80);
165
+ const rel = `${folder ? `${folder}/` : ''}${base}_${Date.now()}_${crypto.randomUUID().slice(0, 6)}.${ext}`;
166
+ const dir = path.join(resolveContentRoot(root, '用例管理').abs, folder);
167
+ fs.mkdirSync(dir, { recursive: true });
168
+ const abs = path.join(resolveContentRoot(root, '用例管理').abs, rel);
169
+ if (ext === 'xlsx') {
170
+ const XLSX = await import('xlsx');
171
+ const sheet = XLSX.utils.json_to_sheet(rows, { header: headers });
172
+ const workbook = XLSX.utils.book_new();
173
+ XLSX.utils.book_append_sheet(workbook, sheet, '测试用例');
174
+ fs.writeFileSync(abs, XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }), {
175
+ flag: 'wx',
176
+ });
177
+ } else if (ext === 'csv') {
178
+ const cell = (value) => '"' + String(value).replaceAll('"', '""') + '"';
179
+ fs.writeFileSync(
180
+ abs,
181
+ '\uFEFF' +
182
+ [headers, ...rows.map((row) => headers.map((h) => row[h]))]
183
+ .map((row) => row.map(cell).join(','))
184
+ .join('\n'),
185
+ { flag: 'wx' },
186
+ );
187
+ } else {
188
+ const cell = (value) => String(value).replaceAll('|', '&#124;').replace(/\r?\n/g, '<br>');
189
+ fs.writeFileSync(
190
+ abs,
191
+ [headers, headers.map(() => '---'), ...rows.map((row) => headers.map((h) => row[h]))]
192
+ .map((row) => '| ' + row.map(cell).join(' | ') + ' |')
193
+ .join('\n'),
194
+ { flag: 'wx' },
195
+ );
196
+ }
197
+ const document = await loadCaseDocument(root, rel);
198
+ const artifact = linkCaseArtifact(root, document, {
199
+ analysisId: analysis?.id || '',
200
+ analysisRevision: analysis ? analysisRevision(analysis) : '',
201
+ sourcePath,
202
+ sourceFileHash: sourceFileHash(root, sourcePath),
203
+ coverage: checked.coverage,
204
+ });
205
+ return {
206
+ ok: true,
207
+ path: rel,
208
+ artifactId: artifact.id,
209
+ caseCount: rows.length,
210
+ coverage: checked.coverage,
211
+ executable: document.executable,
212
+ };
213
+ }
214
+
215
+ export async function caseAcceptance(root, casePath, environmentKey = '') {
216
+ const document = await loadCaseDocument(root, casePath);
217
+ const artifact = readWorkflowAssets(root).artifacts.find(
218
+ (item) => item.id === document.provenance.artifactId,
219
+ );
220
+ const history = artifact?.verificationHistory || [];
221
+ const envKey = (env) => JSON.stringify([env?.name || '', env?.role || '', env?.build || '']);
222
+ const envs = new Map();
223
+ history.forEach((item) => {
224
+ if (item.baselineId === artifact?.baselineId)
225
+ envs.set(envKey(item.environment), item.environment);
226
+ });
227
+ const runsFolder = path.join(root, '.lantern', 'local', 'case-execution', 'runs');
228
+ if (fs.existsSync(runsFolder))
229
+ for (const file of fs.readdirSync(runsFolder).filter((name) => name.endsWith('.json'))) {
230
+ try {
231
+ const run = JSON.parse(fs.readFileSync(path.join(runsFolder, file), 'utf8'));
232
+ if (
233
+ run.provenance?.artifactId === artifact?.id &&
234
+ run.provenance?.baselineId === artifact?.baselineId &&
235
+ run.environment
236
+ )
237
+ envs.set(envKey(run.environment), run.environment);
238
+ } catch {
239
+ /* Ignore incomplete runtime records. */
240
+ }
241
+ }
242
+ const plansFolder = path.join(root, '.lantern', 'local', 'case-execution', 'plans');
243
+ if (fs.existsSync(plansFolder))
244
+ for (const file of fs.readdirSync(plansFolder).filter((name) => name.endsWith('.json'))) {
245
+ try {
246
+ const plan = JSON.parse(fs.readFileSync(path.join(plansFolder, file), 'utf8'));
247
+ if (
248
+ plan.provenance?.artifactId === artifact?.id &&
249
+ plan.provenance?.baselineId === artifact?.baselineId &&
250
+ plan.environment
251
+ )
252
+ envs.set(envKey(plan.environment), plan.environment);
253
+ } catch {
254
+ /* Ignore incomplete plans. */
255
+ }
256
+ }
257
+ const environments = [...envs.entries()].map(([key, env]) => ({
258
+ key,
259
+ label: [env?.name, env?.role, env?.build].filter(Boolean).join(' / ') || '未标注环境',
260
+ }));
261
+ if (environmentKey) {
262
+ for (const item of document.cases) {
263
+ const verified = history
264
+ .filter(
265
+ (entry) =>
266
+ entry.caseId === item.id &&
267
+ envKey(entry.environment) === environmentKey &&
268
+ entry.baselineId === artifact?.baselineId &&
269
+ entry.sourceFileHash === (artifact?.sourceFileHash || '') &&
270
+ entry.contentFingerprint === caseContentFingerprint(item),
271
+ )
272
+ .at(-1);
273
+ item.status =
274
+ verified && !document.provenance.stale && !artifact?.needsReview?.includes(item.id)
275
+ ? verified.status
276
+ : '待验证';
277
+ }
278
+ }
279
+ const analysis = document.provenance.analysisId
280
+ ? analysisSnapshot(root, document.provenance.analysisId)
281
+ : null;
282
+ const rows = document.cases.map((item) =>
283
+ Object.fromEntries((item.fields || []).map((f) => [f.name, f.value])),
284
+ );
285
+ const design = validateCaseDesign({ rows, headers: document.headers }, analysis);
286
+ const statuses = document.cases.map((item) => normalizeExecutionStatus(item.status));
287
+ const progressCoverage = Object.fromEntries(
288
+ Object.entries(design.coverage).map(([kind, value]) => {
289
+ const refs = new Map();
290
+ document.cases.forEach((item) => {
291
+ const text = (item.fields || [])
292
+ .filter((field) => /需求编号|引用需求点|关联需求|需求id/i.test(field.name))
293
+ .map((field) => field.value)
294
+ .join(' ');
295
+ for (const match of text.matchAll(/\b(RO-[A-Za-z0-9_-]+|US-\d+|TP-\d+)\b/g)) {
296
+ if (!match[1].startsWith(kind + '-')) continue;
297
+ const states = refs.get(match[1]) || [];
298
+ states.push(normalizeExecutionStatus(item.status));
299
+ refs.set(match[1], states);
300
+ }
301
+ });
302
+ const validStates = [...refs.entries()]
303
+ .filter(([id]) => value.targets.includes(id))
304
+ .map(([, states]) => states);
305
+ const executed = validStates.filter((states) =>
306
+ states.every((status) => status !== '待验证'),
307
+ ).length;
308
+ const passed = validStates.filter((states) =>
309
+ states.every((status) => status === '通过'),
310
+ ).length;
311
+ return [
312
+ kind,
313
+ {
314
+ total: value.total,
315
+ executed,
316
+ passed,
317
+ executionRate: value.total ? Math.round((executed / value.total) * 100) : null,
318
+ passRate: value.total ? Math.round((passed / value.total) * 100) : null,
319
+ },
320
+ ];
321
+ }),
322
+ );
323
+ const passed = statuses.filter((status) => status === '通过').length;
324
+ const pending = statuses.filter((status) => status === '待验证').length;
325
+ const failed = statuses.filter((status) => status === '不通过').length;
326
+ const blocked = statuses.filter((status) => status === '阻塞').length;
327
+ const skipped = statuses.filter((status) => status === '跳过').length;
328
+ const reasons = [...document.provenance.reasons];
329
+ if (!environmentKey && environments.length > 1)
330
+ reasons.push('包含多个环境或构建的验证记录,请选择具体环境查看验收');
331
+ if (!design.ok) reasons.push('用例字段或需求引用校验未通过');
332
+ if (pending) reasons.push(`${pending} 条待验证`);
333
+ if (failed || blocked) reasons.push(`${failed} 条不通过,${blocked} 条阻塞`);
334
+ if (skipped) reasons.push(`${skipped} 条跳过,需说明接受风险`);
335
+ if (!analysis) reasons.push('未关联需求分析,无法核验需求覆盖');
336
+ if (Object.values(design.coverage).some((item) => item.total && item.missing.length))
337
+ reasons.push('存在未覆盖需求或测试点');
338
+ return {
339
+ ok: true,
340
+ path: casePath,
341
+ provenance: document.provenance,
342
+ environments,
343
+ environmentKey,
344
+ designCoverage: design.coverage,
345
+ progressCoverage,
346
+ total: statuses.length,
347
+ passed,
348
+ pending,
349
+ failed,
350
+ blocked,
351
+ skipped,
352
+ executionRate: statuses.length
353
+ ? Math.round(((statuses.length - pending) / statuses.length) * 100)
354
+ : 0,
355
+ acceptance: { ready: !!statuses.length && !reasons.length, reasons },
356
+ note: '仅汇总用户手动判定状态;不包含缺陷平台状态或性能测试,不替代项目最终准出审批',
357
+ };
358
+ }
359
+
360
+ export async function linkCaseBaseline(root, raw) {
361
+ const document = await loadCaseDocument(root, raw.casePath);
362
+ const analysis = analysisSnapshot(root, raw.analysisId);
363
+ const revision = analysisRevision(analysis);
364
+ const preview = {
365
+ fileHash: document.fileHash,
366
+ revision,
367
+ affected: document.cases.map((item) => ({ id: item.id, title: item.title })),
368
+ note: '关联或更新基线后,历史结果保留但需逐条人工复核,未复核结果不计为通过',
369
+ };
370
+ if (raw.mode !== 'apply') return { ok: true, preview };
371
+ if (raw.expectedFileHash !== document.fileHash || raw.expectedRevision !== revision)
372
+ fail('文件或需求已变化,请重新预览', 409);
373
+ linkCaseArtifact(root, document, {
374
+ analysisId: analysis.id,
375
+ analysisRevision: revision,
376
+ sourcePath: analysis.sourcePath,
377
+ sourceFileHash: sourceFileHash(root, analysis.sourcePath),
378
+ needsReview: document.cases.map((item) => item.id),
379
+ });
380
+ return { ok: true, preview };
381
+ }
382
+
383
+ export function lhCaseDesignPlugin() {
384
+ return {
385
+ name: 'lh-case-design',
386
+ configureServer(server) {
387
+ server.middlewares.use(async (req, res, next) => {
388
+ const url = new URL(req.url || '/', 'http://localhost');
389
+ if (!url.pathname.startsWith(PREFIX + '/')) return next();
390
+ const send = (code, value) => {
391
+ res.statusCode = code;
392
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
393
+ res.setHeader('Cache-Control', 'no-store');
394
+ res.end(JSON.stringify(value));
395
+ };
396
+ try {
397
+ const root = getDataRoot(),
398
+ action = url.pathname.slice(PREFIX.length),
399
+ method = req.method || 'GET';
400
+ if (!isPluginOnInSpace('cases', root)) fail('请开启用例管理', 403);
401
+ if (
402
+ method !== 'GET' &&
403
+ req.headers.origin &&
404
+ new URL(req.headers.origin).host !== req.headers.host
405
+ )
406
+ fail('请求来源不匹配', 403);
407
+ if (action === '/acceptance' && method === 'GET')
408
+ return send(
409
+ 200,
410
+ await caseAcceptance(
411
+ root,
412
+ url.searchParams.get('casePath') || '',
413
+ url.searchParams.get('environmentKey') || '',
414
+ ),
415
+ );
416
+ if (action !== '/link' && !isPluginOnInSpace('caseGen', root))
417
+ fail('请开启用例生成', 403);
418
+ let body = {};
419
+ if (method === 'POST') {
420
+ const chunks = [];
421
+ let size = 0;
422
+ for await (const chunk of req) {
423
+ size += chunk.length;
424
+ if (size > 10 * 1024 * 1024) fail('请求超过 10MB', 413);
425
+ chunks.push(chunk);
426
+ }
427
+ body = JSON.parse(Buffer.concat(chunks).toString() || '{}');
428
+ }
429
+ if (action === '/link' && method === 'POST')
430
+ return send(200, await linkCaseBaseline(root, body));
431
+ if (action === '/context')
432
+ return send(
433
+ 200,
434
+ await caseDesignContext(
435
+ root,
436
+ method === 'GET' ? Object.fromEntries(url.searchParams) : body,
437
+ ),
438
+ );
439
+ if (action === '/validate' && method === 'POST')
440
+ return send(
441
+ 200,
442
+ validateCaseDesign(
443
+ body,
444
+ body.analysisId ? analysisSnapshot(root, body.analysisId) : null,
445
+ ),
446
+ );
447
+ if (action === '/save' && method === 'POST')
448
+ return send(200, await saveCaseDesign(root, body));
449
+ return send(404, { ok: false, error: '接口不存在' });
450
+ } catch (error) {
451
+ return send(error.statusCode || 500, { ok: false, error: error.message });
452
+ }
453
+ });
454
+ },
455
+ };
456
+ }