check-e2e-fixtures.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #!/usr/bin/env node
  2. /* eslint-disable max-lines */
  3. import { existsSync, readFileSync } from "node:fs";
  4. import { basename, resolve } from "node:path";
  5. const desktopDir = resolve(import.meta.dirname, "..");
  6. const upstreamFixtureRoot = resolve(desktopDir, "test/e2e/fixtures/upstream");
  7. const conversationCaseManifestRoot = resolve(
  8. desktopDir,
  9. "test/e2e/fixtures/cases/conversation-session",
  10. );
  11. const pluginCaseManifestRoot = resolve(desktopDir, "test/e2e/fixtures/cases/plugins");
  12. const commonFixturePath = resolve(upstreamFixtureRoot, "common.json");
  13. const conversationFixtureDir = resolve(upstreamFixtureRoot, "conversation-session");
  14. const pluginFixtureDir = resolve(upstreamFixtureRoot, "plugin-management");
  15. const options = parseArgs(process.argv.slice(2));
  16. if (options.help || !options.spec) {
  17. printUsage();
  18. process.exit(options.help ? 0 : 1);
  19. }
  20. const specPath = resolve(process.cwd(), options.spec);
  21. const specContract = resolveE2ESpecContract(specPath);
  22. const caseName = specContract?.caseName ?? null;
  23. const canonicalSpecPath = specContract?.canonicalSpecPath ?? specPath;
  24. const errors = [];
  25. const warnings = [];
  26. const specMarkers = existsSync(specPath)
  27. ? extractSpecE2EMarkers(readFileSync(specPath, "utf8"))
  28. : [];
  29. if (!existsSync(specPath)) {
  30. errors.push(`Spec not found: ${specPath}`);
  31. }
  32. if (!specContract) {
  33. errors.push(
  34. "Fixture check supports formal/pending conversation-session and plugin specs outside recursive globs.",
  35. );
  36. }
  37. const fixturePaths = [
  38. commonFixturePath,
  39. caseName && specContract ? resolve(specContract.fixtureDir, `${caseName}.json`) : "",
  40. ].filter(Boolean);
  41. const fixtureFiles = [];
  42. let caseManifest = null;
  43. for (const fixturePath of fixturePaths) {
  44. if (!existsSync(fixturePath)) {
  45. if (fixturePath === commonFixturePath) {
  46. warnings.push(`Common fixture is missing: ${fixturePath}`);
  47. } else {
  48. errors.push(`Case-local fixture is missing: ${fixturePath}`);
  49. }
  50. continue;
  51. }
  52. const fixtureFile = readFixtureFile(fixturePath, errors);
  53. if (fixtureFile) {
  54. fixtureFiles.push({ path: fixturePath, value: fixtureFile });
  55. }
  56. }
  57. if (caseName) {
  58. const manifestPath = resolve(specContract.manifestRoot, `${caseName}.json`);
  59. if (!existsSync(manifestPath)) {
  60. errors.push(`Case manifest is missing: ${manifestPath}`);
  61. } else {
  62. caseManifest = readCaseManifest(manifestPath, errors);
  63. if (caseManifest) {
  64. validateCaseManifest(
  65. caseManifest,
  66. {
  67. caseName,
  68. canonicalSpecPath,
  69. fixturePaths,
  70. manifestPath,
  71. },
  72. warnings,
  73. errors,
  74. );
  75. }
  76. }
  77. }
  78. validateFixtureIds(fixtureFiles, errors);
  79. for (const fixtureFile of fixtureFiles) {
  80. validateFixtureFile(fixtureFile, warnings, errors);
  81. }
  82. validateSpecMarkerCoverage(specMarkers, fixtureFiles, warnings, caseManifest);
  83. const caseFixture = fixtureFiles.find((file) => file.path !== commonFixturePath);
  84. if (caseFixture && specContract) {
  85. validateCaseFixtureIdentity(
  86. caseFixture,
  87. {
  88. canonicalSpecPath,
  89. caseName: specContract.caseName,
  90. },
  91. errors,
  92. );
  93. }
  94. if (
  95. caseFixture &&
  96. caseFixture.value.fixtures.length === 0 &&
  97. !allowsEmptyCaseLocalFixture(caseManifest)
  98. ) {
  99. errors.push(`Case-local fixture has no fixtures: ${caseFixture.path}`);
  100. }
  101. printSummary({
  102. caseName,
  103. canonicalSpecPath,
  104. errors,
  105. fixtureFiles,
  106. manifest: caseManifest,
  107. specMarkers,
  108. specPath,
  109. warnings,
  110. });
  111. process.exit(errors.length > 0 ? 1 : 0);
  112. function parseArgs(args) {
  113. const parsed = { help: false, spec: "" };
  114. for (let index = 0; index < args.length; index += 1) {
  115. const arg = args[index];
  116. if (arg === "--help" || arg === "-h") {
  117. parsed.help = true;
  118. continue;
  119. }
  120. if (arg === "--") {
  121. continue;
  122. }
  123. if (arg === "--spec") {
  124. parsed.spec = args[index + 1] ?? "";
  125. index += 1;
  126. continue;
  127. }
  128. if (arg.startsWith("--spec=")) {
  129. parsed.spec = arg.slice("--spec=".length);
  130. continue;
  131. }
  132. if (!parsed.spec) {
  133. parsed.spec = arg;
  134. }
  135. }
  136. return parsed;
  137. }
  138. function printUsage() {
  139. console.log(
  140. "Usage:\n" +
  141. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/<scenario>/<case>.test.ts\n" +
  142. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/<scenario>/manual-review/pending/<case>.test.ts\n" +
  143. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/plugins/<scenario>/<case>.test.ts\n" +
  144. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/plugins/<scenario>/manual-review/pending/<case>.test.ts\n",
  145. );
  146. }
  147. function resolveE2ESpecContract(specPath) {
  148. const normalized = specPath.replaceAll("\\", "/");
  149. const candidates = [
  150. {
  151. marker: "/test/e2e/conversation-session/",
  152. fixtureDir: conversationFixtureDir,
  153. manifestRoot: conversationCaseManifestRoot,
  154. formalDir: resolve(desktopDir, "test/e2e/conversation-session"),
  155. },
  156. {
  157. marker: "/test/e2e/plugins/",
  158. fixtureDir: pluginFixtureDir,
  159. manifestRoot: pluginCaseManifestRoot,
  160. formalDir: resolve(desktopDir, "test/e2e/plugins"),
  161. },
  162. ];
  163. for (const candidate of candidates) {
  164. const markerIndex = normalized.lastIndexOf(candidate.marker);
  165. if (markerIndex < 0) continue;
  166. const relativeSpecPath = normalized.slice(markerIndex + candidate.marker.length);
  167. const canonicalRelative = relativeSpecPath.replace(
  168. /(?:^|\/)manual-review\/pending\//u,
  169. (match) => (match.startsWith("/") ? "/" : ""),
  170. );
  171. if (
  172. canonicalRelative.includes("manual-review/") ||
  173. /[*?\[{}]/u.test(canonicalRelative) ||
  174. !canonicalRelative.endsWith(".test.ts")
  175. ) {
  176. return null;
  177. }
  178. // 候选转正只去掉 review 层级,场景目录属于 fixture 的正式身份。
  179. return {
  180. canonicalSpecPath: resolve(candidate.formalDir, canonicalRelative),
  181. caseName: basename(canonicalRelative, ".test.ts"),
  182. fixtureDir: candidate.fixtureDir,
  183. manifestRoot: candidate.manifestRoot,
  184. };
  185. }
  186. return null;
  187. }
  188. function readFixtureFile(fixturePath, nextErrors) {
  189. try {
  190. const value = JSON.parse(readFileSync(fixturePath, "utf8"));
  191. if (value?.version !== 1 || !Array.isArray(value.fixtures)) {
  192. nextErrors.push(`Invalid fixture file shape: ${fixturePath}`);
  193. return null;
  194. }
  195. return value;
  196. } catch (error) {
  197. nextErrors.push(`Failed to parse fixture JSON: ${fixturePath}; ${error.message}`);
  198. return null;
  199. }
  200. }
  201. function readCaseManifest(manifestPath, nextErrors) {
  202. try {
  203. const value = JSON.parse(readFileSync(manifestPath, "utf8"));
  204. if (value?.version !== 1 || typeof value.caseName !== "string") {
  205. nextErrors.push(`Invalid case manifest shape: ${manifestPath}`);
  206. return null;
  207. }
  208. return { path: manifestPath, value };
  209. } catch (error) {
  210. nextErrors.push(`Failed to parse case manifest JSON: ${manifestPath}; ${error.message}`);
  211. return null;
  212. }
  213. }
  214. function validateCaseManifest(
  215. manifest,
  216. { canonicalSpecPath, caseName, fixturePaths, manifestPath },
  217. nextWarnings,
  218. nextErrors,
  219. ) {
  220. const value = manifest.value;
  221. const requests = Array.isArray(value.requests) ? value.requests : [];
  222. if (value.caseName !== caseName) {
  223. nextErrors.push(
  224. `Case manifest caseName mismatch in ${manifestPath}: ${value.caseName} !== ${caseName}`,
  225. );
  226. }
  227. if (value.noProviderRequests === true && requests.length > 0) {
  228. nextErrors.push(`${manifestPath}: noProviderRequests=true requires requests to stay empty`);
  229. }
  230. if (
  231. typeof value.spec !== "string" ||
  232. !samePath(resolve(desktopDir, value.spec), canonicalSpecPath)
  233. ) {
  234. nextErrors.push(
  235. `${manifestPath}: spec must point at canonical formal target ${canonicalSpecPath}`,
  236. );
  237. }
  238. for (const providerFixture of asStringArray(value.providerFixtures)) {
  239. const resolvedProviderFixture = resolve(desktopDir, providerFixture);
  240. if (!fixturePaths.some((fixturePath) => samePath(fixturePath, resolvedProviderFixture))) {
  241. nextWarnings.push(
  242. `${manifestPath}: provider fixture is not in resolved WDIO fixture set: ${providerFixture}`,
  243. );
  244. }
  245. }
  246. for (const request of requests) {
  247. if (
  248. (request.kind === "synthetic" || request.source === "synthetic") &&
  249. typeof request.syntheticReason !== "string"
  250. ) {
  251. nextErrors.push(
  252. `${manifestPath}: synthetic request ${request.id ?? "<missing-id>"} must include syntheticReason`,
  253. );
  254. }
  255. }
  256. if (
  257. value.providerRequestPolicy !== undefined &&
  258. !["none", "external-live"].includes(value.providerRequestPolicy)
  259. ) {
  260. nextErrors.push(
  261. `${manifestPath}: providerRequestPolicy must be "none" or "external-live" when present`,
  262. );
  263. }
  264. if (
  265. value.providerRequestPolicy === "external-live" &&
  266. (typeof value.externalProviderReason !== "string" ||
  267. !value.externalProviderReason.trim() ||
  268. value.noProviderRequests === true ||
  269. requests.length > 0)
  270. ) {
  271. nextErrors.push(
  272. `${manifestPath}: external-live requires a reason, an empty replay ledger and no noProviderRequests claim`,
  273. );
  274. }
  275. if (
  276. value.providerRequestPolicy === "none" &&
  277. Array.isArray(value.requests) &&
  278. value.requests.length > 0
  279. ) {
  280. nextErrors.push(
  281. `${manifestPath}: providerRequestPolicy "none" requires an empty requests array`,
  282. );
  283. }
  284. }
  285. function validateCaseFixtureIdentity(fixtureFile, { canonicalSpecPath, caseName }, nextErrors) {
  286. const value = fixtureFile.value;
  287. if (value.caseName !== caseName) {
  288. nextErrors.push(
  289. `${fixtureFile.path}: caseName must be ${caseName}; received ${JSON.stringify(value.caseName)}`,
  290. );
  291. }
  292. if (
  293. typeof value.spec !== "string" ||
  294. !samePath(resolve(desktopDir, value.spec), canonicalSpecPath)
  295. ) {
  296. nextErrors.push(
  297. `${fixtureFile.path}: spec must point at canonical formal target ${canonicalSpecPath}`,
  298. );
  299. }
  300. }
  301. function allowsEmptyCaseLocalFixture(manifest) {
  302. const value = manifest?.value;
  303. // 真实账号专项没有回放响应,但必须明确保留真实请求语义,不能冒充纯 UI 用例。
  304. const externalLive =
  305. value?.providerRequestPolicy === "external-live" &&
  306. typeof value.externalProviderReason === "string" &&
  307. value.externalProviderReason.trim().length > 0 &&
  308. value.noProviderRequests !== true;
  309. return (
  310. (value?.providerRequestPolicy === "external-live"
  311. ? externalLive
  312. : value?.noProviderRequests === true || value?.providerRequestPolicy === "none") &&
  313. Array.isArray(value.requests) &&
  314. value.requests.length === 0
  315. );
  316. }
  317. function validateFixtureIds(fixtureFiles, nextErrors) {
  318. const seen = new Map();
  319. for (const fixtureFile of fixtureFiles) {
  320. for (const fixture of fixtureFile.value.fixtures) {
  321. if (!fixture?.id || typeof fixture.id !== "string") {
  322. nextErrors.push(`Fixture without string id in ${fixtureFile.path}`);
  323. continue;
  324. }
  325. const previous = seen.get(fixture.id);
  326. if (previous) {
  327. nextErrors.push(
  328. `Duplicate fixture id "${fixture.id}" in ${fixtureFile.path}; first seen in ${previous}`,
  329. );
  330. } else {
  331. seen.set(fixture.id, fixtureFile.path);
  332. }
  333. }
  334. }
  335. }
  336. function validateFixtureFile(fixtureFile, nextWarnings, nextErrors) {
  337. for (const fixture of fixtureFile.value.fixtures) {
  338. const prefix = `${fixture.id ?? "<missing-id>"} (${fixtureFile.path})`;
  339. if (!fixture.match || typeof fixture.match !== "object") {
  340. nextErrors.push(`${prefix}: missing match object`);
  341. continue;
  342. }
  343. if (!fixture.response || typeof fixture.response !== "object") {
  344. nextErrors.push(`${prefix}: missing response object`);
  345. }
  346. if (!fixture.match.method) {
  347. nextWarnings.push(`${prefix}: match.method is missing`);
  348. }
  349. if (!fixture.match.pathIncludes) {
  350. nextWarnings.push(`${prefix}: match.pathIncludes is missing`);
  351. }
  352. const matchTexts = [
  353. ...asStringArray(fixture.match.bodyIncludes),
  354. ...asStringArray(fixture.match.lastUserMessageIncludes),
  355. ];
  356. if (matchTexts.length === 0) {
  357. nextWarnings.push(`${prefix}: matcher has no bodyIncludes or lastUserMessageIncludes`);
  358. } else if (!matchTexts.some((text) => text.includes("E2E_"))) {
  359. nextWarnings.push(`${prefix}: matcher has no E2E marker`);
  360. }
  361. const metadata = fixture.metadata ?? {};
  362. if (
  363. (metadata.kind === "synthetic" || metadata.source === "synthetic") &&
  364. typeof metadata.syntheticReason !== "string"
  365. ) {
  366. nextErrors.push(`${prefix}: synthetic fixture must include metadata.syntheticReason`);
  367. }
  368. }
  369. }
  370. function validateSpecMarkerCoverage(specMarkers, fixtureFiles, nextWarnings, manifest) {
  371. if (allowsEmptyCaseLocalFixture(manifest)) {
  372. return;
  373. }
  374. const matcherTexts = fixtureFiles.flatMap((fixtureFile) =>
  375. fixtureFile.value.fixtures.flatMap((fixture) => [
  376. ...asStringArray(fixture.match?.bodyIncludes),
  377. ...asStringArray(fixture.match?.lastUserMessageIncludes),
  378. ]),
  379. );
  380. for (const marker of specMarkers) {
  381. if (!matcherTexts.some((text) => text.includes(marker))) {
  382. nextWarnings.push(`Spec marker is not covered by fixture matchers: ${marker}`);
  383. }
  384. }
  385. }
  386. function extractSpecE2EMarkers(text) {
  387. const ignoredMarkers = new Set([
  388. "E2E_READONLY_TOOL_FILE_CONTENT",
  389. "E2E_READONLY_TOOL_FILE_PATH",
  390. "E2E_REPLY_TOKEN",
  391. ]);
  392. return (
  393. [
  394. ...new Set(
  395. (text.match(/\bE2E_[A-Z0-9_]+\b/g) ?? []).map((marker) => marker.replace(/_+$/, "")),
  396. ),
  397. ]
  398. // 修复:E2E_PROVIDER_* 是上游供应商配置的环境变量名,不是用例标记;曾被误报为未覆盖的 marker。
  399. .filter((marker) => !ignoredMarkers.has(marker) && !marker.startsWith("E2E_PROVIDER_"))
  400. .sort()
  401. );
  402. }
  403. function asStringArray(value) {
  404. return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
  405. }
  406. function samePath(left, right) {
  407. return resolve(left) === resolve(right);
  408. }
  409. function printSummary({
  410. caseName,
  411. canonicalSpecPath,
  412. errors,
  413. fixtureFiles,
  414. manifest,
  415. specMarkers,
  416. specPath,
  417. warnings,
  418. }) {
  419. console.log(`Spec: ${specPath}`);
  420. console.log(`Canonical formal spec: ${canonicalSpecPath}`);
  421. console.log(`Case: ${caseName ?? "(unresolved)"}`);
  422. console.log(`Manifest: ${manifest?.path ?? "(missing)"}`);
  423. console.log(`Spec markers: ${specMarkers.length > 0 ? specMarkers.join(", ") : "(none)"}`);
  424. console.log("Fixtures:");
  425. for (const fixtureFile of fixtureFiles) {
  426. console.log(`- ${fixtureFile.path} (${fixtureFile.value.fixtures.length} fixtures)`);
  427. }
  428. if (warnings.length > 0) {
  429. console.log("\nWarnings:");
  430. for (const warning of warnings) console.log(`- ${warning}`);
  431. }
  432. if (errors.length > 0) {
  433. console.log("\nErrors:");
  434. for (const error of errors) console.log(`- ${error}`);
  435. } else {
  436. console.log("\nFixture check passed.");
  437. }
  438. }