promote-conversation-e2e.mjs 13 KB

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