saved-workflows-protocol.test.ts 27 KB

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