Merge pull request #29 from yunyingk/feat/issue-1-workflow-analysis

feat: add workflow static analysis CLI
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-05 20:34:42 +08:00
commit 9d351ed15d
7 files changed
+66 -3

No files matched your search

+2
View File
@@ -49,6 +49,7 @@ metadata:
| 跨自建应用工作流聚合检索 | `hose workflow list`, `hose platform list` | [references/workflow.md](references/workflow.md) |
| 特定任务节点扫描 (如脚本/Webhook) | `hose workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断 | `hose workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
| CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) |
@@ -100,6 +101,7 @@ hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
# 6. 服务与守护进程
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
+8
View File
@@ -73,3 +73,11 @@ hose-use workflow toggle wf_01k83y... --enable
# 停用指定工作流
hose-use workflow toggle wf_01k83y... --disable
```
## 6. 工作流静态分析 (`workflow analyze`)
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
```bash
hose-use workflow analyze wf_01k83y... --json
```
+21
View File
@@ -7,6 +7,7 @@ import { stringOption, numberOption, booleanOption } from "../parser.js";
import { createClientsForCorp } from "../helpers.js";
import { printJson, printTable, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -37,6 +38,9 @@ export async function handleWorkflowCommand(
return handleFind(parsed, runtime);
case "toggle":
return handleToggle(parsed, runtime);
case "analyze":
case "analyse":
return handleAnalyze(parsed, runtime);
default:
return {
stdout: "",
@@ -46,6 +50,23 @@ export async function handleWorkflowCommand(
}
}
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose workflow analyze <pipelineId>\n", exitCode: 1 };
const clients = await createClientsForCorp(runtime.selectedCorp!);
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
const result = analyzeWorkflow(detail);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
return { stdout: [
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
printKeyValue({ "工作流 ID": detail.id, "根节点数": result.ast.length, "依赖节点数": result.dependencies.length, "诊断数": result.diagnostics.length }),
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
].join("\n"), stderr: "", exitCode: 0 };
}
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const page = numberOption(parsed.options, ["page"]) || 1;
+1 -1
View File
@@ -118,7 +118,7 @@ export function printHelp(): string {
auth 认证与凭证管理 (login, status, refresh, import, accounts)
corps 多企业租户管理 (list, switch, current)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, toggle)
workflow 工作流管理 (list, get, find, analyze, toggle)
bill 单据与费用明细检索 (list, get <单号|ID>, refs <单号|ID>, relations <单号|ID>, attachments <单号|ID>, flow <单号|ID>, risk <单号|ID>, budget <单号|ID>, schema, link <单号|ID>)
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from "bun:test";
import { analyzeWorkflow } from "./analysis.js";
describe("Workflow static analysis", () => {
it("builds a recursive AST and extracts code references", () => {
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
});
it("reports empty scripts and branches", () => {
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
});
});
+19
View File
@@ -0,0 +1,19 @@
import type { WorkflowDetail, WorkflowTask } from "./types.js";
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
function referencesFromTask(task: WorkflowTask): string[] {
const code = typeof task.code === "string" ? task.code : "";
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
return [...new Set(values)];
}
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
}
+2 -2
View File
@@ -14,9 +14,9 @@ export const PlatformSchema = z.object({
groupType: z.string().default(""),
platformType: z.string().default(""),
source: z.string().default(""),
adminIds: z.array(z.string()).default([]),
adminIds: z.array(z.string()).nullish().transform((value) => value ?? []),
desc: z.string().nullable().optional(),
importMethod: z.array(z.string()).default([]),
importMethod: z.array(z.string()).nullish().transform((value) => value ?? []),
createTime: z.number().default(0),
updateTime: z.number().default(0),
});