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
@@ -1,23 +1,29 @@
1
+ import { bindCaseIdentities, recordManualVerification } from './assets.mjs';
1
2
  import crypto from 'node:crypto';
3
+ import { validateDefectLinks, CASE_FIELD_ALIASES } from '../../builtin/case-workflow-contract.mjs';
2
4
  import fs from 'node:fs';
3
5
  import path from 'node:path';
4
6
 
5
7
  import { resolveContentRoot } from '../../builtin/session/space-layout.mjs';
8
+ import {
9
+ CASE_BACKUP_DIR_NAME,
10
+ backupDirectoryForCasePath,
11
+ } from '../../builtin/case-backup-contract.mjs';
6
12
 
7
13
  const CASE_DIR_NAME = '用例管理';
8
- const BACKUP_DIR_NAME = '备份列表';
9
14
  const DEFECT_URL_HEADER = '缺陷地址';
10
15
  const EXECUTION_STATUSES = ['待验证', '通过', '不通过', '阻塞', '跳过'];
11
16
 
12
17
  const ALIASES = {
13
- no: ['用例编号', '测试用例编号', '案例编号', '用例号', '编号', 'caseid'],
14
- title: ['用例标题', '用例名称', '测试分项目', '测试项目', '测试点', '标题'],
15
- precondition: ['前置条件', '预置条件', '前提条件', '准备条件'],
16
- steps: ['测试步骤', '操作步骤', '执行步骤', '用例步骤', '测试过程'],
17
- expected: ['预期结果', '期望结果', '预期内容', '期望内容标准', '验收标准'],
18
- priority: ['优先级', '重要级别', '重要程度'],
19
- module: ['所属模块', '模块', '测试模块', '功能模块', '测试项目'],
20
- submodule: ['子模块', '小模块', '功能点'],
18
+ ...CASE_FIELD_ALIASES,
19
+ no: CASE_FIELD_ALIASES.no,
20
+ title: CASE_FIELD_ALIASES.title,
21
+ precondition: CASE_FIELD_ALIASES.precondition,
22
+ steps: CASE_FIELD_ALIASES.steps,
23
+ expected: CASE_FIELD_ALIASES.expected,
24
+ priority: CASE_FIELD_ALIASES.priority,
25
+ module: CASE_FIELD_ALIASES.module,
26
+ submodule: CASE_FIELD_ALIASES.submodule,
21
27
  status: ['用例状态', '执行状态', '执行结果', '测试结果'],
22
28
  actual: ['实际结果', '实测结果', '执行实际结果'],
23
29
  executor: ['执行人', '测试人'],
@@ -50,7 +56,15 @@ function fieldMap(headers) {
50
56
  const used = new Set();
51
57
  for (const [field, aliases] of Object.entries(ALIASES)) {
52
58
  for (const alias of aliases.map(normalizeHeader)) {
53
- const hit = pairs.find((item) => !used.has(item.raw) && item.norm === alias);
59
+ const hit =
60
+ pairs.find((item) => !used.has(item.raw) && item.norm === alias) ||
61
+ pairs.find(
62
+ (item) =>
63
+ !used.has(item.raw) &&
64
+ alias.length >= 2 &&
65
+ item.norm.startsWith(alias) &&
66
+ item.norm.length - alias.length <= 4,
67
+ );
54
68
  if (!hit) continue;
55
69
  mapped[field] = hit.raw;
56
70
  used.add(hit.raw);
@@ -96,7 +110,7 @@ function walkCaseFiles(root, dir = caseRoot(root), relative = '') {
96
110
  if (ignored(item.name)) continue;
97
111
  const rel = relative ? `${relative}/${item.name}` : item.name;
98
112
  if (item.isDirectory()) {
99
- if (item.name === BACKUP_DIR_NAME) continue;
113
+ if (item.name === CASE_BACKUP_DIR_NAME) continue;
100
114
  files.push(...walkCaseFiles(root, path.join(dir, item.name), rel));
101
115
  continue;
102
116
  }
@@ -347,7 +361,7 @@ export async function loadCaseDocument(root, relativePath) {
347
361
  : missingColumns.length
348
362
  ? `缺少执行列:${missingColumns.join('、')}`
349
363
  : '';
350
- return {
364
+ return bindCaseIdentities(root, {
351
365
  path: relativePath.replaceAll('\\', '/'),
352
366
  abs,
353
367
  ext,
@@ -374,7 +388,7 @@ export async function loadCaseDocument(root, relativePath) {
374
388
  statuses: EXECUTION_STATUSES,
375
389
  _parsed: parsed,
376
390
  _map: map,
377
- };
391
+ });
378
392
  }
379
393
 
380
394
  export async function listCaseDocuments(root) {
@@ -411,7 +425,10 @@ function stamp(date = new Date()) {
411
425
 
412
426
  export function backupCaseDocument(root, relativePath) {
413
427
  const abs = safeCasePath(root, relativePath);
414
- const backupDir = path.join(caseRoot(root), BACKUP_DIR_NAME);
428
+ const backupDir = path.join(
429
+ caseRoot(root),
430
+ ...backupDirectoryForCasePath(relativePath).split('/'),
431
+ );
415
432
  fs.mkdirSync(backupDir, { recursive: true });
416
433
  const ext = path.extname(abs);
417
434
  const base = path.basename(abs, ext);
@@ -743,6 +760,10 @@ export async function applyCaseFieldUpdates(
743
760
  if (!normalized.length) {
744
761
  throw Object.assign(new Error('没有需要保存的字段'), { statusCode: 400 });
745
762
  }
763
+ for (const update of normalized) {
764
+ if (update.header === (document.columns.defectUrl || DEFECT_URL_HEADER))
765
+ update.value = validateDefectLinks(update.value);
766
+ }
746
767
  let allowed = new Set(document.headers.map((header) => String(header)));
747
768
  const unknown = normalized.filter((update) => !allowed.has(update.header));
748
769
  if (unknown.some((update) => update.header !== DEFECT_URL_HEADER)) {
@@ -765,6 +786,10 @@ export async function applyCaseFieldUpdates(
765
786
  } else {
766
787
  patchText(document.abs, document.ext, document._parsed, rowIndex, normalized);
767
788
  }
789
+ if (normalized.some((update) => update.header === document.columns.status)) {
790
+ const refreshed = await loadCaseDocument(root, relativePath);
791
+ recordManualVerification(root, refreshed, rowIndex);
792
+ }
768
793
  return {
769
794
  ok: true,
770
795
  path: relativePath,
@@ -774,4 +799,31 @@ export async function applyCaseFieldUpdates(
774
799
  };
775
800
  }
776
801
 
777
- export { EXECUTION_STATUSES };
802
+ export { EXECUTION_STATUSES, fieldMap as caseExecutionFieldMap };
803
+
804
+ export async function prepareExecutionColumns(root, raw) {
805
+ let document = await loadCaseDocument(root, raw.casePath);
806
+ const preview = {
807
+ path: document.path,
808
+ fileHash: document.fileHash,
809
+ missingColumns: document.missingColumns,
810
+ executable: document.executable,
811
+ };
812
+ if (raw.mode !== 'apply') return { ok: true, preview };
813
+ if (document.ext === '.xls')
814
+ throw Object.assign(new Error(document.executionIssue), { statusCode: 422 });
815
+ if (raw.expectedFileHash !== document.fileHash)
816
+ throw Object.assign(new Error('文件已变化,请重新预览'), { statusCode: 409 });
817
+ const backup = document.missingColumns.length ? backupCaseDocument(root, raw.casePath) : '';
818
+ for (const header of document.missingColumns) {
819
+ await appendCaseHeader(document, header);
820
+ document = await loadCaseDocument(root, raw.casePath);
821
+ }
822
+ return {
823
+ ok: true,
824
+ preview,
825
+ backup,
826
+ fileHash: document.fileHash,
827
+ executable: document.executable,
828
+ };
829
+ }
@@ -0,0 +1,318 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { startRun, getRun, stopRun, confirmRun } from './service.mjs';
5
+ import { loadCaseDocument, applyCaseExecutionResult } from './files.mjs';
6
+ import { caseContentFingerprint, recordManualVerification } from './assets.mjs';
7
+ import { isPluginOnInSpace } from '../plugin-prompts.mjs';
8
+ import {
9
+ startAutomationProjectRun,
10
+ stopAutomationProjectRun,
11
+ readAutomationProjectRun,
12
+ } from '../lh-uiauto.mjs';
13
+
14
+ const active = new Map();
15
+ const folder = (root) => path.join(root, '.lantern', 'local', 'case-execution', 'plans');
16
+ const key = (root, id) => `${root}\0${id}`;
17
+ const fail = (message, statusCode = 400) => {
18
+ throw Object.assign(new Error(message), { statusCode });
19
+ };
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
+ function file(root, id) {
22
+ if (!/^[a-z0-9-]{36}$/.test(id || '')) fail('计划编号无效');
23
+ return path.join(folder(root), id + '.json');
24
+ }
25
+ function save(root, plan) {
26
+ fs.mkdirSync(folder(root), { recursive: true });
27
+ plan.updatedAt = new Date().toISOString();
28
+ fs.writeFileSync(file(root, plan.id) + '.tmp', JSON.stringify(plan, null, 2), { mode: 0o600 });
29
+ fs.renameSync(file(root, plan.id) + '.tmp', file(root, plan.id));
30
+ }
31
+ function view(plan) {
32
+ return { ...plan, storageStatePath: plan.storageStatePath ? '[local]' : '' };
33
+ }
34
+ function read(root, id) {
35
+ let plan;
36
+ try {
37
+ plan = JSON.parse(fs.readFileSync(file(root, id), 'utf8'));
38
+ } catch {
39
+ fail('执行计划不存在', 404);
40
+ }
41
+ if (plan.status === 'running' && !active.has(key(root, id))) {
42
+ plan.status = 'interrupted';
43
+ plan.error = '服务重启导致计划中断;可显式继续未完成项,已完成证据保留';
44
+ plan.items.forEach((item) => {
45
+ if (item.status === 'running') item.status = 'interrupted';
46
+ });
47
+ save(root, plan);
48
+ }
49
+ return plan;
50
+ }
51
+ export function listExecutionPlans(root, casePath = '') {
52
+ if (!fs.existsSync(folder(root))) return [];
53
+ return fs
54
+ .readdirSync(folder(root))
55
+ .filter((name) => name.endsWith('.json'))
56
+ .map((name) => read(root, name.slice(0, -5)))
57
+ .filter((plan) => !casePath || plan.casePath === casePath)
58
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
59
+ .map(view);
60
+ }
61
+ export function getExecutionPlan(root, id) {
62
+ return view(read(root, id));
63
+ }
64
+ export async function createExecutionPlan(root, raw) {
65
+ if (!String(raw.environment?.name || '').trim() || !String(raw.environment?.build || '').trim())
66
+ fail('环境名称与被测构建版本不能为空');
67
+ const document = await loadCaseDocument(root, raw.casePath);
68
+ if (raw.expectedFileHash !== document.fileHash) fail('用例文件已变化,请重新选择计划范围', 409);
69
+ if (document.provenance?.stale) fail('需求基线已变化,请先更新用例', 409);
70
+ const selected = new Set(Array.isArray(raw.caseIds) ? raw.caseIds : []);
71
+ const cases = document.cases.filter((item) => selected.has(item.id));
72
+ if (!cases.length || cases.length !== selected.size) fail('请选择有效的用例范围');
73
+ const engine = raw.engine === 'automation' ? 'automation' : 'browser';
74
+ if (engine === 'browser' && !document.executable) fail(document.executionIssue, 422);
75
+ if (engine === 'browser') {
76
+ const url = new URL(raw.url);
77
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
78
+ fail('目标地址必须为 HTTP / HTTPS');
79
+ }
80
+ if (engine === 'automation' && !String(raw.file || '').trim())
81
+ fail('请选择指定测试文件,避免误运行整个项目');
82
+ if (engine === 'automation' && !raw.projectId) fail('请选择已挂载的自动化项目');
83
+ const plan = {
84
+ version: 1,
85
+ id: crypto.randomUUID(),
86
+ casePath: document.path,
87
+ fileHash: document.fileHash,
88
+ provenance: document.provenance,
89
+ engine,
90
+ url: String(raw.url || ''),
91
+ storageStatePath: String(raw.storageStatePath || ''),
92
+ allowedOrigins: raw.allowedOrigins || [],
93
+ environment: {
94
+ name: String(raw.environment?.name || '').slice(0, 100),
95
+ role: String(raw.environment?.role || '').slice(0, 100),
96
+ build: String(raw.environment?.build || '').slice(0, 200),
97
+ dataNote: String(raw.environment?.dataNote || '').slice(0, 2000),
98
+ },
99
+ projectId: String(raw.projectId || ''),
100
+ taskId: String(raw.taskId || 'full'),
101
+ setupTaskId: String(raw.setupTaskId || ''),
102
+ cleanupTaskId: String(raw.cleanupTaskId || ''),
103
+ file: String(raw.file || ''),
104
+ items: cases.map((item) => ({
105
+ caseId: item.id,
106
+ title: item.title,
107
+ fingerprint: caseContentFingerprint(item),
108
+ status: 'pending',
109
+ runId: '',
110
+ error: '',
111
+ })),
112
+ status: 'draft',
113
+ error: '',
114
+ createdAt: new Date().toISOString(),
115
+ };
116
+ save(root, plan);
117
+ return view(plan);
118
+ }
119
+ async function execute(root, plan, state) {
120
+ try {
121
+ const snapshot = await loadCaseDocument(root, plan.casePath);
122
+ if (
123
+ snapshot.provenance?.stale ||
124
+ snapshot.provenance?.artifactId !== plan.provenance?.artifactId ||
125
+ snapshot.provenance?.analysisRevision !== plan.provenance?.analysisRevision ||
126
+ snapshot.provenance?.baselineId !== plan.provenance?.baselineId ||
127
+ snapshot.provenance?.sourcePath !== plan.provenance?.sourcePath
128
+ )
129
+ fail('计划需求基线已变化,请重新创建计划');
130
+ for (const item of plan.items) {
131
+ const current = snapshot.cases.find((row) => row.id === item.caseId);
132
+ if (!current || caseContentFingerprint(current) !== item.fingerprint)
133
+ fail('计划用例已变化,请重新创建计划');
134
+ }
135
+ if (state.stop) {
136
+ plan.status = 'stopped';
137
+ return;
138
+ }
139
+ if (plan.engine === 'automation') {
140
+ if (!isPluginOnInSpace('uiAuto', root)) fail('请开启自动化测试插件');
141
+ const runTask = async (taskId, label) => {
142
+ if (state.stop) return null;
143
+ const result = startAutomationProjectRun(root, {
144
+ projectId: plan.projectId,
145
+ taskId,
146
+ file: plan.file,
147
+ });
148
+ if (result.error) fail(result.error);
149
+ state.externalRunId = result.run.id;
150
+ plan.externalRunId = result.run.id;
151
+ plan.taskRuns ||= [];
152
+ plan.taskRuns.push({ label, runId: result.run.id, status: 'running' });
153
+ save(root, plan);
154
+ let run;
155
+ do {
156
+ run = readAutomationProjectRun(root, result.run.id);
157
+ plan.externalResult = {
158
+ id: run.id,
159
+ status: run.status,
160
+ total: run.total,
161
+ passed: run.passed,
162
+ failed: run.failed,
163
+ skipped: run.skipped,
164
+ reportUrl: run.reportUrl,
165
+ logUrl: run.logUrl,
166
+ error: run.error,
167
+ };
168
+ save(root, plan);
169
+ if (state.stop || run.status !== 'running') break;
170
+ await sleep(500);
171
+ } while (true);
172
+ plan.taskRuns[plan.taskRuns.length - 1].status = run.status;
173
+ state.externalRunId = '';
174
+ return run;
175
+ };
176
+ let result;
177
+ try {
178
+ if (plan.setupTaskId) {
179
+ const setup = await runTask(plan.setupTaskId, '准备数据');
180
+ if (setup?.status !== 'passed') fail('准备任务未成功,主测试未执行;请查看项目日志');
181
+ }
182
+ result = await runTask(plan.taskId, '测试执行');
183
+ } finally {
184
+ const primary = plan.externalResult;
185
+ if (plan.cleanupTaskId && !state.stop) {
186
+ const cleanup = await runTask(plan.cleanupTaskId, '清理数据');
187
+ if (cleanup?.status !== 'passed') plan.cleanupWarning = '清理任务未成功,请人工清理数据';
188
+ }
189
+ plan.externalResult = primary;
190
+ }
191
+ if (!result) {
192
+ plan.status = 'stopped';
193
+ return;
194
+ }
195
+ plan.items.forEach((item) => {
196
+ item.status = 'awaiting_confirmation';
197
+ item.externalRunId = result.id;
198
+ });
199
+ plan.note = '自动化项目汇总不等于每条业务用例通过,请核对报告后逐条手动选择结果';
200
+ } else
201
+ for (const item of plan.items.filter((item) =>
202
+ ['pending', 'interrupted'].includes(item.status),
203
+ )) {
204
+ if (state.stop) break;
205
+ const document = await loadCaseDocument(root, plan.casePath);
206
+ const row = document.cases.find((row) => row.id === item.caseId);
207
+ if (
208
+ !row ||
209
+ caseContentFingerprint(row) !== item.fingerprint ||
210
+ document.provenance?.stale ||
211
+ document.provenance?.analysisRevision !== plan.provenance?.analysisRevision ||
212
+ document.provenance?.baselineId !== plan.provenance?.baselineId
213
+ )
214
+ fail('用例内容或需求基线已变化,计划已阻塞');
215
+ const run = await startRun(root, {
216
+ casePath: plan.casePath,
217
+ rowIndex: row.rowIndex,
218
+ url: plan.url,
219
+ storageStatePath: plan.storageStatePath,
220
+ allowedOrigins: plan.allowedOrigins,
221
+ environment: plan.environment,
222
+ });
223
+ state.runId = run.id;
224
+ if (state.stop) stopRun(root, run.id);
225
+ item.runId = run.id;
226
+ item.status = 'running';
227
+ save(root, plan);
228
+ let latest = run;
229
+ while (!state.stop && latest.status === 'running') {
230
+ await sleep(500);
231
+ latest = getRun(root, run.id);
232
+ }
233
+ item.status = state.stop ? 'interrupted' : 'awaiting_confirmation';
234
+ item.error = latest.error || '';
235
+ save(root, plan);
236
+ state.runId = '';
237
+ }
238
+ plan.status = state.stop ? 'stopped' : 'awaiting_confirmation';
239
+ } catch (error) {
240
+ plan.status = state.stop ? 'stopped' : 'blocked';
241
+ plan.error = state.stop ? '用户已停止计划;未完成项可显式继续' : error.message;
242
+ } finally {
243
+ save(root, plan);
244
+ active.delete(key(root, plan.id));
245
+ }
246
+ }
247
+ export function startExecutionPlan(root, id) {
248
+ if (active.size) fail('已有执行计划运行中', 409);
249
+ const plan = read(root, id);
250
+ if (!['draft', 'interrupted', 'stopped', 'blocked'].includes(plan.status))
251
+ fail('此计划不可重复启动;重跑请新建计划', 409);
252
+ const state = { stop: false, runId: '', externalRunId: '' };
253
+ active.set(key(root, id), state);
254
+ plan.status = 'running';
255
+ plan.error = '';
256
+ save(root, plan);
257
+ void execute(root, plan, state);
258
+ return view(plan);
259
+ }
260
+ export function stopExecutionPlan(root, id) {
261
+ const state = active.get(key(root, id));
262
+ if (state) {
263
+ state.stop = true;
264
+ if (state.runId) stopRun(root, state.runId);
265
+ if (state.externalRunId) stopAutomationProjectRun(state.externalRunId);
266
+ }
267
+ return view(read(root, id));
268
+ }
269
+
270
+ export async function verifyExecutionPlanItem(root, id, raw) {
271
+ const plan = read(root, id);
272
+ if (plan.status === 'running' || active.has(key(root, id)))
273
+ fail('计划仍在执行,请结束或停止后验证', 409);
274
+ const item = plan.items.find((item) => item.caseId === raw.caseId);
275
+ if (!item || (!item.runId && !item.externalRunId)) fail('该用例没有本计划的执行记录', 409);
276
+ const document = await loadCaseDocument(root, plan.casePath);
277
+ const row = document.cases.find((row) => row.id === item.caseId);
278
+ if (
279
+ !row ||
280
+ caseContentFingerprint(row) !== item.fingerprint ||
281
+ document.provenance?.stale ||
282
+ document.provenance?.baselineId !== plan.provenance?.baselineId
283
+ )
284
+ fail('计划用例或需求基线已变化,请重新执行', 409);
285
+ if (!String(raw.actualResult || '').trim()) fail('请先填写人工核验的实际结果');
286
+ let applied;
287
+ if (item.runId) {
288
+ applied = await confirmRun(root, item.runId, {
289
+ ...raw,
290
+ executor: '人工验证',
291
+ expectedFileHash: raw.expectedFileHash,
292
+ });
293
+ } else {
294
+ applied = await applyCaseExecutionResult(root, {
295
+ path: plan.casePath,
296
+ rowIndex: row.rowIndex,
297
+ expectedFileHash: raw.expectedFileHash,
298
+ status: raw.status,
299
+ actualResult: String(raw.actualResult),
300
+ executor: '人工验证',
301
+ executedAt: new Date().toISOString(),
302
+ evidence: plan.externalResult?.reportUrl || plan.externalResult?.logUrl || '',
303
+ defectNo: row.defectNo,
304
+ });
305
+ recordManualVerification(
306
+ root,
307
+ await loadCaseDocument(root, plan.casePath),
308
+ row.rowIndex,
309
+ plan.environment,
310
+ );
311
+ }
312
+ item.finalStatus = raw.status;
313
+ item.status = 'verified';
314
+ item.verifiedAt = new Date().toISOString();
315
+ if (plan.items.every((item) => item.status === 'verified')) plan.status = 'completed';
316
+ save(root, plan);
317
+ return { ok: true, plan: view(plan), applied };
318
+ }
@@ -1,3 +1,5 @@
1
+ import { caseContentFingerprint, recordManualVerification } from './assets.mjs';
2
+ import { assertTargetUrl, assessExecutionEvidence } from '../../builtin/case-workflow-contract.mjs';
1
3
  import crypto from 'node:crypto';
2
4
  import fs from 'node:fs';
3
5
  import path from 'node:path';
@@ -194,7 +196,7 @@ function listRuns(root, casePath = '') {
194
196
  .filter((run) => !casePath || run.casePath === casePath)
195
197
  .sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt)))
196
198
  .slice(0, 200)
197
- .map(publicRun);
199
+ .map((run) => publicRun(loadRun(root, run.id)));
198
200
  }
199
201
 
200
202
  function shotsDir(root, runId) {
@@ -442,7 +444,11 @@ async function callModel(settings, messages, signal) {
442
444
  async function executeTool(root, run, name, args) {
443
445
  if (name === 'case_browser_open') {
444
446
  const result = await callExplorer(run.id, 'open', {
445
- url: str(args.url, 2000) || run.target.url,
447
+ url: assertTargetUrl(
448
+ str(args.url, 2000) || run.target.url,
449
+ run.target.url,
450
+ run.target.allowedOrigins || [],
451
+ ),
446
452
  settle: 450,
447
453
  });
448
454
  return {
@@ -536,7 +542,7 @@ async function executeRun(root, run, skill, settings, signal) {
536
542
  saveRun(root, run);
537
543
  appendEvent(run, { type: 'status', title: '开始执行', detail: run.case.title }, root);
538
544
  fs.mkdirSync(caseExecutionRoot(root), { recursive: true });
539
- if (!run.target.authPath || !fs.existsSync(run.target.authPath)) {
545
+ if (run.target.authPath && !fs.existsSync(run.target.authPath)) {
540
546
  throw new Error('目标登录态不存在,请先填写登录态文件或完成手动登录');
541
547
  }
542
548
  await startExplorer({
@@ -546,6 +552,7 @@ async function executeRun(root, run, skill, settings, signal) {
546
552
  baseURL: run.target.url,
547
553
  headed: true,
548
554
  storageState: run.target.authPath,
555
+ allowedOrigins: [new URL(run.target.url).origin, ...(run.target.allowedOrigins || [])],
549
556
  });
550
557
  fs.mkdirSync(shotsDir(root, run.id), { recursive: true });
551
558
  const messages = modelMessages(skill, run);
@@ -638,6 +645,24 @@ async function executeRun(root, run, skill, settings, signal) {
638
645
  );
639
646
  try {
640
647
  const output = await executeTool(root, run, name, args);
648
+ if (output.snapshot) {
649
+ const snapshot = String(output.snapshot)
650
+ .replace(/(Bearer\s+)[A-Za-z0-9._~+\/=-]+/gi, '$1[已隐藏]')
651
+ .replace(
652
+ /((?:password|token|api[_-]?key|authorization)\s*[:=]\s*)[^\s,;]+/gi,
653
+ '$1[已隐藏]',
654
+ );
655
+ appendEvent(
656
+ run,
657
+ {
658
+ type: 'observation',
659
+ title: '页面观察证据',
660
+ url: output.url || '',
661
+ detail: clip(snapshot, 12000),
662
+ },
663
+ root,
664
+ );
665
+ }
641
666
  messages.push({
642
667
  role: 'tool',
643
668
  tool_call_id: str(call?.id, 200),
@@ -679,6 +704,12 @@ async function executeRun(root, run, skill, settings, signal) {
679
704
  if (!run.result && !result.actualResult) {
680
705
  result.actualResult = result.blocker || result.rationale || '未完成用例执行';
681
706
  }
707
+ run.evidenceAssessment = assessExecutionEvidence(result, run.events);
708
+ if (result.status === '通过' && !run.evidenceAssessment.sufficient) {
709
+ result.status = '阻塞';
710
+ result.blocker = '证据不足:' + run.evidenceAssessment.issues.join(';');
711
+ result.unverified = [...new Set([...result.unverified, ...run.evidenceAssessment.issues])];
712
+ }
682
713
  run.result = result;
683
714
  run.status = 'awaiting_confirmation';
684
715
  run.progress.label = '执行完成,等待确认';
@@ -741,15 +772,13 @@ export function startRun(root, raw) {
741
772
  const rowIndex = Number(raw.rowIndex);
742
773
  const url = targetUrl(raw.url || raw.targetUrl);
743
774
  const authPath = str(raw.storageStatePath, 2000) || savedAuthPath(root, url) || '';
744
- if (!authPath) {
745
- throw Object.assign(new Error('请先填写登录态文件或完成手动登录'), { statusCode: 400 });
746
- }
747
- const authAbs = path.resolve(authPath);
748
- if (!fs.existsSync(authAbs) || !fs.statSync(authAbs).isFile()) {
775
+ const authAbs = authPath ? path.resolve(authPath) : '';
776
+ if (authAbs && (!fs.existsSync(authAbs) || !fs.statSync(authAbs).isFile()))
749
777
  throw Object.assign(new Error('登录态文件不存在'), { statusCode: 400 });
750
- }
751
778
  return (async () => {
752
779
  const document = await loadCaseDocument(root, casePath);
780
+ if (ACTIVE.size)
781
+ throw Object.assign(new Error('已有用例正在执行,请等待结束'), { statusCode: 409 });
753
782
  if (!document.executable) {
754
783
  throw Object.assign(new Error(document.executionIssue), {
755
784
  statusCode: 422,
@@ -767,6 +796,22 @@ export function startRun(root, raw) {
767
796
  target: url,
768
797
  authPath: authAbs,
769
798
  });
799
+ run.target.allowedOrigins = (Array.isArray(raw.allowedOrigins) ? raw.allowedOrigins : [])
800
+ .slice(0, 20)
801
+ .map((value) => new URL(targetUrl(value)).origin);
802
+ run.environment = {
803
+ name: str(raw.environment?.name, 100),
804
+ role: str(raw.environment?.role, 100),
805
+ build: str(raw.environment?.build, 200),
806
+ dataNote: str(raw.environment?.dataNote, 2000),
807
+ };
808
+ run.caseId = caseData.id;
809
+ run.caseFingerprint = caseContentFingerprint(caseData);
810
+ run.provenance = document.provenance;
811
+ if (document.provenance?.stale)
812
+ throw Object.assign(new Error('需求基线已变化,请重新生成或重新关联用例后执行'), {
813
+ statusCode: 409,
814
+ });
770
815
  const settings = resolveModelForSpace(root);
771
816
  if (!settings.baseURL || !settings.apiKey || !settings.model) {
772
817
  throw Object.assign(new Error('请先在模型设置中配置可用模型'), { statusCode: 400 });
@@ -815,21 +860,43 @@ export async function confirmRun(root, runId, raw) {
815
860
  if (!actualResult) {
816
861
  throw Object.assign(new Error('实际结果不能为空'), { statusCode: 400 });
817
862
  }
863
+ const currentDocument = await loadCaseDocument(root, run.casePath);
864
+ const currentCase = run.caseId
865
+ ? currentDocument.cases.find((item) => item.id === run.caseId)
866
+ : currentDocument.cases[run.rowIndex];
867
+ if (
868
+ !currentCase ||
869
+ (run.caseFingerprint && caseContentFingerprint(currentCase) !== run.caseFingerprint) ||
870
+ currentDocument.provenance?.stale ||
871
+ (run.provenance?.baselineId &&
872
+ currentDocument.provenance?.baselineId !== run.provenance.baselineId)
873
+ ) {
874
+ throw Object.assign(new Error('用例内容或需求基线已变化,请重新执行;历史结果保留'), {
875
+ statusCode: 409,
876
+ });
877
+ }
818
878
  const applied = await applyCaseExecutionResult(root, {
819
879
  path: run.casePath,
820
- expectedFileHash: run.fileHash,
821
- rowIndex: run.rowIndex,
880
+ expectedFileHash: raw.expectedFileHash || run.fileHash,
881
+ rowIndex: currentCase.rowIndex,
822
882
  status,
823
883
  actualResult,
824
- executor: str(raw.executor, 200) || 'AI + 人工确认',
884
+ executor: str(raw.executor, 200) || '人工验证',
825
885
  executedAt: now().replace('T', ' ').slice(0, 19),
826
886
  evidence: run.events
827
887
  .filter((event) => event.type === 'screenshot')
828
888
  .map((event) => event.url)
829
889
  .slice(-8)
830
890
  .join('\n'),
831
- defectNo: str(raw.defectNo, 200),
891
+ defectNo: raw.defectNo === undefined ? currentCase.defectNo : str(raw.defectNo, 200),
832
892
  });
893
+ recordManualVerification(
894
+ root,
895
+ await loadCaseDocument(root, run.casePath),
896
+ currentCase.rowIndex,
897
+ run.environment,
898
+ );
899
+ run.fileHash = applied.fileHash;
833
900
  run.status = 'confirmed';
834
901
  run.confirmed = {
835
902
  status,
@@ -13,7 +13,10 @@ export const CASE_EXECUTION_PROMPT_TEMPLATE = `# 用例执行
13
13
  5. 用例缺少可执行步骤、预期不可判定或存在歧义时判定“阻塞”,并说明缺少什么。
14
14
  6. 对关键结果、失败位置和阻塞位置保留截图;同时检查控制台错误和失败网络请求。
15
15
  7. 用例要求的文件上传、系统原生弹窗、支付、短信验证码或不可逆高风险动作无法通过浏览器工具完成时,返回“阻塞”。
16
- 8. 不直接修改用例文件、不创建缺陷、不更新统计。只提交执行结论,由页面保存到用例文件并允许用户继续修正。
16
+ 8. 不直接修改用例文件、不创建缺陷、不更新统计。只提交执行结论,保留为待验证建议。由用户核对证据后手动选择最终执行状态;不得自动写入通过或伪称人工确认。
17
+
18
+ 9. 访问地址必须在本次授权的目标 origin 或明确允许的登录 origin 中。脚本跳转、弹窗和 301 / 302 / 303 / 307 / 308 的每一跳都受此限制;导航被拦截时立即返回“阻塞”,说明目标地址,不得继续猜测页面内容。
19
+ 10. 每个步骤必须包含实际观察及证据,存在未验证步骤或证据不足时不得建议通过。
17
20
 
18
21
  ## 输出要求
19
22