diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index dd0cd26..d9e11b9 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -220,4 +220,275 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { expect(notFoundRes.exitCode).toBe(1); expect(notFoundRes.stderr).toContain("未在 Job [job_single] 的执行树中找到匹配 \"不存在的节点\" 的节点"); }); + + it("handles workflow diff comparing code and node changes", async () => { + const snap1 = { + id: "snap_v1", + pipelineId: "pipe_1", + version: "1.0.1", + updateTime: "2026-10-13 14:00:00", + staffName: "张三", + tasks: [ + { + name: "fetch_contract", + type: "ekuaibao-datalink-filter", + displayName: "获取合同台账", + groupName: "action", + orderIndex: 0, + levelIndex: [0], + status: "ENABLE", + combineFilters: { condition: "AND", filters: [{ key: "state", compare: "EQUAL", value: "OPEN" }] }, + }, + { + name: "mvel_calc", + type: "code", + displayName: "MVEL计算节点", + groupName: "action", + orderIndex: 1, + levelIndex: [1], + status: "ENABLE", + code: "double dailyRate = 0.05;\nreturn pvTotal * dailyRate;", + }, + ], + }; + + const snap2 = { + id: "snap_v2", + pipelineId: "pipe_1", + version: "1.0.2", + updateTime: "2026-10-14 09:30:00", + staffName: "李四", + tasks: [ + { + name: "fetch_contract", + type: "ekuaibao-datalink-filter", + displayName: "获取合同台账", + groupName: "action", + orderIndex: 0, + levelIndex: [0], + status: "ENABLE", + combineFilters: { condition: "AND", filters: [{ key: "state", compare: "EQUAL", value: "APPROVING" }] }, + }, + { + name: "mvel_calc", + type: "code", + displayName: "MVEL计算节点", + groupName: "action", + orderIndex: 1, + levelIndex: [1], + status: "ENABLE", + code: "double dailyRate = 0.05;\nif (pvTotal <= 0) throw new RuntimeException('金额非法');\nreturn pvTotal * dailyRate;", + }, + { + name: "notify_audit", + type: "webhook", + displayName: "审计通知", + groupName: "action", + orderIndex: 2, + levelIndex: [2], + status: "ENABLE", + }, + ], + }; + + const mockPiperClient = { + get: (url: string) => { + let payload: any = {}; + if (url.includes("snap_v1")) payload = snap1; + else if (url.includes("snap_v2")) payload = snap2; + return new Response(JSON.stringify({ code: 200, data: payload }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }) }, + easoClient: mockPiperClient, + } as any) + ); + spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any)); + + // 1. 文本输出模式 + const res = await handleWorkflowCommand( + { + area: "workflow", + action: "diff", + args: ["snap_v1", "snap_v2"], + options: {}, + raw: ["workflow", "diff", "snap_v1", "snap_v2"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("工作流快照比对 [1.0.1 -> 1.0.2]"); + expect(res.stdout).toContain("新增节点 (1 个)"); + expect(res.stdout).toContain("notify_audit"); + expect(res.stdout).toContain("mvel_calc"); + expect(res.stdout).toContain("金额非法"); + expect(res.stdout).toContain("过滤/触发条件变动"); + + // 2. JSON 模式 + const jsonRes = await handleWorkflowCommand( + { + area: "workflow", + action: "diff", + args: ["snap_v1", "snap_v2"], + options: { json: true }, + raw: ["workflow", "diff", "snap_v1", "snap_v2", "--json"], + }, + { ...mockRuntime, jsonMode: true } + ); + + expect(jsonRes.exitCode).toBe(0); + const parsed = JSON.parse(jsonRes.stdout); + expect(parsed.addedTasks).toContain("notify_audit"); + expect(parsed.modifiedTasks.find((t: any) => t.taskName === "mvel_calc")).toBeDefined(); + + // 3. 缺少参数 + const errRes = await handleWorkflowCommand( + { + area: "workflow", + action: "diff", + args: ["snap_v1"], + options: {}, + raw: ["workflow", "diff", "snap_v1"], + }, + mockRuntime + ); + expect(errRes.exitCode).toBe(1); + expect(errRes.stderr).toContain("用法: hose-use workflow diff"); + }); + + it("handles workflow diff-job comparing execution branch and error divergence", async () => { + const jobA = { + id: "job_success", + pipelineId: "pipe_1", + state: "COMPLETED", + startTime: "2026-10-14 10:00:00", + durationTime: 450, + hasError: false, + errorTaskCount: 0, + }; + + const treeA = [ + { + id: "ex_1", + name: "get_bill", + displayName: "获取单据", + type: "flow-detail", + status: "COMPLETED", + executionTime: 120, + inputs: { billCode: "ZJ-20261014-001" }, + outputs: { state: "APPROVING" }, + }, + { + id: "ex_2", + name: "auto_approve", + displayName: "自动审批", + type: "flow-approval", + status: "COMPLETED", + executionTime: 330, + inputs: { action: "agree" }, + outputs: { code: 200, success: true }, + }, + ]; + + const jobB = { + id: "job_failed", + pipelineId: "pipe_1", + state: "FAILED", + startTime: "2026-10-14 11:00:00", + durationTime: 320, + hasError: true, + errorTaskCount: 1, + }; + + const treeB = [ + { + id: "ex_1b", + name: "get_bill", + displayName: "获取单据", + type: "flow-detail", + status: "COMPLETED", + executionTime: 100, + inputs: { billCode: "ZJ-20261014-002" }, + outputs: { state: "PAYING" }, + }, + { + id: "ex_2b", + name: "auto_approve", + displayName: "自动审批", + type: "flow-approval", + status: "FAILED", + executionTime: 220, + error: { message: "400: 无待办审批事项" }, + inputs: { action: "agree" }, + outputs: { code: 400, message: "无待办审批事项" }, + }, + ]; + + const mockPiperClient = { + get: (url: string) => { + let payload: any = {}; + if (url.includes("job_success/execution")) payload = treeA; + else if (url.includes("job_failed/execution")) payload = treeB; + else if (url.includes("job_success")) payload = jobA; + else if (url.includes("job_failed")) payload = jobB; + return new Response(JSON.stringify({ code: 200, data: payload }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }) }, + easoClient: mockPiperClient, + } as any) + ); + spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any)); + + // 1. 文本输出模式 + const res = await handleWorkflowCommand( + { + area: "workflow", + action: "diff-job", + args: ["job_success", "job_failed"], + options: {}, + raw: ["workflow", "diff-job", "job_success", "job_failed"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("工作流 Job 执行比对 [job_success vs job_failed]"); + expect(res.stdout).toContain("auto_approve"); + expect(res.stdout).toContain("400: 无待办审批事项"); + expect(res.stdout).toContain("ZJ-20261014-001"); + expect(res.stdout).toContain("ZJ-20261014-002"); + + // 2. JSON 模式 + const jsonRes = await handleWorkflowCommand( + { + area: "workflow", + action: "diff-job", + args: ["job_success", "job_failed"], + options: { json: true }, + raw: ["workflow", "diff-job", "job_success", "job_failed", "--json"], + }, + { ...mockRuntime, jsonMode: true } + ); + + expect(jsonRes.exitCode).toBe(0); + const parsed = JSON.parse(jsonRes.stdout); + expect(parsed.jobA.id).toBe("job_success"); + expect(parsed.jobB.id).toBe("job_failed"); + expect(parsed.summary.statusDiffCount).toBe(1); + expect(parsed.nodes.find((n: any) => n.taskName === "auto_approve").statusB).toBe("FAILED"); + }); }); diff --git a/src/cli/commands/workflow/diff.ts b/src/cli/commands/workflow/diff.ts new file mode 100644 index 0000000..f4a4e74 --- /dev/null +++ b/src/cli/commands/workflow/diff.ts @@ -0,0 +1,197 @@ +import { + diffWorkflowJobs, + diffWorkflowSnapshots, + getJob, + getJobExecutionTree, + getWorkflowSnapshot, +} from "../../../domains/platform/services.js"; +import { stringOption } from "../../parser.js"; +import { printJson, printTable } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { createJobPiperClient } from "./shared.js"; + +export async function handleWorkflowDiff( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const snapIdA = parsed.args[0] || stringOption(parsed.options, ["from", "a", "snapshot1", "snapshotA"]); + const snapIdB = parsed.args[1] || stringOption(parsed.options, ["to", "b", "snapshot2", "snapshotB"]); + + if (!snapIdA || !snapIdB) { + return { + stdout: "", + stderr: "用法: hose-use workflow diff [--pipelineId=]\n", + exitCode: 1, + }; + } + + const client = await createJobPiperClient(parsed, runtime); + const pipelineId = stringOption(parsed.options, ["pipelineId", "pipeline", "id"]); + + const [snapA, snapB] = await Promise.all([ + getWorkflowSnapshot(client, snapIdA, pipelineId), + getWorkflowSnapshot(client, snapIdB, pipelineId), + ]); + + const diff = diffWorkflowSnapshots(snapA, snapB); + + if (runtime.jsonMode) { + return { + stdout: printJson(diff, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const lines: string[] = [ + `====== 工作流快照比对 [${diff.snapshotA.version || snapIdA} -> ${diff.snapshotB.version || snapIdB}] ======`, + ` 快照 A : ${snapIdA} (版本: ${diff.snapshotA.version || "-"}) 更新人: ${diff.snapshotA.staffName || "-"} 时间: ${diff.snapshotA.updateTime || "-"}`, + ` 快照 B : ${snapIdB} (版本: ${diff.snapshotB.version || "-"}) 更新人: ${diff.snapshotB.staffName || "-"} 时间: ${diff.snapshotB.updateTime || "-"}`, + ` 变更统计: ${diff.summary.changedCount} 个节点有变动 (节点总数: A=${diff.summary.totalA}, B=${diff.summary.totalB})`, + "", + ]; + + if (diff.addedTasks.length > 0) { + lines.push(`── ➕ 新增节点 (${diff.addedTasks.length} 个) ──`); + lines.push(` ${diff.addedTasks.join(", ")}`); + lines.push(""); + } + + if (diff.removedTasks.length > 0) { + lines.push(`── ➖ 删除节点 (${diff.removedTasks.length} 个) ──`); + lines.push(` ${diff.removedTasks.join(", ")}`); + lines.push(""); + } + + if (diff.modifiedTasks.length === 0) { + lines.push("✅ 两个快照间未检测到任何节点或代码变更。"); + } else { + lines.push(`── 📝 节点变更明细 (${diff.modifiedTasks.length} 个) ──`); + for (const task of diff.modifiedTasks) { + lines.push(`\n• 节点 [${task.taskName}] (${task.displayName || task.type}) [${task.changeType}]:`); + if (task.codeDiff?.unifiedDiff) { + lines.push(` --- 脚本代码变动 ---`); + lines.push(task.codeDiff.unifiedDiff.split("\n").map((l) => ` ${l}`).join("\n")); + } + if (task.filterDiff) { + lines.push(` --- 过滤/触发条件变动 ---`); + lines.push(` 原条件: ${JSON.stringify(task.filterDiff.from) || "(空)"}`); + lines.push(` 现条件: ${JSON.stringify(task.filterDiff.to) || "(空)"}`); + } + if (task.configChanges.length > 0) { + lines.push(` --- 属性配置变动 ---`); + for (const c of task.configChanges) { + lines.push(` • ${c.field}: ${JSON.stringify(c.from)} -> ${JSON.stringify(c.to)}`); + } + } + } + } + + return { + stdout: lines.join("\n") + "\n", + stderr: "", + exitCode: 0, + }; +} + +export async function handleWorkflowDiffJob( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const jobIdA = parsed.args[0] || stringOption(parsed.options, ["from", "a", "job1", "jobA"]); + const jobIdB = parsed.args[1] || stringOption(parsed.options, ["to", "b", "job2", "jobB"]); + + if (!jobIdA || !jobIdB) { + return { + stdout: "", + stderr: "用法: hose-use workflow diff-job \n", + exitCode: 1, + }; + } + + const client = await createJobPiperClient(parsed, runtime); + + const [jobA, treeA, jobB, treeB] = await Promise.all([ + getJob(client, jobIdA), + getJobExecutionTree(client, jobIdA), + getJob(client, jobIdB), + getJobExecutionTree(client, jobIdB), + ]); + + const diff = diffWorkflowJobs(jobA, treeA, jobB, treeB); + + if (runtime.jsonMode) { + return { + stdout: printJson(diff, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const summaryRows = [ + ["Job ID", diff.jobA.id, diff.jobB.id], + ["运行状态", String(diff.jobA.state ?? "-"), String(diff.jobB.state ?? "-")], + ["开始时间", diff.jobA.startTime || "-", diff.jobB.startTime || "-"], + ["执行耗时(ms)", String(diff.jobA.durationTime ?? "-"), String(diff.jobB.durationTime ?? "-")], + ["执行节点数", String(diff.summary.totalNodesA), String(diff.summary.totalNodesB)], + ["错误标记 (hasError)", diff.jobA.hasError ? "⚠️ 包含错误" : "正常", diff.jobB.hasError ? "⚠️ 包含错误" : "正常"], + ]; + + const lines: string[] = [ + `====== 工作流 Job 执行比对 [${jobIdA} vs ${jobIdB}] ======`, + printTable(["指标项", `Job A (${jobIdA})`, `Job B (${jobIdB})`], summaryRows), + "", + `── 🔀 分支走向与节点执行状态比对 (差异节点: ${diff.summary.divergedNodesCount} 个) ──`, + ]; + + if (diff.summary.divergedNodesCount === 0) { + lines.push(" ✅ 两个 Job 执行链路完全一致,各节点状态与入参相同。"); + } else { + const divergedNodes = diff.nodes.filter((n) => n.diverged); + const nodeRows = divergedNodes.map((n) => [ + n.taskName, + n.displayName || "-", + n.type || "-", + n.statusA || "(未执行)", + n.statusB || "(未执行)", + n.statusA !== n.statusB ? "⚠️ 状态不一致" : "一致", + n.errorB ? "❌ B报错" : n.errorA ? "⚠️ A报错" : "-", + ]); + lines.push( + printTable( + ["节点名称", "显示名称", "类型", "Job A 状态", "Job B 状态", "状态差异", "错误差异"], + nodeRows + ) + ); + + lines.push("\n── 🔍 差异节点入参/出参与报错透视 ──"); + for (const n of divergedNodes) { + lines.push(`\n• 节点 [${n.taskName}] (${n.displayName || n.type || "-"}):`); + if (n.statusA !== n.statusB) { + lines.push(` 状态对比: ${n.statusA || "(未执行)"} -> ${n.statusB || "(未执行)"}`); + } + if (n.errorB || n.errorA) { + if (n.errorA) lines.push(` Job A 报错: ${JSON.stringify(n.errorA)}`); + if (n.errorB) lines.push(` Job B 报错: ${JSON.stringify(n.errorB)}`); + } + if (n.inputsDiff && n.inputsDiff.length > 0) { + lines.push(` 入参差异 (inputs):`); + for (const diffItem of n.inputsDiff) { + lines.push(` ~ ${diffItem.field}: ${JSON.stringify(diffItem.from)} -> ${JSON.stringify(diffItem.to)}`); + } + } + if (n.outputsDiff && n.outputsDiff.length > 0) { + lines.push(` 出参差异 (outputs):`); + for (const diffItem of n.outputsDiff) { + lines.push(` ~ ${diffItem.field}: ${JSON.stringify(diffItem.from)} -> ${JSON.stringify(diffItem.to)}`); + } + } + } + } + + return { + stdout: lines.join("\n") + "\n", + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/workflow/index.ts b/src/cli/commands/workflow/index.ts index a01ac42..1157b2a 100644 --- a/src/cli/commands/workflow/index.ts +++ b/src/cli/commands/workflow/index.ts @@ -6,6 +6,7 @@ import { handleHistory, handleLogs } from "./history.js"; import { handleJob } from "./job.js"; import { handleCheck } from "./check.js"; import { handleAnalyze } from "./analyze.js"; +import { handleWorkflowDiff, handleWorkflowDiffJob } from "./diff.js"; export async function handleWorkflowCommand( parsed: CliParsedArgs, @@ -59,10 +60,19 @@ export async function handleWorkflowCommand( case "analyze": case "analyse": return handleAnalyze(parsed, runtime); + case "diff": + case "diff-snapshot": + case "diff-snapshots": + case "compare": + return handleWorkflowDiff(parsed, runtime); + case "diff-job": + case "diff-jobs": + case "compare-job": + return handleWorkflowDiffJob(parsed, runtime); default: return { stdout: "", - stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, check\n`, + stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check\n`, exitCode: 1, }; } diff --git a/src/cli/commands/workflow/shared.ts b/src/cli/commands/workflow/shared.ts index 160d854..9bd5ddb 100644 --- a/src/cli/commands/workflow/shared.ts +++ b/src/cli/commands/workflow/shared.ts @@ -25,3 +25,27 @@ export async function createWorkflowDetailClient( clients, }; } + +export async function createJobPiperClient( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise>> { + const corp = runtime.selectedCorp!; + const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS); + if (explicit) { + return createPiperClientForCorp(corp, explicit); + } + const clients = await createClientsForCorp(corp); + try { + const corpId = corp.corpId || corp.id; + const { listPlatforms } = await import("../../../domains/platform/services.js"); + const platforms = await listPlatforms(clients.ekbClient, corpId); + const firstActive = platforms.find((p) => p.active) ?? platforms[0]; + if (firstActive?.id) { + return await createPiperClientForCorp(corp, firstActive.id); + } + } catch { + // Fall back to default easoClient + } + return clients.easoClient; +} diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index 08819b8..53db368 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -19,7 +19,9 @@ hose-use workflow list [--platform-id=|--app-id=] hose-use workflow get hose-use workflow analyze [--json] hose-use workflow logs [--has-error] [--state=FAILED] -hose-use workflow job [--failed] [--parent=] [--logs=] +hose-use workflow job [--failed] [--node=] [--verbose] +hose-use workflow diff [--pipelineId=] +hose-use workflow diff-job [--json] ``` ## 详细文档 diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index c2ea106..fda548d 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -7,6 +7,7 @@ import { WorkflowStatsSchema, WorkflowChargeSchema, WorkflowDetailSchema, + WorkflowSnapshotSchema, WorkflowSnapshotPageSchema, WorkflowLogPageSchema, WorkflowJobSchema, @@ -140,6 +141,23 @@ export async function listWorkflowSnapshots( return unwrap(response, WorkflowSnapshotPageSchema); } +export async function getWorkflowSnapshot( + client: KyInstance, + snapshotId: string, + pipelineId?: string +): Promise { + try { + const response = await client.get(`api/easo/snapshots/${snapshotId}`); + return unwrap(response, WorkflowSnapshotSchema); + } catch (err) { + if (pipelineId) { + const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots/${snapshotId}`); + return unwrap(response, WorkflowSnapshotSchema); + } + throw err; + } +} + export async function listWorkflowLogs( client: KyInstance, pipelineId: string, diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index 3ab0566..2bc2987 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -9,6 +9,12 @@ import { WorkflowTaskExecution, WorkflowWithMatches, TaskMatch, + WorkflowSnapshot, + WorkflowSnapshotDiff, + TaskConfigDiff, + WorkflowJobDetail, + WorkflowJobDiff, + NodeExecutionDiff, } from "./types.js"; export interface PlatformClients { @@ -45,6 +51,10 @@ export function listWorkflowSnapshots(...args: Parameters) { + return api.getWorkflowSnapshot(...args); +} + export function listWorkflowLogs(...args: Parameters) { return api.listWorkflowLogs(...args); } @@ -320,3 +330,318 @@ export function findExecutionNode( n.displayName?.toLowerCase().includes(q) ); } + +// ── 工作流快照与 Job 差异比对核心算法 ────────────────────────────────────────── + +/** + * 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点) + */ +export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] { + if (!tasks || !Array.isArray(tasks)) return []; + const result: WorkflowTask[] = []; + + function walk(list: WorkflowTask[]) { + for (const t of list) { + if (!t) continue; + result.push(t); + if (Array.isArray(t.tasks) && t.tasks.length > 0) { + walk(t.tasks); + } + } + } + + walk(tasks); + return result; +} + +/** + * 快速生成标准 Unified Diff 文本 + */ +export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string { + if (a === b) return ""; + const linesA = a.split(/\r?\n/); + const linesB = b.split(/\r?\n/); + const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`]; + + let start = 0; + while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) { + start++; + } + let endA = linesA.length - 1; + let endB = linesB.length - 1; + while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) { + endA--; + endB--; + } + + const hunkStart = Math.max(0, start - 2); + const hunkEndA = Math.min(linesA.length, endA + 3); + const hunkEndB = Math.min(linesB.length, endB + 3); + + output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`); + for (let i = hunkStart; i < start; i++) { + output.push(` ${linesA[i]}`); + } + for (let i = start; i <= endA; i++) { + output.push(`- ${linesA[i]}`); + } + for (let i = start; i <= endB; i++) { + output.push(`+ ${linesB[i]}`); + } + for (let i = endA + 1; i < hunkEndA; i++) { + output.push(` ${linesA[i]}`); + } + return output.join("\n"); +} + +/** + * 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异 + */ +export function diffWorkflowSnapshots( + snapshotA: WorkflowSnapshot, + snapshotB: WorkflowSnapshot +): WorkflowSnapshotDiff { + const tasksA = flattenWorkflowTasks(snapshotA.tasks); + const tasksB = flattenWorkflowTasks(snapshotB.tasks); + + const mapA = new Map(); + for (const t of tasksA) { + if (t?.name) mapA.set(t.name, t); + } + + const mapB = new Map(); + for (const t of tasksB) { + if (t?.name) mapB.set(t.name, t); + } + + const addedTasks: string[] = []; + const removedTasks: string[] = []; + const modifiedTasks: TaskConfigDiff[] = []; + + // 1. 查找新增节点 + for (const [name, tB] of mapB) { + if (!mapA.has(name)) { + addedTasks.push(name); + modifiedTasks.push({ + taskName: name, + displayName: tB.displayName || tB.label, + type: tB.type, + changeType: "ADDED", + configChanges: [], + }); + } + } + + // 2. 查找删除与修改节点 + for (const [name, tA] of mapA) { + const tB = mapB.get(name); + if (!tB) { + removedTasks.push(name); + modifiedTasks.push({ + taskName: name, + displayName: tA.displayName || tA.label, + type: tA.type, + changeType: "REMOVED", + configChanges: [], + }); + continue; + } + + // 两者均存在,深度比较配置与代码 + const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = []; + let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined; + let filterDiff: { from?: unknown; to?: unknown } | undefined; + + // 代码脚本比较 + const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined; + const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined; + if (codeA !== codeB) { + codeDiff = { + from: codeA, + to: codeB, + unifiedDiff: generateTextDiff( + codeA || "", + codeB || "", + `${snapshotA.version || snapshotA.id}`, + `${snapshotB.version || snapshotB.id}` + ), + }; + } + + // 过滤条件比较 (combineFilters / filters) + const filtersA = (tA as any).combineFilters ?? (tA as any).filters; + const filtersB = (tB as any).combineFilters ?? (tB as any).filters; + if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) { + filterDiff = { from: filtersA, to: filtersB }; + } + + // 关键字段变动比较 + const checkFields = [ + "type", + "url", + "method", + "entityId", + "specificationId", + "flowCode", + "formState", + "subType", + "itemType", + "targetType", + "orderMode", + "orderKey", + "batch", + "batchSize", + ]; + for (const f of checkFields) { + const valA = (tA as any)[f]; + const valB = (tB as any)[f]; + if (JSON.stringify(valA) !== JSON.stringify(valB)) { + configChanges.push({ field: f, from: valA, to: valB }); + } + } + + if (codeDiff || filterDiff || configChanges.length > 0) { + modifiedTasks.push({ + taskName: name, + displayName: tB.displayName || tB.label || tA.displayName || tA.label, + type: tB.type || tA.type, + changeType: "MODIFIED", + codeDiff, + filterDiff, + configChanges, + }); + } + } + + return { + snapshotA: { + id: snapshotA.id, + version: snapshotA.version, + updateTime: snapshotA.updateTime, + staffName: snapshotA.staffName || snapshotA.staffId || undefined, + }, + snapshotB: { + id: snapshotB.id, + version: snapshotB.version, + updateTime: snapshotB.updateTime, + staffName: snapshotB.staffName || snapshotB.staffId || undefined, + }, + addedTasks, + removedTasks, + modifiedTasks, + summary: { + totalA: tasksA.length, + totalB: tasksB.length, + changedCount: modifiedTasks.length, + }, + }; +} + +/** + * 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息 + */ +export function diffWorkflowJobs( + jobA: WorkflowJobDetail, + treeA: WorkflowTaskExecution[], + jobB: WorkflowJobDetail, + treeB: WorkflowTaskExecution[] +): WorkflowJobDiff { + const flatA = flattenExecutionTree(treeA); + const flatB = flattenExecutionTree(treeB); + + const allNames = Array.from( + new Set([ + ...flatA.map((n) => n.name).filter(Boolean), + ...flatB.map((n) => n.name).filter(Boolean), + ]) + ) as string[]; + + const nodes: NodeExecutionDiff[] = []; + let divergedNodesCount = 0; + let statusDiffCount = 0; + + for (const name of allNames) { + const nodeA = flatA.find((n) => n.name === name); + const nodeB = flatB.find((n) => n.name === name); + + const statusA = nodeA?.status; + const statusB = nodeB?.status; + const isStatusDiff = statusA !== statusB; + if (isStatusDiff) statusDiffCount++; + + // 比较 inputs + const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; + const inA = (nodeA?.inputs as Record) || {}; + const inB = (nodeB?.inputs as Record) || {}; + const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)])); + for (const k of inputKeys) { + if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) { + inputsDiff.push({ field: k, from: inA[k], to: inB[k] }); + } + } + + // 比较 outputs + const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; + const outA = (nodeA?.outputs as Record) || {}; + const outB = (nodeB?.outputs as Record) || {}; + const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)])); + for (const k of outputKeys) { + if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) { + outputsDiff.push({ field: k, from: outA[k], to: outB[k] }); + } + } + + const isDiverged = + !nodeA || + !nodeB || + isStatusDiff || + Boolean(nodeB.error && !nodeA.error) || + inputsDiff.length > 0; + + if (isDiverged) divergedNodesCount++; + + nodes.push({ + taskName: name, + displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined, + type: nodeB?.type || nodeA?.type, + statusA, + statusB, + durationMsA: nodeA?.executionTime, + durationMsB: nodeB?.executionTime, + errorA: nodeA?.error, + errorB: nodeB?.error, + inputsDiff, + outputsDiff, + diverged: isDiverged, + }); + } + + return { + jobA: { + id: jobA.id, + pipelineId: jobA.pipelineId, + state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined, + startTime: jobA.startTime ? String(jobA.startTime) : undefined, + durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined, + hasError: Boolean(jobA.hasError), + errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined, + }, + jobB: { + id: jobB.id, + pipelineId: jobB.pipelineId, + state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined, + startTime: jobB.startTime ? String(jobB.startTime) : undefined, + durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined, + hasError: Boolean(jobB.hasError), + errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined, + }, + nodes, + summary: { + totalNodesA: flatA.length, + totalNodesB: flatB.length, + divergedNodesCount, + statusDiffCount, + }, + }; +} + diff --git a/src/domains/platform/types.ts b/src/domains/platform/types.ts index 696b81e..5b573fa 100644 --- a/src/domains/platform/types.ts +++ b/src/domains/platform/types.ts @@ -507,3 +507,101 @@ export type WorkflowListAllError = z.infer; export type TaskMatch = z.infer; export type WorkflowWithMatches = z.infer; +// ── 工作流快照与 Job 差异比对模型 ────────────────────────────────────────── + +export interface TaskConfigDiff { + taskName: string; + displayName?: string; + type: string; + changeType: "ADDED" | "REMOVED" | "MODIFIED"; + codeDiff?: { + from?: string; + to?: string; + unifiedDiff?: string; + }; + filterDiff?: { + from?: unknown; + to?: unknown; + }; + configChanges: Array<{ + field: string; + from?: unknown; + to?: unknown; + }>; +} + +export interface WorkflowSnapshotDiff { + snapshotA: { + id: string; + version?: string; + updateTime?: string; + staffName?: string; + }; + snapshotB: { + id: string; + version?: string; + updateTime?: string; + staffName?: string; + }; + addedTasks: string[]; + removedTasks: string[]; + modifiedTasks: TaskConfigDiff[]; + summary: { + totalA: number; + totalB: number; + changedCount: number; + }; +} + +export interface NodeExecutionDiff { + taskName: string; + displayName?: string; + type?: string; + statusA?: string; + statusB?: string; + durationMsA?: number; + durationMsB?: number; + errorA?: unknown; + errorB?: unknown; + inputsDiff?: Array<{ + field: string; + from?: unknown; + to?: unknown; + }>; + outputsDiff?: Array<{ + field: string; + from?: unknown; + to?: unknown; + }>; + diverged: boolean; +} + +export interface WorkflowJobDiff { + jobA: { + id: string; + pipelineId?: string; + state?: string | number; + startTime?: string; + durationTime?: number; + hasError?: boolean; + errorCount?: number; + }; + jobB: { + id: string; + pipelineId?: string; + state?: string | number; + startTime?: string; + durationTime?: number; + hasError?: boolean; + errorCount?: number; + }; + nodes: NodeExecutionDiff[]; + summary: { + totalNodesA: number; + totalNodesB: number; + divergedNodesCount: number; + statusDiffCount: number; + }; +} + +