phases.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 { createWorkflowProgram } from "../src/compiler/compile.js";
  6. import { collectSites } from "../src/analysis/sites.js";
  7. import { collectPhaseMarkerDiagnostics, PHASE_MARKER_CODE } from "../src/analysis/phases.js";
  8. import { FACADE_SITING_CODE } from "../src/analysis/facade-misuse.js";
  9. import { analyzeWorkflowScript } from "../src/index.js";
  10. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  11. // phase() 标记的编译面(docs/analysis.md「Phases」):
  12. // 收集(无站点、不占计数器)、诊断(9004 的三条规则)、与 facade-siting 的分工。
  13. const markers = (scriptText: string) => {
  14. const workflow = createWorkflowProgram(scriptText);
  15. const table = collectSites(workflow);
  16. return { diagnostics: collectPhaseMarkerDiagnostics(workflow, table), table, workflow };
  17. };
  18. describe("phase marker collection", () => {
  19. it("collects a marker with its literal name, consuming no site id", () => {
  20. const { table } = markers(`phase("preflight");\nconst a = agent("a");\nreturn 1;`);
  21. expect(table.phases).toHaveLength(1);
  22. expect(table.phases[0]?.name).toBe("preflight");
  23. expect(table.phases[0]?.loc).toEqual({ column: 1, line: 1 });
  24. // 标记不是站点:actor 的 per-kind id 与全局 order 都从"第一个真站点"开始。
  25. expect(table.actors[0]?.id).toBe("actor#1");
  26. expect(table.actors[0]?.order).toBe(0);
  27. });
  28. it("takes a no-substitution template as a name (string-literal-like)", () => {
  29. const { table, diagnostics } = markers(`phase(\`gate\`);\nreturn 1;`);
  30. expect(table.phases[0]?.name).toBe("gate");
  31. expect(diagnostics).toEqual([]);
  32. });
  33. it("leaves name unset but keeps nameExpr when the argument is not a literal", () => {
  34. const { table } = markers(`const n = "gate";\nphase(n);\nreturn 1;`);
  35. expect(table.phases[0]?.name).toBeUndefined();
  36. expect(table.phases[0]?.nameExpr).toBeDefined();
  37. });
  38. it("ignores a script-local function that happens to be named phase", () => {
  39. // 身份按声明判定,与 sites.ts 的其余分支同一机制:别人的 `phase` 是别人的函数。
  40. const { table, diagnostics } = markers(
  41. `function phase(x: number): void { log(\`\${x}\`); }\nphase(1);\nreturn 1;`,
  42. );
  43. expect(table.phases).toEqual([]);
  44. expect(diagnostics).toEqual([]);
  45. });
  46. // site-id stability(docs/analysis.md 的 "Sites"):加标记
  47. // 不许挪动任何站点的 id,**连全局 order 都不许挪**——这比 report 当年的豁免更强,而
  48. // 标记没有 id 可排,所以这条不变量是免费的。这里逐字节比对两份站点表的 (id, order)。
  49. it("moves no site id and no discovery order when markers are added", () => {
  50. const identity = (scriptText: string): string[] => {
  51. const { table } = markers(scriptText);
  52. return [...table.actors, ...table.asks, ...table.reports, ...table.worldReads]
  53. .sort((a, b) => a.order - b.order)
  54. .map((site) => `${site.order}:${site.id}`);
  55. };
  56. const bare =
  57. `const a = agent("a");\n` +
  58. `const paths = await files.glob("*.ts");\n` +
  59. `const x = await a.ask<string>("go");\n` +
  60. `report(x);\n` +
  61. `return paths.length;`;
  62. const annotated =
  63. `phase("preflight");\n` +
  64. `const a = agent("a");\n` +
  65. `const paths = await files.glob("*.ts");\n` +
  66. `phase("work");\n` +
  67. `const x = await a.ask<string>("go");\n` +
  68. `report(x);\n` +
  69. `phase("wrap-up");\n` +
  70. `return paths.length;`;
  71. expect(identity(annotated)).toEqual(identity(bare));
  72. expect(identity(bare)).toEqual(["0:actor#1", "1:world-read#1", "2:ask#1", "3:report#1"]);
  73. });
  74. });
  75. describe("phase marker diagnostics (9004)", () => {
  76. function expectRejected(
  77. scriptText: string,
  78. expected: { column: number; line: number; contains: string },
  79. ): void {
  80. const { diagnostics } = markers(scriptText);
  81. const match = diagnostics.find((d) => d.line === expected.line && d.column === expected.column);
  82. expect(
  83. match,
  84. `expected a 9004 diagnostic at ${expected.line}:${expected.column}; got ${JSON.stringify(diagnostics)}`,
  85. ).toBeDefined();
  86. expect(match?.code).toBe(PHASE_MARKER_CODE);
  87. expect(match?.message).toContain(expected.contains);
  88. }
  89. it("rejects a variable name, positioned on the offending expression", () => {
  90. expectRejected(`const n = "gate";\nphase(n);\nreturn 1;`, {
  91. column: 7,
  92. contains: "compile-time string literal",
  93. line: 2,
  94. });
  95. });
  96. it("rejects a template with holes", () => {
  97. expectRejected(`const i = 1;\nphase(\`round \${i}\`);\nreturn 1;`, {
  98. column: 7,
  99. contains: "compile-time string literal",
  100. line: 2,
  101. });
  102. });
  103. it("rejects an empty name, and one that is only whitespace", () => {
  104. expectRejected(`phase("");\nreturn 1;`, {
  105. column: 7,
  106. contains: "has no name to show",
  107. line: 1,
  108. });
  109. expectRejected(`phase(" \\t ");\nreturn 1;`, {
  110. column: 7,
  111. contains: "has no name to show",
  112. line: 1,
  113. });
  114. });
  115. it("rejects a marker in expression position (a void initializer typechecks)", () => {
  116. expectRejected(`const x = phase("a");\nreturn x;`, {
  117. column: 11,
  118. contains: "must stand alone as its own statement",
  119. line: 1,
  120. });
  121. });
  122. it("rejects markers in both arms of a ternary", () => {
  123. const { diagnostics } = markers(`const f = true;\nf ? phase("a") : phase("b");\nreturn 1;`);
  124. expect(diagnostics).toHaveLength(2);
  125. expect(diagnostics.map((d) => d.column)).toEqual([5, 18]);
  126. for (const diagnostic of diagnostics) {
  127. expect(diagnostic.code).toBe(PHASE_MARKER_CODE);
  128. expect(diagnostic.message).toContain("must stand alone");
  129. }
  130. });
  131. it("reports both rules for one marker that breaks both", () => {
  132. // `const x = phase(n)`:非字面量名 + 非语句位置。作者一次看全要改什么。
  133. const { diagnostics } = markers(`const n = "g";\nconst x = phase(n);\nreturn x;`);
  134. expect(diagnostics).toHaveLength(2);
  135. expect(diagnostics.map((d) => d.code)).toEqual([PHASE_MARKER_CODE, PHASE_MARKER_CODE]);
  136. });
  137. it("accepts valid markers at every legal position (top level, branch, loop body)", () => {
  138. const { diagnostics } = markers(
  139. `phase("preflight");\n` +
  140. `const paths = await files.glob("*.ts");\n` +
  141. `if (paths.length > 0) {\n` +
  142. ` phase("review");\n` +
  143. ` for (const p of paths) {\n` +
  144. ` phase("per-file");\n` +
  145. ` log(p);\n` +
  146. ` }\n` +
  147. `}\n` +
  148. `phase("wrap-up");\n` +
  149. `return paths.length;`,
  150. );
  151. expect(diagnostics).toEqual([]);
  152. });
  153. it("accepts an effect-free marker (block-final, and two in a row)", () => {
  154. // 无效果的标记合法、无害、不诊断(spec 的「无效果 marker」行):块尾标记什么都不认领,
  155. // 连续两个标记里前一个立刻被后一个取代。两者都是陈旧编辑,不是错误。
  156. const { diagnostics } = markers(
  157. `phase("a");\n` +
  158. `phase("b");\n` +
  159. `const paths = await files.glob("*.ts");\n` +
  160. `if (paths.length > 0) {\n` +
  161. ` log("some");\n` +
  162. ` phase("nothing-follows");\n` +
  163. `}\n` +
  164. `return paths.length;`,
  165. );
  166. expect(diagnostics).toEqual([]);
  167. });
  168. });
  169. describe("phase markers in analyzeWorkflowScript", () => {
  170. it("withholds both views on a 9004 diagnostic (ok: false)", () => {
  171. // 与 world.run 的字面量检查同席:诊断非空即**不提交**,图与因果视图一并扣下——
  172. // 半张图比没有图更坏(handler 只在 ok 时才走 submit)。
  173. const result = analyzeWorkflowScript(`const n = "g";\nphase(n);\nreturn 1;`);
  174. expect(result.ok).toBe(false);
  175. expect(result.graph).toBeUndefined();
  176. expect(result.causality).toBeUndefined();
  177. expect(result.diagnostics.map((d) => d.code)).toEqual([PHASE_MARKER_CODE]);
  178. });
  179. it("withholds both views for every 9004 shape, not just the non-literal name", () => {
  180. for (const script of [
  181. `phase("");\nreturn 1;`,
  182. `const x = phase("a");\nreturn x;`,
  183. `const i = 1;\nphase(\`round \${i}\`);\nreturn 1;`,
  184. ]) {
  185. const result = analyzeWorkflowScript(script);
  186. expect(result.ok, script).toBe(false);
  187. expect(result.graph, script).toBeUndefined();
  188. expect(result.causality, script).toBeUndefined();
  189. expect(
  190. result.diagnostics.some((d) => d.code === PHASE_MARKER_CODE),
  191. script,
  192. ).toBe(true);
  193. }
  194. });
  195. it("reports world.run and phase diagnostics from the same run", () => {
  196. const result = analyzeWorkflowScript(
  197. `const cmd = "lean";\nawait world.run(cmd, []);\nphase("");\nreturn 1;`,
  198. );
  199. expect(result.ok).toBe(false);
  200. expect(new Set(result.diagnostics.map((d) => d.code))).toEqual(new Set([9003, 9004]));
  201. });
  202. it("analyzes a marked script cleanly, and the markers change nothing in the graph (WP1)", () => {
  203. // WP1 收集但不投影:阶段词汇表是 WP2。这条钉住「加标记不动因果图」。
  204. const bare = `const a = agent("a");\nconst x = await a.ask<string>("go");\nreturn x;`;
  205. const marked = `phase("work");\nconst a = agent("a");\nconst x = await a.ask<string>("go");\nreturn x;`;
  206. const bareResult = analyzeWorkflowScript(bare);
  207. const markedResult = analyzeWorkflowScript(marked);
  208. expect(markedResult.ok).toBe(true);
  209. expect(markedResult.diagnostics).toEqual([]);
  210. expect(markedResult.graph?.nodes.map((n) => n.id)).toEqual(
  211. bareResult.graph?.nodes.map((n) => n.id),
  212. );
  213. });
  214. it("rejects aliasing the marker via facade-siting (9001), not via 9004", () => {
  215. // `phase` 是 facade 函数声明,所以 misuse pass 1 已经覆盖别名逃逸——9004 那一趟不必
  216. // 重实现它。反过来说:pass 2("产生站点却没被 site 掉")绝不能误伤合法的直接调用,
  217. // 这正是 phase 不进 SITE_PRODUCING_FUNCTIONS 的原因。
  218. const result = analyzeWorkflowScript(`const p = phase;\np("gate");\nreturn 1;`);
  219. expect(result.ok).toBe(false);
  220. expect(result.diagnostics).toHaveLength(1);
  221. expect(result.diagnostics[0]).toMatchObject({
  222. code: FACADE_SITING_CODE,
  223. column: 11,
  224. line: 1,
  225. });
  226. expect(result.diagnostics[0]?.message).toContain("facade function 'phase'");
  227. });
  228. });
  229. /**
  230. * `alongside` against the causality quotient, over the whole corpus (the plan's "Why
  231. * `alongside` is a node fact, not an edge").
  232. *
  233. * The two answer different questions and are computed by different passes: `alongside` is a
  234. * MARK-TIME fact from the control-flow projection ("which phases' strands were still parked
  235. * when this marker ran"), incomparability is a property of the causality quotient ("neither
  236. * phase must precede the other"). The plan's argument is that one implies the other in one
  237. * direction: if B's marker comes after A's on the main line, both phases actually do work,
  238. * and nothing in the quotient orders A before B, then the only way B was entered is WHILE
  239. * A's work was still in flight — so B must say it is alongside A.
  240. *
  241. * Asserted per fixture rather than by eye, in the style of graphs.test.ts, so a fixture that
  242. * grows a phase vocabulary is covered without being named here. The other direction is NOT
  243. * asserted: `alongside` is deliberately flow-insensitive across choice arms, so it may
  244. * over-claim where the quotient has an edge.
  245. */
  246. describe("`alongside` covers every incomparable later phase (property over the whole corpus)", () => {
  247. const graphsDir = join(dirname(fileURLToPath(import.meta.url)), "graphs");
  248. /** A `phase("…")` marker call in the fixture source, ignoring `.phase` property reads. */
  249. const MARKER_CALL = /(^|[^.\w])phase\s*\(/;
  250. const marked = readdirSync(graphsDir)
  251. .filter((name) => name.endsWith(".ts"))
  252. .filter((name) => MARKER_CALL.test(readFileSync(join(graphsDir, name), "utf8")))
  253. .sort();
  254. it("finds marked fixtures", () => {
  255. expect(marked.length).toBeGreaterThan(0);
  256. });
  257. for (const fixture of marked) {
  258. it(`${fixture}: a phase entered while an earlier one is in flight says so`, () => {
  259. const result = analyzeWorkflowScript(readFileSync(join(graphsDir, fixture), "utf8"));
  260. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  261. const flow = result.flow;
  262. const causality = result.causality;
  263. if (flow === undefined || causality === undefined) throw new Error("expected graphs");
  264. const phases = flow.phases ?? [];
  265. // Where each phase's FIRST marker stands on the main line, and which phases own work.
  266. const firstMark = new Map<string, number>();
  267. const owns = new Set<string>();
  268. flow.nodes.forEach((node, index) => {
  269. if (node.kind === "mark" && !firstMark.has(node.phase)) firstMark.set(node.phase, index);
  270. if (node.kind === "issue") owns.add(node.phase);
  271. });
  272. // Forward reachability in the quotient. `carry` is a repetition's back edge, never an
  273. // ordering between two phases, so it cannot be what makes B comparable to A.
  274. const forward = new Map<string, string[]>();
  275. for (const edge of causality.phaseEdges ?? []) {
  276. if (edge.kind === "carry") continue;
  277. const list = forward.get(edge.from);
  278. if (list === undefined) forward.set(edge.from, [edge.to]);
  279. else list.push(edge.to);
  280. }
  281. const reaches = (from: string, to: string): boolean => {
  282. const seen = new Set<string>([from]);
  283. const stack = [from];
  284. while (stack.length > 0) {
  285. for (const next of forward.get(stack.pop() as string) ?? []) {
  286. if (next === to) return true;
  287. if (!seen.has(next)) {
  288. seen.add(next);
  289. stack.push(next);
  290. }
  291. }
  292. }
  293. return false;
  294. };
  295. const missing: string[] = [];
  296. for (const earlier of phases) {
  297. for (const later of phases) {
  298. const a = firstMark.get(earlier.id);
  299. const b = firstMark.get(later.id);
  300. if (a === undefined || b === undefined || a >= b) continue;
  301. if (!owns.has(earlier.id) || !owns.has(later.id)) continue;
  302. if (reaches(earlier.id, later.id)) continue;
  303. if ((later.alongside ?? []).includes(earlier.id)) continue;
  304. missing.push(`${later.id} entered after ${earlier.id} without ordering or alongside`);
  305. }
  306. }
  307. expect(missing).toEqual([]);
  308. });
  309. }
  310. });