saved-workflows-protocol.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. // 已保存工作流 GUI 中枢的五个 workspace 级协议方法(docs/dynamic-workflow/launch.md)。
  2. // 真实 tmp 目录 + core 的真实 store / codec;只有 journal 用能力探测式的假实现。
  3. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  4. import { createHash } from "node:crypto";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  8. import {
  9. zcodeWorkflowsDeleteResultSchema,
  10. zcodeWorkflowsGetResultSchema,
  11. zcodeWorkflowsListResultSchema,
  12. zcodeWorkflowsMoveResultSchema,
  13. zcodeWorkflowsRunsParamsSchema,
  14. zcodeWorkflowsRunsResultSchema,
  15. zcodeWorkflowsUpdateMetaResultSchema,
  16. } from "@zcode/shared";
  17. import { SavedWorkflowEntrySchema, SavedWorkflowMetaSchema } from "@zcode/contracts";
  18. import { parseSavedWorkflow, serializeSavedWorkflow } from "@zcode/core";
  19. import {
  20. deleteSavedWorkflowOp,
  21. getSavedWorkflowOp,
  22. listSavedWorkflowRunsOp,
  23. listSavedWorkflowsOp,
  24. moveSavedWorkflowOp,
  25. updateSavedWorkflowMetaOp,
  26. } from "../src/zcode-protocol/saved-workflows.js";
  27. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  28. const SCRIPT = [
  29. 'const reviewer = agent("检查员");',
  30. "const found = await reviewer.ask<string>(`检查 ${String(args.target)}`);",
  31. "return found;",
  32. "",
  33. ].join("\n");
  34. let cwd = "";
  35. // 每个用例一份隔离的 HOME:全局档落在 `<HOME>/.zcode/workflows/`,core 恒取 `os.homedir()`
  36. // (posix 上即 `$HOME`)。不隔离的话 list/get/move 的全局变体会读到真实家目录、结果非确定。
  37. let home = "";
  38. let prevHome: string | undefined;
  39. let prevUserProfile: string | undefined;
  40. function workspace() {
  41. return { workspacePath: cwd, workspaceKey: cwd };
  42. }
  43. function contextWith(sessionStore?: unknown): ZCodeProtocolAgentServerContext {
  44. return {
  45. deps: { env: {}, sessionStore },
  46. sessions: new Map(),
  47. } as unknown as ZCodeProtocolAgentServerContext;
  48. }
  49. function projectDir() {
  50. return join(cwd, ".zcode", "workflows");
  51. }
  52. function globalDir() {
  53. return join(home, ".zcode", "workflows");
  54. }
  55. async function seedWorkflow(name: string, meta: Parameters<typeof serializeSavedWorkflow>[0]) {
  56. await mkdir(projectDir(), { recursive: true });
  57. const path = join(projectDir(), `${name}.dwf.ts`);
  58. await writeFile(path, serializeSavedWorkflow(meta, SCRIPT), "utf8");
  59. return path;
  60. }
  61. async function seedGlobalWorkflow(
  62. name: string,
  63. meta: Parameters<typeof serializeSavedWorkflow>[0],
  64. ) {
  65. await mkdir(globalDir(), { recursive: true });
  66. const path = join(globalDir(), `${name}.dwf.ts`);
  67. await writeFile(path, serializeSavedWorkflow(meta, SCRIPT), "utf8");
  68. return path;
  69. }
  70. beforeEach(async () => {
  71. cwd = await mkdtemp(join(tmpdir(), "zcode-saved-workflows-protocol-"));
  72. home = await mkdtemp(join(tmpdir(), "zcode-saved-workflows-home-"));
  73. prevHome = process.env.HOME;
  74. prevUserProfile = process.env.USERPROFILE;
  75. process.env.HOME = home;
  76. process.env.USERPROFILE = home;
  77. });
  78. afterEach(async () => {
  79. if (prevHome === undefined) delete process.env.HOME;
  80. else process.env.HOME = prevHome;
  81. if (prevUserProfile === undefined) delete process.env.USERPROFILE;
  82. else process.env.USERPROFILE = prevUserProfile;
  83. await rm(cwd, { recursive: true, force: true });
  84. await rm(home, { recursive: true, force: true });
  85. });
  86. describe("workflows/* protocol methods", () => {
  87. it("list:目录不存在回空(带 dir);坏文件进 invalid;legacy .workflow.js 不可见;不回脚本正文", async () => {
  88. expect(await listSavedWorkflowsOp(contextWith(), { workspace: workspace() })).toEqual({
  89. workflows: [],
  90. invalid: [],
  91. dir: projectDir(),
  92. });
  93. await seedWorkflow("release-check", {
  94. description: "发布前检查",
  95. whenToUse: "要发版时",
  96. args: { target: { type: "string", required: true } },
  97. });
  98. await writeFile(join(cwd, ".zcode", "workflows", "broken.dwf.ts"), "const x = 1;\n", "utf8");
  99. await writeFile(
  100. join(cwd, ".zcode", "workflows", "legacy.workflow.js"),
  101. "export const meta = {};\n",
  102. );
  103. const result = await listSavedWorkflowsOp(contextWith(), { workspace: workspace() });
  104. // 协议 schema(shared)与 contracts 的 entry schema 都要认同一份结果——两边形状互相钉住。
  105. expect(() => zcodeWorkflowsListResultSchema.parse(result)).not.toThrow();
  106. for (const entry of result.workflows) {
  107. expect(() => SavedWorkflowEntrySchema.parse(entry)).not.toThrow();
  108. }
  109. expect(result.workflows.map((entry) => entry.name)).toEqual(["release-check"]);
  110. expect(result.workflows[0]).toMatchObject({
  111. description: "发布前检查",
  112. whenToUse: "要发版时",
  113. scope: "project",
  114. path: join(cwd, ".zcode", "workflows", "release-check.dwf.ts"),
  115. });
  116. expect(JSON.stringify(result)).not.toContain("reviewer.ask");
  117. expect(result.invalid).toHaveLength(1);
  118. expect(result.invalid[0]?.path).toBe(join(cwd, ".zcode", "workflows", "broken.dwf.ts"));
  119. expect(result.invalid[0]?.reason).toContain("missing_frontmatter");
  120. });
  121. it("get:命中回 meta + 脚本本体;invalid_name / not_found / parse_error 各自可分辨", async () => {
  122. await seedWorkflow("release-check", { description: "发布前检查" });
  123. await writeFile(
  124. join(cwd, ".zcode", "workflows", "broken.dwf.ts"),
  125. "/* zcode-workflow\nx: [\n*/\n",
  126. );
  127. const hit = await getSavedWorkflowOp(contextWith(), {
  128. workspace: workspace(),
  129. name: "release-check",
  130. });
  131. expect(() => zcodeWorkflowsGetResultSchema.parse(hit)).not.toThrow();
  132. expect(hit).toMatchObject({
  133. ok: true,
  134. name: "release-check",
  135. scope: "project",
  136. meta: { description: "发布前检查" },
  137. script: SCRIPT,
  138. });
  139. expect(
  140. await getSavedWorkflowOp(contextWith(), { workspace: workspace(), name: "../etc" }),
  141. ).toMatchObject({
  142. ok: false,
  143. reason: "invalid_name",
  144. });
  145. expect(
  146. await getSavedWorkflowOp(contextWith(), { workspace: workspace(), name: "missing" }),
  147. ).toEqual({
  148. ok: false,
  149. reason: "not_found",
  150. });
  151. expect(
  152. await getSavedWorkflowOp(contextWith(), { workspace: workspace(), name: "broken" }),
  153. ).toMatchObject({
  154. ok: false,
  155. reason: "parse_error",
  156. });
  157. });
  158. it("updateMeta:覆写后可读回新 meta,脚本正文逐字节不变;strict 拒未知键;不存在 → not_found 且不建文件", async () => {
  159. const path = await seedWorkflow("release-check", {
  160. description: "旧说明",
  161. args: { target: { type: "string", required: true } },
  162. });
  163. const scriptHashBefore = createHash("sha256").update(SCRIPT).digest("hex");
  164. const meta = {
  165. description: "新说明",
  166. whenToUse: "要发版、release、上线前检查时",
  167. args: {
  168. target: { type: "string", required: true, description: "要检查的包名或路径" },
  169. skipTests: { type: "boolean", default: false },
  170. },
  171. };
  172. const updated = await updateSavedWorkflowMetaOp(contextWith(), {
  173. workspace: workspace(),
  174. name: "release-check",
  175. meta,
  176. });
  177. expect(() => zcodeWorkflowsUpdateMetaResultSchema.parse(updated)).not.toThrow();
  178. expect(updated).toEqual({ ok: true, path });
  179. const parsed = parseSavedWorkflow(await readFile(path, "utf8"));
  180. expect(parsed.ok).toBe(true);
  181. if (!parsed.ok) throw new Error("unreachable");
  182. expect(parsed.meta).toEqual(SavedWorkflowMetaSchema.parse(meta));
  183. expect(createHash("sha256").update(parsed.script).digest("hex")).toBe(scriptHashBefore);
  184. await expect(
  185. updateSavedWorkflowMetaOp(contextWith(), {
  186. workspace: workspace(),
  187. name: "release-check",
  188. meta: { description: "x", permissionMode: "yolo" },
  189. }),
  190. ).rejects.toThrow();
  191. expect(
  192. await updateSavedWorkflowMetaOp(contextWith(), {
  193. workspace: workspace(),
  194. name: "ghost",
  195. meta: { description: "x" },
  196. }),
  197. ).toEqual({ ok: false, reason: "not_found" });
  198. await expect(readFile(join(cwd, ".zcode", "workflows", "ghost.dwf.ts"))).rejects.toThrow();
  199. });
  200. it("delete:删后 list 不再列出;not_found;非法名字在触盘前拒绝;不删同名 .workflow.js", async () => {
  201. const path = await seedWorkflow("release-check", { description: "发布前检查" });
  202. const legacyPath = join(cwd, ".zcode", "workflows", "release-check.workflow.js");
  203. await writeFile(legacyPath, "export const meta = {};\n");
  204. const deleted = await deleteSavedWorkflowOp(contextWith(), {
  205. workspace: workspace(),
  206. name: "release-check",
  207. });
  208. expect(() => zcodeWorkflowsDeleteResultSchema.parse(deleted)).not.toThrow();
  209. expect(deleted).toEqual({ ok: true, path });
  210. expect(
  211. (await listSavedWorkflowsOp(contextWith(), { workspace: workspace() })).workflows,
  212. ).toEqual([]);
  213. await expect(readFile(legacyPath, "utf8")).resolves.toContain("export const meta");
  214. expect(
  215. await deleteSavedWorkflowOp(contextWith(), { workspace: workspace(), name: "release-check" }),
  216. ).toEqual({
  217. ok: false,
  218. reason: "not_found",
  219. });
  220. for (const name of ["..", "../x", "a/b", "a\\b", "."]) {
  221. expect(await deleteSavedWorkflowOp(contextWith(), { workspace: workspace(), name })).toEqual({
  222. ok: false,
  223. reason: "invalid_name",
  224. });
  225. }
  226. });
  227. it("runs:journal 缺席回空页;有 journal 时按 cwd + name 下推、多取一条判 truncated、行带归属字段", async () => {
  228. expect(
  229. await listSavedWorkflowRunsOp(contextWith(undefined), { workspace: workspace(), limit: 5 }),
  230. ).toEqual({
  231. runs: [],
  232. });
  233. const queries: unknown[] = [];
  234. const rows = [
  235. {
  236. runId: "run_2",
  237. name: "release-check",
  238. status: "completed",
  239. spentTokens: 38_200,
  240. timeCreated: 100,
  241. timeUpdated: 400,
  242. parentSessionId: "session-a",
  243. toolCallId: "call-2",
  244. args: { target: "packages/ui" },
  245. caps: { maxConcurrency: 1 },
  246. },
  247. {
  248. runId: "run_1",
  249. status: "errored",
  250. spentTokens: 6_100,
  251. timeCreated: 10,
  252. timeUpdated: 20,
  253. caps: { maxConcurrency: 1 },
  254. },
  255. {
  256. runId: "run_0",
  257. status: "stopped",
  258. spentTokens: 0,
  259. timeCreated: 1,
  260. timeUpdated: 2,
  261. caps: { maxConcurrency: 1 },
  262. },
  263. ];
  264. const journal = {
  265. countNodesByStatus: () => ({ completed: 0, failed: 0, running: 0 }),
  266. getRunRow: () => undefined,
  267. listRecentLogEvents: () => [],
  268. listRuns: (query: unknown) => {
  269. queries.push(query);
  270. return rows.slice(0, (query as { limit: number }).limit);
  271. },
  272. };
  273. const sessionStore = { workflowJournalStore: () => journal };
  274. const params = zcodeWorkflowsRunsParamsSchema.parse({
  275. workspace: workspace(),
  276. name: "release-check",
  277. limit: 2,
  278. });
  279. const result = await listSavedWorkflowRunsOp(contextWith(sessionStore), params);
  280. expect(() => zcodeWorkflowsRunsResultSchema.parse(result)).not.toThrow();
  281. expect(queries).toEqual([{ cwd, limit: 3, name: "release-check" }]);
  282. expect(result).toEqual({
  283. runs: [
  284. {
  285. runId: "run_2",
  286. name: "release-check",
  287. status: "completed",
  288. createdAt: 100,
  289. updatedAt: 400,
  290. spentTokens: 38_200,
  291. parentSessionId: "session-a",
  292. toolCallId: "call-2",
  293. args: { target: "packages/ui" },
  294. },
  295. { runId: "run_1", status: "errored", createdAt: 10, updatedAt: 20, spentTokens: 6_100 },
  296. ],
  297. truncated: true,
  298. });
  299. // 恰好 limit 条:没有探测行 → 不带 truncated 键。
  300. const exact = await listSavedWorkflowRunsOp(contextWith(sessionStore), {
  301. workspace: workspace(),
  302. limit: 3,
  303. });
  304. expect(exact).not.toHaveProperty("truncated");
  305. expect(exact.runs).toHaveLength(3);
  306. expect(queries.at(-1)).toEqual({ cwd, limit: 4 });
  307. // 上面那个假 journal 没有 listArtifactRows:能力缺席 ⇒ 每行的 artifacts 整字段缺席
  308. // (老 CLI / 注入的测试 store 逐字不变)。上面的 toEqual 已经把这一点钉死了。
  309. });
  310. // 用户面产物的中枢摘要(docs/dynamic-workflow/authoring.md「How the user sees them」)。
  311. // ⚠ 术语:这里的 artifact 是脚本经 `artifact.*` 发布给用户看的产出,不是脚本的顶层返回值。
  312. it("runs:能力在场时按 runId 逐行汇总 artifacts,只取 completed 行与最新版", async () => {
  313. const artifactRow = (
  314. runId: string,
  315. id: string,
  316. version: number,
  317. overrides: Record<string, unknown> = {},
  318. ) => ({
  319. runId,
  320. siteId: `artifact#${version}`,
  321. ordinal: version,
  322. kind: "artifact" as const,
  323. inputHash: "h",
  324. status: "completed" as const,
  325. artifactId: id,
  326. result: { id, version, publishedAt: version, ...overrides },
  327. });
  328. const artifactRows: Record<string, unknown[]> = {
  329. run_2: [
  330. artifactRow("run_2", "audit", 1, { kind: "file", title: "旧版", bytes: 10 }),
  331. artifactRow("run_2", "audit", 2, {
  332. kind: "file",
  333. title: "审计报告",
  334. contentType: "application/pdf",
  335. bytes: 4_096,
  336. }),
  337. // 失败的发布不占版本号,也不该进 chips。
  338. {
  339. runId: "run_2",
  340. siteId: "artifact#3",
  341. ordinal: 3,
  342. kind: "artifact",
  343. inputHash: "h",
  344. status: "errored",
  345. artifactId: "broken",
  346. error: { code: "ArtifactSourceMissing", message: "gone" },
  347. },
  348. artifactRow("run_2", "perf", 1, { kind: "chart", spec: { x: { field: "round" } } }),
  349. ],
  350. run_1: [],
  351. };
  352. const journal = {
  353. countNodesByStatus: () => ({ completed: 0, failed: 0, running: 0 }),
  354. getRunRow: () => undefined,
  355. listRecentLogEvents: () => [],
  356. listRuns: (query: unknown) =>
  357. [
  358. { runId: "run_2", status: "completed", spentTokens: 1, timeCreated: 1, timeUpdated: 2 },
  359. { runId: "run_1", status: "errored", spentTokens: 1, timeCreated: 1, timeUpdated: 2 },
  360. ].slice(0, (query as { limit: number }).limit),
  361. listArtifactRows: (runId: string) => artifactRows[runId] ?? [],
  362. // 预置看板在场时才会被调到:标签 report 行的计数。
  363. listNodes: (runId: string) =>
  364. runId === "run_2"
  365. ? [
  366. {
  367. runId,
  368. siteId: "report#1",
  369. ordinal: 1,
  370. kind: "report",
  371. inputHash: "h",
  372. status: "completed",
  373. artifactId: "perf",
  374. result: {},
  375. },
  376. {
  377. runId,
  378. siteId: "report#2",
  379. ordinal: 2,
  380. kind: "report",
  381. inputHash: "h",
  382. status: "completed",
  383. artifactId: "perf",
  384. result: {},
  385. },
  386. // 无标签的 report 不计入任何产物。
  387. {
  388. runId,
  389. siteId: "report#3",
  390. ordinal: 3,
  391. kind: "report",
  392. inputHash: "h",
  393. status: "completed",
  394. result: {},
  395. },
  396. ]
  397. : [],
  398. };
  399. const sessionStore = { workflowJournalStore: () => journal };
  400. const result = await listSavedWorkflowRunsOp(contextWith(sessionStore), {
  401. workspace: workspace(),
  402. limit: 5,
  403. });
  404. expect(() => zcodeWorkflowsRunsResultSchema.parse(result)).not.toThrow();
  405. // 顶层字段取最新版(title 是 v2 的「审计报告」而不是 v1 的「旧版」);失败行不出现。
  406. expect(result.runs[0]?.artifacts).toEqual([
  407. { id: "audit", kind: "file", title: "审计报告", version: 2, contentType: "application/pdf" },
  408. { id: "perf", kind: "chart", version: 1 },
  409. ]);
  410. // 零件的 run:整字段缺席,不是空数组。
  411. expect(result.runs[1]).not.toHaveProperty("artifacts");
  412. });
  413. });
  414. // 全局作用域(docs/dynamic-workflow/launch.md):五个方法的定向 `scope` 变体 + workflows/move。
  415. // 全局档落在隔离的 `<HOME>/.zcode/workflows/`(见顶部 beforeEach);同名的项目档不受牵连。
  416. describe("workflows/* 全局作用域与 workflows/move", () => {
  417. it("list:项目变体只列项目档 + dir=项目根(即使目录不存在);全局变体只列全局档 + dir=全局根", async () => {
  418. // 项目根不存在也回 dir(GUI 靠它 watch)。
  419. expect(
  420. await listSavedWorkflowsOp(contextWith(), { workspace: workspace(), scope: "project" }),
  421. ).toEqual({
  422. workflows: [],
  423. invalid: [],
  424. dir: projectDir(),
  425. });
  426. expect(
  427. await listSavedWorkflowsOp(contextWith(), { workspace: workspace(), scope: "global" }),
  428. ).toEqual({
  429. workflows: [],
  430. invalid: [],
  431. dir: globalDir(),
  432. });
  433. await seedWorkflow("proj-only", { description: "本项目档" });
  434. await seedGlobalWorkflow("global-only", { description: "全局档" });
  435. const proj = await listSavedWorkflowsOp(contextWith(), {
  436. workspace: workspace(),
  437. scope: "project",
  438. });
  439. expect(() => zcodeWorkflowsListResultSchema.parse(proj)).not.toThrow();
  440. expect(proj.dir).toBe(projectDir());
  441. expect(proj.workflows.map((entry) => entry.name)).toEqual(["proj-only"]);
  442. expect(proj.workflows[0]).toMatchObject({ scope: "project" });
  443. const glob = await listSavedWorkflowsOp(contextWith(), {
  444. workspace: workspace(),
  445. scope: "global",
  446. });
  447. expect(() => zcodeWorkflowsListResultSchema.parse(glob)).not.toThrow();
  448. expect(glob.dir).toBe(globalDir());
  449. expect(glob.workflows.map((entry) => entry.name)).toEqual(["global-only"]);
  450. expect(glob.workflows[0]).toMatchObject({
  451. scope: "global",
  452. path: join(globalDir(), "global-only.dwf.ts"),
  453. });
  454. });
  455. it("list:同名在两档都在时——项目变体只见项目档、全局变体只见全局档(定向列表不做遮蔽)", async () => {
  456. await seedWorkflow("shared", { description: "项目那份" });
  457. await seedGlobalWorkflow("shared", { description: "全局那份" });
  458. const proj = await listSavedWorkflowsOp(contextWith(), {
  459. workspace: workspace(),
  460. scope: "project",
  461. });
  462. expect(proj.workflows).toMatchObject([
  463. { name: "shared", description: "项目那份", scope: "project" },
  464. ]);
  465. const glob = await listSavedWorkflowsOp(contextWith(), {
  466. workspace: workspace(),
  467. scope: "global",
  468. });
  469. expect(glob.workflows).toMatchObject([
  470. { name: "shared", description: "全局那份", scope: "global" },
  471. ]);
  472. });
  473. it("get:scope:global 读全局档、不被同名项目档遮蔽;默认(无 scope)读项目档", async () => {
  474. await seedWorkflow("shared", { description: "项目那份" });
  475. await seedGlobalWorkflow("shared", { description: "全局那份" });
  476. const glob = await getSavedWorkflowOp(contextWith(), {
  477. workspace: workspace(),
  478. name: "shared",
  479. scope: "global",
  480. });
  481. expect(() => zcodeWorkflowsGetResultSchema.parse(glob)).not.toThrow();
  482. expect(glob).toMatchObject({
  483. ok: true,
  484. name: "shared",
  485. scope: "global",
  486. path: join(globalDir(), "shared.dwf.ts"),
  487. meta: { description: "全局那份" },
  488. });
  489. const def = await getSavedWorkflowOp(contextWith(), { workspace: workspace(), name: "shared" });
  490. expect(def).toMatchObject({ ok: true, scope: "project", meta: { description: "项目那份" } });
  491. // 只在全局档存在:项目变体 not_found,全局变体命中。
  492. await seedGlobalWorkflow("global-only", { description: "只全局" });
  493. expect(
  494. await getSavedWorkflowOp(contextWith(), {
  495. workspace: workspace(),
  496. name: "global-only",
  497. scope: "project",
  498. }),
  499. ).toEqual({ ok: false, reason: "not_found" });
  500. expect(
  501. await getSavedWorkflowOp(contextWith(), {
  502. workspace: workspace(),
  503. name: "global-only",
  504. scope: "global",
  505. }),
  506. ).toMatchObject({ ok: true, scope: "global" });
  507. });
  508. it("updateMeta:scope:global 改全局档、同名项目档逐字不动", async () => {
  509. const projPath = await seedWorkflow("shared", { description: "项目原样" });
  510. await seedGlobalWorkflow("shared", { description: "全局旧说明" });
  511. const projBefore = await readFile(projPath, "utf8");
  512. const updated = await updateSavedWorkflowMetaOp(contextWith(), {
  513. workspace: workspace(),
  514. name: "shared",
  515. meta: { description: "全局新说明" },
  516. scope: "global",
  517. });
  518. expect(() => zcodeWorkflowsUpdateMetaResultSchema.parse(updated)).not.toThrow();
  519. expect(updated).toEqual({ ok: true, path: join(globalDir(), "shared.dwf.ts") });
  520. const globParsed = parseSavedWorkflow(
  521. await readFile(join(globalDir(), "shared.dwf.ts"), "utf8"),
  522. );
  523. expect(globParsed.ok).toBe(true);
  524. if (!globParsed.ok) throw new Error("unreachable");
  525. expect(globParsed.meta.description).toBe("全局新说明");
  526. // 项目档逐字不变。
  527. expect(await readFile(projPath, "utf8")).toBe(projBefore);
  528. });
  529. it("delete:scope:global 删全局档、同名项目档留存;按 scope 选根(不写死 roots[0])", async () => {
  530. const projPath = await seedWorkflow("shared", { description: "项目那份" });
  531. const globPath = await seedGlobalWorkflow("shared", { description: "全局那份" });
  532. const deleted = await deleteSavedWorkflowOp(contextWith(), {
  533. workspace: workspace(),
  534. name: "shared",
  535. scope: "global",
  536. });
  537. expect(() => zcodeWorkflowsDeleteResultSchema.parse(deleted)).not.toThrow();
  538. expect(deleted).toEqual({ ok: true, path: globPath });
  539. await expect(readFile(globPath, "utf8")).rejects.toThrow();
  540. // 项目档留存。
  541. await expect(readFile(projPath, "utf8")).resolves.toContain("项目那份");
  542. expect(
  543. (await listSavedWorkflowsOp(contextWith(), { workspace: workspace(), scope: "project" }))
  544. .workflows,
  545. ).toHaveLength(1);
  546. expect(
  547. (await listSavedWorkflowsOp(contextWith(), { workspace: workspace(), scope: "global" }))
  548. .workflows,
  549. ).toEqual([]);
  550. });
  551. it("runs:全局变体跨 cwd(省 cwd 谓词)、每行带 cwd;项目变体仍按 cwd 过滤", async () => {
  552. const queries: unknown[] = [];
  553. const rows = [
  554. {
  555. runId: "run_b",
  556. name: "research",
  557. status: "completed",
  558. spentTokens: 100,
  559. timeCreated: 20,
  560. timeUpdated: 30,
  561. cwd: "/repos/beta",
  562. caps: { maxConcurrency: 1 },
  563. },
  564. {
  565. runId: "run_a",
  566. name: "research",
  567. status: "errored",
  568. spentTokens: 50,
  569. timeCreated: 5,
  570. timeUpdated: 10,
  571. cwd: "/repos/alpha",
  572. caps: { maxConcurrency: 1 },
  573. },
  574. ];
  575. const journal = {
  576. countNodesByStatus: () => ({ completed: 0, failed: 0, running: 0 }),
  577. getRunRow: () => undefined,
  578. listRecentLogEvents: () => [],
  579. listRuns: (query: unknown) => {
  580. queries.push(query);
  581. return rows.slice(0, (query as { limit: number }).limit);
  582. },
  583. };
  584. const sessionStore = { workflowJournalStore: () => journal };
  585. const glob = await listSavedWorkflowRunsOp(contextWith(sessionStore), {
  586. workspace: workspace(),
  587. name: "research",
  588. limit: 10,
  589. scope: "global",
  590. });
  591. expect(() => zcodeWorkflowsRunsResultSchema.parse(glob)).not.toThrow();
  592. // 全局变体:查询袋没有 cwd 键(跨所有项目)。
  593. expect(queries).toEqual([{ limit: 11, name: "research" }]);
  594. expect(glob.runs).toEqual([
  595. {
  596. runId: "run_b",
  597. name: "research",
  598. status: "completed",
  599. createdAt: 20,
  600. updatedAt: 30,
  601. spentTokens: 100,
  602. cwd: "/repos/beta",
  603. },
  604. {
  605. runId: "run_a",
  606. name: "research",
  607. status: "errored",
  608. createdAt: 5,
  609. updatedAt: 10,
  610. spentTokens: 50,
  611. cwd: "/repos/alpha",
  612. },
  613. ]);
  614. // 项目变体:仍带 cwd 谓词。
  615. await listSavedWorkflowRunsOp(contextWith(sessionStore), {
  616. workspace: workspace(),
  617. name: "research",
  618. limit: 10,
  619. scope: "project",
  620. });
  621. expect(queries.at(-1)).toEqual({ cwd, limit: 11, name: "research" });
  622. });
  623. // move 只有全局→项目一向(docs/dynamic-workflow/launch.md「Promote to global」):项目→全局
  624. // 是模型的概括「提升为全局」,协议上没有那一向。
  625. it("move:全局→项目成功——逐字节相同、源删除、结果 {ok, from, to}(无 to 参数)", async () => {
  626. const globPath = await seedGlobalWorkflow("mover", {
  627. description: "回项目",
  628. args: { target: { type: "string", required: true } },
  629. });
  630. const before = await readFile(globPath, "utf8");
  631. const result = await moveSavedWorkflowOp(contextWith(), {
  632. workspace: workspace(),
  633. name: "mover",
  634. });
  635. expect(() => zcodeWorkflowsMoveResultSchema.parse(result)).not.toThrow();
  636. const projPath = join(projectDir(), "mover.dwf.ts");
  637. expect(result).toEqual({ ok: true, from: globPath, to: projPath });
  638. // 源已删。
  639. await expect(readFile(globPath, "utf8")).rejects.toThrow();
  640. // 目标逐字节相同。
  641. expect(await readFile(projPath, "utf8")).toBe(before);
  642. });
  643. it("move:带 to 参数被 -32602 拒(那一向已不存在)", async () => {
  644. await seedWorkflow("mover", { description: "项目那份" });
  645. await expect(
  646. moveSavedWorkflowOp(contextWith(), { workspace: workspace(), name: "mover", to: "global" }),
  647. ).rejects.toThrow();
  648. // 项目档原样不动。
  649. await expect(readFile(join(projectDir(), "mover.dwf.ts"), "utf8")).resolves.toContain(
  650. "项目那份",
  651. );
  652. });
  653. it("move:target_exists(项目里已有同名,不覆盖)带项目落点 path", async () => {
  654. const projPath = await seedWorkflow("dup", { description: "项目那份" });
  655. const globPath = await seedGlobalWorkflow("dup", { description: "全局那份" });
  656. const result = await moveSavedWorkflowOp(contextWith(), {
  657. workspace: workspace(),
  658. name: "dup",
  659. });
  660. expect(() => zcodeWorkflowsMoveResultSchema.parse(result)).not.toThrow();
  661. expect(result).toEqual({ ok: false, reason: "target_exists", path: projPath });
  662. // 两份都还在。
  663. await expect(readFile(join(projectDir(), "dup.dwf.ts"), "utf8")).resolves.toContain("项目那份");
  664. await expect(readFile(globPath, "utf8")).resolves.toContain("全局那份");
  665. });
  666. it("move:not_found(全局根没有这个名字;项目档不是源)与 invalid_name(名字先验)", async () => {
  667. await seedWorkflow("ghost", { description: "只在项目里" });
  668. expect(
  669. await moveSavedWorkflowOp(contextWith(), {
  670. workspace: workspace(),
  671. name: "ghost",
  672. }),
  673. ).toEqual({ ok: false, reason: "not_found" });
  674. const invalid = await moveSavedWorkflowOp(contextWith(), {
  675. workspace: workspace(),
  676. name: "../etc",
  677. });
  678. expect(invalid).toMatchObject({ ok: false, reason: "invalid_name" });
  679. expect(() => zcodeWorkflowsMoveResultSchema.parse(invalid)).not.toThrow();
  680. });
  681. });