diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index e8876d0..10b7ec6 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -214,6 +214,8 @@ hose-use workflow tail wf_01k83y... # 类似 tail -f hose-use workflow tail wf_01k83y... --job= # 针对单个执行中的 Job 实时跟踪直至终态 hose-use workflow tail wf_01k83y... --failed-only # 仅在有报错或异常跳过 (SKIPPED) 时即时打印详情 hose-use workflow tail wf_01k83y... --once --json # 检视最新或当前运行中的 Job 进度快照并返回结构化数据 +hose-use workflow lint-script wf_01k83y... # 批量静态校验代码节点语法规范与上游依赖 (支持 --file/--code) +hose-use workflow eval-script wf_01k83y... <节点> --sample=1 # 离线沙箱仿真运行 JS 节点并复用样本数据 (支持 --input/--timeout) # 6. OpenAPI 密钥与应用中心 hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏 diff --git a/skills/hose-use/references/workflow.md b/skills/hose-use/references/workflow.md index 517c7f4..4797664 100644 --- a/skills/hose-use/references/workflow.md +++ b/skills/hose-use/references/workflow.md @@ -328,7 +328,41 @@ hose-use workflow tail --timeout=60 --- -## 17. 工作流排障与创单排错三大黄金法则(必读) +## 17. 工作流代码节点静态校验与离线沙箱仿真 (`workflow lint-script` / `eval-script`) + +合思工作流支持自定义 JavaScript (`code-js2`) 与 MVEL (`code`) 脚本节点。以往只能在生产派发调试 Job 才能验证脚本,不仅污染发布版本快照,还容易因死循环、语法报错或悬空上游节点引发流程中断。`hose-use` 提供了纯本地 AST 语法检查与安全隔离沙箱运行能力: + +```bash +# 1. 静态扫描整条工作流中所有代码节点的语法、return 语句与上游依赖引用 +hose-use workflow lint-script +hose-use workflow lint --json + +# 2. 定向检查指定代码节点(支持节点名称或 #序号) +hose-use workflow lint-script action_dx9cci + +# 3. 静态检查本地脚本文件或命令行传入的代码片段 +hose-use workflow lint-script --file=./scripts/clean.js +hose-use workflow lint-script --code="const a = 1; return a * 2;" +hose-use workflow lint-script --code="var a = control_123; return a;" --type=mvel + +# 4. 在离线安全沙箱中仿真运行工作流中的某个 JavaScript 节点 (code-js2) +# 自动复用最近一次历史真实样本数据作为入参,打印返回值与全部 console.log 日志: +hose-use workflow eval-script action_dx9cci + +# 5. 指定历史测试样本序号(如第 2 条样本)进行离线仿真 +hose-use workflow eval-script action_dx9cci --sample=2 + +# 6. 自定义输入参数执行离线仿真 (JSON 字符串或本地 JSON 文件) +hose-use workflow eval-script action_dx9cci --input='{"info":{"amount":100}}' +hose-use workflow eval-script action_dx9cci --input-file=./mock_input.json + +# 7. 纯本地行内代码沙箱快速求值与死循环超时控制 (--timeout 默认 3000ms) +hose-use workflow eval-script --code="console.log(items); return items.filter(x => x.active);" --input='{"items":[{"id":1,"active":true},{"id":2,"active":false}]}' +``` + +--- + +## 18. 工作流排障与创单排错三大黄金法则(必读) 在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则: diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index a5205eb..7803f83 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1819,5 +1819,175 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { expect(watchJobRes.exitCode).toBe(0); expect(watchJobRes.stdout).toContain("Job [job_tail_101]"); }); + + it("handles workflow lint-script and eval-script commands end-to-end", async () => { + // 1. Missing args usage + const missingRes = await handleWorkflowCommand( + { + area: "workflow", + action: "lint-script", + args: [], + options: {}, + raw: ["workflow", "lint-script"], + }, + mockRuntime + ); + expect(missingRes.exitCode).toBe(1); + expect(missingRes.stderr).toContain("用法: hose-use workflow lint-script"); + + // 2. Inline JavaScript linting - valid + const validJsRes = await handleWorkflowCommand( + { + area: "workflow", + action: "lint-script", + args: [], + options: { code: "const x = 10; return x * 2;" }, + raw: ["workflow", "lint-script", '--code="const x = 10; return x * 2;"'], + }, + mockRuntime + ); + expect(validJsRes.exitCode).toBe(0); + expect(validJsRes.stdout).toContain("✅ 语法完全合规"); + + // 3. Inline JavaScript linting - syntax error + const syntaxErrRes = await handleWorkflowCommand( + { + area: "workflow", + action: "lint-script", + args: [], + options: { code: "const a = ;" }, + raw: ["workflow", "lint-script", '--code="const a = ;"'], + }, + mockRuntime + ); + expect(syntaxErrRes.exitCode).toBe(1); + expect(syntaxErrRes.stdout).toContain("JavaScript 语法错误"); + + // 4. Inline MVEL linting - unclosed bracket + const mvelErrRes = await handleWorkflowCommand( + { + area: "workflow", + action: "lint", + args: [], + options: { code: "var list = [1, 2; return list;", type: "mvel" }, + raw: ["workflow", "lint", '--code="var list = [1, 2; return list;"', "--type=mvel"], + }, + mockRuntime + ); + expect(mvelErrRes.exitCode).toBe(1); + expect(mvelErrRes.stdout).toContain("未闭合的括号"); + + // 5. Offline sandbox eval - inline code with inputs + const evalSuccessRes = await handleWorkflowCommand( + { + area: "workflow", + action: "eval-script", + args: [], + options: { + code: 'console.log("计算中:", a, b); return { result: a + b };', + input: JSON.stringify({ a: 15, b: 25 }), + }, + raw: ["workflow", "eval-script", '--code="..."', '--input="..."'], + }, + mockRuntime + ); + expect(evalSuccessRes.exitCode).toBe(0); + expect(evalSuccessRes.stdout).toContain("执行成功 ✅"); + expect(evalSuccessRes.stdout).toContain("计算中: 15 25"); + expect(evalSuccessRes.stdout).toContain('"result": 40'); + + // 6. Offline sandbox eval - runtime error + const evalFailRes = await handleWorkflowCommand( + { + area: "workflow", + action: "eval-script", + args: [], + options: { + code: 'return obj.nonExistent.subField;', + input: JSON.stringify({ obj: {} }), + }, + raw: ["workflow", "eval-script", '--code="..."', '--input="..."'], + }, + mockRuntime + ); + expect(evalFailRes.exitCode).toBe(1); + expect(evalFailRes.stdout).toContain("执行失败 ❌"); + expect(evalFailRes.stdout).toContain("TypeError"); + + // 7. Workflow level lint-script with mocked pipeline + const mockDetail = { + id: "pipe_script_test", + label: "脚本测试流水线", + tasks: [ + { + name: "trigger_webhook", + type: "webhook", + label: "Webhook 触发器", + }, + { + name: "action_js_clean", + type: "code-js2", + label: "数据清洗 JS", + code: "console.log(info); return { total: 100 };", + mapping: [{ key: "info", value: "@{choose(trigger_webhook.data)}" }], + }, + { + name: "action_mvel_calc", + type: "code", + label: "MVEL 计算", + code: "var val = trigger_webhook.data;\nreturn val;", + }, + ], + }; + + const mockClient = { + get: () => ({ + json: async () => ({ + code: 200, + data: mockDetail, + }), + }), + }; + 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 wfLintRes = await handleWorkflowCommand( + { + area: "workflow", + action: "lint-script", + args: ["pipe_script_test"], + options: {}, + raw: ["workflow", "lint-script", "pipe_script_test"], + }, + mockRuntime + ); + expect(wfLintRes.exitCode).toBe(0); + expect(wfLintRes.stdout).toContain("共检测 2 个代码节点"); + expect(wfLintRes.stdout).toContain("action_js_clean"); + expect(wfLintRes.stdout).toContain("action_mvel_calc"); + expect(wfLintRes.stdout).toContain("总体验证结果: 全部代码节点均通过语法与引用校验 ✅"); + + // 8. Workflow level eval-script targeting node + const wfEvalRes = await handleWorkflowCommand( + { + area: "workflow", + action: "eval-script", + args: ["pipe_script_test", "action_js_clean"], + options: { input: JSON.stringify({ info: "sample_input" }) }, + raw: ["workflow", "eval-script", "pipe_script_test", "action_js_clean"], + }, + mockRuntime + ); + expect(wfEvalRes.exitCode).toBe(0); + expect(wfEvalRes.stdout).toContain("节点 [action_js_clean]"); + expect(wfEvalRes.stdout).toContain("执行成功 ✅"); + expect(wfEvalRes.stdout).toContain('"total": 100'); + }); }); diff --git a/src/cli/commands/workflow/index.ts b/src/cli/commands/workflow/index.ts index f4d8bbc..16a08c0 100644 --- a/src/cli/commands/workflow/index.ts +++ b/src/cli/commands/workflow/index.ts @@ -13,6 +13,7 @@ import { handleDelete } from "./delete.js"; import { handleCreate } from "./create.js"; import { handleNodeCommand } from "./node.js"; import { handleWorkflowTailCommand } from "./tail.js"; +import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"; export async function handleWorkflowCommand( parsed: CliParsedArgs, @@ -98,10 +99,19 @@ export async function handleWorkflowCommand( case "watch": case "follow": return handleWorkflowTailCommand(parsed, runtime); + case "lint-script": + case "lint": + case "lint-code": + return handleWorkflowLintScript(parsed, runtime); + case "eval-script": + case "eval": + case "eval-code": + case "run-script": + return handleWorkflowEvalScript(parsed, runtime); default: return { stdout: "", - stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail\n`, + stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script\n`, exitCode: 1, }; } diff --git a/src/cli/commands/workflow/script.ts b/src/cli/commands/workflow/script.ts new file mode 100644 index 0000000..c7e8629 --- /dev/null +++ b/src/cli/commands/workflow/script.ts @@ -0,0 +1,413 @@ +import fs from "node:fs"; +import { + getWorkflowDetail, + getWorkflowSampleData, + findWorkflowTask, + lintWorkflowScripts, + lintJavaScriptCode, + lintMvelCode, + executeJavaScriptSandbox, +} from "../../../domains/platform/services.js"; +import { stringOption, booleanOption } from "../../parser.js"; +import { printJson, printKeyValue } from "../../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; +import { createWorkflowDetailClient } from "./shared.js"; + +/** + * 校验工作流脚本 (JavaScript / MVEL) 语法、上游引用与代码规范 + */ +export async function handleWorkflowLintScript( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const isJson = booleanOption(parsed.options, ["json"]); + const filePath = stringOption(parsed.options, ["file", "path"]); + const codeInline = stringOption(parsed.options, ["code"]); + const explicitType = (stringOption(parsed.options, ["type"]) || "code-js2").toLowerCase(); + + // 1. 本地代码文件或行内脚本校验 + if (filePath || codeInline) { + let rawCode = codeInline || ""; + if (filePath) { + if (!fs.existsSync(filePath)) { + return { + stdout: "", + stderr: `指定的脚本文件不存在: ${filePath}\n`, + exitCode: 1, + }; + } + rawCode = fs.readFileSync(filePath, "utf-8"); + } + + const type = explicitType === "code" || explicitType === "mvel" ? "code" : "code-js2"; + let issues: Array<{ level: string; line?: number; column?: number; message: string; rule: string }> = []; + let hasReturn = false; + let referencedNodes: Array<{ name: string; exists: boolean }> = []; + + if (type === "code-js2") { + const res = lintJavaScriptCode(rawCode); + issues = res.issues; + hasReturn = res.hasReturn; + } else { + const res = lintMvelCode(rawCode); + issues = res.issues; + hasReturn = res.hasReturn; + referencedNodes = res.referencedNodes; + } + + const hasErrors = issues.some((i) => i.level === "error"); + const report = { + source: filePath ? `file: ${filePath}` : "inline-code", + type: type === "code-js2" ? "JavaScript (code-js2)" : "MVEL (code)", + codeLength: rawCode.length, + lineCount: rawCode ? rawCode.split(/\r?\n/).length : 0, + hasReturn, + referencedNodes, + issues, + valid: !hasErrors, + }; + + if (isJson) { + printJson(report); + return { stdout: "", stderr: "", exitCode: hasErrors ? 1 : 0 }; + } + + const lines: string[] = []; + lines.push(`脚本静态校验: ${report.source}`); + lines.push(`引擎类型: ${report.type} | 代码行数: ${report.lineCount} | 字符数: ${report.codeLength}`); + lines.push(`return 语句: ${hasReturn ? "✅ 存在" : "⚠️ 缺失"}`); + if (referencedNodes.length > 0) { + lines.push(`引用上游节点: ${referencedNodes.map((n) => n.name).join(", ")}`); + } + + if (issues.length === 0) { + lines.push("校验结果: ✅ 语法完全合规,无任何错误或警告\n"); + } else { + lines.push(`\n发现 ${issues.length} 个潜在问题:`); + for (const iss of issues) { + const icon = iss.level === "error" ? "❌ [错误]" : "⚠️ [警告]"; + const loc = iss.line ? ` L${iss.line}${iss.column ? `:${iss.column}` : ""}` : ""; + lines.push(` ${icon}${loc} [${iss.rule}] ${iss.message}`); + } + lines.push(hasErrors ? "\n校验未通过 ❌ 请根据上述提示修复语法错误。\n" : "\n校验通过 (含告警提示) ⚠️\n"); + } + + return { + stdout: lines.join("\n"), + stderr: "", + exitCode: hasErrors ? 1 : 0, + }; + } + + // 2. 线上工作流整条流水线或指定节点校验 + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]); + const targetNode = parsed.args[1] || stringOption(parsed.options, ["node", "target"]); + + if (!pipelineId) { + return { + stdout: "", + stderr: [ + "用法: hose-use workflow lint-script [节点标识] [选项]", + " 或: hose-use workflow lint-script --file= [--type=code-js2|code] [选项]", + " 或: hose-use workflow lint-script --code=\"\" [--type=code-js2|code] [选项]", + "", + "选项:", + " --node= 仅校验流水线中指定的某个代码节点", + " --file= 静态检查本地脚本文件", + " --code= 静态检查行内传入的代码片段", + " --type=code-js2|code 指定脚本类型(默认 code-js2 JavaScript)", + " --json 输出结构化 JSON 格式结果", + "", + "示例:", + " hose-use workflow lint-script 896398895352487950", + " hose-use workflow lint-script 896398895352487950 action_dx9cci", + " hose-use workflow lint-script --file=./scripts/clean.js", + ].join("\n") + "\n", + exitCode: 1, + }; + } + + const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const workflow = await getWorkflowDetail(client, pipelineId); + const report = lintWorkflowScripts(workflow, targetNode); + + if (isJson) { + printJson(report); + return { stdout: "", stderr: "", exitCode: report.allValid ? 0 : 1 }; + } + + const lines: string[] = []; + lines.push(`工作流脚本静态校验: ${report.label || pipelineId} (${pipelineId})`); + lines.push(`共检测 ${report.totalCodeNodes} 个代码节点 (JS/MVEL): ${report.validCount} 个合规, ${report.invalidCount} 个异常\n`); + + if (report.reports.length === 0) { + lines.push("未找到任何代码节点 (code / code-js2)。"); + return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 }; + } + + for (const node of report.reports) { + const statusIcon = node.valid ? (node.issues.length > 0 ? "⚠️" : "✅") : "❌"; + const typeLabel = node.type === "code-js2" ? "JavaScript" : "MVEL"; + lines.push(`${statusIcon} 节点 [${node.nodeName}] ${node.label || node.displayName || ""} (${typeLabel})`); + lines.push(` 代码行数: ${node.lineCount} | 字符数: ${node.codeLength} | return 语句: ${node.hasReturn ? "有" : "无"}`); + + if (node.boundVariables.length > 0) { + lines.push(` 绑定变量: ${node.boundVariables.map((v) => `${v.key} -> ${v.upstreamTarget || "无"}`).join(", ")}`); + } + + if (node.referencedNodes.length > 0) { + lines.push( + ` 引用节点: ${node.referencedNodes.map((r) => `${r.name}${r.exists ? "" : " (❌不存在)"}`).join(", ")}` + ); + } + + if (node.issues.length === 0) { + lines.push(" 结果: 语法合规"); + } else { + for (const iss of node.issues) { + const flag = iss.level === "error" ? "❌" : "⚠️"; + const loc = iss.line ? ` L${iss.line}${iss.column ? `:${iss.column}` : ""}` : ""; + lines.push(` ${flag}${loc} [${iss.rule}] ${iss.message}`); + } + } + lines.push(""); + } + + if (report.allValid) { + lines.push("总体验证结果: 全部代码节点均通过语法与引用校验 ✅"); + } else { + lines.push(`总体验证结果: 发现 ${report.invalidCount} 个代码节点存在语法错误或悬空引用 ❌`); + } + + return { + stdout: lines.join("\n") + "\n", + stderr: "", + exitCode: report.allValid ? 0 : 1, + }; +} + +/** + * 在隔离沙箱中离线仿真运行工作流代码节点 + */ +export async function handleWorkflowEvalScript( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const isJson = booleanOption(parsed.options, ["json"]); + const filePath = stringOption(parsed.options, ["file", "path"]); + const codeInline = stringOption(parsed.options, ["code"]); + const timeoutStr = stringOption(parsed.options, ["timeout"]); + const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000; + + // 1. 获取输入参数 inputs + let inputs: Record = {}; + const rawInput = stringOption(parsed.options, ["input", "data"]); + const inputFile = stringOption(parsed.options, ["input-file"]); + + if (rawInput) { + try { + inputs = JSON.parse(rawInput); + } catch (e: any) { + return { + stdout: "", + stderr: `解析 --input JSON 参数失败: ${e.message}\n`, + exitCode: 1, + }; + } + } else if (inputFile) { + if (!fs.existsSync(inputFile)) { + return { + stdout: "", + stderr: `指定的 --input-file 不存在: ${inputFile}\n`, + exitCode: 1, + }; + } + try { + inputs = JSON.parse(fs.readFileSync(inputFile, "utf-8")); + } catch (e: any) { + return { + stdout: "", + stderr: `解析 --input-file JSON 失败: ${e.message}\n`, + exitCode: 1, + }; + } + } + + // 2. 本地文件或行内代码沙箱运行 + if (filePath || codeInline) { + let code = codeInline || ""; + if (filePath) { + if (!fs.existsSync(filePath)) { + return { + stdout: "", + stderr: `指定的脚本文件不存在: ${filePath}\n`, + exitCode: 1, + }; + } + code = fs.readFileSync(filePath, "utf-8"); + } + + const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs }); + + if (isJson) { + printJson(evalResult); + return { stdout: "", stderr: "", exitCode: evalResult.success ? 0 : 1 }; + } + + return formatEvalCliResult(evalResult, filePath ? `file: ${filePath}` : "inline-code"); + } + + // 3. 从工作流节点加载脚本并运行 + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]); + const targetNode = parsed.args[1] || stringOption(parsed.options, ["node", "target"]); + + if (!pipelineId || !targetNode) { + return { + stdout: "", + stderr: [ + "用法: hose-use workflow eval-script <节点标识> [选项]", + " 或: hose-use workflow eval-script --file= [--input='{...}'] [选项]", + " 或: hose-use workflow eval-script --code=\"\" [--input='{...}'] [选项]", + "", + "选项:", + " --input= 传递给脚本的入参 JSON 字符串", + " --input-file= 从本地 JSON 文件读取入参", + " --sample= 自动从工作流历史测试样本中提取输入(如 1、2)", + " --timeout= 沙箱执行超时时间(毫秒,默认 3000)", + " --json 输出结构化 JSON 格式结果", + "", + "示例:", + " hose-use workflow eval-script 896398895352487950 action_dx9cci", + " hose-use workflow eval-script 896398895352487950 action_dx9cci --sample=1", + " hose-use workflow eval-script 896398895352487950 action_dx9cci --input='{\"info\":{\"money\":100}}'", + " hose-use workflow eval-script --code=\"return { total: a + b };\" --input='{\"a\":10,\"b\":20}'", + ].join("\n") + "\n", + exitCode: 1, + }; + } + + const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const workflow = await getWorkflowDetail(client, pipelineId); + const located = findWorkflowTask(workflow, targetNode); + + if (!located) { + return { + stdout: "", + stderr: `在工作流 [${pipelineId}] 中未找到节点: ${targetNode}\n`, + exitCode: 1, + }; + } + + const task = located.task; + if (task.type !== "code-js2") { + if (task.type === "code") { + return { + stdout: "", + stderr: [ + `节点 [${task.name}] 是 MVEL (code) 节点。`, + "当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。", + "提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。", + ].join("\n") + "\n", + exitCode: 1, + }; + } + return { + stdout: "", + stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`, + exitCode: 1, + }; + } + + const code: string = (task as any).code || ""; + + // 如果没有显式传 input,尝试提取工作流样本数据 + if (Object.keys(inputs).length === 0) { + const sampleIdxStr = stringOption(parsed.options, ["sample"]); + try { + const sampleResult = await getWorkflowSampleData(client, pipelineId, "webhook"); + const list = sampleResult?.records || []; + if (list.length > 0) { + const idx = sampleIdxStr ? Math.max(0, parseInt(sampleIdxStr, 10) - 1) : 0; + const chosen = list[idx] || list[0]; + let samplePayload: any = chosen; + if (chosen?.dataJson) { + try { + samplePayload = JSON.parse(chosen.dataJson); + } catch { + samplePayload = chosen.dataJson; + } + } + + // 根据 code-js2 mapping 配置进行参数绑定 + const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : []; + if (mappings.length > 0) { + for (const m of mappings) { + if (m.key) { + inputs[m.key] = samplePayload; + } + } + } else { + inputs = typeof samplePayload === "object" && samplePayload !== null ? samplePayload : { sample: samplePayload }; + } + } + } catch { + // 忽略样例拉取失败,继续空入参执行 + } + } + + const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs }); + + if (isJson) { + printJson(evalResult); + return { stdout: "", stderr: "", exitCode: evalResult.success ? 0 : 1 }; + } + + const targetDesc = `节点 [${task.name}] ${task.label || task.displayName || ""} (${pipelineId})`; + return formatEvalCliResult(evalResult, targetDesc); +} + +function formatEvalCliResult( + evalResult: import("../../../domains/platform/workflow-script.js").ScriptEvalResult, + targetDesc: string +): CliResult { + const lines: string[] = []; + const statusStr = evalResult.success ? "执行成功 ✅" : "执行失败 ❌"; + + lines.push(`代码节点沙箱仿真: ${targetDesc}`); + lines.push(`状态: ${statusStr} | 耗时: ${evalResult.durationMs}ms`); + + lines.push("\n入参 (Inputs):"); + lines.push(JSON.stringify(evalResult.inputs, null, 2)); + + if (evalResult.logs.length > 0) { + lines.push("\n控制台日志 (Console Logs):"); + for (const log of evalResult.logs) { + const icon = log.level === "error" ? "🔴" : log.level === "warn" ? "🟡" : "⚪"; + lines.push(` ${icon} [${log.level}] ${log.message}`); + } + } + + if (evalResult.success) { + lines.push("\n返回值 (Return Value):"); + if (typeof evalResult.returnValue === "object" && evalResult.returnValue !== null) { + lines.push(JSON.stringify(evalResult.returnValue, null, 2)); + } else { + lines.push(String(evalResult.returnValue)); + } + lines.push(""); + } else if (evalResult.error) { + lines.push("\n异常信息 (Error Details):"); + const loc = evalResult.error.line ? ` (第 ${evalResult.error.line} 行)` : ""; + lines.push(` ${evalResult.error.name}: ${evalResult.error.message}${loc}`); + if (evalResult.error.stack) { + lines.push(`\n堆栈详情:\n${evalResult.error.stack}`); + } + lines.push(""); + } + + return { + stdout: lines.join("\n"), + stderr: "", + exitCode: evalResult.success ? 0 : 1, + }; +} diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index 470346f..235202a 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -11,6 +11,7 @@ src/domains/platform/ ├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断) ├── workflow-nodes.ts # 节点树展平、树形索引定位、声明式增删改与索引重排 SDK ├── workflow-watch.ts # 实时任务监听、增量状态跃迁追踪与执行日志流引擎 +├── workflow-script.ts# 脚本静态语法分析 (JS/MVEL)、AST 括号校验、上游依赖扫描与离线沙箱仿真引擎 └── tools.ts # MCP tool 注册 + 服务层聚合函数 ``` @@ -35,6 +36,10 @@ hose-use workflow node add --type=code-js2 --label="清洗" --code= hose-use workflow node edit <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes] hose-use workflow node rm <节点name或#序号> [--dry-run|--yes] hose-use workflow tail [--job=] [--once] [--failed-only] [--interval=2] [--json] +hose-use workflow lint-script [节点标识] [--json] +hose-use workflow lint-script --code="" [--type=code-js2|code] +hose-use workflow eval-script <节点标识> [--input='{...}'] [--sample=1] [--timeout=3000] +hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}' ``` ## 触发器分类与调测路径分支 (Path Branching) diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index 93e6909..be22053 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -942,3 +942,4 @@ export async function getWorkflowSampleData( export * from "./workflow-nodes.js"; export * from "./workflow-watch.js"; +export * from "./workflow-script.js"; diff --git a/src/domains/platform/workflow-nodes.ts b/src/domains/platform/workflow-nodes.ts index 8f64d11..44ab711 100644 --- a/src/domains/platform/workflow-nodes.ts +++ b/src/domains/platform/workflow-nodes.ts @@ -103,9 +103,12 @@ export function flattenWorkflowTaskTree(tasks: WorkflowTask[]): FlattenedWorkflo * 在任务树中按节点名称、层级编号 (如 "2.1") 或全局序号定位目标任务 */ export function findWorkflowTask( - tasks: WorkflowTask[], + tasksOrWorkflow: WorkflowTask[] | { tasks?: WorkflowTask[] }, target: string | number ): LocatedWorkflowTask | null { + const tasks = Array.isArray(tasksOrWorkflow) + ? tasksOrWorkflow + : tasksOrWorkflow?.tasks || []; const targetStr = String(target).trim(); const targetNum = Number(targetStr); const isNumeric = !Number.isNaN(targetNum) && Number.isInteger(targetNum) && targetNum > 0; diff --git a/src/domains/platform/workflow-script.test.ts b/src/domains/platform/workflow-script.test.ts new file mode 100644 index 0000000..ea63062 --- /dev/null +++ b/src/domains/platform/workflow-script.test.ts @@ -0,0 +1,189 @@ +import { describe, expect, it } from "bun:test"; +import { + hasReturnStatement, + lintJavaScriptCode, + lintMvelCode, + lintWorkflowScripts, + executeJavaScriptSandbox, +} from "./workflow-script.js"; +import type { WorkflowDetail } from "./types.js"; + +describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => { + describe("hasReturnStatement", () => { + it("identifies return statement correctly", () => { + expect(hasReturnStatement("const x = 1;\nreturn x + 2;")).toBe(true); + expect(hasReturnStatement("// return 123;\nconst x = 1;")).toBe(false); + expect(hasReturnStatement("/*\n * return false;\n */\nconst y = 2;")).toBe(false); + expect(hasReturnStatement("const x = 'returning';")).toBe(false); + }); + }); + + describe("lintJavaScriptCode", () => { + it("reports error for empty script", () => { + const res = lintJavaScriptCode(" "); + expect(res.issues.some((i) => i.rule === "empty-script")).toBe(true); + expect(res.hasReturn).toBe(false); + }); + + it("warns about missing return statement", () => { + const res = lintJavaScriptCode("const a = 1; const b = 2;"); + expect(res.issues.some((i) => i.rule === "missing-return")).toBe(true); + expect(res.hasReturn).toBe(false); + }); + + it("catches syntax errors with line numbers", () => { + const res = lintJavaScriptCode("const a = 1;\nconst b = ;\nreturn a + b;"); + expect(res.issues.some((i) => i.rule === "syntax-error" && i.level === "error")).toBe(true); + }); + + it("accepts valid JavaScript with declared bound variables", () => { + const code = ` + const filtered = items.filter(x => x.amount > 0); + return { count: filtered.length, items: filtered }; + `; + const res = lintJavaScriptCode(code, ["items"]); + expect(res.issues).toHaveLength(0); + expect(res.hasReturn).toBe(true); + }); + }); + + describe("lintMvelCode", () => { + it("detects unclosed brackets in MVEL code", () => { + const code = "var a = HashMap();\na.put('key', 123;"; + const res = lintMvelCode(code); + expect(res.issues.some((i) => i.rule === "unclosed-bracket")).toBe(true); + }); + + it("detects mismatched brackets", () => { + const code = "var a = (1 + 2]; return a;"; + const res = lintMvelCode(code); + expect(res.issues.some((i) => i.rule === "unmatched-brackets")).toBe(true); + }); + + it("flags dangling node references if node does not exist in workflow", () => { + const code = ` + var upstream = action_non_existent; + var r = new HashMap(); + r.put("data", upstream); + return r; + `; + const existing = new Set(["trigger_webhook", "action_calc"]); + const res = lintMvelCode(code, existing); + expect(res.issues.some((i) => i.rule === "dangling-node-reference")).toBe(true); + expect(res.referencedNodes).toHaveLength(1); + expect(res.referencedNodes[0].name).toBe("action_non_existent"); + expect(res.referencedNodes[0].exists).toBe(false); + }); + + it("passes clean MVEL code referencing existing nodes", () => { + const code = ` + import java.util.HashMap; + var upstream = action_calc; + var result = new HashMap(); + result.put("val", upstream); + return result; + `; + const existing = new Set(["trigger_webhook", "action_calc"]); + const res = lintMvelCode(code, existing); + expect(res.issues).toHaveLength(0); + expect(res.referencedNodes[0].exists).toBe(true); + }); + }); + + describe("lintWorkflowScripts", () => { + it("scans and reports issues across all workflow code nodes", () => { + const mockWorkflow = { + id: "pipe_lint_test", + label: "测试流程", + state: 0, + tasks: [ + { + name: "trigger_1", + type: "webhook", + label: "触发器", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }, + { + name: "action_js_bad", + type: "code-js2", + label: "语法错误JS", + groupName: "action", + orderIndex: 1, + levelIndex: [1], + status: "active", + code: "const x = ; return x;", + mapping: [], + }, + { + name: "action_mvel_good", + type: "code", + label: "正常MVEL", + groupName: "action", + orderIndex: 2, + levelIndex: [2], + status: "active", + code: "var a = trigger_1; return a;", + }, + ], + } as unknown as WorkflowDetail; + + const report = lintWorkflowScripts(mockWorkflow); + expect(report.totalCodeNodes).toBe(2); + expect(report.validCount).toBe(1); + expect(report.invalidCount).toBe(1); + expect(report.allValid).toBe(false); + + const badReport = report.reports.find((r) => r.nodeName === "action_js_bad"); + expect(badReport?.valid).toBe(false); + expect(badReport?.issues.some((i) => i.rule === "syntax-error")).toBe(true); + + const goodReport = report.reports.find((r) => r.nodeName === "action_mvel_good"); + expect(goodReport?.valid).toBe(true); + }); + }); + + describe("executeJavaScriptSandbox", () => { + it("executes code in sandbox and returns computed values", async () => { + const code = ` + console.log("Processing records:", items.length); + const total = items.reduce((sum, item) => sum + item.amount, 0); + return { total, count: items.length }; + `; + const inputs = { + items: [{ amount: 100 }, { amount: 250 }, { amount: 50 }], + }; + + const res = await executeJavaScriptSandbox(code, inputs); + expect(res.success).toBe(true); + expect(res.returnValue).toEqual({ total: 400, count: 3 }); + expect(res.logs).toHaveLength(1); + expect(res.logs[0].message).toContain("Processing records: 3"); + expect(res.durationMs).toBeGreaterThanOrEqual(0); + }); + + it("catches runtime errors and reports line number", async () => { + const code = ` + const a = 10; + const b = undefined; + return b.nonExistentField.subField; + `; + + const res = await executeJavaScriptSandbox(code, {}); + expect(res.success).toBe(false); + expect(res.error).toBeDefined(); + expect(res.error?.name).toBe("TypeError"); + expect(res.error?.message).toContain("undefined"); + expect(res.error?.line).toBe(4); + }); + + it("terminates on infinite loops via timeout", async () => { + const code = "while (true) {}"; + const res = await executeJavaScriptSandbox(code, {}, { timeoutMs: 100 }); + expect(res.success).toBe(false); + expect(res.error?.message).toContain("timed out"); + }); + }); +}); diff --git a/src/domains/platform/workflow-script.ts b/src/domains/platform/workflow-script.ts new file mode 100644 index 0000000..90acba4 --- /dev/null +++ b/src/domains/platform/workflow-script.ts @@ -0,0 +1,425 @@ +import vm from "node:vm"; +import type { WorkflowDetail, WorkflowTask } from "./types.js"; +import { flattenExecutionTree } from "./services.js"; + +export interface ScriptIssue { + level: "error" | "warning"; + line?: number; + column?: number; + message: string; + rule: string; +} + +export interface NodeScriptLintReport { + nodeName: string; + displayName?: string; + label?: string; + type: "code-js2" | "code"; + codeLength: number; + lineCount: number; + hasReturn: boolean; + boundVariables: Array<{ key: string; upstreamTarget?: string }>; + referencedNodes: Array<{ name: string; exists: boolean }>; + issues: ScriptIssue[]; + valid: boolean; +} + +export interface WorkflowScriptLintReport { + pipelineId?: string; + label?: string; + totalCodeNodes: number; + validCount: number; + invalidCount: number; + reports: NodeScriptLintReport[]; + allValid: boolean; +} + +export interface ScriptEvalLog { + level: "log" | "warn" | "error"; + message: string; + timestamp: number; +} + +export interface ScriptEvalResult { + success: boolean; + durationMs: number; + returnValue: unknown; + logs: ScriptEvalLog[]; + error?: { + name: string; + message: string; + stack?: string; + line?: number; + column?: number; + }; + inputs: Record; +} + +/** + * 检查代码中是否存在 return 关键字(排除纯注释中的 return) + */ +export function hasReturnStatement(code: string): boolean { + const lines = code.split(/\r?\n/); + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) { + continue; + } + if (/\breturn\b/.test(trimmed)) { + return true; + } + } + return false; +} + +/** + * 静态检查 JavaScript (code-js2) 语法与规范 + */ +export function lintJavaScriptCode( + code: string, + boundVariables: string[] = [] +): { issues: ScriptIssue[]; hasReturn: boolean } { + const issues: ScriptIssue[] = []; + const trimmed = code.trim(); + + if (!trimmed) { + issues.push({ + level: "error", + message: "代码节点脚本内容为空,合思调度时将报错", + rule: "empty-script", + }); + return { issues, hasReturn: false }; + } + + const hasRet = hasReturnStatement(code); + if (!hasRet) { + issues.push({ + level: "warning", + message: "脚本中缺少显式 return 语句,可能导致下游节点接收到 null 或 undefined", + rule: "missing-return", + }); + } + + // 语法验证:通过 Function 构造器做 AST 编译期语法解析 + try { + // 注入声明的参数名以验证语法合法性 + new Function(...boundVariables, code); + } catch (err: any) { + let line: number | undefined; + let column: number | undefined; + + const msg = err?.message || String(err); + // 尝试从堆栈或错误描述提取行号 + const match = err?.stack?.match(/:(\d+):(\d+)/) || msg.match(/line (\d+)/i); + if (match) { + line = Number(match[1]); + if (match[2]) column = Number(match[2]); + } + + issues.push({ + level: "error", + line, + column, + message: `JavaScript 语法错误: ${msg}`, + rule: "syntax-error", + }); + } + + return { issues, hasReturn: hasRet }; +} + +/** + * 静态检查 MVEL (code) 括号闭合与上游节点引用有效性 + */ +export function lintMvelCode( + code: string, + existingNodeNames?: Set +): { + issues: ScriptIssue[]; + referencedNodes: Array<{ name: string; exists: boolean }>; + hasReturn: boolean; +} { + const issues: ScriptIssue[] = []; + const referencedNodes: Array<{ name: string; exists: boolean }> = []; + const trimmed = code.trim(); + + if (!trimmed) { + issues.push({ + level: "error", + message: "MVEL 代码内容为空,合思调度时将报错", + rule: "empty-script", + }); + return { issues, referencedNodes, hasReturn: false }; + } + + const hasRet = hasReturnStatement(code); + if (!hasRet) { + issues.push({ + level: "warning", + message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象", + rule: "missing-return", + }); + } + + // 1. 括号与引号对称性平衡检查 + const stack: Array<{ char: string; line: number }> = []; + const lines = code.split(/\r?\n/); + + for (let l = 0; l < lines.length; l++) { + const lineText = lines[l]; + // 忽略单行注释 + const cleanLine = lineText.replace(/\/\/.*$/, ""); + + for (let c = 0; c < cleanLine.length; c++) { + const ch = cleanLine[c]; + if (ch === "{" || ch === "(" || ch === "[") { + stack.push({ char: ch, line: l + 1 }); + } else if (ch === "}" || ch === ")" || ch === "]") { + const top = stack.pop(); + const expected = ch === "}" ? "{" : ch === ")" ? "(" : "["; + if (!top || top.char !== expected) { + issues.push({ + level: "error", + line: l + 1, + column: c + 1, + message: `括号不匹配: 遇到闭合 '${ch}',但预期匹配 '${expected}'`, + rule: "unmatched-brackets", + }); + } + } + } + } + + while (stack.length > 0) { + const unclosed = stack.pop()!; + issues.push({ + level: "error", + line: unclosed.line, + message: `未闭合的括号: '${unclosed.char}' 缺少对应的闭合括号`, + rule: "unclosed-bracket", + }); + } + + // 2. 提取引用的上游节点标识并比对有效性 + // 合思节点命名规范形如 action_xxx, control_xxx, trigger_xxx + const nodeRefRegex = /\b(action_[a-zA-Z0-9_]+|control_[a-zA-Z0-9_]+|trigger_[a-zA-Z0-9_]+)\b/g; + const foundRefs = new Set(); + let match: RegExpExecArray | null; + + while ((match = nodeRefRegex.exec(code)) !== null) { + foundRefs.add(match[1]); + } + + for (const ref of foundRefs) { + const exists = existingNodeNames ? existingNodeNames.has(ref) : true; + referencedNodes.push({ name: ref, exists }); + if (!exists) { + issues.push({ + level: "error", + message: `引用的上游节点 [${ref}] 在工作流中不存在(可能已被重命名或移除)`, + rule: "dangling-node-reference", + }); + } + } + + return { issues, referencedNodes, hasReturn: hasRet }; +} + +/** + * 递归收集工作流任务树中所有节点标识 + */ +export function collectAllWorkflowNodeNames(tasks: WorkflowTask[]): Set { + const names = new Set(); + + function walk(list: WorkflowTask[]) { + for (const t of list) { + if (!t) continue; + if (t.name) names.add(t.name); + if (Array.isArray(t.tasks) && t.tasks.length > 0) { + walk(t.tasks); + } + } + } + + walk(tasks); + return names; +} + +/** + * 扫描并全面静态校验工作流中的全部代码节点(JS 与 MVEL) + */ +export function lintWorkflowScripts( + workflow: WorkflowDetail, + targetNodeQuery?: string +): WorkflowScriptLintReport { + const tasks = workflow.tasks || []; + const allNodeNames = collectAllWorkflowNodeNames(tasks); + const reports: NodeScriptLintReport[] = []; + + function traverse(list: WorkflowTask[]) { + for (const task of list) { + if (!task) continue; + + if (task.type === "code" || task.type === "code-js2") { + if (!targetNodeQuery || task.name === targetNodeQuery || task.label === targetNodeQuery || task.displayName === targetNodeQuery) { + const rawCode = (task as any).code || ""; + const lineCount = rawCode ? rawCode.split(/\r?\n/).length : 0; + const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : []; + const boundVariables: Array<{ key: string; upstreamTarget?: string }> = mappings.map((m: any) => ({ + key: m.key, + upstreamTarget: m.value, + })); + + let issues: ScriptIssue[] = []; + let hasReturn = false; + let referencedNodes: Array<{ name: string; exists: boolean }> = []; + + if (task.type === "code-js2") { + const paramNames = boundVariables.map((b) => b.key); + const res = lintJavaScriptCode(rawCode, paramNames); + issues = res.issues; + hasReturn = res.hasReturn; + } else { + const res = lintMvelCode(rawCode, allNodeNames); + issues = res.issues; + hasReturn = res.hasReturn; + referencedNodes = res.referencedNodes; + } + + const hasErrors = issues.some((i) => i.level === "error"); + + reports.push({ + nodeName: task.name, + displayName: task.displayName || undefined, + label: task.label || undefined, + type: task.type, + codeLength: rawCode.length, + lineCount, + hasReturn, + boundVariables, + referencedNodes, + issues, + valid: !hasErrors, + }); + } + } + + if (Array.isArray(task.tasks) && task.tasks.length > 0) { + traverse(task.tasks); + } + } + } + + traverse(tasks); + + const validCount = reports.filter((r) => r.valid).length; + const invalidCount = reports.length - validCount; + + return { + pipelineId: workflow.id, + label: workflow.label, + totalCodeNodes: reports.length, + validCount, + invalidCount, + reports, + allValid: invalidCount === 0, + }; +} + +/** + * 在隔离沙箱中执行 JavaScript 代码节点,仿真合思云端运行时并捕获输出与异常 + */ +export async function executeJavaScriptSandbox( + code: string, + inputs: Record = {}, + options: { timeoutMs?: number } = {} +): Promise { + const timeoutMs = options.timeoutMs ?? 3000; + const logs: ScriptEvalLog[] = []; + const start = performance.now(); + + const recordLog = (level: "log" | "warn" | "error", ...args: unknown[]) => { + const message = args + .map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a))) + .join(" "); + logs.push({ level, message, timestamp: Date.now() }); + }; + + const sandboxConsole = { + log: (...args: unknown[]) => recordLog("log", ...args), + info: (...args: unknown[]) => recordLog("log", ...args), + warn: (...args: unknown[]) => recordLog("warn", ...args), + error: (...args: unknown[]) => recordLog("error", ...args), + }; + + // 创建安全的执行沙箱上下文 + const sandboxContext = vm.createContext({ + ...inputs, + console: sandboxConsole, + Date, + Math, + JSON, + RegExp, + Array, + Object, + Number, + String, + Boolean, + parseInt, + parseFloat, + isNaN, + isFinite, + encodeURI, + decodeURI, + encodeURIComponent, + decodeURIComponent, + }); + + // 包裹立即执行函数体 (IIFE),既允许顶层 return 语句,又能直接受 vm timeout 保护 + const wrappedCode = `(function() {\n${code}\n})()`; + + try { + const returnValue = vm.runInContext(wrappedCode, sandboxContext, { + timeout: timeoutMs, + displayErrors: true, + }); + const durationMs = Number((performance.now() - start).toFixed(2)); + + return { + success: true, + durationMs, + returnValue, + logs, + inputs, + }; + } catch (err: any) { + const durationMs = Number((performance.now() - start).toFixed(2)); + const msg = err?.message || String(err); + let line: number | undefined; + let column: number | undefined; + + const stack = err?.stack || ""; + // 匹配包裹函数内的行号(第 1 行是包裹头,因此需要 -1) + const match = stack.match(/evalmachine\.:(\d+):(\d+)/); + if (match) { + const rawLine = Number(match[1]); + line = Math.max(1, rawLine - 1); + column = Number(match[2]); + } + + return { + success: false, + durationMs, + returnValue: undefined, + logs, + error: { + name: err?.name || "ExecutionError", + message: msg, + stack, + line, + column, + }, + inputs, + }; + } +}