graphs.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { readdirSync, readFileSync } from "node:fs";
  2. import { dirname, join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import { describe, expect, it } from "vitest";
  5. import {
  6. actorGraphToMermaid,
  7. analyzeWorkflowScript,
  8. causalityGraphToMermaid,
  9. controlFlowToMermaid,
  10. handoffGraphToMermaid,
  11. phaseFlowToMermaid,
  12. phaseGraphToMermaid,
  13. serializeControlFlow,
  14. serializeCore,
  15. serializeHandoffGraph,
  16. siteGraphToMermaid,
  17. toActorGraph,
  18. type CausalityGraph,
  19. type ControlFlowGraph,
  20. } from "../src/index.js";
  21. import {
  22. serializeActorGraph,
  23. serializeCausalityGraph,
  24. serializeGraph,
  25. } from "../src/analysis/serialize.js";
  26. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  27. // Fixture-driven site-graph tests: every tests/graphs/*.ts file must typecheck
  28. // clean (9006 excepted — see corpusDiagnostics), and its serialized graph is
  29. // snapshotted under tests/graphs/expected/. Four
  30. // derived views are snapshotted alongside: the actor-graph projection as
  31. // <name>.actor.txt (model-facing summary), the causality graph as
  32. // <name>.causality.txt (the GUI's subject; see docs/analysis.md), the
  33. // analysis core as <name>.core.txt (the one artifact every graph projects from;
  34. // see docs/analysis.md — a fusion bug surfaces HERE, not
  35. // only downstream), and the control-flow graph as <name>.cfg.txt (where execution
  36. // can go next; docs/analysis.md).
  37. // Run `pnpm test -- -u` to (re)generate snapshots, then review them by hand.
  38. const graphsDir = join(dirname(fileURLToPath(import.meta.url)), "graphs");
  39. /**
  40. * A `phase("…")` marker call or a `hole<T>(…)` call in the fixture source, ignoring `.phase` /
  41. * `.hole` property reads. A hole is a phase (docs/analysis.md「Sites」), so its presence opens the
  42. * phase vocabulary exactly as a marker does.
  43. */
  44. const MARKER_CALL = /(^|[^.\w])(phase\s*\(|hole\s*<)/;
  45. /**
  46. * The phase vocabulary is ALL-OR-NOTHING, asserted on every fixture in the corpus rather
  47. * than left to the eye on ~205 unchanged snapshots:
  48. *
  49. * - no marker → `phases`, `phaseEdges` and every `Step.phase` absent, which is what makes
  50. * the pre-phase snapshots byte-identical (a regression that emitted `phases: []` instead
  51. * of nothing would pass the snapshots and break the UI's view-switch condition);
  52. * - at least one marker → all three present, and every step carries exactly one phase
  53. * drawn from the phase list — the spec's「划分是全的」invariant, mechanized.
  54. */
  55. function assertPhaseVocabulary(source: string, causality: CausalityGraph, flow: ControlFlowGraph): void {
  56. if (!MARKER_CALL.test(source)) {
  57. expect(causality.phases).toBeUndefined();
  58. expect(causality.phaseEdges).toBeUndefined();
  59. expect(causality.steps.filter((step) => step.phase !== undefined)).toEqual([]);
  60. // The control-flow quotient rides the same all-or-nothing contract.
  61. expect(flow.phases).toBeUndefined();
  62. expect(flow.phaseEdges).toBeUndefined();
  63. return;
  64. }
  65. const phases = causality.phases ?? [];
  66. expect(phases.length).toBeGreaterThan(0);
  67. expect(causality.phaseEdges).toBeDefined();
  68. const ids = new Set(phases.map((phase) => phase.id));
  69. for (const step of causality.steps) {
  70. expect(ids.has(step.phase ?? ""), `step ${step.id} must name a listed phase`).toBe(true);
  71. }
  72. expect(flow.phases).toBeDefined();
  73. expect(flow.phaseEdges).toBeDefined();
  74. const flowIds = new Set((flow.phases ?? []).map((phase) => phase.id));
  75. for (const node of flow.nodes) {
  76. expect(flowIds.has(node.phase), `flow node ${node.id} must name a listed phase`).toBe(true);
  77. }
  78. }
  79. /**
  80. * Fixtures whose script contains a function NO call ever applies. Only such a body may be
  81. * swept to a `detached` region (docs/analysis.md): every function
  82. * value that reaches a call — as callee, through a parameter, or as a callback a library
  83. * invokes — is inlined where it is applied. A new `detached` anywhere else is a call the
  84. * oracle failed to record, i.e. the bug family this pins.
  85. */
  86. const DEAD_CODE_FIXTURES = new Set(["callback-dead-function-sweep"]);
  87. describe("site graph fixtures", () => {
  88. const fixtures = readdirSync(graphsDir)
  89. .filter((name) => name.endsWith(".ts"))
  90. .sort();
  91. it("finds fixtures", () => {
  92. expect(fixtures.length).toBeGreaterThan(0);
  93. });
  94. for (const fixture of fixtures) {
  95. it(fixture, async () => {
  96. const source = readFileSync(join(graphsDir, fixture), "utf8");
  97. const result = analyzeWorkflowScript(source);
  98. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  99. // `ok` 不在这里断言:语料里 26 个 fan-out fixture 用静态 actor 名,那是 9006
  100. // (不可提交但完全可分析,见 tests/helpers/analysis-corpus.ts)。真正的断言是下面
  101. // 两行——图与因果图都必须产出。
  102. const graph = result.graph;
  103. if (graph === undefined) throw new Error("expected a graph for a clean script");
  104. const causality = result.causality;
  105. if (causality === undefined) throw new Error("expected a causality graph for a clean script");
  106. const core = result.core;
  107. if (core === undefined) throw new Error("expected an analysis core for a clean script");
  108. const flow = result.flow;
  109. if (flow === undefined) throw new Error("expected a control-flow graph for a clean script");
  110. const handoff = result.handoff;
  111. if (handoff === undefined) throw new Error("expected a hand-off graph for a clean script");
  112. const base = fixture.replace(/\.ts$/, "");
  113. assertPhaseVocabulary(source, causality, flow);
  114. if (!DEAD_CODE_FIXTURES.has(base)) {
  115. const detached = core.trace.regions.filter((region) => region.detached === true);
  116. expect(detached, `${fixture}: only dead code may be swept to a detached region`).toEqual([]);
  117. }
  118. await expect(serializeGraph(graph)).toMatchFileSnapshot(join(graphsDir, "expected", `${base}.txt`));
  119. await expect(serializeActorGraph(toActorGraph(graph))).toMatchFileSnapshot(
  120. join(graphsDir, "expected", `${base}.actor.txt`),
  121. );
  122. await expect(serializeCausalityGraph(causality)).toMatchFileSnapshot(
  123. join(graphsDir, "expected", `${base}.causality.txt`),
  124. );
  125. await expect(serializeCore(core)).toMatchFileSnapshot(
  126. join(graphsDir, "expected", `${base}.core.txt`),
  127. );
  128. await expect(serializeControlFlow(flow)).toMatchFileSnapshot(
  129. join(graphsDir, "expected", `${base}.cfg.txt`),
  130. );
  131. // Who takes part in each phase and who hands off to whom — the board's second level
  132. // (docs/dynamic-workflow/presentation.md).
  133. await expect(serializeHandoffGraph(handoff, causality.lanes)).toMatchFileSnapshot(
  134. join(graphsDir, "expected", `${base}.handoff.txt`),
  135. );
  136. });
  137. }
  138. });
  139. // Mermaid rendering: snapshot a representative subset only (not the whole corpus).
  140. // Each is hand-justified against the fixture's .txt / .actor.txt / .causality.txt shape.
  141. // `may-set-loop-alternating-receiver` is the regression guard for the symptom that
  142. // motivated lane expansion: under the one-step rule one candidate lane had no homed step,
  143. // the emitter culled it, and a two-player game rendered as a one-player game.
  144. const MERMAID_FIXTURES = [
  145. "planner-reviewer",
  146. "glob-fanout",
  147. "within-fanout",
  148. "join-ports",
  149. "computed-index",
  150. "may-set-loop-alternating-receiver",
  151. ];
  152. describe("mermaid rendering", () => {
  153. for (const base of MERMAID_FIXTURES) {
  154. it(base, async () => {
  155. const source = readFileSync(join(graphsDir, `${base}.ts`), "utf8");
  156. const result = analyzeWorkflowScript(source);
  157. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  158. const graph = result.graph;
  159. const causality = result.causality;
  160. if (graph === undefined || causality === undefined) {
  161. throw new Error("expected graphs for a clean script");
  162. }
  163. await expect(siteGraphToMermaid(graph)).toMatchFileSnapshot(join(graphsDir, "expected", `${base}.site.mmd`));
  164. await expect(actorGraphToMermaid(toActorGraph(graph))).toMatchFileSnapshot(
  165. join(graphsDir, "expected", `${base}.actor.mmd`),
  166. );
  167. await expect(causalityGraphToMermaid(causality)).toMatchFileSnapshot(
  168. join(graphsDir, "expected", `${base}.causality.mmd`),
  169. );
  170. });
  171. }
  172. });
  173. // The phase quotient's mermaid form: one fixture only. The phase vocabulary is a node,
  174. // one arrow form and the sink terminal — far narrower than the step graph's, so the
  175. // motivating example's real shape is the whole surface worth pinning. The control-flow
  176. // quotient of the same fixture sits beside it (.phase-flow.mmd): the two diagrams are
  177. // meant to be read together — "what must precede what" next to "where execution can go".
  178. describe("phase mermaid rendering", () => {
  179. it("phase-jsonl-db", async () => {
  180. const source = readFileSync(join(graphsDir, "phase-jsonl-db.ts"), "utf8");
  181. const result = analyzeWorkflowScript(source);
  182. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  183. const causality = result.causality;
  184. const flow = result.flow;
  185. if (causality === undefined || flow === undefined) throw new Error("expected graphs for a clean script");
  186. await expect(phaseGraphToMermaid(causality)).toMatchFileSnapshot(
  187. join(graphsDir, "expected", "phase-jsonl-db.phase.mmd"),
  188. );
  189. await expect(phaseFlowToMermaid(flow)).toMatchFileSnapshot(
  190. join(graphsDir, "expected", "phase-jsonl-db.phase-flow.mmd"),
  191. );
  192. });
  193. });
  194. // The occurrence-level CFG and the hand-off graph in mermaid form (the portfolio's
  195. // projection switcher, docs/chat/workflow-portfolio.md): three fixtures each, chosen for
  196. // the vocabulary they exercise rather than breadth — the corpus-wide guard is the .cfg.txt
  197. // / .handoff.txt snapshot above; these pin only the drawing conventions.
  198. // - CFG: phase subgraphs + marks + loops/exits/throws (phase-jsonl-db), a recursion SCC
  199. // folded into a `recur` self-loop (control-flow-recursive-helper), may-throw into a catch
  200. // and an uncaught throw to abort (control-flow-throw-in-catch), plus a detached body
  201. // (all-catch).
  202. // - hand-off: phases + literal-cardinality members + typed and back edges
  203. // (handoff-earth-v5), family-to-family fan-in with a `many` card
  204. // (handoff-family-to-family), mutual back edges from a may-set alternation
  205. // (handoff-mayset-two-cards).
  206. const CFG_MERMAID_FIXTURES = [
  207. "phase-jsonl-db",
  208. "control-flow-recursive-helper",
  209. "control-flow-throw-in-catch",
  210. "all-catch",
  211. ];
  212. const HANDOFF_MERMAID_FIXTURES = ["handoff-earth-v5", "handoff-family-to-family", "handoff-mayset-two-cards"];
  213. describe("control-flow mermaid rendering", () => {
  214. for (const base of CFG_MERMAID_FIXTURES) {
  215. it(base, async () => {
  216. const source = readFileSync(join(graphsDir, `${base}.ts`), "utf8");
  217. const result = analyzeWorkflowScript(source);
  218. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  219. const flow = result.flow;
  220. if (flow === undefined) throw new Error("expected a control-flow graph for a clean script");
  221. await expect(controlFlowToMermaid(flow)).toMatchFileSnapshot(join(graphsDir, "expected", `${base}.cfg.mmd`));
  222. });
  223. }
  224. });
  225. describe("hand-off mermaid rendering", () => {
  226. for (const base of HANDOFF_MERMAID_FIXTURES) {
  227. it(base, async () => {
  228. const source = readFileSync(join(graphsDir, `${base}.ts`), "utf8");
  229. const result = analyzeWorkflowScript(source);
  230. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  231. const causality = result.causality;
  232. const handoff = result.handoff;
  233. if (causality === undefined || handoff === undefined) throw new Error("expected graphs for a clean script");
  234. await expect(handoffGraphToMermaid(handoff, causality)).toMatchFileSnapshot(
  235. join(graphsDir, "expected", `${base}.handoff.mmd`),
  236. );
  237. });
  238. }
  239. });