@hamsterbase/evidra 0.0.0-stage → 0.1.0

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 (228) hide show
  1. package/README.md +2 -2
  2. package/bin/evidra.mjs +2 -0
  3. package/dist/sdk/main.d.ts +176 -0
  4. package/dist/sdk/main.js +1322 -0
  5. package/dist/service/cli.js +2645 -0
  6. package/dist/types/modules/core/contracts/comparison.d.ts +41 -0
  7. package/dist/types/modules/core/contracts/config.d.ts +19 -0
  8. package/dist/types/modules/core/contracts/context.d.ts +6 -0
  9. package/dist/types/modules/core/contracts/functions/addCase.d.ts +128 -0
  10. package/dist/types/modules/core/contracts/functions/addTask.d.ts +14 -0
  11. package/dist/types/modules/core/contracts/functions/approve.d.ts +8 -0
  12. package/dist/types/modules/core/contracts/functions/baselineChanges.d.ts +14 -0
  13. package/dist/types/modules/core/contracts/functions/compare.d.ts +14 -0
  14. package/dist/types/modules/core/contracts/functions/compareTask.d.ts +6 -0
  15. package/dist/types/modules/core/contracts/functions/compareTasks.d.ts +18 -0
  16. package/dist/types/modules/core/contracts/functions/deleteBaselineFile.d.ts +8 -0
  17. package/dist/types/modules/core/contracts/functions/finishTask.d.ts +8 -0
  18. package/dist/types/modules/core/contracts/functions/getBaseline.d.ts +10 -0
  19. package/dist/types/modules/core/contracts/functions/getBaselineChanges.d.ts +6 -0
  20. package/dist/types/modules/core/contracts/functions/getGitChanges.d.ts +6 -0
  21. package/dist/types/modules/core/contracts/functions/getGitDiff.d.ts +8 -0
  22. package/dist/types/modules/core/contracts/functions/getTaskCase.d.ts +23 -0
  23. package/dist/types/modules/core/contracts/functions/getTaskTree.d.ts +21 -0
  24. package/dist/types/modules/core/contracts/functions/gitChanges.d.ts +25 -0
  25. package/dist/types/modules/core/contracts/functions/index.d.ts +18 -0
  26. package/dist/types/modules/core/contracts/functions/listBaselines.d.ts +5 -0
  27. package/dist/types/modules/core/contracts/functions/listRuns.d.ts +7 -0
  28. package/dist/types/modules/core/contracts/functions/listTaskSummaries.d.ts +15 -0
  29. package/dist/types/modules/core/contracts/functions/listTasks.d.ts +15 -0
  30. package/dist/types/modules/core/contracts/functions/loadConfig.d.ts +5 -0
  31. package/dist/types/modules/core/contracts/functions/readProjectInfo.d.ts +5 -0
  32. package/dist/types/modules/core/contracts/functions/readTaskReport.d.ts +6 -0
  33. package/dist/types/modules/core/contracts/functions/resolveConfig.d.ts +6 -0
  34. package/dist/types/modules/core/contracts/functions/reviewBaselineChanges.d.ts +9 -0
  35. package/dist/types/modules/core/contracts/functions/reviewCodeChanges.d.ts +9 -0
  36. package/dist/types/modules/core/contracts/functions/taskRecords.d.ts +6 -0
  37. package/dist/types/modules/core/contracts/functions/updateBaseline.d.ts +20 -0
  38. package/dist/types/modules/core/contracts/git.d.ts +14 -0
  39. package/dist/types/modules/core/contracts/imageDiffPool.d.ts +5 -0
  40. package/dist/types/modules/core/contracts/index.d.ts +30 -0
  41. package/dist/types/modules/core/contracts/internal/compare.d.ts +14 -0
  42. package/dist/types/modules/core/contracts/internal/getBaseline.d.ts +10 -0
  43. package/dist/types/modules/core/contracts/internal/listTasks.d.ts +12 -0
  44. package/dist/types/modules/core/contracts/internal/taskRecords.d.ts +6 -0
  45. package/dist/types/modules/core/contracts/internal/updateBaseline.d.ts +20 -0
  46. package/dist/types/modules/core/contracts/model.d.ts +80 -0
  47. package/dist/types/modules/core/contracts/report.d.ts +52 -0
  48. package/dist/types/modules/core/contracts/repository.d.ts +5 -0
  49. package/dist/types/modules/core/contracts/requests.d.ts +23 -0
  50. package/dist/types/modules/core/contracts/scanCases.d.ts +15 -0
  51. package/dist/types/modules/core/contracts/shared.d.ts +6 -0
  52. package/dist/types/modules/core/contracts/snapshots.d.ts +6 -0
  53. package/dist/types/modules/core/contracts/taskRecord.d.ts +76 -0
  54. package/dist/types/modules/core/implementations/Functions/addCase.d.ts +4 -0
  55. package/dist/types/modules/core/implementations/Functions/addTask.d.ts +4 -0
  56. package/dist/types/modules/core/implementations/Functions/approve.d.ts +6 -0
  57. package/dist/types/modules/core/implementations/Functions/compare.d.ts +15 -0
  58. package/dist/types/modules/core/implementations/Functions/compareTask.d.ts +3 -0
  59. package/dist/types/modules/core/implementations/Functions/compareTasks.d.ts +5 -0
  60. package/dist/types/modules/core/implementations/Functions/deleteBaselineFile.d.ts +4 -0
  61. package/dist/types/modules/core/implementations/Functions/finishTask.d.ts +4 -0
  62. package/dist/types/modules/core/implementations/Functions/getBaseline.d.ts +4 -0
  63. package/dist/types/modules/core/implementations/Functions/getBaselineChanges.d.ts +4 -0
  64. package/dist/types/modules/core/implementations/Functions/getGitChanges.d.ts +3 -0
  65. package/dist/types/modules/core/implementations/Functions/getGitDiff.d.ts +3 -0
  66. package/dist/types/modules/core/implementations/Functions/getTaskCase.d.ts +5 -0
  67. package/dist/types/modules/core/implementations/Functions/getTaskTree.d.ts +5 -0
  68. package/dist/types/modules/core/implementations/Functions/listBaselines.d.ts +3 -0
  69. package/dist/types/modules/core/implementations/Functions/listTaskSummaries.d.ts +2 -0
  70. package/dist/types/modules/core/implementations/Functions/listTasks.d.ts +4 -0
  71. package/dist/types/modules/core/implementations/Functions/loadConfig.d.ts +3 -0
  72. package/dist/types/modules/core/implementations/Functions/readProjectInfo.d.ts +3 -0
  73. package/dist/types/modules/core/implementations/Functions/readTaskReport.d.ts +3 -0
  74. package/dist/types/modules/core/implementations/Functions/resolveConfig.d.ts +9 -0
  75. package/dist/types/modules/core/implementations/Functions/reviewBaselineChanges.d.ts +4 -0
  76. package/dist/types/modules/core/implementations/Functions/reviewCodeChanges.d.ts +4 -0
  77. package/dist/types/modules/core/implementations/Functions/taskRecords.d.ts +4 -0
  78. package/dist/types/modules/core/implementations/Functions/updateBaseline.d.ts +5 -0
  79. package/dist/types/modules/core/implementations/Utils/assertNamespace.d.ts +1 -0
  80. package/dist/types/modules/core/implementations/Utils/canonical.d.ts +1 -0
  81. package/dist/types/modules/core/implementations/Utils/createTaskId.d.ts +1 -0
  82. package/dist/types/modules/core/implementations/Utils/deletionAllowed.d.ts +2 -0
  83. package/dist/types/modules/core/implementations/Utils/download.d.ts +3 -0
  84. package/dist/types/modules/core/implementations/Utils/hash.d.ts +1 -0
  85. package/dist/types/modules/core/implementations/Utils/imageDiffPool.d.ts +18 -0
  86. package/dist/types/modules/core/implementations/Utils/imageKey.d.ts +1 -0
  87. package/dist/types/modules/core/implementations/Utils/loadBaseline.d.ts +4 -0
  88. package/dist/types/modules/core/implementations/Utils/mapLimit.d.ts +1 -0
  89. package/dist/types/modules/core/implementations/Utils/observationKey.d.ts +1 -0
  90. package/dist/types/modules/core/implementations/Utils/pngSize.d.ts +4 -0
  91. package/dist/types/modules/core/implementations/Utils/readJson.d.ts +1 -0
  92. package/dist/types/modules/core/implementations/Utils/readTaskRecord.d.ts +2 -0
  93. package/dist/types/modules/core/implementations/Utils/scanCases.d.ts +9 -0
  94. package/dist/types/modules/core/implementations/Utils/taskDirectory.d.ts +1 -0
  95. package/dist/types/modules/core/implementations/Utils/toCase.d.ts +3 -0
  96. package/dist/types/modules/core/implementations/Utils/toObservation.d.ts +3 -0
  97. package/dist/types/modules/core/implementations/Utils/toSnapshot.d.ts +3 -0
  98. package/dist/types/modules/core/implementations/Utils/writeBytesAtomic.d.ts +1 -0
  99. package/dist/types/modules/core/implementations/Utils/writeJsonAtomic.d.ts +1 -0
  100. package/dist/types/modules/core/implementations/Utils/writeTextAtomic.d.ts +1 -0
  101. package/dist/types/modules/core/implementations/baselineChanges.d.ts +6 -0
  102. package/dist/types/modules/core/implementations/config.d.ts +6 -0
  103. package/dist/types/modules/core/implementations/content.d.ts +1 -0
  104. package/dist/types/modules/core/implementations/evidra.d.ts +31 -0
  105. package/dist/types/modules/core/implementations/git.d.ts +11 -0
  106. package/dist/types/modules/core/implementations/gitChanges.d.ts +29 -0
  107. package/dist/types/modules/core/implementations/index.d.ts +17 -0
  108. package/dist/types/modules/core/implementations/internal/compare.d.ts +15 -0
  109. package/dist/types/modules/core/implementations/internal/getBaseline.d.ts +4 -0
  110. package/dist/types/modules/core/implementations/internal/listTasks.d.ts +2 -0
  111. package/dist/types/modules/core/implementations/internal/taskRecords.d.ts +4 -0
  112. package/dist/types/modules/core/implementations/internal/updateBaseline.d.ts +5 -0
  113. package/dist/types/modules/core/implementations/paths.d.ts +48 -0
  114. package/dist/types/modules/core/implementations/report.d.ts +3 -0
  115. package/dist/types/modules/core/implementations/reportResources.d.ts +4 -0
  116. package/dist/types/modules/core/implementations/reportStatus.d.ts +10 -0
  117. package/dist/types/modules/core/implementations/reportTree.d.ts +5 -0
  118. package/dist/types/modules/core/implementations/repository.d.ts +10 -0
  119. package/dist/types/modules/core/implementations/requests.d.ts +13 -0
  120. package/dist/types/modules/core/implementations/snapshots.d.ts +11 -0
  121. package/dist/types/modules/core/implementations/storage/local.d.ts +3 -0
  122. package/dist/types/modules/core/implementations/storage/objects.d.ts +3 -0
  123. package/dist/types/modules/core/index.d.ts +21 -0
  124. package/dist/types/packages/sdk/src/index.d.ts +21 -0
  125. package/dist/types/packages/sdk/src/types.d.ts +9 -0
  126. package/dist/web/assets/InterVariable-DiVDrmQJ.woff2 +0 -0
  127. package/dist/web/assets/abap-08VXUWAP.js +1 -0
  128. package/dist/web/assets/apex-BWPQTe0t.js +1 -0
  129. package/dist/web/assets/azcli-Bc_sGQ0U.js +1 -0
  130. package/dist/web/assets/bat-i0X4ZdIN.js +1 -0
  131. package/dist/web/assets/bicep-B5-_aFwp.js +2 -0
  132. package/dist/web/assets/cameligo-DMUM7wLl.js +1 -0
  133. package/dist/web/assets/clojure-Cm7r79vr.js +1 -0
  134. package/dist/web/assets/codicon-DF1abBS2.ttf +0 -0
  135. package/dist/web/assets/coffee-Ba7i2nA0.js +1 -0
  136. package/dist/web/assets/cpp-C7h46wYY.js +1 -0
  137. package/dist/web/assets/csharp-BKxtCVv1.js +1 -0
  138. package/dist/web/assets/csp-bTuwJoIa.js +1 -0
  139. package/dist/web/assets/css-DIMkf-bt.js +3 -0
  140. package/dist/web/assets/css.worker-DwfUZ3fB.js +96 -0
  141. package/dist/web/assets/cssMode-B8lMpRZk.js +1 -0
  142. package/dist/web/assets/cypher-CVaqCwHa.js +1 -0
  143. package/dist/web/assets/dart-onAF5SnQ.js +1 -0
  144. package/dist/web/assets/dockerfile-DZFCIeNp.js +1 -0
  145. package/dist/web/assets/ecl-94qehhXe.js +1 -0
  146. package/dist/web/assets/editor-DjpsE8to.css +1 -0
  147. package/dist/web/assets/editor.api-v7kHj8A9.js +908 -0
  148. package/dist/web/assets/editor.worker-CRz__AKW.js +33 -0
  149. package/dist/web/assets/elixir-6RTg0lbw.js +1 -0
  150. package/dist/web/assets/flow9-C5_-GSwl.js +1 -0
  151. package/dist/web/assets/freemarker2-DGeBHzes.js +3 -0
  152. package/dist/web/assets/fsharp-C8Ef5oNN.js +1 -0
  153. package/dist/web/assets/go-C-y9NEjX.js +1 -0
  154. package/dist/web/assets/graphql-fmXr3nnJ.js +1 -0
  155. package/dist/web/assets/handlebars-CJj8r50C.js +1 -0
  156. package/dist/web/assets/hcl-CpzslTdj.js +1 -0
  157. package/dist/web/assets/html-DjzDFsf0.js +1 -0
  158. package/dist/web/assets/html.worker-D9ugpX4y.js +509 -0
  159. package/dist/web/assets/htmlMode-CkwZJBoD.js +1 -0
  160. package/dist/web/assets/index-CSk5TcTU.js +37 -0
  161. package/dist/web/assets/index-jRxy440Y.css +2 -0
  162. package/dist/web/assets/ini-sBoK_t0W.js +1 -0
  163. package/dist/web/assets/java-BEtHBSE6.js +1 -0
  164. package/dist/web/assets/javascript-C-MAHJiN.js +1 -0
  165. package/dist/web/assets/json.worker-CV9fqkUp.js +65 -0
  166. package/dist/web/assets/jsonMode-CkXjaZv2.js +7 -0
  167. package/dist/web/assets/julia-Bri6UV-V.js +1 -0
  168. package/dist/web/assets/kotlin-BOotOW0E.js +1 -0
  169. package/dist/web/assets/less-B9JPFI3C.js +2 -0
  170. package/dist/web/assets/lexon-CfSJPG6W.js +1 -0
  171. package/dist/web/assets/liquid-7k8-ZDme.js +1 -0
  172. package/dist/web/assets/lspLanguageFeatures-CUP45dUg.js +4 -0
  173. package/dist/web/assets/lua-CsQS60Ue.js +1 -0
  174. package/dist/web/assets/m3-D-oSqn_W.js +1 -0
  175. package/dist/web/assets/markdown-Cimd5fb3.js +1 -0
  176. package/dist/web/assets/mdx-D-hYSOvW.js +1 -0
  177. package/dist/web/assets/mips-CIPQ_RoX.js +1 -0
  178. package/dist/web/assets/monaco-Dq3bzBUw.js +58 -0
  179. package/dist/web/assets/monaco-n7clI0si.css +1 -0
  180. package/dist/web/assets/msdax-DauUninz.js +1 -0
  181. package/dist/web/assets/mysql-SOo6toE5.js +1 -0
  182. package/dist/web/assets/objective-c-FvmIjYaQ.js +1 -0
  183. package/dist/web/assets/pascal-DrH0SRf2.js +1 -0
  184. package/dist/web/assets/pascaligo-D-ptJ9y-.js +1 -0
  185. package/dist/web/assets/perl-oz_6vUea.js +1 -0
  186. package/dist/web/assets/pgsql-DTj74zXo.js +1 -0
  187. package/dist/web/assets/php-nr791fC2.js +1 -0
  188. package/dist/web/assets/pla-CopQ2nXW.js +1 -0
  189. package/dist/web/assets/postiats-43DmfD33.js +1 -0
  190. package/dist/web/assets/powerquery-D3hlyOfw.js +1 -0
  191. package/dist/web/assets/powershell-DmHpPYUd.js +1 -0
  192. package/dist/web/assets/protobuf-C531GsRP.js +2 -0
  193. package/dist/web/assets/pug-Z5eAx3Zn.js +1 -0
  194. package/dist/web/assets/python-BpkAjkSI.js +1 -0
  195. package/dist/web/assets/qsharp-DkqhCAOL.js +1 -0
  196. package/dist/web/assets/r-BwWrilGY.js +1 -0
  197. package/dist/web/assets/razor-CxgXgZt1.js +1 -0
  198. package/dist/web/assets/redis-ClamHrr6.js +1 -0
  199. package/dist/web/assets/redshift-DT7zqm-g.js +1 -0
  200. package/dist/web/assets/restructuredtext-BYgofb2h.js +1 -0
  201. package/dist/web/assets/ruby-DezsRK8O.js +1 -0
  202. package/dist/web/assets/rust-DdL9SqIa.js +1 -0
  203. package/dist/web/assets/sb-CcwsVR0C.js +1 -0
  204. package/dist/web/assets/scala-DHpiXF5c.js +1 -0
  205. package/dist/web/assets/scheme-BeGwcela.js +1 -0
  206. package/dist/web/assets/scss-gp-XZpBa.js +3 -0
  207. package/dist/web/assets/shell-CC2rA5mh.js +1 -0
  208. package/dist/web/assets/solidity-BEEn4gHE.js +1 -0
  209. package/dist/web/assets/sophia-CRfGWb83.js +1 -0
  210. package/dist/web/assets/sparql-D_Lu-MrJ.js +1 -0
  211. package/dist/web/assets/sql-NEE52Syq.js +1 -0
  212. package/dist/web/assets/st-DbInun42.js +1 -0
  213. package/dist/web/assets/swift-Bxkupp3x.js +1 -0
  214. package/dist/web/assets/systemverilog-Bz4Y3fRF.js +1 -0
  215. package/dist/web/assets/tcl-DISqw1ZD.js +1 -0
  216. package/dist/web/assets/ts.worker-DIAQkoB3.js +67741 -0
  217. package/dist/web/assets/tsMode-BUKs-FlJ.js +11 -0
  218. package/dist/web/assets/twig-De2hgUGE.js +1 -0
  219. package/dist/web/assets/typescript-DVSIawmK.js +1 -0
  220. package/dist/web/assets/typespec-B8J7ngcE.js +1 -0
  221. package/dist/web/assets/vb-DV3o63ZY.js +1 -0
  222. package/dist/web/assets/wgsl-DpFanUEy.js +298 -0
  223. package/dist/web/assets/workers-v4-uKnr3.js +1 -0
  224. package/dist/web/assets/xml-D2x86430.js +1 -0
  225. package/dist/web/assets/yaml-nb07hHZ9.js +1 -0
  226. package/dist/web/index.html +13 -0
  227. package/package.json +77 -4
  228. package/skills/evidra/SKILL.md +112 -0
@@ -0,0 +1,2645 @@
1
+ // packages/service/src/cli.ts
2
+ import { cac } from "cac";
3
+ import path30 from "node:path";
4
+
5
+ // modules/core/implementations/Functions/resolveConfig.ts
6
+ import path3 from "node:path";
7
+
8
+ // modules/core/contracts/functions/resolveConfig.ts
9
+ import { z } from "zod";
10
+ var ResolveConfigInputSchema = z.object({
11
+ repoRoot: z.string(),
12
+ namespace: z.string().optional()
13
+ });
14
+
15
+ // modules/core/implementations/Functions/loadConfig.ts
16
+ import path2 from "node:path";
17
+ import { readFile } from "node:fs/promises";
18
+
19
+ // modules/core/contracts/functions/loadConfig.ts
20
+ import { z as z2 } from "zod";
21
+ var LoadConfigInputSchema = z2.object({ repoRoot: z2.string() });
22
+
23
+ // modules/core/implementations/config.ts
24
+ import path from "node:path";
25
+
26
+ // modules/core/contracts/config.ts
27
+ import { z as z3 } from "zod";
28
+ var NamespaceSchema = z3.object({
29
+ id: z3.string().regex(/^[A-Za-z0-9-]+$/),
30
+ name: z3.string().trim().min(1)
31
+ });
32
+ var ConfigSchema = z3.object({
33
+ reportDir: z3.string().min(1).optional(),
34
+ storage: z3.enum(["s3", "local"]).default("local"),
35
+ namespaces: z3.array(NamespaceSchema)
36
+ });
37
+
38
+ // modules/core/implementations/config.ts
39
+ var CONFIG_NAME = "evidra.config.json";
40
+ function namespaceId(value) {
41
+ if (typeof value !== "string" || !/^[A-Za-z0-9-]+$/.test(value))
42
+ throw new Error(`\u975E\u6CD5 namespace ID: ${String(value)}`);
43
+ }
44
+ function parseConfig(config) {
45
+ const value = ConfigSchema.parse(config);
46
+ const dir = value.reportDir ?? ".test-report";
47
+ if (path.isAbsolute(dir) || dir.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
48
+ throw new Error("reportDir \u5FC5\u987B\u662F\u4ED3\u5E93\u5185\u7684\u76F8\u5BF9\u76EE\u5F55");
49
+ const ids = /* @__PURE__ */ new Set();
50
+ for (const namespace of value.namespaces) {
51
+ namespaceId(namespace.id);
52
+ if (ids.has(namespace.id)) throw new Error(`\u91CD\u590D namespace: ${namespace.id}`);
53
+ ids.add(namespace.id);
54
+ }
55
+ return {
56
+ reportDir: dir,
57
+ storage: value.storage,
58
+ namespaces: value.namespaces.map(({ id, name }) => ({ id, name }))
59
+ };
60
+ }
61
+
62
+ // modules/core/implementations/Functions/loadConfig.ts
63
+ async function loadConfig(input) {
64
+ const { repoRoot } = LoadConfigInputSchema.parse(input);
65
+ return parseConfig(JSON.parse(await readFile(path2.join(repoRoot, CONFIG_NAME), "utf8")));
66
+ }
67
+
68
+ // modules/core/implementations/Functions/resolveConfig.ts
69
+ async function resolveConfig(input) {
70
+ const { repoRoot, namespace } = ResolveConfigInputSchema.parse(input);
71
+ if (typeof repoRoot !== "string" || !path3.isAbsolute(repoRoot))
72
+ throw new Error("repoRoot \u5FC5\u987B\u662F\u663E\u5F0F\u4F20\u5165\u7684\u7EDD\u5BF9\u8DEF\u5F84");
73
+ const config = await loadConfig({ repoRoot });
74
+ const namespaceList = config.namespaces;
75
+ if (namespace !== void 0 && !namespaceList.some((item) => item.id === namespace))
76
+ throw new Error(`\u672A\u914D\u7F6E namespace: ${namespace}`);
77
+ return {
78
+ absoluteReportPath: path3.join(repoRoot, config.reportDir),
79
+ namespaceList
80
+ };
81
+ }
82
+
83
+ // modules/core/implementations/Utils/hash.ts
84
+ import { createHash } from "node:crypto";
85
+ var hash = (value) => createHash("sha256").update(value).digest("hex");
86
+
87
+ // modules/core/implementations/Utils/writeBytesAtomic.ts
88
+ import { randomUUID } from "node:crypto";
89
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
90
+ import path4 from "node:path";
91
+ async function writeBytesAtomic(file, body) {
92
+ await mkdir(path4.dirname(file), { recursive: true });
93
+ const temporary = `${file}.${randomUUID()}.tmp`;
94
+ try {
95
+ await writeFile(temporary, body);
96
+ await rename(temporary, file);
97
+ } finally {
98
+ await rm(temporary, { force: true });
99
+ }
100
+ }
101
+
102
+ // modules/core/implementations/storage/local.ts
103
+ import { readFile as readFile2 } from "node:fs/promises";
104
+ import path5 from "node:path";
105
+ function imageFile(reportDir, key) {
106
+ const root = path5.resolve(reportDir, "objects");
107
+ const target = path5.resolve(root, key);
108
+ if (!target.startsWith(root + path5.sep)) throw new Error(`\u975E\u6CD5\u5B58\u50A8 key: ${key}`);
109
+ return target;
110
+ }
111
+ async function readTaskImage(reportDir, key) {
112
+ const body = await readFile2(imageFile(reportDir, key));
113
+ return body;
114
+ }
115
+ function createLocalStorage(reportDir) {
116
+ const file = (key) => path5.join(reportDir, "baseline-assets", path5.basename(key));
117
+ return {
118
+ async localPath(key) {
119
+ await this.download(key);
120
+ return file(key);
121
+ },
122
+ async upload(key, body) {
123
+ await writeBytesAtomic(file(key), body);
124
+ },
125
+ async download(key) {
126
+ try {
127
+ return await readFile2(file(key));
128
+ } catch (error) {
129
+ if (error.code === "ENOENT")
130
+ throw new Error(`\u672C\u5730\u57FA\u7EBF\u56FE\u7247\u4E0D\u5B58\u5728: ${key}`);
131
+ throw error;
132
+ }
133
+ }
134
+ };
135
+ }
136
+
137
+ // modules/core/contracts/functions/addCase.ts
138
+ import { z as z5 } from "zod";
139
+
140
+ // modules/core/contracts/shared.ts
141
+ import { z as z4 } from "zod";
142
+ var IdSchema = z4.string().regex(/^[A-Za-z0-9-]+$/, "\u53EA\u5141\u8BB8\u5927\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E2D\u5212\u7EBF");
143
+ var NameSchema = z4.string().trim().min(1);
144
+ var ColSchema = z4.number().int("col \u5FC5\u987B\u4E3A 1 \u5230 12 \u7684\u6574\u6570").min(1, "col \u5FC5\u987B\u4E3A 1 \u5230 12 \u7684\u6574\u6570").max(12, "col \u5FC5\u987B\u4E3A 1 \u5230 12 \u7684\u6574\u6570");
145
+ var DateTimeSchema = z4.iso.datetime({ offset: true });
146
+ var TaskPathSchema = z4.string().regex(
147
+ /^\d{4}-\d{2}-\d{2}\/\d{2}-\d{2}-\d{2}-[A-Za-z0-9-]+$/,
148
+ "taskPath \u5FC5\u987B\u662F <yyyy-MM-dd>/<HH-mm-ss>-<taskId>"
149
+ );
150
+
151
+ // modules/core/contracts/functions/addCase.ts
152
+ var BytesSchema = z5.custom((value) => value instanceof Uint8Array, {
153
+ message: "\u56FE\u7247 body \u5FC5\u987B\u662F Uint8Array"
154
+ });
155
+ var TreeSegmentSchema = z5.object({
156
+ key: IdSchema,
157
+ display: NameSchema
158
+ });
159
+ var CaseResultSchema = z5.object({
160
+ status: z5.enum(["passed", "failed", "skipped", "interrupted"]),
161
+ durationMs: z5.number().int().nonnegative().optional(),
162
+ errors: z5.array(z5.string()).optional()
163
+ });
164
+ var SnapshotMetaSchema = z5.object({
165
+ id: IdSchema,
166
+ name: NameSchema,
167
+ col: ColSchema.optional()
168
+ });
169
+ var SnapshotInputSchema = z5.discriminatedUnion("type", [
170
+ SnapshotMetaSchema.extend({
171
+ type: z5.literal("text"),
172
+ body: z5.string(),
173
+ language: z5.string().optional()
174
+ }),
175
+ SnapshotMetaSchema.extend({
176
+ type: z5.literal("image"),
177
+ body: BytesSchema,
178
+ contentType: z5.literal("image/png"),
179
+ maxDiffPixels: z5.number({ error: "maxDiffPixels \u4EC5\u652F\u6301\u56FE\u7247\uFF0C\u4E14\u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570" }).int("maxDiffPixels \u4EC5\u652F\u6301\u56FE\u7247\uFF0C\u4E14\u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570").nonnegative("maxDiffPixels \u4EC5\u652F\u6301\u56FE\u7247\uFF0C\u4E14\u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570").optional()
180
+ })
181
+ ]);
182
+ var ObservationInputSchema = z5.discriminatedUnion("type", [
183
+ z5.object({
184
+ name: NameSchema,
185
+ type: z5.literal("text"),
186
+ body: z5.string(),
187
+ language: z5.string().optional()
188
+ }),
189
+ z5.object({
190
+ name: NameSchema,
191
+ type: z5.literal("image"),
192
+ body: BytesSchema,
193
+ contentType: z5.literal("image/png")
194
+ })
195
+ ]);
196
+ var CaseInputSchema = z5.object({
197
+ id: IdSchema,
198
+ name: NameSchema,
199
+ treePath: z5.array(TreeSegmentSchema),
200
+ snapshots: z5.array(SnapshotInputSchema).min(1, "snapshots \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u6570\u7EC4").nullable(),
201
+ result: CaseResultSchema,
202
+ observations: z5.array(ObservationInputSchema).optional()
203
+ }).superRefine((value, ctx) => {
204
+ if (value.snapshots === null && value.result.status !== "failed") {
205
+ ctx.addIssue({
206
+ code: "custom",
207
+ path: ["snapshots"],
208
+ message: "snapshots \u4EC5\u5728\u7528\u4F8B\u5931\u8D25\u65F6\u5141\u8BB8\u4E3A null"
209
+ });
210
+ }
211
+ if (value.snapshots) {
212
+ const ids = /* @__PURE__ */ new Set();
213
+ value.snapshots.forEach((snapshot, index) => {
214
+ if (ids.has(snapshot.id)) {
215
+ ctx.addIssue({
216
+ code: "custom",
217
+ path: ["snapshots", index, "id"],
218
+ message: `\u91CD\u590D\u5FEB\u7167 ID: ${snapshot.id}`
219
+ });
220
+ }
221
+ ids.add(snapshot.id);
222
+ });
223
+ }
224
+ });
225
+ var AddCaseInputSchema = z5.object({
226
+ repoRoot: z5.string(),
227
+ taskId: IdSchema,
228
+ case: CaseInputSchema
229
+ });
230
+
231
+ // modules/core/implementations/Utils/pngSize.ts
232
+ var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
233
+
234
+ // modules/core/implementations/internal/taskRecords.ts
235
+ import { readFile as readFile5 } from "node:fs/promises";
236
+ import path9 from "node:path";
237
+
238
+ // modules/core/implementations/paths.ts
239
+ import { format } from "date-fns";
240
+ import path6 from "node:path";
241
+ var pathSchema = {
242
+ taskIndex(root, taskId) {
243
+ return path6.join(root, "tasks", "_index", taskId.slice(0, 2), taskId.slice(2));
244
+ },
245
+ task(root, startedAt, taskId) {
246
+ const time = new Date(startedAt);
247
+ const day = format(time, "yyyy-MM-dd");
248
+ const clock = format(time, "HH-mm-ss");
249
+ const taskPath = `${day}/${clock}-${taskId}`;
250
+ const directory = path6.join(root, "tasks", ...taskPath.split("/"));
251
+ return { path: taskPath, directory, manifest: path6.join(directory, "task.json") };
252
+ },
253
+ baseline(root, namespace, casePath) {
254
+ const directory = path6.join(root, "baselines", namespace, ...casePath);
255
+ return {
256
+ directory,
257
+ manifest: path6.join(directory, "baseline.json")
258
+ };
259
+ },
260
+ cache(root) {
261
+ const directory = path6.join(root, "cache");
262
+ return {
263
+ directory,
264
+ baseline(namespace) {
265
+ const baselineDirectory = path6.join(directory, "baselines", namespace);
266
+ return {
267
+ directory: baselineDirectory,
268
+ snapshot: path6.join(baselineDirectory, "snapshot.json")
269
+ };
270
+ },
271
+ comparison(namespace, taskId) {
272
+ return comparisonPaths(path6.join(directory, "comparisons", namespace, taskId));
273
+ },
274
+ taskComparison(baseTaskId, taskId) {
275
+ return comparisonPaths(path6.join(directory, "task-comparisons", baseTaskId, taskId));
276
+ },
277
+ download(hash2) {
278
+ return path6.join(directory, "downloads", `${hash2}.png`);
279
+ }
280
+ };
281
+ }
282
+ };
283
+ function comparisonPaths(directory) {
284
+ const diffDirectory = path6.join(directory, "diff");
285
+ return {
286
+ directory,
287
+ index: path6.join(directory, "index.json"),
288
+ summary: path6.join(directory, "summary.json"),
289
+ diff: (caseId, snapshotId, contentHash) => path6.join(diffDirectory, caseId, `${snapshotId}-${contentHash}.png`)
290
+ };
291
+ }
292
+
293
+ // modules/core/implementations/Utils/readTaskRecord.ts
294
+ import { readFile as readFile4, readdir } from "node:fs/promises";
295
+ import path8 from "node:path";
296
+
297
+ // modules/core/contracts/taskRecord.ts
298
+ var TASK_SCEHAM_VERSION = 3;
299
+
300
+ // modules/core/implementations/Utils/readJson.ts
301
+ import { readFile as readFile3 } from "node:fs/promises";
302
+ async function readJson(file) {
303
+ try {
304
+ return JSON.parse(await readFile3(file, "utf8"));
305
+ } catch (error) {
306
+ if (error.code === "ENOENT") return null;
307
+ throw error;
308
+ }
309
+ }
310
+
311
+ // modules/core/implementations/Utils/writeJsonAtomic.ts
312
+ import { randomUUID as randomUUID2 } from "node:crypto";
313
+ import { mkdir as mkdir2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
314
+ import path7 from "node:path";
315
+ async function writeJsonAtomic(file, value) {
316
+ await mkdir2(path7.dirname(file), { recursive: true });
317
+ const temporary = `${file}.${randomUUID2()}.tmp`;
318
+ try {
319
+ await writeFile2(temporary, `${JSON.stringify(value, null, 2)}
320
+ `, "utf8");
321
+ await rename2(temporary, file);
322
+ } finally {
323
+ await rm2(temporary, { force: true });
324
+ }
325
+ }
326
+
327
+ // modules/core/implementations/Utils/readTaskRecord.ts
328
+ async function readTaskRecord(file) {
329
+ const manifest = JSON.parse(await readFile4(file, "utf8"));
330
+ if ((manifest.formatVersion ?? 0) < TASK_SCEHAM_VERSION)
331
+ throw new Error("\u62A5\u544A\u683C\u5F0F\u4E0D\u652F\u6301\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C\u6D4B\u8BD5");
332
+ const directory = path8.join(path8.dirname(file), "cases");
333
+ const files = (await readdir(directory)).filter((name) => name.endsWith(".json")).sort();
334
+ const listingHash = hash(JSON.stringify(files));
335
+ const cacheFile = path8.join(path8.dirname(file), "cache", "cases", `${listingHash}.json`);
336
+ let cases = await readJson(cacheFile);
337
+ if (!cases) {
338
+ cases = await Promise.all(
339
+ files.map(
340
+ async (name) => JSON.parse(await readFile4(path8.join(directory, name), "utf8"))
341
+ )
342
+ );
343
+ await writeJsonAtomic(cacheFile, cases);
344
+ }
345
+ return { task: { ...manifest.task, caseCount: cases.length }, cases };
346
+ }
347
+
348
+ // modules/core/implementations/internal/taskRecords.ts
349
+ async function getTask(cwd, taskId) {
350
+ if (!/^[a-zA-Z0-9_-]{3,}$/.test(taskId)) return null;
351
+ let taskPath;
352
+ try {
353
+ taskPath = await readFile5(pathSchema.taskIndex(cwd, taskId), "utf8");
354
+ } catch (error) {
355
+ if (error.code === "ENOENT") return null;
356
+ throw error;
357
+ }
358
+ if (!taskPath || taskPath.split("/").some((part) => !part || part === "." || part === "..") || path9.isAbsolute(taskPath))
359
+ throw new Error("\u4EFB\u52A1\u7D22\u5F15\u8DEF\u5F84\u65E0\u6548");
360
+ const record = await readTaskRecord(
361
+ path9.join(cwd, "tasks", ...taskPath.split("/"), "task.json")
362
+ ).catch((error) => {
363
+ if (error.code === "ENOENT") return null;
364
+ throw error;
365
+ });
366
+ if (!record || record.task.id !== taskId) return null;
367
+ return { taskPath, record };
368
+ }
369
+
370
+ // modules/core/implementations/Utils/taskDirectory.ts
371
+ import path10 from "node:path";
372
+ function taskDirectory(cwd, taskPath) {
373
+ return path10.join(cwd, "tasks", ...taskPath.split("/"));
374
+ }
375
+
376
+ // modules/core/implementations/Utils/toObservation.ts
377
+ function toObservation(observation) {
378
+ if (observation.type === "text") {
379
+ return {
380
+ name: observation.name,
381
+ type: "text",
382
+ body: observation.body,
383
+ language: observation.language
384
+ };
385
+ }
386
+ return {
387
+ name: observation.name,
388
+ type: "image",
389
+ key: observation.key,
390
+ contentType: observation.contentType,
391
+ width: observation.width,
392
+ height: observation.height
393
+ };
394
+ }
395
+
396
+ // modules/core/implementations/Utils/toSnapshot.ts
397
+ function toSnapshot(snapshot) {
398
+ if (snapshot.type === "text") {
399
+ return {
400
+ id: snapshot.id,
401
+ name: snapshot.name,
402
+ type: "text",
403
+ body: snapshot.body,
404
+ language: snapshot.language,
405
+ col: snapshot.col
406
+ };
407
+ }
408
+ return {
409
+ id: snapshot.id,
410
+ name: snapshot.name,
411
+ type: "image",
412
+ key: snapshot.key,
413
+ contentType: snapshot.contentType,
414
+ width: snapshot.width,
415
+ height: snapshot.height,
416
+ maxDiffPixels: snapshot.maxDiffPixels,
417
+ col: snapshot.col
418
+ };
419
+ }
420
+
421
+ // modules/core/implementations/Utils/toCase.ts
422
+ function toCase(value) {
423
+ return {
424
+ id: value.id,
425
+ name: value.name,
426
+ treePath: value.treePath,
427
+ snapshots: value.snapshots === null ? null : value.snapshots.map(toSnapshot),
428
+ result: value.result,
429
+ observations: value.observations.map(toObservation)
430
+ };
431
+ }
432
+
433
+ // modules/core/contracts/functions/addTask.ts
434
+ import { z as z6 } from "zod";
435
+ var AddTaskInputSchema = z6.object({
436
+ repoRoot: z6.string(),
437
+ namespace: IdSchema,
438
+ name: NameSchema,
439
+ startedAt: DateTimeSchema,
440
+ coverage: z6.enum(["partial", "complete"]).optional()
441
+ });
442
+
443
+ // modules/core/implementations/Utils/createTaskId.ts
444
+ import { customAlphabet } from "nanoid";
445
+ var generate = customAlphabet(
446
+ "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-",
447
+ 6
448
+ );
449
+
450
+ // modules/core/contracts/functions/finishTask.ts
451
+ import { z as z7 } from "zod";
452
+ var FinishTaskInputSchema = z7.object({
453
+ repoRoot: z7.string(),
454
+ taskId: IdSchema
455
+ });
456
+
457
+ // modules/core/contracts/functions/compareTask.ts
458
+ import { z as z8 } from "zod";
459
+ var CompareTaskInputSchema = z8.object({ repoRoot: z8.string(), taskId: z8.string() });
460
+
461
+ // modules/core/implementations/internal/compare.ts
462
+ import { access } from "node:fs/promises";
463
+ import path13 from "node:path";
464
+ import pixelmatch from "pixelmatch";
465
+ import { PNG } from "pngjs";
466
+
467
+ // modules/core/contracts/internal/compare.ts
468
+ import { z as z9 } from "zod";
469
+ var CompareInputSchema = z9.object({
470
+ taskId: z9.string().min(1)
471
+ });
472
+
473
+ // modules/core/implementations/Utils/deletionAllowed.ts
474
+ function deletionAllowed(record) {
475
+ return !!record.task.finishedAt && record.task.coverage === "complete";
476
+ }
477
+
478
+ // modules/core/implementations/Utils/download.ts
479
+ async function download(_cwd, storage, key) {
480
+ return Buffer.from(await storage.download(key));
481
+ }
482
+
483
+ // modules/core/implementations/Utils/imageDiffPool.ts
484
+ import { createRequire } from "node:module";
485
+ import { Worker } from "node:worker_threads";
486
+ var require2 = createRequire(import.meta.url);
487
+ var pngjsPath = require2.resolve("pngjs");
488
+ var pixelmatchPath = require2.resolve("pixelmatch");
489
+ var WORKER_CODE = `
490
+ const { parentPort, workerData } = require('node:worker_threads');
491
+ const { PNG } = require(workerData.pngjsPath);
492
+ const pixelmatchModule = require(workerData.pixelmatchPath);
493
+ const pixelmatch = pixelmatchModule.default || pixelmatchModule;
494
+
495
+ parentPort.on('message', ({ id, oldBytes, newBytes }) => {
496
+ try {
497
+ const oldImage = PNG.sync.read(Buffer.from(oldBytes));
498
+ const newImage = PNG.sync.read(Buffer.from(newBytes));
499
+ if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) {
500
+ parentPort.postMessage({ id, dimensionMismatch: true });
501
+ return;
502
+ }
503
+ const diff = new PNG({ width: oldImage.width, height: oldImage.height });
504
+ const diffPixels = pixelmatch(
505
+ oldImage.data,
506
+ newImage.data,
507
+ diff.data,
508
+ diff.width,
509
+ diff.height,
510
+ { threshold: 0.1 },
511
+ );
512
+ parentPort.postMessage({ id, diffPixels, png: PNG.sync.write(diff) });
513
+ } catch (error) {
514
+ parentPort.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
515
+ }
516
+ });
517
+ `;
518
+ var ImageDiffPool = class {
519
+ constructor(size) {
520
+ this.size = size;
521
+ }
522
+ size;
523
+ workers = /* @__PURE__ */ new Set();
524
+ idle = [];
525
+ active = /* @__PURE__ */ new Map();
526
+ queue = [];
527
+ nextId = 0;
528
+ compare(oldBytes, newBytes) {
529
+ this.ensureWorkers();
530
+ return new Promise((resolve, reject) => {
531
+ this.queue.push({ id: ++this.nextId, oldBytes, newBytes, resolve, reject });
532
+ this.pump();
533
+ });
534
+ }
535
+ async close() {
536
+ const workers = [...this.workers];
537
+ this.workers.clear();
538
+ this.idle.length = 0;
539
+ await Promise.all(workers.map((worker) => worker.terminate()));
540
+ }
541
+ ensureWorkers() {
542
+ while (this.workers.size < this.size) this.addWorker();
543
+ }
544
+ addWorker() {
545
+ const worker = new Worker(WORKER_CODE, {
546
+ eval: true,
547
+ workerData: { pngjsPath, pixelmatchPath }
548
+ });
549
+ worker.unref();
550
+ worker.on("message", (message) => this.handleResult(worker, message));
551
+ worker.on("error", (error) => this.failWorker(worker, error));
552
+ worker.on("exit", () => {
553
+ this.workers.delete(worker);
554
+ const index = this.idle.indexOf(worker);
555
+ if (index >= 0) this.idle.splice(index, 1);
556
+ const job = this.active.get(worker);
557
+ if (job) {
558
+ this.active.delete(worker);
559
+ job.reject(new Error("image diff worker exited"));
560
+ }
561
+ if (this.queue.length) this.ensureWorkers();
562
+ this.pump();
563
+ });
564
+ this.workers.add(worker);
565
+ this.idle.push(worker);
566
+ }
567
+ handleResult(worker, message) {
568
+ const job = this.active.get(worker);
569
+ if (!job) return;
570
+ this.active.delete(worker);
571
+ worker.unref();
572
+ this.idle.push(worker);
573
+ if (message.error) {
574
+ job.reject(new Error(message.error));
575
+ } else {
576
+ job.resolve(message);
577
+ }
578
+ this.pump();
579
+ }
580
+ failWorker(worker, error) {
581
+ const job = this.active.get(worker);
582
+ if (job) {
583
+ this.active.delete(worker);
584
+ job.reject(error);
585
+ }
586
+ this.workers.delete(worker);
587
+ const index = this.idle.indexOf(worker);
588
+ if (index >= 0) this.idle.splice(index, 1);
589
+ worker.terminate();
590
+ if (this.queue.length) this.ensureWorkers();
591
+ this.pump();
592
+ }
593
+ pump() {
594
+ while (this.idle.length && this.queue.length) {
595
+ const worker = this.idle.pop();
596
+ const job = this.queue.shift();
597
+ this.active.set(worker, job);
598
+ worker.ref();
599
+ worker.postMessage({ id: job.id, oldBytes: job.oldBytes, newBytes: job.newBytes });
600
+ }
601
+ }
602
+ };
603
+
604
+ // modules/core/implementations/Utils/loadBaseline.ts
605
+ import path12 from "node:path";
606
+
607
+ // modules/core/implementations/Utils/scanCases.ts
608
+ import { createHash as createHash2 } from "node:crypto";
609
+ import { glob, readFile as readFile6 } from "node:fs/promises";
610
+ import path11 from "node:path";
611
+
612
+ // modules/core/contracts/scanCases.ts
613
+ import { z as z10 } from "zod";
614
+ var ScanCasesInputSchema = z10.object({
615
+ root: z10.string().min(1)
616
+ });
617
+
618
+ // modules/core/implementations/Utils/scanCases.ts
619
+ var BATCH_SIZE = 16;
620
+ async function scanCases(input) {
621
+ const { root } = ScanCasesInputSchema.parse(input);
622
+ const files = await baselineFiles(root);
623
+ const cases = [];
624
+ for (let index = 0; index < files.length; index += BATCH_SIZE) {
625
+ const batch = await Promise.all(
626
+ files.slice(index, index + BATCH_SIZE).map(async (file) => {
627
+ const baseline = JSON.parse(await readFile6(path11.join(root, file), "utf8"));
628
+ return { file, casePath: path11.posix.dirname(file), baseline };
629
+ })
630
+ );
631
+ for (const entry of batch) {
632
+ cases.push({
633
+ file: entry.file,
634
+ path: entry.casePath === "." ? "" : entry.casePath,
635
+ hash: createHash2("sha256").update(entry.file).update("\0").update(JSON.stringify(entry.baseline)).digest("hex"),
636
+ baseline: entry.baseline
637
+ });
638
+ }
639
+ }
640
+ return { cases };
641
+ }
642
+ async function baselineFiles(root) {
643
+ const files = [];
644
+ for await (const file of glob("**/baseline*.json", {
645
+ cwd: root,
646
+ exclude: ["**/node_modules/**", "**/.git/**", "**/cache/**"]
647
+ })) {
648
+ if (/^baseline(?:-[a-f0-9]{64})?\.json$/.test(path11.basename(file)))
649
+ files.push(file.split(path11.sep).join("/"));
650
+ }
651
+ files.sort();
652
+ return files;
653
+ }
654
+
655
+ // modules/core/implementations/Utils/loadBaseline.ts
656
+ function baselineVersion(baseline) {
657
+ return hash(
658
+ JSON.stringify(
659
+ baseline.files ?? [...baseline.cases.values()].sort((a, b) => a.path.localeCompare(b.path)).map((entry) => [entry.path, entry.hash])
660
+ )
661
+ );
662
+ }
663
+ async function loadBaseline(baselineRoot, namespace) {
664
+ const root = path12.join(baselineRoot, "baselines", namespace);
665
+ const scan = await scanCases({ root });
666
+ const cases = /* @__PURE__ */ new Map();
667
+ for (const item of scan.cases) {
668
+ if (typeof item.baseline?.id !== "string" || !Array.isArray(item.baseline.snapshots)) continue;
669
+ if (cases.has(item.baseline.id)) continue;
670
+ cases.set(item.baseline.id, {
671
+ file: item.file,
672
+ path: item.path,
673
+ hash: item.hash,
674
+ baseline: item.baseline
675
+ });
676
+ }
677
+ return { cases, files: scan.cases.map((item) => item.file).sort() };
678
+ }
679
+ async function readBaselineVersion(root, namespace) {
680
+ return hash(JSON.stringify(await baselineFiles(path12.join(root, "baselines", namespace))));
681
+ }
682
+
683
+ // modules/core/implementations/Utils/mapLimit.ts
684
+ async function mapLimit(items, limit, fn) {
685
+ const results = new Array(items.length);
686
+ let next = 0;
687
+ const workers = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
688
+ while (true) {
689
+ const index = next++;
690
+ if (index >= items.length) return;
691
+ results[index] = await fn(items[index], index);
692
+ }
693
+ });
694
+ await Promise.all(workers);
695
+ return results;
696
+ }
697
+
698
+ // modules/core/implementations/internal/compare.ts
699
+ async function compare(input, cwd, baselineRoot, storage, concurrency = 1) {
700
+ const value = CompareInputSchema.parse(input);
701
+ const found = await getTask(cwd, value.taskId);
702
+ if (!found) throw new Error(`\u4EFB\u52A1\u4E0D\u5B58\u5728: ${value.taskId}`);
703
+ const record = found.record;
704
+ const baseline = await loadBaseline(baselineRoot, record.task.namespace);
705
+ const pool = concurrency > 1 ? new ImageDiffPool(concurrency) : void 0;
706
+ try {
707
+ return await compareRecord(cwd, storage, record, baseline, { concurrency, pool });
708
+ } finally {
709
+ await pool?.close();
710
+ }
711
+ }
712
+ async function compareRecord(cwd, storage, record, baseline, options = {}) {
713
+ const concurrency = Math.max(1, options.concurrency ?? 1);
714
+ const pool = options.pool;
715
+ const canDelete = deletionAllowed(record);
716
+ const cache = pathSchema.cache(cwd);
717
+ const paths = options.baseTaskId ? cache.taskComparison(options.baseTaskId, record.task.id) : cache.comparison(record.task.namespace, record.task.id);
718
+ const cachedIndex = await readJson(paths.index).catch(() => null);
719
+ const cachedCases = cachedIndex?.formatVersion === 4 ? cachedIndex.cases : {};
720
+ const nextCases = {};
721
+ const compareCase = async (current) => {
722
+ const currentHash = hash(JSON.stringify(current));
723
+ const old = baseline.cases.get(current.id);
724
+ const baselineHash = old?.hash ?? null;
725
+ const cachedCase = cachedCases[current.id];
726
+ const diffFilesExist = cachedCase && await Promise.all(
727
+ cachedCase.diff.snapshots.map(async (snapshot) => {
728
+ if (!snapshot.diffFile) return true;
729
+ return access(path13.join(cwd, snapshot.diffFile)).then(
730
+ () => true,
731
+ () => false
732
+ );
733
+ })
734
+ ).then((results2) => results2.every(Boolean));
735
+ if (diffFilesExist && cachedCase?.currentHash === currentHash && cachedCase.baselineHash === baselineHash && cachedCase.canDelete === canDelete) {
736
+ return { diff: cachedCase.diff, cache: cachedCase };
737
+ }
738
+ let diff;
739
+ if (current.snapshots === null || options.unavailableBaseCaseIds?.has(current.id)) {
740
+ diff = {
741
+ id: current.id,
742
+ current: toCase(current),
743
+ baseline: old?.baseline,
744
+ baselineHash: old?.hash,
745
+ change: "unavailable",
746
+ snapshots: []
747
+ };
748
+ } else {
749
+ diff = await buildCaseDiff(
750
+ cwd,
751
+ storage,
752
+ current,
753
+ old,
754
+ canDelete,
755
+ (snapshotId, digest) => paths.diff(current.id, snapshotId, digest),
756
+ concurrency,
757
+ pool
758
+ );
759
+ }
760
+ return {
761
+ diff,
762
+ cache: { currentHash, baselineHash, canDelete, diff }
763
+ };
764
+ };
765
+ const results = await mapLimit(record.cases, concurrency, compareCase);
766
+ const cases = results.map((item) => item.diff);
767
+ for (const item of results) nextCases[item.diff.id] = item.cache;
768
+ if (canDelete) {
769
+ for (const [id, entry] of baseline.cases) {
770
+ if (record.cases.some((item) => item.id === id)) continue;
771
+ const cachedCase = cachedCases[id];
772
+ if (cachedCase?.currentHash === null && cachedCase.baselineHash === entry.hash && cachedCase.canDelete === true) {
773
+ cases.push(cachedCase.diff);
774
+ nextCases[id] = cachedCase;
775
+ continue;
776
+ }
777
+ const diff = deletedCaseDiff(entry);
778
+ cases.push(diff);
779
+ nextCases[id] = {
780
+ currentHash: null,
781
+ baselineHash: entry.hash,
782
+ canDelete: true,
783
+ diff
784
+ };
785
+ }
786
+ }
787
+ const baselineImages = /* @__PURE__ */ new Map();
788
+ async function prepareImage(image, current) {
789
+ if (image.type !== "image") return;
790
+ if (!image.key) throw new Error("\u56FE\u7247\u7F3A\u5C11\u5BF9\u8C61\u5B58\u50A8 key");
791
+ if (current) {
792
+ await readTaskImage(cwd, image.key);
793
+ image.url = path13.resolve(cwd, "objects", image.key);
794
+ } else {
795
+ let pending = baselineImages.get(image.key);
796
+ if (!pending) {
797
+ const key = image.key;
798
+ pending = (async () => {
799
+ if (storage.localPath) return storage.localPath(key);
800
+ const file = path13.join(cwd, "cache", "report-images", path13.basename(key));
801
+ await writeBytesAtomic(file, await download(cwd, storage, key));
802
+ return file;
803
+ })();
804
+ baselineImages.set(key, pending);
805
+ }
806
+ image.url = await pending;
807
+ }
808
+ }
809
+ await mapLimit(cases, concurrency, async (item) => {
810
+ for (const image of [...item.current?.snapshots ?? [], ...item.current?.observations ?? []])
811
+ await prepareImage(image, true);
812
+ for (const image of item.baseline?.snapshots ?? []) await prepareImage(image, false);
813
+ for (const snapshot of item.snapshots) {
814
+ if (snapshot.current) await prepareImage(snapshot.current, true);
815
+ if (snapshot.baseline) await prepareImage(snapshot.baseline, false);
816
+ }
817
+ });
818
+ const version2 = baselineVersion(baseline);
819
+ await writeJsonAtomic(paths.index, {
820
+ formatVersion: 4,
821
+ baselineVersion: version2,
822
+ cases: nextCases
823
+ });
824
+ const summary = {
825
+ added: 0,
826
+ modified: 0,
827
+ deleted: 0,
828
+ same: 0,
829
+ unavailable: 0
830
+ };
831
+ for (const item of cases) summary[item.change] += 1;
832
+ await writeJsonAtomic(paths.summary, {
833
+ baselineVersion: version2,
834
+ summary
835
+ });
836
+ return {
837
+ taskId: record.task.id,
838
+ namespace: record.task.namespace,
839
+ baselineVersion: version2,
840
+ deletionAllowed: canDelete,
841
+ cases,
842
+ summary
843
+ };
844
+ }
845
+ async function readCachedComparisonSummary(cwd, namespace, taskId, currentBaselineVersion) {
846
+ const cached = await readJson(
847
+ pathSchema.cache(cwd).comparison(namespace, taskId).summary
848
+ ).catch(() => null);
849
+ if (!cached || cached.baselineVersion !== currentBaselineVersion || !cached.summary) return null;
850
+ const states = ["added", "modified", "deleted", "same", "unavailable"];
851
+ if (states.some((state) => !Number.isInteger(cached.summary[state]) || cached.summary[state] < 0))
852
+ return null;
853
+ return cached.summary;
854
+ }
855
+ async function buildCaseDiff(cwd, storage, current, old, canDelete, diffPath, concurrency, pool) {
856
+ const snapshots = await mapLimit(current.snapshots ?? [], concurrency, (snapshot) => {
857
+ const previous = old?.baseline.snapshots.find((item) => item.id === snapshot.id);
858
+ return compareSnapshot(cwd, storage, snapshot, previous, diffPath, pool);
859
+ });
860
+ if (canDelete) {
861
+ for (const previous of old?.baseline.snapshots ?? []) {
862
+ if (!current.snapshots?.some((item) => item.id === previous.id)) {
863
+ snapshots.push({ id: previous.id, change: "deleted", baseline: previous });
864
+ }
865
+ }
866
+ }
867
+ const changed = snapshots.some((item) => item.change !== "same") || current.name !== old?.baseline.name || JSON.stringify(current.treePath) !== JSON.stringify(old?.baseline.treePath);
868
+ return {
869
+ id: current.id,
870
+ current: toCase(current),
871
+ baseline: old?.baseline,
872
+ baselineHash: old?.hash,
873
+ change: !old ? "added" : changed ? "modified" : "same",
874
+ snapshots
875
+ };
876
+ }
877
+ function deletedCaseDiff(entry) {
878
+ return {
879
+ id: entry.baseline.id,
880
+ change: "deleted",
881
+ baseline: entry.baseline,
882
+ baselineHash: entry.hash,
883
+ snapshots: entry.baseline.snapshots.map((snapshot) => ({
884
+ id: snapshot.id,
885
+ change: "deleted",
886
+ baseline: snapshot
887
+ }))
888
+ };
889
+ }
890
+ async function compareSnapshot(cwd, storage, current, previous, diffPath, pool) {
891
+ if (!previous) {
892
+ return { id: current.id, change: "added", current: toSnapshot(current) };
893
+ }
894
+ const currentSnapshot = toSnapshot(current);
895
+ let contentSame = current.type === "text" && previous.type === "text" && current.body === previous.body;
896
+ const result = {
897
+ id: current.id,
898
+ change: "same",
899
+ current: currentSnapshot,
900
+ baseline: previous
901
+ };
902
+ if (current.type === "image" && previous.type === "image") {
903
+ const tolerance = current.maxDiffPixels ?? previous.maxDiffPixels ?? 0;
904
+ result.maxDiffPixels = tolerance;
905
+ {
906
+ if (!current.key || !previous.key) throw new Error("\u56FE\u7247\u7F3A\u5C11\u5BF9\u8C61\u5B58\u50A8 key");
907
+ const [oldBytes, newBytes] = await Promise.all([
908
+ download(cwd, storage, previous.key),
909
+ readTaskImage(cwd, current.key)
910
+ ]);
911
+ const diff = await imageDiff(oldBytes, newBytes, pool);
912
+ if (!diff.dimensionMismatch && diff.diffPixels !== void 0) {
913
+ result.diffPixels = diff.diffPixels;
914
+ contentSame = result.diffPixels <= tolerance;
915
+ if (diff.png) {
916
+ const file = diffPath(current.id, hash(diff.png));
917
+ await writeBytesAtomic(file, diff.png);
918
+ result.diffFile = path13.relative(cwd, file).split(path13.sep).join("/");
919
+ result.diffUrl = file;
920
+ }
921
+ }
922
+ }
923
+ result.contentSame = contentSame;
924
+ if (tolerance !== (previous.maxDiffPixels ?? 0)) contentSame = false;
925
+ } else if (current.type === "text" && previous.type === "text") {
926
+ result.contentSame = contentSame;
927
+ }
928
+ const metadataSame = currentSnapshot.name === previous.name && currentSnapshot.type === previous.type && currentSnapshot.language === previous.language && currentSnapshot.contentType === previous.contentType && (currentSnapshot.col ?? 4) === (previous.col ?? 4) && (currentSnapshot.maxDiffPixels ?? previous.maxDiffPixels ?? 0) === (previous.maxDiffPixels ?? 0);
929
+ result.change = contentSame && metadataSame ? "same" : "modified";
930
+ return result;
931
+ }
932
+ async function imageDiff(oldBytes, newBytes, pool) {
933
+ if (pool) {
934
+ try {
935
+ return await pool.compare(oldBytes, newBytes);
936
+ } catch {
937
+ }
938
+ }
939
+ return localImageDiff(oldBytes, newBytes);
940
+ }
941
+ function localImageDiff(oldBytes, newBytes) {
942
+ const oldImage = PNG.sync.read(Buffer.from(oldBytes));
943
+ const newImage = PNG.sync.read(Buffer.from(newBytes));
944
+ if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) {
945
+ return { dimensionMismatch: true };
946
+ }
947
+ const diff = new PNG({ width: oldImage.width, height: oldImage.height });
948
+ const diffPixels = pixelmatch(oldImage.data, newImage.data, diff.data, diff.width, diff.height, {
949
+ threshold: 0.1
950
+ });
951
+ return { diffPixels, png: PNG.sync.write(diff) };
952
+ }
953
+
954
+ // modules/core/implementations/repository.ts
955
+ import path15 from "node:path";
956
+
957
+ // modules/core/implementations/storage/s3.ts
958
+ import { readFile as readFile8 } from "node:fs/promises";
959
+ import path14 from "node:path";
960
+
961
+ // modules/core/implementations/Utils/getEnv.ts
962
+ import { readFile as readFile7 } from "node:fs/promises";
963
+ import { parseEnv } from "node:util";
964
+ async function getEnv({
965
+ keys,
966
+ processEnv,
967
+ filePath
968
+ }) {
969
+ let fileEnv = {};
970
+ try {
971
+ fileEnv = parseEnv(await readFile7(filePath, "utf8"));
972
+ } catch (error) {
973
+ if (error.code !== "ENOENT") throw error;
974
+ }
975
+ return Object.fromEntries(keys.map((key) => [key, processEnv[key] ?? fileEnv[key]]));
976
+ }
977
+
978
+ // modules/core/implementations/storage/s3.ts
979
+ function createS3Storage(repoRoot, reportDir) {
980
+ let config;
981
+ async function loadStorageConfig() {
982
+ const names = ["ENDPOINT", "BUCKET", "REGION", "PREFIX", "ACCESS_KEY", "SECRET_KEY"];
983
+ const env = await getEnv({
984
+ keys: names.map((name) => `EVIDRA_S3_${name}`),
985
+ processEnv: process.env,
986
+ filePath: path14.join(repoRoot, ".evidra.env.local")
987
+ });
988
+ const required = (name) => {
989
+ const value = env[`EVIDRA_S3_${name}`]?.trim();
990
+ if (!value) throw new Error(`\u7F3A\u5C11 EVIDRA_S3_${name}`);
991
+ return value;
992
+ };
993
+ const endpoint = required("ENDPOINT"), bucket = required("BUCKET"), region = required("REGION");
994
+ const prefix = required("PREFIX").replace(/^\/+|\/+$/g, "");
995
+ const { S3Client, GetObjectCommand, PutObjectCommand } = await import("@aws-sdk/client-s3");
996
+ const client = new S3Client({
997
+ endpoint,
998
+ region,
999
+ forcePathStyle: true,
1000
+ credentials: {
1001
+ accessKeyId: required("ACCESS_KEY"),
1002
+ secretAccessKey: required("SECRET_KEY")
1003
+ }
1004
+ });
1005
+ return { client, bucket, prefix, endpoint, region, GetObjectCommand, PutObjectCommand };
1006
+ }
1007
+ const pending = /* @__PURE__ */ new Map();
1008
+ async function location(key) {
1009
+ const remote = await (config ??= loadStorageConfig());
1010
+ const objectKey = remote.prefix && !key.startsWith(remote.prefix + "/") ? `${remote.prefix}/${key}` : key;
1011
+ const identity = [remote.endpoint, remote.bucket, remote.region, remote.prefix];
1012
+ return {
1013
+ remote,
1014
+ objectKey,
1015
+ file: path14.join(
1016
+ reportDir,
1017
+ "cache",
1018
+ "objects",
1019
+ hash(JSON.stringify(identity)),
1020
+ path14.basename(key)
1021
+ )
1022
+ };
1023
+ }
1024
+ return {
1025
+ async localPath(key) {
1026
+ await this.download(key);
1027
+ return (await location(key)).file;
1028
+ },
1029
+ async upload(key, body) {
1030
+ const { remote, objectKey, file } = await location(key);
1031
+ await remote.client.send(
1032
+ new remote.PutObjectCommand({
1033
+ Bucket: remote.bucket,
1034
+ Key: objectKey,
1035
+ Body: body,
1036
+ ContentType: "image/png"
1037
+ })
1038
+ );
1039
+ await writeBytesAtomic(file, body);
1040
+ },
1041
+ async download(key) {
1042
+ if (pending.has(key)) return pending.get(key);
1043
+ const next = (async () => {
1044
+ const { remote, objectKey, file } = await location(key);
1045
+ try {
1046
+ const bytes2 = await readFile8(file);
1047
+ return bytes2;
1048
+ } catch (error) {
1049
+ if (error.code !== "ENOENT") throw error;
1050
+ }
1051
+ const response = await remote.client.send(
1052
+ new remote.GetObjectCommand({ Bucket: remote.bucket, Key: objectKey })
1053
+ );
1054
+ const bytes = await response.Body?.transformToByteArray();
1055
+ if (!bytes) throw new Error(`S3 \u5BF9\u8C61\u4E3A\u7A7A: ${key}`);
1056
+ await writeBytesAtomic(file, bytes);
1057
+ return bytes;
1058
+ })();
1059
+ pending.set(key, next);
1060
+ try {
1061
+ return await next;
1062
+ } finally {
1063
+ pending.delete(key);
1064
+ }
1065
+ }
1066
+ };
1067
+ }
1068
+
1069
+ // modules/core/implementations/storage/objects.ts
1070
+ function createStorage(repoRoot, reportDir) {
1071
+ let storage;
1072
+ function resolveStorage() {
1073
+ return storage ??= loadConfig({ repoRoot }).then(
1074
+ (config) => config.storage === "local" ? createLocalStorage(reportDir) : createS3Storage(repoRoot, reportDir)
1075
+ );
1076
+ }
1077
+ return {
1078
+ async localPath(key) {
1079
+ return (await resolveStorage()).localPath(key);
1080
+ },
1081
+ async upload(key, body) {
1082
+ return (await resolveStorage()).upload(key, body);
1083
+ },
1084
+ async download(key) {
1085
+ return (await resolveStorage()).download(key);
1086
+ }
1087
+ };
1088
+ }
1089
+
1090
+ // modules/core/implementations/repository.ts
1091
+ async function reportRoot(root) {
1092
+ return path15.join(root, (await loadConfig({ repoRoot: root })).reportDir);
1093
+ }
1094
+ function storageFor(reportDir, repoRoot) {
1095
+ return createStorage(repoRoot, reportDir);
1096
+ }
1097
+ function toTaskDetail(record) {
1098
+ return { ...record.task, cases: record.cases };
1099
+ }
1100
+ async function readCoreTask(root, id) {
1101
+ const found = await getTask(await reportRoot(root), id);
1102
+ return found ? toTaskDetail(found.record) : null;
1103
+ }
1104
+ async function taskPathOf(root, id) {
1105
+ const found = await getTask(await reportRoot(root), id);
1106
+ if (!found) throw new Error("\u4EFB\u52A1\u4E0D\u5B58\u5728");
1107
+ return found.taskPath;
1108
+ }
1109
+
1110
+ // modules/core/implementations/Functions/compareTask.ts
1111
+ async function compareTask(input) {
1112
+ const { repoRoot: root, taskId } = CompareTaskInputSchema.parse(input);
1113
+ const reportDir = await reportRoot(root);
1114
+ return compare({ taskId }, reportDir, reportDir, storageFor(reportDir, root));
1115
+ }
1116
+
1117
+ // modules/core/implementations/Functions/approve.ts
1118
+ import path18 from "node:path";
1119
+
1120
+ // modules/core/contracts/functions/approve.ts
1121
+ import { z as z11 } from "zod";
1122
+ var ApproveInputSchema = z11.object({
1123
+ repoRoot: z11.string(),
1124
+ taskId: z11.string(),
1125
+ baselineVersion: z11.string(),
1126
+ caseIds: z11.array(z11.string())
1127
+ });
1128
+
1129
+ // modules/core/implementations/internal/getBaseline.ts
1130
+ import path16 from "node:path";
1131
+ async function getBaseline(baselineRoot, namespace) {
1132
+ const baseline = await loadBaseline(baselineRoot, namespace);
1133
+ const scan = await scanCases({ root: path16.join(baselineRoot, "baselines", namespace) });
1134
+ const seen = /* @__PURE__ */ new Set();
1135
+ const candidates = scan.cases.filter(
1136
+ (item) => typeof item.baseline?.id === "string" && Array.isArray(item.baseline.snapshots)
1137
+ ).map((item) => {
1138
+ const ignored = seen.has(item.path);
1139
+ seen.add(item.path);
1140
+ return { file: item.file, ignored, baseline: item.baseline };
1141
+ });
1142
+ return {
1143
+ candidates,
1144
+ version: baselineVersion(baseline),
1145
+ cases: [...baseline.cases.values()].map((entry) => entry.baseline)
1146
+ };
1147
+ }
1148
+
1149
+ // modules/core/implementations/snapshots.ts
1150
+ var canonical = (value) => {
1151
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1152
+ if (value && typeof value === "object")
1153
+ return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
1154
+ return JSON.stringify(value);
1155
+ };
1156
+ var version = (value) => hash(canonical(value));
1157
+ async function readTask(root, id) {
1158
+ const task = await readCoreTask(root, id);
1159
+ if (!task) throw Object.assign(new Error("\u4EFB\u52A1\u4E0D\u5B58\u5728"), { statusCode: 404 });
1160
+ return task;
1161
+ }
1162
+ async function readBaseline(root, namespace) {
1163
+ const baseline = await getBaseline(await reportRoot(root), namespace);
1164
+ return {
1165
+ candidates: baseline.candidates,
1166
+ cases: baseline.cases,
1167
+ baselineVersion: baseline.version
1168
+ };
1169
+ }
1170
+
1171
+ // modules/core/implementations/internal/updateBaseline.ts
1172
+ import { mkdir as mkdir3, readdir as readdir2, rm as rm3 } from "node:fs/promises";
1173
+ import path17 from "node:path";
1174
+
1175
+ // modules/core/contracts/internal/updateBaseline.ts
1176
+ import { z as z12 } from "zod";
1177
+ var CaseVersionSchema = z12.object({
1178
+ id: IdSchema,
1179
+ baselineHash: z12.string().nullable()
1180
+ });
1181
+ var UpdateBaselineInputSchema = z12.object({
1182
+ taskPath: TaskPathSchema,
1183
+ baselineVersion: z12.string().optional(),
1184
+ cases: z12.array(CaseVersionSchema).min(1)
1185
+ }).superRefine((value, ctx) => {
1186
+ const ids = /* @__PURE__ */ new Set();
1187
+ value.cases.forEach((item, index) => {
1188
+ if (ids.has(item.id)) {
1189
+ ctx.addIssue({ code: "custom", path: ["cases", index, "id"], message: "case \u4E0D\u80FD\u91CD\u590D" });
1190
+ }
1191
+ ids.add(item.id);
1192
+ });
1193
+ });
1194
+
1195
+ // modules/core/implementations/Utils/canonical.ts
1196
+ function canonical2(value) {
1197
+ if (Array.isArray(value)) return `[${value.map(canonical2).join(",")}]`;
1198
+ if (value && typeof value === "object")
1199
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical2(item)}`).join(",")}}`;
1200
+ return JSON.stringify(value);
1201
+ }
1202
+
1203
+ // modules/core/implementations/internal/updateBaseline.ts
1204
+ async function updateBaselineUnlocked(input, cwd, baselineRoot, storage, concurrency = 1) {
1205
+ const value = UpdateBaselineInputSchema.parse(input);
1206
+ const directory = taskDirectory(cwd, value.taskPath);
1207
+ const record = await readTaskRecord(path17.join(directory, "task.json"));
1208
+ if (!record.task.finishedAt) throw new Error("\u4EFB\u52A1\u5C1A\u672A\u7ED3\u675F");
1209
+ const namespace = record.task.namespace;
1210
+ if (value.baselineVersion !== void 0 && await readBaselineVersion(baselineRoot, namespace) !== value.baselineVersion)
1211
+ return {
1212
+ conflict: true,
1213
+ comparison: await compare(
1214
+ { taskId: record.task.id },
1215
+ cwd,
1216
+ baselineRoot,
1217
+ storage,
1218
+ concurrency
1219
+ )
1220
+ };
1221
+ const comparison = await compare(
1222
+ { taskId: record.task.id },
1223
+ cwd,
1224
+ baselineRoot,
1225
+ storage,
1226
+ concurrency
1227
+ );
1228
+ for (const expected of value.cases) {
1229
+ const diff = comparison.cases.find((item) => item.id === expected.id);
1230
+ if (!diff) throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1231
+ if ((diff.baselineHash ?? null) !== expected.baselineHash) {
1232
+ return { conflict: true, comparison };
1233
+ }
1234
+ }
1235
+ const baseline = await loadBaseline(baselineRoot, namespace);
1236
+ const updatedCaseIds = [];
1237
+ const deletedCaseIds = [];
1238
+ for (const expected of value.cases) {
1239
+ const caseId = expected.id;
1240
+ const diff = comparison.cases.find((item) => item.id === caseId);
1241
+ if (!diff || diff.change === "unavailable") throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1242
+ const previous = baseline.cases.get(caseId);
1243
+ if (diff.change === "deleted") {
1244
+ baseline.cases.delete(caseId);
1245
+ const casePath2 = previous?.path ? previous.path.split("/") : [caseId];
1246
+ await rm3(pathSchema.baseline(baselineRoot, namespace, casePath2).directory, {
1247
+ recursive: true,
1248
+ force: true
1249
+ });
1250
+ deletedCaseIds.push(caseId);
1251
+ continue;
1252
+ }
1253
+ const current = diff.current;
1254
+ if (!current || current.snapshots === null) throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1255
+ const currentStored = record.cases.find((item) => item.id === caseId);
1256
+ if (!currentStored || currentStored.snapshots === null) throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1257
+ const storedSnapshots = new Map(
1258
+ currentStored.snapshots.map((snapshot) => [snapshot.id, snapshot])
1259
+ );
1260
+ const casePath = previous?.path ? previous.path.split("/") : [caseId];
1261
+ const paths = pathSchema.baseline(baselineRoot, namespace, casePath);
1262
+ const previousSnapshots = previous?.baseline.snapshots ?? [];
1263
+ const snapshots = comparison.deletionAllowed ? [] : [...previousSnapshots];
1264
+ for (const snapshot of current.snapshots) {
1265
+ const old = previousSnapshots.find((item) => item.id === snapshot.id);
1266
+ const change = diff.snapshots.find((item) => item.id === snapshot.id);
1267
+ if (!change) throw new Error("\u5FEB\u7167\u4E0D\u53EF\u5BA1\u6279");
1268
+ let saved;
1269
+ if (change.change === "same" && old) {
1270
+ saved = old;
1271
+ } else {
1272
+ const source = storedSnapshots.get(snapshot.id);
1273
+ if (!source) throw new Error("\u5FEB\u7167\u4E0D\u5B58\u5728");
1274
+ if (source.type === "text") {
1275
+ saved = toSnapshot(source);
1276
+ } else {
1277
+ if (!source.key) throw new Error("\u56FE\u7247\u7F3A\u5C11\u5BF9\u8C61\u5B58\u50A8 key");
1278
+ const reuse = change.contentSame && old?.type === "image" && !!old.key;
1279
+ if (!reuse) {
1280
+ const bytes = await readTaskImage(cwd, source.key);
1281
+ await storage.upload(source.key, bytes);
1282
+ }
1283
+ saved = reuse ? {
1284
+ ...toSnapshot(source),
1285
+ key: old.key,
1286
+ maxDiffPixels: source.maxDiffPixels ?? old.maxDiffPixels ?? 0
1287
+ } : {
1288
+ ...toSnapshot(source),
1289
+ maxDiffPixels: source.maxDiffPixels ?? old?.maxDiffPixels ?? 0
1290
+ };
1291
+ }
1292
+ }
1293
+ const index = snapshots.findIndex((item) => item.id === snapshot.id);
1294
+ if (index < 0) snapshots.push(saved);
1295
+ else snapshots[index] = saved;
1296
+ }
1297
+ const entry = {
1298
+ id: current.id,
1299
+ name: current.name,
1300
+ treePath: current.treePath,
1301
+ snapshots,
1302
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
1303
+ };
1304
+ const { approvedAt: _approvedAt, ...content } = entry;
1305
+ const filename = `baseline-${hash(canonical2(content))}.json`;
1306
+ await writeJsonAtomic(path17.join(paths.directory, filename), entry);
1307
+ for (const file of await readdir2(paths.directory)) {
1308
+ if (file !== filename && /^baseline(?:-[a-f0-9]{64})?\.json$/.test(file)) {
1309
+ await rm3(path17.join(paths.directory, file));
1310
+ }
1311
+ }
1312
+ const caseFile = [...casePath, filename].join("/");
1313
+ baseline.cases.set(caseId, {
1314
+ path: casePath.join("/"),
1315
+ hash: hash(`${caseFile}\0${JSON.stringify(entry)}`),
1316
+ baseline: entry
1317
+ });
1318
+ updatedCaseIds.push(caseId);
1319
+ }
1320
+ const nextComparison = await compare(
1321
+ { taskId: record.task.id },
1322
+ cwd,
1323
+ baselineRoot,
1324
+ storage,
1325
+ concurrency
1326
+ );
1327
+ return {
1328
+ conflict: false,
1329
+ updatedCaseIds,
1330
+ deletedCaseIds,
1331
+ comparison: nextComparison
1332
+ };
1333
+ }
1334
+ var writes = /* @__PURE__ */ new Map();
1335
+ async function updateBaseline(input, cwd, baselineRoot, storage, concurrency = 1) {
1336
+ const key = path17.resolve(baselineRoot);
1337
+ const next = (writes.get(key) ?? Promise.resolve()).then(async () => {
1338
+ const lock = path17.join(baselineRoot, "cache", "baseline-write.lock");
1339
+ await mkdir3(path17.dirname(lock), { recursive: true });
1340
+ const deadline = Date.now() + 3e4;
1341
+ for (; ; ) {
1342
+ try {
1343
+ await mkdir3(lock);
1344
+ break;
1345
+ } catch (error) {
1346
+ if (error.code !== "EEXIST") throw error;
1347
+ if (Date.now() >= deadline) throw new Error("\u57FA\u7EBF\u5199\u5165\u9501\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u4E2D\u65AD\u7684\u5199\u5165");
1348
+ await new Promise((resolve) => setTimeout(resolve, 20));
1349
+ }
1350
+ }
1351
+ try {
1352
+ return await updateBaselineUnlocked(input, cwd, baselineRoot, storage, concurrency);
1353
+ } finally {
1354
+ await rm3(lock, { recursive: true, force: true });
1355
+ }
1356
+ });
1357
+ const settled = next.catch(() => {
1358
+ });
1359
+ writes.set(key, settled);
1360
+ try {
1361
+ return await next;
1362
+ } finally {
1363
+ if (writes.get(key) === settled) writes.delete(key);
1364
+ }
1365
+ }
1366
+
1367
+ // modules/core/implementations/Functions/approve.ts
1368
+ var approvals = /* @__PURE__ */ new Map();
1369
+ async function approve(input) {
1370
+ const {
1371
+ repoRoot: root,
1372
+ taskId,
1373
+ caseIds: ids,
1374
+ baselineVersion: expectedVersion
1375
+ } = ApproveInputSchema.parse(input);
1376
+ const task = await readTask(root, taskId);
1377
+ const key = path18.join(root, task.namespace);
1378
+ const next = (approvals.get(key) ?? Promise.resolve()).then(async () => {
1379
+ if (!task.finishedAt) throw new Error("\u4EFB\u52A1\u5C1A\u672A\u7ED3\u675F");
1380
+ if (!ids.length || new Set(ids).size !== ids.length) throw new Error("\u5BA1\u6279\u7528\u4F8B\u5217\u8868\u4E3A\u7A7A\u6216\u91CD\u590D");
1381
+ const reportDir = await reportRoot(root);
1382
+ if (await readBaselineVersion(reportDir, task.namespace) !== expectedVersion)
1383
+ return { conflict: true, comparison: await compareTask({ repoRoot: root, taskId }) };
1384
+ const comparison = await compareTask({ repoRoot: root, taskId });
1385
+ const cases = ids.map((id) => {
1386
+ const diff = comparison.cases.find((item) => item.id === id);
1387
+ if (!diff) throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1388
+ return { id, baselineHash: diff.baselineHash ?? null };
1389
+ });
1390
+ const result = await updateBaseline(
1391
+ { taskPath: await taskPathOf(root, taskId), cases, baselineVersion: expectedVersion },
1392
+ reportDir,
1393
+ reportDir,
1394
+ storageFor(reportDir, root)
1395
+ );
1396
+ return { conflict: result.conflict, comparison: result.comparison };
1397
+ });
1398
+ approvals.set(
1399
+ key,
1400
+ next.catch(() => {
1401
+ })
1402
+ );
1403
+ return next;
1404
+ }
1405
+
1406
+ // modules/core/contracts/functions/reviewCodeChanges.ts
1407
+ import { z as z13 } from "zod";
1408
+ var ReviewCodeChangesInputSchema = z13.object({
1409
+ repoRoot: z13.string(),
1410
+ ref: z13.string(),
1411
+ version: z13.string(),
1412
+ items: z13.array(z13.string()).min(1),
1413
+ reviewed: z13.boolean()
1414
+ });
1415
+
1416
+ // modules/core/implementations/Functions/reviewCodeChanges.ts
1417
+ import { realpath as realpath3 } from "node:fs/promises";
1418
+
1419
+ // modules/core/implementations/gitChanges.ts
1420
+ import { createHash as createHash3 } from "node:crypto";
1421
+ import { createReadStream } from "node:fs";
1422
+ import { lstat, readlink, realpath } from "node:fs/promises";
1423
+ import path19 from "node:path";
1424
+
1425
+ // modules/core/implementations/git.ts
1426
+ import { execFile } from "node:child_process";
1427
+ function runGit(repoRoot, args, timeoutMs = 2e4) {
1428
+ return new Promise((resolve) => {
1429
+ execFile(
1430
+ "git",
1431
+ ["-C", repoRoot, ...args],
1432
+ { maxBuffer: 32 * 1024 * 1024, timeout: timeoutMs, windowsHide: true },
1433
+ (error, stdout, stderr) => {
1434
+ resolve({
1435
+ ok: error === null,
1436
+ stdout: String(stdout),
1437
+ stderr: (String(stderr).trim() || (error ? error.message : "")).trim()
1438
+ });
1439
+ }
1440
+ );
1441
+ });
1442
+ }
1443
+ async function gitOptional(repoRoot, args) {
1444
+ const result = await runGit(repoRoot, args);
1445
+ const value = result.stdout.trim();
1446
+ return result.ok && value ? value : null;
1447
+ }
1448
+ async function resolveRef(repoRoot, ref) {
1449
+ return gitOptional(repoRoot, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
1450
+ }
1451
+
1452
+ // modules/core/implementations/gitChanges.ts
1453
+ var MAX_BYTES = 256 * 1024;
1454
+ var REVIEW_KEY_VERSION = 1;
1455
+ async function git(root, args) {
1456
+ const result = await runGit(root, args);
1457
+ if (!result.ok) throw new Error(result.stderr);
1458
+ return result.stdout;
1459
+ }
1460
+ async function collectChanges(root, ref) {
1461
+ const sha = await resolveRef(root, ref);
1462
+ if (!sha) throw new Error("\u627E\u4E0D\u5230\u6BD4\u8F83\u5206\u652F");
1463
+ const [tracked, untracked] = await Promise.all([
1464
+ git(root, ["diff", "--raw", "-z", "--find-renames", sha, "--"]),
1465
+ git(root, ["ls-files", "--others", "--exclude-standard", "-z"])
1466
+ ]);
1467
+ const fields = tracked.split("\0");
1468
+ const files = /* @__PURE__ */ new Map();
1469
+ for (let i = 0; fields[i]; ) {
1470
+ const [raw, , oldSha, , code] = fields[i++].split(" ");
1471
+ const oldMode = raw?.slice(1);
1472
+ if (!oldMode || !oldSha || !code) throw new Error(`\u65E0\u6CD5\u89E3\u6790\u4EE3\u7801\u6539\u52A8\uFF1A${raw ?? ""}`);
1473
+ const first = fields[i++];
1474
+ const renamed = code.startsWith("R") || code.startsWith("C");
1475
+ const file = renamed ? fields[i++] : first;
1476
+ if (!file) throw new Error("\u65E0\u6CD5\u89E3\u6790\u4EE3\u7801\u6539\u52A8\u8DEF\u5F84");
1477
+ files.set(file, {
1478
+ path: file,
1479
+ ...renamed ? { oldPath: first } : {},
1480
+ status: renamed ? "renamed" : code === "A" ? "added" : code === "D" ? "deleted" : "modified",
1481
+ before: oldMode === "000000" ? null : { mode: oldMode, hash: oldSha }
1482
+ });
1483
+ }
1484
+ for (const file of untracked.split("\0").filter(Boolean)) {
1485
+ if (!files.has(file)) files.set(file, { path: file, status: "added", before: null });
1486
+ }
1487
+ return { sha, files: [...files.values()].sort((a, b) => a.path.localeCompare(b.path)) };
1488
+ }
1489
+ function fileDigest(file) {
1490
+ return new Promise((resolve, reject) => {
1491
+ const digest = createHash3("sha256");
1492
+ createReadStream(file).on("error", reject).on("data", (chunk) => digest.update(chunk)).on("end", () => resolve(digest.digest("hex")));
1493
+ });
1494
+ }
1495
+ async function worktreeSide(repo, file) {
1496
+ const absolute = path19.resolve(repo, file);
1497
+ const parent = await realpath(path19.dirname(absolute));
1498
+ const relative = path19.relative(repo, parent);
1499
+ if (relative === ".." || relative.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative))
1500
+ throw new Error("\u6587\u4EF6\u4E0D\u5728\u4ED3\u5E93\u5185");
1501
+ const stat3 = await lstat(absolute);
1502
+ if (stat3.isSymbolicLink()) return { mode: "120000", hash: hash(await readlink(absolute)) };
1503
+ if (stat3.isDirectory()) {
1504
+ const commit = (await git(absolute, ["rev-parse", "HEAD"])).trim();
1505
+ return { mode: "160000", hash: hash(`Subproject commit ${commit}
1506
+ `) };
1507
+ }
1508
+ return {
1509
+ mode: stat3.mode & 73 ? "100755" : "100644",
1510
+ hash: await fileDigest(absolute)
1511
+ };
1512
+ }
1513
+ function reviewKey(change, after) {
1514
+ return hash(
1515
+ JSON.stringify({
1516
+ version: REVIEW_KEY_VERSION,
1517
+ status: change.status,
1518
+ path: change.path,
1519
+ oldPath: change.oldPath ?? null,
1520
+ before: change.before,
1521
+ after
1522
+ })
1523
+ );
1524
+ }
1525
+ function publicChange(change, after) {
1526
+ return {
1527
+ path: change.path,
1528
+ ...change.oldPath ? { oldPath: change.oldPath } : {},
1529
+ status: change.status,
1530
+ reviewKey: reviewKey(change, after)
1531
+ };
1532
+ }
1533
+ async function reviewFile(root) {
1534
+ return path19.join(await reportRoot(root), "cache", "reviews", "code.json");
1535
+ }
1536
+ async function readReviews(root) {
1537
+ return await readJson(await reviewFile(root)) ?? {};
1538
+ }
1539
+
1540
+ // modules/core/implementations/Functions/getGitChanges.ts
1541
+ import { realpath as realpath2 } from "node:fs/promises";
1542
+
1543
+ // modules/core/contracts/functions/getGitChanges.ts
1544
+ import { z as z14 } from "zod";
1545
+ var GetGitChangesInputSchema = z14.object({ repoRoot: z14.string(), ref: z14.string() });
1546
+
1547
+ // modules/core/implementations/Functions/getGitChanges.ts
1548
+ async function getGitChanges(input) {
1549
+ const { repoRoot: root, ref } = GetGitChangesInputSchema.parse(input);
1550
+ const { sha, files } = await collectChanges(root, ref);
1551
+ const repo = await realpath2(root);
1552
+ const reviews = await readReviews(root);
1553
+ const changes = [];
1554
+ for (const change of files) {
1555
+ const after = change.status === "deleted" ? null : await worktreeSide(repo, change.path);
1556
+ changes.push(publicChange(change, after));
1557
+ }
1558
+ const keys = new Set(changes.map((change) => change.reviewKey));
1559
+ return {
1560
+ sha,
1561
+ files: changes,
1562
+ reviewed: Object.keys(reviews).filter((key) => keys.has(key)).sort()
1563
+ };
1564
+ }
1565
+
1566
+ // modules/core/implementations/Functions/reviewCodeChanges.ts
1567
+ async function reviewCodeChanges(input) {
1568
+ const { repoRoot, ref, version: version2, items, reviewed } = ReviewCodeChangesInputSchema.parse(input);
1569
+ const changes = await getGitChanges({ repoRoot, ref });
1570
+ if (changes.sha !== version2)
1571
+ throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1572
+ const files = items.map((key) => {
1573
+ const file = changes.files.find((item) => item.reviewKey === key);
1574
+ if (!file)
1575
+ throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1576
+ return { path: file.path, key };
1577
+ });
1578
+ if (new Set(files.map((file) => file.key)).size !== files.length)
1579
+ throw new Error("\u5BA1\u6838\u6587\u4EF6\u4E0D\u80FD\u91CD\u590D");
1580
+ const { files: currentChanges } = await collectChanges(repoRoot, ref);
1581
+ const byPath = new Map(currentChanges.map((change) => [change.path, change]));
1582
+ const repo = await realpath3(repoRoot);
1583
+ const reviews = await readReviews(repoRoot);
1584
+ for (const file of files) {
1585
+ const change = byPath.get(file.path);
1586
+ if (!change)
1587
+ throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1588
+ const after = change.status === "deleted" ? null : await worktreeSide(repo, change.path);
1589
+ if (reviewKey(change, after) !== file.key)
1590
+ throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1591
+ if (reviewed) reviews[file.key] = (/* @__PURE__ */ new Date()).toISOString();
1592
+ else delete reviews[file.key];
1593
+ }
1594
+ await writeJsonAtomic(await reviewFile(repoRoot), reviews);
1595
+ return { reviewed: (await getGitChanges({ repoRoot, ref })).reviewed };
1596
+ }
1597
+
1598
+ // modules/core/implementations/Functions/reviewBaselineChanges.ts
1599
+ import path22 from "node:path";
1600
+
1601
+ // modules/core/contracts/functions/reviewBaselineChanges.ts
1602
+ import { z as z15 } from "zod";
1603
+ var ReviewBaselineChangesInputSchema = z15.object({
1604
+ repoRoot: z15.string(),
1605
+ ref: z15.string(),
1606
+ version: z15.string(),
1607
+ items: z15.array(z15.string()).min(1),
1608
+ reviewed: z15.boolean()
1609
+ });
1610
+
1611
+ // modules/core/contracts/functions/getBaselineChanges.ts
1612
+ import { z as z16 } from "zod";
1613
+ var GetBaselineChangesInputSchema = z16.object({ repoRoot: z16.string(), ref: z16.string() });
1614
+
1615
+ // modules/core/implementations/reportResources.ts
1616
+ import path20 from "node:path";
1617
+ function reportStaticUrl(reportDir, file) {
1618
+ const relative = path20.relative(reportDir, file);
1619
+ if (relative.startsWith("..") || path20.isAbsolute(relative))
1620
+ throw new Error("\u56FE\u7247\u8DEF\u5F84\u8D85\u51FA\u62A5\u544A\u76EE\u5F55");
1621
+ return `/report-static/${relative.split(path20.sep).map(encodeURIComponent).join("/")}`;
1622
+ }
1623
+ async function prepareBaselineImages(root, snapshots) {
1624
+ const reportDir = await reportRoot(root);
1625
+ const storage = storageFor(reportDir, root);
1626
+ const images = /* @__PURE__ */ new Map();
1627
+ for (const snapshot of snapshots) {
1628
+ if (snapshot.type !== "image") continue;
1629
+ if (!snapshot.key) throw new Error("\u57FA\u7EBF\u56FE\u7247\u7F3A\u5C11\u5BF9\u8C61\u5B58\u50A8 key");
1630
+ let url = images.get(snapshot.key);
1631
+ if (!url) {
1632
+ url = reportStaticUrl(reportDir, await storage.localPath(snapshot.key));
1633
+ images.set(snapshot.key, url);
1634
+ }
1635
+ snapshot.url = url;
1636
+ }
1637
+ }
1638
+
1639
+ // modules/core/implementations/Functions/getBaselineChanges.ts
1640
+ import { readFile as readFile9 } from "node:fs/promises";
1641
+ import { execFile as execFile2 } from "node:child_process";
1642
+ import path21 from "node:path";
1643
+ import { PNG as PNG2 } from "pngjs";
1644
+ async function fromGit(root, sha, file) {
1645
+ const result = await runGit(root, ["show", `${sha}:${file}`]);
1646
+ if (result.ok) return result.stdout;
1647
+ const exists = await runGit(root, ["cat-file", "-e", `${sha}:${file}`]);
1648
+ if (!exists.ok) return null;
1649
+ throw new Error(result.stderr);
1650
+ }
1651
+ async function gitBaselineFiles(root, sha, directory) {
1652
+ const result = await runGit(root, ["ls-tree", "-r", "-z", sha, "--", directory]);
1653
+ if (!result.ok) throw new Error(result.stderr);
1654
+ const files = result.stdout.split("\0").filter(Boolean).flatMap((line) => {
1655
+ const separator = line.indexOf(" ");
1656
+ const file = line.slice(separator + 1);
1657
+ const [, type, oid] = line.slice(0, separator).split(" ");
1658
+ return type === "blob" && /\/baseline(?:-[a-f0-9]{64})?\.json$/.test(file) ? [{ file, oid }] : [];
1659
+ }).sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
1660
+ if (!files.length) return [];
1661
+ const output = await new Promise((resolve, reject) => {
1662
+ const child = execFile2(
1663
+ "git",
1664
+ ["-C", root, "cat-file", "--batch"],
1665
+ {
1666
+ encoding: "buffer",
1667
+ maxBuffer: 32 * 1024 * 1024,
1668
+ timeout: 2e4,
1669
+ windowsHide: true
1670
+ },
1671
+ (error, stdout) => error ? reject(error) : resolve(stdout)
1672
+ );
1673
+ child.stdin.on("error", reject);
1674
+ child.stdin.end(files.map(({ oid }) => oid).join("\n") + "\n");
1675
+ });
1676
+ let offset = 0;
1677
+ return files.map(({ file, oid }) => {
1678
+ const end = output.indexOf(10, offset);
1679
+ const [actualOid, type, length] = output.subarray(offset, end).toString().split(" ");
1680
+ const size = Number(length);
1681
+ if (end < 0 || actualOid !== oid || type !== "blob" || !Number.isSafeInteger(size) || size < 0 || end + 1 + size >= output.length || output[end + 1 + size] !== 10)
1682
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u5386\u53F2\u57FA\u7EBF\uFF1A${file}`);
1683
+ const baseline = JSON.parse(
1684
+ output.subarray(end + 1, end + 1 + size).toString("utf8")
1685
+ );
1686
+ offset = end + 1 + size + 1;
1687
+ const parts = file.slice(directory.length + 1).split("/");
1688
+ return { namespace: parts[0], path: parts.slice(1, -1).join("/"), file, baseline };
1689
+ });
1690
+ }
1691
+ async function currentBaseline(root, namespace) {
1692
+ const baseline = await loadBaseline(await reportRoot(root), namespace);
1693
+ return new Map(
1694
+ [...baseline.cases.entries()].map(([id, entry]) => [
1695
+ entry.path,
1696
+ { path: entry.path, file: entry.file, baseline: entry.baseline }
1697
+ ])
1698
+ );
1699
+ }
1700
+ var definition = (snapshot) => ({
1701
+ id: snapshot.id,
1702
+ name: snapshot.name,
1703
+ type: snapshot.type,
1704
+ content: snapshot.type === "image" ? snapshot.key : snapshot.body,
1705
+ language: snapshot.language,
1706
+ contentType: snapshot.contentType,
1707
+ width: snapshot.width,
1708
+ height: snapshot.height,
1709
+ col: snapshot.col ?? 4,
1710
+ maxDiffPixels: snapshot.maxDiffPixels ?? 0
1711
+ });
1712
+ function currentCase(entry) {
1713
+ return {
1714
+ id: entry.baseline.id,
1715
+ name: entry.baseline.name,
1716
+ treePath: entry.baseline.treePath,
1717
+ snapshots: entry.baseline.snapshots,
1718
+ observations: [],
1719
+ result: { status: "passed" }
1720
+ };
1721
+ }
1722
+ async function getBaselineChanges(input) {
1723
+ const { repoRoot: root, ref } = GetBaselineChangesInputSchema.parse(input);
1724
+ const { sha, files: gitChanges } = await collectChanges(root, ref);
1725
+ if (!sha) throw new Error("\u627E\u4E0D\u5230\u6BD4\u8F83\u5206\u652F");
1726
+ const entries = [];
1727
+ const config = await loadConfig({ repoRoot: root });
1728
+ const historicalConfig = await fromGit(root, sha, "evidra.config.json");
1729
+ const oldConfig = historicalConfig ? parseConfig(JSON.parse(historicalConfig)) : config;
1730
+ const currentDirectory = path21.posix.join(config.reportDir.split(path21.sep).join("/"), "baselines");
1731
+ const oldDirectory = path21.posix.join(oldConfig.reportDir.split(path21.sep).join("/"), "baselines");
1732
+ const configChanged = gitChanges.some((item) => item.path === "evidra.config.json");
1733
+ const affected = new Set(
1734
+ gitChanges.flatMap((item) => [item.path, item.oldPath].filter((file) => !!file)).flatMap((file) => {
1735
+ for (const directory of [currentDirectory, oldDirectory]) {
1736
+ if (file.startsWith(directory + "/")) {
1737
+ const relative = file.slice(directory.length + 1);
1738
+ return [
1739
+ relative.replace(/\/snapshots\/[^/]+$/, "").replace(/\/baseline(?:-[a-f0-9]{64})?\.json$/, "")
1740
+ ];
1741
+ }
1742
+ }
1743
+ return [];
1744
+ })
1745
+ );
1746
+ const historical = configChanged || affected.size ? await gitBaselineFiles(root, sha, oldDirectory) : [];
1747
+ const namespaces = configChanged || affected.size ? [...config.namespaces] : [];
1748
+ const byNamespace = /* @__PURE__ */ new Map();
1749
+ for (const item of historical) {
1750
+ const cases = byNamespace.get(item.namespace) ?? /* @__PURE__ */ new Map();
1751
+ if (!cases.has(item.path)) cases.set(item.path, item);
1752
+ byNamespace.set(item.namespace, cases);
1753
+ }
1754
+ if (configChanged || affected.size) {
1755
+ for (const namespace of [
1756
+ ...oldConfig.namespaces,
1757
+ ...[...byNamespace.keys()].map((id) => ({ id, name: id }))
1758
+ ]) {
1759
+ if (!namespaces.some((item) => item.id === namespace.id)) {
1760
+ namespaceId(namespace.id);
1761
+ namespaces.push(namespace);
1762
+ }
1763
+ }
1764
+ }
1765
+ for (const namespace of namespaces) {
1766
+ if (!configChanged && ![...affected].some((id) => id.startsWith(namespace.id + "/"))) continue;
1767
+ const before = byNamespace.get(namespace.id) ?? /* @__PURE__ */ new Map();
1768
+ const after = await currentBaseline(root, namespace.id);
1769
+ for (const id of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) {
1770
+ if (!configChanged && !affected.has(`${namespace.id}/${id}`)) continue;
1771
+ const a = before.get(id), b = after.get(id);
1772
+ const snapshots = [];
1773
+ for (const sid of /* @__PURE__ */ new Set([
1774
+ ...(a?.baseline.snapshots ?? []).map((snapshot) => snapshot.id),
1775
+ ...(b?.baseline.snapshots ?? []).map((snapshot) => snapshot.id)
1776
+ ])) {
1777
+ const oldSnapshot = a?.baseline.snapshots.find((snapshot) => snapshot.id === sid);
1778
+ const newSnapshot = b?.baseline.snapshots.find((snapshot) => snapshot.id === sid);
1779
+ const change = !oldSnapshot ? "added" : !newSnapshot ? "deleted" : canonical(definition(oldSnapshot)) === canonical(definition(newSnapshot)) ? "same" : "modified";
1780
+ snapshots.push({
1781
+ id: sid,
1782
+ change,
1783
+ baseline: oldSnapshot,
1784
+ current: newSnapshot
1785
+ });
1786
+ }
1787
+ const changed = snapshots.some((snapshot) => snapshot.change !== "same") || a?.baseline.name !== b?.baseline.name || canonical(a?.baseline.treePath) !== canonical(b?.baseline.treePath);
1788
+ if (!changed) continue;
1789
+ entries.push({
1790
+ namespace: namespace.id,
1791
+ namespaceName: namespace.name,
1792
+ file: b?.file ? path21.posix.join(currentDirectory, namespace.id, b.file) : a?.file ?? path21.posix.join(currentDirectory, namespace.id, b?.path ?? a.path, "baseline.json"),
1793
+ item: {
1794
+ id: b?.baseline.id ?? a.baseline.id,
1795
+ change: !a ? "added" : !b ? "deleted" : "modified",
1796
+ baseline: a?.baseline,
1797
+ current: b ? currentCase(b) : void 0,
1798
+ snapshots
1799
+ }
1800
+ });
1801
+ }
1802
+ }
1803
+ const digest = version([sha, entries]);
1804
+ const reportDir = await reportRoot(root);
1805
+ await prepareBaselineImages(
1806
+ root,
1807
+ entries.flatMap(
1808
+ (entry) => entry.item.snapshots.flatMap(
1809
+ (snapshot) => [snapshot.baseline, snapshot.current].filter((item) => !!item)
1810
+ )
1811
+ )
1812
+ );
1813
+ for (const entry of entries) {
1814
+ for (const snapshot of entry.item.snapshots) {
1815
+ if (snapshot.baseline?.type === "image" && snapshot.current?.type === "image" && snapshot.baseline.key !== snapshot.current.key) {
1816
+ const file = await prepareImageDiff(root, snapshot.baseline, snapshot.current);
1817
+ snapshot.diffFile = path21.relative(reportDir, file).split(path21.sep).join("/");
1818
+ snapshot.diffUrl = reportStaticUrl(reportDir, file);
1819
+ }
1820
+ }
1821
+ }
1822
+ return {
1823
+ ref,
1824
+ sha,
1825
+ version: digest,
1826
+ entries,
1827
+ reviewed: await readJson(
1828
+ path21.join(await reportRoot(root), "cache", "reviews", `${digest}.json`)
1829
+ ) ?? []
1830
+ };
1831
+ }
1832
+ async function prepareImageDiff(root, before, after) {
1833
+ if (!before.key || !after.key) throw new Error("\u57FA\u7EBF\u56FE\u7247\u7F3A\u5C11\u5BF9\u8C61\u5B58\u50A8 key");
1834
+ const reportDir = await reportRoot(root);
1835
+ const directory = path21.join(
1836
+ reportDir,
1837
+ "cache",
1838
+ "comparisons",
1839
+ version(["git", before.key, after.key])
1840
+ );
1841
+ const index = path21.join(directory, "diff-v2.json");
1842
+ const cached = await readJson(index);
1843
+ try {
1844
+ if (cached) {
1845
+ const file2 = path21.join(directory, cached);
1846
+ await readFile9(file2);
1847
+ return file2;
1848
+ }
1849
+ } catch (error) {
1850
+ if (error.code !== "ENOENT") throw error;
1851
+ }
1852
+ const storage = storageFor(reportDir, root);
1853
+ const x = PNG2.sync.read(Buffer.from(await storage.download(before.key)));
1854
+ const y = PNG2.sync.read(Buffer.from(await storage.download(after.key)));
1855
+ const width = Math.max(x.width, y.width), height = Math.max(x.height, y.height);
1856
+ const left = new PNG2({ width, height }), right = new PNG2({ width, height });
1857
+ PNG2.bitblt(x, left, 0, 0, x.width, x.height, 0, 0);
1858
+ PNG2.bitblt(y, right, 0, 0, y.width, y.height, 0, 0);
1859
+ const result = localImageDiff(PNG2.sync.write(left), PNG2.sync.write(right));
1860
+ if (!result.png) throw new Error("\u65E0\u6CD5\u751F\u6210\u56FE\u7247\u5DEE\u5F02");
1861
+ const filename = `diff-${hash(result.png)}.png`;
1862
+ const file = path21.join(directory, filename);
1863
+ await writeBytesAtomic(file, result.png);
1864
+ await writeJsonAtomic(index, filename);
1865
+ return file;
1866
+ }
1867
+
1868
+ // modules/core/implementations/Functions/reviewBaselineChanges.ts
1869
+ async function reviewBaselineChanges(input) {
1870
+ const { repoRoot, ref, version: version2, items, reviewed } = ReviewBaselineChangesInputSchema.parse(input);
1871
+ const changes = await getBaselineChanges({ repoRoot, ref });
1872
+ if (changes.version !== version2)
1873
+ throw Object.assign(new Error("\u57FA\u7EBF\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1874
+ const valid = new Set(
1875
+ changes.entries.map((entry) => JSON.stringify([entry.namespace, entry.item.id]))
1876
+ );
1877
+ if (items.some((id) => !valid.has(id)))
1878
+ throw Object.assign(new Error("\u65E0\u6548\u5BA1\u6838\u9879"), { statusCode: 400 });
1879
+ const selected = new Set(changes.reviewed);
1880
+ for (const id of items) reviewed ? selected.add(id) : selected.delete(id);
1881
+ const ids = [...selected];
1882
+ await writeJsonAtomic(
1883
+ path22.join(await reportRoot(repoRoot), "cache", "reviews", `${version2}.json`),
1884
+ ids
1885
+ );
1886
+ return { reviewed: ids };
1887
+ }
1888
+
1889
+ // modules/core/implementations/Functions/deleteBaselineFile.ts
1890
+ import path23 from "node:path";
1891
+ import { rm as rm4 } from "node:fs/promises";
1892
+
1893
+ // modules/core/contracts/functions/deleteBaselineFile.ts
1894
+ import { z as z17 } from "zod";
1895
+ var DeleteBaselineFileInputSchema = z17.object({
1896
+ repoRoot: z17.string(),
1897
+ namespace: z17.string(),
1898
+ file: z17.string(),
1899
+ version: z17.string()
1900
+ });
1901
+
1902
+ // modules/core/implementations/Functions/deleteBaselineFile.ts
1903
+ async function deleteBaselineFile(input) {
1904
+ const { repoRoot, namespace, file, version: version2 } = DeleteBaselineFileInputSchema.parse(input);
1905
+ const { absoluteReportPath } = await resolveConfig({ repoRoot, namespace });
1906
+ const current = await getBaseline(absoluteReportPath, namespace);
1907
+ if (current.version !== version2)
1908
+ throw Object.assign(new Error("\u57FA\u7EBF\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0"), { statusCode: 409 });
1909
+ if (!current.candidates.some((item) => item.file === file))
1910
+ throw Object.assign(new Error("\u57FA\u7EBF\u6587\u4EF6\u4E0D\u5B58\u5728"), { statusCode: 404 });
1911
+ await rm4(path23.join(absoluteReportPath, "baselines", namespace, file));
1912
+ return { ok: true };
1913
+ }
1914
+
1915
+ // modules/core/implementations/Functions/compareTasks.ts
1916
+ import path24 from "node:path";
1917
+
1918
+ // modules/core/contracts/functions/compareTasks.ts
1919
+ import { z as z18 } from "zod";
1920
+ var CompareTasksInputSchema = z18.object({
1921
+ repoRoot: z18.string(),
1922
+ baseTaskId: z18.string().regex(/^[a-zA-Z0-9_-]{3,}$/),
1923
+ taskId: z18.string().regex(/^[a-zA-Z0-9_-]{3,}$/)
1924
+ });
1925
+
1926
+ // modules/core/implementations/Functions/compareTasks.ts
1927
+ async function compareTasks(input) {
1928
+ const { repoRoot, baseTaskId, taskId } = CompareTasksInputSchema.parse(input);
1929
+ const reportDir = await reportRoot(repoRoot);
1930
+ const [base, current] = await Promise.all([
1931
+ getTask(reportDir, baseTaskId),
1932
+ getTask(reportDir, taskId)
1933
+ ]);
1934
+ if (!base) throw new Error(`\u4EFB\u52A1\u4E0D\u5B58\u5728: ${baseTaskId}`);
1935
+ if (!current) throw new Error(`\u4EFB\u52A1\u4E0D\u5B58\u5728: ${taskId}`);
1936
+ if (base.record.task.namespace !== current.record.task.namespace)
1937
+ throw new Error("\u53EA\u80FD\u6BD4\u8F83\u540C\u4E00 namespace \u7684\u4EFB\u52A1");
1938
+ const baseCases = new Map(base.record.cases.map((item) => [item.id, item]));
1939
+ const baseline = { cases: /* @__PURE__ */ new Map() };
1940
+ const unavailableBaseCaseIds = /* @__PURE__ */ new Set();
1941
+ for (const item of base.record.cases) {
1942
+ if (item.snapshots === null) unavailableBaseCaseIds.add(item.id);
1943
+ baseline.cases.set(item.id, {
1944
+ path: item.id,
1945
+ hash: hash(JSON.stringify(item)),
1946
+ baseline: {
1947
+ id: item.id,
1948
+ name: item.name,
1949
+ treePath: item.treePath,
1950
+ snapshots: (item.snapshots ?? []).map(toSnapshot),
1951
+ approvedAt: ""
1952
+ }
1953
+ });
1954
+ }
1955
+ const comparison = await compareRecord(
1956
+ reportDir,
1957
+ {
1958
+ download: (key) => readTaskImage(reportDir, key),
1959
+ localPath: async (key) => {
1960
+ await readTaskImage(reportDir, key);
1961
+ return path24.resolve(reportDir, "objects", key);
1962
+ },
1963
+ upload: async () => {
1964
+ throw new Error("\u4EFB\u52A1\u6BD4\u8F83\u4E0D\u5199\u5165\u57FA\u7EBF\u5B58\u50A8");
1965
+ }
1966
+ },
1967
+ current.record,
1968
+ baseline,
1969
+ { baseTaskId, unavailableBaseCaseIds }
1970
+ );
1971
+ return {
1972
+ baseTaskId,
1973
+ taskId,
1974
+ namespace: comparison.namespace,
1975
+ deletionAllowed: comparison.deletionAllowed,
1976
+ summary: comparison.summary,
1977
+ cases: comparison.cases.map(({ baseline: previous, baselineHash: _hash, ...diff }) => {
1978
+ const old = baseCases.get(diff.id);
1979
+ return {
1980
+ ...diff,
1981
+ baseline: old ? {
1982
+ ...toCase(old),
1983
+ snapshots: old.snapshots === null ? null : previous.snapshots
1984
+ } : void 0
1985
+ };
1986
+ })
1987
+ };
1988
+ }
1989
+
1990
+ // modules/core/implementations/Functions/getGitDiff.ts
1991
+ import path25 from "node:path";
1992
+ import { lstat as lstat2, readFile as readFile10, readlink as readlink2, realpath as realpath4 } from "node:fs/promises";
1993
+
1994
+ // modules/core/contracts/functions/getGitDiff.ts
1995
+ import { z as z19 } from "zod";
1996
+ var GetGitDiffInputSchema = z19.object({
1997
+ repoRoot: z19.string(),
1998
+ ref: z19.string(),
1999
+ file: z19.string(),
2000
+ version: z19.string().optional()
2001
+ });
2002
+
2003
+ // modules/core/implementations/Functions/getGitDiff.ts
2004
+ async function getGitDiff(input) {
2005
+ const { repoRoot: root, ref, file, version: expectedKey } = GetGitDiffInputSchema.parse(input);
2006
+ const { sha, files } = await collectChanges(root, ref);
2007
+ const entry = files.find((entry2) => entry2.path === file);
2008
+ if (!entry) throw new Error("\u627E\u4E0D\u5230\u4EE3\u7801\u6539\u52A8\u6587\u4EF6");
2009
+ if (expectedKey) {
2010
+ const after = entry.status === "deleted" ? null : await worktreeSide(await realpath4(root), entry.path);
2011
+ if (reviewKey(entry, after) !== expectedKey)
2012
+ throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0"), { statusCode: 409 });
2013
+ }
2014
+ let original = "", modified = "", tooLarge = false;
2015
+ if (entry.status !== "added") {
2016
+ const object = `${sha}:${entry.oldPath ?? file}`;
2017
+ const type = (await git(root, ["cat-file", "-t", object])).trim();
2018
+ if (type === "commit")
2019
+ original = `Subproject commit ${(await git(root, ["rev-parse", object])).trim()}
2020
+ `;
2021
+ else if (Number(await git(root, ["cat-file", "-s", object])) > MAX_BYTES) tooLarge = true;
2022
+ else original = await git(root, ["show", object]);
2023
+ }
2024
+ if (entry.status !== "deleted") {
2025
+ const absolute = path25.resolve(root, file);
2026
+ const parent = await realpath4(path25.dirname(absolute));
2027
+ const repo = await realpath4(root);
2028
+ const relative = path25.relative(repo, parent);
2029
+ if (relative === ".." || relative.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative))
2030
+ throw new Error("\u6587\u4EF6\u4E0D\u5728\u4ED3\u5E93\u5185");
2031
+ const stat3 = await lstat2(absolute);
2032
+ if (stat3.isSymbolicLink()) modified = await readlink2(absolute);
2033
+ else if (stat3.isDirectory())
2034
+ modified = `Subproject commit ${(await git(absolute, ["rev-parse", "HEAD"])).trim()}
2035
+ `;
2036
+ else if (stat3.size > MAX_BYTES) tooLarge = true;
2037
+ else modified = await readFile10(absolute, "utf8");
2038
+ }
2039
+ const isBinary = original.includes("\0") || modified.includes("\0");
2040
+ return {
2041
+ path: entry.path,
2042
+ ...entry.oldPath ? { oldPath: entry.oldPath } : {},
2043
+ status: entry.status,
2044
+ original: isBinary || tooLarge ? "" : original,
2045
+ modified: isBinary || tooLarge ? "" : modified,
2046
+ isBinary,
2047
+ tooLarge
2048
+ };
2049
+ }
2050
+
2051
+ // modules/core/contracts/functions/listTaskSummaries.ts
2052
+ import { z as z20 } from "zod";
2053
+ var ListTaskSummariesInputSchema = z20.object({
2054
+ repoRoot: z20.string()
2055
+ });
2056
+
2057
+ // modules/core/implementations/reportStatus.ts
2058
+ function reviewCounts(items) {
2059
+ const counts = {};
2060
+ for (const item of items) {
2061
+ const changes = item.change === "unavailable" ? ["unavailable"] : item.snapshots.length ? item.snapshots.map((snapshot) => snapshot.change) : [item.change];
2062
+ if (item.change === "modified" && !changes.some((change) => change !== "same"))
2063
+ changes.push("modified");
2064
+ for (const change of changes) counts[change] = (counts[change] ?? 0) + 1;
2065
+ }
2066
+ return counts;
2067
+ }
2068
+ function taskStatus(execution, counts) {
2069
+ if (execution.running) return "running";
2070
+ if (execution.total > 0 && execution.failed === execution.total) return "failed";
2071
+ if (execution.failed > 0) return "partial";
2072
+ if (counts.unavailable > 0) return "unavailable";
2073
+ const kinds = ["added", "modified", "deleted"].filter((kind) => counts[kind] > 0);
2074
+ if (!kinds.length) return "same";
2075
+ if (kinds.length > 1 || kinds[0] === "modified") return "changed";
2076
+ return kinds[0] === "added" ? "added" : "deleted";
2077
+ }
2078
+ function taskDisplay(task) {
2079
+ return {
2080
+ executionId: task.id,
2081
+ namespace: task.namespace,
2082
+ namespaceName: task.namespaceName,
2083
+ taskName: task.name,
2084
+ coverage: task.coverage,
2085
+ startedAt: task.startedAt,
2086
+ endedAt: task.finishedAt,
2087
+ durationMs: task.finishedAt ? Date.parse(task.finishedAt) - Date.parse(task.startedAt) : 0,
2088
+ status: task.status === "passed" || task.status === "skipped" ? "success" : task.status,
2089
+ failedCount: task.failedCount,
2090
+ successCount: task.status === "passed" ? 1 : 0,
2091
+ taskStatus: task.cached ? taskStatus(
2092
+ { running: task.status === "running", failed: task.failedCount, total: task.caseCount },
2093
+ task.counts
2094
+ ) : "unknown",
2095
+ sceneCount: task.caseCount,
2096
+ comparison: !task.cached ? "unknown" : Object.entries(task.counts).some(([key, count]) => key !== "same" && count > 0) ? "attention" : "same"
2097
+ };
2098
+ }
2099
+
2100
+ // modules/core/implementations/internal/listTasks.ts
2101
+ import { readdir as readdir3 } from "node:fs/promises";
2102
+ import path26 from "node:path";
2103
+
2104
+ // modules/core/contracts/internal/listTasks.ts
2105
+ import { z as z21 } from "zod";
2106
+ var ListTasksInputSchema = z21.object({
2107
+ limit: z21.number().int().min(1).max(100).optional()
2108
+ });
2109
+
2110
+ // modules/core/implementations/internal/listTasks.ts
2111
+ async function listTasks(input, cwd, namespaces) {
2112
+ const { limit = 20 } = ListTasksInputSchema.parse(input);
2113
+ const root = path26.join(cwd, "tasks");
2114
+ const tasks = [];
2115
+ async function directories(directory, pattern) {
2116
+ try {
2117
+ return (await readdir3(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
2118
+ } catch (error) {
2119
+ if (error.code === "ENOENT") return [];
2120
+ throw error;
2121
+ }
2122
+ }
2123
+ for (const day of await directories(root, /^\d{4}-\d{2}-\d{2}$/)) {
2124
+ const dayRoot = path26.join(root, day);
2125
+ for (const run of await directories(dayRoot, /^\d{2}-\d{2}-\d{2}-[A-Za-z0-9-]+$/)) {
2126
+ const file = path26.join(dayRoot, run, "task.json");
2127
+ const manifest = await readJson(file);
2128
+ if (!manifest || (manifest.formatVersion ?? 0) < TASK_SCEHAM_VERSION || !namespaces.has(manifest.task.namespace))
2129
+ continue;
2130
+ const record = await readTaskRecord(file);
2131
+ tasks.push({
2132
+ ...record.task,
2133
+ failedCount: record.cases.filter((item) => item.result.status === "failed").length
2134
+ });
2135
+ if (tasks.length === limit) return { tasks };
2136
+ }
2137
+ }
2138
+ return { tasks };
2139
+ }
2140
+
2141
+ // modules/core/implementations/Functions/listTaskSummaries.ts
2142
+ async function listTaskSummaries(input) {
2143
+ const { repoRoot: root } = ListTaskSummariesInputSchema.parse(input);
2144
+ const config = await loadConfig({ repoRoot: root });
2145
+ const namespaces = new Set(config.namespaces.map((item) => item.id));
2146
+ const reportDir = await reportRoot(root);
2147
+ const page = await listTasks({ limit: 40 }, reportDir, namespaces);
2148
+ const tasks = page.tasks;
2149
+ const versions = new Map(
2150
+ await Promise.all(
2151
+ [...new Set(tasks.map((task) => task.namespace))].map(
2152
+ async (id) => [id, await readBaselineVersion(reportDir, id)]
2153
+ )
2154
+ )
2155
+ );
2156
+ return Promise.all(
2157
+ tasks.map(async (task) => {
2158
+ const summary = await readCachedComparisonSummary(
2159
+ reportDir,
2160
+ task.namespace,
2161
+ task.id,
2162
+ versions.get(task.namespace)
2163
+ );
2164
+ const item = {
2165
+ id: task.id,
2166
+ namespaceName: config.namespaces.find((ns) => ns.id === task.namespace).name,
2167
+ namespace: task.namespace,
2168
+ name: task.name,
2169
+ startedAt: task.startedAt,
2170
+ status: task.status,
2171
+ finishedAt: task.finishedAt,
2172
+ coverage: task.coverage,
2173
+ caseCount: task.caseCount,
2174
+ failedCount: task.failedCount,
2175
+ cached: summary !== null,
2176
+ counts: summary ? { ...summary } : {}
2177
+ };
2178
+ return { ...item, display: taskDisplay(item) };
2179
+ })
2180
+ );
2181
+ }
2182
+
2183
+ // modules/core/contracts/functions/readProjectInfo.ts
2184
+ import { z as z22 } from "zod";
2185
+ var ReadProjectInfoInputSchema = z22.object({ repoRoot: z22.string() });
2186
+
2187
+ // modules/core/implementations/Functions/readProjectInfo.ts
2188
+ var FALLBACK_REFS = ["main", "master", "origin/main", "origin/master"];
2189
+ async function readProjectInfo(input) {
2190
+ const { repoRoot } = ReadProjectInfoInputSchema.parse(input);
2191
+ const toplevel = await gitOptional(repoRoot, ["rev-parse", "--show-toplevel"]);
2192
+ if (!toplevel) {
2193
+ return {
2194
+ repoRoot,
2195
+ isGitRepo: false,
2196
+ branch: null,
2197
+ detached: false,
2198
+ headSha: null,
2199
+ refs: [],
2200
+ defaultRef: null
2201
+ };
2202
+ }
2203
+ const abbrev = await gitOptional(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
2204
+ const detached = !abbrev || abbrev === "HEAD";
2205
+ const headSha = await gitOptional(repoRoot, ["rev-parse", "--short", "HEAD"]);
2206
+ const localHeads = (await gitOptional(repoRoot, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]))?.split("\n").filter(Boolean) ?? [];
2207
+ const names = [.../* @__PURE__ */ new Set([...localHeads, ...FALLBACK_REFS])];
2208
+ const refs = [];
2209
+ for (const name of names) {
2210
+ const sha = await resolveRef(repoRoot, name);
2211
+ if (!sha) continue;
2212
+ refs.push({
2213
+ name,
2214
+ sha,
2215
+ shortSha: await gitOptional(repoRoot, ["rev-parse", "--short", name]) ?? sha.slice(0, 7)
2216
+ });
2217
+ }
2218
+ const defaultRef = refs.find((ref) => ref.name === "main")?.name ?? refs.find((ref) => ref.name === "origin/main")?.name ?? refs.find((ref) => ref.name === "master")?.name ?? refs[0]?.name ?? null;
2219
+ return {
2220
+ repoRoot: toplevel,
2221
+ isGitRepo: true,
2222
+ branch: detached ? null : abbrev ?? null,
2223
+ detached,
2224
+ headSha,
2225
+ refs,
2226
+ defaultRef
2227
+ };
2228
+ }
2229
+
2230
+ // modules/core/contracts/functions/listBaselines.ts
2231
+ import { z as z23 } from "zod";
2232
+ var ListBaselinesInputSchema = z23.object({ repoRoot: z23.string() });
2233
+
2234
+ // modules/core/implementations/reportTree.ts
2235
+ var reportEntryKey = (namespace, id) => JSON.stringify([namespace, id]);
2236
+ function buildReportTree(namespaces, entries, running) {
2237
+ return namespaces.flatMap((ns) => {
2238
+ const children = [];
2239
+ for (const entry of entries.filter((e) => e.namespace === ns.id)) {
2240
+ const item = entry.item.current ?? entry.item.baseline;
2241
+ const parts = item.treePath.length ? item.treePath : [{ key: item.id, display: item.name }];
2242
+ let nodes = children;
2243
+ const keys = [ns.id];
2244
+ for (const part of parts.slice(0, -1)) {
2245
+ keys.push(part.key);
2246
+ const key = `folder:${JSON.stringify(keys)}`;
2247
+ let folder = nodes.find((node) => node.key === key);
2248
+ if (!folder) {
2249
+ folder = { key, label: part.display, kind: "folder", children: [] };
2250
+ nodes.push(folder);
2251
+ }
2252
+ nodes = folder.children;
2253
+ }
2254
+ nodes.push({
2255
+ key: entry.key,
2256
+ label: parts.at(-1).display + (entry.ignored ? "\uFF08\u5DF2\u5FFD\u7565\uFF09" : ""),
2257
+ kind: "case"
2258
+ });
2259
+ }
2260
+ return running ? children : [
2261
+ {
2262
+ key: `namespace:${ns.id}`,
2263
+ label: ns.name,
2264
+ kind: "namespace",
2265
+ namespace: ns.id,
2266
+ children
2267
+ }
2268
+ ];
2269
+ });
2270
+ }
2271
+
2272
+ // modules/core/implementations/Functions/listBaselines.ts
2273
+ async function listBaselines(input) {
2274
+ const { repoRoot: root } = ListBaselinesInputSchema.parse(input);
2275
+ const config = await loadConfig({ repoRoot: root });
2276
+ const namespaces = await Promise.all(
2277
+ config.namespaces.map(async (ns) => ({ ...ns, ...await readBaseline(root, ns.id) }))
2278
+ );
2279
+ await prepareBaselineImages(
2280
+ root,
2281
+ namespaces.flatMap((group) => [
2282
+ ...group.cases.flatMap((item) => item.snapshots),
2283
+ ...(group.candidates ?? []).flatMap((item) => item.baseline.snapshots)
2284
+ ])
2285
+ );
2286
+ const entries = namespaces.flatMap(
2287
+ (group) => (group.candidates ?? group.cases.map((baseline) => ({ baseline, file: "", ignored: false }))).map(({ baseline, file, ignored }) => ({
2288
+ key: reportEntryKey(group.id, file || baseline.id),
2289
+ ignored,
2290
+ file,
2291
+ namespace: group.id,
2292
+ taskId: "",
2293
+ version: group.baselineVersion,
2294
+ item: {
2295
+ id: baseline.id,
2296
+ baseline,
2297
+ change: "same",
2298
+ snapshots: baseline.snapshots.map((snapshot) => ({
2299
+ id: snapshot.id,
2300
+ baseline: snapshot,
2301
+ change: "same"
2302
+ }))
2303
+ }
2304
+ }))
2305
+ );
2306
+ return { namespaces, entries, tree: buildReportTree(namespaces, entries, false) };
2307
+ }
2308
+
2309
+ // modules/core/implementations/Functions/readTaskReport.ts
2310
+ import path27 from "node:path";
2311
+
2312
+ // modules/core/contracts/functions/readTaskReport.ts
2313
+ import { z as z24 } from "zod";
2314
+ var ReadTaskReportInputSchema = z24.object({ repoRoot: z24.string(), taskId: z24.string() });
2315
+
2316
+ // modules/core/implementations/Functions/readTaskReport.ts
2317
+ async function readTaskReport(input) {
2318
+ const { repoRoot: root, taskId: id } = ReadTaskReportInputSchema.parse(input);
2319
+ const task = await readTask(root, id);
2320
+ const comparison = await compareTask({ repoRoot: root, taskId: id });
2321
+ const reportDir = await reportRoot(root);
2322
+ for (const item of comparison.cases) {
2323
+ const images = [
2324
+ ...item.current?.snapshots ?? [],
2325
+ ...item.current?.observations ?? [],
2326
+ ...item.baseline?.snapshots ?? [],
2327
+ ...item.snapshots.flatMap((snapshot) => [snapshot.current, snapshot.baseline])
2328
+ ];
2329
+ for (const image of new Set(images)) {
2330
+ if (image?.type === "image" && image.url) image.url = reportStaticUrl(reportDir, image.url);
2331
+ }
2332
+ for (const snapshot of item.snapshots) {
2333
+ if (snapshot.diffFile)
2334
+ snapshot.diffUrl = reportStaticUrl(reportDir, path27.join(reportDir, snapshot.diffFile));
2335
+ }
2336
+ }
2337
+ const config = await loadConfig({ repoRoot: root });
2338
+ const namespace = config.namespaces.find((ns) => ns.id === task.namespace) ?? {
2339
+ id: task.namespace,
2340
+ name: task.namespace
2341
+ };
2342
+ const entries = comparison.cases.map((item) => ({
2343
+ key: reportEntryKey(task.namespace, item.id),
2344
+ namespace: task.namespace,
2345
+ item,
2346
+ taskId: id,
2347
+ version: comparison.baselineVersion
2348
+ }));
2349
+ const display = taskDisplay({
2350
+ ...task,
2351
+ namespaceName: namespace.name,
2352
+ cached: true,
2353
+ counts: reviewCounts(comparison.cases),
2354
+ caseCount: task.cases.length,
2355
+ failedCount: task.cases.filter((item) => item.result.status === "failed").length
2356
+ });
2357
+ return { task, comparison, entries, tree: buildReportTree([namespace], entries, true), display };
2358
+ }
2359
+
2360
+ // packages/service/src/index.ts
2361
+ import process2 from "node:process";
2362
+
2363
+ // packages/service/src/server.ts
2364
+ import { serve } from "@hono/node-server";
2365
+ import { serveStatic } from "@hono/node-server/serve-static";
2366
+ import { Hono } from "hono";
2367
+ import { existsSync } from "node:fs";
2368
+ import { stat } from "node:fs/promises";
2369
+ import path28 from "node:path";
2370
+ import { z as z25 } from "zod";
2371
+ function defaultWebDist() {
2372
+ const fromSource = path28.resolve(import.meta.dirname, "../../../dist/web");
2373
+ const fromBundle = path28.resolve(import.meta.dirname, "../../dist/web");
2374
+ return [fromSource, fromBundle].find((directory) => existsSync(path28.join(directory, "index.html"))) ?? fromSource;
2375
+ }
2376
+ async function startServer(options) {
2377
+ const root = path28.resolve(options.repoRoot);
2378
+ await loadConfig({ repoRoot: root });
2379
+ const webDist = options.webDist ?? defaultWebDist();
2380
+ const app = createApp(root, webDist);
2381
+ let server;
2382
+ const address = await new Promise((resolve, reject) => {
2383
+ server = serve(
2384
+ {
2385
+ fetch: app.fetch,
2386
+ port: options.port ?? 4175,
2387
+ hostname: options.host ?? "127.0.0.1"
2388
+ },
2389
+ resolve
2390
+ );
2391
+ server.once("error", reject);
2392
+ });
2393
+ const url = `http://${options.host ?? "127.0.0.1"}:${address.port}`;
2394
+ return {
2395
+ url,
2396
+ port: address.port,
2397
+ async close() {
2398
+ await new Promise((resolve, reject) => {
2399
+ server.close((error) => error ? reject(error) : resolve());
2400
+ server.closeAllConnections?.();
2401
+ });
2402
+ }
2403
+ };
2404
+ }
2405
+ function createApp(root, webDist) {
2406
+ const app = new Hono();
2407
+ app.onError((error, context) => {
2408
+ const status = error instanceof z25.ZodError ? 400 : error.statusCode ?? 500;
2409
+ return context.json({ error: String(error.message ?? error) }, status);
2410
+ });
2411
+ app.use("/api/*", async (context, next) => {
2412
+ context.header("Cache-Control", "no-store");
2413
+ await next();
2414
+ });
2415
+ app.get(
2416
+ "/api/project",
2417
+ async (context) => context.json(await readProjectInfo({ repoRoot: root }))
2418
+ );
2419
+ app.get(
2420
+ "/api/code-changes",
2421
+ async (context) => context.json(await getGitChanges({ repoRoot: root, ref: context.req.query("ref") ?? "HEAD" }))
2422
+ );
2423
+ app.get(
2424
+ "/api/code-changes/diff",
2425
+ async (context) => context.json(
2426
+ await getGitDiff({
2427
+ repoRoot: root,
2428
+ ref: context.req.query("ref") ?? "HEAD",
2429
+ file: context.req.query("path") ?? "",
2430
+ version: context.req.query("version")
2431
+ })
2432
+ )
2433
+ );
2434
+ app.patch("/api/code-changes/reviews", async (context) => {
2435
+ const result = await reviewCodeChanges({ ...await context.req.json(), repoRoot: root });
2436
+ return context.json(result);
2437
+ });
2438
+ app.get(
2439
+ "/api/baseline-changes",
2440
+ async (context) => context.json(
2441
+ await getBaselineChanges({ repoRoot: root, ref: context.req.query("ref") ?? "HEAD" })
2442
+ )
2443
+ );
2444
+ app.patch("/api/baseline-changes/reviews", async (context) => {
2445
+ const result = await reviewBaselineChanges({ ...await context.req.json(), repoRoot: root });
2446
+ return context.json(result);
2447
+ });
2448
+ app.delete("/api/namespaces/:namespace/baselines", async (context) => {
2449
+ const result = await deleteBaselineFile({
2450
+ repoRoot: root,
2451
+ file: context.req.query("file"),
2452
+ version: context.req.query("version"),
2453
+ namespace: context.req.param("namespace")
2454
+ });
2455
+ return context.json(result);
2456
+ });
2457
+ app.get(
2458
+ "/api/baselines",
2459
+ async (context) => context.json(await listBaselines({ repoRoot: root }))
2460
+ );
2461
+ app.get("/api/tasks/:taskId", async (context) => {
2462
+ return context.json(
2463
+ await readTaskReport({ repoRoot: root, taskId: context.req.param("taskId") })
2464
+ );
2465
+ });
2466
+ app.get(
2467
+ "/api/tasks",
2468
+ async (context) => context.json(
2469
+ await listTaskSummaries({
2470
+ repoRoot: root
2471
+ })
2472
+ )
2473
+ );
2474
+ app.post("/api/tasks/:taskId/approvals", async (context) => {
2475
+ const result = await approve({
2476
+ ...await context.req.json(),
2477
+ repoRoot: root,
2478
+ taskId: context.req.param("taskId")
2479
+ });
2480
+ return context.json(result, result.conflict ? 409 : 200);
2481
+ });
2482
+ app.use("*", async (context, next) => {
2483
+ await next();
2484
+ const filePath = context.get("staticFile");
2485
+ if (!filePath) return;
2486
+ const stats = await stat(filePath);
2487
+ context.header(
2488
+ "ETag",
2489
+ `W/"${stats.size.toString(16)}-${stats.mtimeMs.toString(16)}-${stats.ctimeMs.toString(16)}"`
2490
+ );
2491
+ const relativePath = path28.relative(webDist, filePath).split(path28.sep).join("/");
2492
+ const immutable = context.req.path.startsWith("/report-static/") && /(?:^|[-/])[a-f0-9]{64}\.png$/.test(context.req.path) || !context.req.path.startsWith("/report-static/") && /^assets\/.+-[\w-]{8,}\.[\w.]+$/.test(relativePath);
2493
+ context.header("Cache-Control", immutable ? "public, max-age=31536000, immutable" : "no-cache");
2494
+ if (context.res.status !== 200 || !["GET", "HEAD"].includes(context.req.method)) return;
2495
+ const etag = context.res.headers.get("ETag");
2496
+ if (!etag) return;
2497
+ const ifNoneMatch = context.req.header("If-None-Match");
2498
+ const modifiedSince = context.req.header("If-Modified-Since");
2499
+ const lastModified = context.res.headers.get("Last-Modified");
2500
+ const unchanged = ifNoneMatch !== void 0 ? ifNoneMatch.split(",").some(
2501
+ (tag) => tag.trim() === "*" || tag.trim().replace(/^W\//, "") === etag.replace(/^W\//, "")
2502
+ ) : modifiedSince && lastModified && Date.parse(lastModified) <= Date.parse(modifiedSince);
2503
+ if (unchanged) {
2504
+ await context.res.body?.cancel();
2505
+ const headers = new Headers(context.res.headers);
2506
+ headers.delete("Content-Length");
2507
+ context.res = new Response(null, { status: 304, headers });
2508
+ }
2509
+ });
2510
+ const staticOptions = {
2511
+ onFound: (filePath, context) => {
2512
+ context.set("staticFile", filePath);
2513
+ }
2514
+ };
2515
+ app.get("/report-static/*", async (context, next) => {
2516
+ const { absoluteReportPath } = await resolveConfig({ repoRoot: root });
2517
+ context.header("X-Content-Type-Options", "nosniff");
2518
+ return serveStatic({
2519
+ root: absoluteReportPath,
2520
+ rewriteRequestPath: (requestPath) => requestPath.replace(/^\/report-static\//, ""),
2521
+ ...staticOptions
2522
+ })(context, next);
2523
+ });
2524
+ app.get("/report-static/*", (context) => context.notFound());
2525
+ app.all("/api/*", (context) => context.json({ error: "\u672A\u77E5\u63A5\u53E3" }, 404));
2526
+ app.use("*", async (context, next) => {
2527
+ context.header("X-Content-Type-Options", "nosniff");
2528
+ await next();
2529
+ });
2530
+ app.get("*", serveStatic({ root: webDist, ...staticOptions }));
2531
+ app.get("*", (context, next) => path28.extname(context.req.path) ? context.notFound() : next());
2532
+ app.get("*", serveStatic({ root: webDist, path: "index.html", ...staticOptions }));
2533
+ app.get("*", (context) => context.text("\u62A5\u544A UI \u5C1A\u672A\u6784\u5EFA\uFF1A\u8BF7\u5148\u8FD0\u884C pnpm build", 404));
2534
+ return app;
2535
+ }
2536
+
2537
+ // packages/service/src/index.ts
2538
+ async function startWorkbench(options) {
2539
+ const { repoRoot, port } = options;
2540
+ const server = await startServer({ repoRoot, port, host: "0.0.0.0" });
2541
+ console.log(`
2542
+ \u6D4B\u8BD5\u62A5\u544A\u670D\u52A1\u5DF2\u542F\u52A8`);
2543
+ console.log(`\u4ED3\u5E93: ${repoRoot}`);
2544
+ console.log(`\u5730\u5740: ${server.url}`);
2545
+ console.log(`\u9875\u9762: ${server.url}/`);
2546
+ console.log(`\u505C\u6B62: Ctrl+C
2547
+ `);
2548
+ let stopping = false;
2549
+ async function stop() {
2550
+ if (stopping) return;
2551
+ stopping = true;
2552
+ await server.close();
2553
+ process2.exit(0);
2554
+ }
2555
+ process2.once("SIGINT", () => void stop());
2556
+ process2.once("SIGTERM", () => void stop());
2557
+ }
2558
+
2559
+ // packages/service/src/init.ts
2560
+ import { mkdir as mkdir4, readFile as readFile11, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
2561
+ import path29 from "node:path";
2562
+ async function initProject(directory) {
2563
+ const root = path29.resolve(directory);
2564
+ await mkdir4(root, { recursive: true });
2565
+ const messages = [];
2566
+ async function create(file, content) {
2567
+ try {
2568
+ await writeFile3(file, content, { flag: "wx" });
2569
+ messages.push(`\u5DF2\u521B\u5EFA ${path29.relative(root, file)}`);
2570
+ } catch (error) {
2571
+ if (error.code !== "EEXIST") throw error;
2572
+ messages.push(`\u5DF2\u4FDD\u7559 ${path29.relative(root, file)}`);
2573
+ }
2574
+ }
2575
+ const skill = await readFile11(
2576
+ path29.resolve(import.meta.dirname, "../../../skills/evidra/SKILL.md"),
2577
+ "utf8"
2578
+ );
2579
+ let injected = false;
2580
+ for (const agent of [".claude", ".codex"]) {
2581
+ let exists = false;
2582
+ try {
2583
+ exists = (await stat2(path29.join(root, agent))).isDirectory();
2584
+ } catch (error) {
2585
+ if (error.code !== "ENOENT") throw error;
2586
+ }
2587
+ if (!exists) continue;
2588
+ injected = true;
2589
+ const target = path29.join(root, agent, "skills/evidra");
2590
+ await mkdir4(target, { recursive: true });
2591
+ await create(path29.join(target, "SKILL.md"), skill);
2592
+ }
2593
+ if (!injected) messages.push("\u672A\u53D1\u73B0 .claude \u6216 .codex \u6587\u4EF6\u5939\uFF0C\u672A\u6CE8\u5165\u4EFB\u4F55 skill\u3002");
2594
+ return messages;
2595
+ }
2596
+
2597
+ // packages/service/src/cli.ts
2598
+ var cli = cac("evidra");
2599
+ cli.command("init [path]", "\u590D\u5236 skill \u5230\u9879\u76EE\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").action(async (target) => {
2600
+ const root = path30.resolve(target ?? process.cwd());
2601
+ console.log(`\u521D\u59CB\u5316 Evidra\uFF1A${root}`);
2602
+ for (const message of await initProject(root)) console.log(message);
2603
+ });
2604
+ cli.command("start", "\u542F\u52A8\u5DE5\u4F5C\u53F0\uFF0C\u670D\u52A1\u5728\u524D\u53F0\u8FD0\u884C\uFF0C\u6309 Ctrl+C \u505C\u6B62").option("--repo <path>", "\u4ED3\u5E93\u8DEF\u5F84\uFF0C\u9ED8\u8BA4 TEST_REPORT_REPO \u6216\u5F53\u524D\u76EE\u5F55").option("--port <port>", "\u7AEF\u53E3\uFF0C\u9ED8\u8BA4 TEST_REPORT_PORT \u6216 4175").action(async (options) => {
2605
+ const port = Number(options.port ?? process.env.TEST_REPORT_PORT ?? "4175");
2606
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
2607
+ throw new Error("\u7AEF\u53E3\u5FC5\u987B\u662F 1\u201365535 \u7684\u6574\u6570");
2608
+ await startWorkbench({
2609
+ repoRoot: path30.resolve(options.repo ?? process.env.TEST_REPORT_REPO ?? process.cwd()),
2610
+ port
2611
+ });
2612
+ });
2613
+ cli.command("compare", "\u8C03\u7528 core \u6BD4\u8F83\u4EFB\u52A1\u548C\u57FA\u7EBF\uFF0C\u8F93\u51FA summary").option("--repo <path>", "\u4ED3\u5E93\u8DEF\u5F84\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").option("--task-id <id>", "\u4EFB\u52A1 ID").option("--full", "\u8F93\u51FA\u5B8C\u6574\u6BD4\u8F83\u7ED3\u679C").action(async (options) => {
2614
+ if (!options.taskId) throw new Error("\u8BF7\u63D0\u4F9B --task-id");
2615
+ const result = await compareTask({
2616
+ repoRoot: path30.resolve(options.repo ?? process.cwd()),
2617
+ taskId: options.taskId
2618
+ });
2619
+ console.log(JSON.stringify(options.full ? result : result.summary, null, 2));
2620
+ });
2621
+ cli.command("compare-tasks", "\u6BD4\u8F83\u4E24\u4E2A\u4EFB\u52A1\u7684\u7528\u4F8B\u548C\u5FEB\u7167\uFF0C\u8F93\u51FA summary").option("--repo <path>", "\u4ED3\u5E93\u8DEF\u5F84\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").option("--base-task-id <id>", "\u53C2\u7167\u4EFB\u52A1 ID").option("--task-id <id>", "\u5F53\u524D\u4EFB\u52A1 ID").option("--full", "\u8F93\u51FA\u5B8C\u6574\u6BD4\u8F83\u7ED3\u679C").action(
2622
+ async (options) => {
2623
+ if (!options.baseTaskId) throw new Error("\u8BF7\u63D0\u4F9B --base-task-id");
2624
+ if (!options.taskId) throw new Error("\u8BF7\u63D0\u4F9B --task-id");
2625
+ const result = await compareTasks({
2626
+ repoRoot: path30.resolve(options.repo ?? process.cwd()),
2627
+ baseTaskId: options.baseTaskId,
2628
+ taskId: options.taskId
2629
+ });
2630
+ console.log(JSON.stringify(options.full ? result : result.summary, null, 2));
2631
+ }
2632
+ );
2633
+ cli.help();
2634
+ try {
2635
+ cli.parse(process.argv, { run: false });
2636
+ if (!cli.options.help && !cli.matchedCommand) {
2637
+ if (cli.args.length) throw new Error(`\u672A\u77E5\u547D\u4EE4\uFF1A${cli.args[0]}`);
2638
+ cli.outputHelp();
2639
+ } else {
2640
+ await cli.runMatchedCommand();
2641
+ }
2642
+ } catch (error) {
2643
+ console.error(error instanceof Error ? error.message : String(error));
2644
+ process.exitCode = 1;
2645
+ }