actor-names.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { describe, expect, it } from "vitest";
  2. import { analyzeWorkflowScript } from "../src/index.js";
  3. import { DUPLICATE_ACTOR_NAME_CODE, FANOUT_ACTOR_NAME_CODE } from "../src/analysis/actor-names.js";
  4. // 字面量 actor 重名的编译期 courtesy 诊断(docs/execution-engine.md 的
  5. // 「命名唯一性(引擎)」行)。规则的正门在运行期(引擎 createActor 的 DuplicateActorName);
  6. // 这一趟只看字面量,所以它只许漏报、不许误报——每条 "legal" 用例都是对后者的断言。
  7. /** 只取重名诊断(脚本本身必须 typecheck 干净,否则 analyze 根本走不到这一趟)。 */
  8. function duplicates(scriptText: string) {
  9. const result = analyzeWorkflowScript(scriptText);
  10. const hits = result.diagnostics.filter((d) => d.code === DUPLICATE_ACTOR_NAME_CODE);
  11. return { hits, result };
  12. }
  13. /** 只取 fan-out 静态名诊断(子句 2,单独一个码——见 actor-names.ts 顶部)。 */
  14. function fanOutNames(scriptText: string) {
  15. const result = analyzeWorkflowScript(scriptText);
  16. const hits = result.diagnostics.filter((d) => d.code === FANOUT_ACTOR_NAME_CODE);
  17. return { hits, result };
  18. }
  19. /** 干净脚本的断言:无重名诊断,且整份分析通过(图照常产出)。 */
  20. function expectClean(scriptText: string): void {
  21. const { hits, result } = duplicates(scriptText);
  22. expect(hits).toEqual([]);
  23. expect(result.diagnostics).toEqual([]);
  24. expect(result.ok).toBe(true);
  25. }
  26. describe("duplicate actor names (compile-time courtesy)", () => {
  27. it("flags two literal name arguments that are the same string, on the later site", () => {
  28. const { hits, result } = duplicates(
  29. `const a = agent("planner");\nconst b = agent("planner");\nreturn 1;`,
  30. );
  31. expect(hits).toHaveLength(1);
  32. expect(hits[0]?.line).toBe(2);
  33. expect(hits[0]?.message).toContain('"planner"');
  34. // 诊断与 world.run / phase 同席:脚本不可提交,图不产出。
  35. expect(result.ok).toBe(false);
  36. expect(result.graph).toBeUndefined();
  37. });
  38. it("reads through an object-literal persona to the name argument", () => {
  39. // 今天 `AgentPersona` **不声明** name(facade dts),所以脚本能写出的 persona 从不带名字,
  40. // 有效名一律来自 name 实参。收集器仍按 normalizePersona 的规则处理 persona(见下面两条
  41. // 跳过用例)——那是为了与运行期的有效名定义保持同步,而不是为了今天能触发。
  42. const { hits } = duplicates(
  43. `const a = agent("planner", { system: "You plan first." });\n` +
  44. `const b = agent("planner", { system: "You plan." });\n` +
  45. `return 1;`,
  46. );
  47. expect(hits).toHaveLength(1);
  48. expect(hits[0]?.line).toBe(2);
  49. });
  50. it("takes a string persona as a system prompt, not a name", () => {
  51. // agent(name, "You plan.") 的有效名仍是 name 实参——两处同名照样是重名。
  52. const { hits } = duplicates(
  53. `const a = agent("planner", "You plan.");\n` +
  54. `const b = agent("planner", "You also plan.");\n` +
  55. `return 1;`,
  56. );
  57. expect(hits).toHaveLength(1);
  58. });
  59. it("reports each later repetition of a name", () => {
  60. const { hits } = duplicates(
  61. `const a = agent("w");\nconst b = agent("w");\nconst c = agent("w");\nreturn 1;`,
  62. );
  63. expect(hits.map((d) => d.line)).toEqual([2, 3]);
  64. });
  65. it("leaves anonymous actors alone, however many", () => {
  66. // 匿名合法(运行期也不查)。注意站点表会把绑定名当**展示标签**记进 site.name,
  67. // 所以这条同时钉住「诊断读的是实参,不是那个标签」——否则下面两个都叫 "a"/"b" 的
  68. // 匿名 actor 会被误伤。
  69. expectClean(`const a = agent();\nconst b = agent();\nreturn 1;`);
  70. });
  71. it("leaves empty names alone (empty is anonymous, matching the engine)", () => {
  72. expectClean(`const a = agent("");\nconst b = agent("");\nreturn 1;`);
  73. });
  74. it("leaves distinct names alone", () => {
  75. expectClean(`const a = agent("planner");\nconst b = agent("reviewer");\nreturn 1;`);
  76. });
  77. it("skips dynamic names — the runtime check is the real gate", () => {
  78. // 模板洞、标识符、循环里的同一个站点:静态说不准,一律放行,由引擎运行期兜底。
  79. expectClean(
  80. `const workers = [1, 2, 3].map((i) => agent(\`worker-\${i}\`));\n` +
  81. `const n = "planner";\nconst p = agent(n);\nconst q = agent(n);\n` +
  82. `return workers.length;`,
  83. );
  84. });
  85. it("skips a persona with a computed key (the key itself could be `name`)", () => {
  86. // 计算键必须让整个站点放弃,而不是「跳过这一个属性再落回 name 实参」——后者是一次猜测,
  87. // 猜错的方向正好是误报。
  88. expectClean(
  89. `const a = agent("w", { ["system"]: "You work." });\n` +
  90. `const b = agent("w", { ["system"]: "You work." });\n` +
  91. `return 1;`,
  92. );
  93. });
  94. it("skips a template-with-holes persona (it is a runtime string, not a literal)", () => {
  95. expectClean(
  96. `const role = "planner";\n` +
  97. `const a = agent("w", \`You are the \${role}.\`);\n` +
  98. `const b = agent("w", \`You are the \${role}.\`);\n` +
  99. `return 1;`,
  100. );
  101. });
  102. it("skips dynamic names inside a fan-out too (per-element names are the fix, not a violation)", () => {
  103. expectClean(
  104. `const paths = await files.glob("src/**/*.ts");\n` +
  105. `const notes = await Promise.all(paths.map((p) => agent(\`reviewer-\${p}\`).ask<string>(\`Review \${p}\`)));\n` +
  106. `return notes.length;`,
  107. );
  108. });
  109. it("skips a spread persona and a non-literal persona (either could carry a name)", () => {
  110. // 保守而不是聪明:`AgentPersona` 今天没有 name,但收集器不拿 facade 的现状当前提——
  111. // 一旦它长出 name,「按 name 实参判定」就会变成对一个被改名的 actor 的**误报**,而误报
  112. // 会挡住合法脚本。漏报没有代价(引擎运行期兜底),所以看不穿就放行。
  113. expectClean(
  114. `const base = { system: "You work." };\n` +
  115. `const a = agent("w", { ...base });\nconst b = agent("w", base);\nreturn 1;`,
  116. );
  117. });
  118. });
  119. // 第二条子句:fan-out 体内的静态名。一个站点、N 个 actor、同一个名字——运行期必然
  120. // DuplicateActorName。这条**刻意**可能误报(`.map` 的集合可能只有一个元素),理由见
  121. // src/analysis/actor-names.ts 顶部:修复免费,而沉默的代价是烧掉一整个 run。
  122. describe("static actor names inside a fan-out (compile-time)", () => {
  123. it("flags a literal name inside an array-method fan-out, without withholding the graph", () => {
  124. const { hits, result } = fanOutNames(
  125. `const paths = await files.glob("src/**/*.ts");\n` +
  126. `const verdicts = await Promise.all(paths.map((p) => agent("reviewer").ask<string>(\`Review \${p}\`)));\n` +
  127. `return verdicts.length;`,
  128. );
  129. expect(hits).toHaveLength(1);
  130. expect(hits[0]?.line).toBe(2);
  131. expect(hits[0]?.message).toContain("fan-out");
  132. expect(hits[0]?.message).toContain('"reviewer"');
  133. // 提交被挡住(ok:false),但图照常产出——这一条说的是脚本**跑**起来会失败,不是
  134. // 「这段代码没法分析」,而作者正需要看图才知道是哪个 fan-out(见 analyze.ts)。
  135. expect(result.ok).toBe(false);
  136. expect(result.graph).toBeDefined();
  137. expect(result.causality).toBeDefined();
  138. });
  139. it("flags a literal name inside a for...of body", () => {
  140. const { hits } = fanOutNames(
  141. `const items = ["a", "b"];\nconst out: string[] = [];\n` +
  142. `for (const item of items) {\n const w = agent("worker");\n out.push(await w.ask<string>(\`Do \${item}\`));\n}\n` +
  143. `return out;`,
  144. );
  145. expect(hits).toHaveLength(1);
  146. expect(hits[0]?.line).toBe(4);
  147. });
  148. it("still withholds the graph when a blocking clause fires alongside it", () => {
  149. // 9005 与 9006 同时在场:9005 是扣图的那一档,整份分析照旧不产出图。
  150. const { result } = fanOutNames(
  151. `const paths = await files.glob("src/**/*.ts");\n` +
  152. `const verdicts = await Promise.all(paths.map((p) => agent("reviewer").ask<string>(\`Review \${p}\`)));\n` +
  153. `const a = agent("dup");\nconst b = agent("dup");\n` +
  154. `return [verdicts.length, await a.ask<string>("x"), await b.ask<string>("y")];`,
  155. );
  156. expect(result.ok).toBe(false);
  157. expect(result.graph).toBeUndefined();
  158. });
  159. it("leaves an anonymous actor inside a fan-out alone", () => {
  160. expectClean(
  161. `const paths = await files.glob("src/**/*.ts");\n` +
  162. `const verdicts = await Promise.all(paths.map((p) => agent().ask<string>(\`Review \${p}\`)));\n` +
  163. `return verdicts.length;`,
  164. );
  165. });
  166. it("leaves a literal name outside any fan-out alone (single site = runtime's business)", () => {
  167. expectClean(`const reviewer = agent("reviewer");\nreturn await reviewer.ask<string>("Review.");`);
  168. });
  169. it("reports one diagnostic per site, preferring the fan-out clause over the duplicate one", () => {
  170. // 同一个名字既在 fan-out 里、又在外面重复出现:fan-out 站点报 9006,外面那个照常按
  171. // 9005 报——两个站点各一条,不叠加。
  172. const script =
  173. `const paths = await files.glob("src/**/*.ts");\n` +
  174. `const verdicts = await Promise.all(paths.map((p) => agent("reviewer").ask<string>(\`Review \${p}\`)));\n` +
  175. `const late = agent("reviewer");\n` +
  176. `return [verdicts.length, await late.ask<string>("Again?")];`;
  177. expect(fanOutNames(script).hits.map((d) => d.line)).toEqual([2]);
  178. expect(duplicates(script).hits.map((d) => d.line)).toEqual([3]);
  179. });
  180. });