analysis.test.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. import { describe, expect, it } from "vitest";
  2. import { createWorkflowProgram } from "../src/compiler/compile.js";
  3. import { collectSites } from "../src/analysis/sites.js";
  4. import { FACADE_SITING_CODE } from "../src/analysis/facade-misuse.js";
  5. import { analyzeWorkflowScript, siteGraphToMermaid, toActorGraph } from "../src/index.js";
  6. import { serializeActorGraph, serializeGraph } from "../src/analysis/serialize.js";
  7. import type { SiteEdge, SiteGraph } from "../src/analysis/types.js";
  8. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  9. // Unit coverage for the analysis substrate where a full fixture snapshot would be
  10. // awkward: prelude-stripped location mapping and the resolver-driven site table.
  11. describe("createWorkflowProgram", () => {
  12. it("maps positions to 1-based, prelude-stripped script coordinates", () => {
  13. const { scriptFile, toScriptLoc } = createWorkflowProgram(`const x = 1;\nconst y = 2;`);
  14. // The first authored line is line 1 despite the wrapper prelude occupying line 1
  15. // of the wrapped source; the first character is column 1.
  16. const firstConst = scriptFile.text.indexOf("const x");
  17. expect(toScriptLoc(firstConst)).toEqual({ column: 1, line: 1 });
  18. const secondConst = scriptFile.text.indexOf("const y");
  19. expect(toScriptLoc(secondConst)).toEqual({ column: 1, line: 2 });
  20. });
  21. });
  22. describe("collectSites", () => {
  23. const table = (scriptText: string) => collectSites(createWorkflowProgram(scriptText));
  24. it("resolves facade Agent.ask via the checker, not by method name", () => {
  25. const sites = table(`
  26. const notAnAgent = { ask(q: string): string { return q; } };
  27. const ignored = notAnAgent.ask("nope");
  28. const real = await agent("scanner").ask<string>("do it");
  29. return real;
  30. `);
  31. expect(sites.asks).toHaveLength(1);
  32. expect(sites.asks[0]?.label).toBe("scanner");
  33. expect(sites.actors).toHaveLength(1);
  34. });
  35. it("collects asks inside script-local helper functions", () => {
  36. const sites = table(`
  37. async function helper(topic: string): Promise<string> {
  38. const worker = agent("worker");
  39. return await worker.ask<string>(topic);
  40. }
  41. const out = await helper("x");
  42. return out;
  43. `);
  44. expect(sites.asks).toHaveLength(1);
  45. expect(sites.asks[0]?.label).toBe("worker");
  46. // The helper's own `return` is not a top-level (sink) return; only the last one is.
  47. expect(sites.topLevelReturns).toHaveLength(1);
  48. });
  49. it("assigns per-kind source-order ordinal ids", () => {
  50. const sites = table(`
  51. const a = await agent("first").ask<string>("a");
  52. const b = await agent("second").ask<string>("b");
  53. return a + b;
  54. `);
  55. expect(sites.asks.map((s) => s.id)).toEqual(["ask#1", "ask#2"]);
  56. expect(sites.actors.map((s) => s.id)).toEqual(["actor#1", "actor#2"]);
  57. });
  58. it("records array-method fan-out candidates with their binding and iterated node", () => {
  59. const sites = table(`
  60. const paths = await files.glob("src/**/*.ts");
  61. const done = paths.map((p) => agent("r").ask<string>(p));
  62. return done.length;
  63. `);
  64. expect(sites.worldReads).toHaveLength(1);
  65. expect(sites.iterations).toHaveLength(1);
  66. expect(sites.iterations[0]?.form).toBe("array-method");
  67. expect(sites.iterations[0]?.method).toBe("map");
  68. });
  69. });
  70. /** The data edges of a clean script, for asserting exactness/ports directly. */
  71. function dataEdges(scriptText: string): SiteEdge[] {
  72. const result = analyzeWorkflowScript(scriptText);
  73. expect(result.diagnostics).toEqual([]);
  74. const graph = result.graph;
  75. if (graph === undefined) throw new Error("expected a graph for a clean script");
  76. return graph.edges.filter((edge) => edge.kind === "data");
  77. }
  78. function edge(edges: SiteEdge[], from: string, to: string): SiteEdge | undefined {
  79. return edges.find((e) => e.from === from && e.to === to);
  80. }
  81. describe("heap-write soundness (bug-scan regressions)", () => {
  82. it("merges mutator argument taint through an unresolvable (computed-index) receiver", () => {
  83. // Bugfix: `state.buffers[i].push(seed)` has no resolvable receiver place (computed
  84. // index), and the old transfer dropped seed's taint entirely instead of falling back
  85. // to the root-identifier smear the assignment paths use.
  86. const edges = dataEdges(`
  87. const seed = await agent("a").ask<string>("draft");
  88. const state = { buffers: [[""]] };
  89. const i = seed.length % 1;
  90. state.buffers[i]!.push(seed);
  91. const out = await agent("b").ask<string>(\`use \${JSON.stringify(state)}\`);
  92. return out;
  93. `);
  94. expect(edge(edges, "ask#1", "ask#2")).toBeDefined();
  95. });
  96. it("writes loop-carried for-of element mutations back to the collection (pass >= 2 flows)", () => {
  97. // Bugfix: the for-of write-back scanned the current pass's fresh element clone, but the
  98. // body writes land on the loop variable's persistent env slot — taint that first
  99. // arrives on fixpoint pass 2 (the loop-carried reviewer feedback) never reached items.
  100. const edges = dataEdges(`
  101. let fb = "";
  102. const items = [{ note: "" }];
  103. for (let r = 0; r < 2; r++) {
  104. for (const it of items) {
  105. it.note = fb;
  106. }
  107. fb = await agent("reviewer").ask<string>("review the drafts");
  108. }
  109. const out = await agent("writer").ask<string>(items.map((x) => x.note).join(","));
  110. return out;
  111. `);
  112. expect(edge(edges, "ask#1", "ask#2")).toBeDefined();
  113. });
  114. it("writes destructured for-of loop-variable mutations back to the collection", () => {
  115. // Bugfix: `for (const { doc } of items)` binds doc to a detached clone, so its field
  116. // writes never populated the element value the old write-back scanned — dropped even
  117. // on the first pass. The write-back now reads the slots the body actually wrote through.
  118. const edges = dataEdges(`
  119. const t = await agent("a").ask<string>("annotate");
  120. const items = [{ doc: { note: "" } }];
  121. for (const { doc } of items) {
  122. doc.note = t;
  123. }
  124. const out = await agent("b").ask<string>(JSON.stringify(items));
  125. return out;
  126. `);
  127. expect(edge(edges, "ask#1", "ask#2")).toBeDefined();
  128. });
  129. it("carries a container-level param mutation with a sibling param's value back to the caller", () => {
  130. // Bugfix: mergeHeapEffects skipped every top-level placeholder of the param slot, so
  131. // `list.push(v)` inside the callee (which routes ph(fill,1) into the `list` slot's top
  132. // level) never told the caller its array may contain v — the ask#1 -> ask#2 edge vanished.
  133. const edges = dataEdges(`
  134. function fill(list: string[], v: string): void {
  135. list.push(v);
  136. }
  137. const secret = await agent("w").ask<string>("secret");
  138. const list: string[] = [];
  139. fill(list, secret);
  140. const out = await agent("r").ask<string>(\`use \${list.join(" ")}\`);
  141. return out;
  142. `);
  143. expect(edge(edges, "ask#1", "ask#2")).toBeDefined();
  144. });
  145. it("dispatches a script-local method that shares a heap-mutator name (add/set/push)", () => {
  146. // Bugfix: `inbox.add(...)` was intercepted as Set.add by NAME alone; the tracked method
  147. // body was never applied, so its parameter actuals stayed empty and the flow from the
  148. // world read through the method's ask instruction was dropped.
  149. const edges = dataEdges(`
  150. const secretary = agent("s");
  151. const inbox = {
  152. add(item: string) {
  153. return secretary.ask<string>(\`file this: \${item}\`);
  154. },
  155. };
  156. const notes = await files.glob("*.md");
  157. const filed = await inbox.add(notes.join(","));
  158. return filed;
  159. `);
  160. expect(edge(edges, "world-read#1", "ask#1")).toBeDefined();
  161. });
  162. it("still folds native mutator arguments into a resolvable receiver (no regression)", () => {
  163. const edges = dataEdges(`
  164. const seed = await agent("a").ask<string>("draft");
  165. const box = { items: [] as string[] };
  166. box.items.push(seed);
  167. const out = await agent("b").ask<string>(box.items.join(","));
  168. return out;
  169. `);
  170. expect(edge(edges, "ask#1", "ask#2")).toBeDefined();
  171. });
  172. });
  173. describe("taint exactness", () => {
  174. it("preserves exactness through a directly-referenced helper (placeholder substitution)", () => {
  175. const edges = dataEdges(`
  176. function relay(v: string): string { return v; }
  177. const a = await agent("a").ask<string>("A");
  178. const c = await agent("c").ask<string>(\`use \${relay(a)}\`);
  179. return c;
  180. `);
  181. expect(edge(edges, "ask#1", "ask#2")?.exact).toBe(true);
  182. });
  183. it("clears exactness at a computed index access (the widening rule)", () => {
  184. const edges = dataEdges(`
  185. const seed = await agent("s").ask<string>("s");
  186. const items = [seed, "x"];
  187. const picked = items[seed.length % 2];
  188. const out = await agent("o").ask<string>(\`\${picked}\`);
  189. return out;
  190. `);
  191. expect(edge(edges, "ask#1", "ask#2")?.exact).toBe(false);
  192. });
  193. it("clears exactness through a higher-order (non-singleton) callee", () => {
  194. const edges = dataEdges(`
  195. function g(x: string): string { return x; }
  196. function h(x: string): string { return x; }
  197. const seed = await agent("s").ask<string>("s");
  198. const f = seed.length > 2 ? g : h;
  199. const out = await agent("o").ask<string>(\`\${f(seed)}\`);
  200. return out;
  201. `);
  202. expect(edge(edges, "ask#1", "ask#2")?.exact).toBe(false);
  203. });
  204. it("keeps context-sensitive returns from cross-contaminating distinct call sites", () => {
  205. // relay(a) feeds ask#3 and relay(b) feeds ask#4; there must be no ask#1 -> ask#4.
  206. const edges = dataEdges(`
  207. function relay(v: string): string { return v; }
  208. const a = await agent("a").ask<string>("A");
  209. const b = await agent("b").ask<string>("B");
  210. const c = await agent("c").ask<string>(\`\${relay(a)}\`);
  211. const d = await agent("d").ask<string>(\`\${relay(b)}\`);
  212. return \`\${c} \${d}\`;
  213. `);
  214. expect(edge(edges, "ask#1", "ask#3")).toBeDefined();
  215. expect(edge(edges, "ask#2", "ask#4")).toBeDefined();
  216. expect(edge(edges, "ask#1", "ask#4")).toBeUndefined();
  217. expect(edge(edges, "ask#2", "ask#3")).toBeUndefined();
  218. });
  219. it("carries a join element port through static destructuring to the downstream sink", () => {
  220. const edges = dataEdges(`
  221. const [x, y] = await Promise.all([
  222. agent("first").ask<string>("A"),
  223. agent("second").ask<string>("B"),
  224. ]);
  225. const z = await agent("third").ask<string>(\`\${x}\`);
  226. return \`\${y} \${z}\`;
  227. `);
  228. // x is element 0: the join -> ask#3 edge keeps port=0; the additive producer
  229. // edge ask#1 -> ask#3 is portless.
  230. expect(edge(edges, "join#1", "ask#3")?.port).toBe(0);
  231. expect(edge(edges, "ask#1", "ask#3")?.port).toBeUndefined();
  232. });
  233. });
  234. describe("constructor calls", () => {
  235. it("carries taint through a constructor call (new Set) into a downstream sink", () => {
  236. // `new Set([...])` has no script-local constructor summary; the NewExpression
  237. // rule unions the argument collapses so the ask result is not silently dropped.
  238. const edges = dataEdges(`
  239. const a = await agent("a").ask<string>("A");
  240. const set = new Set([a]);
  241. const out = await agent("o").ask<string>(JSON.stringify([...set]));
  242. return out;
  243. `);
  244. expect(edge(edges, "ask#1", "ask#2")).toBeDefined();
  245. });
  246. });
  247. describe("nested heap writes", () => {
  248. it("walks through a non-null assertion on a nested heap-write target", () => {
  249. // `report!.sections.intro = r`: the NonNull wrapper sits on the lvalue chain, so
  250. // the walk to the root identifier `report` must peel it — otherwise the ask taint
  251. // is silently dropped and `report` never reaches the return.
  252. const edges = dataEdges(`
  253. const report = { sections: { intro: "" } };
  254. const r = await agent("writer").ask<string>("write");
  255. report!.sections.intro = r;
  256. return report;
  257. `);
  258. expect(edge(edges, "ask#1", "sink")).toBeDefined();
  259. });
  260. });
  261. describe("ask actor lanes", () => {
  262. function askNode(scriptText: string, id: string) {
  263. const result = analyzeWorkflowScript(scriptText);
  264. expect(result.diagnostics).toEqual([]);
  265. return result.graph?.nodes.find((node) => node.id === id);
  266. }
  267. it("populates ask nodes with the receiver's actor site ids, deduped and ordered", () => {
  268. // `shared` is asked twice; a distinct `loner` once. Each ask node lists its lane.
  269. const script = `
  270. const shared = agent("shared");
  271. const a = await shared.ask<string>("one");
  272. const b = await shared.ask<string>("two");
  273. const loner = agent("loner");
  274. const c = await loner.ask<string>("three");
  275. return \`\${a} \${b} \${c}\`;
  276. `;
  277. expect(askNode(script, "ask#1")?.actors).toEqual(["actor#1"]);
  278. expect(askNode(script, "ask#2")?.actors).toEqual(["actor#1"]);
  279. expect(askNode(script, "ask#3")?.actors).toEqual(["actor#2"]);
  280. });
  281. it("resolves the actor lane of an ask on a helper parameter via the summary", () => {
  282. const script = `
  283. function interrogate(who: Agent): Node<string> {
  284. return who.ask<string>("q");
  285. }
  286. const shared = agent("shared");
  287. const out = await interrogate(shared);
  288. return out;
  289. `;
  290. // The ask lives inside the helper on parameter `who`; it resolves to the actor
  291. // passed in at the call site.
  292. expect(askNode(script, "ask#1")?.actors).toEqual(["actor#1"]);
  293. });
  294. });
  295. describe("mermaid emitters", () => {
  296. function siteMermaid(scriptText: string): string {
  297. const result = analyzeWorkflowScript(scriptText);
  298. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  299. const graph = result.graph;
  300. if (graph === undefined) throw new Error("expected a graph for a clean script");
  301. return siteGraphToMermaid(graph);
  302. }
  303. it("sanitizes node ids to word chars but keeps the original id in the label", () => {
  304. // Two promoted maps -> fan-out#1/#2. The mermaid node id must be `fan_out_2`
  305. // (ids forbid `#`/`-`), while the label still reads `fan-out#2`.
  306. const mermaid = siteMermaid(`
  307. const logs = await files.glob("*.log");
  308. const a = logs.map((f) => agent("A").ask<string>(f));
  309. const b = logs.map((f) => agent("B").ask<string>(f));
  310. return [...a, ...b];
  311. `);
  312. expect(mermaid).toContain('fan_out_2{{"fan-out#2"}}');
  313. expect(mermaid).not.toContain("fan-out#2{{");
  314. });
  315. it("entity-encodes double quotes in a user-derived label", () => {
  316. // An agent name with an embedded quote must not break the diagram: `"` -> `#quot;`.
  317. const mermaid = siteMermaid(`
  318. const out = await agent('say "hi"').ask<string>("go");
  319. return out;
  320. `);
  321. expect(mermaid).toContain("#quot;");
  322. expect(mermaid).not.toContain('say "hi"');
  323. });
  324. it("keeps a multi-actor (may) ask outside any lane subgraph", () => {
  325. // The receiver may be either actor, so the ask has a two-element actor set and
  326. // must stay top-level rather than being placed in one actor's lane.
  327. const mermaid = siteMermaid(`
  328. const a = agent("a");
  329. const b = agent("b");
  330. const who = Math.random() > 0.5 ? a : b;
  331. const out = await who.ask<string>("go");
  332. return out;
  333. `);
  334. expect(mermaid).not.toContain("subgraph");
  335. });
  336. });
  337. describe("actor-graph agent-relevance filter", () => { function actorGraph(scriptText: string) {
  338. const result = analyzeWorkflowScript(scriptText);
  339. expect(result.diagnostics).toEqual([]);
  340. const graph = result.graph;
  341. if (graph === undefined) throw new Error("expected a graph for a clean script");
  342. return toActorGraph(graph);
  343. }
  344. it("drops endpoint-to-endpoint edges and prunes the now-isolated workspace", () => {
  345. // The glob result flows straight into the return (world-read -> sink), which
  346. // projects to `workspace -> sink` — an endpoint-to-endpoint edge that the filter
  347. // drops; the independent ask keeps its source/sink edges.
  348. const graph = actorGraph(`
  349. const raw = await files.glob("*.md");
  350. const out = await agent("w").ask<string>("go");
  351. return [raw, out];
  352. `);
  353. const ids = graph.nodes.map((node) => node.id);
  354. expect(graph.edges.some((edge) => edge.from === "workspace")).toBe(false);
  355. // workspace's only projected edge was the dropped workspace -> sink, so the now
  356. // edge-less workspace endpoint is pruned; the actor lane is untouched.
  357. expect(ids).not.toContain("workspace");
  358. expect(ids).toContain("actor#1");
  359. expect(graph.edges).toContainEqual({ count: 1, exact: true, from: "source", to: "actor#1" });
  360. // The ask's `string` artifact type rides the actor#1 -> sink edge as a message type.
  361. expect(graph.edges).toContainEqual({ count: 1, exact: true, from: "actor#1", to: "sink", types: ["string"] });
  362. });
  363. });
  364. // Producer-side artifact types (docs/analysis.md, "Edge attributes"): every
  365. // data edge's `from` is a producer with a statically known artifact type, recorded on
  366. // the node, resolved onto the edge (port-refined out of a join), and aggregated as the
  367. // message types of the derived actor edge.
  368. describe("artifact types", () => {
  369. function analyze(scriptText: string): SiteGraph {
  370. const result = analyzeWorkflowScript(scriptText);
  371. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  372. const graph = result.graph;
  373. if (graph === undefined) throw new Error("expected a graph for a clean script");
  374. return graph;
  375. }
  376. const nodeType = (graph: SiteGraph, id: string): string | undefined =>
  377. graph.nodes.find((node) => node.id === id)?.artifactType;
  378. const findEdge = (graph: SiteGraph, from: string, to: string, port?: number): SiteEdge | undefined =>
  379. graph.edges.find((e) => e.kind === "data" && e.from === from && e.to === to && e.port === port);
  380. it("labels producer nodes and data edges with named / default / glob types", () => {
  381. const graph = analyze(`
  382. interface Flaky { findings: string[]; }
  383. const a = await agent("s").ask<Flaky>("f");
  384. const b = await agent("p").ask("plan");
  385. const g = await files.glob("*.ts");
  386. const out = await agent("c").ask<string>(\`\${a.findings} \${b} \${g}\`);
  387. return out;
  388. `);
  389. // Named interface prints as its NAME, not a structural expansion.
  390. expect(nodeType(graph, "ask#1")).toBe("Flaky");
  391. expect(nodeType(graph, "ask#2")).toBe("string"); // default T = string, no type argument
  392. expect(nodeType(graph, "world-read#1")).toBe("string[]");
  393. expect(findEdge(graph, "ask#1", "ask#3")?.type).toBe("Flaky");
  394. expect(findEdge(graph, "world-read#1", "ask#3")?.type).toBe("string[]");
  395. });
  396. it("port-refines a join's outgoing edges and takes producer whole types into a join", () => {
  397. const graph = analyze(`
  398. interface Draft { body: string; }
  399. interface Verdict { approved: boolean; }
  400. const worker = agent("worker");
  401. const [x, y] = await Promise.all([worker.ask<Draft>("a"), worker.ask<Verdict>("b")]);
  402. const z = await agent("c").ask<string>(\`\${x.body} \${y.approved}\`);
  403. return z;
  404. `);
  405. // Edges OUT of the join are refined to the selected element's type.
  406. expect(findEdge(graph, "join#1", "ask#3", 0)?.type).toBe("Draft");
  407. expect(findEdge(graph, "join#1", "ask#3", 1)?.type).toBe("Verdict");
  408. // Edges INTO the join carry the producer's (from-side) whole type, not a port lookup.
  409. expect(findEdge(graph, "ask#1", "join#1", 0)?.type).toBe("Draft");
  410. expect(findEdge(graph, "ask#2", "join#1", 1)?.type).toBe("Verdict");
  411. // The two same-actor producers collapse into one actor edge aggregating both types.
  412. const actor = toActorGraph(graph);
  413. expect(actor.edges.find((e) => e.from === "actor#1" && e.to === "actor#2")?.types).toEqual([
  414. "Draft",
  415. "Verdict",
  416. ]);
  417. });
  418. it("omits an uninformative (void) fan-out type", () => {
  419. const graph = analyze(`
  420. const paths = await files.glob("*.ts");
  421. paths.forEach((p) => { void agent("w").ask<string>(p); });
  422. return paths.length;
  423. `);
  424. const fanout = graph.nodes.find((node) => node.kind === "fan-out");
  425. expect(fanout).toBeDefined();
  426. expect(fanout?.artifactType).toBeUndefined(); // forEach result is `void` -> no label
  427. });
  428. it("unwraps the facade wrapper through nested fan-out array levels", () => {
  429. const graph = analyze(`
  430. const rows = await files.glob("*.md");
  431. const out = rows.map((r) => [r].map((c) => agent("w").ask<string>(c)));
  432. return out;
  433. `);
  434. // The outer map's collected type is Node<string>[][]; both array levels and the
  435. // Node<> wrapper peel, so the label is string[][] — never Node<...>.
  436. const fanouts = graph.nodes.filter((node) => node.kind === "fan-out");
  437. expect(fanouts.some((f) => f.artifactType === "string[][]")).toBe(true);
  438. expect(fanouts.every((f) => !(f.artifactType ?? "").includes("Node<"))).toBe(true);
  439. });
  440. it("escapes embedded quotes in serialized message and producer types", () => {
  441. const graph = analyze(`
  442. const a = agent("a");
  443. const decision = await a.ask<"yes" | "no">("decide");
  444. const out = await a.ask<string>(\`route \${decision}\`);
  445. return out;
  446. `);
  447. // Site node/edge type= and actor-edge types= all escape embedded quotes as \\".
  448. const site = serializeGraph(graph);
  449. // The ask#1 producer node and its outgoing data edge both carry the escaped union.
  450. expect(site).toContain('node ask#1 "a" ');
  451. expect(site).toContain('type="\\"yes\\" | \\"no\\""');
  452. const actor = serializeActorGraph(toActorGraph(graph));
  453. expect(actor).toContain('types="\\"yes\\" | \\"no\\""'); // self-edge message on actor#1
  454. });
  455. });
  456. // The facade-siting rule (docs/analysis.md, "Diagnostics"): facade
  457. // callables are second-class and may appear only as the callee of a
  458. // direct call. Any escape into value space — aliasing, method extraction, `.bind`,
  459. // passing a facade function as an argument, a computed member call — has no site and
  460. // is rejected. The diagnostic surfaces through analyzeWorkflowScript with ok=false
  461. // and no graph, exactly like a typechecker diagnostic.
  462. describe("facade-siting diagnostics", () => {
  463. // Asserts a rejection carrying a diagnostic that names `name` at `line:column`. The
  464. // reference scan and the defense-in-depth pass can both flag one escape (the second
  465. // is a redundant safety net), so we assert the specific diagnostic is present rather
  466. // than pin the total count.
  467. function expectRejected(
  468. script: string,
  469. expected: { column: number; line: number; name: string },
  470. ): void {
  471. const result = analyzeWorkflowScript(script);
  472. expect(result.ok).toBe(false);
  473. expect(result.graph).toBeUndefined();
  474. const match = result.diagnostics.find(
  475. (d) => d.line === expected.line && d.column === expected.column,
  476. );
  477. expect(
  478. match,
  479. `expected a diagnostic at ${expected.line}:${expected.column}; got ${JSON.stringify(result.diagnostics)}`,
  480. ).toBeDefined();
  481. expect(match?.code).toBe(FACADE_SITING_CODE);
  482. expect(match?.message).toContain(`facade function '${expected.name}' may only be called directly`);
  483. }
  484. function expectAccepted(script: string): void {
  485. const result = analyzeWorkflowScript(script);
  486. expect(result.diagnostics).toEqual([]);
  487. expect(result.ok).toBe(true);
  488. expect(result.graph).toBeDefined();
  489. }
  490. it("rejects const-aliasing the agent factory (const spawn = agent)", () => {
  491. expectRejected(
  492. `const spawn = agent;\nconst worker = spawn("worker");\nconst a = await worker.ask<string>("task A");\nreturn a;`,
  493. { column: 15, line: 1, name: "agent" },
  494. );
  495. });
  496. it("rejects extracting an ask method (const f = planner.ask)", () => {
  497. expectRejected(
  498. `const planner = agent("planner");\nconst f = planner.ask;\nconst out = await f("go");\nreturn out;`,
  499. { column: 19, line: 2, name: "ask" },
  500. );
  501. });
  502. it("rejects .bind on an ask method (const g = reviewer.ask.bind(reviewer))", () => {
  503. // The inner `reviewer.ask` is a non-callee reference (it is the receiver of `.bind`).
  504. expectRejected(
  505. `const reviewer = agent("reviewer");\nconst g = reviewer.ask.bind(reviewer);\nconst review = await g("review");\nreturn review;`,
  506. { column: 20, line: 2, name: "ask" },
  507. );
  508. });
  509. it("rejects a parenthesized callee ((planner.ask)(…)) — deliberate conservatism", () => {
  510. // Semantically `(planner.ask)("write")` is still a direct method call (parentheses
  511. // preserve the reference), but "direct" in the siting rule is syntactic: the site
  512. // collector does not see through the parens, so allowing the form would leave the
  513. // call unsited. Rejecting errs on the safe side for a form with no reason to exist.
  514. expectRejected(
  515. `const planner = agent("planner");\nconst draft = await (planner.ask)("write");\nreturn draft;`,
  516. { column: 30, line: 2, name: "ask" },
  517. );
  518. });
  519. it("rejects a non-null-asserted callee (planner.ask!(…)) — same conservatism", () => {
  520. // The callee is a NonNullExpression, not a PropertyAccess, so the collector never
  521. // sites the call; the reference scan flags `planner.ask` in non-callee position
  522. // (and the defense-in-depth pass redundantly flags the unsited facade call).
  523. expectRejected(
  524. `const planner = agent("planner");\nconst out = await planner.ask!("go");\nreturn out;`,
  525. { column: 27, line: 2, name: "ask" },
  526. );
  527. });
  528. it("rejects an as-any-cast callee ((planner.ask as any)(…))", () => {
  529. // Casting to `any` erases the call signature, blinding the defense-in-depth pass —
  530. // the reference scan is what still resolves `planner.ask` to the facade method
  531. // symbol in non-callee position and rejects the escape.
  532. expectRejected(
  533. `const planner = agent("planner");\nconst out = await (planner.ask as any)("go");\nreturn out;`,
  534. { column: 28, line: 2, name: "ask" },
  535. );
  536. });
  537. it("rejects a conditional-expression callee ((flag ? files.read : files.glob)(…))", () => {
  538. // A dynamically-selected facade FUNCTION (unlike a dynamically-selected ask
  539. // receiver, which is accepted below): the callee is a ConditionalExpression, so
  540. // neither branch's call would be sited; both branch references are flagged.
  541. expectRejected(
  542. `const flag = "x".length > 1;\nconst c = await (flag ? files.read : files.glob)("ws/x");\nreturn c.length;`,
  543. { column: 31, line: 2, name: "read" },
  544. );
  545. });
  546. it("rejects passing files.read as a callback argument", () => {
  547. expectRejected(
  548. `const paths = await files.glob("*.ts");\nconst bodies = await Promise.all(paths.map(files.read));\nreturn bodies.join("");`,
  549. { column: 50, line: 2, name: "read" },
  550. );
  551. });
  552. it("rejects passing log as a callback argument", () => {
  553. expectRejected(
  554. `const items = ["a", "b"];\nitems.forEach(log);\nconst out = await agent("a").ask<string>("go");\nreturn out;`,
  555. { column: 15, line: 2, name: "log" },
  556. );
  557. });
  558. it("rejects a computed facade call the collector cannot site (defense in depth)", () => {
  559. // `files["read"](x)` has no callee symbol for the reference scan and never
  560. // registers as a world-read site; the signature-resolved defense-in-depth pass
  561. // catches it. It is the sole diagnostic — the reference scan sees nothing here.
  562. const result = analyzeWorkflowScript(`const body = await files["read"]("x");\nreturn body;`);
  563. expect(result.ok).toBe(false);
  564. expect(result.diagnostics).toHaveLength(1);
  565. expect(result.diagnostics[0]).toMatchObject({
  566. code: FACADE_SITING_CODE,
  567. column: 20,
  568. line: 1,
  569. });
  570. expect(result.diagnostics[0]?.message).toContain("facade function 'read'");
  571. });
  572. it("accepts a dynamically-selected ask receiver (ternary)", () => {
  573. // The spec allows dynamic receivers; it is the function VALUE that must not escape.
  574. expectAccepted(
  575. `const a = agent("a");\nconst b = agent("b");\nconst useA = Math.random() > 0.5;\nconst out = await (useA ? a : b).ask<string>("go");\nreturn out;`,
  576. );
  577. });
  578. it("accepts an agent-array indexed receiver", () => {
  579. expectAccepted(
  580. `const agents = [agent("a"), agent("b")];\nconst out = await agents[0]!.ask<string>("go");\nreturn out;`,
  581. );
  582. });
  583. it("accepts binding the files object and calling through it (still sites)", () => {
  584. // Binding the `files` OBJECT (not a callable) is allowed: `f.read(...)` still
  585. // resolves to the facade method and registers as a world-read site.
  586. expectAccepted(`const f = files;\nconst body = await f.read("x");\nreturn body;`);
  587. });
  588. it("accepts a clean planner-reviewer control script", () => {
  589. expectAccepted(
  590. `const planner = agent("planner");\nconst draft = await planner.ask<string>("draft");\nconst reviewer = agent("reviewer");\nconst review = await reviewer.ask<string>(\`review: \${draft}\`);\nreturn review;`,
  591. );
  592. });
  593. // Round-2 hardening: destructuring EXTRACTION of a facade callable. A shorthand
  594. // binding identifier resolves to the freshly-declared local, so the plain identifier
  595. // scan is blind to it; the fix flags at the extraction site by resolving the source
  596. // property on the destructured value's type. See docs "Diagnostics".
  597. it("rejects shorthand destructuring of an ask method (const { ask } = planner)", () => {
  598. expectRejected(
  599. `const planner = agent("planner");\nconst { ask } = planner;\nconst topics = ["a", "b", "c"];\nconst answers = await Promise.all(topics.map(ask));\nreturn answers.join("\\n");`,
  600. { column: 9, line: 2, name: "ask" },
  601. );
  602. });
  603. it("rejects shorthand destructuring of files.read behind a bare .map callback", () => {
  604. // The dossier bypass: `const { read } = files` launders the facade method into an
  605. // opaque local, and `paths.map(read)` keeps it out of direct-callee position, so
  606. // both the pre-fix passes missed it. Now rejected at the extraction.
  607. expectRejected(
  608. `const { read } = files;\nconst paths = await files.glob("src/**/*.ts");\nconst bodies = await Promise.all(paths.map(read));\nreturn bodies.join("\\n");`,
  609. { column: 9, line: 1, name: "read" },
  610. );
  611. });
  612. it("rejects a renamed destructuring binding ({ ask: myAsk })", () => {
  613. expectRejected(
  614. `const planner = agent("planner");\nconst { ask: myAsk } = planner;\nconst out = await myAsk("go");\nreturn out;`,
  615. { column: 9, line: 2, name: "ask" },
  616. );
  617. });
  618. it("rejects a nested destructuring pattern ({ a: { ask } })", () => {
  619. expectRejected(
  620. `const planner = agent("planner");\nconst box = { a: planner };\nconst { a: { ask } } = box;\nconst out = await ask("go");\nreturn out;`,
  621. { column: 14, line: 3, name: "ask" },
  622. );
  623. });
  624. it("rejects destructuring an ask method in parameter position (function f({ ask }: Agent))", () => {
  625. expectRejected(
  626. `async function f({ ask }: Agent): Promise<string> {\n return await ask("go");\n}\nconst planner = agent("planner");\nreturn await f(planner);`,
  627. { column: 20, line: 1, name: "ask" },
  628. );
  629. });
  630. it("rejects a destructuring assignment onto a pre-declared var (({ ask } = planner))", () => {
  631. expectRejected(
  632. `const planner = agent("planner");\nlet ask: Agent["ask"];\n({ ask } = planner);\nconst out = await ask("go");\nreturn out;`,
  633. { column: 4, line: 3, name: "ask" },
  634. );
  635. });
  636. it("rejects a destructured facade method routed through a script-locally-typed helper", () => {
  637. // Dossier repro 3: routing the extracted `read` through `run(fn: (p) => …)` (a
  638. // script-local function type) defeats the defense-in-depth signature check. Flagging
  639. // at the `const { read } = files` extraction rejects it before the indirection matters.
  640. expectRejected(
  641. `const { read } = files;\nfunction run(fn: (p: string) => Promise<string>): Promise<string> {\n return fn("config.json");\n}\nconst body = await run(read);\nreturn body;`,
  642. { column: 9, line: 1, name: "read" },
  643. );
  644. });
  645. it("accepts destructuring a non-facade member (the length of an ask result)", () => {
  646. // Only facade CALLABLES are second-class; destructuring the RESULT of an ask (a plain
  647. // string) is ordinary data flow and must stay accepted.
  648. expectAccepted(
  649. `const planner = agent("planner");\nconst { length } = await planner.ask<string>("x");\nreturn String(length);`,
  650. );
  651. });
  652. it("accepts destructuring a plain (non-facade) object", () => {
  653. // `const { o } = wrap` off a plain object binds a live field, not a facade callable —
  654. // this is the destructure-alias fixture shape and must not start rejecting.
  655. expectAccepted(
  656. `const wrap = { o: { f: "" } };\nconst { o } = wrap;\nconst secret = await agent("writer").ask<string>("secret");\no.f = secret;\nconst out = await agent("reader").ask<string>(\`use \${wrap.o.f}\`);\nreturn out;`,
  657. );
  658. });
  659. // Round-3 hardening (CRITICAL): structural retyping launders facade symbols.
  660. // TypeScript resolves members by declared type, so casting or parameter-typing a
  661. // facade value to a structurally-compatible LOCAL interface makes `.ask` / `.read`
  662. // resolve to the local declaration — the reference scan sees a non-facade symbol and
  663. // the defense-in-depth pass's resolved signature points at the local type, so neither
  664. // pre-fix pass fires and the real facade call runs UNSITED. The retyping-boundary pass
  665. // flags the conversion of a value carrying a facade site member to a type carrying none.
  666. it("rejects casting the agent receiver to a local interface (planner as Askable)", () => {
  667. expectRejected(
  668. `interface Askable { ask(instructions: string): PromiseLike<string>; }\nconst planner = agent("planner");\nconst seed = await agent("seed").ask<string>("seed");\nconst disguised = planner as Askable;\nconst out = await disguised.ask(\`route \${seed}\`);\nreturn out;`,
  669. { column: 19, line: 4, name: "ask" },
  670. );
  671. });
  672. it("rejects passing the agent into a locally-typed helper parameter (run(a: Askable))", () => {
  673. expectRejected(
  674. `interface Askable { ask(instructions: string): PromiseLike<string>; }\nfunction run(a: Askable, p: string): PromiseLike<string> {\n return a.ask(\`route \${p}\`);\n}\nconst planner = agent("planner");\nconst seed = await agent("seed").ask<string>("seed");\nconst out = await run(planner, seed);\nreturn out;`,
  675. { column: 23, line: 7, name: "ask" },
  676. );
  677. });
  678. it("rejects casting the files object to a local reader interface (files as Reader)", () => {
  679. expectRejected(
  680. `interface Reader { read(path: string): Promise<string>; }\nconst seed = await agent("seed").ask<string>("pick a path");\nconst fs = files as Reader;\nconst contents = await fs.read(\`workspace/\${seed}\`);\nconst out = await agent("consumer").ask<string>(\`use \${contents}\`);\nreturn out;`,
  681. { column: 12, line: 3, name: "read" },
  682. );
  683. });
  684. it("accepts retyping an ask RESULT (a Node/awaited value carries no site member)", () => {
  685. // The retyping boundary keys on the site member, not on any facade-declared symbol:
  686. // `Node<T>` exposes only `then` and the awaited value is a primitive, so annotating or
  687. // passing an ask result is ordinary data flow and must stay accepted.
  688. expectAccepted(
  689. `const planner = agent("planner");\nconst n: PromiseLike<string> = planner.ask<string>("x");\nconst s: string = await n;\nreturn s;`,
  690. );
  691. });
  692. it("accepts generic passthrough of the agent handle (identity<T>(x: T))", () => {
  693. // The instantiated parameter type IS `Agent` (facade), so `.ask` still resolves to the
  694. // facade site — no laundering, no diagnostic. Uses resolved/contextual types, not the
  695. // raw generic, so this legitimate pattern is not over-rejected.
  696. expectAccepted(
  697. `function identity<T>(x: T): T {\n return x;\n}\nconst planner = identity(agent("planner"));\nconst out = await planner.ask<string>("go");\nreturn out;`,
  698. );
  699. });
  700. // Round-3 hardening: the same laundering through an ASSIGNMENT into an already-typed
  701. // slot rather than a declaration/cast/parameter. `let d: Askable; d = planner` is the
  702. // first thing anyone writes; without the assignment-boundary arm the reassigned handle
  703. // runs `.ask` unsited exactly like the cast form.
  704. it("rejects assigning the agent into a locally-typed binding (d = planner)", () => {
  705. expectRejected(
  706. `interface Askable { ask(instructions: string): PromiseLike<string>; }\nconst planner = agent("planner");\nlet d: Askable = { ask: async (s: string) => s };\nd = planner;\nconst out = await d.ask("go");\nreturn out;`,
  707. { column: 5, line: 4, name: "ask" },
  708. );
  709. });
  710. it("rejects assigning the agent into a locally-typed property (slot.a = planner)", () => {
  711. expectRejected(
  712. `interface Askable { ask(instructions: string): PromiseLike<string>; }\nconst planner = agent("planner");\nconst slot: { a: Askable } = { a: { ask: async (s: string) => s } };\nslot.a = planner;\nconst out = await slot.a.ask("go");\nreturn out;`,
  713. { column: 10, line: 4, name: "ask" },
  714. );
  715. });
  716. it("rejects assigning the agent into a locally-typed array element (arr[0] = planner)", () => {
  717. expectRejected(
  718. `interface Askable { ask(instructions: string): PromiseLike<string>; }\nconst planner = agent("planner");\nconst arr: Askable[] = [{ ask: async (s: string) => s }];\narr[0] = planner;\nconst out = await arr[0]!.ask("go");\nreturn out;`,
  719. { column: 10, line: 4, name: "ask" },
  720. );
  721. });
  722. it("accepts an evolving-any binding assigned an agent (let x; x = agent(...))", () => {
  723. // An un-annotated `let` narrows to `Agent` at the use, so `.ask` still resolves to the
  724. // facade and the call IS sited — this is not a laundering boundary, only an explicit
  725. // `: any`/`: unknown` annotation is. The assignment-boundary arm must not flag it.
  726. expectAccepted(`let x;\nx = agent("planner");\nconst out = await x.ask<string>("go");\nreturn out;`);
  727. });
  728. // ————————————————————————————————————————————————————————————————
  729. // The git.log / log() collision (docs/execution-engine.md, "The world-read registry")
  730. // ————————————————————————————————————————————————————————————————
  731. // These are the tests that would have caught a bare-name implementation of the
  732. // registry. `git.log` and the top-level `log` share a member name and nothing else:
  733. // one is a world-read site subject to the facade-siting rule, the other is chatter
  734. // that is deliberately outside it. A name-keyed rule has to get one of them wrong.
  735. it("accepts a script calling both git.log and the top-level log", () => {
  736. // The positive half of the collision: both spellings, in one script, both legal.
  737. // A bare-name set that included `log` would mint a world-read site for every progress
  738. // message; one that excluded it would leave `git.log` unsited — and a facade call with
  739. // no site has no journal key, which is the unsoundness the siting rule exists to stop.
  740. expectAccepted(
  741. `log("starting");\nconst commits = await git.log(5);\nlog(\`saw \${commits.length}\`);\nconst out = await agent("a").ask<string>(commits.map((c) => c.subject).join("; "));\nreturn out;`,
  742. );
  743. });
  744. it("rejects aliasing git.log while the plain log stays legal in the same script", () => {
  745. // `const l = git.log` is method extraction, exactly like `const f = planner.ask`.
  746. // The diagnostic names 'log' — resolved from the SYMBOL, so it is git's member, not
  747. // the top-level function that appears untouched two lines later.
  748. expectRejected(
  749. `const l = git.log;\nlog("still fine");\nconst commits = await l(5);\nreturn commits.length;`,
  750. { column: 15, line: 1, name: "log" },
  751. );
  752. });
  753. it("accepts passing the top-level log's own name around as a direct call target only", () => {
  754. // Sanity in the other direction: the top-level `log` is still second-class (already
  755. // covered above by the `items.forEach(log)` rejection), but a direct call is legal
  756. // even in a script that also holds a git world read. This pins that `git.log`'s
  757. // arrival did not accidentally pull the top-level `log` into world-read siting.
  758. const result = analyzeWorkflowScript(
  759. `const s = await git.status();\nlog(\`clean=\${s.clean}\`);\nreturn s.branch ?? "detached";`,
  760. );
  761. expect(result.diagnostics).toEqual([]);
  762. const table = collectSites(createWorkflowProgram(
  763. `const s = await git.status();\nlog(\`clean=\${s.clean}\`);\nreturn s.branch ?? "detached";`,
  764. ));
  765. expect(table.worldReads.map((site) => site.op)).toEqual(["git-status"]);
  766. });
  767. it("rejects aliasing files.grep", () => {
  768. expectRejected(
  769. `const g = files.grep;\nconst hits = await g("TODO");\nreturn hits.length;`,
  770. { column: 17, line: 1, name: "grep" },
  771. );
  772. });
  773. it("rejects computed access to the new members (defense in depth)", () => {
  774. // Computed member access has no callee symbol for the reference scan and never
  775. // registers as a site; the signature-resolved defense-in-depth pass is the only
  776. // thing between `files["grep"](p)` and an unsited world read.
  777. expectRejected(`const hits = await files["grep"]("TODO");\nreturn hits.length;`, {
  778. column: 20,
  779. line: 1,
  780. name: "grep",
  781. });
  782. expectRejected(`const s = await git["status"]();\nreturn s.clean;`, {
  783. column: 17,
  784. line: 1,
  785. name: "status",
  786. });
  787. expectRejected(`const c = await git["log"](3);\nreturn c.length;`, {
  788. column: 17,
  789. line: 1,
  790. name: "log",
  791. });
  792. });
  793. it("rejects retyping the git container to a structurally-compatible local type", () => {
  794. // The laundering shape from round 3, applied to the new container: the local
  795. // interface's `log` resolves to the LOCAL declaration, so the call would run unsited.
  796. expectRejected(
  797. `interface Historian { log(n?: number): Promise<{ hash: string; subject: string; author: string; date: string }[]>; }\nconst h = git as Historian;\nconst commits = await h.log(3);\nreturn commits.length;`,
  798. { column: 11, line: 2, name: "log" },
  799. );
  800. });
  801. it("accepts binding the git object and calling through it (still sites)", () => {
  802. // Binding the CONTAINER (not a callable) is allowed, same as `const f = files`:
  803. // `g.status()` still resolves to the facade method and registers as a world read.
  804. expectAccepted(`const g = git;\nconst s = await g.status();\nreturn s.clean;`);
  805. });
  806. it("accepts a script-local object that merely shares the git member names", () => {
  807. // Identity is declaration-based, so a hand-rolled `myGit.log()` is ordinary code.
  808. expectAccepted(
  809. `const myGit = { log(n: number): number { return n; }, status(): string { return "clean"; } };\nreturn myGit.status() + String(myGit.log(1));`,
  810. );
  811. });
  812. });
  813. // report 站点(execution-engine.md 的 "Progressive results",docs/analysis.md 的
  814. // 「Sites」)。三件事在这里钉住:站点身份存在且有自己的
  815. // per-kind 计数器、facade-siting 规则确实约束它、以及它对两张图**完全没有**影响。
  816. describe("report sites", () => {
  817. const table = (scriptText: string) => collectSites(createWorkflowProgram(scriptText));
  818. it("mints report#N on its own per-kind counter and captures the item expression", () => {
  819. const t = table(
  820. `report("one");\nconst out = await agent("a").ask<string>("go");\nreport({ out });\nreturn out;`,
  821. );
  822. expect(t.reports.map((site) => site.id)).toEqual(["report#1", "report#2"]);
  823. // 实参被捕获(编译侧的可序列化检查读它),但**不进** taint 的 sink 集合。
  824. expect(t.reports.every((site) => site.item !== undefined)).toBe(true);
  825. expect(t.reports[0]?.loc).toEqual({ column: 1, line: 1 });
  826. });
  827. it("leaves every other per-kind id counter bit-for-bit unchanged", () => {
  828. // 站点 id 稳定性规则真正保护的那条不变式:report 有自己的计数器,所以在 ask 之间插
  829. // report 不会挪动任何 ask#N / actor#N / world-read#N。它只消耗全局 `order` 发现序,
  830. // 而 order 只是输出的归并键(execution-engine.md 的 "Site-id stability")。
  831. const withoutReports = table(
  832. `const a = agent("a");\nconst paths = await files.glob("src/**");\nconst x = await a.ask<string>("1");\nconst y = await a.ask<string>("2");\nreturn [x, y, paths.length];`,
  833. );
  834. const withReports = table(
  835. `const a = agent("a");\nreport("start");\nconst paths = await files.glob("src/**");\nreport({ n: paths.length });\nconst x = await a.ask<string>("1");\nreport(x);\nconst y = await a.ask<string>("2");\nreturn [x, y, paths.length];`,
  836. );
  837. const ids = (t: ReturnType<typeof table>) => ({
  838. actors: t.actors.map((s) => s.id),
  839. asks: t.asks.map((s) => s.id),
  840. worldReads: t.worldReads.map((s) => s.id),
  841. });
  842. expect(ids(withReports)).toEqual(ids(withoutReports));
  843. expect(withReports.reports.map((s) => s.id)).toEqual(["report#1", "report#2", "report#3"]);
  844. expect(withoutReports.reports).toEqual([]);
  845. });
  846. it("mints no report site for a script-local function of the same name", () => {
  847. // 身份按声明判定,与 registry 的其余部分一致。
  848. const t = table(
  849. `const report = (item: unknown): void => { void item; };\nreport({ a: 1 });\nreturn 1;`,
  850. );
  851. expect(t.reports).toEqual([]);
  852. });
  853. it("draws no node and no edge in either graph", () => {
  854. // report 发的是进度而不是次序:没有什么能等它,也就没有什么可以让一条边去表示。
  855. const result = analyzeWorkflowScript(
  856. `const a = agent("a");\nconst out = await a.ask<string>("go");\nreport({ out });\nreturn out;`,
  857. );
  858. expect(result.ok).toBe(true);
  859. const text = serializeGraph(result.graph!);
  860. expect(text).not.toContain("report");
  861. expect(result.graph!.nodes.some((n) => n.id.startsWith("report#"))).toBe(false);
  862. expect(result.graph!.edges.some((e) => e.from.startsWith("report#") || e.to.startsWith("report#"))).toBe(false);
  863. expect(result.causality!.steps.some((s) => s.id.startsWith("report#"))).toBe(false);
  864. });
  865. it("leaves all three serialized graphs byte-identical when reports are added between asks", () => {
  866. // 上一条证明 report 不画自己,这一条证明它不**扰动**别人——包括实参没有被当作 sink
  867. // (否则 `plan` 流进 report 会多出一条 data 边)。这是那条排除规则最容易悄悄破掉的一半。
  868. const base =
  869. `interface Plan { steps: string[]; }\nconst p = agent("p");\nconst r = agent("r");\nconst plan = await p.ask<Plan>("draft");\nconst first = await r.ask<string>(plan.steps[0] ?? "x");\nreturn first;`;
  870. const reported =
  871. `interface Plan { steps: string[]; }\nconst p = agent("p");\nconst r = agent("r");\nconst plan = await p.ask<Plan>("draft");\nreport(plan);\nreport({ n: plan.steps.length });\nconst first = await r.ask<string>(plan.steps[0] ?? "x");\nreport(first);\nreturn first;`;
  872. const a = analyzeWorkflowScript(base);
  873. const b = analyzeWorkflowScript(reported);
  874. expect(a.ok && b.ok).toBe(true);
  875. // 位置行号会因插入的行而变,所以比对的是去掉 @line:col 之后的图结构。
  876. const strip = (text: string): string => text.replace(/ @\d+:\d+/g, "");
  877. expect(strip(serializeGraph(b.graph!))).toBe(strip(serializeGraph(a.graph!)));
  878. expect(strip(serializeActorGraph(toActorGraph(b.graph!)))).toBe(
  879. strip(serializeActorGraph(toActorGraph(a.graph!))),
  880. );
  881. });
  882. });
  883. // report 落在 facade-siting 规则的**产生站点**那一半(而不是 log 那一半仅受限的半边):
  884. // 它有一行按站点建键的 journal,所以身份论证对它完全成立(docs/analysis.md)。
  885. describe("report facade-siting", () => {
  886. it("rejects const-aliasing report (const r = report)", () => {
  887. const result = analyzeWorkflowScript(`const r = report;\nr({ a: 1 });\nreturn 1;`);
  888. expect(result.ok).toBe(false);
  889. expect(result.graph).toBeUndefined();
  890. const match = result.diagnostics.find((d) => d.line === 1 && d.column === 11);
  891. expect(match?.code).toBe(FACADE_SITING_CODE);
  892. expect(match?.message).toContain("facade function 'report' may only be called directly");
  893. });
  894. it("rejects passing report as an argument", () => {
  895. const result = analyzeWorkflowScript(
  896. `function emit(f: (item: unknown) => void): void { f({ a: 1 }); }\nemit(report);\nreturn 1;`,
  897. );
  898. expect(result.ok).toBe(false);
  899. expect(result.diagnostics.some((d) => d.code === FACADE_SITING_CODE)).toBe(true);
  900. });
  901. it("accepts a direct report call (no misuse diagnostic for the sited form)", () => {
  902. // 反向防线:report 加入产生站点的清单之后,**普通用法**绝不能被 pass 2 误伤——
  903. // 那一趟拒绝的是"产生站点却没被 site 掉"的调用,所以站点表必须收录 report。
  904. const result = analyzeWorkflowScript(
  905. `const a = agent("a");\nconst out = await a.ask<string>("go");\nreport({ out });\nlog("done");\nreturn out;`,
  906. );
  907. expect(result.diagnostics).toEqual([]);
  908. expect(result.ok).toBe(true);
  909. });
  910. });