conversation-session-formal-admission.mjs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import ts from "typescript";
  4. import { validateFormalAdmissionManifest } from "./conversation-session-formal-admission-contract.mjs";
  5. import {
  6. diagnostic,
  7. isRecord,
  8. readJson,
  9. toRepoPath,
  10. } from "./conversation-session-formal-admission-utils.mjs";
  11. const FORMAL_DIRECTORY = "packages/desktop/test/e2e/conversation-session";
  12. const MANIFEST_DIRECTORY = "packages/desktop/test/e2e/fixtures/cases/conversation-session";
  13. const PROVIDER_FIXTURE_DIRECTORY =
  14. "packages/desktop/test/e2e/fixtures/upstream/conversation-session";
  15. export async function inspectConversationSessionFormalAdmission(repoRoot) {
  16. const root = resolve(repoRoot);
  17. const paths = await listSpecsRecursively(resolve(root, FORMAL_DIRECTORY));
  18. const formalPaths = paths.filter((path) => !toRepoPath(root, path).includes("/manual-review/"));
  19. const pendingPaths = paths.filter((path) => toRepoPath(root, path).includes("/manual-review/"));
  20. const formal = await Promise.all(
  21. formalPaths.map((specPath) => inspectFormalSpec(root, specPath)),
  22. );
  23. const pending = await Promise.all(
  24. pendingPaths.map((specPath) => inspectPendingSpec(root, specPath)),
  25. );
  26. const admitted = formal
  27. .filter((item) => item.reasons.length === 0)
  28. .map(({ caseName, specPath }) => ({ caseName, specPath }));
  29. const rejected = formal.filter((item) => item.reasons.length > 0);
  30. const legacyHarnessFormal = formal.filter((item) => item.legacyHarness.length > 0).length;
  31. const legacyHarnessPending = pending.filter((item) => item.legacyHarness.length > 0).length;
  32. return {
  33. counts: {
  34. formalAdmitted: admitted.length,
  35. formalRejected: rejected.length,
  36. legacyHarness: legacyHarnessFormal + legacyHarnessPending,
  37. legacyHarnessFormal,
  38. legacyHarnessPending,
  39. missingFixture: rejected.filter((item) =>
  40. item.reasons.some((reason) => reason.code === "MISSING_CASE_FIXTURE"),
  41. ).length,
  42. missingManifest: rejected.filter((item) =>
  43. item.reasons.some((reason) => reason.code === "MISSING_CASE_MANIFEST"),
  44. ).length,
  45. pending: pending.length,
  46. pendingFixtureRejected: pending.filter((item) => item.reasons.length > 0).length,
  47. },
  48. formal: { admitted, rejected },
  49. pending,
  50. };
  51. }
  52. async function inspectPendingSpec(root, absoluteSpecPath) {
  53. const specPath = toRepoPath(root, absoluteSpecPath);
  54. const fileName = specPath.split("/").at(-1);
  55. const caseName = fileName.replace(/\.test\.ts$/, "");
  56. const canonicalSpecPath = specPath.replace("/manual-review/pending/", "/");
  57. const canonicalAbsoluteSpecPath = resolve(root, canonicalSpecPath);
  58. const manifestPath = resolve(root, MANIFEST_DIRECTORY, `${caseName}.json`);
  59. const providerFixturePath = resolve(root, PROVIDER_FIXTURE_DIRECTORY, `${caseName}.json`);
  60. const [source, manifestResult, providerFixtureResult] = await Promise.all([
  61. readFile(absoluteSpecPath, "utf8"),
  62. readJson(manifestPath),
  63. readJson(providerFixturePath),
  64. ]);
  65. const reasons = [];
  66. // 修复原因:pending 文件仍可能复用已录制 fixture,但这些 JSON 属于未来 formal
  67. // admission 合同;统一校验 保留场景目录的 canonical target,避免把当前路径和转正目标混用。
  68. inspectPendingArtifactIdentity({
  69. absoluteSpecPath: canonicalAbsoluteSpecPath,
  70. artifactLabel: "case manifest",
  71. artifactPath: manifestPath,
  72. artifactResult: manifestResult,
  73. caseName,
  74. reasons,
  75. root,
  76. specPath,
  77. });
  78. inspectPendingArtifactIdentity({
  79. absoluteSpecPath: canonicalAbsoluteSpecPath,
  80. artifactLabel: "case fixture",
  81. artifactPath: providerFixturePath,
  82. artifactResult: providerFixtureResult,
  83. caseName,
  84. reasons,
  85. root,
  86. specPath,
  87. });
  88. return {
  89. canonicalSpecPath,
  90. caseName,
  91. legacyHarness: inspectLegacyHarness(source),
  92. reasons,
  93. specPath,
  94. };
  95. }
  96. function inspectPendingArtifactIdentity({
  97. absoluteSpecPath,
  98. artifactLabel,
  99. artifactPath,
  100. artifactResult,
  101. caseName,
  102. reasons,
  103. root,
  104. specPath,
  105. }) {
  106. if (artifactResult.missing) {
  107. return;
  108. }
  109. const subjectPath = toRepoPath(root, artifactPath);
  110. if (artifactResult.error) {
  111. reasons.push(
  112. diagnostic({
  113. code: "INVALID_PENDING_FIXTURE_METADATA_JSON",
  114. message: `${artifactLabel} is not valid JSON: ${artifactResult.error.message}`,
  115. specPath,
  116. subjectPath,
  117. }),
  118. );
  119. return;
  120. }
  121. const value = artifactResult.value;
  122. if (!isRecord(value)) {
  123. reasons.push(
  124. diagnostic({
  125. code: "INVALID_PENDING_FIXTURE_METADATA_SHAPE",
  126. message: `${artifactLabel} must be a JSON object`,
  127. specPath,
  128. subjectPath,
  129. }),
  130. );
  131. return;
  132. }
  133. if (value.caseName !== caseName) {
  134. reasons.push(
  135. diagnostic({
  136. code: "PENDING_FIXTURE_CASE_NAME_MISMATCH",
  137. message: `${artifactLabel} caseName must be ${caseName}; received ${JSON.stringify(value.caseName)}`,
  138. specPath,
  139. subjectPath,
  140. }),
  141. );
  142. }
  143. if (
  144. typeof value.spec !== "string" ||
  145. resolve(root, "packages/desktop", value.spec) !== absoluteSpecPath
  146. ) {
  147. reasons.push(
  148. diagnostic({
  149. code: "PENDING_FIXTURE_FORMAL_TARGET_MISMATCH",
  150. message: `${artifactLabel} spec must resolve to ${toRepoPath(root, absoluteSpecPath)}; received ${JSON.stringify(value.spec)}`,
  151. specPath,
  152. subjectPath,
  153. }),
  154. );
  155. }
  156. }
  157. async function inspectFormalSpec(root, absoluteSpecPath) {
  158. const specPath = toRepoPath(root, absoluteSpecPath);
  159. const caseName = specPath
  160. .split("/")
  161. .at(-1)
  162. .replace(/\.test\.ts$/, "");
  163. const reasons = [];
  164. const source = await readFile(absoluteSpecPath, "utf8");
  165. const legacyHarness = inspectLegacyHarness(source);
  166. for (const code of legacyHarness) {
  167. reasons.push(
  168. diagnostic({
  169. code,
  170. message:
  171. code === "LEGACY_HELPER_IMPORT"
  172. ? "formal spec imports the exact legacy helpers/conversation-session.js module"
  173. : "formal spec calls prepareConversationE2E",
  174. specPath,
  175. subjectPath: specPath,
  176. }),
  177. );
  178. }
  179. const manifestPath = resolve(root, MANIFEST_DIRECTORY, `${caseName}.json`);
  180. const caseFixturePath = resolve(root, PROVIDER_FIXTURE_DIRECTORY, `${caseName}.json`);
  181. const manifestResult = await readJson(manifestPath);
  182. const caseFixtureResult = await readJson(caseFixturePath);
  183. if (manifestResult.missing) {
  184. reasons.push(
  185. diagnostic({
  186. code: "MISSING_CASE_MANIFEST",
  187. message: "case manifest is missing",
  188. specPath,
  189. subjectPath: toRepoPath(root, manifestPath),
  190. }),
  191. );
  192. } else if (manifestResult.error) {
  193. reasons.push(
  194. diagnostic({
  195. code: "INVALID_MANIFEST_JSON",
  196. message: `case manifest is not valid JSON: ${manifestResult.error.message}`,
  197. specPath,
  198. subjectPath: toRepoPath(root, manifestPath),
  199. }),
  200. );
  201. }
  202. if (caseFixtureResult.missing) {
  203. reasons.push(
  204. diagnostic({
  205. code: "MISSING_CASE_FIXTURE",
  206. message: "case-local provider fixture is missing",
  207. specPath,
  208. subjectPath: toRepoPath(root, caseFixturePath),
  209. }),
  210. );
  211. } else if (caseFixtureResult.error) {
  212. reasons.push(
  213. diagnostic({
  214. code: "INVALID_CASE_FIXTURE_JSON",
  215. message: `case-local provider fixture is not valid JSON: ${caseFixtureResult.error.message}`,
  216. specPath,
  217. subjectPath: toRepoPath(root, caseFixturePath),
  218. }),
  219. );
  220. }
  221. if (manifestResult.value !== undefined) {
  222. await validateFormalAdmissionManifest({
  223. absoluteSpecPath,
  224. caseFixture: caseFixtureResult.value,
  225. caseFixturePath,
  226. caseName,
  227. manifest: manifestResult.value,
  228. manifestPath,
  229. reasons,
  230. root,
  231. specPath,
  232. });
  233. }
  234. return { caseName, legacyHarness, reasons, specPath };
  235. }
  236. function inspectLegacyHarness(source) {
  237. const codes = [];
  238. const sourceFile = ts.createSourceFile(
  239. "conversation-session.test.ts",
  240. source,
  241. ts.ScriptTarget.Latest,
  242. true,
  243. ts.ScriptKind.TS,
  244. );
  245. let legacyImport = false;
  246. let legacyPrepareCall = false;
  247. const visit = (node) => {
  248. if (
  249. ts.isImportDeclaration(node) &&
  250. ts.isStringLiteral(node.moduleSpecifier) &&
  251. /(?:^|\/)helpers\/conversation-session\.js$/.test(node.moduleSpecifier.text)
  252. ) {
  253. legacyImport = true;
  254. }
  255. if (
  256. ts.isCallExpression(node) &&
  257. ts.isIdentifier(unwrapTransparentExpression(node.expression)) &&
  258. unwrapTransparentExpression(node.expression).text === "prepareConversationE2E"
  259. ) {
  260. legacyPrepareCall = true;
  261. }
  262. ts.forEachChild(node, visit);
  263. };
  264. visit(sourceFile);
  265. if (legacyImport) {
  266. codes.push("LEGACY_HELPER_IMPORT");
  267. }
  268. if (legacyPrepareCall) {
  269. codes.push("LEGACY_PREPARE_CALL");
  270. }
  271. return codes;
  272. }
  273. function unwrapTransparentExpression(expression) {
  274. let current = expression;
  275. while (
  276. ts.isParenthesizedExpression(current) ||
  277. ts.isNonNullExpression(current) ||
  278. ts.isAsExpression(current) ||
  279. ts.isTypeAssertionExpression(current) ||
  280. ts.isSatisfiesExpression(current) ||
  281. ts.isPartiallyEmittedExpression(current)
  282. ) {
  283. current = current.expression;
  284. }
  285. return current;
  286. }
  287. async function listSpecsRecursively(directory) {
  288. const entries = await readDirectory(directory);
  289. const nested = await Promise.all(
  290. entries.map(async (entry) => {
  291. const path = resolve(directory, entry.name);
  292. if (entry.isDirectory()) {
  293. return listSpecsRecursively(path);
  294. }
  295. return entry.isFile() && entry.name.endsWith(".test.ts") ? [path] : [];
  296. }),
  297. );
  298. return nested.flat().sort();
  299. }
  300. async function readDirectory(directory) {
  301. try {
  302. return await readdir(directory, { withFileTypes: true });
  303. } catch (error) {
  304. if (error?.code === "ENOENT") {
  305. return [];
  306. }
  307. throw error;
  308. }
  309. }