dynamic-workflow-run-artifacts-projection.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // 用户面产物在观察面的合成规则(docs/dynamic-workflow/authoring.md):
  2. // `artifactsOf` 与终态快照上的 `artifacts` 键。
  3. //
  4. // ⚠ 术语:本文件里的 artifact 是脚本经 `artifact.*` **发布给用户看的产出**(journal
  5. // `kind = "artifact"` 的行),不是 `RunSettlement.artifact`(脚本顶层返回值,快照上叫
  6. // `output`)。同一个词两个义,spec 的「术语」表是唯一消歧处——两者在本文件的断言里并列出现。
  7. //
  8. // 端口的两条查询(`listArtifactRows` / `listArtifactItems`)不在引擎的 JournalStorePort 上,
  9. // 所以生产路径靠能力探测接上;这里用一个带 / 不带那个方法的内存 journal 把两支都跑到。
  10. import { describe, expect, it, vi } from "vitest";
  11. import { InMemoryJournalStore, type NodeRecord, type RunStatus } from "@zcode/dynamic-workflow";
  12. import {
  13. artifactsOf,
  14. snapshotOf,
  15. type RunRegistryEntry,
  16. } from "../src/app/dynamic-workflow-run-observation.js";
  17. /** 带 `listArtifactRows` 的 journal:adapters 侧那条宿主查询的内存替身。 */
  18. class ArtifactAwareJournalStore extends InMemoryJournalStore {
  19. listArtifactRows(runId: string): NodeRecord[] {
  20. // 真实现按 id 升序(插入序 = 版本序)取 `kind = 'artifact'` 的行;内存实现的 listNodes
  21. // 已经是插入序,所以过滤即可。
  22. return this.listNodes(runId, { kinds: ["artifact"], withResult: true });
  23. }
  24. }
  25. function makeRun(journal: InMemoryJournalStore, runId: string, status: RunStatus): void {
  26. journal.createRun({ runId, caps: { maxConcurrency: 4 }, spentTokens: 0, status });
  27. }
  28. function putArtifact(
  29. journal: InMemoryJournalStore,
  30. runId: string,
  31. ordinal: number,
  32. record: Record<string, unknown>,
  33. overrides: { status?: "completed" | "failed"; artifactId?: string } = {},
  34. ): void {
  35. journal.putNode({
  36. runId,
  37. siteId: `artifact#${ordinal}`,
  38. ordinal,
  39. kind: "artifact",
  40. inputHash: `hash-${ordinal}`,
  41. status: overrides.status ?? "completed",
  42. artifactId: overrides.artifactId ?? (record.id as string),
  43. ...(overrides.status === "failed"
  44. ? { error: { code: "ArtifactSourceMissing", message: "gone" } }
  45. : { result: record }),
  46. });
  47. }
  48. function putTaggedReport(
  49. journal: InMemoryJournalStore,
  50. runId: string,
  51. ordinal: number,
  52. artifactId?: string,
  53. ): void {
  54. journal.putNode({
  55. runId,
  56. siteId: "report#1",
  57. ordinal,
  58. kind: "report",
  59. inputHash: `report-${ordinal}`,
  60. status: "completed",
  61. ...(artifactId === undefined ? {} : { artifactId }),
  62. result: { round: ordinal },
  63. });
  64. }
  65. describe("artifactsOf — journal 行 → 端口的 artifacts", () => {
  66. it("能力缺席(journal 不带 listArtifactRows)⇒ 整字段缺席,绝不抛", () => {
  67. const journal = new InMemoryJournalStore();
  68. makeRun(journal, "run-plain", "completed");
  69. expect(artifactsOf("run-plain", journal)).toEqual({});
  70. });
  71. it("零行 / 未知 run ⇒ 整字段缺席(空数组读起来像「跑过但没产出」)", () => {
  72. const journal = new ArtifactAwareJournalStore();
  73. makeRun(journal, "run-empty", "completed");
  74. expect(artifactsOf("run-empty", journal)).toEqual({});
  75. expect(artifactsOf("run-unknown", journal)).toEqual({});
  76. });
  77. it("同 id 的多行归成一件、版本升序,顶层字段取最新版", () => {
  78. const journal = new ArtifactAwareJournalStore();
  79. makeRun(journal, "run-versions", "completed");
  80. putArtifact(journal, "run-versions", 1, {
  81. id: "audit",
  82. kind: "file",
  83. version: 1,
  84. title: "旧版",
  85. contentType: "text/plain",
  86. sourcePath: "out/audit.txt",
  87. bytes: 10,
  88. uri: "zcode-artifact://one",
  89. publishedAt: 1,
  90. });
  91. putArtifact(journal, "run-versions", 2, {
  92. id: "audit",
  93. kind: "file",
  94. version: 2,
  95. title: "审计报告",
  96. contentType: "application/pdf",
  97. sourcePath: "out/audit.pdf",
  98. bytes: 4_096,
  99. uri: "zcode-artifact://two",
  100. publishedAt: 2,
  101. });
  102. const { artifacts } = artifactsOf("run-versions", journal);
  103. expect(artifacts).toHaveLength(1);
  104. const audit = artifacts![0]!;
  105. expect(audit.id).toBe("audit");
  106. expect(audit.version).toBe(2);
  107. expect(audit.title).toBe("审计报告");
  108. expect(audit.contentType).toBe("application/pdf");
  109. expect(audit.sourcePath).toBe("out/audit.pdf");
  110. // 版本历史完整保留、升序;字节与 uri 只挂在版本项上。
  111. expect(audit.versions.map((version) => version.version)).toEqual([1, 2]);
  112. expect(audit.versions[1]?.bytes).toBe(4_096);
  113. expect(audit.versions[0]?.uri).toBe("zcode-artifact://one");
  114. // 内容产物恒 0 条。
  115. expect(audit.itemCount).toBe(0);
  116. });
  117. // 交付物(docs/dynamic-workflow/authoring.md「Ids, tags and versions」):旗子在版本记录上由引擎盖章、
  118. // 按 id 粘着;投影把它抬到顶层,并让它带头——顺序在这里定一次,下游的每个上界都砍不到它。
  119. it("primary 从版本记录抬到顶层,且交付物带头、其余保持首次发布顺序", () => {
  120. const journal = new ArtifactAwareJournalStore();
  121. makeRun(journal, "run-primary", "completed");
  122. putArtifact(journal, "run-primary", 1, { id: "perf", kind: "chart", version: 1, publishedAt: 1 });
  123. putArtifact(journal, "run-primary", 2, { id: "notes-a", kind: "markdown", version: 1, publishedAt: 2 });
  124. putArtifact(journal, "run-primary", 3, { id: "notes-b", kind: "markdown", version: 1, publishedAt: 3 });
  125. putArtifact(journal, "run-primary", 4, {
  126. id: "report",
  127. kind: "markdown",
  128. version: 1,
  129. title: "审计报告",
  130. description: "结论与修复建议",
  131. primary: true,
  132. publishedAt: 4,
  133. });
  134. putArtifact(journal, "run-primary", 5, {
  135. id: "report",
  136. kind: "markdown",
  137. version: 2,
  138. title: "审计报告",
  139. primary: true,
  140. publishedAt: 5,
  141. });
  142. const { artifacts } = artifactsOf("run-primary", journal);
  143. expect(artifacts!.map((artifact) => artifact.id)).toEqual(["report", "perf", "notes-a", "notes-b"]);
  144. const report = artifacts![0]!;
  145. expect(report.primary).toBe(true);
  146. expect(report.versions.map((version) => version.primary)).toEqual([true, true]);
  147. // 非交付物的键缺席,不是 false。
  148. for (const other of artifacts!.slice(1)) expect("primary" in other).toBe(false);
  149. for (const version of artifacts![1]!.versions) expect("primary" in version).toBe(false);
  150. });
  151. it("没有交付物时顺序与形状与旧 CLI 落的行完全一致(旗子从不被推断)", () => {
  152. const journal = new ArtifactAwareJournalStore();
  153. makeRun(journal, "run-no-primary", "completed");
  154. putArtifact(journal, "run-no-primary", 1, { id: "b", kind: "markdown", version: 1, publishedAt: 1 });
  155. putArtifact(journal, "run-no-primary", 2, { id: "a", kind: "markdown", version: 1, publishedAt: 2 });
  156. const { artifacts } = artifactsOf("run-no-primary", journal);
  157. expect(artifacts!.map((artifact) => artifact.id)).toEqual(["b", "a"]);
  158. expect(artifacts!.some((artifact) => "primary" in artifact)).toBe(false);
  159. });
  160. it("失败的发布行不进版本历史(它不占 id、不占版本号)", () => {
  161. const journal = new ArtifactAwareJournalStore();
  162. makeRun(journal, "run-failed", "completed");
  163. putArtifact(journal, "run-failed", 1, {
  164. id: "audit",
  165. kind: "file",
  166. version: 1,
  167. publishedAt: 1,
  168. });
  169. putArtifact(
  170. journal,
  171. "run-failed",
  172. 2,
  173. { id: "audit" },
  174. { status: "failed", artifactId: "audit" },
  175. );
  176. const { artifacts } = artifactsOf("run-failed", journal);
  177. expect(artifacts).toHaveLength(1);
  178. expect(artifacts![0]!.versions).toHaveLength(1);
  179. expect(artifacts![0]!.version).toBe(1);
  180. });
  181. it("itemCount 只数带该 id 标签的 report 行;无标签的与别的 id 都不算", () => {
  182. const journal = new ArtifactAwareJournalStore();
  183. makeRun(journal, "run-items", "completed");
  184. putArtifact(journal, "run-items", 1, {
  185. id: "perf",
  186. kind: "chart",
  187. version: 1,
  188. publishedAt: 1,
  189. spec: { x: { field: "round" }, y: { field: "ms" } },
  190. });
  191. putArtifact(journal, "run-items", 2, {
  192. id: "board",
  193. kind: "board",
  194. version: 1,
  195. publishedAt: 2,
  196. spec: { key: "id", status: "state", columns: ["todo"] },
  197. });
  198. putTaggedReport(journal, "run-items", 1, "perf");
  199. putTaggedReport(journal, "run-items", 2, "perf");
  200. putTaggedReport(journal, "run-items", 3, "board");
  201. putTaggedReport(journal, "run-items", 4);
  202. const { artifacts } = artifactsOf("run-items", journal);
  203. expect(artifacts?.map((artifact) => [artifact.id, artifact.itemCount])).toEqual([
  204. ["perf", 2],
  205. ["board", 1],
  206. ]);
  207. // 预置看板的 spec 原样带出(UI 据它渲染)。
  208. expect(artifacts![0]!.spec).toEqual({ x: { field: "round" }, y: { field: "ms" } });
  209. });
  210. /**
  211. * 中枢一页 50 行、每行调一次本函数:内容产物的 `itemCount` 恒 0,为它扫一遍全表是纯浪费。
  212. * 这条断言是那条路径上唯一的挡板。
  213. */
  214. it("只有内容产物时不扫节点表;有预置看板时才扫一次", () => {
  215. const journal = new ArtifactAwareJournalStore();
  216. makeRun(journal, "run-content", "completed");
  217. putArtifact(journal, "run-content", 1, {
  218. id: "notes",
  219. kind: "markdown",
  220. version: 1,
  221. publishedAt: 1,
  222. });
  223. const contentSpy = vi.spyOn(journal, "listNodes");
  224. contentSpy.mockClear();
  225. artifactsOf("run-content", journal);
  226. // listArtifactRows 自己会调一次 listNodes(内存替身的实现细节),所以判据是「没有为了
  227. // 计数再调一次」:一次来自行查询,第二次才是计数。
  228. expect(contentSpy).toHaveBeenCalledTimes(1);
  229. makeRun(journal, "run-preset", "completed");
  230. putArtifact(journal, "run-preset", 1, {
  231. id: "perf",
  232. kind: "chart",
  233. version: 1,
  234. publishedAt: 1,
  235. spec: {},
  236. });
  237. contentSpy.mockClear();
  238. artifactsOf("run-preset", journal);
  239. expect(contentSpy).toHaveBeenCalledTimes(2);
  240. });
  241. it("形状不合的行整条跳过:非对象 result、缺 version、未知 kind", () => {
  242. const journal = new ArtifactAwareJournalStore();
  243. makeRun(journal, "run-bad", "completed");
  244. journal.putNode({
  245. runId: "run-bad",
  246. siteId: "artifact#1",
  247. ordinal: 1,
  248. kind: "artifact",
  249. inputHash: "h1",
  250. status: "completed",
  251. artifactId: "a",
  252. result: "not an object",
  253. });
  254. putArtifact(journal, "run-bad", 2, { id: "b", kind: "file", publishedAt: 1 });
  255. putArtifact(journal, "run-bad", 3, { id: "c", kind: "hologram", version: 1, publishedAt: 1 });
  256. putArtifact(journal, "run-bad", 4, { id: "d", kind: "file", version: 1, publishedAt: 1 });
  257. const { artifacts } = artifactsOf("run-bad", journal);
  258. expect(artifacts?.map((artifact) => artifact.id)).toEqual(["d"]);
  259. });
  260. // driver 恒写 publishedAt(引擎的类型上它才是可选的)。缺席时给 0 而不是丢行:一个没有
  261. // 时间戳的产物仍然可看,丢掉它会让版本号在 UI 上出现空洞。
  262. it("缺 publishedAt 的老行仍然可读,时间戳落到 0", () => {
  263. const journal = new ArtifactAwareJournalStore();
  264. makeRun(journal, "run-old", "completed");
  265. putArtifact(journal, "run-old", 1, { id: "legacy", kind: "markdown", version: 1 });
  266. const { artifacts } = artifactsOf("run-old", journal);
  267. expect(artifacts![0]!.versions[0]?.publishedAt).toBe(0);
  268. });
  269. });
  270. describe("snapshotOf — 终态快照上的 artifacts", () => {
  271. function entryFor(): Map<string, RunRegistryEntry> {
  272. return new Map();
  273. }
  274. it("终态才带 artifacts;running 的快照一行都不读", () => {
  275. const journal = new ArtifactAwareJournalStore();
  276. makeRun(journal, "run-live", "running");
  277. putArtifact(journal, "run-live", 1, {
  278. id: "notes",
  279. kind: "markdown",
  280. version: 1,
  281. publishedAt: 1,
  282. });
  283. const listNodes = vi.spyOn(journal, "listNodes");
  284. const running = snapshotOf("run-live", entryFor(), journal);
  285. expect(running?.status).toBe("running");
  286. expect(running && "artifacts" in running).toBe(false);
  287. expect(running && "reports" in running).toBe(false);
  288. // 在飞时既不扫节点表也不查产物行:`getTask` 会被后台追踪器反复轮询。
  289. expect(listNodes).not.toHaveBeenCalled();
  290. journal.updateRunStatus("run-live", "completed", { result: "done" });
  291. const settled = snapshotOf("run-live", entryFor(), journal);
  292. expect(settled?.artifacts).toHaveLength(1);
  293. expect(settled?.artifacts?.[0]?.id).toBe("notes");
  294. // ⚠ 两个 artifact 并列:`output` 是脚本的顶层返回值,`artifacts` 是发布给用户看的产出。
  295. expect(settled?.output).toBe("done");
  296. });
  297. it("errored 与 stopped 的快照一样带 artifacts(半途交付的东西仍在用户面前)", () => {
  298. // 快照基类的 status 是后台任务追踪器的通用词汇(errored → failed、stopped → cancelled);
  299. // 真实词在 runStatus 上(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。
  300. for (const [status, taskStatus] of [
  301. ["errored", "failed"],
  302. ["stopped", "cancelled"],
  303. ] as const) {
  304. const journal = new ArtifactAwareJournalStore();
  305. const runId = `run-${status}`;
  306. makeRun(journal, runId, "running");
  307. putArtifact(journal, runId, 1, { id: "notes", kind: "markdown", version: 1, publishedAt: 1 });
  308. journal.updateRunStatus(runId, status, {
  309. ...(status === "stopped" ? { stopReason: "interrupted" as const } : {}),
  310. failure: { code: status === "stopped" ? "Interrupted" : "DriverError", message: "boom" },
  311. });
  312. const snapshot = snapshotOf(runId, entryFor(), journal);
  313. expect(snapshot?.status).toBe(taskStatus);
  314. expect(snapshot?.runStatus).toBe(status);
  315. expect(snapshot?.artifacts).toHaveLength(1);
  316. }
  317. });
  318. it("零件时整字段缺席;journal 不带能力时也缺席", () => {
  319. const journal = new ArtifactAwareJournalStore();
  320. makeRun(journal, "run-none", "completed");
  321. const snapshot = snapshotOf("run-none", entryFor(), journal);
  322. expect(snapshot && "artifacts" in snapshot).toBe(false);
  323. const plain = new InMemoryJournalStore();
  324. makeRun(plain, "run-plain", "completed");
  325. putArtifact(plain, "run-plain", 1, {
  326. id: "notes",
  327. kind: "markdown",
  328. version: 1,
  329. publishedAt: 1,
  330. });
  331. const plainSnapshot = snapshotOf("run-plain", entryFor(), plain);
  332. expect(plainSnapshot && "artifacts" in plainSnapshot).toBe(false);
  333. });
  334. // 终态快照的读形状(docs/execution-engine.md「Reading the journal」):report item 只读到
  335. // 快照的界,总数是 count,标签计数只读元数据——没有一次读把整张节点表连同 item 读出来。
  336. it("reads report items only up to the snapshot bound and counts everything else", () => {
  337. const journal = new ArtifactAwareJournalStore();
  338. makeRun(journal, "run-share", "running");
  339. putArtifact(journal, "run-share", 1, {
  340. id: "perf",
  341. kind: "chart",
  342. version: 1,
  343. publishedAt: 1,
  344. spec: {},
  345. });
  346. putTaggedReport(journal, "run-share", 1, "perf");
  347. putTaggedReport(journal, "run-share", 2);
  348. journal.updateRunStatus("run-share", "completed");
  349. const listNodes = vi.spyOn(journal, "listNodes");
  350. const snapshot = snapshotOf("run-share", entryFor(), journal);
  351. expect(snapshot?.reports).toHaveLength(2);
  352. expect(snapshot?.reportCount).toBe(2);
  353. expect(snapshot?.artifacts?.[0]?.itemCount).toBe(1);
  354. expect(listNodes.mock.calls.map(([, opts]) => opts)).toEqual([
  355. { kinds: ["report"], withResult: true, limit: 256, maxResultBytes: 8 * 1024 * 1024 },
  356. // listArtifactRows 的内存替身
  357. { kinds: ["artifact"], withResult: true },
  358. // 不带 countTaggedReports 的 store 退回读 report 元数据(不带 item)
  359. { kinds: ["report"], withResult: false },
  360. ]);
  361. });
  362. it("carries the first 256 items and the true total when a run reported more", () => {
  363. const journal = new ArtifactAwareJournalStore();
  364. makeRun(journal, "run-many", "running");
  365. for (let ordinal = 1; ordinal <= 300; ordinal += 1)
  366. putTaggedReport(journal, "run-many", ordinal);
  367. journal.updateRunStatus("run-many", "completed");
  368. const snapshot = snapshotOf("run-many", entryFor(), journal);
  369. expect(snapshot?.reportCount).toBe(300);
  370. expect(snapshot?.reports).toHaveLength(256);
  371. // 报告顺序:前 256 条,一条不跳。
  372. expect(snapshot?.reports?.[0]).toEqual({ round: 1 });
  373. expect(snapshot?.reports?.[255]).toEqual({ round: 256 });
  374. });
  375. it("leaves reports and reportCount out when the run reported nothing", () => {
  376. const journal = new ArtifactAwareJournalStore();
  377. makeRun(journal, "run-quiet", "completed");
  378. const snapshot = snapshotOf("run-quiet", entryFor(), journal);
  379. expect(snapshot && "reports" in snapshot).toBe(false);
  380. expect(snapshot && "reportCount" in snapshot).toBe(false);
  381. });
  382. });