schema-synth.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. MAX_UNION_MEMBERS,
  4. SCHEMA_DIAGNOSTIC_CODE,
  5. buildAskSpecs,
  6. collectSites,
  7. createWorkflowProgram,
  8. synthesizeAskSchemas,
  9. synthesizeWorkflowSchemas,
  10. type AskSpec,
  11. type JsonSchema,
  12. } from "../src/index.js";
  13. // 合成侧单测:用便捷入口 synthesizeWorkflowSchemas 从脚本文本一站式合成,精确断言
  14. // 关键行为(快照套件覆盖整体输出,这里锁定语义细节)。
  15. function schemasOf(script: string): Record<string, JsonSchema> {
  16. const result = synthesizeWorkflowSchemas(script);
  17. expect(result.diagnostics).toEqual([]);
  18. return result.schemas;
  19. }
  20. describe("typedness", () => {
  21. it("skips untyped asks: bare ask() and explicit ask<string>()", () => {
  22. const script = [
  23. `const a = agent("a");`,
  24. `const x = await a.ask("plain");`,
  25. `const y = await a.ask<string>("still plain");`,
  26. `log(x + y);`,
  27. ].join("\n");
  28. expect(schemasOf(script)).toEqual({});
  29. });
  30. it("synthesizes only for typed asks, keyed by site id", () => {
  31. const script = [
  32. `interface Plan { done: boolean }`,
  33. `const a = agent("a");`,
  34. `const p = await a.ask<Plan>("plan");`,
  35. `const t = await a.ask("text");`,
  36. `log(JSON.stringify(p) + t);`,
  37. ].join("\n");
  38. expect(Object.keys(schemasOf(script))).toEqual(["ask#1"]);
  39. });
  40. it("treats ask<string | null> as typed (not the bare string primitive)", () => {
  41. const script = [`const a = agent("a");`, `const v = await a.ask<string | null>("maybe");`, `log(String(v));`].join("\n");
  42. const schema = schemasOf(script)["ask#1"]!;
  43. expect(schema.anyOf).toHaveLength(2);
  44. expect(schema.anyOf).toEqual(expect.arrayContaining([{ type: "string" }, { type: "null" }]));
  45. });
  46. it("treats an alias of string as untyped (checker resolves it to string)", () => {
  47. const script = [
  48. `type Alias = string;`,
  49. `const a = agent("a");`,
  50. `const v = await a.ask<Alias>("plain");`,
  51. `log(v);`,
  52. ].join("\n");
  53. expect(schemasOf(script)).toEqual({});
  54. });
  55. });
  56. describe("unknown is permissive", () => {
  57. it("emits an empty schema for unknown", () => {
  58. const script = [`const a = agent("a");`, `const v = await a.ask<unknown>("anything");`, `log(String(v));`].join("\n");
  59. expect(schemasOf(script)["ask#1"]).toEqual({});
  60. });
  61. });
  62. describe("optional vs undefined", () => {
  63. it("optional property is excluded from required and drops undefined", () => {
  64. const script = [
  65. `interface R { a: string; b?: number }`,
  66. `const g = agent("g");`,
  67. `const r = await g.ask<R>("go");`,
  68. `log(JSON.stringify(r));`,
  69. ].join("\n");
  70. const schema = schemasOf(script)["ask#1"]!;
  71. expect(schema.required).toEqual(["a"]);
  72. expect(schema.properties?.b).toEqual({ type: "number" });
  73. });
  74. it("rejects a non-optional undefined-typed member", () => {
  75. const script = [
  76. `interface R { a: string | undefined }`,
  77. `const g = agent("g");`,
  78. `const r = await g.ask<R>("go");`,
  79. `log(JSON.stringify(r));`,
  80. ].join("\n");
  81. const result = synthesizeWorkflowSchemas(script);
  82. expect(result.schemas).toEqual({});
  83. expect(result.diagnostics).toHaveLength(1);
  84. expect(result.diagnostics[0]!.code).toBe(SCHEMA_DIAGNOSTIC_CODE);
  85. expect(result.diagnostics[0]!.message).toContain("undefined");
  86. });
  87. });
  88. describe("unions", () => {
  89. it("literal unions become enum", () => {
  90. const script = [
  91. `const g = agent("g");`,
  92. `const r = await g.ask<"low" | "high">("pick");`,
  93. `log(String(r));`,
  94. ].join("\n");
  95. expect(schemasOf(script)["ask#1"]).toEqual({ enum: ["low", "high"] });
  96. });
  97. it("general unions become anyOf", () => {
  98. const script = [
  99. `interface A { kind: "a" }`,
  100. `interface B { kind: "b" }`,
  101. `const g = agent("g");`,
  102. `const r = await g.ask<A | B>("pick");`,
  103. `log(JSON.stringify(r));`,
  104. ].join("\n");
  105. const schema = schemasOf(script)["ask#1"]!;
  106. expect(schema.anyOf).toHaveLength(2);
  107. });
  108. it("rejects a pathologically wide union at the ask site", () => {
  109. const members = Array.from({ length: MAX_UNION_MEMBERS + 1 }, (_, i) => String(i)).join(" | ");
  110. const script = [`const g = agent("g");`, `const r = await g.ask<${members}>("pick");`, `log(String(r));`].join("\n");
  111. const result = synthesizeWorkflowSchemas(script);
  112. expect(result.schemas).toEqual({});
  113. expect(result.diagnostics).toHaveLength(1);
  114. expect(result.diagnostics[0]!.line).toBe(2);
  115. expect(result.diagnostics[0]!.message).toContain("too many members");
  116. });
  117. });
  118. describe("recursion via $defs/$ref", () => {
  119. it("hoists a self-referential type into $defs and references it", () => {
  120. const script = [
  121. `interface Tree { value: number; children: Tree[] }`,
  122. `const g = agent("g");`,
  123. `const r = await g.ask<Tree>("build");`,
  124. `log(JSON.stringify(r));`,
  125. ].join("\n");
  126. const schema = schemasOf(script)["ask#1"]!;
  127. expect(schema.$ref).toBe("#/$defs/Tree");
  128. const tree = schema.$defs?.Tree;
  129. expect(tree?.properties?.children).toEqual({ items: { $ref: "#/$defs/Tree" }, type: "array" });
  130. });
  131. it("keeps a non-recursive named type inline (no $defs)", () => {
  132. const script = [
  133. `interface Plan { step: string }`,
  134. `const g = agent("g");`,
  135. `const r = await g.ask<Plan>("plan");`,
  136. `log(JSON.stringify(r));`,
  137. ].join("\n");
  138. const schema = schemasOf(script)["ask#1"]!;
  139. expect(schema.$defs).toBeUndefined();
  140. expect(schema.type).toBe("object");
  141. });
  142. });
  143. describe("JSDoc harvest", () => {
  144. it("harvests description and the constraint-tag subset", () => {
  145. const script = [
  146. `interface Form {`,
  147. ` /**`,
  148. ` * The user's age.`,
  149. ` * @minimum 0`,
  150. ` * @maximum 120`,
  151. ` */`,
  152. ` age: number;`,
  153. ` /** @minLength 1 @pattern ^[a-z]+$ */`,
  154. ` name: string;`,
  155. ` /** @minItems 1 @maxItems 3 */`,
  156. ` tags: string[];`,
  157. `}`,
  158. `const g = agent("g");`,
  159. `const r = await g.ask<Form>("fill");`,
  160. `log(JSON.stringify(r));`,
  161. ].join("\n");
  162. const props = schemasOf(script)["ask#1"]!.properties!;
  163. expect(props.age).toEqual({ description: "The user's age.", maximum: 120, minimum: 0, type: "number" });
  164. expect(props.name).toEqual({ minLength: 1, pattern: "^[a-z]+$", type: "string" });
  165. expect(props.tags).toEqual({ items: { type: "string" }, maxItems: 3, minItems: 1, type: "array" });
  166. });
  167. it("ignores tags outside the subset", () => {
  168. const script = [
  169. `interface F {`,
  170. ` /**`,
  171. ` * @deprecated do not use`,
  172. ` * @minimum 5`,
  173. ` */`,
  174. ` n: number;`,
  175. `}`,
  176. `const g = agent("g");`,
  177. `const r = await g.ask<F>("go");`,
  178. `log(JSON.stringify(r));`,
  179. ].join("\n");
  180. expect(schemasOf(script)["ask#1"]!.properties!.n).toEqual({ minimum: 5, type: "number" });
  181. });
  182. });
  183. describe("buildAskSpecs — 引擎入参的总覆盖", () => {
  184. // 引擎把「站点缺席」当接线错误硬失败(MissingAskSpec),所以 askSpecs 必须**每个 ask
  185. // 站点都有一条**。schemas 只含 typed 站点,因此这个 builder 按站点表遍历——它存在的
  186. // 唯一理由就是把这条规则收在一处,而不是让每个调用点各自实现一遍(其中一处必然写错)。
  187. function specsOf(script: string): {
  188. specs: Map<string, AskSpec>;
  189. siteIds: string[];
  190. schemas: Record<string, JsonSchema>;
  191. } {
  192. const workflow = createWorkflowProgram(script);
  193. const table = collectSites(workflow);
  194. const { diagnostics, schemas } = synthesizeAskSchemas(workflow, table);
  195. expect(diagnostics).toEqual([]);
  196. return { specs: buildAskSpecs(table, schemas), siteIds: table.asks.map((a) => a.id), schemas };
  197. }
  198. it("covers every ask site, typed and untyped alike", () => {
  199. const script = [
  200. `interface Plan { done: boolean }`,
  201. `const a = agent("a");`,
  202. `const p = await a.ask<Plan>("plan");`,
  203. `const t = await a.ask("text");`,
  204. `log(JSON.stringify(p) + t);`,
  205. ].join("\n");
  206. const { specs, siteIds, schemas } = specsOf(script);
  207. expect([...specs.keys()]).toEqual(siteIds);
  208. expect(specs.size).toBe(2);
  209. // typed 站点的 schema 原样透传(builder 不加工 schema,只决定 typed 与否)。
  210. expect(specs.get("ask#1")).toEqual({ typed: true, schema: schemas["ask#1"] });
  211. expect(specs.get("ask#1")?.schema).toBe(schemas["ask#1"]);
  212. expect(specs.get("ask#2")).toEqual({ typed: false });
  213. });
  214. it("gives an untyped-only script a full table of explicit untyped entries", () => {
  215. // 这是那条兜底被删掉后真正的回归风险:从前 askSpecs 为空也能跑,现在必须显式记录。
  216. const script = [`const a = agent("a");`, `const x = await a.ask("one");`, `const y = await a.ask("two");`, `log(x + y);`].join("\n");
  217. const { specs } = specsOf(script);
  218. expect([...specs.entries()]).toEqual([
  219. ["ask#1", { typed: false }],
  220. ["ask#2", { typed: false }],
  221. ]);
  222. });
  223. it("leaves schema absent (not undefined) on untyped entries", () => {
  224. // schema 会随 AskMessage 透传给 driver;`schema: undefined` 与"没有 schema"在
  225. // 序列化与 `in` 判定上不同,untyped 条目必须是后者。
  226. const { specs } = specsOf([`const a = agent("a");`, `const x = await a.ask("plain");`, `log(x);`].join("\n"));
  227. const spec = specs.get("ask#1")!;
  228. expect("schema" in spec).toBe(false);
  229. });
  230. it("returns an empty table for a script with no asks", () => {
  231. const { specs } = specsOf([`const paths = await files.glob("*.ts");`, `log(String(paths.length));`].join("\n"));
  232. expect(specs.size).toBe(0);
  233. });
  234. it("ignores schema keys that no ask site claims", () => {
  235. // 防御:schemas 若因调用方拼错而带了不存在的站点,结果仍严格由站点表定形——
  236. // 站点表是身份的唯一真源。
  237. const script = [`const a = agent("a");`, `const x = await a.ask("plain");`, `log(x);`].join("\n");
  238. const workflow = createWorkflowProgram(script);
  239. const table = collectSites(workflow);
  240. const specs = buildAskSpecs(table, { "ask#42": { type: "string" } });
  241. expect([...specs.keys()]).toEqual(["ask#1"]);
  242. expect(specs.get("ask#1")).toEqual({ typed: false });
  243. });
  244. });