import { extractFailureExecutions, findExecutionNode, flattenExecutionTree, getExecutionLogs, getJob, getJobExecutionLevel, getJobExecutionTree, getJobFailedExecutions, getWorkflowDetail, isTaskExecutionFailed, listPlatforms, explainConditionBranches, } from "../../../domains/platform/services.js"; import type { WorkflowTaskExecution } from "../../../domains/platform/types.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { PLATFORM_ID_OPTION_KEYS, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js"; 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 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; } async function enrichFailedExecutions( client: Awaited>, jobId: string, items: WorkflowTaskExecution[] ): Promise { const parentCache = new Map(); const enriched: WorkflowTaskExecution[] = []; for (const item of items) { if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) { let siblings = parentCache.get(item.parentId); if (!siblings) { try { const level = await getJobExecutionLevel(client, jobId, { parentId: item.parentId, page: 1, pageSize: 100, }); siblings = level.items; } catch { siblings = []; } parentCache.set(item.parentId, siblings); } const matched = siblings.find((s) => s.id === item.id); if (matched) { const itemInputs = item.inputs; const matchedInputs = matched.inputs; const hasItemInputs = Array.isArray(itemInputs) ? itemInputs.length > 0 : Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record).length > 0); const itemOutputs = item.outputs; const matchedOutputs = matched.outputs; const hasItemOutputs = Boolean( itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record).length > 0 ); enriched.push({ ...matched, ...item, name: item.name || matched.name, label: item.label || matched.label, displayName: item.displayName || matched.displayName, type: item.type || matched.type, status: item.status || matched.status, currentLoopPath: item.currentLoopPath || matched.currentLoopPath, levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex, form: item.form ?? matched.form, details: item.details ?? matched.details, inputs: hasItemInputs ? itemInputs : matchedInputs, outputs: hasItemOutputs ? itemOutputs : matchedOutputs, error: item.error ?? matched.error, }); continue; } } enriched.push(item); } return enriched; } export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]); if (!jobId) { return { stdout: "", stderr: "用法: hose-use workflow job [--failed] [--node=] [--verbose] [--parent=] [--logs=]\n", exitCode: 1, }; } const client = await createJobPiperClient(parsed, runtime); const page = numberOption(parsed.options, ["page"]) || 1; const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100; const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]); const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]); const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]); const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]); const verbose = booleanOption(parsed.options, ["verbose", "v"]); const isTimeline = booleanOption(parsed.options, ["timeline", "progress", "steps"]); // 1. --logs= if (logsExecutionId) { const logs = await getExecutionLogs(client, logsExecutionId); if (runtime.jsonMode) { return { stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions), stderr: "", exitCode: 0, }; } const rows = logs.map((log, i) => [ i + 1, String(log.id ?? "-"), String(log.createAt ?? (log as Record).createTime ?? (log as Record).timestamp ?? "-"), String(log.level || "INFO"), String(log.message || JSON.stringify(log)), ]); return { stdout: [ `====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`, rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志", "", ].join("\n"), stderr: "", exitCode: 0, }; } // 2. --parent= if (parentExecutionId) { const levelPage = await getJobExecutionLevel(client, jobId, { parentId: parentExecutionId, page, pageSize, }); if (runtime.jsonMode) { return { stdout: printJson( { jobId, parentId: parentExecutionId, ...levelPage, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const rows = levelPage.items.map((item, idx) => [ idx + 1, item.id, item.name || "-", item.label || item.displayName || "-", item.type || "-", item.status || "-", item.currentLoopPath || "-", item.error?.message || "-", ]); const extraDetails: string[] = []; for (const item of levelPage.items) { if (item.form !== undefined || item.error?.message) { extraDetails.push( `\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──` ); if (item.error?.message) { extraDetails.push(` 错误原因: ${item.error.message}`); } if (item.form !== undefined) { extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`); } if (item.details !== undefined) { extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`); } } } return { stdout: [ `====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`, rows.length ? printTable( ["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"], rows ) : "暂无子节点执行记录", ...extraDetails, "", ].join("\n"), stderr: "", exitCode: 0, }; } // 3. --node= if (nodeQuery) { const tree = await getJobExecutionTree(client, jobId); const matchedNode = findExecutionNode(tree, nodeQuery); if (!matchedNode) { return { stdout: "", stderr: `未在 Job [${jobId}] 的执行树中找到匹配 "${nodeQuery}" 的节点。请核对节点名称或 Execution ID。\n`, exitCode: 1, }; } if (runtime.jsonMode) { return { stdout: printJson({ jobId, node: matchedNode }, runtime.outputOptions), stderr: "", exitCode: 0, }; } const anyNode = matchedNode as any; const inputPayload = anyNode.inputs ?? anyNode.form ?? anyNode.params; const outputPayload = anyNode.outputs ?? anyNode.output ?? anyNode.details; const lines = [ `====== 工作流节点执行详情 [${matchedNode.id}] (Job: ${jobId}) ======`, printKeyValue({ "Execution ID": matchedNode.id, "Parent ID": matchedNode.parentId || "-", "节点标识 (name)": matchedNode.name || "-", "节点名称": matchedNode.displayName || matchedNode.label || "-", "节点类型 (type)": matchedNode.type || "-", "执行状态 (status)": matchedNode.status || anyNode.state || "-", "耗时(ms)": String(matchedNode.executionTime ?? anyNode.durationTime ?? "-"), "开始时间": String(matchedNode.startTime || anyNode.createTime || "-"), "结束时间": String(matchedNode.endTime || "-"), "循环路径": matchedNode.currentLoopPath || "-", ...(matchedNode.error?.message ? { "错误信息": matchedNode.error.message } : {}), }), ]; if (matchedNode.error?.message) { lines.push(""); lines.push("── ❌ 错误堆栈 / 原因 ──"); lines.push(matchedNode.error.message); if (anyNode.error?.stack) { lines.push(anyNode.error.stack); } } if (inputPayload !== undefined) { lines.push(""); lines.push("── 📥 节点入参报文 (inputs / form) ──"); lines.push(typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2)); } if (outputPayload !== undefined) { lines.push(""); lines.push("── 📤 节点出参 / 响应结果 (outputs) ──"); lines.push(typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2)); } lines.push(""); return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0, }; } // 4. --failed if (onlyFailed) { const [job, tree, failedPage] = await Promise.all([ getJob(client, jobId).catch(() => undefined), getJobExecutionTree(client, jobId).catch(() => []), getJobFailedExecutions(client, jobId).catch(() => ({ number: 1, size: 100, totalPages: 0, totalItems: 0, items: [] as WorkflowTaskExecution[], })), ]); const rawFailed = extractFailureExecutions(tree, failedPage.items); const enrichedItems = await enrichFailedExecutions(client, jobId, rawFailed); if (runtime.jsonMode) { return { stdout: printJson( { jobId, job: job ?? null, totalFailed: enrichedItems.length, failedNodes: enrichedItems, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const rows = enrichedItems.map((item: any, idx) => [ idx + 1, item.id, item.parentId || "-", item.name || "-", item.displayName || item.label || item.type || "-", item.status || item.state || "-", String(item.executionTime ?? item.durationTime ?? "-"), item.error?.message || item.errorMessage || item.outputs?.error || "-", ]); const nodeDetailBlocks: string[] = []; const shouldExpand = verbose || enrichedItems.length <= 5; for (const item of enrichedItems) { const anyItem = item as any; const errMsg = item.error?.message || anyItem.errorMessage || anyItem.outputs?.error; const inputPayload = anyItem.inputs ?? anyItem.form ?? anyItem.params; const outputPayload = anyItem.outputs ?? anyItem.output ?? anyItem.details; if (errMsg || inputPayload !== undefined || outputPayload !== undefined) { nodeDetailBlocks.push( `\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | ${item.displayName || item.label || item.type || "-"} | status=${item.status || anyItem.state}) ──` ); if (errMsg) { nodeDetailBlocks.push(` ❌ 错误原因: ${errMsg}`); } if (shouldExpand) { if (inputPayload !== undefined) { const inStr = typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2); nodeDetailBlocks.push(` 📥 节点入参 (inputs/form):\n${inStr.split("\n").map((l: string) => " " + l).join("\n")}`); } if (outputPayload !== undefined) { const outStr = typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2); nodeDetailBlocks.push(` 📤 节点出参 (outputs/details):\n${outStr.split("\n").map((l: string) => " " + l).join("\n")}`); } } else { if (inputPayload !== undefined) { nodeDetailBlocks.push(` 📥 节点入参: [已省略,使用 --verbose 查看完整 JSON]`); } } } } return { stdout: [ `====== Job 异常/失败执行节点透视 (Job: ${jobId}) ======`, job ? printKeyValue({ "Job ID": job.id, "工作流 ID": job.pipelineId, "Job 状态": job.state ?? job.status, "开始时间": job.startTime || "-", "耗时(ms)": String(job.durationTime ?? "-"), "失败节点数": enrichedItems.length, }) : "", "", rows.length ? printTable( ["#", "Execution ID", "Parent ID", "节点标识 (name)", "节点名称/类型", "状态", "耗时(ms)", "错误原因"], rows ) : "✅ 未发现任何异常或报错失败的执行节点", ...nodeDetailBlocks, "", ].filter(Boolean).join("\n"), stderr: "", exitCode: 0, }; } // 4. Default mode: Job overview + top-level tree + failed executions + timeline const [job, tree, failedPage] = await Promise.all([ getJob(client, jobId), getJobExecutionTree(client, jobId), getJobFailedExecutions(client, jobId).catch(() => ({ number: 1, size: 100, totalPages: 0, totalItems: 0, items: [] as WorkflowTaskExecution[], })), ]); const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined); const workflowStateLabel = !workflowDetail ? "未知(无法读取工作流详情)" : workflowDetail.state === 1 ? "🟢 启用中" : workflowDetail.state === 0 ? "⚪ 已停用" : "未知"; const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items); const conditionDiagnoses = explainConditionBranches(tree); const timeline = workflowDetail?.tasks?.map((t: any, idx: number) => { const executed = tree.find((node) => node.name === t.name); let statusText = "⏳ 未执行"; let errorDetail = "-"; if (executed) { if (executed.status === "COMPLETED") statusText = "✅ 已完成"; else if (executed.status === "FAILED") { statusText = "❌ 失败中断"; const msg = (executed.error?.message || "执行失败").replace(/\s+/g, " "); errorDetail = msg.length > 100 ? `${msg.slice(0, 97)}...` : msg; } else if (executed.status === "STARTED" || executed.status === "RUNNING") { statusText = t.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 正在执行中"; } else { statusText = executed.status; } } else { const runningPrior = tree.find((node) => node.status === "STARTED" || node.status === "RUNNING"); const failedPrior = tree.find((node) => node.status === "FAILED"); if (runningPrior) { statusText = "⏳ 等待前序步骤执行完成"; } else if (failedPrior) { statusText = "⏳ 未执行 (因前序步骤中断)"; } } return { index: idx + 1, name: t.name, displayName: t.displayName || t.label || t.name, type: t.type, status: statusText, duration: executed ? String((executed as any).durationTime ?? executed.executionTime ?? "-") : "-", detail: errorDetail, }; }); if (isTimeline && timeline && timeline.length > 0) { if (runtime.jsonMode) { return { stdout: printJson( { jobId, pipelineId: job.pipelineId, workflowName: workflowDetail?.pipelineName || workflowDetail?.label, workflowState: workflowStateLabel, jobStatus: job.state ?? job.status, totalTasks: timeline.length, executedTasks: tree.length, unexecutedTasks: timeline.length - tree.length, timeline, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const timelineRows = timeline.map((it: any) => [ it.index, it.name, it.displayName, it.type, it.status, it.duration, it.detail, ]); return { stdout: [ `====== 工作流全链路步骤进度 [${job.id}] ======`, printKeyValue({ "Job ID": job.id, "工作流 ID": job.pipelineId, ...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}), "工作流状态": workflowStateLabel, "Job 状态": job.state ?? job.status, "定义总步骤数": timeline.length, "已调度步骤数": tree.length, "未执行步骤数": timeline.length - tree.length, }), "", printTable( ["#", "节点标识", "步骤名称", "类型", "执行状态", "耗时(ms)", "详细说明"], timelineRows ), "", ].join("\n"), stderr: "", exitCode: 0, }; } if (runtime.jsonMode) { return { stdout: printJson( { jobId, job, workflow: workflowDetail ? { id: workflowDetail.id, name: workflowDetail.pipelineName || workflowDetail.label, state: workflowDetail.state, stateLabel: workflowStateLabel, totalTasks: workflowDetail.tasks?.length ?? tree.length, } : undefined, executionTree: tree, failedExecutions, conditionDiagnoses, timeline, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } const formatJobStatusLabel = (status?: string, state?: unknown): string => { const s = (status || "").toUpperCase(); if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中 (STARTED)"; if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成 (COMPLETED)"; if (s === "FAILED" || s === "ERROR") return "❌ 失败 (FAILED)"; if (s === "STOP" || s === "STOPPED") return "🛑 终止 (STOPPED)"; if (s === "CANCELLED" || s === "CANCELED") return "🚫 已取消"; return s || String(state ?? "-"); }; const treeRows = tree.map((node, idx) => { const isRunning = node.status === "STARTED" || node.status === "RUNNING"; const statusLabel = isRunning ? (node.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 运行中") : node.status || "-"; return [ idx + 1, node.id, node.name || "-", node.label || node.displayName || "-", node.type || "-", statusLabel, String((node as Record).durationTime ?? node.executionTime ?? "-"), node.error?.message || "-", ]; }); const failedRows = failedExecutions.map((item, idx) => [ idx + 1, item.id, item.parentId || "-", item.name || "-", item.type || "-", item.status || "-", item.currentLoopPath || "-", item.error?.message || "-", ]); const hasUnexecuted = workflowDetail && workflowDetail.tasks && workflowDetail.tasks.length > tree.length; const isJobRunning = (job.status || "").toUpperCase() === "STARTED" || (job.status || "").toUpperCase() === "RUNNING"; const outLines = [ `====== 工作流 Job 执行详情 [${job.id}] ======`, printKeyValue({ "Job ID": job.id, "工作流 ID (pipelineId)": job.pipelineId, ...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}), "工作流状态": workflowStateLabel, "Job 状态 (state)": formatJobStatusLabel(job.status, job.state), "开始时间": job.startTime || "-", "结束时间": job.endTime || "-", "耗时(ms)": String(job.durationTime ?? "-"), "定义总步骤数": workflowDetail?.tasks?.length ?? tree.length, "已调度节点数": tree.length, ...(hasUnexecuted ? { "未执行步骤数": workflowDetail.tasks.length - tree.length } : {}), "异常/跳过节点数": failedExecutions.length, }), ...(hasUnexecuted ? [ "", isJobRunning ? `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,当前正在执行第 ${tree.length} 步(延时等待中或任务处理中),后续 ${workflowDetail.tasks.length - tree.length} 个步骤尚未调度。运行 'hose-use workflow job ${job.id} --timeline' 可查看实时节点进度。` : `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,本次调度在第 ${tree.length} 步中断,后续 ${workflowDetail.tasks.length - tree.length} 个步骤未执行。运行 'hose-use workflow job ${job.id} --timeline' 查看全链路步骤时间线。`, ] : []), "", "── 顶层节点执行树 ──", treeRows.length ? printTable( ["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"], treeRows ) : "暂无顶层节点执行记录", ]; if (failedRows.length > 0) { outLines.push(""); outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──"); outLines.push( printTable( ["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"], failedRows ) ); } if (conditionDiagnoses.length > 0) { outLines.push(""); outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──"); for (const diag of conditionDiagnoses) { outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`); outLines.push(` • 判定结论: ${diag.summary}`); outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`); if (diag.rules.length > 0) { outLines.push(" • 规则比对明细:"); for (const r of diag.rules) { const statusIcon = r.matched === null ? "?" : r.matched ? "✅" : "❌"; const missTag = r.isMissing ? " [⚠️ 属性缺失]" : ""; outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`); outLines.push(` ↳ ${r.detail}`); } } } } const codeSummaries = extractCodeNodeSummaries(tree, flattenExecutionTree); if (codeSummaries.length > 0) { outLines.push(...formatCodeNodeSummariesCard(codeSummaries, job.id)); } return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0, }; }