fill-workflow-hole-tool.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterAll, beforeEach, describe, expect, it } from "vitest";
  5. import {
  6. FILL_WORKFLOW_HOLE_SOURCE_ERROR,
  7. FILL_WORKFLOW_HOLE_TOOL_NAME,
  8. SessionEventType,
  9. WORKFLOW_DRAFTS_DIR,
  10. createRootTraceContext,
  11. createSessionId,
  12. createToolCallId,
  13. createTurnId,
  14. type CreateWorkflowOutput,
  15. type DynamicWorkflowRunFillHoleRequest,
  16. type DynamicWorkflowRunPort,
  17. type DynamicWorkflowRunSnapshot,
  18. type FillWorkflowHoleResult,
  19. type PermissionBrokerRequest,
  20. type PermissionRequestedPayload,
  21. type SessionEvent,
  22. type ToolExecutionResult,
  23. } from "@zcode/contracts";
  24. import { collectSites, createWorkflowProgram } from "@zcode/dynamic-workflow";
  25. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  26. import { createToolExecutor } from "../src/tool/executor.js";
  27. import { createCreateWorkflowDisplay } from "../src/tool/executor/create-workflow-display.js";
  28. import {
  29. FILL_WORKFLOW_HOLE_ERROR_CODE,
  30. fillWorkflowHoleToolEntry,
  31. } from "../src/tool/handlers/fill-workflow-hole.js";
  32. import { resetFillWorkflowHoleRejectionsForTests } from "../src/tool/handlers/fill-workflow-hole-resolve.js";
  33. import { createToolRegistry } from "../src/tool/registry.js";
  34. import type {
  35. ToolExecutionContext,
  36. ToolHandlerFailure,
  37. ToolInputResolutionContext,
  38. } from "../src/tool/types.js";
  39. // docs/dynamic-workflow/launch.md「The `FillWorkflowHole` tool」:resolveInput 把 run_id + hole_id 解析成
  40. // `hole` 事实块(归属、名字、类型、草稿路径)→ 权限服务据它放行本会话的 run / 照常 ask 别的 →
  41. // handler 先把内联函数体写进 fill 文件、再调 port.fillHole,诊断按「落在哪个文件」锚定。
  42. const BODY = 'const verdict = await agent("judge").ask<string>("judge it");\nreturn verdict;';
  43. /** 端口在成功时交回的有效脚本:能编译、带一个阶段,好让 display 与 phasesAdded 都有内容。 */
  44. const EFFECTIVE_SCRIPT = [
  45. 'phase("判定");',
  46. 'const verdict = await agent("judge").ask<string>("judge it");',
  47. "return verdict;",
  48. ].join("\n");
  49. const CWD = mkdtempSync(join(tmpdir(), "dwf-fill-cwd-"));
  50. afterAll(() => {
  51. rmSync(CWD, { force: true, recursive: true });
  52. });
  53. beforeEach(() => {
  54. resetFillWorkflowHoleRejectionsForTests();
  55. });
  56. function sessionOf(name: string): string {
  57. return createSessionId(name) as unknown as string;
  58. }
  59. const WAITING_HOLE = {
  60. siteId: "hole#1",
  61. ordinal: 1,
  62. name: "决定分组",
  63. type: "Verdict",
  64. state: "waiting" as const,
  65. since: 1_725_000_000_000,
  66. line: 12,
  67. before: "收集",
  68. after: "汇总",
  69. };
  70. interface StubPortOptions {
  71. snapshot?: Partial<DynamicWorkflowRunSnapshot>;
  72. fill?:
  73. | FillWorkflowHoleResult
  74. | ((request: DynamicWorkflowRunFillHoleRequest) => FillWorkflowHoleResult);
  75. /** 端口**没有** fillHole(老宿主)。 */
  76. withoutFillHole?: boolean;
  77. }
  78. function stubRunPort(options: StubPortOptions = {}): {
  79. port: DynamicWorkflowRunPort;
  80. fills: DynamicWorkflowRunFillHoleRequest[];
  81. getTaskCalls: string[];
  82. } {
  83. const fills: DynamicWorkflowRunFillHoleRequest[] = [];
  84. const getTaskCalls: string[] = [];
  85. const unreachable = (name: string) => () => {
  86. throw new Error(`stubRunPort.${name} 不应被 FillWorkflowHole 触及`);
  87. };
  88. return {
  89. port: {
  90. async getTask(taskId: string) {
  91. getTaskCalls.push(taskId);
  92. if (options.snapshot === undefined) return undefined;
  93. return {
  94. runId: taskId,
  95. taskId,
  96. startedAt: new Date(0),
  97. status: "running",
  98. ...options.snapshot,
  99. } as DynamicWorkflowRunSnapshot;
  100. },
  101. ...(options.withoutFillHole
  102. ? {}
  103. : {
  104. async fillHole(request: DynamicWorkflowRunFillHoleRequest) {
  105. fills.push(request);
  106. const fill = options.fill;
  107. if (fill === undefined) {
  108. return {
  109. ok: true,
  110. phasesAdded: ["判定"],
  111. scriptPath: "/repo/.zcode/workflow-drafts/triage.dwf.ts",
  112. scriptText: EFFECTIVE_SCRIPT,
  113. };
  114. }
  115. return typeof fill === "function" ? fill(request) : fill;
  116. },
  117. }),
  118. submit: unreachable("submit"),
  119. waitForTask: unreachable("waitForTask"),
  120. cancel: unreachable("cancel"),
  121. listEvents: unreachable("listEvents"),
  122. } as unknown as DynamicWorkflowRunPort,
  123. fills,
  124. getTaskCalls,
  125. };
  126. }
  127. function resolutionContext(
  128. port: DynamicWorkflowRunPort | undefined,
  129. name: string,
  130. loaded = true,
  131. ): ToolInputResolutionContext {
  132. return {
  133. workingDirectory: CWD,
  134. sessionId: sessionOf(name),
  135. hasLoadedSkill: () => loaded,
  136. ...(port === undefined ? {} : { dynamicWorkflowRunPort: port }),
  137. };
  138. }
  139. async function resolve(input: unknown, context: ToolInputResolutionContext) {
  140. return fillWorkflowHoleToolEntry.resolveInput!(input, context);
  141. }
  142. function executionContext(
  143. port: DynamicWorkflowRunPort | undefined,
  144. name: string,
  145. ): ToolExecutionContext {
  146. return {
  147. abortSignal: new AbortController().signal,
  148. sessionId: sessionOf(name) as never,
  149. toolCallId: `toolu_${name}`,
  150. traceId: `trace_${name}` as never,
  151. workingDirectory: CWD,
  152. workspaceRoot: CWD,
  153. ...(port === undefined ? {} : { dynamicWorkflowRunPort: port }),
  154. } as ToolExecutionContext;
  155. }
  156. function asFailure(value: unknown): ToolHandlerFailure {
  157. const failure = value as ToolHandlerFailure;
  158. expect(failure.result).toBe(false);
  159. return failure;
  160. }
  161. function fillFilesIn(dir: string): string[] {
  162. const { readdirSync } = require("node:fs") as typeof import("node:fs");
  163. return existsSync(dir)
  164. ? readdirSync(dir)
  165. .filter((f) => f.endsWith(".dwf.ts"))
  166. .sort()
  167. : [];
  168. }
  169. describe("FillWorkflowHole — validateInput", () => {
  170. it("wants exactly one of script and path", () => {
  171. const validate = fillWorkflowHoleToolEntry.validateInput!;
  172. expect(validate({ run_id: "r", hole_id: "hole#1", script: BODY }, {})).toEqual({
  173. result: true,
  174. });
  175. const both = asFailure(
  176. validate({ run_id: "r", hole_id: "hole#1", script: BODY, path: "x" }, {}),
  177. );
  178. expect(both.message).toBe(FILL_WORKFLOW_HOLE_SOURCE_ERROR);
  179. const neither = asFailure(validate({ run_id: "r", hole_id: "hole#1" }, {}));
  180. expect(neither.message).toBe(FILL_WORKFLOW_HOLE_SOURCE_ERROR);
  181. });
  182. });
  183. describe("FillWorkflowHole — resolveInput", () => {
  184. it("refuses before touching the port when the skill is not loaded", async () => {
  185. const { port, getTaskCalls } = stubRunPort({ snapshot: { holes: [WAITING_HOLE] } });
  186. const failure = asFailure(
  187. await resolve(
  188. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  189. resolutionContext(port, "gate", false),
  190. ),
  191. );
  192. expect(failure.message).toContain("dynamic-workflows");
  193. expect(failure.message).toContain(FILL_WORKFLOW_HOLE_TOOL_NAME);
  194. expect(getTaskCalls).toHaveLength(0);
  195. });
  196. it("fails run_not_found when the run does not exist", async () => {
  197. const { port } = stubRunPort();
  198. const failure = asFailure(
  199. await resolve(
  200. { run_id: "dwfrun-nope", hole_id: "hole#1", script: BODY },
  201. resolutionContext(port, "nf"),
  202. ),
  203. );
  204. expect(failure.message).toContain("run_not_found");
  205. expect(failure.message).toContain("dwfrun-nope");
  206. });
  207. it("refuses hole_not_waiting for an unknown, filled or stopped hole, naming the next step", async () => {
  208. const filled = { ...WAITING_HOLE, siteId: "hole#2", state: "filled" as const, filledAt: 5 };
  209. const { port } = stubRunPort({ snapshot: { holes: [WAITING_HOLE, filled] } });
  210. const unknown = asFailure(
  211. await resolve(
  212. { run_id: "dwfrun-1", hole_id: "hole#9", script: BODY },
  213. resolutionContext(port, "unk"),
  214. ),
  215. );
  216. expect(unknown.message).toContain("hole_not_waiting");
  217. expect(unknown.message).toContain("hole#9");
  218. expect(unknown.errorCode).toBe(FILL_WORKFLOW_HOLE_ERROR_CODE.HOLE_NOT_WAITING);
  219. const already = asFailure(
  220. await resolve(
  221. { run_id: "dwfrun-1", hole_id: "hole#2", script: BODY },
  222. resolutionContext(port, "already"),
  223. ),
  224. );
  225. expect(already.message).toContain("already filled");
  226. const stopped = stubRunPort({
  227. snapshot: {
  228. status: "cancelled",
  229. runStatus: "stopped",
  230. stopReason: "user",
  231. holes: [WAITING_HOLE],
  232. },
  233. });
  234. const notInFlight = asFailure(
  235. await resolve(
  236. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  237. resolutionContext(stopped.port, "stopped"),
  238. ),
  239. );
  240. expect(notInFlight.message).toContain("hole_not_waiting");
  241. expect(notInFlight.message).toContain("ResumeWorkflowRun");
  242. });
  243. it("backfills the hole block from the snapshot and overrides a forged one", async () => {
  244. const name = "owned";
  245. const { port } = stubRunPort({
  246. snapshot: {
  247. parentSessionId: sessionOf(name),
  248. scriptPath: "/repo/.zcode/workflow-drafts/triage.dwf.ts",
  249. holes: [WAITING_HOLE],
  250. },
  251. });
  252. const resolved = await resolve(
  253. {
  254. run_id: "dwfrun-1",
  255. hole_id: "hole#1",
  256. script: BODY,
  257. hole: { name: "forged", type: "never", owned_by_this_session: true },
  258. },
  259. resolutionContext(port, name),
  260. );
  261. expect(resolved).toEqual({
  262. result: true,
  263. input: {
  264. run_id: "dwfrun-1",
  265. hole_id: "hole#1",
  266. script: BODY,
  267. hole: {
  268. name: "决定分组",
  269. type: "Verdict",
  270. draft_path: "/repo/.zcode/workflow-drafts/triage.dwf.ts",
  271. line: 12,
  272. owned_by_this_session: true,
  273. },
  274. },
  275. });
  276. });
  277. it("marks another session's run as not owned", async () => {
  278. const { port } = stubRunPort({
  279. snapshot: { parentSessionId: "sess_other", holes: [WAITING_HOLE] },
  280. });
  281. const resolved = await resolve(
  282. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  283. resolutionContext(port, "foreign"),
  284. );
  285. expect(resolved).toMatchObject({
  286. result: true,
  287. input: { hole: { owned_by_this_session: false } },
  288. });
  289. // 没记过草稿的 run:`draft_path` 缺席而不是空串。
  290. expect("draft_path" in (resolved as { input: { hole: object } }).input.hole).toBe(false);
  291. });
  292. it("reads a path fill into script and keeps the path; an unreadable file fails by name", async () => {
  293. const fillPath = join(CWD, "my-fill.dwf.ts");
  294. writeFileSync(fillPath, BODY);
  295. const { port } = stubRunPort({ snapshot: { holes: [WAITING_HOLE] } });
  296. const resolved = await resolve(
  297. { run_id: "dwfrun-1", hole_id: "hole#1", path: "my-fill.dwf.ts" },
  298. resolutionContext(port, "path"),
  299. );
  300. expect(resolved).toMatchObject({ result: true, input: { script: BODY, path: fillPath } });
  301. const missing = asFailure(
  302. await resolve(
  303. { run_id: "dwfrun-1", hole_id: "hole#1", path: "nowhere.dwf.ts" },
  304. resolutionContext(port, "path-missing"),
  305. ),
  306. );
  307. expect(missing.message).toContain("nowhere.dwf.ts");
  308. expect(missing.errorCode).toBe(FILL_WORKFLOW_HOLE_ERROR_CODE.FILL_FILE);
  309. });
  310. it("passes an inline fill through without a hole block when there is no port", async () => {
  311. const resolved = await resolve(
  312. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  313. resolutionContext(undefined, "noport"),
  314. );
  315. expect(resolved).toEqual({
  316. result: true,
  317. input: { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  318. });
  319. });
  320. });
  321. describe("FillWorkflowHole — handler", () => {
  322. it("writes the inline fill to <slug>.<hole-slug>.dwf.ts BEFORE the port compiles, minting -2 on a resubmission", async () => {
  323. const draftsDir = join(CWD, WORKFLOW_DRAFTS_DIR);
  324. const seenAtCall: boolean[] = [];
  325. const { port } = stubRunPort({
  326. snapshot: {
  327. parentSessionId: sessionOf("write"),
  328. scriptPath: join(draftsDir, "triage.dwf.ts"),
  329. holes: [WAITING_HOLE],
  330. },
  331. fill: () => {
  332. seenAtCall.push(existsSync(join(draftsDir, "triage.决定分组.dwf.ts")));
  333. return { ok: false, reason: "compile_failed", message: "no", diagnostics: [] };
  334. },
  335. });
  336. const context = executionContext(port, "write");
  337. const resolved = await resolve(
  338. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  339. resolutionContext(port, "write"),
  340. );
  341. await fillWorkflowHoleToolEntry.handler((resolved as { input: unknown }).input, context);
  342. expect(seenAtCall).toEqual([true]);
  343. expect(readFileSync(join(draftsDir, "triage.决定分组.dwf.ts"), "utf8")).toBe(BODY);
  344. await fillWorkflowHoleToolEntry.handler((resolved as { input: unknown }).input, context);
  345. expect(fillFilesIn(draftsDir)).toEqual(["triage.决定分组-2.dwf.ts", "triage.决定分组.dwf.ts"]);
  346. });
  347. it("on diagnostics leads with the fill file and anchors each line to the file it falls in", async () => {
  348. const draftsDir = join(CWD, WORKFLOW_DRAFTS_DIR);
  349. const { port, fills } = stubRunPort({
  350. snapshot: {
  351. parentSessionId: sessionOf("diag"),
  352. scriptPath: join(draftsDir, "review.dwf.ts"),
  353. holes: [WAITING_HOLE],
  354. },
  355. fill: {
  356. ok: false,
  357. reason: "compile_failed",
  358. message: "The effective script does not compile.",
  359. diagnostics: [
  360. {
  361. line: 2,
  362. column: 8,
  363. message: "Type 'number' is not assignable to type 'string'.",
  364. code: 2322,
  365. inFill: true,
  366. },
  367. {
  368. line: 30,
  369. column: 1,
  370. message: "Subagent name 'judge' is declared twice.",
  371. code: 9005,
  372. inFill: false,
  373. },
  374. ],
  375. },
  376. });
  377. const resolved = await resolve(
  378. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  379. resolutionContext(port, "diag"),
  380. );
  381. const output = (await fillWorkflowHoleToolEntry.handler(
  382. (resolved as { input: unknown }).input,
  383. executionContext(port, "diag"),
  384. )) as CreateWorkflowOutput;
  385. expect(fills).toHaveLength(1);
  386. expect(fills[0]).toMatchObject({
  387. runId: "dwfrun-1",
  388. holeId: "hole#1",
  389. body: BODY,
  390. parentSessionId: sessionOf("diag"),
  391. });
  392. expect(output.ok).toBe(false);
  393. expect(output.diagnostics).toHaveLength(2);
  394. const fillFile = join(WORKFLOW_DRAFTS_DIR, "review.决定分组.dwf.ts");
  395. expect(
  396. output.response.startsWith(
  397. `The fill is saved at ${fillFile}. Edit that file in place and resubmit with \`path\`; do not paste it inline again.`,
  398. ),
  399. ).toBe(true);
  400. expect(output.response).toContain(
  401. `${fillFile}:L2:C8 Type 'number' is not assignable to type 'string'.`,
  402. );
  403. expect(output.response).toContain(
  404. `${join(WORKFLOW_DRAFTS_DIR, "review.dwf.ts")}:L30:C1 Subagent name 'judge' is declared twice.`,
  405. );
  406. // 函数体之外有诊断:指明那是 run 记录在案的脚本、改草稿没用、出路是 AmendWorkflow。
  407. expect(output.response).toContain("run's recorded script");
  408. expect(output.response).toContain("AmendWorkflow");
  409. expect(output.response).toContain("still waiting");
  410. expect("status" in output).toBe(false);
  411. // 编译反馈行由 CreateWorkflow 的 display 构造器铸出,按工具名选中本工具。
  412. const display = createCreateWorkflowDisplay(FILL_WORKFLOW_HOLE_TOOL_NAME, output);
  413. expect(display?.kind).toBe("create_workflow");
  414. // 被拒的行也要有名字:反馈行的标题不能退成站点 id。
  415. expect(display?.fill).toMatchObject({ siteId: "hole#1", name: "决定分组" });
  416. });
  417. it("refuses fill_unchanged when a path resubmits the bytes of the last rejected attempt, without touching the port", async () => {
  418. const draftsDir = join(CWD, WORKFLOW_DRAFTS_DIR);
  419. const { port, fills } = stubRunPort({
  420. snapshot: {
  421. parentSessionId: sessionOf("unchanged"),
  422. scriptPath: join(draftsDir, "unchanged.dwf.ts"),
  423. holes: [WAITING_HOLE],
  424. },
  425. fill: {
  426. ok: false,
  427. reason: "compile_failed",
  428. message: "no",
  429. diagnostics: [{ line: 1, column: 1, message: "bad", code: 1, inFill: true }],
  430. },
  431. });
  432. const resolved = await resolve(
  433. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  434. resolutionContext(port, "unchanged"),
  435. );
  436. await fillWorkflowHoleToolEntry.handler(
  437. (resolved as { input: unknown }).input,
  438. executionContext(port, "unchanged"),
  439. );
  440. expect(fills).toHaveLength(1);
  441. const fillFile = join(draftsDir, "unchanged.决定分组.dwf.ts");
  442. const again = asFailure(
  443. await resolve(
  444. { run_id: "dwfrun-1", hole_id: "hole#1", path: fillFile },
  445. resolutionContext(port, "unchanged"),
  446. ),
  447. );
  448. expect(again.message).toContain("fill_unchanged");
  449. expect(again.errorCode).toBe(FILL_WORKFLOW_HOLE_ERROR_CODE.FILL_UNCHANGED);
  450. expect(fills).toHaveLength(1);
  451. // 改过一个字节就放行。
  452. writeFileSync(fillFile, `${BODY}\n`);
  453. const edited = await resolve(
  454. { run_id: "dwfrun-1", hole_id: "hole#1", path: fillFile },
  455. resolutionContext(port, "unchanged"),
  456. );
  457. expect(edited).toMatchObject({ result: true });
  458. });
  459. it("a path fill mints nothing and is refused hole_not_waiting / fill_ids_unstable verbatim from the port", async () => {
  460. const draftsDir = join(CWD, WORKFLOW_DRAFTS_DIR);
  461. const before = fillFilesIn(draftsDir);
  462. const fillPath = join(CWD, "path-fill.dwf.ts");
  463. writeFileSync(fillPath, BODY);
  464. const { port } = stubRunPort({
  465. snapshot: { parentSessionId: sessionOf("pathfill"), holes: [WAITING_HOLE] },
  466. fill: {
  467. ok: false,
  468. reason: "fill_ids_unstable",
  469. message: "Site hole#1/ask#1 moved: host fault.",
  470. },
  471. });
  472. const resolved = await resolve(
  473. { run_id: "dwfrun-1", hole_id: "hole#1", path: fillPath },
  474. resolutionContext(port, "pathfill"),
  475. );
  476. const failure = asFailure(
  477. await fillWorkflowHoleToolEntry.handler(
  478. (resolved as { input: unknown }).input,
  479. executionContext(port, "pathfill"),
  480. ),
  481. );
  482. expect(failure.message).toContain("fill_ids_unstable");
  483. expect(failure.message).toContain("Site hole#1/ask#1 moved: host fault.");
  484. expect(fillFilesIn(draftsDir)).toEqual(before);
  485. });
  486. it("on success names the phases added, the draft to edit, and carries the effective script's graph", async () => {
  487. const { port } = stubRunPort({
  488. snapshot: {
  489. parentSessionId: sessionOf("ok"),
  490. scriptPath: join(CWD, WORKFLOW_DRAFTS_DIR, "ok.dwf.ts"),
  491. holes: [WAITING_HOLE],
  492. },
  493. fill: {
  494. ok: true,
  495. phasesAdded: ["判定", "复核"],
  496. scriptPath: join(CWD, WORKFLOW_DRAFTS_DIR, "ok.dwf.ts"),
  497. scriptText: EFFECTIVE_SCRIPT,
  498. },
  499. });
  500. const resolved = await resolve(
  501. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  502. resolutionContext(port, "ok"),
  503. );
  504. const output = (await fillWorkflowHoleToolEntry.handler(
  505. (resolved as { input: unknown }).input,
  506. executionContext(port, "ok"),
  507. )) as CreateWorkflowOutput;
  508. expect(output.ok).toBe(true);
  509. // 行给自己起名的那一块:名字来自解析出的留白,随输出与 display 走(transcript 不存回填的入参)。
  510. expect(output.fill).toEqual({
  511. siteId: "hole#1",
  512. name: "决定分组",
  513. draftPath: join(CWD, WORKFLOW_DRAFTS_DIR, "ok.dwf.ts"),
  514. line: WAITING_HOLE.line,
  515. });
  516. expect(createCreateWorkflowDisplay(FILL_WORKFLOW_HOLE_TOOL_NAME, output)?.fill).toEqual(
  517. output.fill,
  518. );
  519. expect(output.diagnostics).toEqual([]);
  520. expect(output.response).toContain("joined run dwfrun-1");
  521. expect(output.response).toContain("决定分组");
  522. expect(output.response).toContain("判定, 复核");
  523. expect(output.response).toContain(`${join(WORKFLOW_DRAFTS_DIR, "ok.dwf.ts")}`);
  524. expect(output.response).toContain("AmendWorkflow");
  525. expect(output.causalityGraph?.steps).toHaveLength(1);
  526. expect(output.causalityGraph?.phases?.map((phase) => phase.name)).toEqual(["判定"]);
  527. expect("status" in output).toBe(false);
  528. expect("backgroundTaskId" in output).toBe(false);
  529. });
  530. it("returns the same capability failure for an absent port and an absent method", async () => {
  531. const { port } = stubRunPort({ withoutFillHole: true, snapshot: { holes: [WAITING_HOLE] } });
  532. const input = { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY };
  533. const withoutPort = asFailure(
  534. await fillWorkflowHoleToolEntry.handler(input, executionContext(undefined, "cap")),
  535. );
  536. const withoutMethod = asFailure(
  537. await fillWorkflowHoleToolEntry.handler(input, executionContext(port, "cap")),
  538. );
  539. expect(withoutPort.message).toContain("workflow_fill_unavailable");
  540. expect(withoutMethod).toEqual(withoutPort);
  541. });
  542. });
  543. // 审批(docs/dynamic-workflow/launch.md「Approval」):与 AmendWorkflow 同一条 owner 规则——本会话的 run
  544. // 免确认,别的会话的 run 开窗;窗的 optionsPolicy 是会话级 always-allow。
  545. interface RunOutcome {
  546. brokerRequests: PermissionBrokerRequest[];
  547. permissionRequested: PermissionRequestedPayload[];
  548. result: ToolExecutionResult;
  549. }
  550. async function runThroughExecutor(options: {
  551. name: string;
  552. port: DynamicWorkflowRunPort;
  553. input?: Record<string, unknown>;
  554. }): Promise<RunOutcome> {
  555. const sessionId = createSessionId(options.name);
  556. const turnId = createTurnId(options.name);
  557. const traceContext = createRootTraceContext({ sessionId, turnId });
  558. const events: SessionEvent[] = [];
  559. const brokerRequests: PermissionBrokerRequest[] = [];
  560. const registry = createToolRegistry();
  561. registry.register(fillWorkflowHoleToolEntry);
  562. const executor = createToolExecutor({
  563. emitEvent: async (event) => {
  564. events.push(event);
  565. },
  566. dynamicWorkflowRunPort: options.port,
  567. mode: "build",
  568. permissionBroker: {
  569. async requestPermission(request) {
  570. brokerRequests.push(request);
  571. return { decision: "allow" as const };
  572. },
  573. },
  574. permissionService: new PermissionService(defaultPermissionConfig),
  575. registry,
  576. sessionId,
  577. turnId,
  578. traceContext,
  579. workingDirectory: CWD,
  580. });
  581. const result = await executor.execute(
  582. {
  583. id: createToolCallId(options.name),
  584. input: options.input ?? { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  585. name: FILL_WORKFLOW_HOLE_TOOL_NAME,
  586. },
  587. { traceContext },
  588. );
  589. return {
  590. brokerRequests,
  591. permissionRequested: events
  592. .filter((event) => event.type === SessionEventType.PermissionRequested)
  593. .map((event) => event.payload as PermissionRequestedPayload),
  594. result,
  595. };
  596. }
  597. describe("FillWorkflowHole — owner rule", () => {
  598. it("fills a hole of a run this session started without a window", async () => {
  599. const name = "fill-owned";
  600. const { port, fills } = stubRunPort({
  601. snapshot: { parentSessionId: sessionOf(name), holes: [WAITING_HOLE] },
  602. });
  603. const outcome = await runThroughExecutor({ name, port });
  604. expect(outcome.permissionRequested).toHaveLength(0);
  605. expect(outcome.brokerRequests).toHaveLength(0);
  606. expect(outcome.result.success).toBe(true);
  607. expect(fills).toHaveLength(1);
  608. });
  609. it("asks for another session's run, with the hole facts in the input and the session always-allow option", async () => {
  610. const name = "fill-foreign";
  611. const { port, fills } = stubRunPort({
  612. snapshot: { parentSessionId: "sess_someone-else", holes: [WAITING_HOLE] },
  613. });
  614. const outcome = await runThroughExecutor({ name, port });
  615. expect(outcome.permissionRequested).toHaveLength(1);
  616. const payload = outcome.permissionRequested[0]!;
  617. expect(payload.toolName).toBe(FILL_WORKFLOW_HOLE_TOOL_NAME);
  618. expect(payload.optionsPolicy).toBe("session-always-allow");
  619. expect(payload.input).toMatchObject({
  620. run_id: "dwfrun-1",
  621. hole_id: "hole#1",
  622. hole: { name: "决定分组", type: "Verdict", owned_by_this_session: false },
  623. });
  624. // Allow → 补全照常。
  625. expect(fills).toHaveLength(1);
  626. expect(outcome.result.success).toBe(true);
  627. });
  628. });
  629. // 确认窗:函数体点名了 run 绑定表之外的模型,端口必回 9011(bootstrap 的 unboundFillModelDiagnostics),
  630. // 所以不开一个注定作废的窗,与编不过的有效脚本同规(MR !2837 评审 CR-01)。
  631. describe("FillWorkflowHole — approval gate for models the body names", () => {
  632. const STORED = [
  633. 'phase("准备");',
  634. 'const v = await hole<string>("裁决", "decide");',
  635. "return v;",
  636. ].join("\n");
  637. const holeId = collectSites(createWorkflowProgram(STORED)).holes[0]!.id;
  638. const body = (name: string) =>
  639. `const j = await agent("judge", { model: model(${JSON.stringify(name)}) }).ask<string>("judge it");\nreturn j;`;
  640. async function gateFor(name: string, modelBindings?: Record<string, string>) {
  641. const { port } = stubRunPort({
  642. snapshot: {
  643. parentSessionId: "sess_someone-else",
  644. holes: [{ ...WAITING_HOLE, siteId: holeId }],
  645. ...(modelBindings === undefined ? {} : { modelBindings }),
  646. },
  647. });
  648. (port as { getScript?: (runId: string) => Promise<string> }).getScript = async () => STORED;
  649. const resolved = await resolve(
  650. { run_id: "dwfrun-1", hole_id: holeId, script: body(name) },
  651. resolutionContext(port, `fill-gate-${name}`),
  652. );
  653. if (!resolved.result) throw new Error("resolveInput refused");
  654. return fillWorkflowHoleToolEntry.prepareApproval!(resolved.input).gate;
  655. }
  656. it("opens the window when every model the body names is in the run's table", async () => {
  657. expect(await gateFor("GLM-5.3-Flash", { "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash" })).toBe("ask");
  658. });
  659. it("skips the window when the body names a model outside the table, or the run bound none", async () => {
  660. expect(await gateFor("GLM-5.3$high", { "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash" })).toBe(
  661. "proceed",
  662. );
  663. expect(await gateFor("GLM-5.3-Flash")).toBe("proceed");
  664. });
  665. });
  666. // 递归留白(站点 id `hole#1/hole#1`):早期的 hole_not_waiting 判定按 siteId 逐字比对,`fill_unchanged` 的键
  667. // 以 `\0` 拼接(id 里的 `/` 不参与切分),fill 文件按留白**名字**铸名(名字在全部留白里唯一)。
  668. describe("FillWorkflowHole — nested hole ids", () => {
  669. const NESTED_ID = "hole#1/hole#1";
  670. const nestedHole = { ...WAITING_HOLE, siteId: NESTED_ID, name: "内层裁决", type: "Inner" };
  671. it("resolves a nested id, refuses a sibling nested id that is not waiting, and names the fill file by the hole name", async () => {
  672. const name = "nested";
  673. const draftsDir = join(CWD, WORKFLOW_DRAFTS_DIR);
  674. const { port, fills } = stubRunPort({
  675. snapshot: {
  676. parentSessionId: sessionOf(name),
  677. scriptPath: join(draftsDir, "nested.dwf.ts"),
  678. holes: [{ ...WAITING_HOLE, state: "filled", filledAt: 1 }, nestedHole],
  679. },
  680. fill: {
  681. ok: false,
  682. reason: "compile_failed",
  683. message: "no",
  684. diagnostics: [{ line: 1, column: 1, message: "bad", code: 1, inFill: true }],
  685. },
  686. });
  687. // 外层 hole#1 已补过 → hole_not_waiting;内层 hole#1/hole#1 在等 → 放行,事实块是内层的。
  688. const outer = asFailure(
  689. await resolve(
  690. { run_id: "dwfrun-1", hole_id: "hole#1", script: BODY },
  691. resolutionContext(port, name),
  692. ),
  693. );
  694. expect(outer.message).toContain("already filled");
  695. const unknown = asFailure(
  696. await resolve(
  697. { run_id: "dwfrun-1", hole_id: "hole#1/hole#2", script: BODY },
  698. resolutionContext(port, name),
  699. ),
  700. );
  701. expect(unknown.message).toContain("hole#1/hole#2");
  702. const resolved = await resolve(
  703. { run_id: "dwfrun-1", hole_id: NESTED_ID, script: BODY },
  704. resolutionContext(port, name),
  705. );
  706. expect(resolved).toMatchObject({
  707. result: true,
  708. input: {
  709. hole_id: NESTED_ID,
  710. hole: { name: "内层裁决", type: "Inner", line: 12, owned_by_this_session: true },
  711. },
  712. });
  713. // fill 文件按名字铸:`nested.内层裁决.dwf.ts`;端口收到的 holeId 是嵌套 id 原文。
  714. const output = (await fillWorkflowHoleToolEntry.handler(
  715. (resolved as { input: unknown }).input,
  716. executionContext(port, name),
  717. )) as CreateWorkflowOutput;
  718. expect(fills[0]).toMatchObject({ holeId: NESTED_ID, body: BODY });
  719. const fillFile = join(draftsDir, "nested.内层裁决.dwf.ts");
  720. expect(readFileSync(fillFile, "utf8")).toBe(BODY);
  721. expect(output.response).toContain(`hole ${NESTED_ID} of run dwfrun-1 is still waiting`);
  722. // 同一份字节经 path 交回来 → fill_unchanged,键里的嵌套 id 没被 `/` 切坏。
  723. const again = asFailure(
  724. await resolve(
  725. { run_id: "dwfrun-1", hole_id: NESTED_ID, path: fillFile },
  726. resolutionContext(port, name),
  727. ),
  728. );
  729. expect(again.message).toContain("fill_unchanged");
  730. expect(again.message).toContain(NESTED_ID);
  731. // 另一个留白 id 不共享这条记录。
  732. const other = await resolve(
  733. { run_id: "dwfrun-1", hole_id: "hole#1/hole#3", path: fillFile },
  734. resolutionContext(port, name),
  735. );
  736. expect(other).toMatchObject({ result: false });
  737. expect((other as ToolHandlerFailure).message).not.toContain("fill_unchanged");
  738. });
  739. });