check-e2e-fixtures.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #!/usr/bin/env node
  2. /* eslint-disable max-lines */
  3. import { existsSync, readFileSync } from "node:fs";
  4. import { 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/<case>.test.ts\n" +
  142. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/manual-review/pending/<case>.test.ts\n" +
  143. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/plugins/<case>.test.ts\n" +
  144. " pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/plugins/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 isPending = relativeSpecPath.startsWith("manual-review/pending/");
  168. const fileName = isPending
  169. ? relativeSpecPath.slice("manual-review/pending/".length)
  170. : relativeSpecPath;
  171. if (fileName.includes("/") || fileName.includes("*") || !fileName.endsWith(".test.ts")) {
  172. return null;
  173. }
  174. // pending fixture contracts always target the formal direct-root path
  175. return {
  176. canonicalSpecPath: resolve(candidate.formalDir, fileName),
  177. caseName: fileName.slice(0, -".test.ts".length),
  178. fixtureDir: candidate.fixtureDir,
  179. manifestRoot: candidate.manifestRoot,
  180. };
  181. }
  182. return null;
  183. }
  184. function readFixtureFile(fixturePath, nextErrors) {
  185. try {
  186. const value = JSON.parse(readFileSync(fixturePath, "utf8"));
  187. if (value?.version !== 1 || !Array.isArray(value.fixtures)) {
  188. nextErrors.push(`Invalid fixture file shape: ${fixturePath}`);
  189. return null;
  190. }
  191. return value;
  192. } catch (error) {
  193. nextErrors.push(`Failed to parse fixture JSON: ${fixturePath}; ${error.message}`);
  194. return null;
  195. }
  196. }
  197. function readCaseManifest(manifestPath, nextErrors) {
  198. try {
  199. const value = JSON.parse(readFileSync(manifestPath, "utf8"));
  200. if (value?.version !== 1 || typeof value.caseName !== "string") {
  201. nextErrors.push(`Invalid case manifest shape: ${manifestPath}`);
  202. return null;
  203. }
  204. return { path: manifestPath, value };
  205. } catch (error) {
  206. nextErrors.push(`Failed to parse case manifest JSON: ${manifestPath}; ${error.message}`);
  207. return null;
  208. }
  209. }
  210. function validateCaseManifest(
  211. manifest,
  212. { canonicalSpecPath, caseName, fixturePaths, manifestPath },
  213. nextWarnings,
  214. nextErrors,
  215. ) {
  216. const value = manifest.value;
  217. const requests = Array.isArray(value.requests) ? value.requests : [];
  218. if (value.caseName !== caseName) {
  219. nextErrors.push(
  220. `Case manifest caseName mismatch in ${manifestPath}: ${value.caseName} !== ${caseName}`,
  221. );
  222. }
  223. if (value.noProviderRequests === true && requests.length > 0) {
  224. nextErrors.push(`${manifestPath}: noProviderRequests=true requires requests to stay empty`);
  225. }
  226. if (
  227. typeof value.spec !== "string" ||
  228. !samePath(resolve(desktopDir, value.spec), canonicalSpecPath)
  229. ) {
  230. nextErrors.push(
  231. `${manifestPath}: spec must point at canonical formal target ${canonicalSpecPath}`,
  232. );
  233. }
  234. for (const providerFixture of asStringArray(value.providerFixtures)) {
  235. const resolvedProviderFixture = resolve(desktopDir, providerFixture);
  236. if (!fixturePaths.some((fixturePath) => samePath(fixturePath, resolvedProviderFixture))) {
  237. nextWarnings.push(
  238. `${manifestPath}: provider fixture is not in resolved WDIO fixture set: ${providerFixture}`,
  239. );
  240. }
  241. }
  242. for (const request of requests) {
  243. if (
  244. (request.kind === "synthetic" || request.source === "synthetic") &&
  245. typeof request.syntheticReason !== "string"
  246. ) {
  247. nextErrors.push(
  248. `${manifestPath}: synthetic request ${request.id ?? "<missing-id>"} must include syntheticReason`,
  249. );
  250. }
  251. }
  252. if (value.providerRequestPolicy !== undefined && value.providerRequestPolicy !== "none") {
  253. nextErrors.push(`${manifestPath}: providerRequestPolicy must be "none" when present`);
  254. }
  255. if (
  256. value.providerRequestPolicy === "none" &&
  257. Array.isArray(value.requests) &&
  258. value.requests.length > 0
  259. ) {
  260. nextErrors.push(
  261. `${manifestPath}: providerRequestPolicy "none" requires an empty requests array`,
  262. );
  263. }
  264. }
  265. function validateCaseFixtureIdentity(fixtureFile, { canonicalSpecPath, caseName }, nextErrors) {
  266. const value = fixtureFile.value;
  267. if (value.caseName !== caseName) {
  268. nextErrors.push(
  269. `${fixtureFile.path}: caseName must be ${caseName}; received ${JSON.stringify(value.caseName)}`,
  270. );
  271. }
  272. if (
  273. typeof value.spec !== "string" ||
  274. !samePath(resolve(desktopDir, value.spec), canonicalSpecPath)
  275. ) {
  276. nextErrors.push(
  277. `${fixtureFile.path}: spec must point at canonical formal target ${canonicalSpecPath}`,
  278. );
  279. }
  280. }
  281. function allowsEmptyCaseLocalFixture(manifest) {
  282. const value = manifest?.value;
  283. // pure UI cases must opt in via empty provider contract
  284. return (
  285. (value?.noProviderRequests === true || value?.providerRequestPolicy === "none") &&
  286. Array.isArray(value.requests) &&
  287. value.requests.length === 0
  288. );
  289. }
  290. function validateFixtureIds(fixtureFiles, nextErrors) {
  291. const seen = new Map();
  292. for (const fixtureFile of fixtureFiles) {
  293. for (const fixture of fixtureFile.value.fixtures) {
  294. if (!fixture?.id || typeof fixture.id !== "string") {
  295. nextErrors.push(`Fixture without string id in ${fixtureFile.path}`);
  296. continue;
  297. }
  298. const previous = seen.get(fixture.id);
  299. if (previous) {
  300. nextErrors.push(
  301. `Duplicate fixture id "${fixture.id}" in ${fixtureFile.path}; first seen in ${previous}`,
  302. );
  303. } else {
  304. seen.set(fixture.id, fixtureFile.path);
  305. }
  306. }
  307. }
  308. }
  309. function validateFixtureFile(fixtureFile, nextWarnings, nextErrors) {
  310. for (const fixture of fixtureFile.value.fixtures) {
  311. const prefix = `${fixture.id ?? "<missing-id>"} (${fixtureFile.path})`;
  312. if (!fixture.match || typeof fixture.match !== "object") {
  313. nextErrors.push(`${prefix}: missing match object`);
  314. continue;
  315. }
  316. if (!fixture.response || typeof fixture.response !== "object") {
  317. nextErrors.push(`${prefix}: missing response object`);
  318. }
  319. if (!fixture.match.method) {
  320. nextWarnings.push(`${prefix}: match.method is missing`);
  321. }
  322. if (!fixture.match.pathIncludes) {
  323. nextWarnings.push(`${prefix}: match.pathIncludes is missing`);
  324. }
  325. const matchTexts = [
  326. ...asStringArray(fixture.match.bodyIncludes),
  327. ...asStringArray(fixture.match.lastUserMessageIncludes),
  328. ];
  329. if (matchTexts.length === 0) {
  330. nextWarnings.push(`${prefix}: matcher has no bodyIncludes or lastUserMessageIncludes`);
  331. } else if (!matchTexts.some((text) => text.includes("E2E_"))) {
  332. nextWarnings.push(`${prefix}: matcher has no E2E marker`);
  333. }
  334. const metadata = fixture.metadata ?? {};
  335. if (
  336. (metadata.kind === "synthetic" || metadata.source === "synthetic") &&
  337. typeof metadata.syntheticReason !== "string"
  338. ) {
  339. nextErrors.push(`${prefix}: synthetic fixture must include metadata.syntheticReason`);
  340. }
  341. }
  342. }
  343. function validateSpecMarkerCoverage(specMarkers, fixtureFiles, nextWarnings, manifest) {
  344. if (allowsEmptyCaseLocalFixture(manifest)) {
  345. return;
  346. }
  347. const matcherTexts = fixtureFiles.flatMap((fixtureFile) =>
  348. fixtureFile.value.fixtures.flatMap((fixture) => [
  349. ...asStringArray(fixture.match?.bodyIncludes),
  350. ...asStringArray(fixture.match?.lastUserMessageIncludes),
  351. ]),
  352. );
  353. for (const marker of specMarkers) {
  354. if (!matcherTexts.some((text) => text.includes(marker))) {
  355. nextWarnings.push(`Spec marker is not covered by fixture matchers: ${marker}`);
  356. }
  357. }
  358. }
  359. function extractSpecE2EMarkers(text) {
  360. const ignoredMarkers = new Set([
  361. "E2E_READONLY_TOOL_FILE_CONTENT",
  362. "E2E_READONLY_TOOL_FILE_PATH",
  363. "E2E_REPLY_TOKEN",
  364. ]);
  365. return (
  366. [
  367. ...new Set(
  368. (text.match(/\bE2E_[A-Z0-9_]+\b/g) ?? []).map((marker) => marker.replace(/_+$/, "")),
  369. ),
  370. ]
  371. // 修复:E2E_PROVIDER_* 是上游供应商配置的环境变量名,不是用例标记;曾被误报为未覆盖的 marker。
  372. .filter((marker) => !ignoredMarkers.has(marker) && !marker.startsWith("E2E_PROVIDER_"))
  373. .sort()
  374. );
  375. }
  376. function asStringArray(value) {
  377. return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
  378. }
  379. function samePath(left, right) {
  380. return resolve(left) === resolve(right);
  381. }
  382. function printSummary({
  383. caseName,
  384. canonicalSpecPath,
  385. errors,
  386. fixtureFiles,
  387. manifest,
  388. specMarkers,
  389. specPath,
  390. warnings,
  391. }) {
  392. console.log(`Spec: ${specPath}`);
  393. console.log(`Canonical formal spec: ${canonicalSpecPath}`);
  394. console.log(`Case: ${caseName ?? "(unresolved)"}`);
  395. console.log(`Manifest: ${manifest?.path ?? "(missing)"}`);
  396. console.log(`Spec markers: ${specMarkers.length > 0 ? specMarkers.join(", ") : "(none)"}`);
  397. console.log("Fixtures:");
  398. for (const fixtureFile of fixtureFiles) {
  399. console.log(`- ${fixtureFile.path} (${fixtureFile.value.fixtures.length} fixtures)`);
  400. }
  401. if (warnings.length > 0) {
  402. console.log("\nWarnings:");
  403. for (const warning of warnings) console.log(`- ${warning}`);
  404. }
  405. if (errors.length > 0) {
  406. console.log("\nErrors:");
  407. for (const error of errors) console.log(`- ${error}`);
  408. } else {
  409. console.log("\nFixture check passed.");
  410. }
  411. }