v4-native-boundary.test.ts 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // 结构性禁令(08-phasing M4 原生重做版,2026-07-06 裁决):
  2. // zcode-protocol-v4/ 是新协议的原生实现层,禁止 import 旧协议目录(zcode-protocol/)的任何模块。
  3. // 背景:M4 曾被实施为「v4 命令桥翻译回 server-operations」(备份 backup/opus-m4-m5-20260706),
  4. // 桥让旧协议成为实际执行者、e2e 的绿是借旧代码的绿,波次 2/3 永远删不动——本测试把「无桥,
  5. // 新不调老」从口头纪律变成编译期之外的第二道硬闸:任何人(含 agent)想抄近路,此测试先红。
  6. // 允许的方向是反向:旧协议目录里的 binder(如 v4-bridge.ts)可以 import v4 网关做过渡接线,
  7. // 该 binder 随原生 handler 铺全逐条瘦身、随波次 2 删除。
  8. import { readdirSync, readFileSync, statSync } from "node:fs";
  9. import { join, relative } from "node:path";
  10. import { fileURLToPath } from "node:url";
  11. import { describe, expect, it } from "vitest";
  12. const v4Dir = fileURLToPath(
  13. new URL("../src/zcode-protocol-v4/", import.meta.url),
  14. );
  15. function collectTsFiles(dir: string): string[] {
  16. const files: string[] = [];
  17. for (const entry of readdirSync(dir)) {
  18. const fullPath = join(dir, entry);
  19. if (statSync(fullPath).isDirectory()) {
  20. files.push(...collectTsFiles(fullPath));
  21. continue;
  22. }
  23. if (entry.endsWith(".ts")) {
  24. files.push(fullPath);
  25. }
  26. }
  27. return files;
  28. }
  29. /** 匹配 import/export ... from "<path>" 与动态 import("<path>") 的模块说明符。 */
  30. function collectImportSpecifiers(source: string): string[] {
  31. const specifiers: string[] = [];
  32. const staticPattern = /(?:import|export)\s[^;]*?from\s*["']([^"']+)["']/g;
  33. const dynamicPattern = /import\s*\(\s*["']([^"']+)["']\s*\)/g;
  34. for (const pattern of [staticPattern, dynamicPattern]) {
  35. for (const match of source.matchAll(pattern)) {
  36. specifiers.push(match[1]);
  37. }
  38. }
  39. return specifiers;
  40. }
  41. /**
  42. * 旧协议目录的引用特征:路径含 "zcode-protocol/" 段。
  43. * 无需排除逻辑:"zcode-protocol-v4/" 在 "protocol" 后是 "-v4/" 而非 "/",字面量天然不匹配;
  44. * 反而早前加的 (?!.*-v4) 会把 "zcode-protocol/xx-v4.js" 这类旧目录文件误放行(lookahead 漏报)。
  45. */
  46. function isLegacyProtocolImport(specifier: string): boolean {
  47. return /(?:^|\/)zcode-protocol\//.test(specifier.replace(/\\/g, "/"));
  48. }
  49. describe("v4 原生边界禁令(无桥)", () => {
  50. it("zcode-protocol-v4/ 下任何文件不得 import 旧协议目录(zcode-protocol/)", () => {
  51. const violations: string[] = [];
  52. for (const file of collectTsFiles(v4Dir)) {
  53. const source = readFileSync(file, "utf8");
  54. for (const specifier of collectImportSpecifiers(source)) {
  55. if (isLegacyProtocolImport(specifier)) {
  56. violations.push(`${relative(v4Dir, file)} → ${specifier}`);
  57. }
  58. }
  59. }
  60. expect(
  61. violations,
  62. `v4 原生层出现对旧协议的 import(违反 08-phasing M4「无桥」禁令):\n${violations.join("\n")}`,
  63. ).toEqual([]);
  64. });
  65. });