diff --git a/scripts/mvel_date_format_node.mvel b/scripts/mvel_date_format_node.mvel new file mode 100644 index 0000000..aa9c66f --- /dev/null +++ b/scripts/mvel_date_format_node.mvel @@ -0,0 +1,123 @@ +// ============================================================================== +// 合思代码节点 (MVEL): 单据日期/日期范围字段转化为具体时间字符串与时间戳 +// ============================================================================== + +// ── 1. 配置区(按需修改)─────────────────────────────────────────────────────── +// (1) 前置工作流节点 ID(例如:第2步单据详情节点 action_pfsq28) +upstreamNode = action_pfsq28; + +// (2) 需要转化的单据层面字段 ID(例如标准起止日期 "feeDatePeriod",或自定义字段 "u_出差起止日期") +dateFieldKey = "feeDatePeriod"; + +// ── 2. 字段取值与防御提取 ────────────────────────────────────────────────────── +fieldVal = null; +if (upstreamNode != null) { + fieldVal = upstreamNode.get(dateFieldKey); + if (fieldVal == null && upstreamNode.get("form") != null) { + fieldVal = upstreamNode.get("form").get(dateFieldKey); + } +} + +rawStart = null; +rawEnd = null; + +if (fieldVal != null) { + if (fieldVal instanceof java.util.Map) { + rawStart = fieldVal.get("start"); + rawEnd = fieldVal.get("end"); + } else { + rawStart = fieldVal; + } +} + +// ── 3. 初始化日期格式化器(强制北京时间 GMT+8) ──────────────────────────────── +tz = java.util.TimeZone.getTimeZone("GMT+8"); + +sdfSecond = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); +sdfSecond.setTimeZone(tz); + +sdfMinute = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm"); +sdfMinute.setTimeZone(tz); + +sdfDay = new java.text.SimpleDateFormat("yyyy-MM-dd"); +sdfDay.setTimeZone(tz); + +// ── 4. 转换开始时间 (start) ─────────────────────────────────────────────────── +startStr = ""; +startMinute = ""; +startDay = ""; +startMs = 0L; +startSec = 0L; +dStart = null; + +if (rawStart != null && String.valueOf(rawStart).trim() != "") { + startMs = java.lang.Long.parseLong(String.valueOf(rawStart).trim()); + if (startMs < 10000000000L) { + startMs = startMs * 1000L; + } + startSec = startMs / 1000L; + dStart = new java.util.Date(startMs); + startStr = sdfSecond.format(dStart); + startMinute = sdfMinute.format(dStart); + startDay = sdfDay.format(dStart); +} + +// ── 5. 转换结束时间 (end) ───────────────────────────────────────────────────── +endStr = ""; +endMinute = ""; +endDay = ""; +endMs = 0L; +endSec = 0L; +dEnd = null; + +if (rawEnd != null && String.valueOf(rawEnd).trim() != "") { + endMs = java.lang.Long.parseLong(String.valueOf(rawEnd).trim()); + if (endMs < 10000000000L) { + endMs = endMs * 1000L; + } + endSec = endMs / 1000L; + dEnd = new java.util.Date(endMs); + endStr = sdfSecond.format(dEnd); + endMinute = sdfMinute.format(dEnd); + endDay = sdfDay.format(dEnd); +} + +// ── 6. 组合区间显示文本 ─────────────────────────────────────────────────────── +rangeMinuteStr = ""; +rangeSecondStr = ""; +if (startMinute != "" && endMinute != "") { + rangeMinuteStr = startMinute + " ~ " + endMinute; + rangeSecondStr = startStr + " ~ " + endStr; +} else if (startMinute != "") { + rangeMinuteStr = startMinute; + rangeSecondStr = startStr; +} + +// ── 7. 组装返回结果 ─────────────────────────────────────────────────────────── +result = new java.util.HashMap(); + +// 开始时间 / 单个时间 +result.put("startTimeStr", startStr); // 如: "2026-11-19 20:59:00" +result.put("startTimeMinute", startMinute); // 如: "2026-11-19 20:59" +result.put("startDate", startDay); // 如: "2026-11-19" +result.put("startTimestampMs", startMs); // 毫秒时间戳 (Long) +result.put("startTimestampSec", startSec); // 秒时间戳 (Long) + +// 结束时间 +result.put("endTimeStr", endStr); // 如: "2026-11-20 16:55:00" +result.put("endTimeMinute", endMinute); // 如: "2026-11-20 16:55" +result.put("endDate", endDay); // 如: "2026-11-20" +result.put("endTimestampMs", endMs); // 毫秒时间戳 (Long) +result.put("endTimestampSec", endSec); // 秒时间戳 (Long) + +// 区间文本(方便下游直接放入 comment 或通知) +result.put("rangeMinuteStr", rangeMinuteStr); // 如: "2026-11-19 20:59 ~ 2026-11-20 16:55" +result.put("rangeSecondStr", rangeSecondStr); // 如: "2026-11-19 20:59:00 ~ 2026-11-20 16:55:00" + +// 兼容单日期直接取用别名 +result.put("formattedTime", startStr); +result.put("formattedMinute", startMinute); +result.put("timestampMs", startMs); +result.put("timestampSec", startSec); + +return result; diff --git a/skills/hose-use/multi/ekuaibao-mvel/SKILL.md b/skills/hose-use/multi/ekuaibao-mvel/SKILL.md index ad33cfe..fe83fa6 100644 --- a/skills/hose-use/multi/ekuaibao-mvel/SKILL.md +++ b/skills/hose-use/multi/ekuaibao-mvel/SKILL.md @@ -158,3 +158,22 @@ Treat tenant-specific behavior as evidence, not a universal rule. Say what assum - **Deploy to workflow node**: `hose-use workflow node edit --code-file=./scripts/node_calc.mvel --yes` - **End-to-end cloud simulation test**: `hose-use workflow test --flow --yes --force` +## 沙箱调试绝佳技巧:终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning) + +在真实业务流程(尤其包含单据驳回、审批通过、企微/钉钉消息推送、台账更新等危险副作用)中调测新增的代码节点时,强烈建议采用**紧随终止节点 (Stop Node Barrier)** 模式: + +```text +[前置查询/触发节点] ──> [新代码节点 (MVEL)] ──> [临时终止节点 (stop)] ──x (下游循环/驳回/审批被彻底物理隔离) +``` + +### 1. 为什么必须紧随终止节点? +1. **防止业务穿透与脏数据(安全第一)**:调试执行由云端真实引擎运行。若不设断点,引擎向下执行一旦命中驳回 HTTP 节点或审批同意,会向真实系统发起调用;紧随插入一个 `stop` 节点可形成绝对安全隔离,执行到代码节点后即刻安全着陆。 +2. **纯净捕获真实出参**:在安全阻断的同时,当次调试 Job 的 `executionTree` 产物中能完整记录新代码节点的实际返回值(`output`),验证数据精度与格式。 + +### 2. 保存样本数据 (Sample Pinning) 赋能设计器下拉树 +代码节点在没有样本数据(`sampleData`)前,下游节点在合思设计器中打开「引用字段」下拉菜单时**无法识别其输出属性**。 +- **固化样本**:调试成功后,将当次执行的 `output` 一键回写为该节点的 `sampleData`(如使用 `hose-use workflow test ... --save-sample` 或 `workflow node sample-save`); +- **设计器自动解析**:一旦保存样本,合思工作流会自动为该代码节点生成选择器树(chooses),后续人工在配置下游驳回、条件或消息节点时,即可在界面下拉树中直接点选其格式化变量(如 `startTimeMinute`, `rangeMinuteStr`); +- **调试后清理**:业务验证并完成下游表达式配置后,在界面上手动删除该临时的终止节点即可。 + + diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index 55ecae8..c3c11d0 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -340,7 +340,7 @@ export const COMMAND_METADATA: Record = { "outbound-message": "outbound" }, - flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } + flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish save-sample saveSample save-samples saveSamples snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } }, "bill": { diff --git a/src/cli/commands/workflow-node-sample-inspect.test.ts b/src/cli/commands/workflow-node-sample-inspect.test.ts new file mode 100644 index 0000000..7e72490 --- /dev/null +++ b/src/cli/commands/workflow-node-sample-inspect.test.ts @@ -0,0 +1,478 @@ +import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test"; +import { handleWorkflowCommand } from "./workflow/index.js"; +import * as helpers from "./workflow/shared.js"; +import { CorpContext } from "../../core/config/manager.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import type { CliRuntime } from "../types.js"; + +const mockCorp: CorpConfig = { + id: "ID01ofWoOC1wiX", + name: "沈玥妍测试企业", + baseUrl: "https://app.ekuaibao.com", + cluster: "app", + source: "link", + credentials: { + accessToken: "test-token", + corpId: "ID01ofWoOC1wiX", + staffId: "ID01ofWoOC1wiX:ID01KsDgHaH5nN", + }, + env: "test", + isTest: true, +}; + +describe("CLI - workflow node inspect 与 sample-save (只读探针与样本一键固化)", () => { + let spies: any[] = []; + let mockRuntime: CliRuntime; + + beforeEach(() => { + spies = []; + const corpContext = new CorpContext([mockCorp], { stateful: true, defaultCorpId: mockCorp.id }); + mockRuntime = { + corpContext, + selectedCorp: mockCorp, + jsonMode: false, + outputOptions: {}, + }; + }); + + afterEach(() => { + for (const spy of spies) { + spy.mockRestore(); + } + spies = []; + }); + + it("workflow node inspect: 成功透视节点配置、已存样本与历史调试出参", async () => { + const mockTasks = [ + { + name: "trigger_1", + type: "ekuaibao-ebot-trigger", + label: "EBOT触发", + orderIndex: 0, + levelIndex: [0], + status: "active", + }, + { + name: "action_calc_1", + type: "code", + label: "代码节点", + displayName: "时间转换节点", + orderIndex: 1, + levelIndex: [1], + status: "active", + code: "result = ['minute': '2026-11-19 20:59'];\nreturn result;", + sampleData: { + minute: "2026-11-19 20:59", + }, + }, + ]; + + const mockDetail = { + id: "wf_inspect_test", + label: "测试工作流", + state: 0, + tasks: mockTasks, + }; + + const mockExecutionTree = [ + { + id: "exec_1", + name: "action_calc_1", + status: "COMPLETED", + executionTime: 8, + output: { + minute: "2026-11-19 20:59", + timestampMs: 1795093140000, + }, + }, + ]; + + const mockClient = { + get: (url: string) => { + if (url.includes("api/easo/pipelines/wf_inspect_test/log")) { + return { + text: async () => JSON.stringify({ code: 200 }), + json: async () => ({ + code: 200, + data: { + totalCount: 1, + items: [{ id: "job_test_100", status: "COMPLETED" }], + }, + }), + }; + } + if (url.includes("api/easo/pipelines/wf_inspect_test")) { + return { + text: async () => JSON.stringify({ code: 200 }), + json: async () => ({ code: 200, data: mockDetail }), + }; + } + if (url.includes("api/easo/jobs/job_test_100/execution")) { + return { + text: async () => JSON.stringify({ code: 200 }), + json: async () => ({ code: 200, data: mockExecutionTree }), + }; + } + return { + text: async () => JSON.stringify({ code: 200 }), + json: async () => ({ code: 200, data: null }), + }; + }, + }; + + spies.push( + spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({ + client: mockClient as any, + clients: {} as any, + platformId: undefined, + }) + ); + + // 1. 终端文本透视 + const resText = await handleWorkflowCommand( + { + area: "workflow", + action: "node", + args: ["inspect", "wf_inspect_test", "action_calc_1"], + options: {}, + raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1"], + }, + mockRuntime + ); + + expect(resText.exitCode).toBe(0); + expect(resText.stdout).toContain("工作流节点只读探针"); + expect(resText.stdout).toContain("action_calc_1"); + expect(resText.stdout).toContain("时间转换节点"); + expect(resText.stdout).toContain("已固化样本"); + expect(resText.stdout).toContain("最近一次调试执行出参"); + expect(resText.stdout).toContain("job_test_100"); + expect(resText.stdout).toContain("1795093140000"); + + // 2. JSON 模式结构化输出 + mockRuntime.jsonMode = true; + const resJson = await handleWorkflowCommand( + { + area: "workflow", + action: "node", + args: ["inspect", "wf_inspect_test", "action_calc_1"], + options: {}, + raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1", "--json"], + }, + mockRuntime + ); + + expect(resJson.exitCode).toBe(0); + const parsedJson = JSON.parse(resJson.stdout); + expect(parsedJson.sampleData.minute).toBe("2026-11-19 20:59"); + expect(parsedJson.executionProbe.jobId).toBe("job_test_100"); + expect(parsedJson.executionProbe.output.timestampMs).toBe(1795093140000); + }); + + it("workflow node sample-save: 支持 dry-run 预览并一键固化出参至节点 sampleData", async () => { + let savedTasks: any = null; + let choosesRefreshed = false; + + const mockTasks = [ + { + name: "action_target_node", + type: "code", + label: "代码节点", + orderIndex: 0, + levelIndex: [0], + status: "active", + }, + ]; + + const mockDetail = { + id: "wf_save_sample_test", + label: "样本固化测试流", + version: "1.0.0", + tasksVersion: 1, + state: 0, + tasks: mockTasks, + }; + + const mockExecutionTree = [ + { + id: "exec_node_target", + name: "action_target_node", + status: "COMPLETED", + output: { + formattedDate: "2026-11-24 11:30", + rangeSec: "2026-11-24 11:30:00 ~ 2026-11-24 12:00:00", + }, + }, + ]; + + const mockClient = { + get: (url: string) => { + if (url.includes("api/easo/pipelines/wf_save_sample_test")) { + return { json: async () => ({ code: 200, data: mockDetail }) }; + } + if (url.includes("api/easo/jobs/job_custom_999/execution")) { + return { json: async () => ({ code: 200, data: mockExecutionTree }) }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + put: (url: string, opts: any) => { + if (url.endsWith("/chooses")) { + choosesRefreshed = true; + return { + text: async () => JSON.stringify({ code: 200, data: [] }), + json: async () => ({ code: 200, data: [] }), + }; + } + if (url.includes("api/easo/pipelines/wf_save_sample_test")) { + savedTasks = opts.json.tasks; + return { + text: async () => + JSON.stringify({ + code: 200, + data: { + ...mockDetail, + ...opts.json, + tasksVersion: 2, + }, + }), + json: async () => ({ + code: 200, + data: { + ...mockDetail, + ...opts.json, + tasksVersion: 2, + }, + }), + }; + } + return { + text: async () => JSON.stringify({ code: 200, data: null }), + json: async () => ({ code: 200, data: null }), + }; + }, + }; + + spies.push( + spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({ + client: mockClient as any, + clients: {} as any, + platformId: undefined, + }) + ); + + // 1. Dry-run 预览 + const dryRes = await handleWorkflowCommand( + { + area: "workflow", + action: "node", + args: ["sample-save", "wf_save_sample_test", "action_target_node"], + options: { dryRun: true, job: "job_custom_999" }, + raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--dry-run"], + }, + mockRuntime + ); + + expect(dryRes.exitCode).toBe(0); + expect(dryRes.stdout).toContain("[DRY-RUN]"); + expect(dryRes.stdout).toContain("固化节点样本数据 (sampleData)"); + expect(savedTasks).toBeNull(); + + // 2. 确认执行 + const execRes = await handleWorkflowCommand( + { + area: "workflow", + action: "node", + args: ["sample-save", "wf_save_sample_test", "action_target_node"], + options: { yes: true, job: "job_custom_999" }, + raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--yes"], + }, + mockRuntime + ); + + expect(execRes.exitCode).toBe(0); + expect(execRes.stdout).toContain("样本数据 (sampleData) 固化成功"); + expect(execRes.stdout).toContain("固化字段数 : 2 个属性"); + expect(savedTasks).not.toBeNull(); + expect(savedTasks[0].sampleData.formattedDate).toBe("2026-11-24 11:30"); + expect(choosesRefreshed).toBe(true); + }); + + it("workflow test --save-sample: 调试通过后自动固化执行出参为节点 sampleData", async () => { + let savedTasks: any = null; + let choosesRefreshed = false; + + const mockTasks = [ + { + name: "trigger_1", + type: "ekuaibao-flowform-trigger", + label: "单据触发", + orderIndex: 0, + levelIndex: [0], + status: "active", + }, + { + name: "action_code_date", + type: "code", + label: "代码节点", + orderIndex: 1, + levelIndex: [1], + status: "active", + code: "return ['minute': '2026-11-24 11:35'];", + }, + ]; + + const mockDetail = { + id: "wf_test_save_sample", + label: "自动保存样本流程", + version: "1.0.0", + tasksVersion: 1, + state: 0, + tasks: mockTasks, + }; + + const mockClient = { + post: (url: string) => { + if (url.includes("debugSource")) { + return { + json: async () => ({ + code: 200, + data: { + type: "flowForm", + total: 1, + items: [{ id: "S26000001", title: "测试单据", flowState: "审批中" }], + }, + }), + }; + } + if (url.includes("api/easo/jobs")) { + return { + json: async () => ({ + code: 200, + data: "job_auto_sample_123", + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + get: (url: string) => { + if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) }; + if (url.includes("execution")) { + return { + json: async () => ({ + code: 200, + data: [ + { + id: "e1", + name: "trigger_1", + label: "单据触发", + type: "ekuaibao-flowform-trigger", + status: "COMPLETED", + executionTime: 10, + }, + { + id: "e2", + name: "action_code_date", + label: "代码节点", + type: "code", + status: "COMPLETED", + executionTime: 5, + output: { + minute: "2026-11-24 11:35", + timestampMs: 1795093140000, + }, + }, + ], + }), + }; + } + if (url.includes("api/easo/jobs/job_auto_sample_123")) { + return { + json: async () => ({ + code: 200, + data: { + id: "job_auto_sample_123", + pipelineId: "wf_test_save_sample", + status: "COMPLETED", + startTime: 1795490000000, + endTime: 1795490001000, + executionTime: 1000, + }, + }), + }; + } + if (url.includes("api/easo/pipelines/wf_test_save_sample")) { + return { + json: async () => ({ + code: 200, + data: mockDetail, + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + put: (url: string, opts: any) => { + if (url.endsWith("/chooses")) { + choosesRefreshed = true; + return { + text: async () => JSON.stringify({ code: 200, data: [] }), + json: async () => ({ code: 200, data: [] }), + }; + } + if (url.includes("api/easo/pipelines/wf_test_save_sample")) { + savedTasks = opts.json.tasks; + return { + text: async () => + JSON.stringify({ + code: 200, + data: { + ...mockDetail, + ...opts.json, + tasksVersion: 2, + }, + }), + json: async () => ({ + code: 200, + data: { + ...mockDetail, + ...opts.json, + tasksVersion: 2, + }, + }), + }; + } + return { + text: async () => JSON.stringify({ code: 200, data: null }), + json: async () => ({ code: 200, data: null }), + }; + }, + }; + + spies.push( + spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({ + client: mockClient as any, + clients: {} as any, + platformId: undefined, + }) + ); + + const testRes = await handleWorkflowCommand( + { + area: "workflow", + action: "test", + args: ["wf_test_save_sample"], + options: { flow: "S26000001", saveSample: true, yes: true }, + raw: ["workflow", "test", "wf_test_save_sample", "--flow=S26000001", "--save-sample", "--yes"], + }, + mockRuntime + ); + + expect(testRes.exitCode).toBe(0); + expect(testRes.stdout).toContain("工作流自动化调测报告"); + expect(testRes.stdout).toContain("样本数据自动固化"); + expect(testRes.stdout).toContain("action_code_date"); + expect(savedTasks).not.toBeNull(); + expect(savedTasks[1].sampleData.minute).toBe("2026-11-24 11:35"); + expect(savedTasks[1].sampleData.timestampMs).toBe(1795093140000); + expect(choosesRefreshed).toBe(true); + }); +}); diff --git a/src/cli/commands/workflow/node.ts b/src/cli/commands/workflow/node.ts index 13cd8f4..84a33e9 100644 --- a/src/cli/commands/workflow/node.ts +++ b/src/cli/commands/workflow/node.ts @@ -7,6 +7,9 @@ import { editWorkflowTask, removeWorkflowTask, applyNodeMapping, + getJobExecutionTree, + listWorkflowLogs, + refreshWorkflowChooses, } from "../../../domains/platform/workflow/services.js"; import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js"; import { ValidationError } from "../../../core/errors.js"; @@ -26,7 +29,11 @@ async function saveNodeChanges(client: Parameters[0], }); } -const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]); +const SUB_ACTIONS = new Set([ + "list", "ls", "get", "show", "info", "add", "append", "insert", + "edit", "update", "set", "map", "rm", "remove", "delete", "del", + "inspect", "probe", "examine", "sample-save", "save-sample", +]); export async function handleNodeCommand( parsed: CliParsedArgs, @@ -79,12 +86,14 @@ export async function handleNodeCommand( "用法: hose-use workflow node <子命令> [选项]", "", "子命令 (工作流级别):", - " list 列出工作流所有任务节点 (别名: ls, 默认)", - " get <节点标识> 查看指定节点的完整配置 (别名: show, info)", - " add [选项] 声明式追加或插入新任务节点 (别名: append, insert)", - " edit <节点标识> 定向修改指定节点配置 (别名: update, set)", - " map <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)", - " rm <节点标识> 安全移除指定任务节点 (别名: remove, delete)", + " list 列出工作流所有任务节点 (别名: ls, 默认)", + " get <节点标识> 查看指定节点的完整配置 (别名: show, info)", + " inspect <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)", + " sample-save <节点标识> 固化指定 Job 或最新调测出参为 sampleData", + " add [选项] 声明式追加或插入新任务节点 (别名: append, insert)", + " edit <节点标识> 定向修改指定节点配置 (别名: update, set)", + " map <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)", + " rm <节点标识> 安全移除指定任务节点 (别名: remove, delete)", "", "子命令 (企业灰度节点级别):", " nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)", @@ -107,6 +116,13 @@ export async function handleNodeCommand( case "list": case "ls": return handleListNodes(pipelineId, parsed, runtime); + case "inspect": + case "probe": + case "examine": + return handleInspectNode(pipelineId, nodeTarget, parsed, runtime); + case "sample-save": + case "save-sample": + return handleSaveNodeSample(pipelineId, nodeTarget, parsed, runtime); case "get": case "show": case "info": @@ -677,3 +693,251 @@ async function handleRemoveNode( exitCode: 0, }; } + +async function handleInspectNode( + pipelineId: string, + nodeTarget: string, + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + if (!nodeTarget) { + return { + stdout: "", + stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect \n", + exitCode: 1, + }; + } + + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const detail = await getWorkflowDetail(client, pipelineId); + const located = findWorkflowTask(detail.tasks || [], nodeTarget); + + if (!located) { + return { + stdout: "", + stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`, + exitCode: 1, + }; + } + + const { task, hierarchicalIndex, path, parentName } = located; + const sampleData = (task as any).sampleData ?? null; + + let executionProbe: { + jobId: string; + status: string; + executionTime?: number; + output?: any; + error?: any; + } | null = null; + + const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]); + try { + let jobIdToProbe = targetJobId; + if (!jobIdToProbe) { + const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 }); + const firstItem = logs.items?.[0] || (logs as any).records?.[0]; + if (firstItem && firstItem.id) { + jobIdToProbe = firstItem.id; + } + } + + if (jobIdToProbe) { + const tree = await getJobExecutionTree(client, jobIdToProbe); + const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name); + if (matchExecution) { + executionProbe = { + jobId: jobIdToProbe, + status: matchExecution.status || "UNKNOWN", + executionTime: (matchExecution as any).durationTime ?? matchExecution.executionTime, + output: matchExecution.output, + error: matchExecution.error, + }; + } + } + } catch { + // 探针容错 + } + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + pipelineId, + node: located, + sampleData, + executionProbe, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + const outLines: string[] = [ + `====== 工作流节点只读探针 [${detail.label || pipelineId}] · ${task.displayName || task.label || task.name} ======`, + `节点标识 (name) : ${task.name}`, + `层级编号 (#) : ${hierarchicalIndex}`, + `节点类型 (type) : ${task.type}`, + `节点标题 (label) : ${task.label || "-"}`, + `节点显示名 (display): ${(task as any).displayName || "-"}`, + `父容器节点 : ${parentName || "顶级节点 (root)"}`, + `JSON 路径 : ${path}`, + ]; + + if ((task as any).code !== undefined) { + outLines.push(`脚本代码行数 : ${(task as any).code.split("\n").length} 行`); + } + if ((task as any).url) { + outLines.push(`请求 URL : ${(task as any).url}`); + } + if ((task as any).specificationId) { + outLines.push(`单据模板 ID : ${JSON.stringify((task as any).specificationId)}`); + } + + outLines.push(""); + outLines.push("── 📦 节点固化样本数据 (sampleData) ──"); + if (sampleData && typeof sampleData === "object" && Object.keys(sampleData).length > 0) { + const keys = Object.keys(sampleData); + outLines.push(`状态: ✅ 已固化样本 (${keys.length} 个字段)`); + outLines.push(printJson(sampleData, runtime.outputOptions)); + } else { + outLines.push("状态: ⚪ 暂无样本数据 (设计器下拉菜单将无法自动解析其结构化变量)"); + outLines.push("💡 提示: 可运行 hose-use workflow node sample-save 固化最近调测出参"); + } + + outLines.push(""); + outLines.push("── 🧪 最近一次调试执行出参 (Execution Output Probe) ──"); + if (executionProbe) { + outLines.push(`来源 Job ID : ${executionProbe.jobId}`); + outLines.push(`执行状态 (status) : ${executionProbe.status}`); + outLines.push(`执行耗时 (ms) : ${executionProbe.executionTime ?? "-"}`); + if (executionProbe.output && typeof executionProbe.output === "object") { + outLines.push(`出参全貌 (output):`); + outLines.push(printJson(executionProbe.output, runtime.outputOptions)); + } else { + outLines.push(`出参: ${JSON.stringify(executionProbe.output ?? null)}`); + } + } else { + outLines.push("未找到或无匹配的最近调试执行记录。"); + } + + return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 }; +} + +async function handleSaveNodeSample( + pipelineId: string, + nodeTarget: string, + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + if (!nodeTarget) { + return { + stdout: "", + stderr: "用法: hose-use workflow node sample-save [--job=]\n", + exitCode: 1, + }; + } + + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const detail = await getWorkflowDetail(client, pipelineId); + const located = findWorkflowTask(detail.tasks || [], nodeTarget); + + if (!located) { + return { + stdout: "", + stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`, + exitCode: 1, + }; + } + + const { task } = located; + const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]); + + let jobIdToProbe = targetJobId; + if (!jobIdToProbe) { + const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 }); + const firstItem = logs.items?.[0] || (logs as any).records?.[0]; + if (firstItem && firstItem.id) { + jobIdToProbe = firstItem.id; + } + } + + if (!jobIdToProbe) { + return { + stdout: "", + stderr: `未指定 Job ID 且未查询到工作流 [${pipelineId}] 的历史运行日志,无法提取样本数据。请先执行调试或通过 --job= 指定。\n`, + exitCode: 1, + }; + } + + const tree = await getJobExecutionTree(client, jobIdToProbe); + const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name); + + if (!matchExecution || matchExecution.output === undefined) { + return { + stdout: "", + stderr: `在 Job [${jobIdToProbe}] 中未找到节点 [${task.name}] 的有效执行出参 (output)。\n`, + exitCode: 1, + }; + } + + const samplePayload = matchExecution.output; + + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "固化节点样本数据 (sampleData)", `${pipelineId}:${task.name}`, { + pipelineId, + nodeName: task.name, + jobId: jobIdToProbe, + samplePayload, + }); + } + + requireMutationConfirmation( + parsed, + runtime, + "固化节点样本数据 (sampleData)", + `hose-use workflow node sample-save ${pipelineId} ${nodeTarget} --job=${jobIdToProbe} --yes` + ); + + (task as any).sampleData = samplePayload; + const saveResult = await saveNodeChanges(client, detail, detail, platformId); + + try { + await refreshWorkflowChooses(client, pipelineId); + } catch {} + + const fieldCount = typeof samplePayload === "object" && samplePayload !== null ? Object.keys(samplePayload).length : 1; + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + success: true, + pipelineId, + nodeName: task.name, + jobId: jobIdToProbe, + fieldsSaved: fieldCount, + sampleData: samplePayload, + workflow: saveResult, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: [ + `✨ 节点 [${task.name}] (${task.displayName || task.label || task.type}) 样本数据 (sampleData) 固化成功!`, + ` • 来源 Job ID : ${jobIdToProbe}`, + ` • 固化字段数 : ${fieldCount} 个属性`, + ` • 设计器联动 : 已刷新选择器 (chooses) 树,下游节点现在可在下拉列表中直接点选其输出变量。`, + `📌 ${formatWorkflowVersion(saveResult)}`, + ].join("\n") + "\n", + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/workflow/test.ts b/src/cli/commands/workflow/test.ts index 8cc3e4c..ef389e2 100644 --- a/src/cli/commands/workflow/test.ts +++ b/src/cli/commands/workflow/test.ts @@ -6,6 +6,9 @@ import { getWorkflowDetail, getWorkflowSampleData, runWorkflowDebugTest, + updateWorkflow, + refreshWorkflowChooses, + flattenWorkflowTaskTree, type WorkflowTriggerCategory, } from "../../../domains/platform/workflow/services.js"; import { stringOption, booleanOption, numberOption } from "../../parser.js"; @@ -46,6 +49,7 @@ export async function handleWorkflowTest( " 4. 外部调用 (webhook): --body='{...}' 或 --file= 传入事件请求体", "", "通用选项:", + " --save-sample 调试通过后自动将执行节点的真实出参保存为样本数据 (sampleData)", " --timeout= 设置轮询超时时间 (默认 15000ms)", " --auto-publish 是否自动发布测试快照 (默认 false)", " --allow-prod 确认在正式生产环境 (env: prod) 下执行调试(--force 为兼容别名)", @@ -59,6 +63,7 @@ export async function handleWorkflowTest( } const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]); + const saveSample = booleanOption(parsed.options, ["save-sample", "saveSample", "save-samples", "saveSamples"]); const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000; const rawBody = stringOption(parsed.options, ["body", "data", "payload"]); const filePath = stringOption(parsed.options, ["file", "path"]); @@ -109,7 +114,7 @@ export async function handleWorkflowTest( }); if (blocked) return blocked; if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution(); - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); // 1. 获取工作流详情与触发器元数据 const detail = await getWorkflowDetail(client, pipelineId).catch(() => { @@ -414,9 +419,48 @@ export async function handleWorkflowTest( autoPublish, timeoutMs, }); + + const savedSampleNodes: Array<{ name: string; label: string; fieldCount: number }> = []; + if (saveSample && execution.outcome === "completed" && execution.executionTree?.length > 0) { + try { + const latestDetail = await getWorkflowDetail(client, pipelineId); + const flattened = flattenWorkflowTaskTree(latestDetail.tasks || []); + let updatedCount = 0; + + for (const execNode of execution.executionTree) { + if (!execNode.name || execNode.output === undefined || execNode.output === null) continue; + if (typeof execNode.output !== "object" || Object.keys(execNode.output).length === 0) continue; + + const matched = flattened.find((f) => f.task.name === execNode.name); + if (matched) { + (matched.task as any).sampleData = execNode.output; + savedSampleNodes.push({ + name: matched.task.name, + label: (matched.task as any).displayName || matched.task.label || matched.task.type, + fieldCount: Object.keys(execNode.output).length, + }); + updatedCount++; + } + } + + if (updatedCount > 0) { + await updateWorkflow(client, latestDetail, { + platformId, + expectedVersion: { version: latestDetail.version, tasksVersion: latestDetail.tasksVersion }, + }); + try { + await refreshWorkflowChooses(client, pipelineId); + } catch {} + } + } catch (sampleErr: any) { + warnings.push(`自动固化样本数据警告: ${sampleErr.message || String(sampleErr)}`); + } + } + const report = { ...execution, productionEnabled: detail ? isEnabled : null, + savedSampleNodes: savedSampleNodes.length > 0 ? savedSampleNodes : undefined, warnings, ...productionOverrideMeta( parsed, @@ -514,6 +558,15 @@ export async function handleWorkflowTest( outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId)); } + if (savedSampleNodes.length > 0) { + outLines.push(""); + outLines.push("── ✨ 样本数据自动固化 (Sample Data Saved) ──"); + outLines.push(`已自动将 ${savedSampleNodes.length} 个节点的真实调试出参固化为 sampleData 并刷新设计器选择树:`); + for (const sn of savedSampleNodes) { + outLines.push(` • [${sn.name}] (${sn.label}): 固化 ${sn.fieldCount} 个属性`); + } + } + if (category === "WEBHOOK" && report.outcome !== "completed") { outLines.push(""); outLines.push("💡 [Webhook 流程调试提示]"); diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index db0c3f8..f4c340a 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -149,8 +149,9 @@ export class CorpContext { if (!corp) return false; this.current = corp; this.defaultCorpId = corp.id; - if (persist && this.stateful) { - saveGlobalConfig({ defaultCorpId: corp.id }); + if (persist) { + this.stateful = true; + saveGlobalConfig({ defaultCorpId: corp.id, stateful: true }); } return true; }