workflow-driver-artifacts.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. /**
  2. * 用户面产物的 driver 侧执行(docs/dynamic-workflow/authoring.md「Publishing content」 + Tests 表的
  3. * driver 一行)。照 workflow-driver-world-run.test.ts 的形状:只碰 driver 端口本身,不经脚本、
  4. * 不经引擎——facade 的类型签名、id 的编译期字面量规则与版本号推导都在上游,这里防的是
  5. * 编译期之外的接线错误,以及「一次发布 → 一条落库记录 / 一条命名拒绝」的映射契约。
  6. *
  7. * ⚠ 术语:本文件的 artifact 一律指**用户面产物**(脚本交付给用户看的字节),不是引擎内部
  8. * 那个 artifact(顶层返回值,给模型看的)。见 spec 的「术语」表。
  9. *
  10. * 文件系统用**真实的**临时目录 + NodeFileSystemAdapter:这一侧要证的两件事(软链按真实路径
  11. * 判越界、cap+1 探测)都是真实文件系统的性质,用一个 fake 端口证不出来。store 则是 fake——
  12. * 它的落盘行为不归本切片,本切片只对「写进去的参数」负责。
  13. */
  14. import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
  15. import { tmpdir } from "node:os";
  16. import { join } from "node:path";
  17. import { afterAll, beforeAll, describe, expect, it } from "vitest";
  18. import { createFileSystemError } from "@zcode/contracts";
  19. import type {
  20. ExecutionPort,
  21. FileSystemPort,
  22. SessionId,
  23. ToolArtifactStorePort,
  24. ToolArtifactWriteResult,
  25. ToolBinaryArtifactWriteRequest,
  26. } from "@zcode/contracts";
  27. import { createNodeFileSystemAdapter } from "@zcode/adapters/fs";
  28. import {
  29. ARTIFACT_CAPS,
  30. InMemoryJournalStore,
  31. WorkflowError,
  32. type ArtifactPublishRequest,
  33. type WorkflowDriver,
  34. type WorkflowReportSink,
  35. } from "@zcode/dynamic-workflow";
  36. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  37. import { createAgentRuntimeWorkflowDriver } from "../src/app/workflow-driver.js";
  38. const SESSION_ID = "sess_parent" as SessionId;
  39. /** 触及即失败的执行端口:产物发布不该起子进程。 */
  40. function unsupportedExecutionPort(): ExecutionPort {
  41. return new Proxy({} as ExecutionPort, {
  42. get(_target, name) {
  43. return () => {
  44. throw new Error(`executionPort.${String(name)} 不应被产物发布触及`);
  45. };
  46. },
  47. });
  48. }
  49. function noopSink(): WorkflowReportSink {
  50. const unexpected = (name: string) => (): never => {
  51. throw new Error(`noopSink.${name} 不应被触及`);
  52. };
  53. return {
  54. askSubmitAttempted: unexpected("askSubmitAttempted"),
  55. askTurnEnded: unexpected("askTurnEnded"),
  56. askProgress: unexpected("askProgress"),
  57. askStats: unexpected("askStats"),
  58. askFailed: unexpected("askFailed"),
  59. };
  60. }
  61. interface RecordedWrite {
  62. kind: "text" | "binary";
  63. sessionId: string;
  64. toolCallId: string;
  65. toolName: string;
  66. retention: string | undefined;
  67. contentType: string;
  68. extension: string | undefined;
  69. byteLength: number;
  70. text?: string;
  71. }
  72. /** 记录写入参数的 fake store。`binary: false` 造一个只有文本写的 store(能力探测用)。 */
  73. function fakeArtifactStore(options?: { binary?: boolean; failWith?: Error }): {
  74. store: ToolArtifactStorePort;
  75. writes: RecordedWrite[];
  76. } {
  77. const writes: RecordedWrite[] = [];
  78. const receipt = (index: number, bytes: number, contentType: string): ToolArtifactWriteResult => ({
  79. id: `artifact-${index}`,
  80. uri: `zcode-artifact://${SESSION_ID}/artifact-${index}`,
  81. path: `/store/${SESSION_ID}/artifact-${index}`,
  82. bytes,
  83. contentType,
  84. createdAt: new Date("2026-09-04T00:00:00.000Z"),
  85. });
  86. const store: ToolArtifactStorePort = {
  87. writeToolResultArtifact: async (request) => {
  88. if (options?.failWith) throw options.failWith;
  89. const byteLength = Buffer.byteLength(request.content, "utf8");
  90. writes.push({
  91. kind: "text",
  92. sessionId: request.sessionId,
  93. toolCallId: String(request.toolCallId),
  94. toolName: request.toolName,
  95. retention: request.retention,
  96. contentType: request.contentType ?? "",
  97. extension: undefined,
  98. byteLength,
  99. text: request.content,
  100. });
  101. return receipt(writes.length, byteLength, request.contentType ?? "text/plain");
  102. },
  103. readToolResultArtifact: async () => {
  104. throw new Error("readToolResultArtifact 不应被本用例触及");
  105. },
  106. };
  107. if (options?.binary !== false) {
  108. store.writeToolResultBinaryArtifact = async (request: ToolBinaryArtifactWriteRequest) => {
  109. if (options?.failWith) throw options.failWith;
  110. writes.push({
  111. kind: "binary",
  112. sessionId: request.sessionId,
  113. toolCallId: String(request.toolCallId),
  114. toolName: request.toolName,
  115. retention: request.retention,
  116. contentType: request.contentType,
  117. extension: request.extension,
  118. byteLength: request.content.byteLength,
  119. });
  120. return receipt(writes.length, request.content.byteLength, request.contentType);
  121. };
  122. }
  123. return { store, writes };
  124. }
  125. function makeDriver(input: {
  126. cwd: string;
  127. fileSystemPort?: FileSystemPort;
  128. artifactStore?: ToolArtifactStorePort;
  129. parentSessionId?: SessionId;
  130. }): WorkflowDriver {
  131. return createAgentRuntimeWorkflowDriver({
  132. journal: new InMemoryJournalStore(),
  133. emit: () => undefined,
  134. fileSystemPort: input.fileSystemPort ?? createNodeFileSystemAdapter(),
  135. executionPort: unsupportedExecutionPort(),
  136. escalationRegistry: createWorkflowEscalationRegistry(),
  137. cwd: input.cwd,
  138. runId: "run-1",
  139. ...(input.artifactStore === undefined ? {} : { artifactStore: input.artifactStore }),
  140. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  141. runtimeFactory: () => {
  142. throw new Error("runtimeFactory 不应被产物发布触及");
  143. },
  144. })(noopSink());
  145. }
  146. function fileRequest(overrides: Partial<ArtifactPublishRequest> = {}): ArtifactPublishRequest {
  147. return {
  148. runId: "run-1",
  149. siteId: "artifact#1",
  150. ordinal: 1,
  151. op: "file",
  152. id: "report",
  153. version: 1,
  154. path: "out/report.pdf",
  155. ...overrides,
  156. };
  157. }
  158. function markdownRequest(overrides: Partial<ArtifactPublishRequest> = {}): ArtifactPublishRequest {
  159. return {
  160. runId: "run-1",
  161. siteId: "artifact#2",
  162. ordinal: 1,
  163. op: "markdown",
  164. id: "summary",
  165. version: 1,
  166. content: "# 结论\n\n跑通了。",
  167. ...overrides,
  168. };
  169. }
  170. /** 断言一次发布以某个结构化码被拒绝,并把错误交回给调用方做消息断言。 */
  171. async function rejection(promise: Promise<unknown>, code: string): Promise<WorkflowError> {
  172. let caught: unknown;
  173. try {
  174. await promise;
  175. } catch (error) {
  176. caught = error;
  177. }
  178. expect(caught, "发布本应被拒绝").toBeInstanceOf(WorkflowError);
  179. const error = caught as WorkflowError;
  180. expect(error.code).toBe(code);
  181. return error;
  182. }
  183. /** 本套件共用的工作区:真实临时目录,含一个越界目标供软链用例指向。 */
  184. let workspace: string;
  185. let outside: string;
  186. beforeAll(async () => {
  187. const root = await mkdtemp(join(tmpdir(), "zcode-dwf-artifact-"));
  188. workspace = join(root, "workspace");
  189. outside = join(root, "outside");
  190. await mkdir(join(workspace, "out"), { recursive: true });
  191. await mkdir(outside, { recursive: true });
  192. await writeFile(join(outside, "secret.txt"), "TOP SECRET", "utf8");
  193. await writeFile(join(workspace, "out", "report.pdf"), "%PDF-1.7\n…", "utf8");
  194. });
  195. afterAll(async () => {
  196. await rm(join(workspace, ".."), { recursive: true, force: true });
  197. });
  198. describe("workflow driver — 产物发布(artifact.file)", () => {
  199. it("把字节写进 store,并交出一条完整的落库记录", async () => {
  200. const { store, writes } = fakeArtifactStore();
  201. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  202. const before = Date.now();
  203. const record = await driver.executeArtifactPublish!(
  204. fileRequest({
  205. version: 3,
  206. opts: { title: "回归报告", description: "本轮的性能回归" },
  207. }),
  208. );
  209. expect(record).toMatchObject({
  210. id: "report",
  211. kind: "file",
  212. version: 3,
  213. title: "回归报告",
  214. description: "本轮的性能回归",
  215. contentType: "application/pdf",
  216. bytes: Buffer.byteLength("%PDF-1.7\n…", "utf8"),
  217. uri: `zcode-artifact://${SESSION_ID}/artifact-1`,
  218. sourcePath: "out/report.pdf",
  219. });
  220. // publishedAt 由 driver 填(引擎没有时钟),且必须是本次调用期间的时刻。
  221. expect(record.publishedAt ?? 0).toBeGreaterThanOrEqual(before);
  222. expect(record.publishedAt ?? 0).toBeLessThanOrEqual(Date.now());
  223. expect(writes).toHaveLength(1);
  224. });
  225. it("按 spec 的四个参数写 store(retention / toolName / toolCallId / sessionId)", async () => {
  226. const { store, writes } = fakeArtifactStore();
  227. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  228. await driver.executeArtifactPublish!(
  229. fileRequest({ runId: "run-42", siteId: "artifact#7", ordinal: 5 }),
  230. );
  231. expect(writes[0]).toMatchObject({
  232. kind: "binary",
  233. sessionId: SESSION_ID,
  234. // 每一版一份字节,而 (run, 站点, 序号) 恰好唯一标定一次发布。
  235. toolCallId: "run-42:artifact#7@5",
  236. toolName: "CreateWorkflow",
  237. // 产物要活过会话(中枢跨会话读运行历史)。
  238. retention: "project",
  239. contentType: "application/pdf",
  240. // 扩展名随字节一起交出去:store 读回时按落盘文件名回推类型。
  241. extension: "pdf",
  242. });
  243. });
  244. it("路径是工作区相对的,子目录与反斜杠都归一成正斜杠出处", async () => {
  245. await mkdir(join(workspace, "a", "b"), { recursive: true });
  246. await writeFile(join(workspace, "a", "b", "note.txt"), "hi", "utf8");
  247. const { store } = fakeArtifactStore();
  248. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  249. const record = await driver.executeArtifactPublish!(
  250. fileRequest({ path: "./a/b/../b/note.txt" }),
  251. );
  252. expect(record.sourcePath).toBe("a/b/note.txt");
  253. expect(record.contentType).toBe("text/plain");
  254. });
  255. it("越出工作区的相对路径被 ArtifactPathOutsideWorkspace 拒绝", async () => {
  256. const { store, writes } = fakeArtifactStore();
  257. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  258. const error = await rejection(
  259. driver.executeArtifactPublish!(fileRequest({ path: "../outside/secret.txt" })),
  260. "ArtifactPathOutsideWorkspace",
  261. );
  262. expect(error.message).toContain("../outside/secret.txt");
  263. expect(writes).toHaveLength(0);
  264. });
  265. it("绝对路径同样按越界处理(工作区之外没有可展示的出处)", async () => {
  266. const { store } = fakeArtifactStore();
  267. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  268. await rejection(
  269. driver.executeArtifactPublish!(fileRequest({ path: join(outside, "secret.txt") })),
  270. "ArtifactPathOutsideWorkspace",
  271. );
  272. });
  273. it("工作区内指向外部的软链按解析后的真实路径判越界", async () => {
  274. // 这一条是发布与世界读取的分界:files.read 只做词法检查,而发布会把字节拷进一个持久
  275. // store 摆到用户面前,所以软链必须堵住。
  276. const link = join(workspace, "leak.txt");
  277. await rm(link, { force: true });
  278. await symlink(join(outside, "secret.txt"), link);
  279. const { store, writes } = fakeArtifactStore();
  280. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  281. await rejection(
  282. driver.executeArtifactPublish!(fileRequest({ path: "leak.txt" })),
  283. "ArtifactPathOutsideWorkspace",
  284. );
  285. expect(writes).toHaveLength(0);
  286. });
  287. it("工作区内部的软链照常可发布(判据是真实路径的落点,而非是否软链)", async () => {
  288. const link = join(workspace, "alias.pdf");
  289. await rm(link, { force: true });
  290. await symlink(join(workspace, "out", "report.pdf"), link);
  291. const { store } = fakeArtifactStore();
  292. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  293. const record = await driver.executeArtifactPublish!(fileRequest({ path: "alias.pdf" }));
  294. expect(record.sourcePath).toBe("alias.pdf");
  295. expect(record.contentType).toBe("application/pdf");
  296. });
  297. it("路径不存在 / 指向目录都是 ArtifactSourceMissing", async () => {
  298. const { store } = fakeArtifactStore();
  299. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  300. const missing = await rejection(
  301. driver.executeArtifactPublish!(fileRequest({ path: "out/nope.pdf" })),
  302. "ArtifactSourceMissing",
  303. );
  304. expect(missing.message).toContain("out/nope.pdf");
  305. await rejection(
  306. driver.executeArtifactPublish!(fileRequest({ path: "out" })),
  307. "ArtifactSourceMissing",
  308. );
  309. });
  310. it("超过 20 MiB 上限的文件被拒绝而不是截断,消息给出下一步", async () => {
  311. const big = join(workspace, "out", "huge.bin");
  312. await writeFile(big, Buffer.alloc(ARTIFACT_CAPS.maxFileBytes + 1, 0));
  313. const { store, writes } = fakeArtifactStore();
  314. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  315. const error = await rejection(
  316. driver.executeArtifactPublish!(fileRequest({ path: "out/huge.bin" })),
  317. "ArtifactTooLarge",
  318. );
  319. // code 已由 rejection() 断言;消息只验可变部分(上限值)。
  320. expect(error.message).toContain(String(ARTIFACT_CAPS.maxFileBytes));
  321. expect(writes).toHaveLength(0);
  322. await rm(big, { force: true });
  323. });
  324. it("按 cap+1 向端口探测上限(恰好 cap 字节必须放行,而不是与溢出混为一谈)", async () => {
  325. const seen: (number | undefined)[] = [];
  326. // 只桩掉 readBinaryFile:路径解析走真实文件系统(软链复核要真的 realpath),
  327. // 而"端口收到的 maxBytes 是几"是本用例唯一要证的事。
  328. const port = {
  329. readBinaryFile: async (request: { path: string; maxBytes?: number }) => {
  330. seen.push(request.maxBytes);
  331. return {
  332. path: request.path,
  333. content: new Uint8Array(ARTIFACT_CAPS.maxFileBytes),
  334. bytesRead: ARTIFACT_CAPS.maxFileBytes,
  335. sizeBytes: ARTIFACT_CAPS.maxFileBytes,
  336. };
  337. },
  338. } as unknown as FileSystemPort;
  339. const { store, writes } = fakeArtifactStore();
  340. const driver = makeDriver({
  341. cwd: workspace,
  342. fileSystemPort: port,
  343. artifactStore: store,
  344. parentSessionId: SESSION_ID,
  345. });
  346. const record = await driver.executeArtifactPublish!(fileRequest());
  347. expect(seen).toEqual([ARTIFACT_CAPS.maxFileBytes + 1]);
  348. expect(record.bytes).toBe(ARTIFACT_CAPS.maxFileBytes);
  349. expect(writes).toHaveLength(1);
  350. });
  351. it("端口自己报的 too_large 也归一成 ArtifactTooLarge", async () => {
  352. const port = {
  353. readBinaryFile: async () => {
  354. throw createFileSystemError({ code: "too_large", message: "too big" });
  355. },
  356. } as unknown as FileSystemPort;
  357. const { store } = fakeArtifactStore();
  358. const driver = makeDriver({
  359. cwd: workspace,
  360. fileSystemPort: port,
  361. artifactStore: store,
  362. parentSessionId: SESSION_ID,
  363. });
  364. await rejection(driver.executeArtifactPublish!(fileRequest()), "ArtifactTooLarge");
  365. });
  366. });
  367. describe("workflow driver — 产物的内容类型", () => {
  368. const table: [string, string][] = [
  369. ["pdf", "application/pdf"],
  370. ["html", "text/html"],
  371. ["htm", "text/html"],
  372. ["md", "text/markdown"],
  373. ["markdown", "text/markdown"],
  374. ["txt", "text/plain"],
  375. ["csv", "text/csv"],
  376. ["json", "application/json"],
  377. ["png", "image/png"],
  378. ["jpg", "image/jpeg"],
  379. ["jpeg", "image/jpeg"],
  380. ["gif", "image/gif"],
  381. ["webp", "image/webp"],
  382. ["svg", "image/svg+xml"],
  383. ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  384. ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  385. ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  386. ];
  387. it.each(table)("扩展名 .%s → %s", async (extension, contentType) => {
  388. const name = `typed.${extension}`;
  389. await writeFile(join(workspace, "out", name), "x", "utf8");
  390. const { store, writes } = fakeArtifactStore();
  391. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  392. const record = await driver.executeArtifactPublish!(fileRequest({ path: `out/${name}` }));
  393. expect(record.contentType).toBe(contentType);
  394. expect(writes[0]?.contentType).toBe(contentType);
  395. });
  396. it("表外扩展名与无扩展名都落到 application/octet-stream(不做内容嗅探)", async () => {
  397. await writeFile(join(workspace, "out", "blob.zzz"), "x", "utf8");
  398. await writeFile(join(workspace, "out", "Makefile"), "x", "utf8");
  399. const { store } = fakeArtifactStore();
  400. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  401. expect(
  402. (await driver.executeArtifactPublish!(fileRequest({ path: "out/blob.zzz" }))).contentType,
  403. ).toBe("application/octet-stream");
  404. expect(
  405. (await driver.executeArtifactPublish!(fileRequest({ path: "out/Makefile" }))).contentType,
  406. ).toBe("application/octet-stream");
  407. });
  408. it("opts.contentType 覆盖扩展名表", async () => {
  409. const { store, writes } = fakeArtifactStore();
  410. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  411. const record = await driver.executeArtifactPublish!(
  412. fileRequest({ opts: { contentType: "text/html" } }),
  413. );
  414. expect(record.contentType).toBe("text/html");
  415. // 扩展名仍取自源文件:覆盖的是展示类型,不是落盘文件名。
  416. expect(writes[0]).toMatchObject({ contentType: "text/html", extension: "pdf" });
  417. });
  418. it("带参数的 contentType 被拒绝(展示侧按裸 MIME 精确分派)", async () => {
  419. const { store } = fakeArtifactStore();
  420. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  421. const error = await rejection(
  422. driver.executeArtifactPublish!(
  423. fileRequest({ opts: { contentType: "text/markdown; charset=utf-8" } }),
  424. ),
  425. "DriverError",
  426. );
  427. // 消息只验可变部分:被拒的那个 contentType 原样出现。
  428. expect(error.message).toContain("text/markdown; charset=utf-8");
  429. });
  430. });
  431. describe("workflow driver — 产物发布(artifact.markdown)", () => {
  432. it("走文本写通道,恒 text/markdown,且不带 sourcePath", async () => {
  433. const { store, writes } = fakeArtifactStore();
  434. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  435. const record = await driver.executeArtifactPublish!(
  436. markdownRequest({ opts: { title: "小结" } }),
  437. );
  438. expect(record).toMatchObject({
  439. id: "summary",
  440. kind: "markdown",
  441. version: 1,
  442. title: "小结",
  443. contentType: "text/markdown",
  444. });
  445. expect(record.sourcePath).toBeUndefined();
  446. expect(writes[0]).toMatchObject({
  447. kind: "text",
  448. contentType: "text/markdown",
  449. toolName: "CreateWorkflow",
  450. retention: "project",
  451. toolCallId: "run-1:artifact#2@1",
  452. text: "# 结论\n\n跑通了。",
  453. });
  454. });
  455. it("正文按 UTF-8 计字节:恰好 256 KB 放行,多一个字节即 ArtifactTooLarge", async () => {
  456. const { store, writes } = fakeArtifactStore();
  457. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  458. const exact = "a".repeat(ARTIFACT_CAPS.maxMarkdownBytes);
  459. const ok = await driver.executeArtifactPublish!(markdownRequest({ content: exact }));
  460. expect(ok.bytes).toBe(ARTIFACT_CAPS.maxMarkdownBytes);
  461. const error = await rejection(
  462. driver.executeArtifactPublish!(markdownRequest({ content: `${exact}a` })),
  463. "ArtifactTooLarge",
  464. );
  465. expect(error.message).toContain(String(ARTIFACT_CAPS.maxMarkdownBytes));
  466. expect(writes).toHaveLength(1);
  467. });
  468. it("多字节字符按 UTF-8 而不是按字符数计上限", async () => {
  469. const { store } = fakeArtifactStore();
  470. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  471. // 「中」是 3 字节:字符数远未超限,字节数刚好越线。
  472. const content = "中".repeat(Math.floor(ARTIFACT_CAPS.maxMarkdownBytes / 3) + 1);
  473. expect(content.length).toBeLessThan(ARTIFACT_CAPS.maxMarkdownBytes);
  474. await rejection(
  475. driver.executeArtifactPublish!(markdownRequest({ content })),
  476. "ArtifactTooLarge",
  477. );
  478. });
  479. it("markdown 不读 opts.contentType(这一族恒 text/markdown)", async () => {
  480. const { store } = fakeArtifactStore();
  481. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  482. const record = await driver.executeArtifactPublish!(
  483. markdownRequest({ opts: { contentType: "text/html" } }),
  484. );
  485. expect(record.contentType).toBe("text/markdown");
  486. });
  487. });
  488. describe("workflow driver — 产物的实参形状", () => {
  489. const cases: [string, unknown][] = [
  490. ["字符串", "title"],
  491. ["数组", ["title"]],
  492. ["null", null],
  493. ];
  494. it.each(cases)("opts 是%s时大声拒绝", async (_label, opts) => {
  495. const { store } = fakeArtifactStore();
  496. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  497. const error = await rejection(
  498. driver.executeArtifactPublish!(markdownRequest({ opts })),
  499. "DriverError",
  500. );
  501. expect(error.message).toContain("opts");
  502. });
  503. it("title / description 必须是 string,绝不强转", async () => {
  504. const { store } = fakeArtifactStore();
  505. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  506. const title = await rejection(
  507. driver.executeArtifactPublish!(markdownRequest({ opts: { title: 7 } })),
  508. "DriverError",
  509. );
  510. expect(title.message).toContain("opts.title");
  511. expect(title.message).toContain("number");
  512. const description = await rejection(
  513. driver.executeArtifactPublish!(markdownRequest({ opts: { description: {} } })),
  514. "DriverError",
  515. );
  516. expect(description.message).toContain("opts.description");
  517. });
  518. it("title / description 超长按上限拒绝而不是截断", async () => {
  519. const { store } = fakeArtifactStore();
  520. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  521. const title = await rejection(
  522. driver.executeArtifactPublish!(
  523. markdownRequest({ opts: { title: "x".repeat(ARTIFACT_CAPS.maxTitleLength + 1) } }),
  524. ),
  525. "ArtifactTooLarge",
  526. );
  527. expect(title.message).toContain(String(ARTIFACT_CAPS.maxTitleLength));
  528. await rejection(
  529. driver.executeArtifactPublish!(
  530. markdownRequest({
  531. opts: { description: "x".repeat(ARTIFACT_CAPS.maxDescriptionLength + 1) },
  532. }),
  533. ),
  534. "ArtifactTooLarge",
  535. );
  536. // 恰好等于上限放行。
  537. const ok = await driver.executeArtifactPublish!(
  538. markdownRequest({ opts: { title: "x".repeat(ARTIFACT_CAPS.maxTitleLength) } }),
  539. );
  540. expect(ok.title).toHaveLength(ARTIFACT_CAPS.maxTitleLength);
  541. });
  542. it("不认识的 opts 键静默忽略(编译期已拦住,运行期不再报第二次)", async () => {
  543. const { store } = fakeArtifactStore();
  544. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  545. const record = await driver.executeArtifactPublish!(
  546. markdownRequest({ opts: { title: "小结", 未知键: 1 } }),
  547. );
  548. expect(record.title).toBe("小结");
  549. });
  550. it("非法 id(字符集 / 超长)是接线错误,报 DriverError", async () => {
  551. const { store } = fakeArtifactStore();
  552. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  553. await rejection(
  554. driver.executeArtifactPublish!(markdownRequest({ id: "bad id/slash" })),
  555. "DriverError",
  556. );
  557. await rejection(
  558. driver.executeArtifactPublish!(
  559. markdownRequest({ id: "i".repeat(ARTIFACT_CAPS.maxIdLength + 1) }),
  560. ),
  561. "DriverError",
  562. );
  563. });
  564. it("payload 缺席或类型不对同样大声失败(引擎护栏之外的第二道)", async () => {
  565. const { store } = fakeArtifactStore();
  566. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  567. await rejection(
  568. driver.executeArtifactPublish!(fileRequest({ path: undefined })),
  569. "DriverError",
  570. );
  571. await rejection(
  572. driver.executeArtifactPublish!(markdownRequest({ content: undefined })),
  573. "DriverError",
  574. );
  575. });
  576. });
  577. describe("workflow driver — 产物存储缺席", () => {
  578. it("装配没有 store 时,两个内容成员都以 ArtifactStoreUnavailable 拒绝", async () => {
  579. const driver = makeDriver({ cwd: workspace, parentSessionId: SESSION_ID });
  580. const file = await rejection(
  581. driver.executeArtifactPublish!(fileRequest()),
  582. "ArtifactStoreUnavailable",
  583. );
  584. expect(file.message).toContain("report");
  585. await rejection(driver.executeArtifactPublish!(markdownRequest()), "ArtifactStoreUnavailable");
  586. });
  587. it("store 不支持二进制写时:文件拒绝,markdown 照常发布", async () => {
  588. const { store, writes } = fakeArtifactStore({ binary: false });
  589. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  590. await rejection(driver.executeArtifactPublish!(fileRequest()), "ArtifactStoreUnavailable");
  591. const record = await driver.executeArtifactPublish!(markdownRequest());
  592. expect(record.kind).toBe("markdown");
  593. expect(writes).toHaveLength(1);
  594. });
  595. it("store 在场但父会话 id 未接线时同样大声失败(不猜一个会话)", async () => {
  596. const { store, writes } = fakeArtifactStore();
  597. const driver = makeDriver({ cwd: workspace, artifactStore: store });
  598. await rejection(driver.executeArtifactPublish!(markdownRequest()), "ArtifactStoreUnavailable");
  599. expect(writes).toHaveLength(0);
  600. });
  601. it("store 缺席时不读文件(病因是没有落点,不该被一条 ArtifactSourceMissing 盖掉)", async () => {
  602. const port = new Proxy({} as FileSystemPort, {
  603. get(_target, name) {
  604. return () => {
  605. throw new Error(`fileSystemPort.${String(name)} 不应在 store 缺席时被触及`);
  606. };
  607. },
  608. });
  609. const driver = makeDriver({ cwd: workspace, fileSystemPort: port, parentSessionId: SESSION_ID });
  610. await rejection(
  611. driver.executeArtifactPublish!(fileRequest({ path: "out/nope.pdf" })),
  612. "ArtifactStoreUnavailable",
  613. );
  614. });
  615. it("store 写入自身失败归一成 DriverError,并带上原因文本", async () => {
  616. const { store } = fakeArtifactStore({ failWith: new Error("ENOSPC: no space left") });
  617. const driver = makeDriver({ cwd: workspace, artifactStore: store, parentSessionId: SESSION_ID });
  618. const error = await rejection(driver.executeArtifactPublish!(fileRequest()), "DriverError");
  619. expect(error.message).toContain("ENOSPC");
  620. });
  621. });