promote-conversation-e2e.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #!/usr/bin/env node
  2. import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
  3. import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
  4. import {
  5. createPromotionCaseManifest,
  6. createPromotionProviderFixture,
  7. runPromotionAuditTransaction,
  8. runPromotionCoverageAudit,
  9. } from "./lib/e2e-promotion-audit-transaction.mjs";
  10. import { rewriteFormalSpecImports } from "./lib/e2e-promotion-spec-imports.mjs";
  11. const desktopDir = resolve(import.meta.dirname, "..");
  12. const repoRoot = resolve(desktopDir, "../..");
  13. const conversationDir = resolve(desktopDir, "test/e2e/conversation-session");
  14. const pendingDir = resolve(conversationDir, "manual-review/pending");
  15. const providerFixtureDir = resolve(desktopDir, "test/e2e/fixtures/upstream/conversation-session");
  16. const caseManifestDir = resolve(desktopDir, "test/e2e/fixtures/cases/conversation-session");
  17. const coverageMatrixPath = resolve(
  18. repoRoot,
  19. "docs/testing/conversation-session-e2e-coverage-matrix.md",
  20. );
  21. const coverageAuditPath = resolve(repoRoot, "scripts/audit-conversation-session-case-coverage.mjs");
  22. const options = parseArgs(process.argv.slice(2));
  23. if (options.help || !options.spec) {
  24. printUsage();
  25. process.exit(options.help ? 0 : 1);
  26. }
  27. const result = await promote(options);
  28. printResult(result);
  29. process.exit(result.errors.length > 0 ? 1 : 0);
  30. function parseArgs(args) {
  31. const parsed = {
  32. apply: false,
  33. force: false,
  34. help: false,
  35. reviewed: false,
  36. spec: "",
  37. };
  38. for (let index = 0; index < args.length; index += 1) {
  39. const arg = args[index];
  40. if (arg === "--" || arg.trim().length === 0) {
  41. continue;
  42. }
  43. if (arg === "--help" || arg === "-h") {
  44. parsed.help = true;
  45. continue;
  46. }
  47. if (arg === "--apply") {
  48. parsed.apply = true;
  49. continue;
  50. }
  51. if (arg === "--force") {
  52. parsed.force = true;
  53. continue;
  54. }
  55. if (arg === "--reviewed") {
  56. parsed.reviewed = true;
  57. continue;
  58. }
  59. if (arg === "--spec") {
  60. parsed.spec = args[index + 1] ?? "";
  61. index += 1;
  62. continue;
  63. }
  64. if (arg.startsWith("--spec=")) {
  65. parsed.spec = arg.slice("--spec=".length);
  66. continue;
  67. }
  68. if (!parsed.spec) {
  69. parsed.spec = arg;
  70. }
  71. }
  72. return parsed;
  73. }
  74. function printUsage() {
  75. console.log(`Usage:
  76. pnpm --filter @zcode/desktop e2e:promote -- --spec ./test/e2e/conversation-session/manual-review/pending/<case>.test.ts --reviewed --apply
  77. Options:
  78. --apply Write changes. Without this flag the tool only prints a dry run.
  79. --reviewed Confirm the pending case has already passed human review.
  80. --force Overwrite generated fixture/manifest files if they already exist.
  81. `);
  82. }
  83. async function promote({ apply, force, reviewed, spec }) {
  84. const errors = [];
  85. const warnings = [];
  86. const actions = [];
  87. let audit = null;
  88. const sourcePath = resolve(process.cwd(), spec);
  89. const relSourceFromPending = relative(pendingDir, sourcePath);
  90. if (relSourceFromPending.startsWith("..") || isAbsolute(relSourceFromPending)) {
  91. errors.push(`Spec must be under manual-review/pending: ${relative(repoRoot, sourcePath)}`);
  92. }
  93. if (!sourcePath.endsWith(".test.ts")) {
  94. errors.push(`Spec must be a .test.ts file: ${sourcePath}`);
  95. }
  96. if (!existsSync(sourcePath)) {
  97. errors.push(`Spec not found: ${sourcePath}`);
  98. }
  99. if (apply && !reviewed) {
  100. errors.push("Use --reviewed when applying promotion after human review.");
  101. }
  102. const fileName = basename(sourcePath);
  103. const caseName = fileName.replace(/\.test\.ts$/, "");
  104. const targetPath = resolve(conversationDir, fileName);
  105. const providerFixturePath = resolve(providerFixtureDir, `${caseName}.json`);
  106. const caseManifestPath = resolve(caseManifestDir, `${caseName}.json`);
  107. const specRelFromDesktop = `./test/e2e/conversation-session/${fileName}`;
  108. const pendingRelFromRepo = `packages/desktop/test/e2e/conversation-session/manual-review/pending/${fileName}`;
  109. const targetRelFromRepo = `packages/desktop/test/e2e/conversation-session/${fileName}`;
  110. validateExistingFixtureIdentity(
  111. {
  112. caseName,
  113. filePath: providerFixturePath,
  114. specRelFromDesktop,
  115. },
  116. errors,
  117. );
  118. validateExistingFixtureIdentity(
  119. {
  120. caseName,
  121. filePath: caseManifestPath,
  122. specRelFromDesktop,
  123. },
  124. errors,
  125. );
  126. if (existsSync(targetPath)) {
  127. errors.push(`Target spec already exists: ${targetPath}`);
  128. }
  129. const markerSummary = existsSync(sourcePath)
  130. ? extractE2EMarkers(readFileSync(sourcePath, "utf8"))
  131. : [];
  132. if (errors.length === 0) {
  133. actions.push(
  134. `Move spec: ${relative(repoRoot, sourcePath)} -> ${relative(repoRoot, targetPath)}`,
  135. );
  136. actions.push(
  137. "Rewrite common pending helper, page, and file fixture paths for the formal spec location.",
  138. );
  139. actions.push(`Create provider fixture scaffold: ${relative(repoRoot, providerFixturePath)}`);
  140. actions.push(`Create case manifest scaffold: ${relative(repoRoot, caseManifestPath)}`);
  141. actions.push(`Update coverage matrix path: ${pendingRelFromRepo} -> ${targetRelFromRepo}`);
  142. actions.push(
  143. "Run pnpm audit:conversation-session-coverage and keep the promotion only if it passes.",
  144. );
  145. }
  146. if (!reviewed) {
  147. warnings.push(
  148. "This dry run did not include --reviewed; do not apply until human review is complete.",
  149. );
  150. }
  151. if (markerSummary.length === 0) {
  152. warnings.push("No E2E_* marker found in spec; fixture matching may be too broad.");
  153. }
  154. if (apply && errors.length === 0) {
  155. try {
  156. const transaction = await runPromotionAuditTransaction({
  157. affectedPaths: [
  158. sourcePath,
  159. targetPath,
  160. providerFixturePath,
  161. caseManifestPath,
  162. coverageMatrixPath,
  163. ],
  164. applyChanges: () => {
  165. mkdirSync(dirname(targetPath), { recursive: true });
  166. renameSync(sourcePath, targetPath);
  167. rewriteFormalSpecImports(targetPath);
  168. writeJsonIfMissing(
  169. providerFixturePath,
  170. createPromotionProviderFixture(caseName, specRelFromDesktop),
  171. { force, warnings },
  172. );
  173. writeJsonIfMissing(
  174. caseManifestPath,
  175. createPromotionCaseManifest(caseName, specRelFromDesktop),
  176. { force, warnings },
  177. );
  178. updateCoverageMatrix({
  179. matrixPath: coverageMatrixPath,
  180. oldPath: pendingRelFromRepo,
  181. newPath: targetRelFromRepo,
  182. warnings,
  183. });
  184. },
  185. runAudit: () => runPromotionCoverageAudit({ auditPath: coverageAuditPath, repoRoot }),
  186. });
  187. audit = transaction.audit;
  188. if (!transaction.committed) {
  189. errors.push(
  190. "pnpm audit:conversation-session-coverage failed; promotion was rejected and all file changes were rolled back.",
  191. );
  192. }
  193. } catch (error) {
  194. errors.push(
  195. `Promotion audit transaction failed; file changes were rolled back: ${error instanceof Error ? error.message : String(error)}`,
  196. );
  197. }
  198. }
  199. return {
  200. actions,
  201. apply,
  202. audit,
  203. caseManifestPath,
  204. caseName,
  205. errors,
  206. markerSummary,
  207. providerFixturePath,
  208. specPath: apply && errors.length === 0 ? targetPath : sourcePath,
  209. targetPath,
  210. warnings,
  211. };
  212. }
  213. function validateExistingFixtureIdentity({ caseName, filePath, specRelFromDesktop }, errors) {
  214. if (!existsSync(filePath)) {
  215. return;
  216. }
  217. let value;
  218. try {
  219. value = JSON.parse(readFileSync(filePath, "utf8"));
  220. } catch (error) {
  221. errors.push(`Invalid fixture JSON: ${relative(repoRoot, filePath)}; ${error.message}`);
  222. return;
  223. }
  224. if (value?.caseName !== caseName) {
  225. errors.push(
  226. `${relative(repoRoot, filePath)}: caseName must be ${caseName}; received ${JSON.stringify(value?.caseName)}`,
  227. );
  228. }
  229. // 修复原因:promotion 会保留已有 fixture 内容;若这里接受 pending 物理路径,移动
  230. // spec 后 manifest 会立刻违反 formal admission,形成“转正成功但门禁不可运行”的半状态。
  231. if (
  232. typeof value?.spec !== "string" ||
  233. resolve(desktopDir, value.spec) !== resolve(desktopDir, specRelFromDesktop)
  234. ) {
  235. errors.push(
  236. `${relative(repoRoot, filePath)}: spec must point at canonical formal target ${specRelFromDesktop}`,
  237. );
  238. }
  239. }
  240. function writeJsonIfMissing(filePath, value, { force, warnings }) {
  241. if (existsSync(filePath) && !force) {
  242. warnings.push(`Skipped existing file: ${relative(repoRoot, filePath)}`);
  243. return;
  244. }
  245. mkdirSync(dirname(filePath), { recursive: true });
  246. writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
  247. }
  248. function updateCoverageMatrix({ matrixPath, oldPath, newPath, warnings }) {
  249. if (!existsSync(matrixPath)) {
  250. warnings.push(`Coverage matrix not found: ${relative(repoRoot, matrixPath)}`);
  251. return;
  252. }
  253. const original = readFileSync(matrixPath, "utf8");
  254. if (!original.includes(oldPath)) {
  255. if (!original.includes(newPath)) {
  256. warnings.push(`Coverage matrix does not reference pending or formal path for ${newPath}.`);
  257. }
  258. return;
  259. }
  260. writeFileSync(matrixPath, original.replaceAll(oldPath, newPath), "utf8");
  261. }
  262. function extractE2EMarkers(text) {
  263. const ignoredMarkers = new Set([
  264. "E2E_READONLY_TOOL_FILE_CONTENT",
  265. "E2E_READONLY_TOOL_FILE_PATH",
  266. "E2E_REPLY_TOKEN",
  267. ]);
  268. return (
  269. [
  270. ...new Set(
  271. (text.match(/\bE2E_[A-Z0-9_]+\b/g) ?? []).map((marker) => marker.replace(/_+$/, "")),
  272. ),
  273. ]
  274. // 修复:E2E_PROVIDER_* 是上游供应商配置的环境变量名,不是用例标记;曾被误报为未覆盖的 marker。
  275. .filter((marker) => !ignoredMarkers.has(marker) && !marker.startsWith("E2E_PROVIDER_"))
  276. .sort()
  277. );
  278. }
  279. function printResult(result) {
  280. console.log(`${result.apply ? "Apply" : "Dry run"} conversation E2E promotion`);
  281. console.log(`Case: ${result.caseName}`);
  282. console.log(`Spec: ${relative(repoRoot, result.specPath)}`);
  283. console.log(`Target: ${relative(repoRoot, result.targetPath)}`);
  284. console.log(`Provider fixture: ${relative(repoRoot, result.providerFixturePath)}`);
  285. console.log(`Case manifest: ${relative(repoRoot, result.caseManifestPath)}`);
  286. if (result.markerSummary.length > 0) {
  287. console.log(`Markers: ${result.markerSummary.join(", ")}`);
  288. }
  289. if (result.actions.length > 0) {
  290. console.log("\nActions:");
  291. for (const action of result.actions) {
  292. console.log(`- ${action}`);
  293. }
  294. }
  295. if (result.warnings.length > 0) {
  296. console.log("\nWarnings:");
  297. for (const warning of result.warnings) {
  298. console.log(`- ${warning}`);
  299. }
  300. }
  301. if (result.audit) {
  302. console.log("\nAudit:");
  303. console.log(`- Command: ${result.audit.command}`);
  304. console.log(`- Result: ${result.audit.exitCode === 0 ? "passed" : "failed"}`);
  305. if (result.audit.stdout.trim().length > 0) {
  306. console.log(result.audit.stdout.trimEnd());
  307. }
  308. if (result.audit.stderr.trim().length > 0) {
  309. console.error(result.audit.stderr.trimEnd());
  310. }
  311. }
  312. if (result.errors.length > 0) {
  313. console.log("\nErrors:");
  314. for (const error of result.errors) {
  315. console.log(`- ${error}`);
  316. }
  317. return;
  318. }
  319. const specArg = `./test/e2e/conversation-session/${result.caseName}.test.ts`;
  320. if (!result.apply) {
  321. const pendingSpecArg = `./${relative(desktopDir, result.specPath).replaceAll("\\", "/")}`;
  322. console.log("\nNext:");
  323. console.log(
  324. `- Complete the canonical fixtures and requests in ${relative(repoRoot, result.providerFixturePath)} and ${relative(repoRoot, result.caseManifestPath)} while the spec is still pending.`,
  325. );
  326. console.log(`- pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ${pendingSpecArg}`);
  327. console.log(
  328. `- pnpm --filter @zcode/desktop e2e:promote -- --spec ${pendingSpecArg} --reviewed --apply`,
  329. );
  330. console.log(
  331. "- The apply command keeps the formal promotion only after pnpm audit:conversation-session-coverage passes.",
  332. );
  333. return;
  334. }
  335. const caseFixture = `packages/desktop/test/e2e/fixtures/upstream/conversation-session/${result.caseName}.json`;
  336. console.log("\nNext:");
  337. console.log(`- pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ${specArg}`);
  338. console.log(
  339. `- E2E_PROVIDER_REPLAY_FIXTURE_PATH=packages/desktop/test/e2e/fixtures/upstream/common.json,${caseFixture} pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec '${specArg}'`,
  340. );
  341. console.log(`- pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec '${specArg}'`);
  342. console.log(`- E2E_SPEC=${specArg} pnpm run test:e2e:container`);
  343. console.log(
  344. `- pnpm --filter @zcode/desktop e2e:docker:admit -- --spec ${specArg} --verified --artifact packages/desktop/.e2e-artifacts/<run-id> --apply`,
  345. );
  346. }