feat(workflow): 支持节点只读透视与样本固化,规范企业切换上下文持久化

- skill: 补充终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning) 最佳实践
- config: 修复 switchCorp / enter --switch 持久化写入 defaultCorpId 与激活 stateful 模式
- workflow node: 新增 inspect (探针透视配置/样本/执行) 与 sample-save (一键固化出参至 sampleData 并刷新选择树)
- workflow test: 新增 --save-sample 选项,调测通过后自动将产生出参的节点固化为 sampleData
- parser/metadata: 注册 save-sample 选项词汇表,补充单测 workflow-node-sample-inspect.test.ts
This commit is contained in:
gitea committed 2026-11-24 11:45:46 +08:00
1 parent 5e59c835f1
commit 86a02b82b7
7 files changed
+949 -11

No files matched your search

+271 -7
View File
@@ -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<typeof getWorkflowDetail>[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 <子命令> <pipelineId> [选项]",
"",
"子命令 (工作流级别):",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" inspect <pipelineId> <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)",
" sample-save <pipelineId> <节点标识> 固化指定 Job 或最新调测出参为 sampleData",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: 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<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect <pipelineId> <nodeNameOrIndex>\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 <pipelineId> <nodeName> 固化最近调测出参");
}
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<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "用法: hose-use workflow node sample-save <pipelineId> <nodeNameOrIndex> [--job=<jobId>]\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=<id> 指定。\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,
};
}
+54 -1
View File
@@ -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=<path.json> 传入事件请求体",
"",
"通用选项:",
" --save-sample 调试通过后自动将执行节点的真实出参保存为样本数据 (sampleData)",
" --timeout=<ms> 设置轮询超时时间 (默认 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 流程调试提示]");