dwf-child-command.test.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /**
  2. * 隐藏子命令 `__zcode-dwf-child` 的分派与执行。
  3. *
  4. * Bug 根因(docs/dynamic-workflow/launch.md「Single-executable builds」):SEA 单文件二进制不解释 Node
  5. * CLI 旗标,harness 缺省的 `node --max-old-space-size=… <entry>` 在 SEA 下会把旗标交给严格
  6. * parseArgs,子进程立刻报错退出——SEA 下每一个 dwf run 必然失败。修法与 official plugin host
  7. * 同款:自 re-exec 本二进制 + 在 parseArgs **之前**分派。
  8. *
  9. * 2026-09-09 追记之后 argv 末位是入口文件路径(payload 不再过命令行)。两件事必须钉住:
  10. * 1. 分派发生在 parseArgs 之前——任何进了 parseArgs 的形态都会把路径当未知参数报错;
  11. * 2. 子进程真的跑起来:子命令 `import()` 入口文件、注入真实 vm/readline/stdio 调它的 `start`,
  12. * 把 NDJSON 写回 stdout。入口文件由 harness 同一个 `renderChildEntry` 渲染,与生产同形。
  13. */
  14. import assert from "node:assert/strict";
  15. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  16. import { tmpdir } from "node:os";
  17. import { join } from "node:path";
  18. import { Readable } from "node:stream";
  19. import test from "node:test";
  20. import { ZCODE_DWF_CHILD_COMMAND } from "@zcode/contracts";
  21. import { renderChildEntry } from "@zcode/dynamic-workflow-runtime";
  22. import type { RunContext } from "@zcode/shared-types";
  23. import { isDwfChildInvocation } from "../src/dwf-child-command.js";
  24. import { run } from "../src/run.js";
  25. const createCapturedStdout = () => {
  26. let output = "";
  27. return {
  28. output: () => output,
  29. stream: {
  30. isTTY: false,
  31. write: (chunk: string | Uint8Array): boolean => {
  32. output += typeof chunk === "string" ? chunk : chunk.toString();
  33. return true;
  34. },
  35. } as unknown as NodeJS.WriteStream,
  36. };
  37. };
  38. /**
  39. * 子进程语境的 RunContext:stdin 必须是**真** Readable(childMain 拿它建 readline,
  40. * cli.unit.test.ts 里那个 `{ isTTY: false }` 假 stdin 会直接让 readline 抛错)。
  41. * 这里给一条立即 EOF 的空流:本用例的脚本不发 ask,父进程也就没有 response 要喂。
  42. */
  43. const createChildContext = (
  44. argv: string[],
  45. ): { ctx: RunContext; stdout: () => string; stderr: () => string } => {
  46. const stdout = createCapturedStdout();
  47. const stderr = createCapturedStdout();
  48. return {
  49. ctx: {
  50. argv,
  51. stderr: stderr.stream,
  52. stdin: Readable.from([]) as unknown as NodeJS.ReadStream,
  53. stdout: stdout.stream,
  54. },
  55. stdout: stdout.output,
  56. stderr: stderr.output,
  57. };
  58. };
  59. /**
  60. * 用生产同一个渲染器写一份入口文件。刻意**不**经引擎/编译器:这里被测的是 CLI 边界的契约
  61. * (argv 末位的路径 + 入口文件的 `start` 导出),不是 workflow 的编译管线。
  62. * 不带 `maxOldSpaceSizeMb`:入口文件在 `execArgv` 缺旗标时会对**本进程** best-effort 设堆上限,
  63. * 测试进程不该被它改。
  64. */
  65. const writeEntry = async (lowered: string): Promise<{ path: string; dispose: () => Promise<void> }> => {
  66. const root = await mkdtemp(join(tmpdir(), "dwf-child-cmd-"));
  67. const path = join(root, "run.mjs");
  68. await writeFile(path, renderChildEntry({ lowered }, { runId: "run" }), "utf8");
  69. return { path, dispose: () => rm(root, { force: true, recursive: true }) };
  70. };
  71. test("recognises the dwf child subcommand only as argv[0]", () => {
  72. assert.equal(isDwfChildInvocation([ZCODE_DWF_CHILD_COMMAND, "/tmp/run.mjs"]), true);
  73. assert.equal(isDwfChildInvocation([ZCODE_DWF_CHILD_COMMAND]), true);
  74. assert.equal(isDwfChildInvocation([]), false);
  75. assert.equal(isDwfChildInvocation(["--help"]), false);
  76. // 出现在别处不算:否则一个普通 prompt 里提到这个词就能改变 CLI 的行为。
  77. assert.equal(isDwfChildInvocation(["-p", ZCODE_DWF_CHILD_COMMAND]), false);
  78. });
  79. test("runs the sandbox child from the entry file and writes the NDJSON completion to stdout", async () => {
  80. const entry = await writeEntry('__host.log("from the sandbox");\nreturn { ok: 42 };');
  81. try {
  82. const { ctx, stdout, stderr } = createChildContext([ZCODE_DWF_CHILD_COMMAND, entry.path]);
  83. const exitCode = await run(ctx);
  84. assert.equal(exitCode, 0);
  85. assert.equal(stderr(), "");
  86. const lines = stdout()
  87. .split("\n")
  88. .filter((line) => line.trim().length > 0)
  89. .map((line) => JSON.parse(line));
  90. assert.deepEqual(lines, [
  91. { kind: "event", type: "log", message: "from the sandbox" },
  92. { kind: "complete", ok: true, value: { ok: 42 } },
  93. ]);
  94. } finally {
  95. await entry.dispose();
  96. }
  97. });
  98. test("reports a lowered-body syntax error as an error completion, not a crash", async () => {
  99. const entry = await writeEntry("this is not javascript(");
  100. try {
  101. const { ctx, stdout, stderr } = createChildContext([ZCODE_DWF_CHILD_COMMAND, entry.path]);
  102. const exitCode = await run(ctx);
  103. assert.equal(exitCode, 0);
  104. assert.equal(stderr(), "");
  105. const message = JSON.parse(stdout().trim());
  106. assert.equal(message.kind, "complete");
  107. assert.equal(message.ok, false);
  108. assert.equal(message.error.name, "SyntaxError");
  109. } finally {
  110. await entry.dispose();
  111. }
  112. });
  113. test("fails with usage when the entry path argument is missing", async () => {
  114. const { ctx, stdout, stderr } = createChildContext([ZCODE_DWF_CHILD_COMMAND]);
  115. const exitCode = await run(ctx);
  116. assert.equal(exitCode, 1);
  117. // stdout 是父进程的 NDJSON 通道,接线错误只许走 stderr。
  118. assert.equal(stdout(), "");
  119. assert.match(stderr(), new RegExp(`Usage: ${ZCODE_DWF_CHILD_COMMAND}`));
  120. });
  121. test("fails on stderr when the entry file does not exist", async () => {
  122. const { ctx, stdout, stderr } = createChildContext([
  123. ZCODE_DWF_CHILD_COMMAND,
  124. join(tmpdir(), "dwf-child-cmd-missing", "nope.mjs"),
  125. ]);
  126. const exitCode = await run(ctx);
  127. assert.equal(exitCode, 1);
  128. assert.equal(stdout(), "");
  129. assert.match(stderr(), /Workflow child failed: /);
  130. });