workflow-driver-artifacts.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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({
  202. cwd: workspace,
  203. artifactStore: store,
  204. parentSessionId: SESSION_ID,
  205. });
  206. const before = Date.now();
  207. const record = await driver.executeArtifactPublish!(
  208. fileRequest({
  209. version: 3,
  210. opts: { title: "回归报告", description: "本轮的性能回归" },
  211. }),
  212. );
  213. expect(record).toMatchObject({
  214. id: "report",
  215. kind: "file",
  216. version: 3,
  217. title: "回归报告",
  218. description: "本轮的性能回归",
  219. contentType: "application/pdf",
  220. bytes: Buffer.byteLength("%PDF-1.7\n…", "utf8"),
  221. uri: `zcode-artifact://${SESSION_ID}/artifact-1`,
  222. sourcePath: "out/report.pdf",
  223. });
  224. // publishedAt 由 driver 填(引擎没有时钟),且必须是本次调用期间的时刻。
  225. expect(record.publishedAt ?? 0).toBeGreaterThanOrEqual(before);
  226. expect(record.publishedAt ?? 0).toBeLessThanOrEqual(Date.now());
  227. expect(writes).toHaveLength(1);
  228. });
  229. it("按 spec 的四个参数写 store(retention / toolName / toolCallId / sessionId)", async () => {
  230. const { store, writes } = fakeArtifactStore();
  231. const driver = makeDriver({
  232. cwd: workspace,
  233. artifactStore: store,
  234. parentSessionId: SESSION_ID,
  235. });
  236. await driver.executeArtifactPublish!(
  237. fileRequest({ runId: "run-42", siteId: "artifact#7", ordinal: 5 }),
  238. );
  239. expect(writes[0]).toMatchObject({
  240. kind: "binary",
  241. sessionId: SESSION_ID,
  242. // 每一版一份字节,而 (run, 站点, 序号) 恰好唯一标定一次发布。
  243. toolCallId: "run-42:artifact#7@5",
  244. toolName: "CreateWorkflow",
  245. // 产物要活过会话(中枢跨会话读运行历史)。
  246. retention: "project",
  247. contentType: "application/pdf",
  248. // 扩展名随字节一起交出去:store 读回时按落盘文件名回推类型。
  249. extension: "pdf",
  250. });
  251. });
  252. it("工作区相对路径的点段归一后保留子目录出处", async () => {
  253. await mkdir(join(workspace, "a", "b"), { recursive: true });
  254. await writeFile(join(workspace, "a", "b", "note.txt"), "hi", "utf8");
  255. const { store } = fakeArtifactStore();
  256. const driver = makeDriver({
  257. cwd: workspace,
  258. artifactStore: store,
  259. parentSessionId: SESSION_ID,
  260. });
  261. const record = await driver.executeArtifactPublish!(
  262. fileRequest({ path: "./a/b/../b/note.txt" }),
  263. );
  264. expect(record.sourcePath).toBe("a/b/note.txt");
  265. expect(record.contentType).toBe("text/plain");
  266. });
  267. it("越出工作区的相对路径被 ArtifactPathOutsideWorkspace 拒绝", async () => {
  268. const { store, writes } = fakeArtifactStore();
  269. const driver = makeDriver({
  270. cwd: workspace,
  271. artifactStore: store,
  272. parentSessionId: SESSION_ID,
  273. });
  274. const error = await rejection(
  275. driver.executeArtifactPublish!(fileRequest({ path: "../outside/secret.txt" })),
  276. "ArtifactPathOutsideWorkspace",
  277. );
  278. expect(error.message).toContain("../outside/secret.txt");
  279. expect(writes).toHaveLength(0);
  280. });
  281. it("绝对路径同样按越界处理(工作区之外没有可展示的出处)", async () => {
  282. const { store } = fakeArtifactStore();
  283. const driver = makeDriver({
  284. cwd: workspace,
  285. artifactStore: store,
  286. parentSessionId: SESSION_ID,
  287. });
  288. await rejection(
  289. driver.executeArtifactPublish!(fileRequest({ path: join(outside, "secret.txt") })),
  290. "ArtifactPathOutsideWorkspace",
  291. );
  292. });
  293. it("工作区内指向外部的软链按解析后的真实路径判越界", async () => {
  294. // 这一条是发布与世界读取的分界:files.read 只做词法检查,而发布会把字节拷进一个持久
  295. // store 摆到用户面前,所以软链必须堵住。
  296. const link = join(workspace, "leak.txt");
  297. await rm(link, { force: true });
  298. await symlink(join(outside, "secret.txt"), link);
  299. const { store, writes } = fakeArtifactStore();
  300. const driver = makeDriver({
  301. cwd: workspace,
  302. artifactStore: store,
  303. parentSessionId: SESSION_ID,
  304. });
  305. await rejection(
  306. driver.executeArtifactPublish!(fileRequest({ path: "leak.txt" })),
  307. "ArtifactPathOutsideWorkspace",
  308. );
  309. expect(writes).toHaveLength(0);
  310. });
  311. it("工作区内部的软链照常可发布(判据是真实路径的落点,而非是否软链)", async () => {
  312. const link = join(workspace, "alias.pdf");
  313. await rm(link, { force: true });
  314. await symlink(join(workspace, "out", "report.pdf"), link);
  315. const { store } = fakeArtifactStore();
  316. const driver = makeDriver({
  317. cwd: workspace,
  318. artifactStore: store,
  319. parentSessionId: SESSION_ID,
  320. });
  321. const record = await driver.executeArtifactPublish!(fileRequest({ path: "alias.pdf" }));
  322. expect(record.sourcePath).toBe("alias.pdf");
  323. expect(record.contentType).toBe("application/pdf");
  324. });
  325. it("路径不存在 / 指向目录都是 ArtifactSourceMissing", async () => {
  326. const { store } = fakeArtifactStore();
  327. const driver = makeDriver({
  328. cwd: workspace,
  329. artifactStore: store,
  330. parentSessionId: SESSION_ID,
  331. });
  332. const missing = await rejection(
  333. driver.executeArtifactPublish!(fileRequest({ path: "out/nope.pdf" })),
  334. "ArtifactSourceMissing",
  335. );
  336. expect(missing.message).toContain("out/nope.pdf");
  337. await rejection(
  338. driver.executeArtifactPublish!(fileRequest({ path: "out" })),
  339. "ArtifactSourceMissing",
  340. );
  341. });
  342. it("超过 20 MiB 上限的文件被拒绝而不是截断,消息给出下一步", async () => {
  343. const big = join(workspace, "out", "huge.bin");
  344. await writeFile(big, Buffer.alloc(ARTIFACT_CAPS.maxFileBytes + 1, 0));
  345. const { store, writes } = fakeArtifactStore();
  346. const driver = makeDriver({
  347. cwd: workspace,
  348. artifactStore: store,
  349. parentSessionId: SESSION_ID,
  350. });
  351. const error = await rejection(
  352. driver.executeArtifactPublish!(fileRequest({ path: "out/huge.bin" })),
  353. "ArtifactTooLarge",
  354. );
  355. // code 已由 rejection() 断言;消息只验可变部分(上限值)。
  356. expect(error.message).toContain(String(ARTIFACT_CAPS.maxFileBytes));
  357. expect(writes).toHaveLength(0);
  358. await rm(big, { force: true });
  359. });
  360. it("按 cap+1 向端口探测上限(恰好 cap 字节必须放行,而不是与溢出混为一谈)", async () => {
  361. const seen: (number | undefined)[] = [];
  362. // 只桩掉 readBinaryFile:路径解析走真实文件系统(软链复核要真的 realpath),
  363. // 而"端口收到的 maxBytes 是几"是本用例唯一要证的事。
  364. const port = {
  365. readBinaryFile: async (request: { path: string; maxBytes?: number }) => {
  366. seen.push(request.maxBytes);
  367. return {
  368. path: request.path,
  369. content: new Uint8Array(ARTIFACT_CAPS.maxFileBytes),
  370. bytesRead: ARTIFACT_CAPS.maxFileBytes,
  371. sizeBytes: ARTIFACT_CAPS.maxFileBytes,
  372. };
  373. },
  374. } as unknown as FileSystemPort;
  375. const { store, writes } = fakeArtifactStore();
  376. const driver = makeDriver({
  377. cwd: workspace,
  378. fileSystemPort: port,
  379. artifactStore: store,
  380. parentSessionId: SESSION_ID,
  381. });
  382. const record = await driver.executeArtifactPublish!(fileRequest());
  383. expect(seen).toEqual([ARTIFACT_CAPS.maxFileBytes + 1]);
  384. expect(record.bytes).toBe(ARTIFACT_CAPS.maxFileBytes);
  385. expect(writes).toHaveLength(1);
  386. });
  387. it("端口自己报的 too_large 也归一成 ArtifactTooLarge", async () => {
  388. const port = {
  389. readBinaryFile: async () => {
  390. throw createFileSystemError({ code: "too_large", message: "too big" });
  391. },
  392. } as unknown as FileSystemPort;
  393. const { store } = fakeArtifactStore();
  394. const driver = makeDriver({
  395. cwd: workspace,
  396. fileSystemPort: port,
  397. artifactStore: store,
  398. parentSessionId: SESSION_ID,
  399. });
  400. await rejection(driver.executeArtifactPublish!(fileRequest()), "ArtifactTooLarge");
  401. });
  402. });
  403. describe("workflow driver — 产物的内容类型", () => {
  404. const table: [string, string][] = [
  405. ["pdf", "application/pdf"],
  406. ["html", "text/html"],
  407. ["htm", "text/html"],
  408. ["md", "text/markdown"],
  409. ["markdown", "text/markdown"],
  410. ["txt", "text/plain"],
  411. ["csv", "text/csv"],
  412. ["json", "application/json"],
  413. ["png", "image/png"],
  414. ["jpg", "image/jpeg"],
  415. ["jpeg", "image/jpeg"],
  416. ["gif", "image/gif"],
  417. ["webp", "image/webp"],
  418. ["svg", "image/svg+xml"],
  419. ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  420. ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  421. ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  422. ];
  423. it.each(table)("扩展名 .%s → %s", async (extension, contentType) => {
  424. const name = `typed.${extension}`;
  425. await writeFile(join(workspace, "out", name), "x", "utf8");
  426. const { store, writes } = fakeArtifactStore();
  427. const driver = makeDriver({
  428. cwd: workspace,
  429. artifactStore: store,
  430. parentSessionId: SESSION_ID,
  431. });
  432. const record = await driver.executeArtifactPublish!(fileRequest({ path: `out/${name}` }));
  433. expect(record.contentType).toBe(contentType);
  434. expect(writes[0]?.contentType).toBe(contentType);
  435. });
  436. it("表外扩展名与无扩展名都落到 application/octet-stream(不做内容嗅探)", async () => {
  437. await writeFile(join(workspace, "out", "blob.zzz"), "x", "utf8");
  438. await writeFile(join(workspace, "out", "Makefile"), "x", "utf8");
  439. const { store } = fakeArtifactStore();
  440. const driver = makeDriver({
  441. cwd: workspace,
  442. artifactStore: store,
  443. parentSessionId: SESSION_ID,
  444. });
  445. expect(
  446. (await driver.executeArtifactPublish!(fileRequest({ path: "out/blob.zzz" }))).contentType,
  447. ).toBe("application/octet-stream");
  448. expect(
  449. (await driver.executeArtifactPublish!(fileRequest({ path: "out/Makefile" }))).contentType,
  450. ).toBe("application/octet-stream");
  451. });
  452. it("opts.contentType 覆盖扩展名表", async () => {
  453. const { store, writes } = fakeArtifactStore();
  454. const driver = makeDriver({
  455. cwd: workspace,
  456. artifactStore: store,
  457. parentSessionId: SESSION_ID,
  458. });
  459. const record = await driver.executeArtifactPublish!(
  460. fileRequest({ opts: { contentType: "text/html" } }),
  461. );
  462. expect(record.contentType).toBe("text/html");
  463. // 扩展名仍取自源文件:覆盖的是展示类型,不是落盘文件名。
  464. expect(writes[0]).toMatchObject({ contentType: "text/html", extension: "pdf" });
  465. });
  466. it("带参数的 contentType 被拒绝(展示侧按裸 MIME 精确分派)", async () => {
  467. const { store } = fakeArtifactStore();
  468. const driver = makeDriver({
  469. cwd: workspace,
  470. artifactStore: store,
  471. parentSessionId: SESSION_ID,
  472. });
  473. const error = await rejection(
  474. driver.executeArtifactPublish!(
  475. fileRequest({ opts: { contentType: "text/markdown; charset=utf-8" } }),
  476. ),
  477. "DriverError",
  478. );
  479. // 消息只验可变部分:被拒的那个 contentType 原样出现。
  480. expect(error.message).toContain("text/markdown; charset=utf-8");
  481. });
  482. });
  483. describe("workflow driver — 产物发布(artifact.markdown)", () => {
  484. it("走文本写通道,恒 text/markdown,且不带 sourcePath", async () => {
  485. const { store, writes } = fakeArtifactStore();
  486. const driver = makeDriver({
  487. cwd: workspace,
  488. artifactStore: store,
  489. parentSessionId: SESSION_ID,
  490. });
  491. const record = await driver.executeArtifactPublish!(
  492. markdownRequest({ opts: { title: "小结" } }),
  493. );
  494. expect(record).toMatchObject({
  495. id: "summary",
  496. kind: "markdown",
  497. version: 1,
  498. title: "小结",
  499. contentType: "text/markdown",
  500. });
  501. expect(record.sourcePath).toBeUndefined();
  502. expect(writes[0]).toMatchObject({
  503. kind: "text",
  504. contentType: "text/markdown",
  505. toolName: "CreateWorkflow",
  506. retention: "project",
  507. toolCallId: "run-1:artifact#2@1",
  508. text: "# 结论\n\n跑通了。",
  509. });
  510. });
  511. it("正文按 UTF-8 计字节:恰好 256 KB 放行,多一个字节即 ArtifactTooLarge", async () => {
  512. const { store, writes } = fakeArtifactStore();
  513. const driver = makeDriver({
  514. cwd: workspace,
  515. artifactStore: store,
  516. parentSessionId: SESSION_ID,
  517. });
  518. const exact = "a".repeat(ARTIFACT_CAPS.maxMarkdownBytes);
  519. const ok = await driver.executeArtifactPublish!(markdownRequest({ content: exact }));
  520. expect(ok.bytes).toBe(ARTIFACT_CAPS.maxMarkdownBytes);
  521. const error = await rejection(
  522. driver.executeArtifactPublish!(markdownRequest({ content: `${exact}a` })),
  523. "ArtifactTooLarge",
  524. );
  525. expect(error.message).toContain(String(ARTIFACT_CAPS.maxMarkdownBytes));
  526. expect(writes).toHaveLength(1);
  527. });
  528. it("多字节字符按 UTF-8 而不是按字符数计上限", async () => {
  529. const { store } = fakeArtifactStore();
  530. const driver = makeDriver({
  531. cwd: workspace,
  532. artifactStore: store,
  533. parentSessionId: SESSION_ID,
  534. });
  535. // 「中」是 3 字节:字符数远未超限,字节数刚好越线。
  536. const content = "中".repeat(Math.floor(ARTIFACT_CAPS.maxMarkdownBytes / 3) + 1);
  537. expect(content.length).toBeLessThan(ARTIFACT_CAPS.maxMarkdownBytes);
  538. await rejection(
  539. driver.executeArtifactPublish!(markdownRequest({ content })),
  540. "ArtifactTooLarge",
  541. );
  542. });
  543. it("markdown 不读 opts.contentType(这一族恒 text/markdown)", async () => {
  544. const { store } = fakeArtifactStore();
  545. const driver = makeDriver({
  546. cwd: workspace,
  547. artifactStore: store,
  548. parentSessionId: SESSION_ID,
  549. });
  550. const record = await driver.executeArtifactPublish!(
  551. markdownRequest({ opts: { contentType: "text/html" } }),
  552. );
  553. expect(record.contentType).toBe("text/markdown");
  554. });
  555. });
  556. describe("workflow driver — 产物的实参形状", () => {
  557. const cases: [string, unknown][] = [
  558. ["字符串", "title"],
  559. ["数组", ["title"]],
  560. ["null", null],
  561. ];
  562. it.each(cases)("opts 是%s时大声拒绝", async (_label, opts) => {
  563. const { store } = fakeArtifactStore();
  564. const driver = makeDriver({
  565. cwd: workspace,
  566. artifactStore: store,
  567. parentSessionId: SESSION_ID,
  568. });
  569. const error = await rejection(
  570. driver.executeArtifactPublish!(markdownRequest({ opts })),
  571. "DriverError",
  572. );
  573. expect(error.message).toContain("opts");
  574. });
  575. it("title / description 必须是 string,绝不强转", async () => {
  576. const { store } = fakeArtifactStore();
  577. const driver = makeDriver({
  578. cwd: workspace,
  579. artifactStore: store,
  580. parentSessionId: SESSION_ID,
  581. });
  582. const title = await rejection(
  583. driver.executeArtifactPublish!(markdownRequest({ opts: { title: 7 } })),
  584. "DriverError",
  585. );
  586. expect(title.message).toContain("opts.title");
  587. expect(title.message).toContain("number");
  588. const description = await rejection(
  589. driver.executeArtifactPublish!(markdownRequest({ opts: { description: {} } })),
  590. "DriverError",
  591. );
  592. expect(description.message).toContain("opts.description");
  593. });
  594. it("title / description 超长按上限拒绝而不是截断", async () => {
  595. const { store } = fakeArtifactStore();
  596. const driver = makeDriver({
  597. cwd: workspace,
  598. artifactStore: store,
  599. parentSessionId: SESSION_ID,
  600. });
  601. const title = await rejection(
  602. driver.executeArtifactPublish!(
  603. markdownRequest({ opts: { title: "x".repeat(ARTIFACT_CAPS.maxTitleLength + 1) } }),
  604. ),
  605. "ArtifactTooLarge",
  606. );
  607. expect(title.message).toContain(String(ARTIFACT_CAPS.maxTitleLength));
  608. await rejection(
  609. driver.executeArtifactPublish!(
  610. markdownRequest({
  611. opts: { description: "x".repeat(ARTIFACT_CAPS.maxDescriptionLength + 1) },
  612. }),
  613. ),
  614. "ArtifactTooLarge",
  615. );
  616. // 恰好等于上限放行。
  617. const ok = await driver.executeArtifactPublish!(
  618. markdownRequest({ opts: { title: "x".repeat(ARTIFACT_CAPS.maxTitleLength) } }),
  619. );
  620. expect(ok.title).toHaveLength(ARTIFACT_CAPS.maxTitleLength);
  621. });
  622. it("不认识的 opts 键静默忽略(编译期已拦住,运行期不再报第二次)", async () => {
  623. const { store } = fakeArtifactStore();
  624. const driver = makeDriver({
  625. cwd: workspace,
  626. artifactStore: store,
  627. parentSessionId: SESSION_ID,
  628. });
  629. const record = await driver.executeArtifactPublish!(
  630. markdownRequest({ opts: { title: "小结", 未知键: 1 } }),
  631. );
  632. expect(record.title).toBe("小结");
  633. });
  634. it("非法 id(字符集 / 超长)是接线错误,报 DriverError", async () => {
  635. const { store } = fakeArtifactStore();
  636. const driver = makeDriver({
  637. cwd: workspace,
  638. artifactStore: store,
  639. parentSessionId: SESSION_ID,
  640. });
  641. await rejection(
  642. driver.executeArtifactPublish!(markdownRequest({ id: "bad id/slash" })),
  643. "DriverError",
  644. );
  645. await rejection(
  646. driver.executeArtifactPublish!(
  647. markdownRequest({ id: "i".repeat(ARTIFACT_CAPS.maxIdLength + 1) }),
  648. ),
  649. "DriverError",
  650. );
  651. });
  652. it("payload 缺席或类型不对同样大声失败(引擎护栏之外的第二道)", async () => {
  653. const { store } = fakeArtifactStore();
  654. const driver = makeDriver({
  655. cwd: workspace,
  656. artifactStore: store,
  657. parentSessionId: SESSION_ID,
  658. });
  659. await rejection(
  660. driver.executeArtifactPublish!(fileRequest({ path: undefined })),
  661. "DriverError",
  662. );
  663. await rejection(
  664. driver.executeArtifactPublish!(markdownRequest({ content: undefined })),
  665. "DriverError",
  666. );
  667. });
  668. });
  669. describe("workflow driver — 产物存储缺席", () => {
  670. it("装配没有 store 时,两个内容成员都以 ArtifactStoreUnavailable 拒绝", async () => {
  671. const driver = makeDriver({ cwd: workspace, parentSessionId: SESSION_ID });
  672. const file = await rejection(
  673. driver.executeArtifactPublish!(fileRequest()),
  674. "ArtifactStoreUnavailable",
  675. );
  676. expect(file.message).toContain("report");
  677. await rejection(driver.executeArtifactPublish!(markdownRequest()), "ArtifactStoreUnavailable");
  678. });
  679. it("store 不支持二进制写时:文件拒绝,markdown 照常发布", async () => {
  680. const { store, writes } = fakeArtifactStore({ binary: false });
  681. const driver = makeDriver({
  682. cwd: workspace,
  683. artifactStore: store,
  684. parentSessionId: SESSION_ID,
  685. });
  686. await rejection(driver.executeArtifactPublish!(fileRequest()), "ArtifactStoreUnavailable");
  687. const record = await driver.executeArtifactPublish!(markdownRequest());
  688. expect(record.kind).toBe("markdown");
  689. expect(writes).toHaveLength(1);
  690. });
  691. it("store 在场但父会话 id 未接线时同样大声失败(不猜一个会话)", async () => {
  692. const { store, writes } = fakeArtifactStore();
  693. const driver = makeDriver({ cwd: workspace, artifactStore: store });
  694. await rejection(driver.executeArtifactPublish!(markdownRequest()), "ArtifactStoreUnavailable");
  695. expect(writes).toHaveLength(0);
  696. });
  697. it("store 缺席时不读文件(病因是没有落点,不该被一条 ArtifactSourceMissing 盖掉)", async () => {
  698. const port = new Proxy({} as FileSystemPort, {
  699. get(_target, name) {
  700. return () => {
  701. throw new Error(`fileSystemPort.${String(name)} 不应在 store 缺席时被触及`);
  702. };
  703. },
  704. });
  705. const driver = makeDriver({
  706. cwd: workspace,
  707. fileSystemPort: port,
  708. parentSessionId: SESSION_ID,
  709. });
  710. await rejection(
  711. driver.executeArtifactPublish!(fileRequest({ path: "out/nope.pdf" })),
  712. "ArtifactStoreUnavailable",
  713. );
  714. });
  715. it("store 写入自身失败归一成 DriverError,并带上原因文本", async () => {
  716. const { store } = fakeArtifactStore({ failWith: new Error("ENOSPC: no space left") });
  717. const driver = makeDriver({
  718. cwd: workspace,
  719. artifactStore: store,
  720. parentSessionId: SESSION_ID,
  721. });
  722. const error = await rejection(driver.executeArtifactPublish!(fileRequest()), "DriverError");
  723. expect(error.message).toContain("ENOSPC");
  724. });
  725. });