Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fac81b08e8 | ||
|
|
74954b3e7a | ||
|
|
99e1e0c4b6 | ||
|
|
18da4cc066 | ||
|
|
c1e94ce63e | ||
|
|
9ca9af97e5 | ||
|
|
0768b94d65 | ||
|
|
4f0eea5725 | ||
|
|
9a9e857606 |
No files matched your search
@@ -10,6 +10,11 @@ on:
|
||||
description: Release tag already merged into main (e.g. v0.8.14)
|
||||
required: true
|
||||
type: string
|
||||
mirror_only:
|
||||
description: Reuse the existing GitHub assets and repair only the Gitea mirror
|
||||
required: false
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
concurrency:
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
@@ -27,6 +32,7 @@ jobs:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||
MIRROR_ONLY: ${{ inputs.mirror_only || false }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
@@ -47,34 +53,43 @@ jobs:
|
||||
bun run scripts/verify-release.ts "$RELEASE_TAG"
|
||||
|
||||
- name: Install dependencies
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Check committed version consistency
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run check:version
|
||||
|
||||
- name: Generate & bundle OpenAPI
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run openapi:all
|
||||
|
||||
- name: Type-check
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run check
|
||||
|
||||
- name: Test
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun test
|
||||
|
||||
- name: Compile multi-target binaries
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: |
|
||||
mkdir -p dist/bin
|
||||
node scripts/build-binary.mjs --all --release
|
||||
|
||||
- name: Verify packaged MCP entrypoint
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64
|
||||
|
||||
- name: Verify plugin bundle runtime
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: |
|
||||
bun run build:plugin
|
||||
bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
|
||||
- name: Package release archives
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y zip
|
||||
package_unix() {
|
||||
@@ -102,6 +117,7 @@ jobs:
|
||||
(cd dist/bin && sha256sum hose-use-* > checksums.txt)
|
||||
|
||||
- name: Publish GitHub Release
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
@@ -115,28 +131,40 @@ jobs:
|
||||
|
||||
- name: Publish Gitea Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
GITEA_HOST: "https://git.ying-qing.cn"
|
||||
GITEA_REPO: "gitea/hose-use"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$GITEA_TOKEN" ]; then
|
||||
if [ "${MIRROR_ONLY:-false}" = "true" ]; then
|
||||
echo "::error::GITEA_TOKEN is required to repair the mirror."
|
||||
exit 1
|
||||
fi
|
||||
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
TAG_NAME="${RELEASE_TAG}"
|
||||
if [ "${MIRROR_ONLY:-false}" = "true" ]; then
|
||||
# Preserve the published bytes and checksums; never rebuild or replace GitHub assets.
|
||||
mkdir -p dist/bin
|
||||
gh release download "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --dir dist/bin --pattern 'hose-use-*' --pattern checksums.txt
|
||||
(cd dist/bin && sha256sum --strict -c checksums.txt)
|
||||
fi
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
|
||||
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
|
||||
|
||||
echo "==> Creating release on Gitea for ${TAG_NAME}..."
|
||||
RELEASE_RESP=$(curl -s -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
|
||||
RELEASE_RESP=$(curl -sS --connect-timeout 15 --max-time 60 -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}")
|
||||
|
||||
RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty')
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
RELEASE_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
|
||||
RELEASE_ID=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
|
||||
fi
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
@@ -146,32 +174,56 @@ jobs:
|
||||
|
||||
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
|
||||
upload_asset() {
|
||||
local file="$1"
|
||||
local filename
|
||||
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
||||
filename=$(basename "$file")
|
||||
echo " [start] Uploading ${filename} to Gitea..."
|
||||
# Match GitHub --clobber when retrying the same verified release.
|
||||
existing=$(curl -fsS -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id')
|
||||
for asset_id in $existing; do
|
||||
curl -fsS -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}"
|
||||
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
||||
for attempt in 1 2 3; do
|
||||
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
|
||||
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
||||
continue
|
||||
fi
|
||||
existing=$(printf '%s' "$info" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id')
|
||||
if [ -n "$existing" ]; then
|
||||
if ! remote_hash=$(curl -fLsS --connect-timeout 15 --max-time 600 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/${GITEA_REPO}/releases/download/${TAG_NAME}/${filename}" | sha256sum | awk '{ print $1 }'); then
|
||||
continue
|
||||
fi
|
||||
if [ "$remote_hash" = "$expected_hash" ]; then
|
||||
echo " [skip] ${filename} already matches SHA-256"
|
||||
return 0
|
||||
fi
|
||||
# Match GitHub --clobber only when the existing bytes differ.
|
||||
delete_failed=0
|
||||
for asset_id in $existing; do
|
||||
curl -fsS --connect-timeout 15 --max-time 60 -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}" || delete_failed=1
|
||||
done
|
||||
if [ "$delete_failed" -ne 0 ]; then continue; fi
|
||||
fi
|
||||
if response=$(curl -fsS --connect-timeout 15 --max-time 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-F "attachment=@${file}"); then
|
||||
echo " [done] ${filename} -> $(printf '%s' "$response" | tail -n 1)"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
RESP=$(curl -fsS -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-F "attachment=@${file}")
|
||||
STATUS=$(echo "$RESP" | tail -n 1)
|
||||
echo " [done] ${filename} -> ${STATUS}"
|
||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
||||
pids=()
|
||||
failed=0
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
if [ "${#pids[@]}" -eq 2 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
pids=()
|
||||
fi
|
||||
done
|
||||
|
||||
failed=0
|
||||
for pid in "${pids[@]}"; do
|
||||
wait "$pid" || failed=1
|
||||
done
|
||||
if [ "${#pids[@]}" -gt 0 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
fi
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.14",
|
||||
"version": "0.8.15",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.14)
|
||||
# hose-use (v0.8.15)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+566
-528
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.14",
|
||||
"version": "0.8.15",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -32,6 +33,48 @@ function repository() {
|
||||
return { root, git, version: () => JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version };
|
||||
}
|
||||
|
||||
function mirrorFixture(mode: "retry" | "skip" | "concurrency", mirrorOnly = false) {
|
||||
const f = repository();
|
||||
const tools = join(f.root, "tools"), published = join(f.root, "published");
|
||||
mkdirSync(tools); mkdirSync(published); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
|
||||
const names = mode === "concurrency" ? Array.from({ length: 5 }, (_, i) => `hose-use-fixture-${i}`) : ["hose-use-linux-x64"];
|
||||
const manifest = names.map(name => {
|
||||
const data = `published bytes for ${name}`;
|
||||
writeFileSync(join(published, name), data);
|
||||
return `${createHash("sha256").update(data).digest("hex")} ${name}\n`;
|
||||
}).join("");
|
||||
writeFileSync(join(published, "checksums.txt"), manifest);
|
||||
const files = [...names, "checksums.txt"];
|
||||
if (!mirrorOnly) for (const name of files) writeFileSync(join(f.root, "dist/bin", name), readFileSync(join(published, name)));
|
||||
writeFileSync(join(f.root, "info.json"), JSON.stringify({ assets: mode === "skip" ? files.map((name, i) => ({ id: i + 1, name })) : [] }));
|
||||
writeFileSync(join(tools, "gh"), '#!/bin/sh\nprintf "%s\\n" "$*" > "$MIRROR_FIXTURE/gh.log"\ncp "$MIRROR_FIXTURE"/published/* dist/bin/\n', { mode: 0o755 });
|
||||
writeFileSync(join(tools, "curl"), `#!/bin/bash
|
||||
url=""
|
||||
for arg in "$@"; do case "$arg" in https://*) url="$arg" ;; esac; done
|
||||
case "$url" in
|
||||
*/assets?*)
|
||||
name="\${url##*name=}"
|
||||
printf 'start\\n' >> "$MIRROR_FIXTURE/events"
|
||||
if [ "$MIRROR_MODE" = "skip" ]; then printf 'unexpected upload\\n' >> "$MIRROR_FIXTURE/uploads"; exit 22; fi
|
||||
count_file="$MIRROR_FIXTURE/count-$name"
|
||||
count=0; [ ! -f "$count_file" ] || count=$(cat "$count_file")
|
||||
count=$((count + 1)); printf '%s' "$count" > "$count_file"
|
||||
if [ "$MIRROR_MODE" = "retry" ] && [ "$count" -eq 1 ]; then printf 'end\\n' >> "$MIRROR_FIXTURE/events"; exit 28; fi
|
||||
if [ "$MIRROR_MODE" = "concurrency" ]; then sleep 0.1; fi
|
||||
printf 'end\\n' >> "$MIRROR_FIXTURE/events"
|
||||
printf '{"id":100}\\nHTTP_STATUS:201'
|
||||
;;
|
||||
*/download/*) cat "$MIRROR_FIXTURE/published/\${url##*/}" ;;
|
||||
*/releases) printf '{"id":42}' ;;
|
||||
*/releases/42) cat "$MIRROR_FIXTURE/info.json" ;;
|
||||
*) exit 22 ;;
|
||||
esac
|
||||
`, { mode: 0o755 });
|
||||
const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8"));
|
||||
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
|
||||
return { ...f, files, run: () => spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0", MIRROR_ONLY: String(mirrorOnly), GITHUB_REPOSITORY: "test/repo", MIRROR_FIXTURE: f.root, MIRROR_MODE: mode }, encoding: "utf8", timeout: 5000 }) };
|
||||
}
|
||||
|
||||
describe("release preparation and publication guards", () => {
|
||||
test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => {
|
||||
const f = repository();
|
||||
@@ -93,6 +136,10 @@ describe("release preparation and publication guards", () => {
|
||||
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
|
||||
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
|
||||
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
|
||||
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
|
||||
for (const name of ["Compile multi-target binaries", "Package release archives", "Publish GitHub Release"]) {
|
||||
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
|
||||
}
|
||||
});
|
||||
|
||||
test("a failed background Gitea upload makes the Release step fail", () => {
|
||||
@@ -112,9 +159,42 @@ for arg in "$@"; do
|
||||
done
|
||||
exit 22
|
||||
`, { mode: 0o755 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 5000 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 5000 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
});
|
||||
|
||||
test("transient asset upload failures are retried", () => {
|
||||
const f = mirrorFixture("retry");
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
||||
expect(result.stdout).toContain("attempt 2/3");
|
||||
});
|
||||
|
||||
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
||||
const f = mirrorFixture("skip");
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout.match(/already matches SHA-256/g)).toHaveLength(f.files.length);
|
||||
});
|
||||
|
||||
test("mirror-only recovery downloads and verifies the existing GitHub assets", () => {
|
||||
const f = mirrorFixture("skip", true);
|
||||
expect(f.run().status).toBe(0);
|
||||
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
||||
});
|
||||
|
||||
test("asset transfers never exceed two concurrent workers", () => {
|
||||
const f = mirrorFixture("concurrency");
|
||||
expect(f.run().status).toBe(0);
|
||||
let active = 0, peak = 0;
|
||||
for (const event of readFileSync(join(f.root, "events"), "utf8").trim().split("\n")) {
|
||||
active += event === "start" ? 1 : -1;
|
||||
peak = Math.max(peak, active);
|
||||
}
|
||||
expect(active).toBe(0);
|
||||
expect(peak).toBeLessThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.14
|
||||
version: 0.8.15
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.14)
|
||||
# hose-use (v0.8.15)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -95,7 +95,8 @@ metadata:
|
||||
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job <jobId>`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断(禁用/SKIP风险/联动覆盖) | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze <pipelineId> [--fail]` | [references/workflow.md](references/workflow.md) |
|
||||
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
|
||||
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
|
||||
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) |
|
||||
@@ -202,6 +203,9 @@ hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
|
||||
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
|
||||
hose-use workflow nodes grant code-js2 # 申请开通灰度节点(支持免密模式或 --password 预留密码管控)
|
||||
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
||||
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
||||
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
|
||||
|
||||
@@ -143,17 +143,47 @@ hose-use workflow toggle wf_01k83y... --enable
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
```
|
||||
|
||||
## 7. 工作流静态分析 (`workflow analyze`)
|
||||
## 7. 工作流静态分析与发布门禁 (`workflow analyze`)
|
||||
|
||||
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。内置以下核心风险检测:
|
||||
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
|
||||
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内的创单节点(`flow-create-task`)配置了 `onError.defaultAction === "SKIP"`,且后续台账更新节点(`ekuaibao-datalink-edit`)未守卫创单节点的 `$status`,会导致创单失败时仍将台账状态改成“创建成功”;
|
||||
- `LINKAGE_PRIORITY_OVERRIDE`:创单节点绑定了 `dataLink` 台账字段,同时目标单据模板对应字段开启了自动联动赋值且优先级 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`,导致单据模板联动静默覆盖工作流显式传入的值。
|
||||
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。
|
||||
诊断结果显式划分为 **⛔ 硬门禁 (Hard Block)** 与 **💡 软建议 (Soft Advice)**:
|
||||
- **⛔ 硬门禁**(必挂致命缺陷):
|
||||
- `PERMISSION_MISSING_NODE`:使用了租户未开通的灰度节点(如未开通时的 `code-js2`);
|
||||
- `MISPLACED_FORMULA_IN_DATALINK_MAPPING`:在底层 DataLink 数据写入节点中配置了前端表单公式(如 `AddMonths(...)`);
|
||||
- `EMPTY_CODE`:代码节点缺少可执行脚本;
|
||||
- `DEADLOCK_TRIGGER_STATE_FILTER` / `DEADLOCK_CONDITION_STATE_FILTER`:单据状态误配置导致事件静默丢弃或条件恒假;
|
||||
- `INVALID_ACTION_ENUM_TEXT_VALUE`:枚举字段误配纯中文文本导致无法匹配。
|
||||
- **💡 软建议**(最佳实践与潜在风险):
|
||||
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
|
||||
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内创单节点配置了 SKIP 跳过,但后续节点未校验前序状态;
|
||||
- `LINKAGE_PRIORITY_OVERRIDE`:单据模板联动优先级高于手工/API 传入。
|
||||
|
||||
```bash
|
||||
# 1. 静态分析指定工作流(直观展示硬门禁与软建议分类表格)
|
||||
hose-use workflow analyze 886351399301758976
|
||||
|
||||
# 2. 作为 CI/CD 或脚本门禁运行(存在硬门禁时 exitCode = 2 阻断发布)
|
||||
hose-use workflow analyze 886351399301758976 --fail
|
||||
|
||||
# 3. 输出结构化 JSON
|
||||
hose-use workflow analyze 886351399301758976 --json
|
||||
```
|
||||
|
||||
## 7.1 企业已开通节点探针与灰度开通 (`workflow nodes`)
|
||||
|
||||
合思微前端(Piper)仅向开通了权限的租户展示对应节点,未开通节点在界面中隐身且运行时直接报错:
|
||||
|
||||
```bash
|
||||
# 1. 查看当前企业已开通的节点字典(动作/控制/触发)
|
||||
hose-use workflow nodes
|
||||
|
||||
# 2. 与官方全量 108 个灰度节点清单进行完整对照
|
||||
hose-use workflow nodes --all
|
||||
|
||||
# 3. 申请开通灰度节点(支持节点拼音与中文名)
|
||||
hose-use workflow nodes grant code-js2
|
||||
```
|
||||
|
||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||
|
||||
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.14",
|
||||
"version": "0.8.15",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.14
|
||||
version: 0.8.15
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
@@ -205,6 +205,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"diff-job": "对比两次执行的节点分支与报错发散点",
|
||||
"test": "端到端一键调试单据(替代前端手工调测)",
|
||||
"node": "声明式节点编排与增删改 (list|get|add|edit|rm)",
|
||||
"nodes": "查询企业已开通工作流节点字典或开通灰度节点 (list|grant)",
|
||||
"tail": "实时监听任务派发与节点执行日志流 (watch|follow)",
|
||||
"create": "从零新建工作流草稿",
|
||||
"copy": "复制克隆工作流",
|
||||
@@ -271,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
},
|
||||
flags: { ...flagList("allow-prod allow-production auto-publish autoPublish detail empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a after app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId l label log logs max-jobs maxJobs n name node node-id nodeId output output-file outputFile p page page-size pageSize parent parent-id parentId path payload pipeline pipeline-id pipelineId platform-id platformId record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type 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 has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a admin-key adminKey after app-id appId b bill body c code code-file container count d data desc description 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 keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform-id platformId pwd query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source 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": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "ID01rJEL708iTI",
|
||||
name: "浙江麦瑞克科技有限公司",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
staffId: "ID01rJEL708iTI:RkQ8G8L_eMhI00",
|
||||
appKey: "test-key",
|
||||
appSecurity: "test-security",
|
||||
},
|
||||
};
|
||||
|
||||
const mockRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
};
|
||||
|
||||
describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
delete process.env.HOSE_ADMIN_PASSWORD;
|
||||
});
|
||||
|
||||
it("workflow nodes: 成功探查当前企业已开通节点字典", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["http", "code", "condition", "clock"]),
|
||||
actionNodes: [
|
||||
{ name: "http节点", type: "http" },
|
||||
{ name: "代码节点", type: "code" },
|
||||
],
|
||||
controlNodes: [{ name: "条件节点", type: "condition" }],
|
||||
triggerNodes: [{ name: "定时触发", type: "clock" }],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["workflow", "nodes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前企业已开通工作流节点字典 [浙江麦瑞克科技有限公司]");
|
||||
expect(res.stdout).toContain("代码节点 (code)");
|
||||
expect(res.stdout).toContain("已开通节点数");
|
||||
});
|
||||
|
||||
it("workflow nodes --all: 成功输出与 108 个灰度节点对照表", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["code", "http"]),
|
||||
actionNodes: [{ name: "代码节点", type: "code" }],
|
||||
controlNodes: [],
|
||||
triggerNodes: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: [],
|
||||
options: { all: true },
|
||||
raw: ["workflow", "nodes", "--all"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("工作流节点字典与灰度开通对照 [浙江麦瑞克科技有限公司]");
|
||||
expect(res.stdout).toContain("code-js2");
|
||||
expect(res.stdout).toContain("🔒 未开通");
|
||||
expect(res.stdout).toContain("✅ 已开通");
|
||||
});
|
||||
|
||||
it("workflow nodes --json: 输出机器可读的结构化 JSON", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["code"]),
|
||||
actionNodes: [{ name: "代码节点", type: "code" }],
|
||||
controlNodes: [],
|
||||
triggerNodes: [],
|
||||
})
|
||||
);
|
||||
|
||||
const jsonRuntime: CliRuntime = { ...mockRuntime, jsonMode: true };
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["workflow", "nodes", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsedJson = JSON.parse(res.stdout);
|
||||
expect(parsedJson.corpId).toBe("ID01rJEL708iTI");
|
||||
expect(parsedJson.totalGranted).toBe(1);
|
||||
expect(parsedJson.grantedTypes).toContain("code");
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 免密模式下成功发起灰度节点开通", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: ["grant", "code-js2"],
|
||||
options: {},
|
||||
raw: ["workflow", "nodes", "grant", "code-js2"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("灰度节点开通结果 [浙江麦瑞克科技有限公司]");
|
||||
expect(res.stdout).toContain("新开通成功");
|
||||
expect(res.stdout).toContain("code-js2");
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
token: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 节点名称自动中文归一化 (如 'JS节点(新)' 映射为 'code-js2')", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "nodes",
|
||||
args: ["grant", "JS节点(新)"],
|
||||
options: {},
|
||||
raw: ["workflow", "nodes", "grant", "JS节点(新)"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 管理员密码保护预留生效 (未提供密码或密码错误被拒绝)", async () => {
|
||||
process.env.HOSE_ADMIN_PASSWORD = "secret_admin_pass";
|
||||
|
||||
// 1. 无密码调用被拒绝
|
||||
expect(
|
||||
services.grantWorkflowNodes(mockCorp, {
|
||||
nodes: ["code-js2"],
|
||||
})
|
||||
).rejects.toThrow("管理员保护");
|
||||
|
||||
// 2. 错误密码调用被拒绝
|
||||
expect(
|
||||
services.grantWorkflowNodes(mockCorp, {
|
||||
nodes: ["code-js2"],
|
||||
password: "wrong_password",
|
||||
})
|
||||
).rejects.toThrow("管理员保护");
|
||||
|
||||
// 3. 正确密码调用放行
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "开通成功",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
const result = await services.grantWorkflowNodes(mockCorp, {
|
||||
nodes: ["code-js2"],
|
||||
password: "secret_admin_pass",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
expect(grantSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("workflow analyze: 显式输出硬门禁与软建议边界,且支持 --fail 退出码门禁", async () => {
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
ekbClient: {},
|
||||
easoClient: {},
|
||||
} as any),
|
||||
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any),
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValue({
|
||||
id: "wf-gate-test",
|
||||
label: "门禁测试流程",
|
||||
state: 0,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "bad_node",
|
||||
type: "code-js2",
|
||||
label: "未开通JS2节点",
|
||||
code: "return 1;",
|
||||
},
|
||||
],
|
||||
} as any),
|
||||
spyOn(services, "getWorkflowAvailableNodes").mockResolvedValue({
|
||||
allTypes: new Set(["http", "code"]),
|
||||
catalog: { action: [], control: [], trigger: [] },
|
||||
} as any)
|
||||
);
|
||||
|
||||
// 1. 常规运行(无 --fail):展示门禁裁决,exitCode 为 0
|
||||
const normalRes = await handleWorkflowCommand(
|
||||
{
|
||||
action: "analyze",
|
||||
args: ["wf-gate-test"],
|
||||
options: {},
|
||||
raw: ["workflow", "analyze", "wf-gate-test"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(normalRes.exitCode).toBe(0);
|
||||
expect(normalRes.stdout).toContain("门禁裁决");
|
||||
expect(normalRes.stdout).toContain("硬门禁数");
|
||||
expect(normalRes.stdout).toContain("软建议数");
|
||||
expect(normalRes.stdout).toContain("⛔ 硬门禁");
|
||||
expect(normalRes.stdout).toContain("💡 软建议");
|
||||
expect(normalRes.stdout).toContain("PERMISSION_MISSING_NODE");
|
||||
|
||||
// 2. 带 --fail 运行:检测到硬门禁,exitCode 为 2
|
||||
const failRes = await handleWorkflowCommand(
|
||||
{
|
||||
action: "analyze",
|
||||
args: ["wf-gate-test"],
|
||||
options: { fail: true },
|
||||
raw: ["workflow", "analyze", "wf-gate-test", "--fail"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(failRes.exitCode).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import { getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import { getWorkflowDetail, getWorkflowAvailableNodes } from "../../../domains/platform/services.js";
|
||||
import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../../domains/platform/workflow/analysis/index.js";
|
||||
import { getFormSpecification } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
@@ -30,20 +30,53 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
})
|
||||
);
|
||||
}
|
||||
const result = analyzeWorkflow(detail, { specifications });
|
||||
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]);
|
||||
let availableNodeTypes: Set<string> | undefined;
|
||||
try {
|
||||
const available = await getWorkflowAvailableNodes(client);
|
||||
availableNodeTypes = available.allTypes;
|
||||
} catch {
|
||||
// 离线或受限网络环境下忽略探针失败
|
||||
}
|
||||
|
||||
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes });
|
||||
const failOnAlert = booleanOption(parsed.options, ["fail", "fail-on-alert", "failOnAlert"]);
|
||||
const exitCode = failOnAlert && !result.summary.passed ? 2 : 0;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode };
|
||||
|
||||
const gateDecision =
|
||||
result.summary.hardBlocks > 0
|
||||
? `❌ 发现 ${result.summary.hardBlocks} 项硬门禁阻断 (禁止发布上线)`
|
||||
: result.summary.softAdvices > 0
|
||||
? `⚠️ 硬门禁全通过,存在 ${result.summary.softAdvices} 项优化建议`
|
||||
: "✅ 全部门禁通过,可安全发布上线";
|
||||
|
||||
const diagnosticRows = result.diagnostics.map((item) => [
|
||||
item.category === "hard_block" ? "⛔ 硬门禁" : "💡 软建议",
|
||||
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,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"根节点数": 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 };
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"门禁裁决": gateDecision,
|
||||
"硬门禁数": `${result.summary.hardBlocks} 项 (致命配置/无权限/崩溃)`,
|
||||
"软建议数": `${result.summary.softAdvices} 项 (规范与最佳实践)`,
|
||||
"根节点数": result.ast.length,
|
||||
"依赖节点数": result.dependencies.length,
|
||||
}),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断列表 (硬门禁 ⛔ / 软建议 💡):\n${diagnosticRows.length ? printTable(["分类", "级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
@@ -6,20 +6,50 @@ import {
|
||||
addWorkflowTask,
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
getWorkflowAvailableNodes,
|
||||
grantWorkflowNodes,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import {
|
||||
GRAY_NODES_CATALOG,
|
||||
findGrayNode,
|
||||
} from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createPiperClientForCorp } from "../../helpers.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
|
||||
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isPluralNodes = parsed.action === "nodes";
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
|
||||
// 1. 企业级节点字典与灰度开通快捷分支
|
||||
if (firstArg === "grant" || firstArg === "open") {
|
||||
return handleGrantNodes(parsed, runtime);
|
||||
}
|
||||
if (
|
||||
firstArg === "available" ||
|
||||
firstArg === "list-available" ||
|
||||
firstArg === "catalog" ||
|
||||
firstArg === "probe"
|
||||
) {
|
||||
return handleListAvailableNodes(parsed, runtime);
|
||||
}
|
||||
|
||||
// 2. 如果是 `hose-use workflow nodes`(复数)且没有指定具体的 pipelineId
|
||||
const secondArg = parsed.args[1];
|
||||
const isSecondArgPipelineId = secondArg && /^\d{10,}$/.test(secondArg.trim());
|
||||
if (isPluralNodes && (!firstArg || ((firstArg === "list" || firstArg === "ls") && !isSecondArgPipelineId && !parsed.options.id && !parsed.options.pipelineId))) {
|
||||
return handleListAvailableNodes(parsed, runtime);
|
||||
}
|
||||
|
||||
let subAction = "list";
|
||||
let pipelineId = "";
|
||||
let nodeTarget = "";
|
||||
@@ -43,19 +73,22 @@ export async function handleNodeCommand(
|
||||
stderr: [
|
||||
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
|
||||
"",
|
||||
"子命令:",
|
||||
"子命令 (工作流级别):",
|
||||
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
|
||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||
"",
|
||||
"子命令 (企业灰度节点级别):",
|
||||
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
||||
" nodes grant <type...> 为当前企业开通灰度节点",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow nodes",
|
||||
" hose-use workflow nodes --all",
|
||||
" hose-use workflow nodes grant code-js2",
|
||||
" hose-use workflow node list 896398895352487950",
|
||||
" hose-use workflow node get 896398895352487950 action_dx9cci",
|
||||
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code='return items;' --yes",
|
||||
" hose-use workflow node edit 896398895352487950 action_dx9cci --label='新清洗逻辑' --yes",
|
||||
" hose-use workflow node rm 896398895352487950 action_dx9cci --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
@@ -426,3 +459,164 @@ async function handleRemoveNode(
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 企业可用节点字典与灰度开通 ──────────────────────────────────────────────
|
||||
|
||||
async function handleListAvailableNodes(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]) || corp.id;
|
||||
const piperClient = await createPiperClientForCorp(corp, platformId);
|
||||
const available = await getWorkflowAvailableNodes(piperClient);
|
||||
|
||||
const showAll = Boolean(parsed.options.all || parsed.options.compare || parsed.options.diff);
|
||||
const filterKw = (
|
||||
parsed.args[1] ||
|
||||
stringOption(parsed.options, ["keyword", "query", "filter"]) ||
|
||||
""
|
||||
).toLowerCase();
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const output = {
|
||||
corpId: corp.corpId || corp.id,
|
||||
corpName: corp.name,
|
||||
totalGranted: available.allTypes.size,
|
||||
actionNodesCount: available.actionNodes.length,
|
||||
controlNodesCount: available.controlNodes.length,
|
||||
triggerNodesCount: available.triggerNodes.length,
|
||||
grantedTypes: Array.from(available.allTypes).sort(),
|
||||
catalog: {
|
||||
action: available.actionNodes.map((n) => ({ name: n.name, type: n.type })),
|
||||
control: available.controlNodes.map((n) => ({ name: n.name, type: n.type })),
|
||||
trigger: available.triggerNodes.map((n) => ({ name: n.name, type: n.type })),
|
||||
},
|
||||
};
|
||||
return {
|
||||
stdout: printJson(output, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 渲染人类友好视图
|
||||
if (showAll) {
|
||||
// 对照全量 108 个灰度节点
|
||||
const rows = GRAY_NODES_CATALOG.filter((item) => {
|
||||
if (!filterKw) return true;
|
||||
return (
|
||||
item.displayName.toLowerCase().includes(filterKw) ||
|
||||
item.type.toLowerCase().includes(filterKw)
|
||||
);
|
||||
}).map((item) => {
|
||||
const isGranted = available.allTypes.has(item.type.toLowerCase());
|
||||
const statusText = isGranted ? "✅ 已开通" : "🔒 未开通";
|
||||
return [item.displayName, item.type, item.category || "action", statusText];
|
||||
});
|
||||
|
||||
const output = [
|
||||
`====== 工作流节点字典与灰度开通对照 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"当前企业": `${corp.name} (${corp.corpId || corp.id})`,
|
||||
"已开通节点总数": `${available.allTypes.size} 个`,
|
||||
"灰度对照清单": `${GRAY_NODES_CATALOG.length} 个`,
|
||||
}),
|
||||
"",
|
||||
printTable(["显示名称", "节点类型 (type)", "分组", "开通状态"], rows),
|
||||
"",
|
||||
"提示:",
|
||||
" - 使用 hose-use workflow nodes grant <type> 开通灰度节点 (如: hose-use workflow nodes grant code-js2)",
|
||||
].join("\n");
|
||||
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 简要分组视图
|
||||
const actionList = available.actionNodes.map((n) => `${n.name} (${n.type})`).join("、");
|
||||
const controlList = available.controlNodes.map((n) => `${n.name} (${n.type})`).join("、");
|
||||
const triggerList = available.triggerNodes.map((n) => `${n.name} (${n.type})`).join("、");
|
||||
|
||||
const output = [
|
||||
`====== 当前企业已开通工作流节点字典 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"当前企业": `${corp.name} (${corp.corpId || corp.id})`,
|
||||
"已开通节点数": `${available.allTypes.size} 个 (动作 ${available.actionNodes.length}, 控制 ${available.controlNodes.length}, 触发 ${available.triggerNodes.length})`,
|
||||
}),
|
||||
"",
|
||||
`⚡ 触发器节点 (${available.triggerNodes.length}):`,
|
||||
triggerList || "无",
|
||||
"",
|
||||
`⚙️ 动作节点 (${available.actionNodes.length}):`,
|
||||
actionList || "无",
|
||||
"",
|
||||
`🔀 控制流程节点 (${available.controlNodes.length}):`,
|
||||
controlList || "无",
|
||||
"",
|
||||
"提示:",
|
||||
" - 添加 --all 参数可查看与官方 108 个灰度节点清单的完整开通对照表",
|
||||
" - 使用 hose-use workflow nodes grant <type...> 开通新灰度节点 (如: hose-use workflow nodes grant code-js2)",
|
||||
].join("\n");
|
||||
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGrantNodes(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const rawNodes = parsed.args.slice(1);
|
||||
const optionNodes = stringOption(parsed.options, ["nodes", "node", "type", "types"]);
|
||||
const targetNodes: string[] = [];
|
||||
|
||||
if (optionNodes) {
|
||||
targetNodes.push(...optionNodes.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
for (const arg of rawNodes) {
|
||||
if (arg && !arg.startsWith("-")) {
|
||||
targetNodes.push(...arg.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
}
|
||||
|
||||
if (targetNodes.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误: 请指定要开通的节点类型 (如: hose-use workflow nodes grant code-js2 或 dify)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const password = stringOption(parsed.options, ["password", "pwd", "admin-key"]);
|
||||
|
||||
const result = await grantWorkflowNodes(corp, {
|
||||
nodes: targetNodes,
|
||||
password,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 灰度节点开通结果 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"申请开通节点": targetNodes.join(", "),
|
||||
"新开通成功": result.saved.length ? result.saved.join(", ") : "无 (已处于开通状态)",
|
||||
"跳过(已开通)": result.skipped.length ? result.skipped.join(", ") : "无",
|
||||
"网关反馈": result.rawMessage || "处理成功",
|
||||
}),
|
||||
"",
|
||||
"✅ 节点权限已生效!工作流设计器与 hose-use workflow analyze 将立即支持该节点。",
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import ky, { KyInstance } from "ky";
|
||||
import { AuthenticationError, BusinessError, EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
WorkflowExecutionPageSchema,
|
||||
WorkflowExecutionLogSchema,
|
||||
WorkflowDslSchema,
|
||||
WorkflowDslCatalogSchema,
|
||||
StaffSchema,
|
||||
WebhookInfoSchema,
|
||||
WorkflowSampleDataSchema,
|
||||
@@ -325,7 +326,34 @@ export async function listDsl(
|
||||
client: KyInstance
|
||||
): Promise<import("./types.js").WorkflowDsl[]> {
|
||||
const response = await client.get("api/easo/dsl/all");
|
||||
return unwrap(response, z.array(WorkflowDslSchema));
|
||||
const raw = await response.json<any>();
|
||||
const payload = raw?.data ?? raw;
|
||||
if (Array.isArray(payload)) {
|
||||
return payload.map((item) => WorkflowDslSchema.parse(item));
|
||||
}
|
||||
// 若是对象结构,将各分类下的 items 拍平返回
|
||||
const allItems: any[] = [
|
||||
...(payload?.action || []),
|
||||
...(payload?.control || []),
|
||||
...(payload?.trigger || []),
|
||||
];
|
||||
return allItems.map((item) => WorkflowDslSchema.parse(item));
|
||||
}
|
||||
|
||||
export async function listDslCatalog(
|
||||
client: KyInstance
|
||||
): Promise<import("./types.js").WorkflowDslCatalog> {
|
||||
const response = await client.get("api/easo/dsl/all");
|
||||
const raw = await response.json<any>();
|
||||
const payload = raw?.data ?? raw;
|
||||
if (Array.isArray(payload)) {
|
||||
return {
|
||||
action: payload,
|
||||
control: [],
|
||||
trigger: [],
|
||||
};
|
||||
}
|
||||
return WorkflowDslCatalogSchema.parse(payload || {});
|
||||
}
|
||||
|
||||
// ── 员工列表(Piper)──────────────────────────────────────────────────────────
|
||||
@@ -429,4 +457,39 @@ export async function getWorkflowEnumOptions(
|
||||
return unwrap(response, z.array(WorkflowEnumItemSchema));
|
||||
}
|
||||
|
||||
// ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function grantWorkflowNodesApi(options: {
|
||||
token: string;
|
||||
corpId: string;
|
||||
nodes: string[];
|
||||
baseUrl?: string;
|
||||
}): Promise<import("./types.js").GrantWorkflowNodesResult> {
|
||||
const payload = {
|
||||
token: options.token,
|
||||
corpId: options.corpId,
|
||||
nodes: options.nodes.join(","),
|
||||
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await ky.post("https://d9jxeccs5j.sealosgzg.site/hose-workflow-node", {
|
||||
json: payload,
|
||||
timeout: 30000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const data = json?.data ?? {};
|
||||
return {
|
||||
success: Boolean(json?.success ?? true),
|
||||
saved: Array.isArray(data.saved) ? data.saved : [],
|
||||
skipped: Array.isArray(data.skipped) ? data.skipped : [],
|
||||
rawMessage: json?.msg || json?.message || "",
|
||||
};
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
throw new EkbApiError(`灰度节点开通网关调用失败: ${message}`, "GATEWAY_ERROR", 502);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import * as api from "./api.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import { PermissionError, ValidationError } from "../../core/errors.js";
|
||||
import { explainConditionBranches } from "./workflow/branch/index.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
import {
|
||||
@@ -70,7 +70,12 @@ export async function copyWorkflow(
|
||||
(cloned.tasks[0] as any).urlPath = crypto.randomUUID();
|
||||
delete (cloned.tasks[0] as any).sampleId;
|
||||
}
|
||||
return api.copyWorkflow(client, pipelineId, cloned);
|
||||
const result = await api.copyWorkflow(client, pipelineId, cloned);
|
||||
if (options.label && result.label !== options.label) {
|
||||
result.label = options.label;
|
||||
return api.updateWorkflow(client, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export interface CreateWorkflowOptions {
|
||||
@@ -977,4 +982,74 @@ export async function resolveWorkflowEnumOptions(
|
||||
return [];
|
||||
}
|
||||
|
||||
// ── 工作流企业可用节点探针与灰度开通 ──────────────────────────────────────────
|
||||
|
||||
export async function getWorkflowAvailableNodes(
|
||||
client: KyInstance
|
||||
): Promise<import("./types.js").AvailableWorkflowNodes> {
|
||||
const catalog = await api.listDslCatalog(client);
|
||||
const allTypes = new Set<string>();
|
||||
|
||||
for (const item of catalog.action) {
|
||||
if (item.type) allTypes.add(item.type);
|
||||
}
|
||||
for (const item of catalog.control) {
|
||||
if (item.type) allTypes.add(item.type);
|
||||
}
|
||||
for (const item of catalog.trigger) {
|
||||
if (item.type) allTypes.add(item.type);
|
||||
}
|
||||
|
||||
return {
|
||||
allTypes,
|
||||
actionNodes: catalog.action,
|
||||
controlNodes: catalog.control,
|
||||
triggerNodes: catalog.trigger,
|
||||
};
|
||||
}
|
||||
|
||||
export async function grantWorkflowNodes(
|
||||
corp: CorpConfig,
|
||||
options: import("./types.js").GrantWorkflowNodesOptions
|
||||
): Promise<import("./types.js").GrantWorkflowNodesResult> {
|
||||
if (!options.nodes || options.nodes.length === 0) {
|
||||
throw new ValidationError("必须指定至少一个需要开通的节点名称或类型");
|
||||
}
|
||||
|
||||
// 1. 管理员密码保护预留设计
|
||||
const adminPassword = process.env.HOSE_ADMIN_PASSWORD;
|
||||
if (adminPassword) {
|
||||
if (!options.password || options.password !== adminPassword) {
|
||||
throw new PermissionError(
|
||||
"灰度节点开通功能已启用管理员保护,请通过 --password 或配置输入正确的管理员密码"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type)
|
||||
const { findGrayNode } = await import("./workflow/nodes/gray-nodes-catalog.js");
|
||||
const normalizedNodes = options.nodes.map((node) => {
|
||||
const matched = findGrayNode(node);
|
||||
return matched ? matched.type : node.trim();
|
||||
});
|
||||
|
||||
const token = corp.credentials?.accessToken;
|
||||
const corpId = corp.corpId || corp.credentials?.corpId || corp.id;
|
||||
const baseUrl = corp.baseUrl;
|
||||
|
||||
if (!token) {
|
||||
throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请");
|
||||
}
|
||||
|
||||
// 3. 调用开通 API
|
||||
const result = await api.grantWorkflowNodesApi({
|
||||
token,
|
||||
corpId,
|
||||
nodes: normalizedNodes,
|
||||
baseUrl,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export * from "./workflow/index.js";
|
||||
@@ -269,20 +269,31 @@ export const WorkflowDetailSchema = z.object({
|
||||
label: z.string().default(""),
|
||||
desc: z.string().nullable().optional(),
|
||||
customDesc: z.string().nullable().optional(),
|
||||
state: z.number().default(0),
|
||||
debugState: z.number().default(0),
|
||||
runTimes: z.number().default(0),
|
||||
errorTimes: z.number().default(0),
|
||||
state: z.coerce.number().default(0),
|
||||
debugState: z.coerce.number().default(0),
|
||||
runTimes: z.coerce.number().default(0),
|
||||
errorTimes: z.coerce.number().default(0),
|
||||
updateTime: z.string().default(""),
|
||||
updateUser: z.string().nullable().optional(),
|
||||
staffName: z.string().nullable().optional(),
|
||||
version: z.string().default(""),
|
||||
dataLimit: z.number().default(20),
|
||||
source: z.number().default(0),
|
||||
dataLimit: z.coerce.number().default(20),
|
||||
source: z.coerce.number().default(0),
|
||||
queueJobs: z.boolean().default(false),
|
||||
tasksVersion: z.number().default(0),
|
||||
tasksVersion: z.coerce.number().default(0),
|
||||
tasks: z.array(WorkflowTaskSchema).default([]),
|
||||
alarm: WorkflowAlarmSchema.optional(),
|
||||
alarm: z.union([
|
||||
WorkflowAlarmSchema,
|
||||
z.string().transform((val) => {
|
||||
try {
|
||||
const parsed = JSON.parse(val);
|
||||
return WorkflowAlarmSchema.safeParse(parsed).data ?? undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}),
|
||||
z.null(),
|
||||
]).optional(),
|
||||
inputs: z.array(z.object({ key: z.string(), value: z.any() })).optional(),
|
||||
"$snapshot": z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
}).passthrough();
|
||||
@@ -422,12 +433,58 @@ export const WorkflowExecutionPageSchema = z
|
||||
// ── DSL 配置 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const WorkflowDslSchema = z.object({
|
||||
id: z.string(),
|
||||
id: z.string().optional(),
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
config: z.record(z.string(), z.any()).default({}),
|
||||
});
|
||||
|
||||
export const WorkflowNodeDefinitionSchema = z
|
||||
.object({
|
||||
id: z.string().nullable().optional(),
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
groupName: z.string().nullable().optional(),
|
||||
icon: z.string().nullable().optional(),
|
||||
iconColor: z.string().nullable().optional(),
|
||||
remark: z.string().nullable().optional(),
|
||||
platform: z.string().nullable().optional(),
|
||||
version: z.number().nullable().optional(),
|
||||
$json: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type WorkflowNodeDefinition = z.infer<typeof WorkflowNodeDefinitionSchema>;
|
||||
|
||||
export const WorkflowDslCatalogSchema = z
|
||||
.object({
|
||||
action: z.array(WorkflowNodeDefinitionSchema).default([]),
|
||||
control: z.array(WorkflowNodeDefinitionSchema).default([]),
|
||||
trigger: z.array(WorkflowNodeDefinitionSchema).default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type WorkflowDslCatalog = z.infer<typeof WorkflowDslCatalogSchema>;
|
||||
|
||||
export interface AvailableWorkflowNodes {
|
||||
allTypes: Set<string>;
|
||||
actionNodes: WorkflowNodeDefinition[];
|
||||
controlNodes: WorkflowNodeDefinition[];
|
||||
triggerNodes: WorkflowNodeDefinition[];
|
||||
}
|
||||
|
||||
export interface GrantWorkflowNodesOptions {
|
||||
nodes: string[];
|
||||
password?: string;
|
||||
}
|
||||
|
||||
export interface GrantWorkflowNodesResult {
|
||||
success: boolean;
|
||||
saved: string[];
|
||||
skipped: string[];
|
||||
rawMessage: string;
|
||||
}
|
||||
|
||||
// ── 员工 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const StaffSchema = z.object({
|
||||
|
||||
@@ -18,6 +18,8 @@ hose-use workflow debug <pipelineId> --flow=<单号> --yes
|
||||
hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flowform] [--file=<JSON模板>] [--dry-run|--yes]
|
||||
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
||||
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
||||
hose-use workflow nodes [list] [--all]
|
||||
hose-use workflow nodes grant <type...> [--password=<pwd>]
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||
@@ -72,3 +74,57 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
|
||||
## 企业可用节点探针与灰度开通(Nodes Probe & Grant)
|
||||
|
||||
合思微前端(Piper)在进入流程设计器与渲染节点级联选择器时,调用 `GET /api/easo/dsl/all` 获取当前租户真实已开通的节点字典(Action、Control、Trigger):
|
||||
- 前端级联选择器仅会渲染当前企业已开通的节点,未开通节点在界面中完全隐身;
|
||||
- 若工作流在后端配置了当前租户未开通的节点类型,执行 `hose-use workflow analyze` 会触发 `PERMISSION_MISSING_NODE` 阻止性诊断并提示开通命令;
|
||||
- 执行 `hose-use workflow nodes` 查看当前租户已开通的节点字典;
|
||||
- 执行 `hose-use workflow nodes --all` 查看当前企业与官方全量 108 个灰度节点清单的开通状态对照;
|
||||
- 执行 `hose-use workflow nodes grant <type...>` 申请开通灰度节点(内置管理员密码预留设计:未配置环境变量 `HOSE_ADMIN_PASSWORD` 时为免密便捷模式;配置后强制要求 `--password` 授权)。
|
||||
|
||||
## 静态分析器:诊断边界显式化(硬门禁 vs 软建议)
|
||||
|
||||
`hose-use workflow analyze <pipelineId>` 将诊断项明确划分为 **硬门禁(Hard Block)** 与 **软建议(Soft Advice)** 两大明确边界,支持使用 `--fail` 或 `--fail-on-alert` 接入 CI/CD 发布门禁(存在硬门禁时 exitCode = 2):
|
||||
|
||||
### ⛔ 硬门禁(Hard Block - 导致流程崩溃或死锁的致命配置)
|
||||
|
||||
| 规则代码 (`code`) | 级别 | 触发根因与运行后果 | 修复措施与建议 |
|
||||
|---|---|---|---|
|
||||
| `PERMISSION_MISSING_NODE` | error | 工作流使用了当前租户尚未开通的灰度节点(如 `code-js2`、AI节点等),运行时合思引擎直接阻断抛错 | 使用 `hose-use workflow nodes grant <type>` 开通权限,或替换为已开通节点 |
|
||||
| `MISPLACED_FORMULA_IN_DATALINK_MAPPING` | error | 在 DataLink 业务对象写入/修改节点的字段映射中填入了表单公式(如 `AddMonths(...)`),底层写入引擎无法求值导致 `ParseException` | 前置增加【代码节点】(JS/MVEL)计算变量,在 DataLink 节点中引用计算结果 |
|
||||
| `EMPTY_CODE` | error | 代码节点(`code` / `code-js2`)缺少可执行脚本,流程执行到该节点时空指针或停止流转 | 补充清洗/计算脚本或移除无用代码节点 |
|
||||
| `DEADLOCK_TRIGGER_STATE_FILTER` | error | 触发器节点配置了 `state` 单据审批状态过滤(如 `REJECTED` / `被驳回`),合思出站事件初始阶段状态为空或动作事件,导致事件 100% 被静默丢弃,流程永久不触发 | 移除 `state` 过滤,改用通知类型(`action`)过滤或后置条件节点 |
|
||||
| `DEADLOCK_CONDITION_STATE_FILTER` | error | 条件节点使用单据审批状态 `state` 匹配中文 `被驳回/审批驳回`,动作事件载荷不满足中文匹配,判定恒为 false | 改用通知类型 `action` 匹配宏枚举(如 `flow.rejected`) |
|
||||
| `INVALID_ACTION_ENUM_TEXT_VALUE` | error | 条件节点中通知类型 `action` 配置了纯中文文本比对值,Piper 底层使用英文枚举 Code 比对,导致恒不匹配 | 在条件节点右侧下拉列表中选择标准枚举项 |
|
||||
|
||||
### 💡 软建议(Soft Advice - 规范提醒与潜在运行风险)
|
||||
|
||||
| 规则代码 (`code`) | 级别 | 根因与风险提示 | 优化建议 |
|
||||
|---|---|---|---|
|
||||
| `WORKFLOW_DISABLED` | warning | 工作流当前处于未启用/草稿状态 (`state=0`) | 修改验证完成后执行 `workflow publish` 或 `toggle --state=1` 启用上线 |
|
||||
| `EMPTY_BRANCH` | warning | `condition` 或 `every` 控制节点内部没有配置子节点 | 补充分支逻辑或清理空节点容器 |
|
||||
| `UNKNOWN_TASK_TYPE` | warning | 遇到系统未内置收录的新型节点类型 | 确认是否为平台新发布或定制化组件 |
|
||||
| `UNSAFE_SKIP_WITHOUT_STATUS_GUARD` | warning | 循环内的建单节点配置了报错跳过(SKIP),但后续台账更新节点未校验前序执行状态 | 增加状态守卫(如 `${taskName}.$status === 'SUCCESS'`),防止建单失败时误改台账状态 |
|
||||
| `LINKAGE_PRIORITY_OVERRIDE` | warning | 表单字段存在业务对象联动配置,且联动赋值优先级高于手工/API 传入 | 注意显式传入的值可能被关联对象中的字段值覆盖 |
|
||||
| `MISSING_BACKLOG_DATA_BRACKETS` | warning | HTTP 自动审批节点 URL 路径参数缺少规范的方括号(如缺少 `[{flowId}]`) | 补齐方括号以符合合思 OpenAPI 规范,避免 404 Not Found |
|
||||
|
||||
---
|
||||
|
||||
## 架构记录与后续演进规划 (Architecture Notes)
|
||||
|
||||
### 1. DataLink 映射“影子沙盒模拟”的设计思考与边界记录(现阶段放弃)
|
||||
- **合思业务对象约束**:合思平台底层的业务对象台账**没有物理删除接口**,所谓的“停用”仅仅是更新其状态属性。在客户生产租户中,任何真实的创建调用都会产生无法物理清除的脏数据记录;
|
||||
- **方案抉择与边界**:
|
||||
- 严禁通过“先真实创建、再设为停用”的伪删除方案去模拟 DataLink,这会破坏生产账目连续性并污染审计日志;
|
||||
- 现阶段放弃向服务端发起写请求的模拟模式;
|
||||
- **后续演进路径**:若后续需要提供仿真功能,必须收敛为 **纯客户端内存沙箱(Memory-Only Dry-Run Mapping Engine)**——利用本地已有的 AST 和脚本沙箱,仅对上下文变量、字段映射规则及类型格式进行离线模拟计算与断言,全程零网络写调用、零生产副作用。
|
||||
|
||||
### 2. 非费用类单据与自定义业务对象探针技术规划
|
||||
- **现状与背景**:目前工作流调测与单据详情主要打通了通用报销、费用申请及借款等标准财务表单;
|
||||
- **痛点**:企业用户广泛使用采购单、合同台账、固定资产领用、付款申请等非费用类自定义业务单据。这类单据在流程触发器(`ekuaibao-datalink-create-trigger`)、微前端表单(Form Spec)与字段映射机制上与费用单据存在差异;
|
||||
- **规划技术路径**:
|
||||
- 借助 Kimi 网桥(`kimi-webbridge`)建立真实微前端会话,自动探测并解析不同应用类型下的非费用类表单元数据;
|
||||
- 提取出动态列、关联实体 ID 与系统字段字典,在 CLI 层面提供对非费用类业务对象的只读探针与结构化校验能力。
|
||||
|
||||
@@ -4,10 +4,22 @@ import type {
|
||||
WorkflowAstNode,
|
||||
WorkflowDependency,
|
||||
WorkflowDiagnostic,
|
||||
DiagnosticCategory,
|
||||
WorkflowAnalysisSummary,
|
||||
WorkflowFormSpecComponentLike,
|
||||
AnalyzeWorkflowOptions,
|
||||
} from "./types.js";
|
||||
|
||||
function addDiagnostic(
|
||||
diagnostics: WorkflowDiagnostic[],
|
||||
item: Omit<WorkflowDiagnostic, "category"> & { category?: DiagnosticCategory }
|
||||
): void {
|
||||
diagnostics.push({
|
||||
...item,
|
||||
category: item.category ?? (item.severity === "error" ? "hard_block" : "soft_advice"),
|
||||
});
|
||||
}
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
@@ -19,6 +31,13 @@ const KNOWN_TYPES = new Set([
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"apportion",
|
||||
"flow-change-trigger",
|
||||
"datalink-button-trigger",
|
||||
"email",
|
||||
"message",
|
||||
"message-dingtalk",
|
||||
"dmn",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
@@ -212,6 +231,81 @@ function findUnguardedDatalinkEdits(
|
||||
return found;
|
||||
}
|
||||
|
||||
const FORMULA_REGEX =
|
||||
/\b(AddMonths|dateDIF|DATEADD|DATEDIF|IF|SUM|ROUND|INT|TEXT|YEAR|MONTH|DAY)\s*\(/i;
|
||||
|
||||
function checkMisplacedFormulasInDatalink(
|
||||
task: WorkflowTask,
|
||||
path: string,
|
||||
diagnostics: WorkflowDiagnostic[]
|
||||
): void {
|
||||
if (!task.type.includes("datalink")) return;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const inspectTargets: Array<{ key: string; value: unknown }> = [];
|
||||
|
||||
// 1. inspect task.inputs
|
||||
if (Array.isArray(task.inputs)) {
|
||||
for (const inp of task.inputs) {
|
||||
if (inp && typeof inp === "object") {
|
||||
inspectTargets.push({ key: inp.key || (inp as any).name || "input", value: inp.value });
|
||||
}
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
for (const [k, v] of Object.entries(raw.inputs as Record<string, unknown>)) {
|
||||
inspectTargets.push({ key: k, value: v });
|
||||
}
|
||||
}
|
||||
|
||||
// 2. inspect task.form / formValues / mapping
|
||||
const formEntries = getTaskFormEntries(task);
|
||||
for (const entry of formEntries) {
|
||||
if (entry.key) {
|
||||
inspectTargets.push({ key: entry.key, value: entry.value });
|
||||
}
|
||||
}
|
||||
|
||||
// 3. inspect raw.mapping / raw.data / raw.jsonMapping
|
||||
if (Array.isArray(raw.mapping)) {
|
||||
for (const m of raw.mapping) {
|
||||
if (m && typeof m === "object") {
|
||||
const item = m as Record<string, unknown>;
|
||||
inspectTargets.push({
|
||||
key: String(item.key || item.target || "field"),
|
||||
value: item.value ?? item.source,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. inspect task.fields / raw.fields (合思业务对象新增/修改字段映射)
|
||||
const fields = (task as any).fields ?? raw.fields;
|
||||
if (Array.isArray(fields)) {
|
||||
for (const f of fields) {
|
||||
if (f && typeof f === "object") {
|
||||
const item = f as Record<string, unknown>;
|
||||
inspectTargets.push({
|
||||
key: String(item.key || item.label || "field"),
|
||||
value: item.value,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const target of inspectTargets) {
|
||||
if (typeof target.value === "string") {
|
||||
const match = target.value.match(FORMULA_REGEX);
|
||||
if (match) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
code: "MISPLACED_FORMULA_IN_DATALINK_MAPPING",
|
||||
path,
|
||||
message: `DataLink 任务 '${task.label || task.name}' 的字段 '${target.key}' 配置了表单公式 '${match[0]}...'。合思 DataLink 属于底层数据写入节点,不支持前端表单公式求值,传入公式字符串会导致后端强类型解析崩溃 (如 ParseException)。请前置添加【代码节点】计算该值并在此处引用。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
@@ -220,8 +314,17 @@ export function analyzeWorkflow(
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
const availableSet: Set<string> | undefined = options.availableNodeTypes
|
||||
? new Set(
|
||||
(Array.isArray(options.availableNodeTypes)
|
||||
? options.availableNodeTypes
|
||||
: Array.from(options.availableNodeTypes)
|
||||
).map((t) => t.trim().toLowerCase())
|
||||
)
|
||||
: undefined;
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
@@ -238,7 +341,7 @@ export function analyzeWorkflow(
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
@@ -246,7 +349,7 @@ export function analyzeWorkflow(
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
@@ -254,7 +357,7 @@ export function analyzeWorkflow(
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
@@ -262,6 +365,19 @@ export function analyzeWorkflow(
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断:租户节点开通权限校验
|
||||
if (availableSet && availableSet.size > 0 && !availableSet.has(task.type.toLowerCase())) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
code: "PERMISSION_MISSING_NODE",
|
||||
path,
|
||||
message: `当前企业尚未开通节点类型 '${task.type}',工作流运行时将被合思引擎直接阻断。请先使用 'hose-use workflow nodes grant ${task.type}' 开通灰度权限,或替换为已开通的等价节点。`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断:DataLink 字段误填表单公式硬校验
|
||||
checkMisplacedFormulasInDatalink(task, path, diagnostics);
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
@@ -283,7 +399,7 @@ export function analyzeWorkflow(
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
@@ -359,7 +475,7 @@ export function analyzeWorkflow(
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
@@ -385,7 +501,7 @@ export function analyzeWorkflow(
|
||||
rawFilters.includes("被驳回") ||
|
||||
rawFilters.includes("审批驳回"))
|
||||
) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
code: "DEADLOCK_TRIGGER_STATE_FILTER",
|
||||
path,
|
||||
@@ -414,7 +530,7 @@ export function analyzeWorkflow(
|
||||
/"label":"[^"]*通知类型"/i.test(keyStr);
|
||||
|
||||
if (isStateField && /被驳回|审批驳回|REJECTED|reject/i.test(valStr)) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
code: "DEADLOCK_CONDITION_STATE_FILTER",
|
||||
path,
|
||||
@@ -432,7 +548,7 @@ export function analyzeWorkflow(
|
||||
!valStr.includes("timeout.") &&
|
||||
/被驳回|已支付|待审批|待支付|待收单|撤回|删除|催办/i.test(valStr)
|
||||
) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
code: "INVALID_ACTION_ENUM_TEXT_VALUE",
|
||||
path,
|
||||
@@ -450,7 +566,7 @@ export function analyzeWorkflow(
|
||||
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
|
||||
const segment = match ? match[1] : "";
|
||||
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
|
||||
diagnostics.push({
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "MISSING_BACKLOG_DATA_BRACKETS",
|
||||
path,
|
||||
@@ -465,6 +581,15 @@ export function analyzeWorkflow(
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
const hardBlocks = diagnostics.filter((d) => d.category === "hard_block").length;
|
||||
const softAdvices = diagnostics.filter((d) => d.category === "soft_advice").length;
|
||||
const summary: WorkflowAnalysisSummary = {
|
||||
total: diagnostics.length,
|
||||
hardBlocks,
|
||||
softAdvices,
|
||||
passed: hardBlocks === 0,
|
||||
};
|
||||
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
@@ -475,5 +600,6 @@ export function analyzeWorkflow(
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
summary,
|
||||
};
|
||||
}
|
||||
@@ -164,5 +164,103 @@ describe("Workflow static analysis", () => {
|
||||
expect(codes).toContain("MISSING_BACKLOG_DATA_BRACKETS");
|
||||
expect(result.diagnostics.find((d) => d.code === "MISSING_BACKLOG_DATA_BRACKETS")?.severity).toBe("warning");
|
||||
});
|
||||
|
||||
it("detects PERMISSION_MISSING_NODE when workflow uses nodes not granted to the enterprise", () => {
|
||||
const wf = {
|
||||
id: "wf-missing-perm",
|
||||
label: "新代码节点测试",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_1",
|
||||
type: "code-js2",
|
||||
label: "新版JS节点",
|
||||
code: "return 1;",
|
||||
},
|
||||
],
|
||||
};
|
||||
// 假设企业只开通了 code 和 http,没有开通 code-js2
|
||||
const result = analyzeWorkflow(wf as any, {
|
||||
availableNodeTypes: ["code", "http"],
|
||||
});
|
||||
const missingNodeDiag = result.diagnostics.find(
|
||||
(d) => d.code === "PERMISSION_MISSING_NODE"
|
||||
);
|
||||
expect(missingNodeDiag).toBeDefined();
|
||||
expect(missingNodeDiag?.severity).toBe("error");
|
||||
expect(missingNodeDiag?.message).toContain("code-js2");
|
||||
});
|
||||
|
||||
it("detects MISPLACED_FORMULA_IN_DATALINK_MAPPING when formulas are placed in DataLink fields", () => {
|
||||
const wf = {
|
||||
id: "wf-datalink-formula",
|
||||
label: "台账摊销工作流",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_create",
|
||||
type: "ekuaibao-datalink-create",
|
||||
label: "新增摊销台账",
|
||||
mapping: [
|
||||
{
|
||||
key: "amortizationMonth",
|
||||
value: "AddMonths(date, 1)",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const formulaDiag = result.diagnostics.find(
|
||||
(d) => d.code === "MISPLACED_FORMULA_IN_DATALINK_MAPPING"
|
||||
);
|
||||
expect(formulaDiag).toBeDefined();
|
||||
expect(formulaDiag?.severity).toBe("error");
|
||||
expect(formulaDiag?.message).toContain("AddMonths");
|
||||
expect(formulaDiag?.message).toContain("代码节点");
|
||||
});
|
||||
|
||||
it("calculates summary metrics and classifies diagnostics into hard_block and soft_advice", () => {
|
||||
const wf = {
|
||||
id: "wf-summary-test",
|
||||
label: "门禁分类测试",
|
||||
state: 0, // -> warning (soft_advice): WORKFLOW_DISABLED
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "empty_code_node",
|
||||
type: "code",
|
||||
label: "空代码",
|
||||
code: "", // -> error (hard_block): EMPTY_CODE
|
||||
},
|
||||
{
|
||||
name: "empty_branch_node",
|
||||
type: "condition",
|
||||
label: "空分支",
|
||||
tasks: [], // -> warning (soft_advice): EMPTY_BRANCH
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
expect(result.summary).toBeDefined();
|
||||
expect(result.summary.total).toBe(3);
|
||||
expect(result.summary.hardBlocks).toBe(1);
|
||||
expect(result.summary.softAdvices).toBe(2);
|
||||
expect(result.summary.passed).toBe(false);
|
||||
|
||||
const emptyCode = result.diagnostics.find((d) => d.code === "EMPTY_CODE");
|
||||
expect(emptyCode?.category).toBe("hard_block");
|
||||
expect(emptyCode?.severity).toBe("error");
|
||||
|
||||
const disabled = result.diagnostics.find((d) => d.code === "WORKFLOW_DISABLED");
|
||||
expect(disabled?.category).toBe("soft_advice");
|
||||
expect(disabled?.severity).toBe("warning");
|
||||
|
||||
const emptyBranch = result.diagnostics.find((d) => d.code === "EMPTY_BRANCH");
|
||||
expect(emptyBranch?.category).toBe("soft_advice");
|
||||
expect(emptyBranch?.severity).toBe("warning");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,18 +14,29 @@ export interface WorkflowDependency {
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export type DiagnosticCategory = "hard_block" | "soft_advice";
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
category: DiagnosticCategory;
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysisSummary {
|
||||
total: number;
|
||||
hardBlocks: number;
|
||||
softAdvices: number;
|
||||
passed: boolean;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
summary: WorkflowAnalysisSummary;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
@@ -47,4 +58,5 @@ export interface WorkflowFormSpecLike {
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
availableNodeTypes?: Set<string> | string[];
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
export interface GrayNodeItem {
|
||||
displayName: string;
|
||||
name: string;
|
||||
type: string;
|
||||
category?: "action" | "control" | "trigger" | "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* 合思官方工作流灰度节点清单(共 108 个有效去重条目)
|
||||
* 来源于官方灰度开通对照表
|
||||
*/
|
||||
export const GRAY_NODES_CATALOG: readonly GrayNodeItem[] = [
|
||||
{ displayName: "JS节点(新)", name: "JS节点(新)", type: "code-js2", category: "action" },
|
||||
{ displayName: "重算审批流", name: "重算审批流", type: "recalculate-the-approval-flow", category: "action" },
|
||||
{ displayName: "提示框", name: "提示框", type: "ui-notification", category: "action" },
|
||||
{ displayName: "定时任务节点", name: "定时任务节点", type: "start", category: "trigger" },
|
||||
{ displayName: "推送飞书消息", name: "推送飞书消息", type: "feishu-sendMsg", category: "action" },
|
||||
{ displayName: "飞书消息", name: "飞书消息", type: "message-feishu", category: "action" },
|
||||
{ displayName: "if节点", name: "if节点", type: "if", category: "control" },
|
||||
{ displayName: "http节点", name: "http节点", type: "http", category: "action" },
|
||||
{ displayName: "遍历数组", name: "遍历数组", type: "loop", category: "control" },
|
||||
{ displayName: "循环节点", name: "循环节点", type: "while", category: "control" },
|
||||
{ displayName: "企业微信开放平台获取子部门ID列表", name: "企业微信开放平台获取子部门ID列表", type: "wecom-department", category: "action" },
|
||||
{ displayName: "易桥参数转化", name: "易桥参数转化", type: "eBridge-mapData", category: "action" },
|
||||
{ displayName: "代码节点", name: "代码节点", type: "code", category: "action" },
|
||||
{ displayName: "数据映射", name: "数据映射", type: "mapping", category: "action" },
|
||||
{ displayName: "纷享销客鉴权", name: "纷享销客鉴权", type: "fxiaoke-auth", category: "action" },
|
||||
{ displayName: "纷享销客数据列表", name: "纷享销客数据列表", type: "fxiaoke-list", category: "action" },
|
||||
{ displayName: "NetSuite数据列表", name: "NetSuite数据列表", type: "netsuite-sync", category: "action" },
|
||||
{ displayName: "NetSuite数据创建", name: "NetSuite数据创建", type: "netsuite-create", category: "action" },
|
||||
{ displayName: "易桥鉴权", name: "易桥鉴权", type: "ebridge-auth", category: "action" },
|
||||
{ displayName: "新增业务对象数据", name: "新增业务对象数据", type: "ekuaibao-datalink-create", category: "action" },
|
||||
{ displayName: "定时触发", name: "定时触发", type: "clock", category: "trigger" },
|
||||
{ displayName: "纷享销客触发器", name: "纷享销客触发器", type: "fxiaoke-trigger", category: "trigger" },
|
||||
{ displayName: "到达业务对象数据中的日期时触发", name: "到达业务对象数据中的日期时触发", type: "ekuaibao-datalink-time-trigger", category: "trigger" },
|
||||
{ displayName: "发送邮件", name: "发送邮件", type: "email", category: "action" },
|
||||
{ displayName: "查找业务对象数据", name: "查找业务对象数据", type: "ekuaibao-datalink-filter", category: "action" },
|
||||
{ displayName: "修改业务对象数据", name: "修改业务对象数据", type: "ekuaibao-datalink-edit", category: "action" },
|
||||
{ displayName: "NetSuite数据删除", name: "NetSuite数据删除", type: "netsuite-delete", category: "action" },
|
||||
{ displayName: "薪人薪事触发器", name: "薪人薪事触发器", type: "xrxs-trigger", category: "trigger" },
|
||||
{ displayName: "新增业务对象数据时触发", name: "新增业务对象数据时触发", type: "ekuaibao-datalink-create-trigger", category: "trigger" },
|
||||
{ displayName: "变更业务对象数据时触发", name: "变更业务对象数据时触发", type: "ekuaibao-datalink-change-trigger", category: "trigger" },
|
||||
{ displayName: "单据审批事件触发器", name: "单据审批事件触发器", type: "ekuaibao-flowform-trigger", category: "trigger" },
|
||||
{ displayName: "发送短信", name: "发送短信", type: "message", category: "action" },
|
||||
{ displayName: "webhook触发器", name: "webhook触发器", type: "webhook", category: "trigger" },
|
||||
{ displayName: "对话框", name: "对话框", type: "ui-dialog", category: "action" },
|
||||
{ displayName: "流程日志", name: "流程日志", type: "task-log", category: "action" },
|
||||
{ displayName: "动态节点测试", name: "动态节点测试", type: "task-dynamic-test", category: "action" },
|
||||
{ displayName: "条件节点", name: "条件节点", type: "condition", category: "control" },
|
||||
{ displayName: "OpenAPI", name: "OpenAPI", type: "task-openapi", category: "action" },
|
||||
{ displayName: "终止节点", name: "终止节点", type: "stop", category: "action" },
|
||||
{ displayName: "收集节点", name: "收集节点", type: "context", category: "action" },
|
||||
{ displayName: "到达单据日期时触发", name: "到达单据日期时触发", type: "flow-change-trigger", category: "trigger" },
|
||||
{ displayName: "获取钉钉考勤", name: "获取钉钉考勤", type: "task-dynamic-ding-attendance", category: "action" },
|
||||
{ displayName: "摊销节点", name: "摊销节点", type: "apportion", category: "control" },
|
||||
{ displayName: "创建单据", name: "创建单据", type: "flow-create-task", category: "action" },
|
||||
{ displayName: "站内信", name: "站内信", type: "message-internet", category: "action" },
|
||||
{ displayName: "钉钉消息", name: "钉钉消息", type: "message-dingtalk", category: "action" },
|
||||
{ displayName: "修改角色", name: "修改角色", type: "role-update", category: "action" },
|
||||
{ displayName: "依次执行", name: "依次执行", type: "every", category: "control" },
|
||||
{ displayName: "查询申请事项详情", name: "查询申请事项详情", type: "ekuaibao-requision-detail", category: "action" },
|
||||
{ displayName: "查询单据详情", name: "查询单据详情", type: "flow-detail", category: "action" },
|
||||
{ displayName: "查询单据历史详情", name: "查询单据历史详情", type: "flow-detail-versioned", category: "action" },
|
||||
{ displayName: "业务对象数据按钮触发", name: "业务对象数据按钮触发", type: "datalink-button-trigger", category: "trigger" },
|
||||
{ displayName: "查找行程数据", name: "查找行程数据", type: "ekuaibao-tmc-datalink-filter", category: "action" },
|
||||
{ displayName: "新增行程数据时触发", name: "新增行程数据时触发", type: "ekuaibao-tmc-datalink-create-trigger", category: "trigger" },
|
||||
{ displayName: "变更行程数据时触发", name: "变更行程数据时触发", type: "ekuaibao-tmc-datalink-change-trigger", category: "trigger" },
|
||||
{ displayName: "到达行程日期时触发", name: "到达行程日期时触发", type: "ekuaibao-tmc-datalink-time-trigger", category: "trigger" },
|
||||
{ displayName: "查询发票", name: "查询发票", type: "ekuaibao-invoice-datalink-filter", category: "action" },
|
||||
{ displayName: "结果输出", name: "结果输出", type: "output", category: "action" },
|
||||
{ displayName: "EBOT触发", name: "EBOT触发", type: "ekuaibao-ebot-trigger", category: "trigger" },
|
||||
{ displayName: "补充发票触发", name: "补充发票触发", type: "other-event-trigger", category: "trigger" },
|
||||
{ displayName: "发票验真", name: "发票验真", type: "invoice-verification", category: "action" },
|
||||
{ displayName: "JS节点", name: "JS节点", type: "code-js", category: "action" },
|
||||
{ displayName: "数据转化", name: "数据转化", type: "data-convert", category: "action" },
|
||||
{ displayName: "新摊销", name: "新摊销", type: "amortization", category: "control" },
|
||||
{ displayName: "数据映射", name: "数据映射", type: "dmn", category: "action" },
|
||||
{ displayName: "查询人员", name: "查询人员", type: "ekuaibao-staff-filter", category: "action" },
|
||||
{ displayName: "查询单据列表", name: "查询单据列表", type: "flow-list", category: "action" },
|
||||
{ displayName: "HAB触发器", name: "HAB触发器", type: "hab-trigger-task", category: "trigger" },
|
||||
{ displayName: "申请事项触发器", name: "申请事项触发器", type: "ekuaibao-requisition-trigger", category: "trigger" },
|
||||
{ displayName: "创建部门", name: "创建部门", type: "department-create", category: "action" },
|
||||
{ displayName: "部门查询", name: "部门查询", type: "department-filter", category: "action" },
|
||||
{ displayName: "新增人员", name: "新增人员", type: "staff-create", category: "action" },
|
||||
{ displayName: "查询随手记列表", name: "查询随手记列表", type: "ekuaibao-ecard-fee-filter", category: "action" },
|
||||
{ displayName: "查询人员详情", name: "查询人员详情", type: "ekuaibao-staff-detail", category: "action" },
|
||||
{ displayName: "查询部门详情", name: "查询部门详情", type: "ekuaibao-department-detail", category: "action" },
|
||||
{ displayName: "查询易商卡申请事项列表", name: "查询易商卡申请事项列表", type: "ekuaibao-ecard-requisition-filter", category: "action" },
|
||||
{ displayName: "查询飞书部门", name: "查询飞书部门", type: "feishu-department-filter", category: "action" },
|
||||
{ displayName: "修改部门", name: "修改部门", type: "ekuaibao-department-update", category: "action" },
|
||||
{ displayName: "站外信", name: "站外信", type: "message-outnet", category: "action" },
|
||||
{ displayName: "AI节点", name: "AI节点", type: "ekb-ai", category: "action" },
|
||||
{ displayName: "修改单据", name: "修改单据", type: "flow-update-task", category: "action" },
|
||||
{ displayName: "提取文本(word,PDF)", name: "提取文本(word,PDF)", type: "ekb-ai-pdf", category: "action" },
|
||||
{ displayName: "单据风险写入", name: "单据风险写入", type: "risk", category: "action" },
|
||||
{ displayName: "天润工单查询", name: "天润工单查询", type: "tr-select", category: "action" },
|
||||
{ displayName: "天润工单评论", name: "天润工单评论", type: "tr-comment", category: "action" },
|
||||
{ displayName: "天润工单查询详情", name: "天润工单查询详情", type: "tr-detail", category: "action" },
|
||||
{ displayName: "Dify接入", name: "Dify接入", type: "dify", category: "action" },
|
||||
{ displayName: "图片URL识别", name: "图片URL识别", type: "ekb-ai-url", category: "action" },
|
||||
{ displayName: "AI文本理解", name: "AI文本理解", type: "ekb-minimax-text", category: "action" },
|
||||
{ displayName: "AI图像理解", name: "AI图像理解", type: "ekb-minimax-photo", category: "action" },
|
||||
{ displayName: "查询角色下的人员", name: "查询角色下的人员", type: "search-staff-by-role", category: "action" },
|
||||
{ displayName: "发票巡检", name: "发票巡检", type: "ekuaibao-invoice-inspector", category: "action" },
|
||||
{ displayName: "招商银行商务卡查询", name: "招商银行商务卡查询", type: "task-zs", category: "action" },
|
||||
{ displayName: "单据查询详情(跨租户)", name: "单据查询详情(跨租户)", type: "escape", category: "action" },
|
||||
{ displayName: "海亮单据查询详情", name: "海亮单据查询详情", type: "hl-detail", category: "action" },
|
||||
{ displayName: "单据查询详情AI审批专用", name: "单据查询详情AI审批专用", type: "mapping-detail", category: "action" },
|
||||
{ displayName: "海亮数据集列表", name: "海亮数据集列表", type: "hl", category: "action" },
|
||||
{ displayName: "查询易商卡流水的费用信息", name: "查询易商卡流水的费用信息", type: "ekuaibao-ecard-fee-detail-filter", category: "action" },
|
||||
{ displayName: "Ebot审批", name: "Ebot审批", type: "ebot-approval-flow", category: "action" },
|
||||
{ displayName: "给OA账号发送提醒", name: "给OA账号发送提醒", type: "oa", category: "action" },
|
||||
{ displayName: "查询历史单据测试集", name: "查询历史单据测试集", type: "flow-sample-list", category: "action" },
|
||||
{ displayName: "分类汇总", name: "分类汇总", type: "aggregation", category: "action" },
|
||||
{ displayName: "单据转译节点", name: "单据转译节点", type: "flow-format", category: "action" },
|
||||
{ displayName: "导出表格", name: "导出表格", type: "excel", category: "action" },
|
||||
{ displayName: "AI附件理解", name: "AI附件理解", type: "ai-attachment", category: "action" },
|
||||
{ displayName: "AI智能匹配", name: "AI智能匹配", type: "ai-classification", category: "action" },
|
||||
{ displayName: "AI智能提取", name: "AI智能提取", type: "ai-extraction", category: "action" },
|
||||
{ displayName: "延迟执行节点", name: "延迟执行节点", type: "task-dynamic-delay", category: "action" },
|
||||
];
|
||||
|
||||
const typeMap = new Map<string, GrayNodeItem>();
|
||||
const nameMap = new Map<string, GrayNodeItem>();
|
||||
|
||||
for (const item of GRAY_NODES_CATALOG) {
|
||||
typeMap.set(item.type.toLowerCase(), item);
|
||||
nameMap.set(item.displayName.toLowerCase(), item);
|
||||
}
|
||||
|
||||
export function findGrayNode(query: string): GrayNodeItem | undefined {
|
||||
const q = query.trim().toLowerCase();
|
||||
return typeMap.get(q) || nameMap.get(q);
|
||||
}
|
||||
|
||||
export function isKnownGrayNodeType(type: string): boolean {
|
||||
return typeMap.has(type.trim().toLowerCase());
|
||||
}
|
||||
@@ -2,3 +2,4 @@ export * from "./types.js";
|
||||
export * from "./tree.js";
|
||||
export * from "./locator.js";
|
||||
export * from "./mutations.js";
|
||||
export * from "./gray-nodes-catalog.js";
|
||||
@@ -30,6 +30,8 @@ Skill 初始化明确执行 `skill install --yes`;失败会报告二进制已
|
||||
- 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。
|
||||
- Release:构建前检查 tag 版本、实际 HEAD 和 main 祖先关系;手动触发也必须输入 tag。正式构建显式使用 `--release`,两个发布源都上传校验清单,后台镜像上传失败会使任务失败。
|
||||
|
||||
Gitea 同时最多传输两个资产,每个资产最多尝试三次;已有文件经 SHA-256 验证一致时直接保留。镜像传输中断后,可在 main 上手动运行 Release workflow,传入原 tag 并启用 `mirror_only`:该模式下载并核对 GitHub 已发布资产,只修复 Gitea,不重建或替换 GitHub 产物,也不移动 tag。
|
||||
|
||||
版本准备使用 `codex/release-vX.Y.Z` 或 `release/vX.Y.Z` 分支及干净工作区。`bun run bump <版本|patch|minor|major>` 在写入前校验分支、递增版本和重复 tag,再同步仓库版本及生成物;全局开发版同步通过单独的 `bun run dev:override` 执行。预检失败不写版本文件;后续生成步骤若失败,会保留可复查的仓库修改以便修复。
|
||||
|
||||
完成本地验证后,提交发布分支、开 PR、等待 CI 和审查、合入并同步 main;然后创建带说明的 tag,依次推送 `home`、`origin`,最后检查两个源的 Release 产物。GitHub 是否能把 CI 设置为强制合并条件取决于仓库规则与套餐,workflow 本身只负责执行检查。
|
||||
Reference in new issue
Block a user