amend-workflow-permission.test.ts 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  1. import { mkdtempSync, readFileSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterAll, describe, expect, it } from "vitest";
  5. import {
  6. CoreErrorType,
  7. SessionEventType,
  8. createRootTraceContext,
  9. createSessionId,
  10. createToolCallId,
  11. createTurnId,
  12. type CollaborationMode,
  13. type CreateWorkflowOutput,
  14. type DynamicWorkflowRunAmendRequest,
  15. type DynamicWorkflowRunAmendResult,
  16. type DynamicWorkflowRunPort,
  17. type DynamicWorkflowRunRetuneRequest,
  18. type DynamicWorkflowRunRetuneResult,
  19. type DynamicWorkflowRunSnapshot,
  20. type ModelCatalogEntry,
  21. type ModelCatalogPort,
  22. type PermissionBrokerPort,
  23. type PermissionBrokerRequest,
  24. type PermissionRequestedPayload,
  25. type SessionEvent,
  26. type ToolExecutionResult,
  27. } from "@zcode/contracts";
  28. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  29. import { createToolExecutor } from "../src/tool/executor.js";
  30. import { amendWorkflowToolEntry } from "../src/tool/handlers/amend-workflow.js";
  31. import { createToolRegistry } from "../src/tool/registry.js";
  32. import { AMEND_WORKFLOW_ERROR_CODE } from "../src/tool/handlers/amend-workflow-resolve.js";
  33. import { workflowRunNotFoundFailure } from "../src/tool/handlers/workflow-run-introspection.js";
  34. // docs/dynamic-workflow/launch.md「The `AmendWorkflow` tool」与「Amending this session's runs」:
  35. // resolveInput 把 run_id 解析成 predecessor 事实块 → 权限服务据它放行本会话的 run / 照常 ask 别的
  36. // → handler 调 port.amend(service 负责停在飞前驱、等结算、导入、启动)。
  37. function cleanScript(actor: string): string {
  38. return [
  39. "interface R { done: boolean }",
  40. `const r = await agent("${actor}").ask<R>("do");`,
  41. "return r.done;",
  42. ].join("\n");
  43. }
  44. /** 分析器语料里的脚本(与 create-workflow-tool.test.ts 同一份 corpus、同一条读法)。 */
  45. function fixture(name: string): string {
  46. return readFileSync(
  47. new URL(`../../dynamic-workflow/tests/graphs/${name}`, import.meta.url),
  48. "utf8",
  49. );
  50. }
  51. const BROKEN_SCRIPT = 'const x: number = "s";';
  52. // 真目录而不是一个写死的 /tmp 路径:内联修订会往 `<cwd>/.zcode/workflow-drafts/` 写草稿
  53. // (docs/dynamic-workflow/launch.md「Script files」),用例之间不该互相看见对方的草稿。
  54. const AMEND_CWD = mkdtempSync(join(tmpdir(), "dwf-amend-cwd-"));
  55. afterAll(() => {
  56. rmSync(AMEND_CWD, { force: true, recursive: true });
  57. });
  58. /** 本会话的 id 由用例名派生(run() 里同一条派生),所以「归属」在这里可控。 */
  59. function sessionOf(name: string): string {
  60. return createSessionId(name) as unknown as string;
  61. }
  62. interface StubPortOptions {
  63. /** getTask 的答案:缺席即「run 不存在」。 */
  64. snapshot?: Partial<DynamicWorkflowRunSnapshot>;
  65. /** amend 的答案;缺省成功铸 `dwfrun-amended`。 */
  66. amend?: DynamicWorkflowRunAmendResult;
  67. /** 默认并发 D;缺席即端口没有 `defaultConcurrency`(老宿主的形状)。 */
  68. defaultConcurrency?: number;
  69. /**
  70. * 前驱存档的脚本,即 `getScript` 的答案(docs/dynamic-workflow/launch.md「Keeping the
  71. * predecessor's script」)。缺席即端口**没有** `getScript`(老宿主的形状);`null` 即方法在、
  72. * 记录里却没有脚本(脚本落库之前的老 run)。
  73. */
  74. storedScript?: string | null;
  75. /**
  76. * `retuneConcurrency` 的答复(docs/dynamic-workflow/launch.md「Changing only the parallelism of a
  77. * live run」)。缺席即端口**没有**这个方法(老宿主的形状)——那时只改并发的调用照旧走修订。
  78. */
  79. retune?:
  80. | DynamicWorkflowRunRetuneResult
  81. | ((request: DynamicWorkflowRunRetuneRequest) => DynamicWorkflowRunRetuneResult);
  82. }
  83. function stubRunPort(options: StubPortOptions = {}): {
  84. port: DynamicWorkflowRunPort;
  85. amends: DynamicWorkflowRunAmendRequest[];
  86. getTaskCalls: string[];
  87. getScriptCalls: string[];
  88. retunes: DynamicWorkflowRunRetuneRequest[];
  89. } {
  90. const amends: DynamicWorkflowRunAmendRequest[] = [];
  91. const getTaskCalls: string[] = [];
  92. const getScriptCalls: string[] = [];
  93. const retunes: DynamicWorkflowRunRetuneRequest[] = [];
  94. const unreachable = (name: string) => () => {
  95. throw new Error(`stubRunPort.${name} 不应被 AmendWorkflow 触及`);
  96. };
  97. return {
  98. port: {
  99. async getTask(taskId: string) {
  100. getTaskCalls.push(taskId);
  101. if (options.snapshot === undefined) return undefined;
  102. // 只给基类字段;`runStatus` 由用例决定——缺席即「还在跑」(resolveInput 据此读作 running)。
  103. return {
  104. runId: taskId,
  105. taskId,
  106. startedAt: new Date(0),
  107. status: "running",
  108. ...options.snapshot,
  109. } as DynamicWorkflowRunSnapshot;
  110. },
  111. async amend(request) {
  112. amends.push(request);
  113. return options.amend ?? { ok: true, runId: "dwfrun-amended" };
  114. },
  115. ...(options.defaultConcurrency === undefined
  116. ? {}
  117. : { defaultConcurrency: () => options.defaultConcurrency as number }),
  118. ...(options.storedScript === undefined
  119. ? {}
  120. : {
  121. async getScript(runId: string) {
  122. getScriptCalls.push(runId);
  123. return options.storedScript ?? undefined;
  124. },
  125. }),
  126. ...(options.retune === undefined
  127. ? {}
  128. : {
  129. async retuneConcurrency(request: DynamicWorkflowRunRetuneRequest) {
  130. retunes.push(request);
  131. return typeof options.retune === "function"
  132. ? options.retune(request)
  133. : (options.retune as DynamicWorkflowRunRetuneResult);
  134. },
  135. }),
  136. submit: unreachable("submit"),
  137. waitForTask: unreachable("waitForTask"),
  138. cancel: unreachable("cancel"),
  139. listEvents: unreachable("listEvents"),
  140. } as unknown as DynamicWorkflowRunPort,
  141. amends,
  142. getTaskCalls,
  143. getScriptCalls,
  144. retunes,
  145. };
  146. }
  147. interface RunOptions {
  148. broker?: PermissionBrokerPort;
  149. input?: Record<string, unknown>;
  150. /** 宿主的模型目录;缺席即「这台机器不能选子代理模型」。 */
  151. modelCatalogPort?: ModelCatalogPort;
  152. mode?: CollaborationMode;
  153. name: string;
  154. port?: DynamicWorkflowRunPort;
  155. runId?: string;
  156. script?: string;
  157. }
  158. interface RunOutcome {
  159. brokerRequests: PermissionBrokerRequest[];
  160. permissionRequested: PermissionRequestedPayload[];
  161. result: ToolExecutionResult;
  162. }
  163. async function run(options: RunOptions): Promise<RunOutcome> {
  164. const sessionId = createSessionId(options.name);
  165. const turnId = createTurnId(options.name);
  166. const traceContext = createRootTraceContext({ sessionId, turnId });
  167. const events: SessionEvent[] = [];
  168. const brokerRequests: PermissionBrokerRequest[] = [];
  169. const permissionBroker: PermissionBrokerPort = {
  170. async requestPermission(request, requestOptions) {
  171. brokerRequests.push(request);
  172. return (
  173. options.broker?.requestPermission(request, requestOptions) ?? { decision: "allow" as const }
  174. );
  175. },
  176. };
  177. const registry = createToolRegistry();
  178. registry.register(amendWorkflowToolEntry);
  179. const executor = createToolExecutor({
  180. emitEvent: async (event) => {
  181. events.push(event);
  182. },
  183. ...(options.port ? { dynamicWorkflowRunPort: options.port } : {}),
  184. ...(options.modelCatalogPort ? { modelCatalogPort: options.modelCatalogPort } : {}),
  185. mode: options.mode ?? "build",
  186. permissionBroker,
  187. permissionService: new PermissionService(defaultPermissionConfig),
  188. registry,
  189. sessionId,
  190. turnId,
  191. traceContext,
  192. workingDirectory: AMEND_CWD,
  193. });
  194. const result = await executor.execute(
  195. {
  196. id: createToolCallId(options.name),
  197. input: options.input ?? {
  198. run_id: options.runId ?? "dwfrun-prev",
  199. script: options.script ?? cleanScript(options.name),
  200. },
  201. name: "AmendWorkflow",
  202. },
  203. { traceContext },
  204. );
  205. return {
  206. brokerRequests,
  207. permissionRequested: events
  208. .filter((event) => event.type === SessionEventType.PermissionRequested)
  209. .map((event) => event.payload as PermissionRequestedPayload),
  210. result,
  211. };
  212. }
  213. describe("AmendWorkflow — owner rule", () => {
  214. it("amends a settled run this session started without a window, naming both runs", async () => {
  215. const name = "amend-owned-settled";
  216. const { port, amends, getTaskCalls } = stubRunPort({
  217. snapshot: { parentSessionId: sessionOf(name), runStatus: "errored", status: "failed" },
  218. });
  219. const outcome = await run({ name, port });
  220. // 第一次 getTask 是 resolveInput 解析前驱;之后的是后台追踪器轮询新 run(与 CreateWorkflow 同)。
  221. expect(getTaskCalls[0]).toBe("dwfrun-prev");
  222. expect(outcome.permissionRequested).toHaveLength(0);
  223. expect(outcome.brokerRequests).toHaveLength(0);
  224. expect(outcome.result.success).toBe(true);
  225. expect(amends).toHaveLength(1);
  226. expect(amends[0]).toMatchObject({
  227. cwd: AMEND_CWD,
  228. predecessorRunId: "dwfrun-prev",
  229. parentSessionId: sessionOf(name),
  230. });
  231. expect("name" in amends[0]!).toBe(false);
  232. const output = outcome.result.output as CreateWorkflowOutput;
  233. expect(output.status).toBe("backgrounded");
  234. expect(output.backgroundTaskId).toBe("dwfrun-amended");
  235. expect(output.response).toContain("dwfrun-prev had already settled");
  236. expect(output.response).toContain("run dwfrun-amended");
  237. expect(output.response).toContain("Do not wait for it");
  238. });
  239. it("amends a RUNNING run this session started without a window and reports the supersede", async () => {
  240. const name = "amend-owned-running";
  241. const { port, amends } = stubRunPort({
  242. snapshot: { parentSessionId: sessionOf(name), status: "running" },
  243. amend: { ok: true, runId: "dwfrun-next", supersededRunId: "dwfrun-prev" },
  244. });
  245. const outcome = await run({ name, port, mode: "plan" });
  246. expect(outcome.permissionRequested).toHaveLength(0);
  247. expect(amends).toHaveLength(1);
  248. const output = outcome.result.output as CreateWorkflowOutput;
  249. expect(output.backgroundTaskId).toBe("dwfrun-next");
  250. expect(output.response).toContain("dwfrun-prev was still running");
  251. expect(output.response).toContain("stopped and superseded");
  252. expect(output.response).toContain("will not send a notification of its own");
  253. });
  254. // 轨道画的是**新脚本**的站点:修订沿用前驱的锚点,两张表却必须一起从新脚本的图上取。
  255. it("passes the new script's phase table and its alongside table through", async () => {
  256. const name = "amend-alongside";
  257. const { port, amends } = stubRunPort({
  258. snapshot: { parentSessionId: sessionOf(name), status: "completed", runStatus: "completed" },
  259. });
  260. await run({
  261. name,
  262. port,
  263. input: { run_id: "dwfrun-prev", script: fixture("strand-fanout-two-phases-join.ts") },
  264. });
  265. expect(amends).toHaveLength(1);
  266. expect(amends[0]!.phaseNames).toEqual(["A", "B", "C"]);
  267. expect(amends[0]!.phaseAlongside).toEqual([[], [0], []]);
  268. });
  269. it("passes the optional display name through", async () => {
  270. const name = "amend-owned-named";
  271. const { port, amends } = stubRunPort({
  272. snapshot: { parentSessionId: sessionOf(name), status: "completed", runStatus: "completed" },
  273. });
  274. await run({
  275. name,
  276. port,
  277. input: { run_id: "dwfrun-prev", script: cleanScript(name), name: "second pass" },
  278. });
  279. expect(amends[0]?.name).toBe("second pass");
  280. });
  281. it("asks for another session's run, with the create_workflow graph and the predecessor facts in the input", async () => {
  282. const name = "amend-foreign";
  283. const { port, amends } = stubRunPort({
  284. snapshot: { parentSessionId: "sess_someone-else", status: "running", name: "triage" },
  285. });
  286. const outcome = await run({ name, port });
  287. expect(outcome.permissionRequested).toHaveLength(1);
  288. const payload = outcome.permissionRequested[0]!;
  289. expect(payload.toolName).toBe("AmendWorkflow");
  290. expect(payload.optionsPolicy).toBe("session-always-allow");
  291. expect(payload.display?.kind).toBe("create_workflow");
  292. expect(
  293. (payload.display as { causalityGraph?: { steps: unknown[] } }).causalityGraph?.steps,
  294. ).toHaveLength(1);
  295. // 确认窗从**入参**读 lineage 行与「仍在运行」的注记(协议零新载荷)。
  296. expect(payload.input).toMatchObject({
  297. run_id: "dwfrun-prev",
  298. predecessor: { name: "triage", status: "running", owned_by_this_session: false },
  299. });
  300. // Allow → amend 照常。
  301. expect(amends).toHaveLength(1);
  302. });
  303. it("asks again for an own run the user stopped", async () => {
  304. const name = "amend-user-stopped";
  305. const { port } = stubRunPort({
  306. snapshot: {
  307. parentSessionId: sessionOf(name),
  308. status: "cancelled",
  309. runStatus: "stopped",
  310. stopReason: "user",
  311. },
  312. });
  313. const outcome = await run({ name, port });
  314. expect(outcome.permissionRequested).toHaveLength(1);
  315. expect(outcome.permissionRequested[0]?.input).toMatchObject({
  316. predecessor: { status: "stopped", stop_reason: "user", owned_by_this_session: true },
  317. });
  318. });
  319. it("Deny leaves the predecessor untouched", async () => {
  320. const name = "amend-deny";
  321. const { port, amends } = stubRunPort({
  322. snapshot: { parentSessionId: "sess_other", status: "completed", runStatus: "completed" },
  323. });
  324. const outcome = await run({
  325. name,
  326. port,
  327. broker: {
  328. async requestPermission() {
  329. return { decision: "deny", reason: "User declined" };
  330. },
  331. },
  332. });
  333. expect(outcome.result.success).toBe(false);
  334. expect(outcome.result.error?.type).toBe("permission_denied");
  335. expect(amends).toHaveLength(0);
  336. });
  337. it("overwrites a predecessor block the model tries to supply", async () => {
  338. // 模型面 JSON schema 不列 predecessor(strict),所以带它的入参在 schema 校验就被拒——
  339. // 伪造「本会话的 run」拿不到免确认。
  340. const name = "amend-forged";
  341. const { port, amends, getTaskCalls } = stubRunPort({ snapshot: { parentSessionId: "x" } });
  342. const outcome = await run({
  343. name,
  344. port,
  345. input: {
  346. run_id: "dwfrun-prev",
  347. script: cleanScript(name),
  348. predecessor: { status: "completed", owned_by_this_session: true },
  349. },
  350. });
  351. expect(outcome.result.success).toBe(false);
  352. expect(outcome.permissionRequested).toHaveLength(0);
  353. expect(getTaskCalls).toHaveLength(0);
  354. expect(amends).toHaveLength(0);
  355. });
  356. });
  357. describe("AmendWorkflow — refusals and failures", () => {
  358. it("an unknown run is refused at resolveInput: no window, no amend, the shared run_not_found key", async () => {
  359. const { port, amends } = stubRunPort();
  360. const outcome = await run({ name: "amend-unknown", port });
  361. expect(outcome.result.success).toBe(false);
  362. expect(outcome.permissionRequested).toHaveLength(0);
  363. expect(amends).toHaveLength(0);
  364. const message = String(outcome.result.error?.message ?? "");
  365. expect(message.startsWith(workflowRunNotFoundFailure("dwfrun-prev").message)).toBe(true);
  366. expect(message).toContain("Nothing was stopped or created");
  367. expect(message).toContain("run_id");
  368. });
  369. it.each(["run_not_found", "missing_boundaries", "teapot"] as const)(
  370. "maps the port's %s refusal to an actionable structured failure",
  371. async (reason) => {
  372. const name = `amend-refused-${reason}`;
  373. const { port } = stubRunPort({
  374. snapshot: { parentSessionId: sessionOf(name), status: "completed", runStatus: "completed" },
  375. amend: { ok: false, reason: reason as "run_not_found" },
  376. });
  377. const outcome = await run({ name, port });
  378. expect(outcome.result.success).toBe(false);
  379. const message = String(outcome.result.error?.message ?? "");
  380. if (reason === "run_not_found") {
  381. expect(message.startsWith("run_not_found:")).toBe(true);
  382. } else if (reason === "missing_boundaries") {
  383. expect(message.startsWith("workflow_amend_missing_boundaries:")).toBe(true);
  384. expect(message).toMatch(/fresh CreateWorkflow/u);
  385. } else {
  386. expect(message.startsWith("workflow_amend_refused:")).toBe(true);
  387. expect(message).toContain("teapot");
  388. }
  389. expect(message).toContain("dwfrun-prev");
  390. expect(message).toMatch(/nothing was stopped or created/iu);
  391. },
  392. );
  393. it("a script that does not compile never asks and never touches the predecessor", async () => {
  394. const name = "amend-broken";
  395. const { port, amends } = stubRunPort({ snapshot: { parentSessionId: "sess_other" } });
  396. const outcome = await run({ name, port, script: BROKEN_SCRIPT });
  397. expect(outcome.permissionRequested).toHaveLength(0);
  398. expect(amends).toHaveLength(0);
  399. const output = outcome.result.output as CreateWorkflowOutput;
  400. expect(output.ok).toBe(false);
  401. expect(output.diagnostics.length).toBeGreaterThan(0);
  402. expect(output.response).toContain("Run dwfrun-prev was not touched");
  403. });
  404. it("without a run port the script is only typechecked", async () => {
  405. const outcome = await run({ name: "amend-no-port" });
  406. // 端口缺席:resolveInput 放行、权限照常 ask(没有归属事实)、handler 只报编译通过。
  407. expect(outcome.permissionRequested).toHaveLength(1);
  408. const output = outcome.result.output as CreateWorkflowOutput;
  409. expect(output.ok).toBe(true);
  410. expect(output.backgroundTaskId).toBeUndefined();
  411. expect(output.response).toContain("NOT executed");
  412. });
  413. });
  414. // 并发上界的三态(docs/dynamic-workflow/concurrency.md「Two bounds on a run」):省略 = 沿用前驱、
  415. // `null` = 解除、数 = 设定。三态只活到 resolveInput——handler 与确认窗此后只面对「一个数或没有」,
  416. // 而 handler 自己会用 .strict() 重新 parse 一遍归一化后的入参,所以形状越界在这些用例里必炸。
  417. describe("AmendWorkflow — max_concurrency", () => {
  418. /** 归一化后递到端口的那个数;键缺席即 undefined。 */
  419. async function amendWith(
  420. name: string,
  421. options: { defaultConcurrency?: number; inherited?: number; requested?: number | null },
  422. ): Promise<{ amends: DynamicWorkflowRunAmendRequest[]; outcome: RunOutcome }> {
  423. const { port, amends } = stubRunPort({
  424. snapshot: {
  425. parentSessionId: sessionOf(name),
  426. status: "completed",
  427. runStatus: "completed",
  428. ...(options.inherited === undefined ? {} : { maxConcurrency: options.inherited }),
  429. },
  430. ...(options.defaultConcurrency === undefined
  431. ? {}
  432. : { defaultConcurrency: options.defaultConcurrency }),
  433. });
  434. const outcome = await run({
  435. name,
  436. port,
  437. input: {
  438. run_id: "dwfrun-prev",
  439. script: cleanScript(name),
  440. ...(options.requested === undefined ? {} : { max_concurrency: options.requested }),
  441. },
  442. });
  443. return { amends, outcome };
  444. }
  445. it("a number above the default goes through unclamped and is named in the result", async () => {
  446. const { amends, outcome } = await amendWith("amend-maxconc-raised", {
  447. defaultConcurrency: 8,
  448. requested: 32,
  449. });
  450. expect(amends[0]?.maxConcurrency).toBe(32);
  451. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  452. "At most 32 subagents run at once.",
  453. );
  454. });
  455. it("a number equal to the default is named as the default", async () => {
  456. const { amends, outcome } = await amendWith("amend-maxconc-at-default", {
  457. defaultConcurrency: 8,
  458. requested: 8,
  459. });
  460. expect(amends[0]?.maxConcurrency).toBe(8);
  461. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  462. "At most 8 subagents run at once (the default).",
  463. );
  464. });
  465. it("a number under the default goes through unchanged", async () => {
  466. const { amends, outcome } = await amendWith("amend-maxconc-set", {
  467. defaultConcurrency: 8,
  468. requested: 2,
  469. });
  470. expect(amends[0]?.maxConcurrency).toBe(2);
  471. const response = (outcome.result.output as CreateWorkflowOutput).response;
  472. expect(response).toContain("At most 2 subagents run at once.");
  473. expect(response).not.toContain("(the default)");
  474. });
  475. it("null removes the predecessor's limit: the key is gone, not zeroed", async () => {
  476. const { amends, outcome } = await amendWith("amend-maxconc-null", {
  477. defaultConcurrency: 8,
  478. inherited: 2,
  479. requested: null,
  480. });
  481. expect(amends).toHaveLength(1);
  482. expect("maxConcurrency" in amends[0]!).toBe(false);
  483. expect((outcome.result.output as CreateWorkflowOutput).response).not.toContain("At most");
  484. });
  485. it("omitting the field inherits the predecessor's limit", async () => {
  486. const { amends, outcome } = await amendWith("amend-maxconc-inherit", {
  487. defaultConcurrency: 8,
  488. inherited: 2,
  489. });
  490. expect(amends[0]?.maxConcurrency).toBe(2);
  491. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  492. "At most 2 subagents run at once.",
  493. );
  494. });
  495. it("omitting the field inherits a raised predecessor's limit as is", async () => {
  496. // 快照只在不等于默认时带 maxConcurrency:一个被调高过的前驱把它的数原样传下去,不再被钳。
  497. const { amends } = await amendWith("amend-maxconc-inherit-raised", {
  498. defaultConcurrency: 8,
  499. inherited: 40,
  500. });
  501. expect(amends[0]?.maxConcurrency).toBe(40);
  502. });
  503. it("omitting it stays absent when the predecessor ran at the default", async () => {
  504. // 快照只在不等于默认时带 maxConcurrency,所以「前驱没设过」在这里就是字段缺席。
  505. const { amends } = await amendWith("amend-maxconc-none", { defaultConcurrency: 8 });
  506. expect(amends).toHaveLength(1);
  507. expect("maxConcurrency" in amends[0]!).toBe(false);
  508. });
  509. it("shows the inherited limit in the confirmation window of another session's run", async () => {
  510. // 确认窗读的是归一化后的入参:沿用下来的上界必须在那里,否则用户批准的是另一个 run。
  511. const { port } = stubRunPort({
  512. snapshot: { parentSessionId: "sess_someone-else", status: "running", maxConcurrency: 2 },
  513. defaultConcurrency: 8,
  514. });
  515. const outcome = await run({
  516. name: "amend-maxconc-window",
  517. port,
  518. input: { run_id: "dwfrun-prev", script: cleanScript("amend-maxconc-window") },
  519. });
  520. expect(outcome.permissionRequested).toHaveLength(1);
  521. expect(outcome.permissionRequested[0]!.input).toMatchObject({ max_concurrency: 2 });
  522. });
  523. it("strips null and passes a number through when the session has no run port", async () => {
  524. // 端口缺席:既没有前驱也没有默认并发,三态塌成「一个数或没有」,且归一化后的入参仍要
  525. // 过得了 handler 的 .strict() 重解析。
  526. const removed = await run({
  527. name: "amend-maxconc-no-port-null",
  528. input: {
  529. run_id: "dwfrun-prev",
  530. script: cleanScript("amend-maxconc-no-port-null"),
  531. max_concurrency: null,
  532. },
  533. });
  534. expect(removed.result.success).toBe(true);
  535. expect(removed.permissionRequested[0]!.input).not.toHaveProperty("max_concurrency");
  536. const kept = await run({
  537. name: "amend-maxconc-no-port-number",
  538. input: {
  539. run_id: "dwfrun-prev",
  540. script: cleanScript("amend-maxconc-no-port-number"),
  541. max_concurrency: 4,
  542. },
  543. });
  544. expect(kept.permissionRequested[0]!.input).toMatchObject({ max_concurrency: 4 });
  545. });
  546. });
  547. // 子代理模型的三态(docs/dynamic-workflow/launch.md):省略 = 沿用前驱、`null` = 回到会话模型、
  548. // 字符串 = 设定。与并发上界逐条同构,唯一的差别是**沿用的那一个也要重新解析一遍**——前驱可能
  549. // 是几天前起的,它选的模型此后可能被删掉或停用。
  550. describe("AmendWorkflow — subagent_model", () => {
  551. function entry(
  552. providerId: string,
  553. modelId: string,
  554. extra: Partial<ModelCatalogEntry> = {},
  555. ): ModelCatalogEntry {
  556. return { providerId, modelId, reasoningLevels: [], current: false, ...extra };
  557. }
  558. const CATALOG: ModelCatalogPort = {
  559. listModels: () => [
  560. entry("bigmodel", "GLM-4.6", { current: true }),
  561. entry("openai", "gpt-5"),
  562. ],
  563. };
  564. /** 目录里只剩一个模型:前驱选过的那一个已经不在了。 */
  565. const SHRUNK_CATALOG: ModelCatalogPort = {
  566. listModels: () => [entry("openai", "gpt-5", { current: true })],
  567. };
  568. async function amendWith(
  569. name: string,
  570. options: {
  571. catalog?: ModelCatalogPort;
  572. inherited?: string;
  573. requested?: string | null;
  574. },
  575. ): Promise<{ amends: DynamicWorkflowRunAmendRequest[]; outcome: RunOutcome }> {
  576. const { port, amends } = stubRunPort({
  577. snapshot: {
  578. parentSessionId: sessionOf(name),
  579. status: "completed",
  580. runStatus: "completed",
  581. ...(options.inherited === undefined ? {} : { subagentModel: options.inherited }),
  582. },
  583. });
  584. const outcome = await run({
  585. name,
  586. port,
  587. ...(options.catalog === undefined ? {} : { modelCatalogPort: options.catalog }),
  588. input: {
  589. run_id: "dwfrun-prev",
  590. script: cleanScript(name),
  591. ...(options.requested === undefined ? {} : { subagent_model: options.requested }),
  592. },
  593. });
  594. return { amends, outcome };
  595. }
  596. it("a model id is resolved to its canonical form and named in the result", async () => {
  597. const { amends, outcome } = await amendWith("amend-model-set", {
  598. catalog: CATALOG,
  599. requested: "gpt-5",
  600. });
  601. expect(amends[0]?.subagentModel).toEqual({ providerId: "openai", modelId: "gpt-5" });
  602. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  603. "Subagents run on openai/gpt-5 (the main agent stays on the session model).",
  604. );
  605. });
  606. it("null puts the subagents back on the session model: the key is gone, not blanked", async () => {
  607. const { amends, outcome } = await amendWith("amend-model-null", {
  608. catalog: CATALOG,
  609. inherited: "bigmodel/GLM-4.6",
  610. requested: null,
  611. });
  612. expect(amends).toHaveLength(1);
  613. expect("subagentModel" in amends[0]!).toBe(false);
  614. expect((outcome.result.output as CreateWorkflowOutput).response).not.toContain(
  615. "Subagents run on",
  616. );
  617. });
  618. it("omitting the field inherits the predecessor's model", async () => {
  619. const { amends, outcome } = await amendWith("amend-model-inherit", {
  620. catalog: CATALOG,
  621. inherited: "bigmodel/GLM-4.6",
  622. });
  623. expect(amends[0]?.subagentModel).toEqual({ providerId: "bigmodel", modelId: "GLM-4.6" });
  624. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  625. "Subagents run on bigmodel/GLM-4.6",
  626. );
  627. });
  628. it("omitting it stays absent when the predecessor ran on the session model", async () => {
  629. const { amends } = await amendWith("amend-model-none", { catalog: CATALOG });
  630. expect(amends).toHaveLength(1);
  631. expect("subagentModel" in amends[0]!).toBe(false);
  632. });
  633. /**
  634. * 沿用的那一个也要重新解析:不重解的话,失败要等到子代理第一次开口时才发生,那时看起来像
  635. * 运行时故障而不是一次可以当场改掉的选择。
  636. */
  637. it("fails now, not at the first ask, when the inherited model has vanished from the catalog", async () => {
  638. const { amends, outcome } = await amendWith("amend-model-vanished", {
  639. catalog: SHRUNK_CATALOG,
  640. inherited: "bigmodel/GLM-4.6",
  641. });
  642. expect(outcome.result.success).toBe(false);
  643. expect(amends).toHaveLength(0);
  644. expect(outcome.permissionRequested).toHaveLength(0);
  645. const message = String(outcome.result.error?.message ?? "");
  646. // 文案必须说清它是**继承来的**:这次调用压根没提模型名。
  647. expect(message).toContain("inherited the predecessor run's subagent model");
  648. expect(message).toContain("bigmodel/GLM-4.6");
  649. expect(message).toContain("subagent_model: null");
  650. expect(message).toContain("Nothing was stopped or created.");
  651. });
  652. it("an unresolvable id stops the call before anything is stopped or created", async () => {
  653. const { amends, outcome } = await amendWith("amend-model-miss", {
  654. catalog: CATALOG,
  655. requested: "gemini-3",
  656. });
  657. expect(outcome.result.success).toBe(false);
  658. expect(amends).toHaveLength(0);
  659. expect(outcome.permissionRequested).toHaveLength(0);
  660. expect(String(outcome.result.error?.message ?? "")).toContain("No configured model matches");
  661. });
  662. it("shows the inherited model in the confirmation window of another session's run", async () => {
  663. // 确认窗读的是归一化后的入参:沿用下来的模型必须在那里,否则用户批准的是另一个 run。
  664. const { port } = stubRunPort({
  665. snapshot: {
  666. parentSessionId: "sess_someone-else",
  667. status: "running",
  668. subagentModel: "bigmodel/GLM-4.6",
  669. },
  670. });
  671. const outcome = await run({
  672. name: "amend-model-window",
  673. port,
  674. modelCatalogPort: CATALOG,
  675. input: { run_id: "dwfrun-prev", script: cleanScript("amend-model-window") },
  676. });
  677. expect(outcome.permissionRequested).toHaveLength(1);
  678. expect(outcome.permissionRequested[0]!.input).toMatchObject({
  679. subagent_model: "bigmodel/GLM-4.6",
  680. });
  681. });
  682. it("refuses a model id on a host with no catalog, and still strips null", async () => {
  683. const refused = await amendWith("amend-model-no-catalog", { requested: "gpt-5" });
  684. expect(refused.outcome.result.success).toBe(false);
  685. expect(String(refused.outcome.result.error?.message ?? "")).toContain(
  686. "This host cannot choose a subagent model",
  687. );
  688. const removed = await amendWith("amend-model-no-catalog-null", { requested: null });
  689. expect(removed.outcome.result.success).toBe(true);
  690. expect("subagentModel" in removed.amends[0]!).toBe(false);
  691. });
  692. it("strips the field and passes a resolved id through when the session has no run port", async () => {
  693. // 端口缺席:没有前驱可沿用,`null` 与省略都塌成缺席,而给了字符串仍然要解析一次——
  694. // 归一化后的入参还要过得了 handler 的 .strict() 重解析。
  695. const resolved = await run({
  696. name: "amend-model-no-port",
  697. modelCatalogPort: CATALOG,
  698. input: {
  699. run_id: "dwfrun-prev",
  700. script: cleanScript("amend-model-no-port"),
  701. subagent_model: "gpt-5",
  702. },
  703. });
  704. expect(resolved.result.success).toBe(true);
  705. expect(resolved.permissionRequested[0]!.input).toMatchObject({
  706. subagent_model: "openai/gpt-5",
  707. });
  708. const removed = await run({
  709. name: "amend-model-no-port-null",
  710. modelCatalogPort: CATALOG,
  711. input: {
  712. run_id: "dwfrun-prev",
  713. script: cleanScript("amend-model-no-port-null"),
  714. subagent_model: null,
  715. },
  716. });
  717. expect(removed.result.success).toBe(true);
  718. expect(removed.permissionRequested[0]!.input).not.toHaveProperty("subagent_model");
  719. });
  720. });
  721. // 省略 `script` = 沿用前驱的脚本(docs/dynamic-workflow/launch.md「Keeping the predecessor's
  722. // script」):与两个设定同一条规则、同一个生命周期——resolveInput 读前驱存档的脚本回填进入参并
  723. // 盖上 `predecessor.script_inherited`,此后 hook、确认窗、prepareApproval 与 handler 面对的都是
  724. // 「一份脚本」,端口也永远收到一份脚本。
  725. describe("AmendWorkflow — omitted script", () => {
  726. const STORED = fixture("strand-fanout-two-phases-join.ts");
  727. it("keeps the predecessor's script byte for byte and changes only the settings", async () => {
  728. const name = "amend-keep-script";
  729. const { port, amends, getScriptCalls } = stubRunPort({
  730. snapshot: { parentSessionId: sessionOf(name), status: "completed", runStatus: "completed" },
  731. defaultConcurrency: 8,
  732. storedScript: STORED,
  733. });
  734. const outcome = await run({
  735. name,
  736. port,
  737. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  738. });
  739. expect(outcome.result.success).toBe(true);
  740. expect(outcome.permissionRequested).toHaveLength(0);
  741. expect(getScriptCalls).toEqual(["dwfrun-prev"]);
  742. expect(amends).toHaveLength(1);
  743. expect(amends[0]!.scriptText).toBe(STORED);
  744. expect(amends[0]!.maxConcurrency).toBe(2);
  745. // 阶段表从回填的脚本上取:侧栏轨道画的仍是将要跑的那份脚本。
  746. expect(amends[0]!.phaseNames).toEqual(["A", "B", "C"]);
  747. expect(amends[0]!.phaseAlongside).toEqual([[], [0], []]);
  748. const output = outcome.result.output as CreateWorkflowOutput;
  749. expect(output.status).toBe("backgrounded");
  750. expect(output.response).toContain(
  751. "The script of run dwfrun-prev started unchanged in the background as run dwfrun-amended.",
  752. );
  753. expect(output.response).not.toContain("revised script");
  754. expect(output.response).toContain("At most 2 subagents run at once.");
  755. });
  756. it("with nothing but run_id, re-runs the script under the predecessor's settings", async () => {
  757. const name = "amend-keep-everything";
  758. const catalog: ModelCatalogPort = {
  759. listModels: () => [
  760. { providerId: "openai", modelId: "gpt-5", reasoningLevels: [], current: true },
  761. ],
  762. };
  763. const { port, amends } = stubRunPort({
  764. snapshot: {
  765. parentSessionId: sessionOf(name),
  766. status: "failed",
  767. runStatus: "errored",
  768. maxConcurrency: 3,
  769. subagentModel: "openai/gpt-5",
  770. },
  771. defaultConcurrency: 8,
  772. storedScript: STORED,
  773. });
  774. const outcome = await run({
  775. name,
  776. port,
  777. modelCatalogPort: catalog,
  778. input: { run_id: "dwfrun-prev" },
  779. });
  780. expect(outcome.result.success).toBe(true);
  781. expect(amends).toHaveLength(1);
  782. expect(amends[0]).toMatchObject({
  783. scriptText: STORED,
  784. maxConcurrency: 3,
  785. subagentModel: { providerId: "openai", modelId: "gpt-5" },
  786. });
  787. });
  788. it("asks for another session's run with the predecessor's script, its graph and the inherited flag", async () => {
  789. const stored = cleanScript("amend-keep-foreign");
  790. const { port, amends } = stubRunPort({
  791. snapshot: { parentSessionId: "sess_someone-else", status: "running", name: "triage" },
  792. storedScript: stored,
  793. });
  794. const outcome = await run({
  795. name: "amend-keep-foreign",
  796. port,
  797. input: { run_id: "dwfrun-prev" },
  798. });
  799. expect(outcome.permissionRequested).toHaveLength(1);
  800. const payload = outcome.permissionRequested[0]!;
  801. // 确认窗与 hook 读的是归一化后的入参:脚本就是将要跑的那一份,flag 让窗上说「脚本不变」。
  802. expect(payload.input).toMatchObject({
  803. run_id: "dwfrun-prev",
  804. script: stored,
  805. predecessor: {
  806. name: "triage",
  807. status: "running",
  808. owned_by_this_session: false,
  809. script_inherited: true,
  810. },
  811. });
  812. expect(payload.display?.kind).toBe("create_workflow");
  813. expect(
  814. (payload.display as { causalityGraph?: { steps: unknown[] } }).causalityGraph?.steps,
  815. ).toHaveLength(1);
  816. expect(amends).toHaveLength(1);
  817. expect(amends[0]!.scriptText).toBe(stored);
  818. });
  819. it("a passed script never reads the stored one and carries no inherited flag", async () => {
  820. const script = cleanScript("amend-pass-script");
  821. const { port, amends, getScriptCalls } = stubRunPort({
  822. snapshot: { parentSessionId: "sess_someone-else", status: "completed" },
  823. storedScript: "return 'stale';",
  824. });
  825. const outcome = await run({ name: "amend-pass-script", port, script });
  826. expect(getScriptCalls).toHaveLength(0);
  827. const predecessor = (outcome.permissionRequested[0]!.input as Record<string, unknown>)
  828. .predecessor as Record<string, unknown>;
  829. expect(predecessor).not.toHaveProperty("script_inherited");
  830. expect(amends[0]!.scriptText).toBe(script);
  831. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  832. "The revised script started in the background as run dwfrun-amended.",
  833. );
  834. });
  835. it("an unknown run is refused as run_not_found before the script is read", async () => {
  836. const { port, amends, getScriptCalls } = stubRunPort({ storedScript: STORED });
  837. const outcome = await run({
  838. name: "amend-keep-unknown",
  839. port,
  840. input: { run_id: "dwfrun-prev" },
  841. });
  842. expect(outcome.result.success).toBe(false);
  843. expect(String(outcome.result.error?.message ?? "").startsWith("run_not_found:")).toBe(true);
  844. expect(getScriptCalls).toHaveLength(0);
  845. expect(amends).toHaveLength(0);
  846. });
  847. it.each([
  848. [
  849. "a predecessor whose record has no script",
  850. "no-record",
  851. { storedScript: null },
  852. "has no stored script",
  853. ],
  854. ["a host whose port cannot read scripts", "no-method", {}, "cannot read"],
  855. ] as const)(
  856. "%s is refused before any window, pointing at the whole script",
  857. async (_label, key, options, detail) => {
  858. const name = `amend-keep-unavailable-${key}`;
  859. const { port, amends } = stubRunPort({
  860. snapshot: { parentSessionId: sessionOf(name), status: "completed", runStatus: "completed" },
  861. ...options,
  862. });
  863. const outcome = await run({
  864. name,
  865. port,
  866. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  867. });
  868. expect(outcome.result.success).toBe(false);
  869. expect(outcome.permissionRequested).toHaveLength(0);
  870. expect(amends).toHaveLength(0);
  871. const message = String(outcome.result.error?.message ?? "");
  872. expect(message.startsWith("workflow_amend_script_unavailable:")).toBe(true);
  873. expect(message).toContain("dwfrun-prev");
  874. expect(message).toContain(detail);
  875. expect(message).toContain("pass the whole script");
  876. expect(message).toContain("Nothing was stopped or created.");
  877. },
  878. );
  879. it("a session without a run port is refused the same way: there is nothing to typecheck", async () => {
  880. const outcome = await run({ name: "amend-keep-no-port", input: { run_id: "dwfrun-prev" } });
  881. expect(outcome.result.success).toBe(false);
  882. expect(outcome.permissionRequested).toHaveLength(0);
  883. const message = String(outcome.result.error?.message ?? "");
  884. expect(message.startsWith("workflow_amend_script_unavailable:")).toBe(true);
  885. expect(message).toContain("pass the whole script");
  886. });
  887. /**
  888. * 继承来的脚本编不过(facade 在前驱之后变过):模型这次调用没写这些行,不说清就会把诊断读成
  889. * 自己传错了参数——与「继承来的模型已不可用」同一条理由。
  890. */
  891. it("an inherited script that no longer compiles says it was inherited, and touches nothing", async () => {
  892. const name = "amend-keep-broken";
  893. const { port, amends } = stubRunPort({
  894. snapshot: { parentSessionId: sessionOf(name), status: "running" },
  895. storedScript: BROKEN_SCRIPT,
  896. });
  897. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  898. expect(outcome.permissionRequested).toHaveLength(0);
  899. expect(amends).toHaveLength(0);
  900. const output = outcome.result.output as CreateWorkflowOutput;
  901. expect(output.ok).toBe(false);
  902. expect(output.diagnostics.length).toBeGreaterThan(0);
  903. const [lead] = output.response.split("\n");
  904. expect(lead).toContain("run dwfrun-prev's script");
  905. expect(lead).toContain("inherited because you omitted both `script` and `path`");
  906. expect(output.response).toMatch(/L\d+:C\d+ /u);
  907. // 沿用的脚本与任何不来自文件的脚本一样落成草稿(docs/dynamic-workflow/launch.md「Script files」),
  908. // 所以下一步是去改那个文件,而不是把整份脚本内联再抄一遍。
  909. expect(output.response).toContain("Edit that file in place and resubmit with `path:");
  910. expect(output.response).toContain("Run dwfrun-prev was not touched");
  911. });
  912. });
  913. // 只改并发、run 还活着 = 就地调并发,不是一次修订(docs/dynamic-workflow/launch.md「Changing only
  914. // the parallelism of a live run」):同一个 run id、不铸后继、不 supersede、不读脚本、不编译、
  915. // 一个窗都不弹。路由在 resolveInput 判定,handler 调的是 `port.retuneConcurrency`。
  916. describe("AmendWorkflow — 只改并发即就地生效", () => {
  917. const STORED = fixture("strand-fanout-two-phases-join.ts");
  918. /** 一个还在跑、属于本会话、端口带 retuneConcurrency 的前驱。 */
  919. function liveRetunablePort(
  920. name: string,
  921. options: {
  922. defaultConcurrency?: number;
  923. inherited?: number;
  924. owner?: string;
  925. retune?: StubPortOptions["retune"];
  926. runStatus?: DynamicWorkflowRunSnapshot["runStatus"];
  927. storedScript?: string | null;
  928. } = {},
  929. ): ReturnType<typeof stubRunPort> {
  930. return stubRunPort({
  931. snapshot: {
  932. parentSessionId: options.owner ?? sessionOf(name),
  933. status: "running",
  934. ...(options.runStatus === undefined ? {} : { runStatus: options.runStatus }),
  935. ...(options.inherited === undefined ? {} : { maxConcurrency: options.inherited }),
  936. },
  937. defaultConcurrency: options.defaultConcurrency ?? 8,
  938. retune: options.retune ?? { ok: true, maxConcurrency: 2, previous: 8, defaultConcurrency: 8 },
  939. ...(options.storedScript === undefined ? {} : { storedScript: options.storedScript }),
  940. });
  941. }
  942. it("retunes in place: one run named, no successor, no compile, no script read, no window", async () => {
  943. const name = "retune-ok";
  944. const { port, amends, retunes, getScriptCalls } = liveRetunablePort(name, {
  945. retune: { ok: true, maxConcurrency: 2, previous: 8, defaultConcurrency: 8 },
  946. });
  947. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  948. expect(outcome.result.success).toBe(true);
  949. expect(outcome.permissionRequested).toHaveLength(0);
  950. expect(outcome.brokerRequests).toHaveLength(0);
  951. // 这条路不读脚本、不编译、不起后继。
  952. expect(getScriptCalls).toHaveLength(0);
  953. expect(amends).toHaveLength(0);
  954. expect(retunes).toEqual([{ runId: "dwfrun-prev", maxConcurrency: 2 }]);
  955. const output = outcome.result.output as CreateWorkflowOutput;
  956. expect(output.ok).toBe(true);
  957. expect(output.diagnostics).toEqual([]);
  958. expect(output.status).toBeUndefined();
  959. expect(output.backgroundTaskId).toBeUndefined();
  960. expect(output.causalityGraph).toBeUndefined();
  961. // 「就地生效」是一个显式的块,消费方不按形状猜;工具卡据它不画「已编译」。
  962. expect(output.retuned).toEqual({
  963. runId: "dwfrun-prev",
  964. maxConcurrency: 2,
  965. previous: 8,
  966. defaultConcurrency: 8,
  967. });
  968. // 没有 display 载荷:这条路一行脚本都没编译,而 `create_workflow` 的 `ok` 在卡上读作「已编译」。
  969. expect(outcome.result.display).toBeUndefined();
  970. expect(output.response).toContain("Applied to the running run dwfrun-prev");
  971. expect(output.response).toContain("at most 2 subagents run at once");
  972. expect(output.response).toContain("no new run was started");
  973. // 只点名一个 run:模型据此分辨这次调用走的是哪条路。
  974. expect(output.response).not.toContain("superseded");
  975. });
  976. it("null travels to the port as null and the applied default is named as the default", async () => {
  977. const name = "retune-null";
  978. const { port, retunes } = liveRetunablePort(name, {
  979. inherited: 2,
  980. retune: { ok: true, maxConcurrency: 8, previous: 2, defaultConcurrency: 8 },
  981. });
  982. const outcome = await run({
  983. name,
  984. port,
  985. input: { run_id: "dwfrun-prev", max_concurrency: null },
  986. });
  987. // 端口收的是三态里的 `null` 本身:默认并发那个数只有端口知道,工具不猜第二遍。
  988. expect(retunes).toEqual([{ runId: "dwfrun-prev", maxConcurrency: null }]);
  989. const response = (outcome.result.output as CreateWorkflowOutput).response;
  990. expect(response).toContain("Applied to the running run dwfrun-prev");
  991. expect(response).toContain("at most 8 subagents run at once (the default)");
  992. });
  993. it("a number above the default reaches the port as is and is applied as is", async () => {
  994. const name = "retune-raised";
  995. const { port, retunes } = liveRetunablePort(name, {
  996. defaultConcurrency: 16,
  997. inherited: 2,
  998. retune: { ok: true, maxConcurrency: 32, previous: 2, defaultConcurrency: 16 },
  999. });
  1000. const outcome = await run({
  1001. name,
  1002. port,
  1003. input: { run_id: "dwfrun-prev", max_concurrency: 32 },
  1004. });
  1005. // 默认并发不是上限:工具不钳,端口也不钳,模型读到的就是它要的那个 32。
  1006. expect(retunes[0]?.maxConcurrency).toBe(32);
  1007. const response = (outcome.result.output as CreateWorkflowOutput).response;
  1008. expect(response).toContain("at most 32 subagents run at once");
  1009. expect(response).not.toContain("(the default)");
  1010. });
  1011. it("the same bound is refused `unchanged` before any hook, naming the bound in force", async () => {
  1012. const name = "retune-unchanged";
  1013. const { port, retunes, amends, getScriptCalls } = liveRetunablePort(name, { inherited: 2 });
  1014. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1015. expect(outcome.result.success).toBe(false);
  1016. expect(outcome.permissionRequested).toHaveLength(0);
  1017. // 早于 hook 与确认窗:端口一次都没被碰过。
  1018. expect(retunes).toHaveLength(0);
  1019. expect(amends).toHaveLength(0);
  1020. expect(getScriptCalls).toHaveLength(0);
  1021. const message = String(outcome.result.error?.message ?? "");
  1022. expect(message.startsWith("workflow_retune_unchanged:")).toBe(true);
  1023. expect(message).toContain("dwfrun-prev");
  1024. expect(message).toContain("2");
  1025. expect(message).toMatch(/nothing was stopped/iu);
  1026. });
  1027. it("null against a run already at the default is `unchanged` too", async () => {
  1028. const name = "retune-unchanged-default";
  1029. const { port, retunes } = liveRetunablePort(name);
  1030. const outcome = await run({
  1031. name,
  1032. port,
  1033. input: { run_id: "dwfrun-prev", max_concurrency: null },
  1034. });
  1035. expect(outcome.result.success).toBe(false);
  1036. expect(retunes).toHaveLength(0);
  1037. const message = String(outcome.result.error?.message ?? "");
  1038. expect(message.startsWith("workflow_retune_unchanged:")).toBe(true);
  1039. expect(message).toContain(
  1040. "already runs at the default parallelism (at most 8 subagents at once)",
  1041. );
  1042. });
  1043. it("the port's own `unchanged` (the value moved under us) is the same refusal", async () => {
  1044. const name = "retune-unchanged-race";
  1045. const { port, amends } = liveRetunablePort(name, {
  1046. inherited: 4,
  1047. retune: { ok: false, reason: "unchanged", current: 2 },
  1048. });
  1049. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1050. expect(outcome.result.success).toBe(false);
  1051. expect(amends).toHaveLength(0);
  1052. const message = String(outcome.result.error?.message ?? "");
  1053. expect(message.startsWith("workflow_retune_unchanged:")).toBe(true);
  1054. expect(message).toContain("2");
  1055. });
  1056. it.each([
  1057. ["a revised script", { script: cleanScript("retune-with-script") }],
  1058. ["a script file", { path: "nope.ts" }],
  1059. ["a subagent model", { subagent_model: null }],
  1060. ["a name", { name: "second pass" }],
  1061. ] as const)("%s sends the call down the amendment path", async (_label, extra) => {
  1062. const name = `retune-not-only-${Object.keys(extra)[0]}`;
  1063. const { port, retunes, amends } = liveRetunablePort(name, { storedScript: STORED });
  1064. const outcome = await run({
  1065. name,
  1066. port,
  1067. input: { run_id: "dwfrun-prev", max_concurrency: 2, ...extra },
  1068. });
  1069. expect(retunes).toHaveLength(0);
  1070. if ("path" in extra) {
  1071. // 读不出来的文件是修订自己的失败——证明这次调用确实走了修订。
  1072. expect(outcome.result.success).toBe(false);
  1073. expect(String(outcome.result.error?.message ?? "")).toContain(
  1074. "workflow_script_file_unreadable:",
  1075. );
  1076. return;
  1077. }
  1078. expect(amends).toHaveLength(1);
  1079. expect((outcome.result.output as CreateWorkflowOutput).status).toBe("backgrounded");
  1080. });
  1081. it("a run that already settled takes the amendment, unchanged", async () => {
  1082. const name = "retune-settled";
  1083. const { port, retunes, amends, getScriptCalls } = liveRetunablePort(name, {
  1084. runStatus: "errored",
  1085. storedScript: STORED,
  1086. });
  1087. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1088. expect(retunes).toHaveLength(0);
  1089. expect(getScriptCalls).toEqual(["dwfrun-prev"]);
  1090. expect(amends).toHaveLength(1);
  1091. expect(amends[0]?.maxConcurrency).toBe(2);
  1092. expect((outcome.result.output as CreateWorkflowOutput).status).toBe("backgrounded");
  1093. });
  1094. it("a port with no retuneConcurrency keeps today's amendment, window and all", async () => {
  1095. const { port, amends, getScriptCalls } = stubRunPort({
  1096. snapshot: { parentSessionId: "sess_someone-else", status: "running", name: "triage" },
  1097. defaultConcurrency: 8,
  1098. storedScript: STORED,
  1099. });
  1100. const outcome = await run({
  1101. name: "retune-old-host",
  1102. port,
  1103. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  1104. });
  1105. expect(getScriptCalls).toEqual(["dwfrun-prev"]);
  1106. expect(outcome.permissionRequested).toHaveLength(1);
  1107. expect(amends).toHaveLength(1);
  1108. expect((outcome.result.output as CreateWorkflowOutput).status).toBe("backgrounded");
  1109. });
  1110. // 「没有窗」对任何归属都成立:窗是为了把脚本摆到人面前,而这条路一段脚本都不跑。
  1111. /**
  1112. * 拒绝必须与本工具既有的那些(run_not_found / missing_boundaries / script_unchanged)走**同一个
  1113. * 出口**:`success: false` + 带码的 `error`,没有 output。这条路不带 display 载荷,读侧(工具卡)
  1114. * 因此只能靠「是不是错误」分辨「调成功了」与「被拒了」——两种结局的入参长得一模一样。
  1115. */
  1116. /**
  1117. * 回话文本是**唯一**过得了 v4 的事实(这条路没有 display 载荷,协议的 toolOutput 只带 text),
  1118. * 工具卡拿它当整行画。所以两种上界都逐字钉住:改词等于改 UI。
  1119. */
  1120. it.each([
  1121. [
  1122. "a bound below the default",
  1123. { ok: true, maxConcurrency: 2, previous: 8, defaultConcurrency: 8 } as const,
  1124. "Applied to the running run dwfrun-prev; at most 2 subagents run at once. Run dwfrun-prev keeps running under it: nothing was stopped and no new run was started.",
  1125. ],
  1126. [
  1127. "a bound of one",
  1128. { ok: true, maxConcurrency: 1, previous: 8, defaultConcurrency: 8 } as const,
  1129. "Applied to the running run dwfrun-prev; at most 1 subagent runs at once. Run dwfrun-prev keeps running under it: nothing was stopped and no new run was started.",
  1130. ],
  1131. [
  1132. "the default",
  1133. { ok: true, maxConcurrency: 8, previous: 2, defaultConcurrency: 8 } as const,
  1134. "Applied to the running run dwfrun-prev; at most 8 subagents run at once (the default). Run dwfrun-prev keeps running under it: nothing was stopped and no new run was started.",
  1135. ],
  1136. [
  1137. "a bound above the default",
  1138. { ok: true, maxConcurrency: 40, previous: 8, defaultConcurrency: 8 } as const,
  1139. "Applied to the running run dwfrun-prev; at most 40 subagents run at once. Run dwfrun-prev keeps running under it: nothing was stopped and no new run was started.",
  1140. ],
  1141. ] as const)("reads back verbatim for %s", async (label, retune, expected) => {
  1142. const name = `retune-text-${label.replace(/\s+/gu, "-")}`;
  1143. const { port } = liveRetunablePort(name, { inherited: 4, retune });
  1144. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1145. expect((outcome.result.output as CreateWorkflowOutput).response).toBe(expected);
  1146. });
  1147. it("a refusal comes back as a tool error with no output, like every other one", async () => {
  1148. const name = "retune-refusal-shape";
  1149. const { port } = liveRetunablePort(name, { inherited: 2 });
  1150. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1151. expect(outcome.result.success).toBe(false);
  1152. expect(outcome.result.output).toBeNull();
  1153. expect(outcome.result.error?.type).toBe(CoreErrorType.ToolExecutionFailed);
  1154. // 码是稳定判别键(house rule:不拿错误文本做流程判断),取自码表而不是散落的字面量。
  1155. expect(outcome.result.error?.code).toBe(String(AMEND_WORKFLOW_ERROR_CODE.RETUNE_UNCHANGED));
  1156. expect(
  1157. String(outcome.result.error?.message ?? "").startsWith("workflow_retune_unchanged:"),
  1158. ).toBe(true);
  1159. });
  1160. it("another session's live run is retuned with no window either", async () => {
  1161. const { port, retunes } = liveRetunablePort("retune-foreign-live", {
  1162. owner: "sess_someone-else",
  1163. });
  1164. const outcome = await run({
  1165. name: "retune-foreign-live",
  1166. port,
  1167. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  1168. });
  1169. expect(outcome.permissionRequested).toHaveLength(0);
  1170. expect(outcome.brokerRequests).toHaveLength(0);
  1171. expect(retunes).toHaveLength(1);
  1172. expect(outcome.result.success).toBe(true);
  1173. });
  1174. });
  1175. // 结算竞态(docs/dynamic-workflow/launch.md「When the port says `not_live`」):同一份入参此刻
  1176. // 描述的是一次修订,能不能做取决于「那次修订本来要不要开窗」。
  1177. describe("AmendWorkflow — 就地调并发遇上 not_live", () => {
  1178. const STORED = fixture("strand-fanout-two-phases-join.ts");
  1179. /**
  1180. * resolveInput 看到的还是活的(端口随后答 not_live);handler 再读一次快照时它已是 `settled`
  1181. * 描述的那个终态。两次 getTask 答不同的事实,正是这条路要覆盖的竞态。
  1182. */
  1183. function racingPort(options: {
  1184. owner: string;
  1185. inherited?: number;
  1186. settled?: Partial<DynamicWorkflowRunSnapshot>;
  1187. storedScript?: string | null;
  1188. }): ReturnType<typeof stubRunPort> {
  1189. const base = stubRunPort({
  1190. snapshot: {
  1191. parentSessionId: options.owner,
  1192. status: "running",
  1193. ...(options.inherited === undefined ? {} : { maxConcurrency: options.inherited }),
  1194. },
  1195. defaultConcurrency: 8,
  1196. retune: { ok: false, reason: "not_live" },
  1197. ...(options.storedScript === undefined ? {} : { storedScript: options.storedScript }),
  1198. });
  1199. let reads = 0;
  1200. const port = base.port as unknown as Record<string, unknown>;
  1201. const first = port.getTask as (runId: string) => Promise<DynamicWorkflowRunSnapshot>;
  1202. port.getTask = async (runId: string) => {
  1203. const snapshot = await first(runId);
  1204. reads += 1;
  1205. // 第一次(resolveInput)仍读作在跑;第二次(handler 的落回路)读到终态。
  1206. return reads === 1 ? snapshot : ({ ...snapshot, ...options.settled } as typeof snapshot);
  1207. };
  1208. return base;
  1209. }
  1210. it("this session's own run falls through to a real amendment, reading the script at that point", async () => {
  1211. const name = "retune-race-own";
  1212. const { port, retunes, amends, getScriptCalls } = racingPort({
  1213. owner: sessionOf(name),
  1214. settled: { status: "completed", runStatus: "completed" },
  1215. storedScript: STORED,
  1216. });
  1217. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1218. expect(retunes).toHaveLength(1);
  1219. // 脚本是**这时候**才读的:retune 路上一次都没读过。
  1220. expect(getScriptCalls).toEqual(["dwfrun-prev"]);
  1221. expect(outcome.permissionRequested).toHaveLength(0);
  1222. expect(amends).toHaveLength(1);
  1223. expect(amends[0]).toMatchObject({ scriptText: STORED, maxConcurrency: 2 });
  1224. const output = outcome.result.output as CreateWorkflowOutput;
  1225. expect(output.status).toBe("backgrounded");
  1226. expect(output.response).toContain("started unchanged in the background as run dwfrun-amended");
  1227. });
  1228. it("null on the fall-through removes the limit: the port gets no maxConcurrency key", async () => {
  1229. const name = "retune-race-own-null";
  1230. const { port, amends } = racingPort({
  1231. owner: sessionOf(name),
  1232. // 前驱本来压在 2 上,所以 `null`(回默认)确实是一次改动,不是 `unchanged`。
  1233. inherited: 2,
  1234. settled: { status: "completed", runStatus: "completed" },
  1235. storedScript: STORED,
  1236. });
  1237. await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: null } });
  1238. expect(amends).toHaveLength(1);
  1239. expect("maxConcurrency" in amends[0]!).toBe(false);
  1240. });
  1241. it("a missing script on the fall-through is reported as the amendment's own refusal", async () => {
  1242. const name = "retune-race-own-no-script";
  1243. const { port, amends } = racingPort({
  1244. owner: sessionOf(name),
  1245. settled: { status: "completed", runStatus: "completed" },
  1246. storedScript: null,
  1247. });
  1248. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1249. expect(outcome.result.success).toBe(false);
  1250. expect(amends).toHaveLength(0);
  1251. const message = String(outcome.result.error?.message ?? "");
  1252. expect(message.startsWith("workflow_amend_script_unavailable:")).toBe(true);
  1253. expect(message).toContain("pass the whole script");
  1254. });
  1255. it("a script that no longer compiles on the fall-through comes back as diagnostics", async () => {
  1256. const name = "retune-race-own-broken";
  1257. const { port, amends } = racingPort({
  1258. owner: sessionOf(name),
  1259. settled: { status: "failed", runStatus: "errored" },
  1260. storedScript: BROKEN_SCRIPT,
  1261. });
  1262. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1263. expect(amends).toHaveLength(0);
  1264. const output = outcome.result.output as CreateWorkflowOutput;
  1265. expect(output.ok).toBe(false);
  1266. expect(output.diagnostics.length).toBeGreaterThan(0);
  1267. expect(output.response).toContain("Run dwfrun-prev was not touched");
  1268. });
  1269. it("another session's settled run is refused `run_settled`, not amended", async () => {
  1270. const { port, amends } = racingPort({
  1271. owner: "sess_someone-else",
  1272. settled: { status: "completed", runStatus: "completed" },
  1273. storedScript: STORED,
  1274. });
  1275. const outcome = await run({
  1276. name: "retune-race-foreign-settled",
  1277. port,
  1278. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  1279. });
  1280. expect(outcome.result.success).toBe(false);
  1281. expect(outcome.permissionRequested).toHaveLength(0);
  1282. expect(amends).toHaveLength(0);
  1283. // 与既有拒绝同一个出口:错误 + output 为 null(读侧没有 display 可看,只能靠这个分辨结局)。
  1284. expect(outcome.result.output).toBeNull();
  1285. expect(outcome.result.error?.type).toBe(CoreErrorType.ToolExecutionFailed);
  1286. expect(outcome.result.error?.code).toBe(String(AMEND_WORKFLOW_ERROR_CODE.RUN_SETTLED));
  1287. const message = String(outcome.result.error?.message ?? "");
  1288. expect(message.startsWith("workflow_run_settled:")).toBe(true);
  1289. expect(message).toContain("dwfrun-prev");
  1290. expect(message).toMatch(/call .*again/iu);
  1291. });
  1292. it("another session's run this agent never held live is refused `not_retunable`", async () => {
  1293. const { port, amends } = racingPort({
  1294. owner: "sess_someone-else",
  1295. settled: { runStatus: "pending" },
  1296. storedScript: STORED,
  1297. });
  1298. const outcome = await run({
  1299. name: "retune-race-foreign-pending",
  1300. port,
  1301. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  1302. });
  1303. expect(outcome.result.success).toBe(false);
  1304. expect(amends).toHaveLength(0);
  1305. expect(outcome.result.output).toBeNull();
  1306. expect(outcome.result.error?.type).toBe(CoreErrorType.ToolExecutionFailed);
  1307. expect(outcome.result.error?.code).toBe(String(AMEND_WORKFLOW_ERROR_CODE.NOT_RETUNABLE));
  1308. const message = String(outcome.result.error?.message ?? "");
  1309. expect(message.startsWith("workflow_run_not_retunable:")).toBe(true);
  1310. expect(message).toContain("dwfrun-prev");
  1311. });
  1312. // 用户亲手停下的 run 在修订路上本来要开窗(owner 规则把它排除在外),所以落回路不能替它跳过。
  1313. it("an own run the user stopped is refused instead of silently amended", async () => {
  1314. const name = "retune-race-own-user-stopped";
  1315. const { port, amends } = racingPort({
  1316. owner: sessionOf(name),
  1317. settled: { status: "cancelled", runStatus: "stopped", stopReason: "user" },
  1318. storedScript: STORED,
  1319. });
  1320. const outcome = await run({ name, port, input: { run_id: "dwfrun-prev", max_concurrency: 2 } });
  1321. expect(outcome.result.success).toBe(false);
  1322. expect(amends).toHaveLength(0);
  1323. expect(String(outcome.result.error?.message ?? "").startsWith("workflow_run_settled:")).toBe(
  1324. true,
  1325. );
  1326. });
  1327. });
  1328. // docs/dynamic-workflow/launch.md「What the model is told」:三条 bullet 说的是**同一条**规则(省略即
  1329. // 沿用前驱),脚本在最前——模型若以为脚本必填,就会为了改一个数把几千 token 的脚本再抄一遍。
  1330. // 2026-09-21 起描述只剩路由(docs/dynamic-workflow/launch.md「What the model is told」):沿用规则的
  1331. // 三态字段、两条来路的先后与就地调并发那一句都搬进了 dynamic-workflows 技能 §16.4,由技能门保证
  1332. // 读过;它们的顺序断言在 bootstrap/tests/dynamic-workflow-skill.test.ts。这里只钉描述必须留下的路由。
  1333. describe("AmendWorkflow — description", () => {
  1334. it("routes: a settings-only revision names neither script field, resume is another tool", () => {
  1335. const description = amendWorkflowToolEntry.metadata.description;
  1336. expect(description).toContain("neither `path` nor `script`");
  1337. // 停下的 run 不改任何东西就继续:那是 ResumeWorkflowRun 的活,不是一次空修订。
  1338. expect(description).toContain("To continue a stopped run unchanged, use ResumeWorkflowRun");
  1339. // 跑到一半就修,不先停不等结束——门的边界也写在这里:带脚本才需要技能。
  1340. expect(description).toContain("Do not TaskStop it first");
  1341. expect(description).toContain("a settings-only call is not");
  1342. });
  1343. });
  1344. // docs/dynamic-workflow/launch.md「Adjusting the settings in the window」:另一个会话的 run 才开窗,
  1345. // 窗里的调整与 CreateWorkflow 同一条路——回填块、批准后落进入参、结果先说一句。
  1346. describe("AmendWorkflow — settings adjusted in the confirmation window", () => {
  1347. const CATALOG: ModelCatalogPort = {
  1348. listModels: () => [
  1349. { providerId: "openai", modelId: "gpt-5", reasoningLevels: [], current: true },
  1350. ],
  1351. };
  1352. it("the ask carries the adjustable_settings block next to the predecessor facts", async () => {
  1353. const { port } = stubRunPort({
  1354. snapshot: { parentSessionId: "sess_someone-else", status: "running", maxConcurrency: 2 },
  1355. defaultConcurrency: 8,
  1356. });
  1357. const outcome = await run({ modelCatalogPort: CATALOG, name: "amend-adjustable", port });
  1358. expect(outcome.permissionRequested[0]!.input).toMatchObject({
  1359. max_concurrency: 2,
  1360. adjustable_settings: { subagent_model: true, concurrency_ceiling: 8 },
  1361. });
  1362. });
  1363. it("applies the adjustments to the amendment and names them in the result", async () => {
  1364. const { port, amends } = stubRunPort({
  1365. snapshot: { parentSessionId: "sess_someone-else", status: "running", maxConcurrency: 2 },
  1366. defaultConcurrency: 8,
  1367. });
  1368. const outcome = await run({
  1369. broker: {
  1370. async requestPermission() {
  1371. return {
  1372. decision: "allow",
  1373. inputAdjustments: { subagent_model: "gpt-5", max_concurrency: null },
  1374. };
  1375. },
  1376. },
  1377. modelCatalogPort: CATALOG,
  1378. name: "amend-adjusted",
  1379. port,
  1380. });
  1381. expect(amends).toHaveLength(1);
  1382. expect(amends[0]!.subagentModel).toEqual({ providerId: "openai", modelId: "gpt-5" });
  1383. expect("maxConcurrency" in amends[0]!).toBe(false);
  1384. const response = (outcome.result.output as CreateWorkflowOutput).response;
  1385. expect(response).toContain(
  1386. "Before approving, the user adjusted the settings in the confirmation window: subagents run on openai/gpt-5 (the main agent stays on the session model); the limit on subagents at once is back to the default.",
  1387. );
  1388. expect(response).not.toContain("At most 2");
  1389. });
  1390. it("an own run amends without a window, so it carries the block but never an adjustment", async () => {
  1391. const name = "amend-adjustable-owned";
  1392. const { port, amends } = stubRunPort({
  1393. snapshot: { parentSessionId: sessionOf(name), status: "completed", runStatus: "completed" },
  1394. defaultConcurrency: 8,
  1395. });
  1396. const outcome = await run({ name, port });
  1397. expect(outcome.permissionRequested).toHaveLength(0);
  1398. expect(amends).toHaveLength(1);
  1399. expect((outcome.result.output as CreateWorkflowOutput).response).not.toContain(
  1400. "Before approving",
  1401. );
  1402. });
  1403. });