workflow-driver.helpers.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import { createTestAgentRuntime } from "./helpers/test-agent-runtime.js";
  2. /**
  3. * bootstrap 集成测试装配(确定性层,CI 安全):真实脚本 → 真实 schema 合成 + validate + lowering
  4. * → 沙箱子进程 → 引擎核心 → **真实 AgentRuntime driver**(本任务实现),actor runtime 注入
  5. * **脚本化 model adapter**(core/tests 的 generateText 模式)。整条 phase-1.5 管线跑通,只把「真模型」
  6. * 换成可预测的脚本,用以验证 submit 桥接、三值→二值裁决映射、turn-stop、同 turn repair、nudge。
  7. */
  8. import { createInMemorySessionEventStore } from "@zcode/adapters/storage";
  9. import {
  10. SUBMIT_RESULT_TOOL_NAME,
  11. type ExecutionPort,
  12. type FileSystemPort,
  13. type SessionStorePort,
  14. } from "@zcode/contracts";
  15. import { AgentRuntime } from "@zcode/core";
  16. import {
  17. InMemoryJournalStore,
  18. buildAskSpecs,
  19. collectSites,
  20. createWorkflowProgram,
  21. deriveActorSubmitProfilesFor,
  22. refToString,
  23. synthesizeAskSchemas,
  24. validate,
  25. type ActorSubmitProfile,
  26. type AskSpec,
  27. type Caps,
  28. type JsonSchema,
  29. type RunEvent,
  30. type RunSettlement,
  31. type ValidateFn,
  32. } from "@zcode/dynamic-workflow";
  33. import { mkdtempSync } from "node:fs";
  34. import { tmpdir } from "node:os";
  35. import { join } from "node:path";
  36. import { runWorkflowScript } from "@zcode/dynamic-workflow-runtime";
  37. import { workflowActorToolPolicy } from "../src/app/workflow-actor-tools.js";
  38. import {
  39. createWorkflowEscalationRegistry,
  40. type WorkflowEscalationRegistry,
  41. } from "../src/app/workflow-escalation-registry.js";
  42. import {
  43. createAgentRuntimeWorkflowDriver,
  44. type ActorRuntimeFactory,
  45. } from "../src/app/workflow-driver.js";
  46. import type { AgentRuntimeWorkflowDriverDeps } from "../src/app/workflow-driver-types.js";
  47. import type { WorkflowConcurrencyPort } from "../src/app/workflow-concurrency-governor.js";
  48. /**
  49. * 独立的 run cwd:harness 把入口文件写到 `<cwd>/.zcode/workflow-runs/<runId>.mjs` 且保留,
  50. * 用 process.cwd() 会把存档留在包目录里,并让并行测试文件互相覆写同名入口文件。
  51. */
  52. const TEST_CWD: string = mkdtempSync(join(tmpdir(), "dwf-bootstrap-test-cwd-"));
  53. /** 适配真实校验器到引擎的 ValidateFn 契约。 */
  54. const validateFn: ValidateFn = (schema, value) => validate(schema as JsonSchema, value);
  55. /**
  56. * 由脚本文本合成 ask 规格:走包里的规范构造器 {@link buildAskSpecs}(按站点表遍历,
  57. * untyped 站点显式记 `{typed:false}`——引擎把站点缺席当接线错误硬失败)。
  58. *
  59. * 同时演示「编译一次」:一个 ts.Program 同时喂站点表与 schema 合成。
  60. */
  61. function askSpecsFor(scriptText: string): Map<string, AskSpec> {
  62. const workflow = createWorkflowProgram(scriptText);
  63. const table = collectSites(workflow);
  64. const { schemas } = synthesizeAskSchemas(workflow, table);
  65. return buildAskSpecs(table, schemas);
  66. }
  67. /**
  68. * 由脚本文本推导每个 actor 站点的 submit profile(照 run 提交路径的 compileOnce:同一 Program 上的
  69. * 站点表 + schema 合成 + 站点图)。docs/execution-engine.md「Typed asks and `submit_result`」。
  70. */
  71. export function actorSubmitProfilesFor(scriptText: string): Map<string, ActorSubmitProfile> {
  72. const workflow = createWorkflowProgram(scriptText);
  73. const table = collectSites(workflow);
  74. const { schemas } = synthesizeAskSchemas(workflow, table);
  75. return deriveActorSubmitProfilesFor(workflow, table, buildAskSpecs(table, schemas));
  76. }
  77. /** 脚本化模型的一步计划:提交一个 payload、只发一段最终文本(不提交)、或挂起(永不返回)。 */
  78. export type PlannedResponse =
  79. | { kind: "submit"; result: unknown }
  80. | { kind: "text"; text: string }
  81. // 挂起:模拟一个在飞的 turn(取消/恢复用例靠它把 run 停在可预测的节点上)。
  82. | { kind: "hang" };
  83. /** 记录某 actor runtime 实际发生的模型请求数(供断言 repair 是否真的在 turn 内重试)。 */
  84. interface ModelCallLog {
  85. calls: number;
  86. /** 每次 generateText 请求实际带上的工具名列表(供断言 actor 的工具面减法真的落到了模型请求上)。 */
  87. toolNames: string[][];
  88. /** 每次 generateText 请求里最后一条 user 消息的文本(供断言 ask 尾注真的到了模型面)。 */
  89. prompts: string[];
  90. /**
  91. * 每次 generateText 请求里 submit_result 的声明(inputSchema + strict 资格),没有该工具时为
  92. * undefined(供断言 submit profile 真的落到了工具面)。
  93. */
  94. submitTools: ({ inputSchema: unknown; strict: boolean | undefined } | undefined)[];
  95. }
  96. /** 取请求里最后一条 user 消息的文本;content 为分块时拼接其中的 text 块。 */
  97. function lastUserPrompt(request: unknown): string {
  98. const messages = (request as { messages?: unknown[] } | undefined)?.messages ?? [];
  99. for (let i = messages.length - 1; i >= 0; i--) {
  100. const message = messages[i] as { role?: unknown; content?: unknown };
  101. if (message?.role !== "user") continue;
  102. const content = message.content;
  103. if (typeof content === "string") return content;
  104. if (Array.isArray(content)) {
  105. return content
  106. .map((part) => (typeof part?.text === "string" ? part.text : ""))
  107. .join("");
  108. }
  109. return "";
  110. }
  111. return "";
  112. }
  113. /**
  114. * 造一个脚本化 model adapter:按 responses 顺序逐次应答每个 generateText 请求。
  115. * submit → 发一个 submit_result 工具调用(input.result = payload);text → 发一段最终文本 stop。
  116. * 队列耗尽后兜底发一段文本,避免无限循环。
  117. */
  118. function scriptedModelAdapter(responses: PlannedResponse[], log: ModelCallLog): unknown {
  119. let index = 0;
  120. return {
  121. async generateText(request?: {
  122. tools?: readonly { name: string; inputSchema?: unknown; strict?: boolean }[];
  123. }) {
  124. log.calls++;
  125. log.toolNames.push((request?.tools ?? []).map((tool) => tool.name));
  126. log.prompts.push(lastUserPrompt(request));
  127. const submit = (request?.tools ?? []).find((tool) => tool.name === SUBMIT_RESULT_TOOL_NAME);
  128. log.submitTools.push(
  129. submit === undefined
  130. ? undefined
  131. : { inputSchema: submit.inputSchema, strict: submit.strict },
  132. );
  133. const planned = responses[index++] ?? { kind: "text", text: "(no further scripted response)" };
  134. if (planned.kind === "hang") return new Promise(() => {});
  135. const usage = { inputTokens: 12, outputTokens: 8, totalTokens: 20 };
  136. if (planned.kind === "submit") {
  137. return {
  138. finishReason: "tool-calls",
  139. model: "scripted",
  140. providerMetadata: undefined,
  141. text: "",
  142. toolCalls: [
  143. { id: `submit-call-${index}`, name: SUBMIT_RESULT_TOOL_NAME, input: { result: planned.result } },
  144. ],
  145. usage,
  146. };
  147. }
  148. return {
  149. finishReason: "stop",
  150. model: "scripted",
  151. providerMetadata: undefined,
  152. text: planned.text,
  153. usage,
  154. };
  155. },
  156. };
  157. }
  158. /** 极简内存 fs 端口:仅实现 world-read 用到的 searchFiles / readTextFile,其余抛错(不该被触及)。 */
  159. export function fakeFileSystemPort(files: {
  160. glob?: string[];
  161. read?: string;
  162. }): FileSystemPort {
  163. const unsupported = (name: string) => () => {
  164. throw new Error(`fakeFileSystemPort.${name} 不应被 world-read 触及`);
  165. };
  166. return {
  167. async searchFiles(request: { path: string; pattern: string }) {
  168. const list = files.glob ?? [];
  169. return { path: request.path, pattern: request.pattern, durationMs: 0, files: list, numFiles: list.length, truncated: false };
  170. },
  171. async readTextFile(request: { path: string }) {
  172. return {
  173. path: request.path,
  174. content: files.read ?? "",
  175. encoding: "utf-8",
  176. bytesRead: (files.read ?? "").length,
  177. sizeBytes: (files.read ?? "").length,
  178. truncated: false,
  179. };
  180. },
  181. createDirectory: unsupported("createDirectory"),
  182. stat: unsupported("stat"),
  183. readBinaryFile: unsupported("readBinaryFile"),
  184. readTextFileRange: unsupported("readTextFileRange"),
  185. writeTextFile: unsupported("writeTextFile"),
  186. removeFile: unsupported("removeFile"),
  187. listDirectory: unsupported("listDirectory"),
  188. searchText: unsupported("searchText"),
  189. } as unknown as FileSystemPort;
  190. }
  191. interface RunDriverScriptOptions {
  192. /** 按 actor ref 串(如 "actor#1@1")的模型计划序列;每个 actor 一个持久 runtime。 */
  193. actorScripts: Record<string, PlannedResponse[]>;
  194. caps?: Caps;
  195. timeoutMs?: number;
  196. journal?: InMemoryJournalStore;
  197. files?: { glob?: string[]; read?: string };
  198. runId?: string;
  199. /**
  200. * 覆盖内部的脚本化 runtime 工厂(live 层用它注入真实 model adapter 的 runtime)。
  201. * 提供时 actorScripts 被忽略,modelCalls 不再记录(由调用方自证)。
  202. */
  203. runtimeFactory?: ActorRuntimeFactory;
  204. /**
  205. * 真实会话存储。接上它,actor runtime 才真的把消息落库,driver 也才拿得到转录存取面——
  206. * amend-resume 的边界记账与转录截断两族用例的前提(缺省不接:其余用例不需要,也不该为它们
  207. * 付一次 sqlite 的代价)。默认工厂随之照生产的样子先把会话行落库(FK 要求)。
  208. */
  209. sessionStore?: SessionStorePort;
  210. /**
  211. * 升级问答的停驻表。传进来即可在用例里扮演 run service 的应答侧(`registry.resolve(...)`);
  212. * 缺省新建一张,于是既有用例一字不改(没有 actor 会调 escalate)。
  213. */
  214. escalationRegistry?: WorkflowEscalationRegistry;
  215. /**
  216. * 默认工厂每造一个 actor runtime 就回调一次(键为 actor ref 串)。用例靠它拿到 runtime 的
  217. * 弱引用 / 关闭链 spy,而不必复制整个脚本化工厂;runtimeFactory 被覆盖时不回调。
  218. */
  219. onRuntimeCreated?: (runtime: AgentRuntime, actorKey: string) => void;
  220. /**
  221. * 每个 actor 站点的 submit profile(docs/execution-engine.md「Submit profiles」)。`"derive"` 照
  222. * 生产从脚本推导;给一张表则原样使用(守卫用例靠它喂一份**错误**的静态 profile);缺省不传 =
  223. * 2026-09-13 之前的行为(每个 actor generic),既有用例因此一字不改。
  224. */
  225. actorSubmitProfiles?: "derive" | ReadonlyMap<string, ActorSubmitProfile>;
  226. /**
  227. * 进程级并发治理器的窄端口(故障矩阵用真 governor 让闸门生效;缺省不接,行为与既有用例同)。
  228. */
  229. concurrency?: WorkflowConcurrencyPort;
  230. /** driver 的时钟与定时器(故障矩阵把重驱曲线与 stall 窗缩到毫秒级);缺省真时间。 */
  231. clock?: AgentRuntimeWorkflowDriverDeps["clock"];
  232. }
  233. interface RunDriverScriptResult {
  234. settlement: RunSettlement;
  235. journal: InMemoryJournalStore;
  236. events: RunEvent[];
  237. /** 各 actor runtime 的模型请求计数,键为 actor ref 串。 */
  238. modelCalls: Record<string, ModelCallLog>;
  239. /** 本次跑用的停驻表(调用方没传时是这里新建的那一张)。 */
  240. escalationRegistry: WorkflowEscalationRegistry;
  241. }
  242. const DEFAULT_CAPS: Caps = { maxConcurrency: 16 };
  243. /**
  244. * 用真实管线跑一份脚本:真实 driver + 真实 AgentRuntime(脚本化模型)+ 内存 journal。
  245. * 返回结算、journal、Boundary C 事件、各 actor 的模型调用计数。
  246. */
  247. /**
  248. * 世界读取用不到子进程的用例里的 ExecutionPort 占位:被触及即失败。
  249. *
  250. * deps 里 executionPort 是**必填**(见 workflow-driver.ts 的字段注释:可选会给出一条静默
  251. * 降级的运行路径),所以这里不能省;而一个会抛的占位比一个空实现好——它让"本用例其实跑了
  252. * 一次 git"变成一次显式失败,而不是一个被忽略的空结果。
  253. */
  254. export function unsupportedExecutionPort(): ExecutionPort {
  255. return {
  256. run: () => {
  257. throw new Error("本用例不应触及 ExecutionPort(git.* world-read)");
  258. },
  259. };
  260. }
  261. export async function runDriverScript(
  262. scriptText: string,
  263. opts: RunDriverScriptOptions,
  264. ): Promise<RunDriverScriptResult> {
  265. const journal = opts.journal ?? new InMemoryJournalStore();
  266. const events: RunEvent[] = [];
  267. const modelCalls: Record<string, ModelCallLog> = {};
  268. const fileSystemPort = fakeFileSystemPort(opts.files ?? {});
  269. const escalationRegistry = opts.escalationRegistry ?? createWorkflowEscalationRegistry();
  270. const makeDriver = createAgentRuntimeWorkflowDriver({
  271. journal,
  272. emit: (event) => events.push(event),
  273. executionPort: unsupportedExecutionPort(),
  274. escalationRegistry,
  275. fileSystemPort,
  276. cwd: process.cwd(),
  277. // driver 与 harness 必须看到同一个 runId:actor 会话 id 以它为作用域,
  278. // 只传给 harness 会让测试里的会话 id 永远落在兜底的 "run" 上。
  279. runId: opts.runId ?? "run",
  280. ...(opts.sessionStore === undefined ? {} : { actorTranscriptStore: opts.sessionStore }),
  281. ...(opts.actorSubmitProfiles === undefined
  282. ? {}
  283. : {
  284. actorSubmitProfiles:
  285. opts.actorSubmitProfiles === "derive"
  286. ? actorSubmitProfilesFor(scriptText)
  287. : opts.actorSubmitProfiles,
  288. }),
  289. ...(opts.concurrency === undefined ? {} : { concurrency: opts.concurrency }),
  290. ...(opts.clock === undefined ? {} : { clock: opts.clock }),
  291. runtimeFactory:
  292. opts.runtimeFactory ??
  293. (async ({ sessionId, actor, persona, submitPort, submitProfile }) => {
  294. const key = refToString(actor);
  295. const log: ModelCallLog = { calls: 0, toolNames: [], prompts: [], submitTools: [] };
  296. modelCalls[key] = log;
  297. const responses = opts.actorScripts[key] ?? [];
  298. const runtime = createTestAgentRuntime(
  299. sessionId,
  300. {
  301. systemPrompt: persona.system ?? "You are a workflow actor.",
  302. mode: "yolo",
  303. taskType: "workflow_child",
  304. subagents: { enabled: false },
  305. // actor 的工具面:全集减去会悬挂/越权的交互工具。
  306. ...workflowActorToolPolicy(),
  307. },
  308. {
  309. eventStore: createInMemorySessionEventStore(),
  310. modelAdapter: scriptedModelAdapter(responses, log) as never,
  311. // 照生产工厂(create-app.ts):untyped 不注入端口(无工具);mono 注入端口 + typed 声明。
  312. ...(submitProfile.kind === "untyped" ? {} : { workflowSubmitPort: submitPort }),
  313. ...(submitProfile.kind === "mono" ? { workflowSubmitSchema: { ...submitProfile.schema } } : {}),
  314. fileSystemPort,
  315. ...(opts.sessionStore === undefined ? {} : { sessionStore: opts.sessionStore }),
  316. },
  317. );
  318. // 照生产(dynamic-workflow-run-launch.ts 的 persistActorSession):会话行必须先落库,
  319. // `message.session_id` 对 `session(id)` 有 FK,否则第一条消息就写不进去。
  320. if (opts.sessionStore !== undefined) {
  321. await runtime.ensureSessionPersistedForExternalActivity(`workflow actor ${key}`);
  322. }
  323. opts.onRuntimeCreated?.(runtime, key);
  324. return runtime;
  325. }),
  326. });
  327. const settlement = await runWorkflowScript({
  328. scriptText,
  329. cwd: TEST_CWD,
  330. runId: opts.runId ?? "run",
  331. caps: opts.caps ?? DEFAULT_CAPS,
  332. askSpecs: askSpecsFor(scriptText),
  333. validate: validateFn,
  334. makeDriver,
  335. timeoutMs: opts.timeoutMs ?? 30000,
  336. });
  337. return { settlement, journal, events, modelCalls, escalationRegistry };
  338. }