From b043cb614ee92fae0ae260d63a45df14472744d1 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 15 Oct 2026 15:18:49 +0800 Subject: [PATCH] feat(workflow): implement workflow copy and delete lifecycle commands --- skills/hose-use/SKILL.md | 2 + skills/hose-use/references/workflow.md | 24 ++- src/cli/commands/workflow.test.ts | 262 ++++++++++++++++++++++++ src/cli/commands/workflow/copy.ts | 96 +++++++++ src/cli/commands/workflow/delete.ts | 64 ++++++ src/cli/commands/workflow/index.ts | 12 +- src/domains/platform/README.platform.md | 2 + src/domains/platform/api.ts | 30 +++ src/domains/platform/services.ts | 31 +++ 9 files changed, 521 insertions(+), 2 deletions(-) create mode 100644 src/cli/commands/workflow/copy.ts create mode 100644 src/cli/commands/workflow/delete.ts diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 88f066e..22efd6b 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -202,6 +202,8 @@ hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code -- hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史 hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数 hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用 +hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath) +hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览) # 6. OpenAPI 密钥与应用中心 hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏 diff --git a/skills/hose-use/references/workflow.md b/skills/hose-use/references/workflow.md index ecb483c..77618aa 100644 --- a/skills/hose-use/references/workflow.md +++ b/skills/hose-use/references/workflow.md @@ -234,7 +234,29 @@ hose-use workflow publish --- -## 14. 工作流排障与创单排错三大黄金法则(必读) +## 14. 复制与删除工作流 (`workflow copy` / `workflow delete`) + +对标合思 EASO/Piper 网页端“复制流水线”与“删除”功能,严格遵循 `--dry-run` 预览与 `--yes` 安全确认门禁: + +```bash +# 复制已有工作流为新草稿(默认名称加" 副本",首节点为 Webhook 时自动重新分配独立 urlPath 并清理老样本) +hose-use workflow copy --dry-run +hose-use workflow copy --name="发票监控克隆版" --yes + +# 别名支持 cp, clone +hose-use workflow cp --yes + +# 删除指定工作流(不可逆,必须确认) +hose-use workflow delete --dry-run +hose-use workflow delete --yes + +# 别名支持 rm, remove +hose-use workflow rm --yes +``` + +--- + +## 15. 工作流排障与创单排错三大黄金法则(必读) 在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则: diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 1bce82f..565ddea 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1035,4 +1035,266 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { expect(res.stdout).toContain("张三"); expect(res.stdout).toContain("--record="); }); + + it("handles workflow copy: requires pipelineId, confirmation, dry-run, execution, and json mode", async () => { + // 1. Missing pipelineId + const noArgRes = await handleWorkflowCommand( + { + area: "workflow", + action: "copy", + args: [], + options: {}, + raw: ["workflow", "copy"], + }, + mockRuntime + ); + expect(noArgRes.exitCode).toBe(1); + expect(noArgRes.stderr).toContain("用法: hose-use workflow copy"); + + // 2. Missing mutation confirmation + await expect( + handleWorkflowCommand( + { + area: "workflow", + action: "copy", + args: ["pipe_orig"], + options: {}, + raw: ["workflow", "copy", "pipe_orig"], + }, + mockRuntime + ) + ).rejects.toThrow("请先使用 --dry-run"); + + // 3. Dry-run preview + let copiedPayload: any = null; + const mockClient = { + get: (url: string) => { + if (url.includes("api/easo/pipelines/pipe_orig")) { + return { + json: async () => ({ + code: 200, + data: { + id: "pipe_orig", + label: "风险发票实时监控", + platformId: "app_orig", + state: 1, + tasks: [ + { + id: "t1", + name: "webhook_1", + label: "发票数据接入", + type: "webhook", + urlPath: "old-path-uuid", + sampleId: "old-sample-id", + }, + ], + }, + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + put: (url: string, opts: any) => { + if (url.includes("api/easo/pipelines/pipe_orig/copy")) { + copiedPayload = opts.json; + return { + json: async () => ({ + code: 200, + data: { + id: "pipe_cloned_888", + label: opts.json.label, + platformId: opts.json.platformId || "app_orig", + state: 0, + version: "26.10.1", + tasks: opts.json.tasks, + }, + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: mockClient as any, + easoClient: mockClient as any, + corp: mockCorp, + } as any) + ); + spies.push( + spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) + ); + + const dryRunRes = await handleWorkflowCommand( + { + area: "workflow", + action: "copy", + args: ["pipe_orig"], + options: { "dry-run": true }, + raw: ["workflow", "copy", "pipe_orig", "--dry-run"], + }, + mockRuntime + ); + expect(dryRunRes.exitCode).toBe(0); + expect(dryRunRes.stdout).toContain("[DRY-RUN]"); + expect(dryRunRes.stdout).toContain("pipe_orig"); + expect(dryRunRes.stdout).toContain("风险发票实时监控 副本"); + expect(copiedPayload).toBeNull(); + + // 4. Confirmed execution with custom name and platform + const copyRes = await handleWorkflowCommand( + { + area: "workflow", + action: "copy", + args: ["pipe_orig"], + options: { name: "发票监控克隆版", "platform-id": "app_custom", yes: true }, + raw: ["workflow", "copy", "pipe_orig", "--name=发票监控克隆版", "--platform-id=app_custom", "--yes"], + }, + mockRuntime + ); + expect(copyRes.exitCode).toBe(0); + expect(copyRes.stdout).toContain("工作流复制成功"); + expect(copyRes.stdout).toContain("pipe_cloned_888"); + expect(copyRes.stdout).toContain("发票监控克隆版"); + expect(copyRes.stdout).toContain("草稿未发布"); + + // Verify webhook payload transformation + expect(copiedPayload).not.toBeNull(); + expect(copiedPayload.label).toBe("发票监控克隆版"); + expect(copiedPayload.platformId).toBe("app_custom"); + expect(copiedPayload.tasks[0].urlPath).not.toBe("old-path-uuid"); + expect(copiedPayload.tasks[0].sampleId).toBeUndefined(); + + // 5. JSON mode via alias "cp" + const jsonRes = await handleWorkflowCommand( + { + area: "workflow", + action: "cp", + args: ["pipe_orig"], + options: { yes: true }, + raw: ["workflow", "cp", "pipe_orig", "--yes"], + }, + { ...mockRuntime, jsonMode: true } + ); + expect(jsonRes.exitCode).toBe(0); + const parsedJson = JSON.parse(jsonRes.stdout); + expect(parsedJson.id).toBe("pipe_cloned_888"); + expect(parsedJson.state).toBe(0); + }); + + it("handles workflow delete: requires pipelineId, confirmation, dry-run, execution, and json mode", async () => { + // 1. Missing pipelineId + const noArgRes = await handleWorkflowCommand( + { + area: "workflow", + action: "delete", + args: [], + options: {}, + raw: ["workflow", "delete"], + }, + mockRuntime + ); + expect(noArgRes.exitCode).toBe(1); + expect(noArgRes.stderr).toContain("用法: hose-use workflow delete"); + + // 2. Missing mutation confirmation + await expect( + handleWorkflowCommand( + { + area: "workflow", + action: "delete", + args: ["pipe_del_999"], + options: {}, + raw: ["workflow", "delete", "pipe_del_999"], + }, + mockRuntime + ) + ).rejects.toThrow("请先使用 --dry-run"); + + let deletedUrl: string | null = null; + const mockClient = { + get: (url: string) => { + if (url.includes("api/easo/pipelines/pipe_del_999")) { + return { + json: async () => ({ + code: 200, + data: { + id: "pipe_del_999", + label: "待删除工作流", + state: 0, + }, + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + delete: (url: string) => { + deletedUrl = url; + return { + text: async () => "", + }; + }, + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: mockClient as any, + easoClient: mockClient as any, + corp: mockCorp, + } as any) + ); + spies.push( + spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) + ); + + // 3. Dry-run preview + const dryRunRes = await handleWorkflowCommand( + { + area: "workflow", + action: "delete", + args: ["pipe_del_999"], + options: { "dry-run": true }, + raw: ["workflow", "delete", "pipe_del_999", "--dry-run"], + }, + mockRuntime + ); + expect(dryRunRes.exitCode).toBe(0); + expect(dryRunRes.stdout).toContain("[DRY-RUN]"); + expect(dryRunRes.stdout).toContain("pipe_del_999"); + expect(dryRunRes.stdout).toContain("待删除工作流"); + expect(deletedUrl).toBeNull(); + + // 4. Confirmed execution via alias "rm" + const delRes = await handleWorkflowCommand( + { + area: "workflow", + action: "rm", + args: ["pipe_del_999"], + options: { yes: true }, + raw: ["workflow", "rm", "pipe_del_999", "--yes"], + }, + mockRuntime + ); + expect(delRes.exitCode).toBe(0); + expect(delRes.stdout).toContain("pipe_del_999"); + expect(delRes.stdout).toContain("已成功删除"); + expect(deletedUrl as string | null).toBe("api/easo/pipelines/pipe_del_999"); + + // 5. JSON mode via alias "remove" + const jsonRes = await handleWorkflowCommand( + { + area: "workflow", + action: "remove", + args: ["pipe_del_999"], + options: { yes: true }, + raw: ["workflow", "remove", "pipe_del_999", "--yes"], + }, + { ...mockRuntime, jsonMode: true } + ); + expect(jsonRes.exitCode).toBe(0); + const parsedJson = JSON.parse(jsonRes.stdout); + expect(parsedJson.success).toBe(true); + expect(parsedJson.pipelineId).toBe("pipe_del_999"); + }); }); diff --git a/src/cli/commands/workflow/copy.ts b/src/cli/commands/workflow/copy.ts new file mode 100644 index 0000000..3444f90 --- /dev/null +++ b/src/cli/commands/workflow/copy.ts @@ -0,0 +1,96 @@ +import { copyWorkflow, getWorkflowDetail } from "../../../domains/platform/services.js"; +import { stringOption } from "../../parser.js"; +import { printJson, printKeyValue } from "../../printer.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { createWorkflowDetailClient } from "./shared.js"; + +export async function handleCopy( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "source"]); + const targetName = stringOption(parsed.options, ["name", "label", "targetName"]); + const targetPlatformId = stringOption(parsed.options, ["platform-id", "platformId", "targetPlatformId"]); + + if (!pipelineId) { + return { + stdout: "", + stderr: [ + "用法: hose-use workflow copy [选项]", + "", + "选项:", + " --name=<名称> 指定新工作流名称 (默认原名称加' 副本')", + " --platform-id=<应用ID> 指定目标自建应用 (默认原自建应用)", + " --dry-run 预览复制操作,不实际创建", + " --yes 确认执行复制", + "", + "别名: cp, clone", + "示例: hose-use workflow copy 896398895352487950 --name='发票风险监控-副本' --yes", + ].join("\n") + "\n", + exitCode: 1, + }; + } + + requireMutationConfirmation( + parsed, + runtime, + "复制工作流", + `hose-use workflow copy ${pipelineId}${targetName ? ` --name="${targetName}"` : ""} --yes` + ); + + const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + + if (isDryRun(parsed, runtime)) { + const detail = await getWorkflowDetail(client, pipelineId); + return mutationPreview(parsed, runtime, "复制工作流", pipelineId, { + sourceId: pipelineId, + sourceName: detail.label, + targetName: targetName || (detail.label.includes("副本") ? detail.label : `${detail.label} 副本`), + targetPlatformId: targetPlatformId || detail.platformId, + triggerType: detail.tasks?.[0]?.type || "unknown", + tasksCount: detail.tasks?.length || 0, + initialState: 0, + }); + } + + const result = await copyWorkflow(client, pipelineId, { + label: targetName, + platformId: targetPlatformId, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson(result, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const triggerNode = result.tasks?.[0]; + const triggerSummary = triggerNode ? `${triggerNode.label || triggerNode.name} (${triggerNode.type})` : "-"; + + const out = [ + `✨ 工作流复制成功!新工作流已生成为草稿状态 (state = 0):`, + printKeyValue({ + "新工作流 ID (pipelineId)": result.id, + "新工作流名称": result.label, + "自建应用 ID (platformId)": result.platformId || "-", + "首节点触发器": triggerSummary, + "节点总数": String(result.tasks?.length || 0), + "版本号": result.version || "26.10.1", + "当前状态": "⚪ 草稿未发布 (停用中)", + }), + "", + "下一步操作建议:", + ` 查看明细: hose-use workflow get ${result.id}`, + ` 测试执行: hose-use workflow test ${result.id}`, + ` 发布上线: hose-use workflow publish ${result.id} --yes`, + ].join("\n"); + + return { + stdout: `${out}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/workflow/delete.ts b/src/cli/commands/workflow/delete.ts new file mode 100644 index 0000000..7c7d034 --- /dev/null +++ b/src/cli/commands/workflow/delete.ts @@ -0,0 +1,64 @@ +import { deleteWorkflow, getWorkflowDetail } from "../../../domains/platform/services.js"; +import { stringOption } from "../../parser.js"; +import { printJson } from "../../printer.js"; +import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { createWorkflowDetailClient } from "./shared.js"; + +export async function handleDelete( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); + + if (!pipelineId) { + return { + stdout: "", + stderr: [ + "用法: hose-use workflow delete [选项]", + "", + "选项:", + " --dry-run 预览删除操作,不实际删除", + " --yes 确认执行删除", + "", + "别名: rm, remove", + "示例: hose-use workflow delete 898588496146063385 --yes", + ].join("\n") + "\n", + exitCode: 1, + }; + } + + requireMutationConfirmation( + parsed, + runtime, + "删除工作流", + `hose-use workflow delete ${pipelineId} --yes` + ); + + const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + + if (isDryRun(parsed, runtime)) { + const detail = await getWorkflowDetail(client, pipelineId).catch(() => null); + return mutationPreview(parsed, runtime, "删除工作流", pipelineId, { + pipelineId, + name: detail?.label || "未知流程", + state: detail?.state === 1 ? "🟢 启用中" : "⚪ 停用中", + }); + } + + await deleteWorkflow(client, pipelineId); + + if (runtime.jsonMode) { + return { + stdout: printJson({ success: true, pipelineId }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `🗑️ 工作流 [${pipelineId}] 已成功删除。\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/workflow/index.ts b/src/cli/commands/workflow/index.ts index b232fe0..eeecdb1 100644 --- a/src/cli/commands/workflow/index.ts +++ b/src/cli/commands/workflow/index.ts @@ -8,6 +8,8 @@ import { handleCheck } from "./check.js"; import { handleAnalyze } from "./analyze.js"; import { handleWorkflowDiff, handleWorkflowDiffJob } from "./diff.js"; import { handleWorkflowTest } from "./test.js"; +import { handleCopy } from "./copy.js"; +import { handleDelete } from "./delete.js"; export async function handleWorkflowCommand( parsed: CliParsedArgs, @@ -74,10 +76,18 @@ export async function handleWorkflowCommand( case "debug": case "run-test": return handleWorkflowTest(parsed, runtime); + case "copy": + case "cp": + case "clone": + return handleCopy(parsed, runtime); + case "delete": + case "rm": + case "remove": + return handleDelete(parsed, runtime); default: return { stdout: "", - stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, debug\n`, + stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, delete\n`, exitCode: 1, }; } diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index 72ec63c..64ac47a 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -24,6 +24,8 @@ hose-use workflow diff [--pipelineId=] hose-use workflow diff-job [--json] hose-use workflow test [--flow=<单号>] [--record=] [--body='{...}'] [--dry-run|--yes] hose-use workflow debug --flow=<单号> --yes +hose-use workflow copy [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes] +hose-use workflow delete [--dry-run|--yes] ``` ## 触发器分类与调测路径分支 (Path Branching) diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index 7b6ee0d..e5332ef 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -132,6 +132,36 @@ export async function updateWorkflow( return unwrap(response, WorkflowDetailSchema); } +export async function copyWorkflow( + client: KyInstance, + pipelineId: string, + workflow: import("./types.js").WorkflowDetail +): Promise { + const response = await client.put(`api/easo/pipelines/${pipelineId}/copy`, { + json: workflow, + }); + return unwrap(response, WorkflowDetailSchema); +} + +export async function createWorkflow( + client: KyInstance, + workflow: Record +): Promise { + const response = await client.post("api/easo/pipelines", { + json: workflow, + }); + return unwrap(response, WorkflowDetailSchema); +} + +export async function deleteWorkflow( + client: KyInstance, + pipelineId: string +): Promise { + const response = await client.delete(`api/easo/pipelines/${pipelineId}`); + await response.text().catch(() => ""); + return true; +} + export async function listWorkflowSnapshots( client: KyInstance, pipelineId: string, diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index a67e480..c05aa8a 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -50,6 +50,37 @@ export function updateWorkflow(...args: Parameters) { return api.updateWorkflow(...args); } +export async function copyWorkflow( + client: import("ky").KyInstance, + pipelineId: string, + options: { label?: string; platformId?: string } = {} +): Promise { + const detail = await api.getWorkflowDetail(client, pipelineId); + const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; + if (options.label) { + cloned.label = options.label; + } else if (!cloned.label.includes("副本")) { + cloned.label = `${cloned.label} 副本`; + } + if (options.platformId) { + cloned.platformId = options.platformId; + } + // 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本 + if (cloned.tasks?.[0]?.type === "webhook") { + (cloned.tasks[0] as any).urlPath = crypto.randomUUID(); + delete (cloned.tasks[0] as any).sampleId; + } + return api.copyWorkflow(client, pipelineId, cloned); +} + +export function createWorkflow(...args: Parameters) { + return api.createWorkflow(...args); +} + +export function deleteWorkflow(...args: Parameters) { + return api.deleteWorkflow(...args); +} + export function listWorkflowSnapshots(...args: Parameters) { return api.listWorkflowSnapshots(...args); }