Compare commits
34
Commits
febeecdec7
...
v0.8.14
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07031f58a0 | ||
|
|
3151897a9a | ||
|
|
103ead0fe5 | ||
|
|
f0902f5f20 | ||
|
|
1876e8a8f2 | ||
|
|
627e17e0f2 | ||
|
|
af1e11c018 | ||
|
|
908286c1df | ||
|
|
5aef332026 | ||
|
|
c917df13cc | ||
|
|
d293bb47a4 | ||
|
|
97eaed1066 | ||
|
|
53201ba4e1 | ||
|
|
71f9879f68 | ||
|
|
3261b6ebdb | ||
|
|
61123ad550 | ||
|
|
02b197c119 | ||
|
|
aa58dd7f6f | ||
|
|
b043cb614e | ||
|
|
fec25bff8a | ||
|
|
c56460716f | ||
|
|
8531530ccd | ||
|
|
b605d7c2bb | ||
|
|
7ec369f77e | ||
|
|
f333c7f1fb | ||
|
|
c8d9e409c6 | ||
|
|
c74fdda7da | ||
|
|
c507879896 | ||
|
|
f6227f277a | ||
|
|
0b4519652b | ||
|
|
36a3c3b28d | ||
|
|
86d6c1d340 | ||
|
|
ed3f38f1ab | ||
|
|
fe6183dd44 |
No files matched your search
@@ -0,0 +1,36 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
- run: bun install --frozen-lockfile
|
||||
- run: bun run check:version
|
||||
- run: bun run check
|
||||
- run: bun test
|
||||
- run: bun run build:binary
|
||||
- run: bun run scripts/verify-binary.ts dist/bin/hose-use
|
||||
- run: bun run build:plugin
|
||||
- run: git diff --exit-code -- dist/mcp/server.js
|
||||
- run: bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
@@ -5,26 +5,53 @@ on:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Release tag already merged into main (e.g. v0.8.14)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
ref: ${{ inputs.tag || github.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
|
||||
# A tag alone does not prove review. Also verify the commit actually being
|
||||
# compiled, so manual dispatch cannot validate one tag and ship another ref.
|
||||
- name: Verify release commit and version
|
||||
run: |
|
||||
git fetch --no-tags origin main:refs/remotes/origin/main
|
||||
bun run scripts/verify-release.ts "$RELEASE_TAG"
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Check committed version consistency
|
||||
run: bun run check:version
|
||||
|
||||
- name: Generate & bundle OpenAPI
|
||||
run: bun run openapi:all
|
||||
|
||||
@@ -37,7 +64,15 @@ jobs:
|
||||
- name: Compile multi-target binaries
|
||||
run: |
|
||||
mkdir -p dist/bin
|
||||
node scripts/build-binary.mjs --all
|
||||
node scripts/build-binary.mjs --all --release
|
||||
|
||||
- name: Verify packaged MCP entrypoint
|
||||
run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64
|
||||
|
||||
- name: Verify plugin bundle runtime
|
||||
run: |
|
||||
bun run build:plugin
|
||||
bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
|
||||
- name: Package release archives
|
||||
run: |
|
||||
@@ -64,17 +99,19 @@ jobs:
|
||||
(cd "${stage}" && zip -q "${GITHUB_WORKSPACE}/dist/bin/hose-use-windows-x64.zip" hose-use-windows-x64.exe hose-aipro.cmd)
|
||||
rm -rf "${stage}"
|
||||
|
||||
(cd dist/bin && sha256sum hose-use-* > checksums.txt)
|
||||
|
||||
- name: Publish GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${GITHUB_REF_NAME}" | sed '/^$/d')
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${RELEASE_TAG}" | sed '/^$/d')
|
||||
if [ -n "$TAG_MSG" ]; then
|
||||
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --notes "$TAG_MSG" --generate-notes
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --notes "$TAG_MSG" --generate-notes
|
||||
else
|
||||
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --generate-notes
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --generate-notes
|
||||
fi
|
||||
gh release upload "${GITHUB_REF_NAME}" dist/bin/hose-use-* --repo "${GITHUB_REPOSITORY}" --clobber
|
||||
gh release upload "${RELEASE_TAG}" dist/bin/hose-use-* dist/bin/checksums.txt --repo "${GITHUB_REPOSITORY}" --clobber
|
||||
|
||||
- name: Publish Gitea Release
|
||||
env:
|
||||
@@ -87,7 +124,7 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
TAG_NAME="${GITHUB_REF_NAME}"
|
||||
TAG_NAME="${RELEASE_TAG}"
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
|
||||
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
|
||||
|
||||
@@ -103,8 +140,8 @@ jobs:
|
||||
fi
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
echo "::warning::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
|
||||
exit 0
|
||||
echo "::error::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
|
||||
@@ -113,7 +150,12 @@ jobs:
|
||||
local filename
|
||||
filename=$(basename "$file")
|
||||
echo " [start] Uploading ${filename} to Gitea..."
|
||||
RESP=$(curl -s -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
# 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}"
|
||||
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)
|
||||
@@ -121,12 +163,17 @@ jobs:
|
||||
}
|
||||
|
||||
pids=()
|
||||
for file in dist/bin/hose-use-*; do
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
done
|
||||
|
||||
failed=0
|
||||
for pid in "${pids[@]}"; do
|
||||
wait "$pid" || true
|
||||
wait "$pid" || failed=1
|
||||
done
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ Successfully published release assets to Gitea!"
|
||||
@@ -2,7 +2,7 @@
|
||||
"mcpServers": {
|
||||
"hose-use": {
|
||||
"type": "stdio",
|
||||
"command": "node",
|
||||
"command": "bun",
|
||||
"args": [
|
||||
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.13",
|
||||
"version": "0.8.14",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -22,7 +22,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
||||
cli/registry.ts & cli/commands/* (命令分发与视图渲染)
|
||||
│
|
||||
▼
|
||||
domains/ (14 个业务子域:编排 tools/services + 传输 api)
|
||||
domains/ (业务子域:编排 tools/services + 传输 api;清单见域层说明)
|
||||
│
|
||||
▼
|
||||
core/ (严格基础设施白名单)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.13)
|
||||
# hose-use (v0.8.14)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
安装与自更新会校验 Release 的 SHA-256 清单;版本固定、镜像设置及发布流程见 [构建与分发说明](./src/packaging/README.packaging.md)。
|
||||
|
||||
### 方式二:本地 Bun 源码开发
|
||||
|
||||
```bash
|
||||
@@ -92,7 +94,7 @@ hose-use service logs # 查看守护进程日志
|
||||
hose-use service stop # 优雅停止常驻守护进程
|
||||
|
||||
# 8. Agent Skill 与连通性诊断
|
||||
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use skill install --yes # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
|
||||
|
||||
# 9. MCP Server (单工具网关模式)
|
||||
@@ -105,14 +107,14 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
- 避免数十个业务工具占用大量 Prompt Tokens;
|
||||
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 与 `references/` 专卷中,Agent 按需学习;
|
||||
- 内部同进程调用 CLI 分发层,零子进程开销;
|
||||
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
|
||||
- `HOSE_MCP_MODE` 始终采用 `single`;通过 `HOSE_USE_MCP_ENABLED=false` 可关闭工具暴露,写操作沿用 CLI 的预览与确认约定。
|
||||
|
||||
### 模块化 Agent Skill 与 IDE 插件规范
|
||||
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install --yes` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
|
||||
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
|
||||
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
|
||||
|
||||
## 架构
|
||||
|
||||
|
||||
Vendored
+1507
-1242
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.13",
|
||||
"version": "0.8.14",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -19,6 +19,7 @@ function run(args) {
|
||||
|
||||
const mcpOutput = resolve(root, "dist/mcp/server.js");
|
||||
mkdirSync(dirname(mcpOutput), { recursive: true });
|
||||
run(["build", "src/server.ts", "--minify", "--target=node", "--outfile", mcpOutput]);
|
||||
// The shared CLI uses bun:sqlite; the plugin manifest must use this runtime too.
|
||||
run(["build", "src/server.ts", "--minify", "--target=bun", "--outfile", mcpOutput]);
|
||||
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
|
||||
console.log(`✓ Successfully bundled MCP server: ${mcpOutput}`);
|
||||
+113
-85
@@ -1,93 +1,121 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { execSync } from "node:child_process";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const ROOT = join(import.meta.dirname, "..");
|
||||
const pkgPath = join(ROOT, "package.json");
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
||||
const currentVersion: string = pkg.version;
|
||||
export function bumpVersion(ROOT: string, input: string, rebuild = () => {
|
||||
execFileSync(process.execPath, ["run", "openapi:all"], { cwd: ROOT, stdio: "inherit" });
|
||||
execFileSync(process.execPath, ["run", "build:plugin"], { cwd: ROOT, stdio: "inherit" });
|
||||
execFileSync(process.execPath, ["run", "check:version"], { cwd: ROOT, stdio: "inherit" });
|
||||
}): string {
|
||||
const pkgPath = join(ROOT, "package.json");
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
||||
const currentVersion: string = pkg.version;
|
||||
|
||||
const input = process.argv[2]?.trim();
|
||||
if (!input) {
|
||||
console.error("Usage: bun run bump <version | patch | minor | major>");
|
||||
console.error(`Current version: ${currentVersion}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let nextVersion = input.replace(/^v/, "");
|
||||
if (input === "patch" || input === "minor" || input === "major") {
|
||||
const [major, minor, patch] = currentVersion.split(".").map(Number);
|
||||
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
|
||||
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
|
||||
if (input === "major") nextVersion = `${major + 1}.0.0`;
|
||||
}
|
||||
|
||||
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(nextVersion)) {
|
||||
console.error(`Invalid SemVer format: '${nextVersion}'`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
|
||||
|
||||
// 1. package.json
|
||||
pkg.version = nextVersion;
|
||||
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
|
||||
console.log("✓ Updated package.json");
|
||||
|
||||
// 2. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v[\d.]+: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. specs/openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated specs/openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
const srcDir = join(ROOT, "skills", "hose-use");
|
||||
for (const item of readdirSync(srcDir)) {
|
||||
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
|
||||
if (!input) {
|
||||
console.error("Usage: bun run bump <version | patch | minor | major>");
|
||||
console.error(`Current version: ${currentVersion}`);
|
||||
throw new Error("A release version is required");
|
||||
}
|
||||
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
|
||||
|
||||
let nextVersion = input.replace(/^v/, "");
|
||||
if (input === "patch" || input === "minor" || input === "major") {
|
||||
const [major, minor, patch] = currentVersion.split("-")[0].split(".").map(Number);
|
||||
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
|
||||
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
|
||||
if (input === "major") nextVersion = `${major + 1}.0.0`;
|
||||
}
|
||||
|
||||
if (!isReleaseVersion(nextVersion)) throw new Error(`Invalid SemVer format: '${nextVersion}'`);
|
||||
if (Bun.semver.order(nextVersion, currentVersion) <= 0) throw new Error(`Version must increase: ${currentVersion} -> ${nextVersion}`);
|
||||
const git = (args: string[]) => execFileSync("git", args, { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
if (git(["status", "--porcelain"])) throw new Error("Release preparation requires a clean working tree");
|
||||
const branch = git(["branch", "--show-current"]);
|
||||
if (!["codex/release-v", "release/v"].some(prefix => branch === `${prefix}${nextVersion}`)) {
|
||||
throw new Error(`Prepare the release on codex/release-v${nextVersion} or release/v${nextVersion}; current branch: ${branch || "detached HEAD"}`);
|
||||
}
|
||||
if (git(["tag", "--list", `v${nextVersion}`])) throw new Error(`Tag v${nextVersion} already exists`);
|
||||
// Read all versioned sources before writing any of them.
|
||||
for (const file of ["README.md", "skills/hose-use/SKILL.md"]) readFileSync(join(ROOT, file), "utf8");
|
||||
for (const file of ["specs/openapi/openapi.yaml", ".zcode-plugin/plugin.json"]) {
|
||||
if (existsSync(join(ROOT, file))) {
|
||||
const content = readFileSync(join(ROOT, file), "utf8");
|
||||
if (file.endsWith(".json")) JSON.parse(content);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
|
||||
|
||||
// 1. package.json
|
||||
pkg.version = nextVersion;
|
||||
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
|
||||
console.log("✓ Updated package.json");
|
||||
|
||||
// 2. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. specs/openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated specs/openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ is now an explicit dev:override step.
|
||||
// A version bump must not overwrite personal Skill files in the user's environment.
|
||||
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
rebuild();
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Review the diff, then run bun test && bun run check && bun run check:version`);
|
||||
console.log(` 2. Commit on ${branch}, push that branch and open a PR to main`);
|
||||
console.log(` 3. Wait for CI and review, then merge the PR`);
|
||||
console.log(` 4. Switch to main; git pull --ff-only origin main; git push home main`);
|
||||
console.log(` 5. Create annotated tag v${nextVersion} on the merged release commit`);
|
||||
console.log(` 6. git push home refs/tags/v${nextVersion} (first), then git push origin refs/tags/v${nextVersion}`);
|
||||
console.log(` 7. Verify the Release build, binary archives and checksums on both sources`);
|
||||
console.log(` Optional: bun run dev:override to explicitly sync your global development binary and Skill`);
|
||||
return nextVersion;
|
||||
}
|
||||
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
|
||||
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
|
||||
export function isReleaseVersion(value: string): boolean {
|
||||
const match = value.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*))?$/);
|
||||
return !!match && (!match[4] || match[4].split(".").every(part => !/^0\d+$/.test(part)));
|
||||
}
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Update CHANGELOG.md (if exists)`);
|
||||
console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`);
|
||||
console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`);
|
||||
console.log(` 4. git push origin <feature-branch>\n`);
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
bumpVersion(join(import.meta.dirname, ".."), process.argv[2]?.trim() || "");
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
+119
-78
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
set -euo pipefail
|
||||
|
||||
REPO="yunyingk/hose-use"
|
||||
|
||||
@@ -34,9 +34,10 @@ case "$ARCH" in
|
||||
esac
|
||||
|
||||
# Resolve best writable bin directory without requiring sudo
|
||||
TARGET_DIR=""
|
||||
TARGET_DIR="${HOSE_USE_INSTALL_DIR:-}"
|
||||
if [ -n "$TARGET_DIR" ]; then mkdir -p "$TARGET_DIR"; fi
|
||||
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
||||
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
if [ -z "$TARGET_DIR" ] && [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
TARGET_DIR="$candidate"
|
||||
break
|
||||
fi
|
||||
@@ -49,6 +50,10 @@ fi
|
||||
|
||||
ASSET_NAME="hose-use-${PLATFORM}-${ARCH_NAME}"
|
||||
TARGET_PATH="${TARGET_DIR}/hose-use"
|
||||
if [ -d "$TARGET_PATH" ] || { [ -d "${TARGET_DIR}/hose-aipro" ] && [ ! -L "${TARGET_DIR}/hose-aipro" ]; }; then
|
||||
echo "Error: an install target is a directory; refusing to replace it." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
get_file_size() {
|
||||
local file="$1"
|
||||
@@ -102,7 +107,7 @@ download_candidate() {
|
||||
if curl -fL --progress-bar "$url" -o "$dest"; then
|
||||
local size_bytes
|
||||
size_bytes="$(get_file_size "$dest")"
|
||||
if [ "$size_bytes" -gt 1000000 ]; then
|
||||
if [ "$size_bytes" -gt 0 ]; then
|
||||
echo "✓ Download complete! Total size: $(format_bytes "$size_bytes")"
|
||||
echo "✓ Successfully fetched from host: ${host}"
|
||||
return 0
|
||||
@@ -114,103 +119,139 @@ download_candidate() {
|
||||
}
|
||||
|
||||
echo "==> Target install location: ${TARGET_PATH}"
|
||||
TMP_FILE="$(mktemp)"
|
||||
TMP_DIR="$(mktemp -d)"
|
||||
TMP_FILE="${TMP_DIR}/download"
|
||||
CHECKSUM_FILE="${TMP_DIR}/checksums.txt"
|
||||
INSTALL_STAGE=""
|
||||
trap 'rm -rf "$TMP_DIR"; if [ -n "$INSTALL_STAGE" ]; then rm -f "$INSTALL_STAGE"; fi' EXIT
|
||||
DOWNLOAD_SUCCESS=false
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
|
||||
# Resolve latest Gitea tag if available
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
LATEST_TAG=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
LATEST_TAG="$(curl -sL --connect-timeout 3 "$GITEA_API_URL" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' || true)"
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
echo "Error: curl is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
[ -z "$LATEST_TAG" ] && LATEST_TAG="v0.8.9"
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
hash_file() { sha256sum "$1" | awk '{ print tolower($1) }'; }
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
hash_file() { shasum -a 256 "$1" | awk '{ print tolower($1) }'; }
|
||||
else
|
||||
echo "Error: SHA-256 verification requires sha256sum or shasum." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
MIRROR="${HOSE_USE_MIRROR:-auto}"
|
||||
case "$MIRROR" in auto|github|gitea) ;; *) echo "Invalid HOSE_USE_MIRROR: $MIRROR" >&2; exit 1 ;; esac
|
||||
|
||||
# Resolve latest Gitea tag if available. Resolve once, then pin every mirror and
|
||||
# checksum request to that exact version instead of guessing an old release.
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
GITHUB_API_URL="https://api.github.com/repos/${REPO}/releases/latest"
|
||||
LATEST_TAG="${HOSE_USE_VERSION:-}"
|
||||
if [ -n "$LATEST_TAG" ]; then
|
||||
LATEST_TAG="v${LATEST_TAG#v}"
|
||||
else
|
||||
api_urls=()
|
||||
if [ "$MIRROR" != "github" ]; then api_urls+=("$GITEA_API_URL"); fi
|
||||
if [ "$MIRROR" != "gitea" ]; then api_urls+=("$GITHUB_API_URL"); fi
|
||||
for api_url in "${api_urls[@]}"; do
|
||||
if release_json=$(curl -fsSL --connect-timeout 4 --max-time 15 "$api_url"); then
|
||||
LATEST_TAG=$(printf '%s' "$release_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^" ]*\)".*/\1/p' | head -n 1)
|
||||
if [ -n "$LATEST_TAG" ]; then break; fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if ! [[ "$LATEST_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then
|
||||
echo "Error: could not resolve a release version; set HOSE_USE_VERSION explicitly." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
release_bases=()
|
||||
if [ "$MIRROR" != "github" ]; then release_bases+=("https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}"); fi
|
||||
if [ "$MIRROR" != "gitea" ]; then
|
||||
release_bases+=("https://github.com/${REPO}/releases/download/${LATEST_TAG}")
|
||||
release_bases+=("https://ghfast.top/https://github.com/${REPO}/releases/download/${LATEST_TAG}")
|
||||
fi
|
||||
|
||||
verified_download() {
|
||||
local base="$1" asset="$2" expected actual
|
||||
if ! download_candidate "${base}/checksums.txt" "$CHECKSUM_FILE" "Release checksums"; then
|
||||
echo " ↳ Missing checksums.txt for ${LATEST_TAG}; refusing an unverified install." >&2
|
||||
return 1
|
||||
fi
|
||||
expected=$(awk -v name="$asset" '{ sub(/\r$/, "") } $2 == name || $2 == "*" name { count++; if (length($1) == 64 && $1 ~ /^[0-9a-fA-F]+$/) value=tolower($1); else invalid=1 } END { if (count == 1 && !invalid) print value; else exit 1 }' "$CHECKSUM_FILE") || {
|
||||
echo " ↳ Missing or ambiguous checksum for ${asset}." >&2
|
||||
return 1
|
||||
}
|
||||
if ! download_candidate "${base}/${asset}" "$TMP_FILE" "Release ${LATEST_TAG}"; then return 1; fi
|
||||
actual=$(hash_file "$TMP_FILE")
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
echo " ↳ SHA-256 mismatch for ${asset}; refusing this download." >&2
|
||||
return 1
|
||||
fi
|
||||
echo "✓ SHA-256 verified: ${asset}"
|
||||
}
|
||||
|
||||
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
|
||||
GITEA_ARCHIVE_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}.tar.gz"
|
||||
GITHUB_ARCHIVE_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
GHPROXY_ARCHIVE_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_ARCHIVE_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Archive)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_ARCHIVE_URL" "$TMP_FILE" "GitHub Releases (Archive Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_ARCHIVE_URL" "$TMP_FILE" "Fast CDN Mirror (Archive Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Second priority: Raw Executable (Fallback)
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
GITEA_RAW_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}"
|
||||
GITHUB_RAW_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_RAW_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_RAW_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Raw Binary)"; then
|
||||
# 2. Second priority: Raw Executable (Fallback), with the same checksum requirement.
|
||||
for format in archive raw; do
|
||||
asset="$ASSET_NAME"
|
||||
if [ "$format" = "archive" ]; then asset="${asset}.tar.gz"; fi
|
||||
for base in "${release_bases[@]}"; do
|
||||
if verified_download "$base" "$asset"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
DOWNLOADED_FORMAT="$format"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_RAW_URL" "$TMP_FILE" "GitHub Releases (Raw Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_RAW_URL" "$TMP_FILE" "Fast CDN Mirror (Raw Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [ "$DOWNLOAD_SUCCESS" = "true" ]; then break; fi
|
||||
done
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
echo "Error: Failed to download ${ASSET_NAME} from all candidate mirrors." >&2
|
||||
rm -f "$TMP_FILE"
|
||||
echo "Error: Failed to obtain a verified ${ASSET_NAME} for ${LATEST_TAG} from all candidate mirrors." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
|
||||
echo "==> Extracting archive to ${TARGET_DIR}..."
|
||||
tar -xzf "$TMP_FILE" -C "$TARGET_DIR"
|
||||
rm -f "$TMP_FILE"
|
||||
chmod +x "$TARGET_PATH"
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && chmod +x "${TARGET_DIR}/hose-aipro"
|
||||
echo "==> Extracting selected binary in temporary staging..."
|
||||
member=""
|
||||
listing=$(tar -tzf "$TMP_FILE")
|
||||
for candidate in "$ASSET_NAME" "./$ASSET_NAME" hose-use ./hose-use; do
|
||||
if printf '%s\n' "$listing" | awk -v name="$candidate" '$0 == name { count++ } END { exit count != 1 }'; then
|
||||
member="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$member" ]; then echo "Error: release archive has no expected platform binary." >&2; exit 1; fi
|
||||
# Stream only the exact member; archive paths and aliases never get written to bin.
|
||||
tar -xOzf "$TMP_FILE" "$member" > "${TMP_DIR}/hose-use"
|
||||
if [ ! -s "${TMP_DIR}/hose-use" ]; then echo "Error: release binary is empty." >&2; exit 1; fi
|
||||
else
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
mv "$TMP_FILE" "${TMP_DIR}/hose-use"
|
||||
fi
|
||||
|
||||
# Stage on the target filesystem so the final rename is atomic.
|
||||
INSTALL_STAGE=$(mktemp "${TARGET_DIR}/.hose-use-install.XXXXXX")
|
||||
cp "${TMP_DIR}/hose-use" "$INSTALL_STAGE"
|
||||
chmod 755 "$INSTALL_STAGE"
|
||||
# Ad-hoc sign on macOS
|
||||
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
|
||||
echo "==> Applying macOS code signature..."
|
||||
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && codesign --force --sign - "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
codesign --force --sign - "$INSTALL_STAGE" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
mv -f "$INSTALL_STAGE" "$TARGET_PATH"
|
||||
INSTALL_STAGE=""
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
ln -sfn hose-use "${TARGET_DIR}/hose-aipro"
|
||||
|
||||
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
|
||||
"$TARGET_PATH" skill install >/dev/null 2>&1 || true
|
||||
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
|
||||
if "$TARGET_PATH" skill install --yes; then
|
||||
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
|
||||
else
|
||||
echo "Error: binary installed to ${TARGET_PATH}, but Agent Skill installation failed. Retry: hose-use skill install --yes" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✨ hose-use successfully installed to ${TARGET_PATH}!"
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readlinkSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const fixtures: string[] = [];
|
||||
afterEach(() => { for (const root of fixtures.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const hash = (data: Buffer | string) => createHash("sha256").update(data).digest("hex");
|
||||
|
||||
function fixture(options: { badHash?: boolean; missingEntry?: boolean; duplicate?: boolean; rawOnly?: boolean } = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-installer-test-"));
|
||||
fixtures.push(root);
|
||||
const tools = join(root, "tools"), source = join(root, "release"), target = join(root, "bin");
|
||||
for (const dir of [tools, source, target]) mkdirSync(dir);
|
||||
const binary = `#!/bin/sh
|
||||
if [ "$1" = "skill" ]; then
|
||||
printf '%s\\n' "$*" > "$HOSE_FIXTURE_LOG"
|
||||
[ "$2" = "install" ] && [ "$3" = "--yes" ] || exit 10
|
||||
[ "\${HOSE_FIXTURE_SKILL_FAIL:-0}" != "1" ] || exit 3
|
||||
else
|
||||
printf 'hose-use v9.9.9\\n'
|
||||
fi
|
||||
`;
|
||||
const asset = "hose-use-linux-x64";
|
||||
writeFileSync(join(source, asset), binary, { mode: 0o755 });
|
||||
symlinkSync(asset, join(source, "hose-aipro"));
|
||||
writeFileSync(join(source, "unrelated.txt"), "must not reach the install directory");
|
||||
const archive = `${asset}.tar.gz`;
|
||||
expect(spawnSync("tar", ["-czf", join(source, archive), "-C", source, asset, "hose-aipro", "unrelated.txt"]).status).toBe(0);
|
||||
const entry = `${options.badHash ? "0".repeat(64) : hash(readFileSync(join(source, archive)))} ${archive}\n`;
|
||||
writeFileSync(join(source, "checksums.txt"), (options.missingEntry ? "" : entry + (options.duplicate ? entry : "")) + `${options.badHash ? "0".repeat(64) : hash(binary)} ${asset}\n`);
|
||||
if (options.rawOnly) rmSync(join(source, archive));
|
||||
const curl = `#!/bin/bash
|
||||
set -eu
|
||||
url=""; dest=""; head_only=false
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
-o) dest="$2"; shift 2 ;;
|
||||
--connect-timeout|--max-time) shift 2 ;;
|
||||
-fIs) head_only=true; shift ;;
|
||||
https://*) url="$1"; shift ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
done
|
||||
printf '%s\\n' "$url" >> "$HOSE_FIXTURE_REQUESTS"
|
||||
if [ "\${HOSE_FIXTURE_GITEA_FAIL:-0}" = "1" ] && [[ "$url" == *git.ying-qing.cn* ]]; then exit 22; fi
|
||||
if [[ "$url" == */releases/latest ]]; then
|
||||
[ "\${HOSE_FIXTURE_NO_TAG:-0}" != "1" ] || exit 22
|
||||
printf '{"tag_name": "v9.9.9"}'
|
||||
exit 0
|
||||
fi
|
||||
name="\${url##*/}"
|
||||
if [ "$name" = "checksums.txt" ] && [ "\${HOSE_FIXTURE_NO_MANIFEST:-0}" = "1" ]; then exit 22; fi
|
||||
file="$HOSE_FIXTURE_SOURCE/$name"
|
||||
[ -f "$file" ] || exit 22
|
||||
if [ "$head_only" = "true" ]; then exit 0; fi
|
||||
if [ -n "$dest" ]; then cp "$file" "$dest"; else cat "$file"; fi
|
||||
`;
|
||||
writeFileSync(join(tools, "curl"), curl, { mode: 0o755 });
|
||||
writeFileSync(join(tools, "uname"), '#!/bin/sh\nif [ "$1" = "-s" ]; then echo Linux; else echo x86_64; fi\n', { mode: 0o755 });
|
||||
const run = (env: Record<string, string> = {}) => spawnSync("bash", [resolve(import.meta.dir, "install.sh")], {
|
||||
cwd: root,
|
||||
env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, HOSE_USE_INSTALL_DIR: target, HOSE_USE_VERSION: "9.9.9", HOSE_USE_MIRROR: "auto", HOSE_FIXTURE_SOURCE: source, HOSE_FIXTURE_LOG: join(root, "skill.log"), HOSE_FIXTURE_REQUESTS: join(root, "requests.log"), ...env },
|
||||
encoding: "utf8", timeout: 10_000,
|
||||
});
|
||||
return { root, source, target, run, binary };
|
||||
}
|
||||
|
||||
describe("verified standalone installer", () => {
|
||||
test("installs a platform-named archive and alias, then explicitly confirms Skill setup", () => {
|
||||
const f = fixture();
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
|
||||
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
|
||||
expect(readFileSync(join(f.root, "skill.log"), "utf8").trim()).toBe("skill install --yes");
|
||||
expect(readdirSync(f.target).sort()).toEqual(["hose-aipro", "hose-use"]);
|
||||
});
|
||||
|
||||
for (const options of [{ badHash: true }, { missingEntry: true }, { duplicate: true }]) {
|
||||
test(`rejects an invalid manifest/archive and preserves the old binary: ${JSON.stringify(options)}`, () => {
|
||||
const f = fixture(options);
|
||||
// Remove raw fallback, so a missing archive entry cannot be hidden by another valid asset.
|
||||
rmSync(join(f.source, "hose-use-linux-x64"));
|
||||
writeFileSync(join(f.target, "hose-use"), "old binary");
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(1);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
|
||||
expect(existsSync(join(f.root, "skill.log"))).toBe(false);
|
||||
});
|
||||
}
|
||||
|
||||
test("does not silently bypass missing checksums or guess an old tag", () => {
|
||||
const f = fixture();
|
||||
expect(f.run({ HOSE_FIXTURE_NO_MANIFEST: "1" }).status).toBe(1);
|
||||
const unknown = f.run({ HOSE_USE_VERSION: "", HOSE_FIXTURE_NO_TAG: "1" });
|
||||
expect(unknown.status).toBe(1);
|
||||
expect(unknown.stderr).toContain("could not resolve");
|
||||
expect(existsSync(join(f.target, "hose-use"))).toBe(false);
|
||||
expect(readFileSync(join(f.root, "requests.log"), "utf8")).not.toContain("v0.8.9");
|
||||
});
|
||||
|
||||
test("uses a verified raw fallback and a fixed tag when the first mirror fails", () => {
|
||||
const f = fixture({ rawOnly: true });
|
||||
const result = f.run({ HOSE_FIXTURE_GITEA_FAIL: "1", HOSE_USE_VERSION: "" });
|
||||
expect(result.status).toBe(0);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
|
||||
const requests = readFileSync(join(f.root, "requests.log"), "utf8");
|
||||
expect(requests).toContain("/download/v9.9.9/");
|
||||
expect(requests).not.toContain("/latest/download/");
|
||||
});
|
||||
|
||||
test("reports Skill failure without claiming it was installed", () => {
|
||||
const f = fixture();
|
||||
const result = f.run({ HOSE_FIXTURE_SKILL_FAIL: "1" });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("binary installed");
|
||||
expect(result.stdout).not.toContain("Agent skill installed");
|
||||
expect(result.stdout).not.toContain("successfully installed");
|
||||
});
|
||||
|
||||
test("does not replace directories or follow an existing alias into a directory", () => {
|
||||
const f = fixture();
|
||||
mkdirSync(join(f.root, "personal"));
|
||||
symlinkSync(join(f.root, "personal"), join(f.target, "hose-aipro"));
|
||||
expect(f.run().status).toBe(0);
|
||||
expect(readdirSync(join(f.root, "personal"))).toEqual([]);
|
||||
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
|
||||
rmSync(join(f.target, "hose-aipro"));
|
||||
mkdirSync(join(f.target, "hose-aipro"));
|
||||
writeFileSync(join(f.target, "hose-use"), "old binary");
|
||||
expect(f.run().status).toBe(1);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parse } from "yaml";
|
||||
import { bumpVersion } from "./bump-version.js";
|
||||
import { verifyReleaseTag } from "./verify-release.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
|
||||
function repository() {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-release-test-"));
|
||||
roots.push(root);
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
git("init", "--initial-branch=main");
|
||||
git("config", "user.name", "Release fixture");
|
||||
git("config", "user.email", "fixture@example.test");
|
||||
git("config", "core.hooksPath", "/dev/null");
|
||||
git("config", "commit.gpgsign", "false");
|
||||
git("config", "tag.gpgsign", "false");
|
||||
for (const dir of ["skills/hose-use", "specs/openapi", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true });
|
||||
writeFileSync(join(root, "package.json"), '{"version":"1.0.0"}\n');
|
||||
writeFileSync(join(root, "README.md"), "# hose-use (v1.0.0)\n");
|
||||
writeFileSync(join(root, "skills/hose-use/SKILL.md"), "version: 1.0.0\n# hose-use (v1.0.0)\n");
|
||||
writeFileSync(join(root, "specs/openapi/openapi.yaml"), "info:\n version: 1.0.0\n");
|
||||
writeFileSync(join(root, ".zcode-plugin/plugin.json"), '{"version":"1.0.0"}\n');
|
||||
git("add", ".");
|
||||
git("commit", "-m", "fixture");
|
||||
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
||||
return { root, git, version: () => JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version };
|
||||
}
|
||||
|
||||
describe("release preparation and publication guards", () => {
|
||||
test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => {
|
||||
const f = repository();
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("release-v1.0.1");
|
||||
f.git("switch", "-c", "codex/release-v1.0.1");
|
||||
writeFileSync(join(f.root, "untracked.txt"), "work in progress");
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("clean working tree");
|
||||
rmSync(join(f.root, "untracked.txt"));
|
||||
for (const version of ["1.0.0", "0.9.9", "1.0.01", "1.0.1-rc.01", "invalid"]) expect(() => bumpVersion(f.root, version, () => {})).toThrow();
|
||||
expect(f.version()).toBe("1.0.0");
|
||||
expect(f.git("status", "--porcelain")).toBe("");
|
||||
});
|
||||
|
||||
test("bump updates sources on its release branch and explicitly invokes regeneration", () => {
|
||||
const f = repository();
|
||||
f.git("switch", "-c", "release/v1.0.1");
|
||||
let rebuilt = false;
|
||||
expect(bumpVersion(f.root, "patch", () => { rebuilt = true; })).toBe("1.0.1");
|
||||
expect(rebuilt).toBe(true);
|
||||
expect(f.version()).toBe("1.0.1");
|
||||
expect(readFileSync(join(f.root, "skills/hose-use/SKILL.md"), "utf8")).toContain("version: 1.0.1");
|
||||
expect(parse(readFileSync(join(f.root, "specs/openapi/openapi.yaml"), "utf8")).info.version).toBe("1.0.1");
|
||||
});
|
||||
|
||||
test("an existing release tag cannot be reused during bump", () => {
|
||||
const f = repository();
|
||||
f.git("switch", "-c", "release/v1.0.1");
|
||||
f.git("tag", "v1.0.1");
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("already exists");
|
||||
expect(f.version()).toBe("1.0.0");
|
||||
});
|
||||
|
||||
test("publication validates the actual HEAD, main ancestry and package version", () => {
|
||||
const f = repository();
|
||||
f.git("tag", "v1.0.0");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.0")).not.toThrow();
|
||||
expect(() => verifyReleaseTag(f.root, "main")).toThrow("Invalid release tag");
|
||||
f.git("tag", "v9.9.9");
|
||||
expect(() => verifyReleaseTag(f.root, "v9.9.9")).toThrow("does not match");
|
||||
f.git("switch", "-c", "unmerged");
|
||||
writeFileSync(join(f.root, "change"), "unreviewed");
|
||||
f.git("add", "."); f.git("commit", "-m", "unmerged fixture");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.0")).toThrow("exact tagged commit");
|
||||
f.git("tag", "v1.0.1");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.1")).toThrow("ancestor");
|
||||
});
|
||||
|
||||
test("workflows validate committed versions before generation and ship the checksum manifest", () => {
|
||||
const root = join(import.meta.dir, "..");
|
||||
const ci = parse(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"));
|
||||
const release = parse(readFileSync(join(root, ".github/workflows/release.yml"), "utf8"));
|
||||
expect(ci.on.pull_request.branches).toContain("main");
|
||||
expect(ci.permissions.contents).toBe("read");
|
||||
const steps = release.jobs["build-and-publish"].steps;
|
||||
const runs = steps.map((s: { run?: string }) => s.run || "");
|
||||
expect(runs.findIndex((s: string) => s.includes("check:version"))).toBeLessThan(runs.findIndex((s: string) => s.includes("openapi:all")));
|
||||
expect(steps[0].with.ref).toContain("inputs.tag");
|
||||
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
|
||||
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");
|
||||
});
|
||||
|
||||
test("a failed background Gitea upload makes the Release step fail", () => {
|
||||
const f = repository();
|
||||
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");
|
||||
mkdirSync(join(f.root, "tools")); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
|
||||
writeFileSync(join(f.root, "dist/bin/hose-use-linux-x64"), "fixture");
|
||||
writeFileSync(join(f.root, "dist/bin/checksums.txt"), "fixture checksums");
|
||||
writeFileSync(join(f.root, "tools/curl"), `#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
*/assets?*) exit 22 ;;
|
||||
*/releases) printf '{"id":42}'; exit 0 ;;
|
||||
*/releases/42) printf '{"assets":[]}'; exit 0 ;;
|
||||
esac
|
||||
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 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bun
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
|
||||
const binary = resolve(process.argv[2] || "dist/bin/hose-use");
|
||||
const plugin = process.argv.includes("--plugin");
|
||||
const command = plugin ? process.execPath : binary;
|
||||
const prefix = plugin ? [binary] : [];
|
||||
const cwd = mkdtempSync(join(tmpdir(), "hose-binary-smoke-"));
|
||||
// The binary must work without Bun on PATH or a source checkout in cwd.
|
||||
const env = { PATH: process.platform === "win32" ? process.env.SystemRoot || "C:\\Windows" : "/usr/bin:/bin", HOSE_USE_MCP_ENABLED: "true", HOSE_CONFIG_FILE: join(cwd, "config.json"), HOSE_ENTERPRISES_DIR: cwd };
|
||||
const client = new Client({ name: "hose-binary-smoke", version: "1.0.0" });
|
||||
const transport = new StdioClientTransport({ command, args: plugin ? prefix : ["mcp", "serve"], cwd, env, stderr: "pipe" });
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", chunk => { stderr += chunk.toString(); });
|
||||
const deadline = setTimeout(() => { void client.close(); }, 15_000);
|
||||
try {
|
||||
const version = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "version", "--json"], { cwd, env, encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(version.status, 0, version.stderr);
|
||||
assert.ok(JSON.parse(version.stdout).version);
|
||||
await client.connect(transport, { timeout: 5000 });
|
||||
const tools = await client.listTools();
|
||||
assert.deepEqual(tools.tools.map(tool => tool.name), ["hose_cli"]);
|
||||
const result = await client.callTool({ name: "hose_cli", arguments: { command: "version --json" } });
|
||||
assert.ok(!result.isError, JSON.stringify(result));
|
||||
const text = (result.content as Array<{ type: string; text?: string }>).find(c => c.type === "text")?.text;
|
||||
assert.equal(JSON.parse(text || "").version, JSON.parse(version.stdout).version);
|
||||
const invalid = await client.callTool({ name: "hose_cli", arguments: { command: "bill list --limitt 5 --json" } });
|
||||
assert.equal(invalid.isError, true);
|
||||
assert.match(JSON.stringify(invalid.content), /未知选项/);
|
||||
console.log(plugin ? "Plugin bundle version and MCP stdio verified with its Bun runtime." : "Binary version and MCP stdio verified without Bun or source files.");
|
||||
} catch (error) {
|
||||
throw new Error(`Binary smoke failed: ${error instanceof Error ? error.message : error}\n${stderr}`);
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
await client.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bun
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { isReleaseVersion } from "./bump-version.js";
|
||||
|
||||
export function verifyReleaseTag(root: string, tag: string): void {
|
||||
if (!tag.startsWith("v") || !isReleaseVersion(tag.slice(1))) throw new Error(`Invalid release tag: ${tag}`);
|
||||
const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
const taggedCommit = git(["rev-parse", "--verify", `refs/tags/${tag}^{commit}`]);
|
||||
if (git(["rev-parse", "HEAD"]) !== taggedCommit) throw new Error("Release HEAD must be the exact tagged commit");
|
||||
try {
|
||||
git(["merge-base", "--is-ancestor", taggedCommit, "refs/remotes/origin/main"]);
|
||||
} catch {
|
||||
throw new Error("Release tag must be an ancestor of origin/main; merge the PR before tagging");
|
||||
}
|
||||
const { version } = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
|
||||
if (tag !== `v${version}`) throw new Error(`Release tag ${tag} does not match package.json v${version}`);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
verifyReleaseTag(resolve(import.meta.dir, ".."), process.argv[2] || "");
|
||||
console.log("Release tag, HEAD, main ancestry and package version verified.");
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.13
|
||||
version: 0.8.14
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.13)
|
||||
# hose-use (v0.8.14)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -202,6 +202,20 @@ 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 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 预览)
|
||||
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
|
||||
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
|
||||
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
|
||||
hose-use workflow tail wf_01k83y... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
|
||||
hose-use workflow tail wf_01k83y... --failed-only # 仅在有报错或异常跳过 (SKIPPED) 时即时打印详情
|
||||
hose-use workflow tail wf_01k83y... --once --json # 检视最新或当前运行中的 Job 进度快照并返回结构化数据
|
||||
hose-use workflow lint-script wf_01k83y... # 批量静态校验代码节点语法规范与上游依赖 (支持 --file/--code)
|
||||
hose-use workflow eval-script wf_01k83y... <节点> --sample=1 # 离线沙箱仿真运行 JS 节点并复用样本数据 (支持 --input/--timeout)
|
||||
|
||||
# 6. OpenAPI 密钥与应用中心
|
||||
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
|
||||
|
||||
@@ -234,7 +234,135 @@ hose-use workflow publish <pipelineId>
|
||||
|
||||
---
|
||||
|
||||
## 14. 工作流排障与创单排错三大黄金法则(必读)
|
||||
## 14. 从零创建、复制与删除工作流 (`workflow create` / `copy` / `delete`)
|
||||
|
||||
对标合思 EASO/Piper 网页端“新建工作流”、“复制流水线”与“删除”功能,严格遵循 `--dry-run` 预览与 `--yes` 安全确认门禁,且新流程初始状态**强制锁定为草稿未启用(`state = 0`)**:
|
||||
|
||||
```bash
|
||||
# 1. 从零新建工作流(支持自动初始化 Webhook、定时 Clock、业务对象 DataLink 或单据 Flowform 首节点)
|
||||
hose-use workflow create --name="外部风险推送" --trigger=webhook --yes
|
||||
hose-use workflow create --name="每日发票对账" --trigger=clock --platform-id=ID01uzxB4x07fh --yes
|
||||
|
||||
# 2. 从本地 JSON 模板文件一键新建
|
||||
hose-use workflow create --file=workflow-template.json --name="生产流程-A" --yes
|
||||
|
||||
# 别名支持 new, add
|
||||
hose-use workflow new --name="合同归档触发" --trigger=datalink --yes
|
||||
|
||||
# 3. 复制已有工作流为新草稿(默认名称加" 副本",首节点为 Webhook 时自动重新分配独立 urlPath 并清理老样本)
|
||||
hose-use workflow copy <pipelineId> --dry-run
|
||||
hose-use workflow copy <pipelineId> --name="发票监控克隆版" --yes
|
||||
|
||||
# 别名支持 cp, clone
|
||||
hose-use workflow cp <pipelineId> --yes
|
||||
|
||||
# 4. 删除指定工作流(不可逆,必须确认)
|
||||
hose-use workflow delete <pipelineId> --dry-run
|
||||
hose-use workflow delete <pipelineId> --yes
|
||||
|
||||
# 别名支持 rm, remove
|
||||
hose-use workflow rm <pipelineId> --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 15. 工作流节点级声明式编排与编辑 (`workflow node`)
|
||||
|
||||
针对合思 EASO/Piper 任务流水线内部的复杂节点树(支持 `every` 循环、`condition` 分支多层深度嵌套),提供直接按节点标识(如 `action_xxx`)或层级序号(如 `1`, `2.1`, `2.2.1`)定向查看、追加、修改与移除的能力,避免手动拼接庞大 JSON 报文的低效与格式错误:
|
||||
|
||||
```bash
|
||||
# 1. 树形层级索引查看工作流中所有任务节点与配置摘要 (别名: ls)
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node list <pipelineId> --json
|
||||
|
||||
# 2. 定向查看指定节点的完整属性与映射详情 (别名: show, info)
|
||||
# 支持传节点 name (如 action_dx9cci) 或序号 (如 2 或 2.1)
|
||||
hose-use workflow node get <pipelineId> action_dx9cci
|
||||
hose-use workflow node get <pipelineId> 2 --json
|
||||
|
||||
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
|
||||
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --yes
|
||||
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
|
||||
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
|
||||
|
||||
# 4. 定向修改指定节点配置 (别名: update, set)
|
||||
# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --yes
|
||||
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||
|
||||
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
||||
# 自动标准化重排同层 index 与 levelIndex;内置首节点触发器保护,严禁误删流程唯一的触发源
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --dry-run
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --yes
|
||||
hose-use workflow node rm <pipelineId> 3 --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. 实时任务监听与执行日志流 (`workflow tail` / `watch` / `follow`)
|
||||
|
||||
类似 Unix `tail -f` 实时监听工作流在合思云端的任务派发与节点执行树跃迁。当有外部 Webhook 推送、定时 CRON 调度或业务单据流转触发工作流时,无需反复手动敲 `workflow logs` 或 `workflow job` 轮询,即时流式打出节点状态跃迁与详细报错:
|
||||
|
||||
```bash
|
||||
# 1. 类似 tail -f 实时监听流水线任务派发与各节点执行状态跃迁 (别名: watch, follow)
|
||||
hose-use workflow tail <pipelineId>
|
||||
hose-use workflow watch <pipelineId> --interval=1
|
||||
|
||||
# 2. 针对指定单次运行中的 Job 进行实时跟踪直至执行完成
|
||||
hose-use workflow tail <pipelineId> --job=<jobId>
|
||||
hose-use workflow tail 898268773466365973 --job=898577624451395602
|
||||
|
||||
# 3. 仅在有报错或异常跳过 (SKIPPED) 节点时即时告警并打出底层错误
|
||||
hose-use workflow tail <pipelineId> --failed-only
|
||||
|
||||
# 4. 检视最新或当前运行中的 Job 进度快照 (不进入持续循环,适合脚本快速检查)
|
||||
hose-use workflow tail <pipelineId> --once
|
||||
hose-use workflow tail <pipelineId> --once --json
|
||||
|
||||
# 5. 设置最长监听超时 (秒)
|
||||
hose-use workflow tail <pipelineId> --timeout=60
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 17. 工作流代码节点静态校验与离线沙箱仿真 (`workflow lint-script` / `eval-script`)
|
||||
|
||||
合思工作流支持自定义 JavaScript (`code-js2`) 与 MVEL (`code`) 脚本节点。以往只能在生产派发调试 Job 才能验证脚本,不仅污染发布版本快照,还容易因死循环、语法报错或悬空上游节点引发流程中断。`hose-use` 提供了纯本地 AST 语法检查与安全隔离沙箱运行能力:
|
||||
|
||||
```bash
|
||||
# 1. 静态扫描整条工作流中所有代码节点的语法、return 语句与上游依赖引用
|
||||
hose-use workflow lint-script <pipelineId>
|
||||
hose-use workflow lint <pipelineId> --json
|
||||
|
||||
# 2. 定向检查指定代码节点(支持节点名称或 #序号)
|
||||
hose-use workflow lint-script <pipelineId> action_dx9cci
|
||||
|
||||
# 3. 静态检查本地脚本文件或命令行传入的代码片段
|
||||
hose-use workflow lint-script --file=./scripts/clean.js
|
||||
hose-use workflow lint-script --code="const a = 1; return a * 2;"
|
||||
hose-use workflow lint-script --code="var a = control_123; return a;" --type=mvel
|
||||
|
||||
# 4. 在离线安全沙箱中仿真运行工作流中的某个 JavaScript 节点 (code-js2)
|
||||
# 自动复用最近一次历史真实样本数据作为入参,打印返回值与全部 console.log 日志:
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci
|
||||
|
||||
# 5. 指定历史测试样本序号(如第 2 条样本)进行离线仿真
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci --sample=2
|
||||
|
||||
# 6. 自定义输入参数执行离线仿真 (JSON 字符串或本地 JSON 文件)
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci --input='{"info":{"amount":100}}'
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci --input-file=./mock_input.json
|
||||
|
||||
# 7. 纯本地行内代码沙箱快速求值与死循环超时控制 (--timeout 默认 3000ms)
|
||||
hose-use workflow eval-script --code="console.log(items); return items.filter(x => x.active);" --input='{"items":[{"id":1,"active":true},{"id":2,"active":false}]}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 18. 工作流排障与创单排错三大黄金法则(必读)
|
||||
|
||||
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.13",
|
||||
"version": "0.8.14",
|
||||
"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.13
|
||||
version: 0.8.14
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+17
-4
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseArgs, stringOption, booleanOption } from "./cli/parser.js";
|
||||
import { printJson, redactSensitiveText } from "./cli/printer.js";
|
||||
import { parseArgs, stringOption, booleanOption, isJsonRequested } from "./cli/parser.js";
|
||||
import { cliErrorResult } from "./cli/runner.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./cli/printer.js";
|
||||
import { getSessionClientForRuntime, initCorpRuntime, requireSelectedCorp } from "./cli/helpers.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
@@ -27,10 +28,22 @@ import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
export async function runAiProCli(
|
||||
rawArgs: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
try {
|
||||
return await runAiProCliOnce(rawArgs);
|
||||
} catch (error) {
|
||||
return cliErrorResult(error, isJsonRequested(rawArgs));
|
||||
}
|
||||
}
|
||||
|
||||
async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs, "aipro");
|
||||
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
|
||||
if (booleanOption(parsed.options, ["help", "h", "?"])) {
|
||||
const help = printHelp(["aipro", ...(parsed.area && parsed.area !== "help" ? [parsed.area] : [])]);
|
||||
return { stdout: jsonMode ? printJson({ help }) : `${help}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
const runtime = initCorpRuntime({
|
||||
corpId: stringOption(parsed.options, ["corp", "c"]),
|
||||
corpId: stringOption(parsed.options, ["corp"]),
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname } from "node:path";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { writeStdoutChunk } from "./cli/printer.js";
|
||||
|
||||
process.stdout.on("error", (err: any) => {
|
||||
if (err?.code === "EPIPE") process.exit(0);
|
||||
@@ -26,6 +27,7 @@ const result = isAiPro
|
||||
: await runCli(process.argv.slice(2), {
|
||||
appRoot,
|
||||
entryFile,
|
||||
writeStdout: writeStdoutChunk,
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
+14
-2
@@ -4,12 +4,14 @@
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层命令唯一声明式注册表(`area` / `aliases` / `standing` 常驻属性 / `handler`)。新增命令先在此注册。
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
|
||||
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`)。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
|
||||
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
|
||||
- `help.ts`:帮助文本组织。
|
||||
@@ -20,3 +22,13 @@
|
||||
|
||||
- handler 统一签名 `(parsed, runtime, options) => Promise<CliResult>`。
|
||||
- 命令文件内部不重复做异常体系,只抛/透传 `EkbError` 子类。
|
||||
|
||||
## 嵌入调用与流式输出
|
||||
|
||||
`runCli` 默认通过 `CliResult` 返回结果,不直接写进进程 stdout。终端入口可显式传入 `CliRunOptions.writeStdout` 异步回调;处理器必须等待回调完成,保证慢管道有背压。MCP / HTTP 不提供该回调,流式记录应使用 `--output-file`,否则返回用法错误。普通命令的返回结构保持不变。
|
||||
|
||||
参数解析与运行时初始化也经过统一异常边界。`--json` 的错误对象继续写入 `stdout`,保留退出码和恢复建议;人类日志写入 `stderr`。`help <域>`、`<域> --help` 支持同一份域别名,帮助主题不存在时返回用法错误。处理器自身保留的详细用法说明仍可供直接嵌入调用使用。
|
||||
|
||||
优先用 `--corp` 明确指定企业。短参数 `-c` 在命令之前表示全局企业选择;在声明了同名参数的命令之后,遵循该命令的含义(例如 `bill list -c` 为单号)。布尔值可写 `--active=false` 或 `--active false`;数字形式使用 `=0` / `=1`,空格后的数字保留为可能的位置 ID。`--` 之后的内容全部作为位置参数。
|
||||
|
||||
`hose-use mcp [serve]` 在当前进程启动服务,不派生 Bun 或访问源码脚本;MCP 调用继续只通过 `hose_cli` 分发,流式终端回调不会被注入协议通道。
|
||||
@@ -39,6 +39,17 @@ function resolveImportRelativeToSrc(fromFile: string, specifier: string): string
|
||||
}
|
||||
|
||||
describe("Architecture Layering Boundaries", () => {
|
||||
test("workflow imports use the module directories after the platform migration", () => {
|
||||
const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/;
|
||||
const violations: string[] = [];
|
||||
for (const file of collectTsFiles(SRC_ROOT, true)) {
|
||||
for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) {
|
||||
const target = resolveImportRelativeToSrc(file, specifier);
|
||||
if (target && legacy.test(target)) violations.push(`${relative(SRC_ROOT, file)} -> ${target}`);
|
||||
}
|
||||
}
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => {
|
||||
const entrypointFiles = [
|
||||
...collectTsFiles(join(SRC_ROOT, "cli")),
|
||||
|
||||
@@ -0,0 +1,809 @@
|
||||
/** Static command vocabulary shared by dispatch, parsing and help. No handler imports. */
|
||||
export type FlagKind = "boolean" | "value" | "boolean-or-value";
|
||||
export interface HelpTopic {
|
||||
summary: string; usage: string; commands: Record<string, string>; options?: string[];
|
||||
}
|
||||
export interface CliCommandMetadata extends HelpTopic {
|
||||
aliases: string[]; commandAliases: Record<string, string>; flags: Record<string, FlagKind>;
|
||||
}
|
||||
|
||||
export const GLOBAL_FLAGS: Record<string, FlagKind> = {
|
||||
...Object.fromEntries("json j help h ? version v V full allow-full allowFull summary stateless stateful dry-run dryRun dryrun yes y confirm force-write forceWrite force".split(" ").map(k => [k, "boolean" as const])),
|
||||
...Object.fromEntries("corp c output-file outputFile o".split(" ").map(k => [k, "value" as const])),
|
||||
};
|
||||
|
||||
function flagList(keys: string, kind: FlagKind): Record<string, FlagKind> {
|
||||
return Object.fromEntries(keys.split(" ").filter(Boolean).map(key => [key, kind]));
|
||||
}
|
||||
|
||||
export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"context": {
|
||||
"summary": "全局运行上下文与身份诊断",
|
||||
"usage": "hose-use context [--json]",
|
||||
"commands": {
|
||||
"context": "输出当前企业、账号、运行模式与认证状态"
|
||||
},
|
||||
"aliases": [
|
||||
"status",
|
||||
"whoami",
|
||||
"env"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"aipro": {
|
||||
"summary": "AI PRO 确定性审批仲裁",
|
||||
"usage": "hose-use aipro <子命令>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"context": "status",
|
||||
"info": "status",
|
||||
"start": "init",
|
||||
"index": "scopes",
|
||||
"indexes": "scopes",
|
||||
"doc": "translate",
|
||||
"markdown": "translate",
|
||||
"render": "translate",
|
||||
"rule": "rules",
|
||||
"mount": "bind",
|
||||
"clauses": "points",
|
||||
"list": "checklist",
|
||||
"eval": "review",
|
||||
"evaluate": "review",
|
||||
"approve": "decide",
|
||||
"reject": "decide",
|
||||
"log": "logs",
|
||||
"history": "logs",
|
||||
"trail": "logs"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"auth": {
|
||||
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
"usage": "hose-use auth <子命令>",
|
||||
"commands": {
|
||||
"login": "登录并保存企业凭证",
|
||||
"status": "查看当前认证状态",
|
||||
"refresh": "刷新账号或企业 AccessToken",
|
||||
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
"accounts": "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
"import": "导入抓包或协助凭证",
|
||||
"hose-link": "生成企业免密登录链接",
|
||||
"sync-seal": "导入已保存的企业配置"
|
||||
},
|
||||
"aliases": [
|
||||
"login"
|
||||
],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"current": "status",
|
||||
"renew": "refresh",
|
||||
"add": "import",
|
||||
"import-link": "add-link",
|
||||
"auth-link": "hose-link",
|
||||
"login-link": "hose-link",
|
||||
"add-hose-persistent": "add-persistent",
|
||||
"add-openapi": "add-persistent",
|
||||
"add-hose": "add-persistent",
|
||||
"extract-key": "extract-keys",
|
||||
"hose-extract-keys": "extract-keys",
|
||||
"extract-hose-keys": "extract-keys",
|
||||
"elevate-hose": "elevate",
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal",
|
||||
"list": "accounts",
|
||||
"account": "accounts",
|
||||
"accs": "accounts",
|
||||
"switch": "switch-account",
|
||||
"use-account": "switch-account"
|
||||
},
|
||||
flags: { ...flagList("a p app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user accessToken account curl headers phone pwd raw token", "value"), ...flagList("add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite persist plain prod production r refresh reveal save save-staff t test upgrade-all verify i interactive sms sync", "boolean") }
|
||||
},
|
||||
"corps": {
|
||||
"summary": "多企业租户管理",
|
||||
"usage": "hose-use corps <子命令>",
|
||||
"commands": {
|
||||
"list": "列出本地企业配置",
|
||||
"search": "搜索企业与员工",
|
||||
"switch": "切换当前工作企业",
|
||||
"current": "查看当前企业",
|
||||
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
"tag": "标记企业环境",
|
||||
"hose-link": "生成企业免密登录链接",
|
||||
"sync-seal": "导入已有企业配置",
|
||||
"probe-hose": "检查企业接口连通性",
|
||||
"hose-staffs": "查询企业员工",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [
|
||||
"corp"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"find": "search",
|
||||
"query": "search",
|
||||
"filter": "search",
|
||||
"set-env": "tag",
|
||||
"mark": "tag",
|
||||
"use": "switch",
|
||||
"whoami": "current",
|
||||
"status": "current",
|
||||
"active": "current",
|
||||
"import-link": "add-link",
|
||||
"auth-link": "hose-link",
|
||||
"login-link": "hose-link",
|
||||
"add-hose-persistent": "add-persistent",
|
||||
"add-openapi": "add-persistent",
|
||||
"add-hose": "add-persistent",
|
||||
"extract-key": "extract-keys",
|
||||
"hose-extract-keys": "extract-keys",
|
||||
"extract-hose-keys": "extract-keys",
|
||||
"elevate-hose": "elevate",
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal"
|
||||
},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"config": {
|
||||
"summary": "全局运行模式与路径配置",
|
||||
"usage": "hose-use config <子命令>",
|
||||
"commands": {
|
||||
"paths": "诊断配置目录链",
|
||||
"get": "查看全局配置",
|
||||
"mode": "切换 stateful/stateless",
|
||||
"set": "更新指定配置项",
|
||||
"test-dir": "设置测试企业目录"
|
||||
},
|
||||
"aliases": [
|
||||
"mode"
|
||||
],
|
||||
"commandAliases": {
|
||||
"path": "paths",
|
||||
"dirs": "paths",
|
||||
"show": "paths",
|
||||
"list": "paths",
|
||||
"status": "get",
|
||||
"info": "get",
|
||||
"test-enterprises-dir": "test-dir"
|
||||
},
|
||||
flags: { ...flagList("clear", "boolean") }
|
||||
},
|
||||
"workflow": {
|
||||
"summary": "工作流查询、草稿、运行排障与生命周期管理",
|
||||
"usage": "hose-use workflow <子命令> [参数] [选项]",
|
||||
"commands": {
|
||||
"list": "列出工作流",
|
||||
"get": "查看工作流详情",
|
||||
"find": "按节点类型搜索",
|
||||
"analyze": "静态分析工作流(含禁用/SKIP/联动覆盖检查)",
|
||||
"job": "查看单次运行实例树、报错节点与MVEL日志",
|
||||
"diff": "对比两个工作流快照的结构与脚本差异",
|
||||
"diff-job": "对比两次执行的节点分支与报错发散点",
|
||||
"test": "端到端一键调试单据(替代前端手工调测)",
|
||||
"node": "声明式节点编排与增删改 (list|get|add|edit|rm)",
|
||||
"tail": "实时监听任务派发与节点执行日志流 (watch|follow)",
|
||||
"create": "从零新建工作流草稿",
|
||||
"copy": "复制克隆工作流",
|
||||
"delete": "删除工作流",
|
||||
"patch": "生成草稿字段补丁",
|
||||
"save": "保存草稿到远端",
|
||||
"toggle": "切换启停状态",
|
||||
"publish": "发布并启用工作流",
|
||||
"history": "查看版本历史",
|
||||
"logs": "查看运行日志",
|
||||
"check": "检查错误管道",
|
||||
"enum": "查询在线枚举字典(不可用时使用内置字典)",
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本"
|
||||
},
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
"--file=<workflow.json> 指定工作流快照",
|
||||
"--failed 只看失败节点",
|
||||
"--parent=<executionId> 展开循环/分支子节点",
|
||||
"--logs=<executionId> 查看节点执行日志",
|
||||
"--dry-run 只预览写操作",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
"workflows",
|
||||
"wf"
|
||||
],
|
||||
"commandAliases": {
|
||||
"list-all": "list",
|
||||
"ls": "list",
|
||||
"detail": "get",
|
||||
"info": "get",
|
||||
"search": "find",
|
||||
"enable": "publish",
|
||||
"update": "save",
|
||||
"snapshots": "history",
|
||||
"log": "logs",
|
||||
"execution": "job",
|
||||
"health": "check",
|
||||
"analyse": "analyze",
|
||||
"diff-snapshot": "diff",
|
||||
"diff-snapshots": "diff",
|
||||
"compare": "diff",
|
||||
"diff-jobs": "diff-job",
|
||||
"compare-job": "diff-job",
|
||||
"debug": "test",
|
||||
"run-test": "test",
|
||||
"cp": "copy",
|
||||
"clone": "copy",
|
||||
"rm": "delete",
|
||||
"remove": "delete",
|
||||
"new": "create",
|
||||
"add": "create",
|
||||
"nodes": "node",
|
||||
"watch": "tail",
|
||||
"follow": "tail",
|
||||
"lint": "lint-script",
|
||||
"lint-code": "lint-script",
|
||||
"eval": "eval-script",
|
||||
"eval-code": "eval-script",
|
||||
"run-script": "eval-script",
|
||||
"enums": "enum",
|
||||
"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") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
"usage": "hose-use bill <子命令> [单号|ID] [选项]",
|
||||
"commands": {
|
||||
"list": "查询单据",
|
||||
"get": "查看单据详情",
|
||||
"spec": "查看单据模板字段配置与联动覆盖规则",
|
||||
"flow": "查看审批流程",
|
||||
"approve": "同意审批",
|
||||
"reject": "驳回审批",
|
||||
"transfer": "转交审批",
|
||||
"add-node": "加签审批",
|
||||
"comment": "添加评论",
|
||||
"trace": "穿透诊断单据与当前待办",
|
||||
"schema": "查看单据实体模型",
|
||||
"risk": "查看风险信息",
|
||||
"budget": "查看预算状态",
|
||||
"refs": "解析关联人员与部门",
|
||||
"relations": "查看关联单据",
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容"
|
||||
],
|
||||
"aliases": [
|
||||
"bills",
|
||||
"fee",
|
||||
"fees",
|
||||
"invoice",
|
||||
"invoices"
|
||||
],
|
||||
"commandAliases": {
|
||||
"agree": "approve",
|
||||
"deny": "reject",
|
||||
"shift": "transfer",
|
||||
"addnode": "add-node",
|
||||
"countersign": "add-node",
|
||||
"counter-sign": "add-node",
|
||||
"remark": "comment",
|
||||
"search": "list",
|
||||
"show": "get",
|
||||
"find": "get",
|
||||
"inspect": "trace",
|
||||
"diagnose": "trace",
|
||||
"schemas": "schema",
|
||||
"entities": "schema",
|
||||
"records": "flow",
|
||||
"timeline": "flow",
|
||||
"review": "risk",
|
||||
"warnings": "risk",
|
||||
"budgets": "budget",
|
||||
"references": "refs",
|
||||
"resolve": "refs",
|
||||
"relation": "relations",
|
||||
"links": "relations",
|
||||
"attachment": "attachments",
|
||||
"files": "attachments",
|
||||
"file-download": "download",
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
"usage": "hose-use flow <子命令> [单号|ID]",
|
||||
"commands": {
|
||||
"get": "穿透诊断单据流转",
|
||||
"history": "查看审批流转时间线",
|
||||
"risk": "查看风险信息",
|
||||
"list": "查询单据",
|
||||
"approve": "审批同意",
|
||||
"reject": "审批驳回"
|
||||
},
|
||||
"aliases": [
|
||||
"flows",
|
||||
"trace"
|
||||
],
|
||||
"commandAliases": {
|
||||
"records": "history",
|
||||
"timeline": "history",
|
||||
"search": "list",
|
||||
"agree": "approve",
|
||||
"deny": "reject",
|
||||
"trace": "get",
|
||||
"inspect": "get",
|
||||
"diagnose": "get",
|
||||
"show": "get",
|
||||
"find": "get"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"contact": {
|
||||
"summary": "企业通讯录与人员检索",
|
||||
"usage": "hose-use contact <子命令>",
|
||||
"commands": {
|
||||
"list": "列出员工",
|
||||
"search": "搜索员工",
|
||||
"get": "查看员工详情"
|
||||
},
|
||||
"aliases": [
|
||||
"contacts",
|
||||
"staff",
|
||||
"staffs"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("id k keyword l limit query staff-id", "value") }
|
||||
},
|
||||
"task": {
|
||||
"summary": "待办中心与审批任务",
|
||||
"usage": "hose-use task <子命令>",
|
||||
"commands": {
|
||||
"todo": "待我审批",
|
||||
"approved": "我已审批",
|
||||
"submitted": "我发起的",
|
||||
"records": "审批记录",
|
||||
"cc": "抄送任务"
|
||||
},
|
||||
"aliases": [
|
||||
"tasks",
|
||||
"todo"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("read unread", "boolean"), ...flagList("count end-date from limit n offset staff staff-id staffId start start-date to", "value") }
|
||||
},
|
||||
"dimension": {
|
||||
"summary": "系统与自定义档案维度",
|
||||
"usage": "hose-use dimension <子命令>",
|
||||
"commands": {
|
||||
"list": "列出维度",
|
||||
"items": "列出维度项"
|
||||
},
|
||||
"aliases": [
|
||||
"dimensions",
|
||||
"archive",
|
||||
"archives"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("code count dimension id keyword limit n name q query", "value") }
|
||||
},
|
||||
"feetype": {
|
||||
"summary": "费用类型全生命周期管理与模板规格查询",
|
||||
"usage": "hose-use feetype <子命令> [参数]",
|
||||
"commands": {
|
||||
"list": "查看费用类型树",
|
||||
"get": "查看详情与字段",
|
||||
"spec": "查看单据/申请模板字段与联动规则",
|
||||
"create": "新建费用类型",
|
||||
"update": "修改属性",
|
||||
"disable": "停用",
|
||||
"enable": "启用",
|
||||
"move": "移动层级",
|
||||
"fields": "查看字段配置"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览写操作",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
"feetypes",
|
||||
"fee-type",
|
||||
"fee-types",
|
||||
"expense-type",
|
||||
"expense-types",
|
||||
"costtype"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") }
|
||||
},
|
||||
"role": {
|
||||
"summary": "企业角色定义与成员",
|
||||
"usage": "hose-use role <子命令>",
|
||||
"commands": {
|
||||
"list": "列出角色",
|
||||
"groups": "列出角色组",
|
||||
"members": "查看角色成员"
|
||||
},
|
||||
"aliases": [
|
||||
"roles"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("code count id keyword limit n name q query role", "value") }
|
||||
},
|
||||
"permission": {
|
||||
"summary": "权限模型快照",
|
||||
"usage": "hose-use permission get",
|
||||
"commands": {
|
||||
"get": "查看角色权限开关"
|
||||
},
|
||||
"aliases": [
|
||||
"permissions"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"rule": {
|
||||
"summary": "本地审批规约管理",
|
||||
"usage": "hose-use rule <子命令> [参数]",
|
||||
"commands": {
|
||||
"scopes": "列出适用场景",
|
||||
"scope": "查看场景明细",
|
||||
"list": "列出规则",
|
||||
"get": "查看规则详情",
|
||||
"add": "新增规则",
|
||||
"delete": "删除规则"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览增删",
|
||||
"--yes/--confirm 确认增删"
|
||||
],
|
||||
"aliases": [
|
||||
"rules"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("all", "boolean"), ...flagList("b body code id index name s scope status target", "value") }
|
||||
},
|
||||
"approval": {
|
||||
"summary": "确定性审批网关与要点仲裁",
|
||||
"usage": "hose-use approval audit <子命令> [单号]",
|
||||
"commands": {
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"review": "核验事实",
|
||||
"decide": "生成或执行仲裁决定",
|
||||
"audit": "审批核验与仲裁入口"
|
||||
},
|
||||
"options": [
|
||||
"--apply --yes 执行真实审批流转"
|
||||
],
|
||||
"aliases": [
|
||||
"approvals",
|
||||
"audit"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("apply confirm do execute run y yes", "boolean"), ...flagList("action code comment data e eval evidence findings i id index m message p point proof r reason reasoning s scope sn state status target", "value") }
|
||||
},
|
||||
"message": {
|
||||
"summary": "消息中心与通知管理",
|
||||
"usage": "hose-use message <子命令>",
|
||||
"commands": {
|
||||
"list": "查询消息",
|
||||
"count": "查看未读数",
|
||||
"read": "标记消息已读",
|
||||
"read-all": "全部标记已读"
|
||||
},
|
||||
"aliases": [
|
||||
"messages",
|
||||
"notify",
|
||||
"notifications"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("all read unread", "boolean"), ...flagList("count id limit message-id message-type n offset start type", "value") }
|
||||
},
|
||||
"platform": {
|
||||
"summary": "自建应用、业务对象、全量记录安全更新与台账体检",
|
||||
"usage": "hose-use platform <子命令> [参数]",
|
||||
"commands": {
|
||||
"list": "列出自建应用",
|
||||
"entities": "列出业务对象",
|
||||
"schema": "查看字段定义",
|
||||
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
||||
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
||||
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
||||
"permissions": "查看权限",
|
||||
"imports": "查看导入任务",
|
||||
"get": "查看应用详情"
|
||||
},
|
||||
"options": [
|
||||
"--all 自动翻页拉取全量记录",
|
||||
"--ndjson 流式逐行下发 JSON Lines ($O(1)内存)",
|
||||
"--flat 剥离底层实体动态字段前缀并提取引用",
|
||||
"--stats 输出总数/启停/重名/编码规则聚类画像",
|
||||
"--dry-run 只预览记录写操作",
|
||||
"--yes/--confirm 确认记录写操作",
|
||||
"--raw 跳过安全合并直接发送原始补丁"
|
||||
],
|
||||
"aliases": [
|
||||
"platforms",
|
||||
"datalink",
|
||||
"data-link"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"apps": "list",
|
||||
"show": "get",
|
||||
"objects": "entities",
|
||||
"fields": "schema",
|
||||
"data": "records",
|
||||
"search": "records",
|
||||
"stats": "records",
|
||||
"profile": "records",
|
||||
"check": "audit",
|
||||
"health": "audit",
|
||||
"record-get": "record",
|
||||
"record-toggle": "record",
|
||||
"record-edit": "record",
|
||||
"record-batch-edit": "record",
|
||||
"batch-edit": "record",
|
||||
"record-update": "record",
|
||||
"update": "record",
|
||||
"batch-update": "record",
|
||||
"record-recompute": "record",
|
||||
"permission": "permissions",
|
||||
"auth": "permissions",
|
||||
"import-jobs": "imports"
|
||||
},
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
|
||||
},
|
||||
"app": {
|
||||
"summary": "桌面端工作台应用管理",
|
||||
"usage": "hose-use app <子命令>",
|
||||
"commands": {
|
||||
"list": "列出应用",
|
||||
"get": "查看应用详情"
|
||||
},
|
||||
"aliases": [
|
||||
"apps",
|
||||
"workbench"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"apps": "list",
|
||||
"workbench": "list",
|
||||
"show": "get"
|
||||
},
|
||||
flags: { ...flagList("app id k keyword name q query", "value") }
|
||||
},
|
||||
"menu": {
|
||||
"summary": "桌面端主导航菜单树",
|
||||
"usage": "hose-use menu list",
|
||||
"commands": {
|
||||
"list": "查看主导航",
|
||||
"apps": "查看应用入口"
|
||||
},
|
||||
"aliases": [
|
||||
"menus"
|
||||
],
|
||||
"commandAliases": {
|
||||
"workbench": "apps",
|
||||
"ls": "list",
|
||||
"tree": "list"
|
||||
},
|
||||
flags: { }
|
||||
},
|
||||
"skill": {
|
||||
"summary": "Agent Skill 管理",
|
||||
"usage": "hose-use skill <install|status|dump>",
|
||||
"commands": {
|
||||
"install": "安装内嵌 Skill",
|
||||
"status": "查看安装状态",
|
||||
"dump": "导出 Skill 文件"
|
||||
},
|
||||
"aliases": [
|
||||
"skills"
|
||||
],
|
||||
"commandAliases": {
|
||||
"cat": "dump",
|
||||
"show": "dump",
|
||||
"init": "install",
|
||||
"sync": "install",
|
||||
"get": "status"
|
||||
},
|
||||
flags: { ...flagList("local workspace", "boolean"), ...flagList("dir target", "value") }
|
||||
},
|
||||
"probe": {
|
||||
"summary": "企业连通性诊断",
|
||||
"usage": "hose-use probe [corpId]",
|
||||
"commands": {
|
||||
"probe": "检查认证与 API 连通性"
|
||||
},
|
||||
"aliases": [
|
||||
"diagnose"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"update": {
|
||||
"summary": "版本自更新与发布记录",
|
||||
"usage": "hose-use update [check|--changelog]",
|
||||
"commands": {
|
||||
"update": "检查并升级版本",
|
||||
"check": "只检查可用版本",
|
||||
"changelog": "查看发布记录"
|
||||
},
|
||||
"aliases": [
|
||||
"upgrade",
|
||||
"self-update",
|
||||
"changelog"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("c changelog check check-only f force gh gitea github l log mirror yingqing", "boolean"), ...flagList("limit n repo t tag target version", "value") }
|
||||
},
|
||||
"openapi": {
|
||||
"summary": "OpenAPI 规范导出与路径查询",
|
||||
"usage": "hose-use openapi [paths|info|--raw|keys]",
|
||||
"commands": {
|
||||
"paths": "列出路径概要",
|
||||
"info": "查看规范元数据",
|
||||
"keys": "查看企业接入密钥",
|
||||
"dump": "导出规范"
|
||||
},
|
||||
"aliases": [
|
||||
"schema",
|
||||
"spec"
|
||||
],
|
||||
"commandAliases": {
|
||||
"list": "paths",
|
||||
"ls": "paths",
|
||||
"summary": "info",
|
||||
"export": "dump",
|
||||
"raw": "dump"
|
||||
},
|
||||
flags: { ...flagList("raw elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"keys": {
|
||||
"summary": "企业 OpenAPI 接入凭证",
|
||||
"usage": "hose-use keys [--json] [--reveal] [--save]",
|
||||
"commands": {
|
||||
"keys": "读取当前企业密钥(默认脱敏)"
|
||||
},
|
||||
"options": [
|
||||
"--reveal 仅在明确授权后查看明文",
|
||||
"--save --yes 提取并持久化保存到本地企业配置"
|
||||
],
|
||||
"aliases": [
|
||||
"key",
|
||||
"secret",
|
||||
"secrets"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"store": {
|
||||
"summary": "已购应用与应用商店探查",
|
||||
"usage": "hose-use store <list|search|get>",
|
||||
"commands": {
|
||||
"list": "列出已购应用",
|
||||
"search": "搜索应用商店",
|
||||
"get": "查看应用详情",
|
||||
"keys": "查看企业接入密钥"
|
||||
},
|
||||
"aliases": [
|
||||
"market"
|
||||
],
|
||||
"commandAliases": {
|
||||
"key": "keys",
|
||||
"ls": "list",
|
||||
"find": "search",
|
||||
"info": "get",
|
||||
"detail": "get"
|
||||
},
|
||||
flags: { ...flagList("a all elevate f force persist plain r reveal save", "boolean"), ...flagList("id k keyword name app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"http": {
|
||||
"summary": "轻量 HTTP Server 与交互文档",
|
||||
"usage": "hose-use http [--port=<port>]",
|
||||
"commands": {
|
||||
"http": "启动 HTTP 服务"
|
||||
},
|
||||
"aliases": [
|
||||
"server",
|
||||
"web"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("h", "boolean-or-value"), ...flagList("host p port", "value") }
|
||||
},
|
||||
"service": {
|
||||
"summary": "常驻守护进程管理",
|
||||
"usage": "hose-use service <start|stop|restart|status|logs|poll>",
|
||||
"commands": {
|
||||
"start": "启动服务",
|
||||
"stop": "停止服务",
|
||||
"restart": "重启服务",
|
||||
"status": "查看服务状态",
|
||||
"logs": "查看服务日志",
|
||||
"poll": "轮询事件"
|
||||
},
|
||||
"aliases": [
|
||||
"daemon"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("count host limit n p port state-file stateFile", "value"), ...flagList("h", "boolean-or-value") }
|
||||
},
|
||||
"mcp": {
|
||||
"summary": "MCP Server",
|
||||
"usage": "hose-use mcp serve",
|
||||
"commands": {
|
||||
"serve": "启动 MCP 服务"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
}
|
||||
};
|
||||
|
||||
export function resolveCommandMetadata(area?: string): { area: string; metadata: CliCommandMetadata } | undefined {
|
||||
if (!area) return undefined;
|
||||
const normalized = area.toLowerCase();
|
||||
for (const [name, metadata] of Object.entries(COMMAND_METADATA)) {
|
||||
if (name === normalized || metadata.aliases.includes(normalized)) return { area: name, metadata };
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveCommandAction(area: string | undefined, action?: string): string | undefined {
|
||||
const metadata = resolveCommandMetadata(area)?.metadata;
|
||||
const key = action?.toLowerCase();
|
||||
return key ? (metadata && Object.hasOwn(metadata.commandAliases, key) ? metadata.commandAliases[key] : key) : undefined;
|
||||
}
|
||||
|
||||
export function localCommandFlags(area?: string, action?: string): Record<string, FlagKind> {
|
||||
const resolved = resolveCommandMetadata(area);
|
||||
const flags = { ...resolved?.metadata.flags };
|
||||
const canonical = resolveCommandAction(area, action);
|
||||
// Most commands retain -c as the global corp selector. A few actions declare
|
||||
// a local meaning (bill code, node code, batch concurrency or bound rule codes).
|
||||
const localC = resolved?.area === "update"
|
||||
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|
||||
|| (resolved?.area === "workflow" && canonical === "node")
|
||||
|| (resolved?.area === "platform" && canonical === "record")
|
||||
|| (resolved?.area === "aipro" && canonical === "bind");
|
||||
if (!localC) delete flags.c;
|
||||
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
|
||||
// --run historically accepts a session ID and, for decide, an apply boolean.
|
||||
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
|
||||
return flags;
|
||||
}
|
||||
|
||||
export function commandFlags(area?: string, action?: string): Record<string, FlagKind> {
|
||||
return { ...GLOBAL_FLAGS, ...localCommandFlags(area, action) };
|
||||
}
|
||||
@@ -267,7 +267,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
` 阶段判定 : ${report.diagnostic.stageLabel}`,
|
||||
` 当前驻留节点: ${report.currentNode?.name || "-"}${report.currentNode?.id ? ` (${report.currentNode.id})` : ""}`,
|
||||
` 待办处理人: ${approverNames || "(当前无待办审批人)"}`,
|
||||
` 是否可审批: ${report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
|
||||
` 是否可审批: ${report.diagnostic.canApprove === null ? "未知(需核对当前身份的实际待办与权限)" : report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
|
||||
` 诊断结论 : ${report.diagnostic.summary}`,
|
||||
` 排障建议 : ${report.diagnostic.advice}`,
|
||||
];
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "../../core/config/loader.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, printJson } from "../printer.js";
|
||||
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
@@ -75,6 +75,8 @@ export async function handleContextCommand(
|
||||
? {
|
||||
id: currentCorp.id,
|
||||
name: currentCorp.name,
|
||||
env: currentCorp.env,
|
||||
isTest: currentCorp.isTest,
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
@@ -93,6 +95,9 @@ export async function handleContextCommand(
|
||||
total: allCorps.length,
|
||||
validCount: validCorps.length,
|
||||
expiredCount: expiredCorps.length,
|
||||
prodCount: allCorps.filter((c) => c.env === "prod").length,
|
||||
testCount: allCorps.filter((c) => c.env === "test").length,
|
||||
demoCount: allCorps.filter((c) => c.env === "demo").length,
|
||||
activeCorpId: currentCorp?.id || null,
|
||||
},
|
||||
aiProGateway: {
|
||||
@@ -122,6 +127,9 @@ export async function handleContextCommand(
|
||||
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
|
||||
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
|
||||
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
|
||||
const prodCount = allCorps.filter((c) => c.env === "prod").length;
|
||||
const testCount = allCorps.filter((c) => c.env === "test").length;
|
||||
const demoCount = allCorps.filter((c) => c.env === "demo").length;
|
||||
|
||||
const scopesStr =
|
||||
scopes.length > 0
|
||||
@@ -131,13 +139,13 @@ export async function handleContextCommand(
|
||||
const lines = [
|
||||
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
|
||||
` 当前活跃账号 : ${accountStr}${userIdStr}`,
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id}) [${formatCorpEnvLabel(currentCorp.env)}]` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
||||
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import { handleContextCommand } from "./context.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
const sampleCorps: CorpConfig[] = [
|
||||
{
|
||||
id: "corp_prod",
|
||||
name: "新转转集团",
|
||||
env: "prod",
|
||||
isTest: false,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "corp_prod", staffId: "staff_1", accessToken: "t1" },
|
||||
},
|
||||
{
|
||||
id: "corp_test",
|
||||
name: "HAB对公测试环境",
|
||||
env: "test",
|
||||
isTest: true,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "corp_test", staffId: "staff_2", accessToken: "t2" },
|
||||
},
|
||||
{
|
||||
id: "corp_demo",
|
||||
name: "营销中心演示企业",
|
||||
env: "demo",
|
||||
isTest: true,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "corp_demo", staffId: "staff_3", accessToken: "t3" },
|
||||
},
|
||||
];
|
||||
|
||||
function createMockRuntime(corps: CorpConfig[] = sampleCorps): CliRuntime {
|
||||
const context = new CorpContext(corps, { stateful: true, defaultCorpId: "corp_prod" });
|
||||
return {
|
||||
corpContext: context,
|
||||
selectedCorp: context.getCurrent()!,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CLI - corps environment attributes & filtering", () => {
|
||||
it("corps list displays environment column with emoji labels", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "list"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("环境");
|
||||
expect(res.stdout).toContain("🏭 正式");
|
||||
expect(res.stdout).toContain("🧪 测试");
|
||||
expect(res.stdout).toContain("🎪 演示");
|
||||
expect(res.stdout).toContain("共 3 家企业 (🏭 正式 1 家, 🧪 测试 1 家, 🎪 演示 1 家)");
|
||||
});
|
||||
|
||||
it("corps list --test filters only test and demo enterprises", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { test: true },
|
||||
raw: ["corps", "list", "--test"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("HAB对公测试环境");
|
||||
expect(res.stdout).toContain("营销中心演示企业");
|
||||
expect(res.stdout).not.toContain("新转转集团");
|
||||
expect(res.stdout).toContain("已筛选显示 2 家");
|
||||
});
|
||||
|
||||
it("corps list --prod filters only production enterprises", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { prod: true },
|
||||
raw: ["corps", "list", "--prod"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("新转转集团");
|
||||
expect(res.stdout).not.toContain("HAB对公测试环境");
|
||||
expect(res.stdout).not.toContain("营销中心演示企业");
|
||||
expect(res.stdout).toContain("已筛选显示 1 家");
|
||||
});
|
||||
|
||||
it("corps list --env=demo filters precisely demo enterprises", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { env: "demo" },
|
||||
raw: ["corps", "list", "--env=demo"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("营销中心演示企业");
|
||||
expect(res.stdout).not.toContain("新转转集团");
|
||||
expect(res.stdout).not.toContain("HAB对公测试环境");
|
||||
});
|
||||
|
||||
it("corps tag requires mutation confirmation unless confirmed or dry-run", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
await expect(
|
||||
handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "tag",
|
||||
args: ["corp_prod"],
|
||||
options: { test: true },
|
||||
raw: ["corps", "tag", "corp_prod", "--test"],
|
||||
},
|
||||
runtime
|
||||
)
|
||||
).rejects.toThrow("拒绝执行设置企业环境属性");
|
||||
});
|
||||
|
||||
it("corps tag previews change under --dry-run", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "tag",
|
||||
args: ["corp_prod"],
|
||||
options: { test: true, "dry-run": true },
|
||||
raw: ["corps", "tag", "corp_prod", "--test", "--dry-run"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("设置企业环境属性");
|
||||
expect(res.stdout).toContain("newEnv: test");
|
||||
});
|
||||
|
||||
it("corps current displays environment attribute label", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "current",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "current"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("环境属性");
|
||||
expect(res.stdout).toContain("🏭 正式");
|
||||
});
|
||||
|
||||
it("context command reports environment counts and current corp env tag", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleContextCommand(
|
||||
{
|
||||
area: "context",
|
||||
action: "",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["context"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("新转转集团 (corp_prod) [🏭 正式]");
|
||||
expect(res.stdout).toContain("🏭 正式: 1 家, 🧪 测试: 1 家, 🎪 演示: 1 家");
|
||||
});
|
||||
});
|
||||
@@ -346,11 +346,18 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
|
||||
it("supports dynamic staff switching via corps link [corp] --staff=<id>", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
new Response(JSON.stringify({ items: [] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof fetch;
|
||||
const corp = structuredClone(mockCorps[0]);
|
||||
Object.assign(corp.credentials, { appKey: "staff-switch-key", appSecurity: "staff-switch-security" });
|
||||
const dynamicRuntime = { ...searchRuntime, selectedCorp: corp, corpContext: { ...searchRuntime.corpContext, resolve: () => corp } } as CliRuntime;
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
const body = url.includes("getAccessToken")
|
||||
? { value: { accessToken: "openapi-staff-switch", corporationId: "alphaPhysicalId", expireTime: Date.now() + 7200000 } }
|
||||
: url.includes("getProvisionalAuth")
|
||||
? { value: { message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=token-new-staff&ekbCorpId=alphaPhysicalId" } }
|
||||
: { items: [] };
|
||||
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const res = await handleCorpsCommand(
|
||||
@@ -361,7 +368,7 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF" },
|
||||
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF"],
|
||||
},
|
||||
searchRuntime
|
||||
dynamicRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
@@ -370,7 +377,7 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.stdout).toContain("动态换签");
|
||||
|
||||
// --json 模式验证
|
||||
const jsonRuntime = { ...searchRuntime, jsonMode: true };
|
||||
const jsonRuntime = { ...dynamicRuntime, jsonMode: true };
|
||||
const jsonRes = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
@@ -385,6 +392,8 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
const parsed = JSON.parse(jsonRes.stdout);
|
||||
expect(parsed.dynamicStaff).toBe(true);
|
||||
expect(parsed.staffId).toBe("alphaPhysicalId:NEW_ADMIN_STAFF");
|
||||
expect(corp.credentials.accessToken).toBe("token-alpha");
|
||||
expect(corp.credentials.staffId).toBe("STAFF_001");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../../core/auth/login.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt, formatCorpEnvLabel } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -28,8 +28,9 @@ export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const envLabel = formatCorpEnvLabel(current?.env);
|
||||
return {
|
||||
stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id})\n`,
|
||||
stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id}) [${envLabel}]\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -51,6 +52,7 @@ export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const pairs: Record<string, unknown> = {
|
||||
"企业 ID": current.id,
|
||||
"企业名称": current.name,
|
||||
"环境属性": formatCorpEnvLabel(current.env),
|
||||
"员工工号": current.credentials.staffId,
|
||||
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
|
||||
|
||||
@@ -5,11 +5,13 @@ import { handleSwitch, handleCurrent } from "./context.js";
|
||||
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
|
||||
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
|
||||
import { handleTagCorp } from "./tag.js";
|
||||
import { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
// 供 auth.ts 等跨命令复用的 handler 与 helper 维持原有命名导出。
|
||||
export { handleGenerateCorpLink } from "./link.js";
|
||||
export { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
export { handleTagCorp } from "./tag.js";
|
||||
export { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
@@ -27,6 +29,10 @@ export async function handleCorpsCommand(
|
||||
case "query":
|
||||
case "filter":
|
||||
return handleSearch(parsed, runtime);
|
||||
case "tag":
|
||||
case "set-env":
|
||||
case "mark":
|
||||
return handleTagCorp(parsed, runtime);
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
@@ -75,7 +81,7 @@ export async function handleCorpsCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, tag, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -87,8 +93,9 @@ export function printCorpsHelp(): string {
|
||||
hose-use corps <子命令> [参数] [选项]
|
||||
|
||||
子命令:
|
||||
list 列出本地已保存的所有企业配置 (别名: ls)
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
|
||||
list 列出本地已保存的所有企业配置 (支持 --test, --prod, --demo, --env 筛选,别名: ls)
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId, env,别名: find)
|
||||
tag [企业ID] 标记企业环境属性 (--test / --prod / --demo / --env=<env>) 或 --migrate-all 批量升级持久化 (别名: set-env)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
|
||||
@@ -101,19 +108,19 @@ export function printCorpsHelp(): string {
|
||||
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
|
||||
|
||||
选项:
|
||||
--test 筛选测试环境企业 (corps list)
|
||||
--prod 筛选正式生产企业 (corps list)
|
||||
--demo 筛选演示/POC企业 (corps list)
|
||||
--json, -j 以 JSON 格式输出
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
示例:
|
||||
hose-use corps list
|
||||
hose-use corps search 某企业
|
||||
hose-use corps search 17718556446
|
||||
hose-use corps switch ID01MCcOgJl1td
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps link 新转转集团 --staff="合思-姜尧"
|
||||
hose-use corps link 新转转集团 --staff="17865187018" --persist
|
||||
hose-use corps add-link "<url>" --elevate --yes
|
||||
hose-use corps add-persistent --app-key=... --app-security=... --yes
|
||||
hose-use corps list --test
|
||||
hose-use corps list --prod
|
||||
hose-use corps tag ID01uzxB4x07fh --test --yes
|
||||
hose-use corps tag ID01PH4Q5CJboX --prod --yes
|
||||
hose-use corps tag --migrate-all --yes
|
||||
`.trim();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, formatExpiresAt, formatSourceLabel } from "../../printer.js";
|
||||
import { getCorpEnv, isCorpTest } from "../../../core/config/types.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, formatExpiresAt, formatSourceLabel, formatCorpEnvLabel } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
@@ -10,6 +11,7 @@ const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
staffId: "员工工号",
|
||||
staffName: "员工姓名",
|
||||
accountId: "所属账号",
|
||||
env: "环境属性",
|
||||
};
|
||||
|
||||
export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -35,6 +37,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
(c.credentials?.appKey || c.auth?.appKey) &&
|
||||
(c.credentials?.appSecurity || c.auth?.appSecurity)
|
||||
);
|
||||
const env = getCorpEnv(c);
|
||||
const test = isCorpTest(c);
|
||||
return {
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
@@ -48,6 +52,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
hasOpenApi,
|
||||
env,
|
||||
isTest: test,
|
||||
};
|
||||
})
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
@@ -63,6 +69,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
expiresAt: c.expiresAt,
|
||||
persistent: c.persistent,
|
||||
hasOpenApi: c.hasOpenApi,
|
||||
env: c.env || (c.isTest ? "test" : "prod"),
|
||||
isTest: c.isTest ?? (c.env !== "prod"),
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
@@ -88,6 +96,9 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("accountId");
|
||||
}
|
||||
if (corp.env && (corp.env.toLowerCase() === kw || (kw === "正式" && corp.env === "prod") || (kw === "测试" && corp.env === "test") || (kw === "演示" && corp.env === "demo"))) {
|
||||
matchedFields.push("env");
|
||||
}
|
||||
|
||||
if (matchedFields.length > 0) {
|
||||
matches.push({ ...corp, matchedFields });
|
||||
@@ -105,6 +116,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
corpId: m.corpId,
|
||||
env: m.env,
|
||||
isTest: m.isTest,
|
||||
staffId: m.staffId,
|
||||
staffName: m.staffName || undefined,
|
||||
accountId: m.accountId || undefined,
|
||||
@@ -136,6 +149,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
|
||||
return [
|
||||
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
formatCorpEnvLabel(m.env),
|
||||
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
|
||||
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
|
||||
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
|
||||
@@ -147,7 +161,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
});
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
|
||||
["#", "环境", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
|
||||
rows
|
||||
);
|
||||
|
||||
@@ -159,14 +173,41 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
}
|
||||
|
||||
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corps = runtime.corpContext.listCorps();
|
||||
const allCorps = runtime.corpContext.listCorps();
|
||||
|
||||
const filterTest = booleanOption(parsed.options, ["test", "t"]);
|
||||
const filterProd = booleanOption(parsed.options, ["prod", "production", "p"]);
|
||||
const filterDemo = booleanOption(parsed.options, ["demo"]);
|
||||
const filterEnv = stringOption(parsed.options, ["env", "e"])?.toLowerCase();
|
||||
|
||||
let filteredCorps = allCorps;
|
||||
if (filterTest) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.isTest || c.env === "test" || c.env === "demo");
|
||||
} else if (filterProd) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.env === "prod");
|
||||
} else if (filterDemo) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.env === "demo");
|
||||
} else if (filterEnv) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.env === filterEnv);
|
||||
}
|
||||
|
||||
const prodCount = allCorps.filter((c) => c.env === "prod").length;
|
||||
const testCount = allCorps.filter((c) => c.env === "test").length;
|
||||
const demoCount = allCorps.filter((c) => c.env === "demo").length;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: corps,
|
||||
total: allCorps.length,
|
||||
count: filteredCorps.length,
|
||||
summary: {
|
||||
prodCount,
|
||||
testCount,
|
||||
demoCount,
|
||||
},
|
||||
corporations: filteredCorps,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -175,12 +216,21 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
};
|
||||
}
|
||||
|
||||
if (corps.length === 0) {
|
||||
if (allCorps.length === 0) {
|
||||
return { stdout: "未找到任何企业配置,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = corps.map((c, i) => [
|
||||
if (filteredCorps.length === 0) {
|
||||
return {
|
||||
stdout: `没有找到符合筛选条件的企业 (总计 ${allCorps.length} 家: 🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = filteredCorps.map((c, i) => [
|
||||
c.current ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
formatCorpEnvLabel(c.env),
|
||||
c.id,
|
||||
c.name,
|
||||
c.staffId,
|
||||
@@ -190,12 +240,16 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
["#", "环境", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
rows
|
||||
);
|
||||
|
||||
const filterHint = (filteredCorps.length !== allCorps.length)
|
||||
? `已筛选显示 ${filteredCorps.length} 家 (总计 ${allCorps.length} 家: 🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)`
|
||||
: `共 ${allCorps.length} 家企业 (🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)`;
|
||||
|
||||
return {
|
||||
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stdout: `====== 已配置企业列表 (${filterHint}) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 支持筛选: --test (仅测试/演示), --prod (仅正式生产), --env=<prod|test|demo>\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { saveCorpConfig } from "../../../core/config/loader.js";
|
||||
import { CorpEnv, getCorpEnv } from "../../../core/config/types.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { formatCorpEnvLabel, printJson, printKeyValue, printTable } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleTagCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isMigrateAll = booleanOption(parsed.options, ["migrate-all", "all", "upgrade-all", "a"]);
|
||||
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
|
||||
if (isMigrateAll) {
|
||||
if (allCorps.length === 0) {
|
||||
return { stdout: "未找到任何企业配置可供迁移升级。\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const previewList = allCorps.map((corp) => {
|
||||
const deducedEnv = getCorpEnv(corp);
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
currentEnv: corp.env || "(未显式声明)",
|
||||
targetEnv: deducedEnv,
|
||||
targetIsTest: deducedEnv !== "prod",
|
||||
};
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量显式持久化升级所有企业环境属性",
|
||||
`共 ${allCorps.length} 家企业`,
|
||||
{
|
||||
total: allCorps.length,
|
||||
preview: previewList,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量显式持久化升级所有企业环境属性",
|
||||
"hose-use corps tag --migrate-all --yes"
|
||||
);
|
||||
|
||||
const savedPaths: string[] = [];
|
||||
for (const corp of allCorps) {
|
||||
const targetEnv = getCorpEnv(corp);
|
||||
const updated = {
|
||||
...corp,
|
||||
env: targetEnv,
|
||||
isTest: targetEnv !== "prod",
|
||||
};
|
||||
const filePath = saveCorpConfig(updated);
|
||||
savedPaths.push(filePath);
|
||||
runtime.corpContext.upsertCorp(updated, corp.id === runtime.selectedCorp?.id);
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
migrated: true,
|
||||
count: savedPaths.length,
|
||||
corporations: previewList,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = previewList.map((item, i) => [
|
||||
i + 1,
|
||||
formatCorpEnvLabel(item.targetEnv),
|
||||
item.id,
|
||||
item.name,
|
||||
item.targetEnv,
|
||||
item.targetIsTest ? "是" : "否",
|
||||
]);
|
||||
|
||||
const table = printTable(["#", "环境属性", "企业 ID", "企业名称", "写入环境值", "isTest"], rows);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功完成 ${savedPaths.length} 家企业配置环境属性的显式持久化升级:\n\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 单个企业打标
|
||||
const targetArg = parsed.args[0] || stringOption(parsed.options, ["id", "corp", "corpId"]);
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法:",
|
||||
" hose-use corps tag <企业ID|名称> [--test | --prod | --demo | --env=<prod|test|demo>] [--yes]",
|
||||
" hose-use corps tag --migrate-all [--yes] # 一键按名称智能初判持久化升级所有企业配置",
|
||||
"",
|
||||
"选项:",
|
||||
" --test, -t 标记为测试环境 (test)",
|
||||
" --prod, -p 标记为正式生产环境 (prod)",
|
||||
" --demo 标记为演示/POC环境 (demo)",
|
||||
" --env=<env> 显式指定环境属性 (prod / test / demo)",
|
||||
" --migrate-all 批量智能推导并持久化所有企业配置",
|
||||
" --dry-run 仅预览变更,不写入磁盘",
|
||||
" --yes, -y 确认执行写入",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const optTest = booleanOption(parsed.options, ["test", "t"]);
|
||||
const optProd = booleanOption(parsed.options, ["prod", "production", "p"]);
|
||||
const optDemo = booleanOption(parsed.options, ["demo"]);
|
||||
const optEnv = stringOption(parsed.options, ["env", "e"])?.toLowerCase();
|
||||
|
||||
let targetEnv: CorpEnv | undefined;
|
||||
if (optTest) {
|
||||
targetEnv = "test";
|
||||
} else if (optProd) {
|
||||
targetEnv = "prod";
|
||||
} else if (optDemo) {
|
||||
targetEnv = "demo";
|
||||
} else if (optEnv) {
|
||||
if (["prod", "test", "demo"].includes(optEnv)) {
|
||||
targetEnv = optEnv as CorpEnv;
|
||||
} else {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `错误: 非法的环境属性 "${optEnv}",仅支持 prod (正式生产), test (测试环境), demo (演示/POC)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetEnv) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `请指定要标记的环境属性 (--test, --prod, --demo 或 --env=<prod|test|demo>)。\n例如: hose-use corps tag ${targetCorp.id} --test --yes\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const changes = {
|
||||
corpId: targetCorp.id,
|
||||
name: targetCorp.name,
|
||||
currentEnv: targetCorp.env,
|
||||
newEnv: targetEnv,
|
||||
newIsTest: targetEnv !== "prod",
|
||||
};
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "设置企业环境属性", `${targetCorp.name} (${targetCorp.id})`, changes);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"设置企业环境属性",
|
||||
`hose-use corps tag ${targetCorp.id} --env=${targetEnv} --yes`
|
||||
);
|
||||
|
||||
const updatedCorp = {
|
||||
...targetCorp,
|
||||
env: targetEnv,
|
||||
isTest: targetEnv !== "prod",
|
||||
};
|
||||
|
||||
const filePath = saveCorpConfig(updatedCorp);
|
||||
runtime.corpContext.upsertCorp(updatedCorp, targetCorp.id === runtime.selectedCorp?.id);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
corpId: updatedCorp.id,
|
||||
name: updatedCorp.name,
|
||||
env: updatedCorp.env,
|
||||
isTest: updatedCorp.isTest,
|
||||
configFile: filePath,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const summary = printKeyValue({
|
||||
"企业名称": updatedCorp.name,
|
||||
"企业 ID": updatedCorp.id,
|
||||
"环境属性": `${formatCorpEnvLabel(updatedCorp.env)} (${updatedCorp.env})`,
|
||||
"是否测试企业 (isTest)": updatedCorp.isTest ? "是" : "否",
|
||||
"持久化配置文件": filePath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -219,7 +219,7 @@ describe("CLI - flow & trace 全域透视与穿透诊断命令族", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("单据全域穿透诊断 [BX-999]");
|
||||
expect(res.stdout).toContain("总监审批");
|
||||
expect(res.stdout).toContain("是否可审批: ✅ 是");
|
||||
expect(res.stdout).toContain("是否可审批: 未知");
|
||||
});
|
||||
|
||||
it("未找到单据时返回 exitCode 1 与排障建议", async () => {
|
||||
|
||||
+7
-15
@@ -1,24 +1,16 @@
|
||||
import { spawn } from "child_process";
|
||||
import { join } from "path";
|
||||
import { usageError } from "../errors.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "../types.js";
|
||||
|
||||
export async function handleMcpCommand(
|
||||
parsed: CliParsedArgs,
|
||||
options: CliRunOptions
|
||||
): Promise<CliResult> {
|
||||
const appRoot = options.appRoot || process.cwd();
|
||||
const serverPath = join(appRoot, "src", "server.ts");
|
||||
|
||||
console.error("启动 MCP Server on stdio...");
|
||||
const child = spawn("bun", ["run", serverPath], {
|
||||
stdio: "inherit",
|
||||
cwd: appRoot,
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
child.on("exit", () => resolve());
|
||||
});
|
||||
if (parsed.action && parsed.action !== "serve") {
|
||||
throw usageError(`未知 mcp 子命令: ${parsed.action}。用法: hose-use mcp [serve]`);
|
||||
}
|
||||
// Lazy loading avoids a runner -> registry -> server -> runner startup cycle.
|
||||
const { startServer } = await import("../../server.js");
|
||||
await startServer(options);
|
||||
|
||||
return { stdout: "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -487,7 +487,6 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
|
||||
const streamedLines: string[] = [];
|
||||
const writeSpy = spyOn(process.stdout, "write").mockImplementation((str: any) => {
|
||||
streamedLines.push(String(str));
|
||||
return true;
|
||||
});
|
||||
spies.push(writeSpy);
|
||||
@@ -500,11 +499,12 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
options: { ndjson: true },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--ndjson"],
|
||||
},
|
||||
dummyRuntime
|
||||
{ ...dummyRuntime, writeStdout: async (chunk) => { streamedLines.push(chunk); } }
|
||||
);
|
||||
|
||||
expect(streamRes.exitCode).toBe(0);
|
||||
expect(streamedLines.length).toBe(2);
|
||||
expect(writeSpy).not.toHaveBeenCalled();
|
||||
|
||||
const row1 = JSON.parse(streamedLines[0].trim());
|
||||
expect(row1.id).toBe("r-1");
|
||||
@@ -513,5 +513,17 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(row1.active).toBe(true);
|
||||
expect(row1.fields["自定义字段"]).toBe("测试值");
|
||||
});
|
||||
|
||||
it("rejects malformed batch predicates before fetching all records or calling the writer", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const fetch = spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ data: [], total: 0 } as any);
|
||||
const write = spyOn(services, "batchSafeEditRecords").mockResolvedValue([]);
|
||||
spies.push(fetch, write);
|
||||
await expect(handlePlatformCommand({ area: "platform", action: "batch-edit", args: ["platform-1", "entity-1"], options: { where: "序号 in [1]", set: "active=true", yes: true }, raw: [] }, dummyRuntime)).rejects.toThrow("不支持的筛选条件");
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
compileRecordPredicate,
|
||||
getRecordDetail,
|
||||
parseSetClause,
|
||||
recomputeRecordLedger,
|
||||
@@ -146,6 +146,7 @@ async function handleBatchEdit(
|
||||
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const setClause = stringOption(parsed.options, ["set"]);
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
@@ -237,9 +238,7 @@ async function handleBatchEdit(
|
||||
{ filterBy }
|
||||
);
|
||||
let records = page.data;
|
||||
if (whereClause) {
|
||||
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
|
||||
}
|
||||
if (predicate) records = records.filter(predicate);
|
||||
recordIds = records
|
||||
.map((r) => {
|
||||
const dl =
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
buildKeywordFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
compileRecordPredicate,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
parseExpectClause,
|
||||
@@ -14,11 +14,17 @@ import {
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||
import { usageError } from "../../errors.js";
|
||||
import { open } from "node:fs/promises";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
|
||||
|
||||
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
|
||||
if (isStream && !runtime.outputOptions?.outputFile && !runtime.writeStdout) {
|
||||
throw usageError("当前调用入口不支持直接 NDJSON 流,请使用 --output-file <path> 保存,或在终端运行该命令。");
|
||||
}
|
||||
const isStatsSubcommand = parsed.args[0] === "stats" || parsed.action === "stats";
|
||||
const appIndex = parsed.args[0] === "stats" ? 1 : 0;
|
||||
const entityIndex = parsed.args[0] === "stats" ? 2 : 1;
|
||||
@@ -28,9 +34,9 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
|
||||
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
@@ -44,33 +50,41 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
|
||||
if (isStream) {
|
||||
let streamCount = 0;
|
||||
const maxLimit = isAll ? Infinity : count;
|
||||
let bytes = 0;
|
||||
const maxLimit = isAll ? Infinity : count ?? 20;
|
||||
const outputFile = runtime.outputOptions?.outputFile;
|
||||
const file = outputFile ? await open(outputFile, "w", 0o600) : undefined;
|
||||
|
||||
for await (const rawRecord of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
if (whereClause) {
|
||||
const matched = filterRecordsByPredicate([rawRecord], whereClause, resolved.entity);
|
||||
if (matched.length === 0) continue;
|
||||
try {
|
||||
if (maxLimit > 0) {
|
||||
for await (const rawRecord of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
if (predicate && !predicate(rawRecord)) continue;
|
||||
|
||||
let outputRecord: Record<string, unknown> = isRaw
|
||||
? (rawRecord as Record<string, unknown>)
|
||||
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
|
||||
|
||||
if (fields.length) {
|
||||
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
|
||||
}
|
||||
|
||||
const chunk = redactSensitiveText(JSON.stringify(outputRecord)) + "\n";
|
||||
if (file) await file.writeFile(chunk);
|
||||
else await runtime.writeStdout!(chunk);
|
||||
bytes += Buffer.byteLength(chunk);
|
||||
streamCount++;
|
||||
if (maxLimit !== undefined && streamCount >= maxLimit) break;
|
||||
}
|
||||
}
|
||||
|
||||
let outputRecord: Record<string, unknown> = isRaw
|
||||
? (rawRecord as Record<string, unknown>)
|
||||
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
|
||||
|
||||
if (fields.length) {
|
||||
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify(outputRecord) + "\n");
|
||||
streamCount++;
|
||||
if (maxLimit !== undefined && streamCount >= maxLimit) break;
|
||||
} finally {
|
||||
await file?.close();
|
||||
}
|
||||
|
||||
return { stdout: "", stderr: "", exitCode: 0 };
|
||||
return { stdout: outputFile ? printJson({ outputFile, bytes, records: streamCount }) : "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 2. 宏观画像与统计模式 (--stats 或 platform records stats <应用> <对象>)
|
||||
@@ -82,9 +96,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
{ filterBy, pageSize }
|
||||
);
|
||||
let records = page.data;
|
||||
if (whereClause) {
|
||||
records = filterRecordsByPredicate(records, whereClause, resolved.entity);
|
||||
}
|
||||
if (predicate) records = records.filter(predicate);
|
||||
const stats = calculateEntityRecordStats(records, resolved.entity, page.total);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -118,9 +130,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
|
||||
let data = page.data;
|
||||
if (whereClause) {
|
||||
data = filterRecordsByPredicate(data, whereClause, resolved.entity);
|
||||
}
|
||||
if (predicate) data = data.filter(predicate);
|
||||
|
||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||
if (sumOption) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
|
||||
import * as api from "../../domains/platform/services.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt, formatCorpEnvLabel } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleProbeCommand(
|
||||
@@ -24,6 +24,8 @@ export async function handleProbeCommand(
|
||||
enterprise: {
|
||||
id: currentCorp.id,
|
||||
name: currentCorp.name,
|
||||
env: currentCorp.env,
|
||||
isTest: currentCorp.isTest,
|
||||
staffId: currentCorp.credentials.staffId,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
source: currentCorp.source,
|
||||
@@ -102,6 +104,7 @@ export async function handleProbeCommand(
|
||||
const probePairs: Record<string, unknown> = {
|
||||
"企业名称": currentCorp.name,
|
||||
"企业 ID": currentCorp.id,
|
||||
"环境属性": formatCorpEnvLabel(currentCorp.env),
|
||||
"员工工号": currentCorp.credentials.staffId,
|
||||
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(currentCorp.source, hasOpenApi),
|
||||
|
||||
@@ -99,7 +99,7 @@ export async function handleSkillCommand(
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install 进行全局安装\n`,
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
detectArch,
|
||||
detectPlatform,
|
||||
downloadFile,
|
||||
downloadVerifiedReleaseAsset,
|
||||
extractTarGz,
|
||||
extractZip,
|
||||
fetchGitHubRelease,
|
||||
@@ -447,14 +448,13 @@ export async function handleUpdateCommand(
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const downloadedFile = join(tmpDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name, repo, options.sourcePreference);
|
||||
const downloadedFile = await downloadVerifiedReleaseAsset(release, asset, tmpDir, repo, options.sourcePreference);
|
||||
|
||||
let newBinaryPath = downloadedFile;
|
||||
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform, arch);
|
||||
} else if (asset.name.endsWith(".zip")) {
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform, arch);
|
||||
}
|
||||
|
||||
chmodSync(newBinaryPath, 0o755);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { downloadVerifiedReleaseAsset, extractTarGz, extractZip, fetchGitHubRelease, verifyAssetChecksum, type GitHubRelease } from "./releases.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const temp = () => { const root = mkdtempSync(join(tmpdir(), "hose-update-test-")); roots.push(root); return root; };
|
||||
const payload = Buffer.alloc(2048, 42);
|
||||
const assetName = "hose-use-linux-x64.tar.gz";
|
||||
const digest = createHash("sha256").update(payload).digest("hex");
|
||||
const asset = { name: assetName, downloadUrl: `https://github.com/test/repo/releases/download/v9.9.9/${assetName}`, size: payload.length };
|
||||
const release: GitHubRelease = { version: "9.9.9", tagName: "v9.9.9", notes: "", htmlUrl: "", assets: [asset, { name: "checksums.txt", downloadUrl: "https://github.com/test/repo/releases/download/v9.9.9/checksums.txt", size: 100 }] };
|
||||
|
||||
describe("verified self-update assets", () => {
|
||||
test("rejects missing, duplicate and mismatched checksums", () => {
|
||||
const file = join(temp(), "asset"); writeFileSync(file, payload);
|
||||
expect(() => verifyAssetChecksum(file, assetName, `${digest} ${assetName}\n`)).not.toThrow();
|
||||
expect(() => verifyAssetChecksum(file, assetName, `${digest} *${assetName}\r\n`)).not.toThrow();
|
||||
for (const manifest of ["", `${digest} unrelated\n`, `${digest} ${assetName}\n${digest} ${assetName}\n`, `${digest} ${assetName}\ninvalid ${assetName}\n`, `${"0".repeat(64)} ${assetName}\n`]) {
|
||||
expect(() => verifyAssetChecksum(file, assetName, manifest)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test("pins manifest and binary to the release tag and never sends GitHub credentials to proxies", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const tokenBefore = process.env.GITHUB_TOKEN;
|
||||
process.env.GITHUB_TOKEN = "fixture-token";
|
||||
const requests: Array<{ url: string; authorization?: string }> = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request, options?: RequestInit) => {
|
||||
const url = String(input);
|
||||
requests.push({ url, authorization: new Headers(options?.headers).get("Authorization") || undefined });
|
||||
return new Response(url.endsWith("checksums.txt") ? `${digest} ${assetName}\n` : payload);
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
const path = await downloadVerifiedReleaseAsset(release, asset, temp(), "test/repo", "github");
|
||||
expect(readFileSync(path)).toEqual(payload);
|
||||
expect(requests).toHaveLength(2);
|
||||
for (const request of requests) {
|
||||
expect(request.url).toContain("/download/v9.9.9/");
|
||||
if (new URL(request.url).hostname !== "github.com") expect(request.authorization).toBeUndefined();
|
||||
}
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
|
||||
}
|
||||
});
|
||||
|
||||
test("does not start downloading a release without a checksum manifest", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("must not fetch"); }) as unknown as typeof fetch;
|
||||
try {
|
||||
await expect(downloadVerifiedReleaseAsset({ ...release, assets: [asset] }, asset, temp())).rejects.toThrow("checksums.txt");
|
||||
expect(requests).toBe(0);
|
||||
} finally { globalThis.fetch = fetchBefore; }
|
||||
});
|
||||
|
||||
test("GitHub API credentials are also excluded from mirror metadata requests", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const tokenBefore = process.env.GITHUB_TOKEN;
|
||||
process.env.GITHUB_TOKEN = "fixture-token";
|
||||
let authorization: string | null = "not-called";
|
||||
globalThis.fetch = (async (_input: string | URL | Request, options?: RequestInit) => {
|
||||
authorization = new Headers(options?.headers).get("Authorization");
|
||||
return Response.json({ tag_name: "v9.9.9", assets: [{ name: "checksums.txt", browser_download_url: "https://example.test/checksums.txt" }] });
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
expect((await fetchGitHubRelease("yunyingk/hose-use", "9.9.9", "gitea"))?.tagName).toBe("v9.9.9");
|
||||
expect(authorization).toBeNull();
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
|
||||
}
|
||||
});
|
||||
|
||||
test("extracts only a known binary and rejects archives containing no expected member", () => {
|
||||
const root = temp(), source = join(root, "source"), target = join(root, "target");
|
||||
mkdirSync(source); mkdirSync(target);
|
||||
const platform = process.platform === "darwin" ? "darwin" : "linux";
|
||||
const name = `hose-use-${platform}-${process.arch === "arm64" ? "arm64" : "x64"}`;
|
||||
writeFileSync(join(source, name), payload);
|
||||
writeFileSync(join(source, "unrelated.txt"), "not a binary");
|
||||
const archive = join(target, "release.tar.gz");
|
||||
expect(spawnSync("tar", ["-czf", archive, "-C", source, name, "unrelated.txt"]).status).toBe(0);
|
||||
const extracted = extractTarGz(archive, target, platform);
|
||||
expect(readFileSync(extracted)).toEqual(payload);
|
||||
expect(existsSync(join(target, "unrelated.txt"))).toBe(false);
|
||||
expect(spawnSync("tar", ["-czf", archive, "-C", source, "unrelated.txt"]).status).toBe(0);
|
||||
expect(() => extractTarGz(archive, target, platform)).toThrow("目标平台二进制");
|
||||
});
|
||||
|
||||
test("extracts the selected Windows ZIP binary without materializing wrappers or extra files", () => {
|
||||
const root = temp(), source = join(root, "source"), target = join(root, "target");
|
||||
mkdirSync(source); mkdirSync(target);
|
||||
const name = "hose-use-windows-x64.exe";
|
||||
writeFileSync(join(source, name), payload);
|
||||
writeFileSync(join(source, "hose-aipro.cmd"), "fixture wrapper");
|
||||
const archive = join(target, "release.zip");
|
||||
expect(spawnSync("zip", ["-q", archive, name, "hose-aipro.cmd"], { cwd: source }).status).toBe(0);
|
||||
const extracted = extractZip(archive, target, "windows", "x64");
|
||||
expect(readFileSync(extracted)).toEqual(payload);
|
||||
expect(existsSync(join(target, "hose-aipro.cmd"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { unlinkSync, writeFileSync } from "node:fs";
|
||||
import { closeSync, mkdtempSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { basename, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { VERSION } from "../../../version.js";
|
||||
|
||||
@@ -79,7 +81,7 @@ export async function fetchGitHubReleases(
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as Array<{
|
||||
tag_name?: string;
|
||||
@@ -168,7 +170,7 @@ export async function fetchGitHubRelease(
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
@@ -181,6 +183,7 @@ export async function fetchGitHubRelease(
|
||||
};
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
if (tag && tagName !== tag) continue;
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
|
||||
@@ -269,13 +272,22 @@ function logProgress(msg: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Credentials for GitHub must never be forwarded to a CDN or the Gitea mirror. */
|
||||
function scopedHeaders(headers: Record<string, string>, url: string): Record<string, string> {
|
||||
const hostname = new URL(url).hostname;
|
||||
if (hostname === "github.com" || hostname === "api.github.com") return headers;
|
||||
const { Authorization: _authorization, ...publicHeaders } = headers;
|
||||
return publicHeaders;
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
tagName?: string,
|
||||
assetName?: string,
|
||||
repo: string = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
sourcePreference: UpdateSourcePreference = "auto",
|
||||
minimumBytes = 1000
|
||||
) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
@@ -326,7 +338,7 @@ export async function downloadFile(
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
};
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
if (token && candidate.includes("github.com")) {
|
||||
if (token && ["github.com", "api.github.com"].includes(new URL(candidate).hostname)) {
|
||||
reqHeaders["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
const res = await fetch(candidate, {
|
||||
@@ -341,7 +353,7 @@ export async function downloadFile(
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
if (buffer.length < minimumBytes) {
|
||||
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
@@ -381,7 +393,7 @@ export async function downloadFile(
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
if (completeBuffer.length < minimumBytes) {
|
||||
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
@@ -396,56 +408,63 @@ export async function downloadFile(
|
||||
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
||||
}
|
||||
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
// Exact match for hose-use or hose-use.exe
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
export function verifyAssetChecksum(assetPath: string, assetName: string, manifest: string): void {
|
||||
const matches = manifest.split(/\r?\n/).flatMap(line => {
|
||||
const match = line.match(/^(\S+)\s+\*?(.+)$/);
|
||||
return match?.[2] === assetName ? [match[1].toLowerCase()] : [];
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
if (matches.length !== 1 || !/^[a-f0-9]{64}$/.test(matches[0])) throw new Error(`checksums.txt 缺少、重复或错误列出 ${assetName},拒绝未经校验的更新`);
|
||||
const actual = createHash("sha256").update(readFileSync(assetPath)).digest("hex");
|
||||
if (actual !== matches[0]) throw new Error(`SHA-256 校验失败: ${assetName};现有安装未替换`);
|
||||
}
|
||||
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
|
||||
export async function downloadVerifiedReleaseAsset(
|
||||
release: GitHubRelease,
|
||||
asset: GitHubAsset,
|
||||
targetDir: string,
|
||||
repo = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<string> {
|
||||
if (basename(asset.name) !== asset.name || /[\\/]/.test(asset.name)) throw new Error("非法 Release 资产文件名");
|
||||
if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(release.tagName)) throw new Error("非法 Release tag");
|
||||
const manifest = release.assets.find(item => item.name === "checksums.txt");
|
||||
if (!manifest) throw new Error(`Release ${release.tagName} 缺少 checksums.txt,拒绝未经校验的更新`);
|
||||
const manifestPath = join(targetDir, "checksums.txt");
|
||||
await downloadFile(manifest.downloadUrl, manifestPath, release.tagName, manifest.name, repo, sourcePreference, 1);
|
||||
const assetPath = join(targetDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, assetPath, release.tagName, asset.name, repo, sourcePreference);
|
||||
verifyAssetChecksum(assetPath, asset.name, readFileSync(manifestPath, "utf8"));
|
||||
return assetPath;
|
||||
}
|
||||
|
||||
/** Extract only a known binary member; never materialize archive paths or aliases. */
|
||||
function extractReleaseBinary(archivePath: string, targetDir: string, platform: string, arch: string, format: "tar" | "zip"): string {
|
||||
const listing = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-tzf", archivePath] : ["-Z1", archivePath], { encoding: "utf8" });
|
||||
if (listing.status !== 0) throw new Error(`无法读取 Release 归档: ${listing.stderr}`);
|
||||
const names = listing.stdout.split(/\r?\n/);
|
||||
const suffix = platform === "windows" ? ".exe" : "";
|
||||
const expected = [`hose-use-${platform}-${arch}${suffix}`, `hose-use${suffix}`];
|
||||
const member = expected.flatMap(name => [name, `./${name}`]).find(name => names.filter(item => item === name).length === 1);
|
||||
if (!member) throw new Error("Release 归档中没有唯一的目标平台二进制");
|
||||
const output = join(mkdtempSync(join(targetDir, ".extract-")), `hose-use${suffix}`);
|
||||
const fd = openSync(output, "wx", 0o700);
|
||||
try {
|
||||
const extraction = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-xOzf", archivePath, member] : ["-p", archivePath, member], { stdio: ["ignore", fd, "pipe"] });
|
||||
if (extraction.status !== 0) throw new Error(`解压 Release 二进制失败: ${extraction.stderr}`);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
if (!statSync(output).size) throw new Error("Release 二进制为空");
|
||||
unlinkSync(archivePath);
|
||||
return output;
|
||||
}
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
||||
return extractReleaseBinary(archivePath, targetDir, platform, arch, "tar");
|
||||
}
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
||||
return extractReleaseBinary(archivePath, targetDir, platform, arch, "zip");
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { handleWorkflowTest } from "./workflow/test.js";
|
||||
import * as shared from "./workflow/shared.js";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../types.js";
|
||||
import type { WorkflowTestReport } from "../../domains/platform/types.js";
|
||||
|
||||
const runtime = {
|
||||
selectedCorp: { id: "mock-corp", name: "Mock测试企业", env: "test", isTest: true } as any,
|
||||
jsonMode: true,
|
||||
} as CliRuntime;
|
||||
const args = (options: Record<string, string | boolean> = {}): CliParsedArgs => ({ area: "workflow", action: "test", args: ["pipe"], options: { flow: "ID01-record", ...options }, raw: ["workflow", "test", "pipe", "--flow=ID01-record"] });
|
||||
const completed: WorkflowTestReport = { jobId: "job", pipelineId: "pipe", status: "COMPLETED", outcome: "completed", timedOut: false, diagnosticsComplete: true, diagnosticsErrors: [], runType: "DEBUG", targetEntityId: "record", executionTree: [], failedExecutions: [], conditionDiagnoses: [] };
|
||||
|
||||
describe("workflow debug mutation and result contract", () => {
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
afterEach(() => { while (spies.length) spies.pop()!.mockRestore(); });
|
||||
function setup(report = completed) {
|
||||
const client = spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any);
|
||||
const detail = spyOn(services, "getWorkflowDetail").mockResolvedValue({ state: 1 } as any);
|
||||
const run = spyOn(services, "runWorkflowDebugTest").mockResolvedValue(report);
|
||||
spies.push(client, detail, run);
|
||||
return { client, detail, run };
|
||||
}
|
||||
it("dry-run with auto-publish does not create clients or start a job even if --yes is also set", async () => {
|
||||
const { client, run } = setup();
|
||||
const result = await handleWorkflowTest(args({ "dry-run": true, "auto-publish": true, yes: true }), runtime);
|
||||
const preview = JSON.parse(result.stdout);
|
||||
expect(preview.dryRun).toBe(true);
|
||||
expect(preview.changes.autoPublish).toBe(true);
|
||||
expect(preview.changes.warnings).not.toHaveLength(0);
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
it("requires explicit mutation confirmation before creating clients", async () => {
|
||||
const { client, run } = setup();
|
||||
await expect(handleWorkflowTest(args(), runtime)).rejects.toThrow("请先使用 --dry-run");
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
for (const [triggerType, options] of [
|
||||
["clock", {}],
|
||||
["webhook", { body: '{"event":"test"}' }],
|
||||
["webhook", { empty: true }],
|
||||
["webhook", { file: "/unused-in-dry-run.json" }],
|
||||
["ekuaibao-datalink-create-trigger", { record: "ID01-record" }],
|
||||
] as Array<[string, Record<string, string | boolean>]>) {
|
||||
it(`previews ${triggerType} without creating clients (${Object.keys(options).join(",")})`, async () => {
|
||||
const { client, run } = setup();
|
||||
const result = await handleWorkflowTest({ ...args(), options: { ...options, "dry-run": true, yes: true } }, runtime);
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
it("requires confirmation for a schedule trigger without --flow", async () => {
|
||||
const { detail, run } = setup();
|
||||
detail.mockResolvedValue({ state: 1, tasks: [{ type: "clock" }] } as any);
|
||||
await expect(handleWorkflowTest({ ...args(), options: {} }, runtime)).rejects.toThrow("请先使用 --dry-run");
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps confirmed schedule and webhook trigger routing", async () => {
|
||||
const { detail, run } = setup();
|
||||
detail.mockResolvedValue({ state: 1, tasks: [{ type: "clock" }] } as any);
|
||||
const scheduled = await handleWorkflowTest({ ...args(), options: { yes: true } }, runtime);
|
||||
expect(scheduled.exitCode).toBe(0);
|
||||
expect(run.mock.calls[0]?.[2]?.triggerCategory).toBe("SCHEDULE");
|
||||
expect(run.mock.calls[0]?.[2]?.flowCodeOrId).toBe("");
|
||||
detail.mockResolvedValue({ state: 1, tasks: [{ type: "webhook" }] } as any);
|
||||
const webhook = await handleWorkflowTest({ ...args(), options: { body: '{"event":"test"}', yes: true } }, runtime);
|
||||
expect(webhook.exitCode).toBe(0);
|
||||
expect(run.mock.calls[1]?.[2]?.data).toEqual({ event: "test" });
|
||||
expect(run.mock.calls[1]?.[2]?.triggerCategory).toBe("WEBHOOK");
|
||||
});
|
||||
it("allows confirmed enabled-workflow debug with machine-readable risk information", async () => {
|
||||
const { run } = setup();
|
||||
const result = await handleWorkflowTest(args({ yes: true }), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(report.productionEnabled).toBe(true);
|
||||
expect(report.warnings).not.toHaveLength(0);
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("retains an unknown production state in the result when the status check fails", async () => {
|
||||
const { detail } = setup();
|
||||
detail.mockRejectedValue(new Error("status unavailable"));
|
||||
const result = await handleWorkflowTest(args({ yes: true }), runtime);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(report.productionEnabled).toBeNull();
|
||||
expect(report.warnings.join(" ")).toContain("启用状态未知");
|
||||
});
|
||||
for (const jsonMode of [true, false]) {
|
||||
it(`returns a failing exit code for failed and incomplete runs (json=${jsonMode})`, async () => {
|
||||
setup({ ...completed, status: "FAILED", outcome: "failed" });
|
||||
const result = await handleWorkflowTest(args({ yes: true }), { ...runtime, jsonMode });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toContain("FAILED");
|
||||
});
|
||||
}
|
||||
|
||||
it("blocks workflow test without --force when selected corp is production environment", async () => {
|
||||
const { run } = setup();
|
||||
const prodRuntime = {
|
||||
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
|
||||
jsonMode: false,
|
||||
} as any;
|
||||
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
|
||||
expect(blocked.exitCode).toBe(1);
|
||||
expect(blocked.stderr).toContain("生产环境安全阻断");
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
|
||||
const allowed = await handleWorkflowTest(args({ yes: true, force: true }), prodRuntime);
|
||||
expect(allowed.exitCode).toBe(0);
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,7 @@ import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../../domains/platform/analysis.js";
|
||||
} from "../../../domains/platform/workflow/analysis/index.js";
|
||||
import { getFormSpecification } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/services.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow-alert-store.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow/alert/index.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { copyWorkflow, getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleCopy(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "source"]);
|
||||
const targetName = stringOption(parsed.options, ["name", "label", "targetName"]);
|
||||
const targetPlatformId = stringOption(parsed.options, ["platform-id", "platformId", "targetPlatformId"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow copy <pipelineId> [选项]",
|
||||
"",
|
||||
"选项:",
|
||||
" --name=<名称> 指定新工作流名称 (默认原名称加' 副本')",
|
||||
" --platform-id=<应用ID> 指定目标自建应用 (默认原自建应用)",
|
||||
" --dry-run 预览复制操作,不实际创建",
|
||||
" --yes 确认执行复制",
|
||||
"",
|
||||
"别名: cp, clone",
|
||||
"示例: hose-use workflow copy 896398895352487950 --name='发票风险监控-副本' --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"复制工作流",
|
||||
`hose-use workflow copy ${pipelineId}${targetName ? ` --name="${targetName}"` : ""} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
return mutationPreview(parsed, runtime, "复制工作流", pipelineId, {
|
||||
sourceId: pipelineId,
|
||||
sourceName: detail.label,
|
||||
targetName: targetName || (detail.label.includes("副本") ? detail.label : `${detail.label} 副本`),
|
||||
targetPlatformId: targetPlatformId || detail.platformId,
|
||||
triggerType: detail.tasks?.[0]?.type || "unknown",
|
||||
tasksCount: detail.tasks?.length || 0,
|
||||
initialState: 0,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await copyWorkflow(client, pipelineId, {
|
||||
label: targetName,
|
||||
platformId: targetPlatformId,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const triggerNode = result.tasks?.[0];
|
||||
const triggerSummary = triggerNode ? `${triggerNode.label || triggerNode.name} (${triggerNode.type})` : "-";
|
||||
|
||||
const out = [
|
||||
`✨ 工作流复制成功!新工作流已生成为草稿状态 (state = 0):`,
|
||||
printKeyValue({
|
||||
"新工作流 ID (pipelineId)": result.id,
|
||||
"新工作流名称": result.label,
|
||||
"自建应用 ID (platformId)": result.platformId || "-",
|
||||
"首节点触发器": triggerSummary,
|
||||
"节点总数": String(result.tasks?.length || 0),
|
||||
"版本号": result.version || "26.10.1",
|
||||
"当前状态": "⚪ 草稿未发布 (停用中)",
|
||||
}),
|
||||
"",
|
||||
"下一步操作建议:",
|
||||
` 查看明细: hose-use workflow get ${result.id}`,
|
||||
` 测试执行: hose-use workflow test ${result.id}`,
|
||||
` 发布上线: hose-use workflow publish ${result.id} --yes`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: `${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createWorkflow } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleCreate(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const name = parsed.args[0] || stringOption(parsed.options, ["name", "label", "n"]);
|
||||
const trigger = stringOption(parsed.options, ["trigger", "t"]);
|
||||
const platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]);
|
||||
const file = stringOption(parsed.options, ["file", "f"]);
|
||||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"创建工作流",
|
||||
`hose-use workflow create${name ? ` --name="${name}"` : ""}${trigger ? ` --trigger=${trigger}` : ""}${platformId ? ` --platform-id=${platformId}` : ""}${file ? ` --file=${file}` : ""} --yes`
|
||||
);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "创建工作流", name || "未命名流程", {
|
||||
name: name || "未命名流程",
|
||||
trigger: trigger || (file ? "from-file" : "none"),
|
||||
platformId: platformId || "-",
|
||||
fromFile: file || "-",
|
||||
initialState: 0,
|
||||
});
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, "");
|
||||
|
||||
const result = await createWorkflow(client, {
|
||||
label: name,
|
||||
trigger,
|
||||
platformId,
|
||||
file,
|
||||
desc,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const triggerNode = result.tasks?.[0];
|
||||
const triggerSummary = triggerNode ? `${triggerNode.label || triggerNode.name} (${triggerNode.type})` : "无首节点 (需在设计器配置)";
|
||||
const webhookUrl = triggerNode?.type === "webhook" && (triggerNode as any).urlPath
|
||||
? `https://piper.ekuaibao.com/api/webhook/${(triggerNode as any).urlPath}`
|
||||
: undefined;
|
||||
|
||||
const kvData: Record<string, string> = {
|
||||
"新工作流 ID (pipelineId)": result.id,
|
||||
"工作流名称": result.label,
|
||||
"自建应用 ID (platformId)": String((result as any).platformId || "-"),
|
||||
"首节点触发器": triggerSummary,
|
||||
};
|
||||
|
||||
if (webhookUrl) {
|
||||
kvData["Webhook 调用地址"] = webhookUrl;
|
||||
}
|
||||
|
||||
kvData["节点总数"] = String(result.tasks?.length || 0);
|
||||
kvData["版本号"] = result.version || "26.10.1";
|
||||
kvData["当前状态"] = "⚪ 草稿未发布 (停用中)";
|
||||
|
||||
const out = [
|
||||
`✨ 工作流创建成功!新工作流已生成为草稿状态 (state = 0):`,
|
||||
printKeyValue(kvData),
|
||||
"",
|
||||
"下一步操作建议:",
|
||||
` 查看明细: hose-use workflow get ${result.id}`,
|
||||
` 测试执行: hose-use workflow test ${result.id}`,
|
||||
` 发布上线: hose-use workflow publish ${result.id} --yes`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: `${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { deleteWorkflow, getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleDelete(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow delete <pipelineId> [选项]",
|
||||
"",
|
||||
"选项:",
|
||||
" --dry-run 预览删除操作,不实际删除",
|
||||
" --yes 确认执行删除",
|
||||
"",
|
||||
"别名: rm, remove",
|
||||
"示例: hose-use workflow delete 898588496146063385 --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"删除工作流",
|
||||
`hose-use workflow delete ${pipelineId} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const detail = await getWorkflowDetail(client, pipelineId).catch(() => null);
|
||||
return mutationPreview(parsed, runtime, "删除工作流", pipelineId, {
|
||||
pipelineId,
|
||||
name: detail?.label || "未知流程",
|
||||
state: detail?.state === 1 ? "🟢 启用中" : "⚪ 停用中",
|
||||
});
|
||||
}
|
||||
|
||||
await deleteWorkflow(client, pipelineId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🗑️ 工作流 [${pipelineId}] 已成功删除。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -149,7 +149,7 @@ export async function handleWorkflowDiffJob(
|
||||
} else {
|
||||
const divergedNodes = diff.nodes.filter((n) => n.diverged);
|
||||
const nodeRows = divergedNodes.map((n) => [
|
||||
n.taskName,
|
||||
n.currentLoopPath ? `${n.taskName} [loop ${n.currentLoopPath}]` : n.taskName,
|
||||
n.displayName || "-",
|
||||
n.type || "-",
|
||||
n.statusA || "(未执行)",
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
createWorkflowDraft,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
} from "../../../domains/platform/workflow-state.js";
|
||||
} from "../../../domains/platform/workflow/state/index.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
resolveWorkflowEnumOptions,
|
||||
SYSTEM_WORKFLOW_ACTION_ENUMS,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createJobPiperClient } from "./shared.js";
|
||||
|
||||
export async function handleWorkflowEnum(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const thirdId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["third-id", "thirdId", "id", "type"]) ||
|
||||
"action";
|
||||
|
||||
let client: any = undefined;
|
||||
if (runtime.selectedCorp) {
|
||||
try {
|
||||
client = await createJobPiperClient(parsed, runtime);
|
||||
} catch {
|
||||
// 离线或创建客户端失败时走本地内置 Fallback
|
||||
}
|
||||
}
|
||||
|
||||
const platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]);
|
||||
const items = await resolveWorkflowEnumOptions(client, thirdId, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(items, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未查询到字典/枚举 [${thirdId}] 的可用选项(可能无网络、无自建应用权限或该 thirdId 不存在)。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const isAction = thirdId.toLowerCase() === "action";
|
||||
const rows = items.map((item) => [
|
||||
item.code,
|
||||
item.label,
|
||||
item.description ||
|
||||
(isAction
|
||||
? SYSTEM_WORKFLOW_ACTION_ENUMS.find((s) => s.code === item.code)?.description || "-"
|
||||
: "-"),
|
||||
]);
|
||||
|
||||
const output = [
|
||||
`====== 工作流枚举字典: ${thirdId} (共 ${items.length} 项) ======`,
|
||||
printKeyValue({
|
||||
"字典类别 (thirdId)": thirdId,
|
||||
"总项数": items.length,
|
||||
"数据来源": client ? "在线获取 (含内置兼容)" : "系统内置静态字典 (离线/默认)",
|
||||
}),
|
||||
"",
|
||||
printTable(["Code (底层真实值)", "名称 (界面展示)", "说明 / 适用场景"], rows),
|
||||
"",
|
||||
isAction
|
||||
? "💡 提示:在配置工作流条件节点时,务必选择 [通知类型] (action) 并从下拉列表中选中上述枚举,切勿选择 [审批状态] 匹配汉字!"
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
return {
|
||||
stdout: output + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,14 @@ import { handleJob } from "./job.js";
|
||||
import { handleCheck } from "./check.js";
|
||||
import { handleAnalyze } from "./analyze.js";
|
||||
import { handleWorkflowDiff, handleWorkflowDiffJob } from "./diff.js";
|
||||
import { handleWorkflowTest } from "./test.js";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
import { handleNodeCommand } from "./node.js";
|
||||
import { handleWorkflowTailCommand } from "./tail.js";
|
||||
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -69,10 +77,47 @@ export async function handleWorkflowCommand(
|
||||
case "diff-jobs":
|
||||
case "compare-job":
|
||||
return handleWorkflowDiffJob(parsed, runtime);
|
||||
case "test":
|
||||
case "debug":
|
||||
case "run-test":
|
||||
return handleWorkflowTest(parsed, runtime);
|
||||
case "copy":
|
||||
case "cp":
|
||||
case "clone":
|
||||
return handleCopy(parsed, runtime);
|
||||
case "delete":
|
||||
case "rm":
|
||||
case "remove":
|
||||
return handleDelete(parsed, runtime);
|
||||
case "create":
|
||||
case "new":
|
||||
case "add":
|
||||
return handleCreate(parsed, runtime);
|
||||
case "node":
|
||||
case "nodes":
|
||||
return handleNodeCommand(parsed, runtime);
|
||||
case "tail":
|
||||
case "watch":
|
||||
case "follow":
|
||||
return handleWorkflowTailCommand(parsed, runtime);
|
||||
case "lint-script":
|
||||
case "lint":
|
||||
case "lint-code":
|
||||
return handleWorkflowLintScript(parsed, runtime);
|
||||
case "eval-script":
|
||||
case "eval":
|
||||
case "eval-code":
|
||||
case "run-script":
|
||||
return handleWorkflowEvalScript(parsed, runtime);
|
||||
case "enum":
|
||||
case "enums":
|
||||
case "dictionary":
|
||||
case "dict":
|
||||
return handleWorkflowEnum(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
getJobFailedExecutions,
|
||||
isTaskExecutionFailed,
|
||||
listPlatforms,
|
||||
explainConditionBranches,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
@@ -402,6 +403,8 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
]);
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
@@ -410,6 +413,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
job,
|
||||
executionTree: tree,
|
||||
failedExecutions,
|
||||
conditionDiagnoses,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -473,6 +477,25 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
);
|
||||
}
|
||||
|
||||
if (conditionDiagnoses.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
|
||||
for (const diag of conditionDiagnoses) {
|
||||
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
|
||||
outLines.push(` • 判定结论: ${diag.summary}`);
|
||||
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
|
||||
if (diag.rules.length > 0) {
|
||||
outLines.push(" • 规则比对明细:");
|
||||
for (const r of diag.rules) {
|
||||
const statusIcon = r.matched === null ? "?" : r.matched ? "✅" : "❌";
|
||||
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
|
||||
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
|
||||
outLines.push(` ↳ ${r.detail}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
import {
|
||||
getWorkflowDetail,
|
||||
updateWorkflow,
|
||||
flattenWorkflowTaskTree,
|
||||
findWorkflowTask,
|
||||
addWorkflowTask,
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
} from "../../../domains/platform/services.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 { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
let subAction = "list";
|
||||
let pipelineId = "";
|
||||
let nodeTarget = "";
|
||||
|
||||
if (firstArg && SUB_ACTIONS.has(firstArg)) {
|
||||
subAction = firstArg;
|
||||
pipelineId = parsed.args[1] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
|
||||
nodeTarget = parsed.args[2] || stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||||
} else if (firstArg) {
|
||||
// 允许缩写直接跟 pipelineId: hose-use workflow node <pipelineId>
|
||||
pipelineId = firstArg;
|
||||
nodeTarget = parsed.args[1] || stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||||
} else {
|
||||
pipelineId = stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
|
||||
nodeTarget = stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||||
}
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
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)",
|
||||
"",
|
||||
"示例:",
|
||||
" 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,
|
||||
};
|
||||
}
|
||||
|
||||
switch (subAction) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleListNodes(pipelineId, parsed, runtime);
|
||||
case "get":
|
||||
case "show":
|
||||
case "info":
|
||||
return handleGetNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "add":
|
||||
case "append":
|
||||
case "insert":
|
||||
return handleAddNode(pipelineId, parsed, runtime);
|
||||
case "edit":
|
||||
case "update":
|
||||
case "set":
|
||||
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "rm":
|
||||
case "remove":
|
||||
case "delete":
|
||||
case "del":
|
||||
return handleRemoveNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow node 子命令: ${subAction}。支持: list, get, add, edit, rm\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleListNodes(
|
||||
pipelineId: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
const tasks = detail.tasks || [];
|
||||
const flattened = flattenWorkflowTaskTree(tasks);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ pipelineId, label: detail.label, totalNodes: flattened.length, nodes: flattened }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (flattened.length === 0) {
|
||||
return {
|
||||
stdout: `工作流 [${detail.label || pipelineId}] 暂无任何任务节点。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = flattened.map((item) => [
|
||||
item.hierarchicalIndex,
|
||||
item.task.name,
|
||||
item.task.type,
|
||||
item.task.label || "-",
|
||||
item.task.groupName || "-",
|
||||
item.summary,
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "节点标识 (name)", "类型 (type)", "标题 (label)", "分组", "配置摘要"],
|
||||
rows
|
||||
);
|
||||
|
||||
const out = [
|
||||
`====== 工作流 [${detail.label || pipelineId}] 任务节点树 (共 ${flattened.length} 个节点) ======`,
|
||||
table,
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGetNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node get <pipelineId> <nodeNameOrIndex>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client } = 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,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ pipelineId, ...located }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const { task, hierarchicalIndex, path, parentName } = located;
|
||||
const kv: Record<string, string> = {
|
||||
"工作流 ID": pipelineId,
|
||||
"节点标识 (name)": task.name,
|
||||
"层级编号 (#)": hierarchicalIndex,
|
||||
"JSON 路径": path,
|
||||
"父容器节点": parentName || "顶级节点 (root)",
|
||||
"节点类型 (type)": task.type,
|
||||
"节点标题 (label)": task.label || "-",
|
||||
"节点分组 (group)": task.groupName || "-",
|
||||
"状态 (status)": task.status || "active",
|
||||
};
|
||||
|
||||
if ((task as any).code !== undefined) {
|
||||
kv["代码行数"] = String((task as any).code.split("\n").length);
|
||||
}
|
||||
|
||||
const outLines = [
|
||||
`====== 节点详情 [${task.name}] (${task.label || task.type}) ======`,
|
||||
printKeyValue(kv),
|
||||
];
|
||||
|
||||
if ((task as any).code) {
|
||||
outLines.push("\n--- 脚本内容 ---");
|
||||
outLines.push((task as any).code);
|
||||
}
|
||||
|
||||
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleAddNode(
|
||||
pipelineId: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const type = stringOption(parsed.options, ["type", "t"]);
|
||||
if (!type) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请指定新增节点类型: --type=<类型>",
|
||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const label = stringOption(parsed.options, ["label", "name", "l"]);
|
||||
const parent = stringOption(parsed.options, ["parent", "container", "p"]);
|
||||
const after = stringOption(parsed.options, ["after", "insert-after"]);
|
||||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||||
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
|
||||
let code = stringOption(parsed.options, ["code", "c"]);
|
||||
|
||||
if (codeFile) {
|
||||
const fs = await import("fs/promises");
|
||||
code = await fs.readFile(codeFile, "utf-8");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"追加工作流节点",
|
||||
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, newTask } = addWorkflowTask(detail, {
|
||||
type,
|
||||
label,
|
||||
desc,
|
||||
code,
|
||||
parent,
|
||||
after,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||||
pipelineId,
|
||||
newNodeName: newTask.name,
|
||||
type: newTask.type,
|
||||
label: newTask.label,
|
||||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||||
totalTasksCount: updatedWorkflow.tasks?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const out = [
|
||||
`✨ 节点 [${newTask.name}] (${newTask.label}) 已成功添加至工作流 [${pipelineId}]:`,
|
||||
printKeyValue({
|
||||
"节点标识 (name)": newTask.name,
|
||||
"节点类型 (type)": newTask.type,
|
||||
"节点标题 (label)": newTask.label || "-",
|
||||
"所属位置": parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流顶级末尾",
|
||||
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
|
||||
}),
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleEditNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const label = stringOption(parsed.options, ["label", "l"]);
|
||||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||||
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
|
||||
let code = stringOption(parsed.options, ["code", "c"]);
|
||||
|
||||
if (codeFile) {
|
||||
const fs = await import("fs/promises");
|
||||
code = await fs.readFile(codeFile, "utf-8");
|
||||
}
|
||||
|
||||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||||
const customSet: Record<string, any> = {};
|
||||
if (rawSet) {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
try {
|
||||
customSet[k] = JSON.parse(v);
|
||||
} catch {
|
||||
customSet[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"修改工作流节点",
|
||||
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, editedTask } = editWorkflowTask(detail, nodeTarget, {
|
||||
label,
|
||||
desc,
|
||||
code,
|
||||
set: Object.keys(customSet).length > 0 ? customSet : undefined,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${editedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: editedTask.name,
|
||||
label: editedTask.label,
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(desc ? { desc } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRemoveNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供待删除节点标识 (name 或层级序号): hose-use workflow node rm <pipelineId> <nodeNameOrIndex>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"移除工作流节点",
|
||||
`hose-use workflow node rm ${pipelineId} ${nodeTarget} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, removedTask } = removeWorkflowTask(detail, nodeTarget);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "移除工作流节点", `${pipelineId}:${removedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: removedTask.name,
|
||||
type: removedTask.type,
|
||||
label: removedTask.label || "-",
|
||||
remainingTasksCount: updatedWorkflow.tasks?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, removedTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🗑️ 节点 [${removedTask.name}] (${removedTask.label || removedTask.type}) 已从工作流 [${pipelineId}] 中安全移除。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
import fs from "node:fs";
|
||||
import {
|
||||
getWorkflowDetail,
|
||||
getWorkflowSampleData,
|
||||
findWorkflowTask,
|
||||
lintWorkflowScripts,
|
||||
lintJavaScriptCode,
|
||||
lintMvelCode,
|
||||
executeJavaScriptSandbox,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
/**
|
||||
* 校验工作流脚本 (JavaScript / MVEL) 语法、上游引用与代码规范
|
||||
*/
|
||||
export async function handleWorkflowLintScript(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isJson = booleanOption(parsed.options, ["json"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const codeInline = stringOption(parsed.options, ["code"]);
|
||||
const explicitType = (stringOption(parsed.options, ["type"]) || "code-js2").toLowerCase();
|
||||
|
||||
// 1. 本地代码文件或行内脚本校验
|
||||
if (filePath || codeInline) {
|
||||
let rawCode = codeInline || "";
|
||||
if (filePath) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `指定的脚本文件不存在: ${filePath}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
rawCode = fs.readFileSync(filePath, "utf-8");
|
||||
}
|
||||
|
||||
const type = explicitType === "code" || explicitType === "mvel" ? "code" : "code-js2";
|
||||
let issues: Array<{ level: string; line?: number; column?: number; message: string; rule: string }> = [];
|
||||
let hasReturn = false;
|
||||
let referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
|
||||
if (type === "code-js2") {
|
||||
const res = lintJavaScriptCode(rawCode);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
} else {
|
||||
const res = lintMvelCode(rawCode);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
referencedNodes = res.referencedNodes;
|
||||
}
|
||||
|
||||
const hasErrors = issues.some((i) => i.level === "error");
|
||||
const report = {
|
||||
source: filePath ? `file: ${filePath}` : "inline-code",
|
||||
type: type === "code-js2" ? "JavaScript (code-js2)" : "MVEL (code)",
|
||||
codeLength: rawCode.length,
|
||||
lineCount: rawCode ? rawCode.split(/\r?\n/).length : 0,
|
||||
hasReturn,
|
||||
referencedNodes,
|
||||
issues,
|
||||
valid: !hasErrors,
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
printJson(report);
|
||||
return { stdout: "", stderr: "", exitCode: hasErrors ? 1 : 0 };
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`脚本静态校验: ${report.source}`);
|
||||
lines.push(`引擎类型: ${report.type} | 代码行数: ${report.lineCount} | 字符数: ${report.codeLength}`);
|
||||
lines.push(`return 语句: ${hasReturn ? "✅ 存在" : "⚠️ 缺失"}`);
|
||||
if (referencedNodes.length > 0) {
|
||||
lines.push(`引用上游节点: ${referencedNodes.map((n) => n.name).join(", ")}`);
|
||||
}
|
||||
|
||||
if (issues.length === 0) {
|
||||
lines.push("校验结果: ✅ 语法完全合规,无任何错误或警告\n");
|
||||
} else {
|
||||
lines.push(`\n发现 ${issues.length} 个潜在问题:`);
|
||||
for (const iss of issues) {
|
||||
const icon = iss.level === "error" ? "❌ [错误]" : "⚠️ [警告]";
|
||||
const loc = iss.line ? ` L${iss.line}${iss.column ? `:${iss.column}` : ""}` : "";
|
||||
lines.push(` ${icon}${loc} [${iss.rule}] ${iss.message}`);
|
||||
}
|
||||
lines.push(hasErrors ? "\n校验未通过 ❌ 请根据上述提示修复语法错误。\n" : "\n校验通过 (含告警提示) ⚠️\n");
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: hasErrors ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 线上工作流整条流水线或指定节点校验
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]);
|
||||
const targetNode = parsed.args[1] || stringOption(parsed.options, ["node", "target"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow lint-script <pipelineId> [节点标识] [选项]",
|
||||
" 或: hose-use workflow lint-script --file=<path> [--type=code-js2|code] [选项]",
|
||||
" 或: hose-use workflow lint-script --code=\"<code>\" [--type=code-js2|code] [选项]",
|
||||
"",
|
||||
"选项:",
|
||||
" --node=<name|index> 仅校验流水线中指定的某个代码节点",
|
||||
" --file=<path> 静态检查本地脚本文件",
|
||||
" --code=<code> 静态检查行内传入的代码片段",
|
||||
" --type=code-js2|code 指定脚本类型(默认 code-js2 JavaScript)",
|
||||
" --json 输出结构化 JSON 格式结果",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow lint-script 896398895352487950",
|
||||
" hose-use workflow lint-script 896398895352487950 action_dx9cci",
|
||||
" hose-use workflow lint-script --file=./scripts/clean.js",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const workflow = await getWorkflowDetail(client, pipelineId);
|
||||
const report = lintWorkflowScripts(workflow, targetNode);
|
||||
|
||||
if (isJson) {
|
||||
printJson(report);
|
||||
return { stdout: "", stderr: "", exitCode: report.allValid ? 0 : 1 };
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`工作流脚本静态校验: ${report.label || pipelineId} (${pipelineId})`);
|
||||
lines.push(`共检测 ${report.totalCodeNodes} 个代码节点 (JS/MVEL): ${report.validCount} 个合规, ${report.invalidCount} 个异常\n`);
|
||||
|
||||
if (report.reports.length === 0) {
|
||||
lines.push("未找到任何代码节点 (code / code-js2)。");
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
for (const node of report.reports) {
|
||||
const statusIcon = node.valid ? (node.issues.length > 0 ? "⚠️" : "✅") : "❌";
|
||||
const typeLabel = node.type === "code-js2" ? "JavaScript" : "MVEL";
|
||||
lines.push(`${statusIcon} 节点 [${node.nodeName}] ${node.label || node.displayName || ""} (${typeLabel})`);
|
||||
lines.push(` 代码行数: ${node.lineCount} | 字符数: ${node.codeLength} | return 语句: ${node.hasReturn ? "有" : "无"}`);
|
||||
|
||||
if (node.boundVariables.length > 0) {
|
||||
lines.push(` 绑定变量: ${node.boundVariables.map((v) => `${v.key} -> ${v.upstreamTarget || "无"}`).join(", ")}`);
|
||||
}
|
||||
|
||||
if (node.referencedNodes.length > 0) {
|
||||
lines.push(
|
||||
` 引用节点: ${node.referencedNodes.map((r) => `${r.name}${r.exists ? "" : " (❌不存在)"}`).join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
if (node.issues.length === 0) {
|
||||
lines.push(" 结果: 语法合规");
|
||||
} else {
|
||||
for (const iss of node.issues) {
|
||||
const flag = iss.level === "error" ? "❌" : "⚠️";
|
||||
const loc = iss.line ? ` L${iss.line}${iss.column ? `:${iss.column}` : ""}` : "";
|
||||
lines.push(` ${flag}${loc} [${iss.rule}] ${iss.message}`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
if (report.allValid) {
|
||||
lines.push("总体验证结果: 全部代码节点均通过语法与引用校验 ✅");
|
||||
} else {
|
||||
lines.push(`总体验证结果: 发现 ${report.invalidCount} 个代码节点存在语法错误或悬空引用 ❌`);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: report.allValid ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 在隔离沙箱中离线仿真运行工作流代码节点
|
||||
*/
|
||||
export async function handleWorkflowEvalScript(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isJson = booleanOption(parsed.options, ["json"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const codeInline = stringOption(parsed.options, ["code"]);
|
||||
const timeoutStr = stringOption(parsed.options, ["timeout"]);
|
||||
const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000;
|
||||
|
||||
// 1. 获取输入参数 inputs
|
||||
let inputs: Record<string, unknown> = {};
|
||||
const rawInput = stringOption(parsed.options, ["input", "data"]);
|
||||
const inputFile = stringOption(parsed.options, ["input-file"]);
|
||||
|
||||
if (rawInput) {
|
||||
try {
|
||||
inputs = JSON.parse(rawInput);
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `解析 --input JSON 参数失败: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (inputFile) {
|
||||
if (!fs.existsSync(inputFile)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `指定的 --input-file 不存在: ${inputFile}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
try {
|
||||
inputs = JSON.parse(fs.readFileSync(inputFile, "utf-8"));
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `解析 --input-file JSON 失败: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 本地文件或行内代码沙箱运行
|
||||
if (filePath || codeInline) {
|
||||
let code = codeInline || "";
|
||||
if (filePath) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `指定的脚本文件不存在: ${filePath}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
code = fs.readFileSync(filePath, "utf-8");
|
||||
}
|
||||
|
||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
|
||||
if (isJson) {
|
||||
printJson(evalResult);
|
||||
return { stdout: "", stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
}
|
||||
|
||||
return formatEvalCliResult(evalResult, filePath ? `file: ${filePath}` : "inline-code");
|
||||
}
|
||||
|
||||
// 3. 从工作流节点加载脚本并运行
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]);
|
||||
const targetNode = parsed.args[1] || stringOption(parsed.options, ["node", "target"]);
|
||||
|
||||
if (!pipelineId || !targetNode) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow eval-script <pipelineId> <节点标识> [选项]",
|
||||
" 或: hose-use workflow eval-script --file=<path> [--input='{...}'] [选项]",
|
||||
" 或: hose-use workflow eval-script --code=\"<code>\" [--input='{...}'] [选项]",
|
||||
"",
|
||||
"选项:",
|
||||
" --input=<json> 传递给脚本的入参 JSON 字符串",
|
||||
" --input-file=<path> 从本地 JSON 文件读取入参",
|
||||
" --sample=<index> 自动从工作流历史测试样本中提取输入(如 1、2)",
|
||||
" --timeout=<ms> 沙箱执行超时时间(毫秒,默认 3000)",
|
||||
" --json 输出结构化 JSON 格式结果",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow eval-script 896398895352487950 action_dx9cci",
|
||||
" hose-use workflow eval-script 896398895352487950 action_dx9cci --sample=1",
|
||||
" hose-use workflow eval-script 896398895352487950 action_dx9cci --input='{\"info\":{\"money\":100}}'",
|
||||
" hose-use workflow eval-script --code=\"return { total: a + b };\" --input='{\"a\":10,\"b\":20}'",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const workflow = await getWorkflowDetail(client, pipelineId);
|
||||
const located = findWorkflowTask(workflow, targetNode);
|
||||
|
||||
if (!located) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${targetNode}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const task = located.task;
|
||||
if (task.type !== "code-js2") {
|
||||
if (task.type === "code") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
`节点 [${task.name}] 是 MVEL (code) 节点。`,
|
||||
"当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。",
|
||||
"提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const code: string = (task as any).code || "";
|
||||
|
||||
// 如果没有显式传 input,尝试提取工作流样本数据
|
||||
if (Object.keys(inputs).length === 0) {
|
||||
const sampleIdxStr = stringOption(parsed.options, ["sample"]);
|
||||
try {
|
||||
const sampleResult = await getWorkflowSampleData(client, pipelineId, "webhook");
|
||||
const list = sampleResult?.records || [];
|
||||
if (list.length > 0) {
|
||||
const idx = sampleIdxStr ? Math.max(0, parseInt(sampleIdxStr, 10) - 1) : 0;
|
||||
const chosen = list[idx] || list[0];
|
||||
let samplePayload: any = chosen;
|
||||
if (chosen?.dataJson) {
|
||||
try {
|
||||
samplePayload = JSON.parse(chosen.dataJson);
|
||||
} catch {
|
||||
samplePayload = chosen.dataJson;
|
||||
}
|
||||
}
|
||||
|
||||
// 根据 code-js2 mapping 配置进行参数绑定
|
||||
const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : [];
|
||||
if (mappings.length > 0) {
|
||||
for (const m of mappings) {
|
||||
if (m.key) {
|
||||
inputs[m.key] = samplePayload;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inputs = typeof samplePayload === "object" && samplePayload !== null ? samplePayload : { sample: samplePayload };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略样例拉取失败,继续空入参执行
|
||||
}
|
||||
}
|
||||
|
||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
|
||||
if (isJson) {
|
||||
printJson(evalResult);
|
||||
return { stdout: "", stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
}
|
||||
|
||||
const targetDesc = `节点 [${task.name}] ${task.label || task.displayName || ""} (${pipelineId})`;
|
||||
return formatEvalCliResult(evalResult, targetDesc);
|
||||
}
|
||||
|
||||
function formatEvalCliResult(
|
||||
evalResult: import("../../../domains/platform/workflow/script/index.js").ScriptEvalResult,
|
||||
targetDesc: string
|
||||
): CliResult {
|
||||
const lines: string[] = [];
|
||||
const statusStr = evalResult.success ? "执行成功 ✅" : "执行失败 ❌";
|
||||
|
||||
lines.push(`代码节点沙箱仿真: ${targetDesc}`);
|
||||
lines.push(`状态: ${statusStr} | 耗时: ${evalResult.durationMs}ms`);
|
||||
|
||||
lines.push("\n入参 (Inputs):");
|
||||
lines.push(JSON.stringify(evalResult.inputs, null, 2));
|
||||
|
||||
if (evalResult.logs.length > 0) {
|
||||
lines.push("\n控制台日志 (Console Logs):");
|
||||
for (const log of evalResult.logs) {
|
||||
const icon = log.level === "error" ? "🔴" : log.level === "warn" ? "🟡" : "⚪";
|
||||
lines.push(` ${icon} [${log.level}] ${log.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (evalResult.success) {
|
||||
lines.push("\n返回值 (Return Value):");
|
||||
if (typeof evalResult.returnValue === "object" && evalResult.returnValue !== null) {
|
||||
lines.push(JSON.stringify(evalResult.returnValue, null, 2));
|
||||
} else {
|
||||
lines.push(String(evalResult.returnValue));
|
||||
}
|
||||
lines.push("");
|
||||
} else if (evalResult.error) {
|
||||
lines.push("\n异常信息 (Error Details):");
|
||||
const loc = evalResult.error.line ? ` (第 ${evalResult.error.line} 行)` : "";
|
||||
lines.push(` ${evalResult.error.name}: ${evalResult.error.message}${loc}`);
|
||||
if (evalResult.error.stack) {
|
||||
lines.push(`\n堆栈详情:\n${evalResult.error.stack}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: evalResult.success ? 0 : 1,
|
||||
};
|
||||
}
|
||||
@@ -17,8 +17,15 @@ export async function createWorkflowDetailClient(
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
try {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
const { listPlatforms } = await import("../../../domains/platform/services.js");
|
||||
const platforms = await listPlatforms(clients.ekbClient, corpId);
|
||||
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
|
||||
platformId = firstActive?.id;
|
||||
} catch {
|
||||
// Fall back to easoClient
|
||||
}
|
||||
}
|
||||
return {
|
||||
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
watchWorkflowPipeline,
|
||||
formatWatchEvent,
|
||||
type WorkflowWatchEvent,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleWorkflowTailCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const targetArg = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId", "job", "jobId"]);
|
||||
|
||||
if (!targetArg) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow tail <pipelineId> [选项]",
|
||||
"别名: hose-use workflow watch, hose-use workflow follow",
|
||||
"",
|
||||
"说明:",
|
||||
" 类似 tail -f 实时监听工作流在云端的任务派发与节点执行树跃迁,即时捕获错误与异常跳过 (SKIPPED)。",
|
||||
"",
|
||||
"选项:",
|
||||
" --job=<jobId> 定向实时监听指定 Job 直至其运行结束",
|
||||
" --interval=<秒> 轮询检查间隔秒数 (默认 2 秒,最小 1 秒)",
|
||||
" --timeout=<秒> 最长监听秒数 (超时后退出)",
|
||||
" --max-jobs=<数量> 最多持续跟踪的 Job 个数后退出",
|
||||
" --once 仅检视最新或当前运行中的 Job 进度快照,不进入持续监听循环",
|
||||
" --failed-only 仅打印报错或异常跳过的节点与失败摘要",
|
||||
" --follow, -f 持续监听 (即使单个 Job 完成后也继续等待后续新任务)",
|
||||
" --json 以 JSON 结构或 JSONL 事件流输出",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow tail 898268773466365973",
|
||||
" hose-use workflow tail 898268773466365973 --job=898577624451395602",
|
||||
" hose-use workflow watch 898268773466365973 --failed-only",
|
||||
" hose-use workflow tail 898268773466365973 --once --json",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// 允许将特定 jobId 直接作为参数,或通过 --job 指定
|
||||
const explicitJob = stringOption(parsed.options, ["job", "jobId"]);
|
||||
let pipelineId = targetArg;
|
||||
let jobId = explicitJob;
|
||||
|
||||
const intervalSec = numberOption(parsed.options, ["interval", "i"]) ?? 2;
|
||||
const timeoutSec = numberOption(parsed.options, ["timeout", "t"]);
|
||||
const maxJobs = numberOption(parsed.options, ["max-jobs", "maxJobs", "count"]);
|
||||
const once = booleanOption(parsed.options, ["once", "snapshot"], false);
|
||||
const follow = booleanOption(parsed.options, ["follow", "f"], !once && !jobId);
|
||||
const failedOnly = booleanOption(parsed.options, ["failed-only", "failedOnly", "errors"], false);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
const outputChunks: string[] = [];
|
||||
const eventsCollected: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (chunk: string) => {
|
||||
outputChunks.push(chunk);
|
||||
if (runtime.writeStdout) {
|
||||
await runtime.writeStdout(chunk);
|
||||
}
|
||||
};
|
||||
|
||||
const report = await watchWorkflowPipeline(client, pipelineId, {
|
||||
jobId,
|
||||
intervalMs: Math.max(intervalSec, 1) * 1000,
|
||||
timeoutMs: timeoutSec !== undefined ? timeoutSec * 1000 : undefined,
|
||||
maxJobs,
|
||||
once,
|
||||
follow,
|
||||
failedOnly,
|
||||
onEvent: async (ev) => {
|
||||
eventsCollected.push(ev);
|
||||
if (runtime.jsonMode) {
|
||||
if (!once) {
|
||||
await emit(JSON.stringify(ev) + "\n");
|
||||
}
|
||||
} else {
|
||||
const line = formatWatchEvent(ev);
|
||||
await emit(line + "\n");
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
if (once) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
|
||||
stderr: "",
|
||||
exitCode: report.hasFailures ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { isCorpProd } from "../../../core/config/types.js";
|
||||
import {
|
||||
classifyWorkflowTrigger,
|
||||
getWorkflowDebugSource,
|
||||
getWorkflowDetail,
|
||||
getWorkflowSampleData,
|
||||
runWorkflowDebugTest,
|
||||
type WorkflowTriggerCategory,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
|
||||
export async function handleWorkflowTest(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow test <pipelineId> [选项]",
|
||||
"",
|
||||
"不同触发器的调试参数分支:",
|
||||
" 1. 单据触发 (flowForm): --flow=<单号|ID> 指定单据",
|
||||
" 2. 台账触发 (dataLink): --record=<记录ID|编码> 指定业务对象数据",
|
||||
" 3. 定时触发 (clock): 无需业务参数,使用 --yes 确认执行",
|
||||
" 4. 外部调用 (webhook): --body='{...}' 或 --file=<path.json> 传入事件请求体",
|
||||
"",
|
||||
"通用选项:",
|
||||
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
|
||||
" --auto-publish 是否自动发布测试快照 (默认 false)",
|
||||
" --force, -f 允许在正式生产环境 (env: prod) 下执行调试",
|
||||
" --dry-run 只预览,不发起调试",
|
||||
" --yes/--confirm 确认执行真实工作流节点",
|
||||
"",
|
||||
"别名: hose-use workflow debug <pipelineId>",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
|
||||
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
|
||||
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"]);
|
||||
const isEmpty = booleanOption(parsed.options, ["empty", "none"]);
|
||||
const sampleOption = stringOption(parsed.options, ["sample", "sample-id", "sampleId"]);
|
||||
const forceProd = booleanOption(parsed.options, ["force", "f", "allow-prod", "allow-production"]);
|
||||
const isProductionCorp = Boolean(runtime.selectedCorp && isCorpProd(runtime.selectedCorp));
|
||||
|
||||
const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"];
|
||||
if (isProductionCorp) {
|
||||
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
|
||||
}
|
||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||
}
|
||||
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
// 1. 获取工作流详情与触发器元数据
|
||||
const detail = await getWorkflowDetail(client, pipelineId).catch(() => {
|
||||
warnings.push("未能读取工作流状态,启用状态未知。");
|
||||
return null;
|
||||
});
|
||||
const isEnabled = detail?.state === 1 || (detail as any)?.active === true;
|
||||
const triggerNode = detail?.tasks?.[0];
|
||||
const triggerType = triggerNode?.type || "unknown";
|
||||
const triggerLabel = triggerNode?.label || triggerNode?.name || "触发器";
|
||||
const category: WorkflowTriggerCategory = classifyWorkflowTrigger(triggerType);
|
||||
|
||||
let targetId = flowCodeOrId;
|
||||
let customPayload: Record<string, any> | undefined;
|
||||
|
||||
// 2. 根据触发器类型进行路径分支分发 (Path Branching)
|
||||
switch (category) {
|
||||
case "SCHEDULE": {
|
||||
// 分支 A: 定时任务触发器 (clock) ── 无需单据/台账,直接派发执行
|
||||
targetId = "";
|
||||
break;
|
||||
}
|
||||
|
||||
case "WEBHOOK": {
|
||||
// 分支 B: Webhook / 外部事件触发器 ── 支持 sample / body / file / empty
|
||||
targetId = "";
|
||||
if (rawBody) {
|
||||
try {
|
||||
customPayload = JSON.parse(rawBody);
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ --body 参数不是合法的 JSON 字符串: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (filePath) {
|
||||
if (!existsSync(filePath)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
try {
|
||||
customPayload = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 读取并解析文件 ${filePath} 失败: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (sampleOption) {
|
||||
// 从服务器获取历史接收样本发起测试
|
||||
try {
|
||||
const sampleResult = await getWorkflowSampleData(client, pipelineId);
|
||||
const records = sampleResult.records || [];
|
||||
let matched = records.find((r) => r.id === sampleOption);
|
||||
if (!matched) {
|
||||
const num = parseInt(sampleOption, 10);
|
||||
if (!isNaN(num) && num >= 1 && num <= records.length) {
|
||||
matched = records[num - 1];
|
||||
}
|
||||
}
|
||||
if (!matched) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 未找到指定的数据样本 [${sampleOption}]。当前服务器保存了 ${records.length} 条样本。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
customPayload = JSON.parse(matched.dataJson);
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 获取或解析数据样本失败: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (isEmpty) {
|
||||
customPayload = {};
|
||||
} else {
|
||||
// 未提供 Payload 时,展示参数定义与服务器最近接收的数据样本
|
||||
let sampleLines: string[] = [];
|
||||
try {
|
||||
const sampleResult = await getWorkflowSampleData(client, pipelineId);
|
||||
const records = sampleResult.records || [];
|
||||
if (records.length > 0) {
|
||||
const rows = records.map((r, idx) => {
|
||||
const timeStr = r.createTime
|
||||
? new Date(r.createTime).toLocaleString("zh-CN", { hour12: false })
|
||||
: "-";
|
||||
let preview = r.dataJson || "";
|
||||
if (preview.length > 55) preview = preview.slice(0, 52) + "...";
|
||||
return [idx + 1, r.id, timeStr, preview];
|
||||
});
|
||||
sampleLines = [
|
||||
"",
|
||||
`── 服务器最近接收的数据样本 (最近 ${records.length} 条) ──`,
|
||||
printTable(["#", "样本 ID", "接收时间", "数据摘要 (Payload Preview)"], rows),
|
||||
];
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// 解析触发器定义的请求参数与中文昵称映射
|
||||
const triggerParams = Array.isArray((triggerNode as any)?.params)
|
||||
? ((triggerNode as any).params as Array<{ key: string; value: string }>)
|
||||
: [];
|
||||
let paramLines: string[] = [];
|
||||
if (triggerParams.length > 0) {
|
||||
paramLines = [
|
||||
"",
|
||||
"── 接收的请求参数定义 (Params) ──",
|
||||
printTable(
|
||||
["参数名 (Key)", "中文昵称 (Label)"],
|
||||
triggerParams.map((p) => [p.key, p.value])
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`📡 [外部事件触发器: ${triggerLabel} (${triggerType})]`,
|
||||
`该工作流由 Webhook / 外部系统事件驱动,需提供模拟请求体 (Payload) 进行测试。`,
|
||||
...paramLines,
|
||||
...sampleLines,
|
||||
"",
|
||||
"调试传参选项:",
|
||||
...(sampleLines.length > 0
|
||||
? [` --sample=<1|2|3> 直接选用上述服务器最近接收的数据样本发起测试`]
|
||||
: []),
|
||||
` --body='{"key": "value"}' 直接传入自定义 JSON 请求体`,
|
||||
` --file=<payload.json> 从本地 JSON 文件读取请求体`,
|
||||
` --empty 使用空对象 {} 直接发起测试`,
|
||||
"",
|
||||
`示例: hose-use workflow test ${pipelineId} ${
|
||||
sampleLines.length > 0 ? "--sample=1" : `--body='{"code": "TEST-001"}'`
|
||||
}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "DATALINK": {
|
||||
// 分支 C: 业务对象台账变更触发器 ── 需要台账数据记录 ID (ID01...)
|
||||
if (!targetId) {
|
||||
try {
|
||||
const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 动态解析数据源列字段 (Fields)
|
||||
const hasFields = Array.isArray(source.fields) && source.fields.length > 0;
|
||||
const headers = hasFields
|
||||
? ["#", "记录 ID", ...source.fields.map((f) => f.label)]
|
||||
: ["#", "记录 ID", "编码 (Code)", "名称 (Name)", "负责人 (Owner)"];
|
||||
|
||||
const rows = source.items.map((it, idx) => {
|
||||
if (hasFields) {
|
||||
return [
|
||||
idx + 1,
|
||||
it.id,
|
||||
...source.fields.map((f) => (it as any)[f.key] || "-"),
|
||||
];
|
||||
}
|
||||
return [
|
||||
idx + 1,
|
||||
it.id,
|
||||
(it as any).code || "-",
|
||||
(it as any).name || it.title || "-",
|
||||
(it as any).owner || "-",
|
||||
];
|
||||
});
|
||||
|
||||
const out = [
|
||||
`⚠️ 未指定台账记录,请通过 --record=<记录ID|编码> 传入测试台账。`,
|
||||
...(isEnabled
|
||||
? [
|
||||
`💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`,
|
||||
` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`,
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
`── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "业务对象台账"}) ──`,
|
||||
rows.length ? printTable(headers, rows) : "暂无可用台账记录",
|
||||
"",
|
||||
`示例: hose-use workflow test ${pipelineId} --record=${source.items[0]?.id || "ID01..."}`,
|
||||
].join("\n");
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 1 };
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未指定台账记录 (--record=<ID>),且拉取候选台账失败: ${err.message || String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "FLOW_FORM":
|
||||
default: {
|
||||
// 分支 D: 单据审批事件触发器 ── 需要单据编号 (ZJ-xxx / flowId)
|
||||
if (!targetId) {
|
||||
try {
|
||||
const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = source.items.map((it, idx) => [
|
||||
idx + 1,
|
||||
it.id,
|
||||
it.title || "-",
|
||||
it.flowState || "-",
|
||||
]);
|
||||
const out = [
|
||||
`⚠️ 未指定测试单号,请通过 --flow=<单号> 传入测试单据。`,
|
||||
...(isEnabled
|
||||
? [
|
||||
`💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`,
|
||||
` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`,
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
`── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "我的单据"}) ──`,
|
||||
rows.length ? printTable(["#", "单据编号 (ID)", "单据名称 (Title)", "状态 (Status)"], rows) : "暂无可用测试单据",
|
||||
"",
|
||||
`示例: hose-use workflow test ${pipelineId} --flow=${source.items[0]?.id || "ZJ-xxxx"}`,
|
||||
].join("\n");
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 1 };
|
||||
} catch (err: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 执行端到端调试测试
|
||||
confirmExecution();
|
||||
|
||||
if (isProductionCorp && !forceProd) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
`🛑 生产环境安全阻断 (Production Safeguard):`,
|
||||
`当前工作企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 被标记为【🏭 正式生产环境】(env: prod)!`,
|
||||
`在正式生产企业执行工作流调试可能产生不可逆的单据流转、第三方系统调用与真实业务变更。`,
|
||||
``,
|
||||
`如确需在生产环境进行带副作用的真实调试,必须显式附加 --force 参数确认生产风险:`,
|
||||
` hose-use workflow test ${pipelineId} ${parsed.raw.filter((a) => !["--yes", "-y", "--dry-run"].includes(a)).slice(2).join(" ")} --yes --force`,
|
||||
``,
|
||||
`建议切换至测试企业进行调试:`,
|
||||
` hose-use corps switch <测试企业ID>`,
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const execution = await runWorkflowDebugTest(client, pipelineId, {
|
||||
flowCodeOrId: targetId,
|
||||
data: customPayload,
|
||||
triggerCategory: category,
|
||||
triggerType,
|
||||
triggerLabel,
|
||||
autoPublish,
|
||||
timeoutMs,
|
||||
});
|
||||
const report = { ...execution, productionEnabled: detail ? isEnabled : null, warnings };
|
||||
const exitCode = report.outcome === "completed" ? 0 : 1;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
const treeRows = report.executionTree.map((node, idx) => [
|
||||
idx + 1,
|
||||
node.id,
|
||||
node.name || "-",
|
||||
node.label || (node as any).displayName || "-",
|
||||
node.type || "-",
|
||||
node.status || "-",
|
||||
String((node as any).durationTime ?? node.executionTime ?? "-"),
|
||||
node.error?.message || "-",
|
||||
]);
|
||||
|
||||
const targetDescription =
|
||||
category === "SCHEDULE"
|
||||
? "(定时调度模拟触发)"
|
||||
: category === "WEBHOOK"
|
||||
? `(Webhook Payload: ${customPayload ? Object.keys(customPayload).join(", ") || "{}" : "-"})`
|
||||
: report.targetEntityId || "-";
|
||||
|
||||
const outLines = [
|
||||
...(isEnabled
|
||||
? [
|
||||
"⚠️ [生产启用态调试安全提醒]",
|
||||
`• 目标工作流 [${pipelineId}] 当前处于【🟢 生产启用中】(state = 1);`,
|
||||
"• 特权调测通道:合思 Web 控制台已置灰【调试】按钮,CLI 为您打通了此直接调测通道;",
|
||||
"• 风险提示:合思后端缺乏沙箱隔离,真实写节点(如自动审批、HTTP请求)将直接在生产生效,且服务端已自动生成新快照版本。",
|
||||
"",
|
||||
]
|
||||
: []),
|
||||
`====== 工作流自动化调测报告 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"工作流 ID (pipelineId)": pipelineId,
|
||||
"触发器类型": `[${category}] ${triggerLabel} (${triggerType})`,
|
||||
"生成 Job ID": report.jobId,
|
||||
"测试目标对象": targetDescription,
|
||||
"执行结果状态": report.status,
|
||||
"测试结果": report.outcome,
|
||||
"是否超时": String(report.timedOut),
|
||||
"诊断完整": String(report.diagnosticsComplete),
|
||||
"运行模式": report.runType,
|
||||
"总耗时(ms)": String(report.durationTime ?? "-"),
|
||||
"节点执行总数": report.executionTree.length,
|
||||
"异常/跳过节点数": report.failedExecutions.length,
|
||||
}),
|
||||
"",
|
||||
"── 顶层节点执行树 ──",
|
||||
treeRows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
|
||||
treeRows
|
||||
)
|
||||
: "暂无顶层节点执行记录",
|
||||
];
|
||||
|
||||
outLines.push(...warnings.map(warning => `⚠️ ${warning}`));
|
||||
outLines.push(...report.diagnosticsErrors.map(error => `诊断读取失败 [${error.source}]: ${error.message}`));
|
||||
|
||||
if (report.conditionDiagnoses.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
|
||||
for (const diag of report.conditionDiagnoses) {
|
||||
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
|
||||
outLines.push(` • 判定结论: ${diag.summary}`);
|
||||
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
|
||||
if (diag.rules.length > 0) {
|
||||
outLines.push(" • 规则比对明细:");
|
||||
for (const r of diag.rules) {
|
||||
const statusIcon = r.matched === null ? "?" : r.matched ? "✅" : "❌";
|
||||
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
|
||||
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
|
||||
outLines.push(` ↳ ${r.detail}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
+10
-70
@@ -1,80 +1,20 @@
|
||||
export interface HelpTopic {
|
||||
summary: string;
|
||||
usage: string;
|
||||
commands: Record<string, string>;
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
|
||||
auth: {
|
||||
summary: "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
usage: "hose-use auth <子命令>",
|
||||
commands: {
|
||||
login: "登录并保存企业凭证",
|
||||
status: "查看当前认证状态",
|
||||
refresh: "刷新账号或企业 AccessToken",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
accounts: "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
},
|
||||
},
|
||||
corps: {
|
||||
summary: "多企业租户管理",
|
||||
usage: "hose-use corps <子命令>",
|
||||
commands: {
|
||||
list: "列出本地企业配置",
|
||||
search: "搜索企业与员工",
|
||||
switch: "切换当前工作企业",
|
||||
current: "查看当前企业",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志"] },
|
||||
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
|
||||
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
|
||||
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
|
||||
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
|
||||
task: { summary: "待办中心与审批任务", usage: "hose-use task <子命令>", commands: { todo: "待我审批", approved: "我已审批", submitted: "我发起的", records: "审批记录", cc: "抄送任务" } },
|
||||
contact: { summary: "企业通讯录与人员检索", usage: "hose-use contact <子命令>", commands: { list: "列出员工", search: "搜索员工", get: "查看员工详情" } },
|
||||
dimension: { summary: "系统与自定义档案维度", usage: "hose-use dimension <子命令>", commands: { list: "列出维度", items: "列出维度项" } },
|
||||
role: { summary: "企业角色定义与成员", usage: "hose-use role <子命令>", commands: { list: "列出角色", groups: "列出角色组", members: "查看角色成员" } },
|
||||
permission: { summary: "权限模型快照", usage: "hose-use permission get", commands: { get: "查看角色权限开关" } },
|
||||
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
|
||||
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
|
||||
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
|
||||
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
|
||||
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
|
||||
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
|
||||
service: { summary: "常驻守护进程管理", usage: "hose-use service <start|stop|restart|status|logs|poll>", commands: { start: "启动服务", stop: "停止服务", restart: "重启服务", status: "查看服务状态", logs: "查看服务日志", poll: "轮询事件" } },
|
||||
probe: { summary: "企业连通性诊断", usage: "hose-use probe [corpId]", commands: { probe: "检查认证与 API 连通性" } },
|
||||
http: { summary: "轻量 HTTP Server 与交互文档", usage: "hose-use http [--port=<port>]", commands: { http: "启动 HTTP 服务" } },
|
||||
mcp: { summary: "MCP Server", usage: "hose-use mcp serve", commands: { serve: "启动 MCP 服务" } },
|
||||
aipro: { summary: "AI PRO 确定性审批仲裁", usage: "hose-use aipro <子命令>", commands: { status: "查看网关状态", bind: "绑定单据", review: "核验要点", decide: "执行仲裁" } },
|
||||
};
|
||||
import { COMMAND_METADATA, commandFlags, resolveCommandAction, resolveCommandMetadata } from "./command-metadata.js";
|
||||
import { usageError } from "./errors.js";
|
||||
export type { HelpTopic } from "./command-metadata.js";
|
||||
export const HELP_REGISTRY = COMMAND_METADATA;
|
||||
|
||||
export function renderScopedHelp(target: string[]): string {
|
||||
const area = target[0]?.toLowerCase();
|
||||
const topic = area ? HELP_REGISTRY[area] : undefined;
|
||||
if (!topic) return `未找到命令域帮助: ${target.join(" ") || "<empty>"}\n运行 hose-use --help 查看全部命令域。`;
|
||||
const resolved = resolveCommandMetadata(target[0]);
|
||||
if (!resolved) throw usageError(`未找到命令域帮助: ${target.join(" ") || "<empty>"}。运行 hose-use --help 查看全部命令域。`);
|
||||
const { area, metadata: topic } = resolved;
|
||||
|
||||
const action = target[1]?.toLowerCase();
|
||||
const action = resolveCommandAction(area, target[1]);
|
||||
if (action && !Object.hasOwn(topic.commands, action)) throw usageError(`未找到子命令帮助: ${area} ${target[1]}`);
|
||||
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
|
||||
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
|
||||
lines.push("", "支持选项:", ...Object.entries(commandFlags(area, action)).map(([key, kind]) => ` --${key}${kind === "value" ? "=<值>" : kind === "boolean-or-value" ? "[=<值>]" : ""}`));
|
||||
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import ts from "typescript";
|
||||
import { commandFlags, COMMAND_METADATA } from "./command-metadata.js";
|
||||
import { parseArgs } from "./parser.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { CLI_COMMAND_REGISTRY, findCommandByArea } from "./registry.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
|
||||
describe("strict command options", () => {
|
||||
test("rejects misspellings and missing values instead of silently dropping filters", async () => {
|
||||
const typo = await runCli(["bill", "list", "--limitt", "5", "--json"]);
|
||||
expect(typo.exitCode).toBe(2);
|
||||
expect(JSON.parse(typo.stdout).message).toContain("--limit");
|
||||
expect(typo.stderr).toBe("");
|
||||
for (const args of [["bill", "list", "--limit"], ["bill", "get", "-o"], ["--corp"], ["workflow", "get", "--file="], ["bill", "list", "--limit", "--json"]]) {
|
||||
expect((await runCli(args)).exitCode).toBe(2);
|
||||
}
|
||||
expect((await runCli(["mcp", "serve", "--unknwon"])).exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("uses command-specific boolean and value options without swallowing IDs", () => {
|
||||
expect(parseArgs(["bill", "list", "--fields", "name,code"]).options.fields).toBe("name,code");
|
||||
expect(parseArgs(["feetype", "get", "--fields", "FT001"]).args).toEqual(["FT001"]);
|
||||
expect(parseArgs(["wf", "job", "--verbose", "JOB_123"]).args).toEqual(["JOB_123"]);
|
||||
expect(parseArgs(["workflow", "create", "-f", "template.json"]).options.f).toBe("template.json");
|
||||
expect(parseArgs(["workflow", "tail", "-f", "PIPE_123"]).args).toEqual(["PIPE_123"]);
|
||||
expect(parseArgs(["auth", "import", "--raw", "curl https://example.test"]).options.raw).toBe("curl https://example.test");
|
||||
expect(parseArgs(["update", "--version", "0.9.0"]).options.version).toBe("0.9.0");
|
||||
expect(parseArgs(["http", "-h", "127.0.0.1"]).options.h).toBe("127.0.0.1");
|
||||
expect(parseArgs(["-c", "corp-test", "bill", "list"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["workflow", "get", "ID", "-c", "corp-test"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["status", "-c", "corp-test"], "aipro").options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["platform", "records", "App", "Entity", "-c", "corp-test"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["bind", "R1", "-c", "[1]"], "aipro").options.corp).toBeUndefined();
|
||||
expect(parseArgs(["bill", "list", "-c", "BILL001"]).options.corp).toBeUndefined();
|
||||
expect(parseArgs(["-h", "http"]).options.help).toBe(true);
|
||||
expect(parseArgs(["feetype", "get", "--fields", "1"]).args).toEqual(["1"]);
|
||||
});
|
||||
|
||||
test("preserves explicit booleans, aliases, negative values, and -- boundaries", () => {
|
||||
const parsed = parseArgs(["--json", "--corp", "corp-test", "bill", "list", "--limit=-5", "--mine=false", "--", "--literal"]);
|
||||
expect(parsed.options).toMatchObject({ json: true, corp: "corp-test", limit: "-5", mine: false });
|
||||
expect(parsed.args).toEqual(["--literal"]);
|
||||
expect(parseArgs(["bill", "list", "--limit", "-5"]).options.limit).toBe("-5");
|
||||
expect(parseArgs(["platform", "record", "toggle", "--active=0", "REC_1"]).args).toEqual(["toggle", "REC_1"]);
|
||||
expect(parseArgs(["bill", "get", "ID", "-o", "/tmp/output.json"]).options.outputFile).toBe("/tmp/output.json");
|
||||
expect(() => parseArgs(["bill", "get", "ID", "--json=garbage"])).toThrow("布尔值");
|
||||
});
|
||||
|
||||
test("AI PRO returns structured parse failures before opening its repository", async () => {
|
||||
const result = await runAiProCli(["review", "--findngs", "[]", "--json"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(JSON.parse(result.stdout).message).toContain("--findings");
|
||||
expect(parseArgs(["review", "--run", "R1"], "aipro").options.run).toBe("R1");
|
||||
expect(parseArgs(["decide", "approve", "R1", "--run", "--yes"], "aipro").options.run).toBe(true);
|
||||
const help = await runAiProCli(["review", "--help", "--json"]);
|
||||
expect(help.exitCode).toBe(0);
|
||||
expect(JSON.parse(help.stdout).help).toContain("核验要点");
|
||||
});
|
||||
|
||||
test("all command domains, aliases and declared flags have usable help", async () => {
|
||||
expect(CLI_COMMAND_REGISTRY.map(command => command.area)).toEqual(Object.keys(COMMAND_METADATA));
|
||||
const names = CLI_COMMAND_REGISTRY.flatMap(command => [command.area, ...command.aliases]);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
for (const [area, metadata] of Object.entries(COMMAND_METADATA)) {
|
||||
for (const name of [area, ...metadata.aliases]) {
|
||||
expect(findCommandByArea(name)?.area).toBe(area);
|
||||
const result = await runCli(["help", name]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(`${area} -`);
|
||||
if (name === area) {
|
||||
const documentedFlags = result.stdout.split("支持选项:\n")[1].split("\n\n提示:")[0].trim().split("\n").map(line => line.trim().match(/^--([^=[\s]+)/)?.[1]);
|
||||
expect(documentedFlags).toEqual(Object.keys(commandFlags(area)));
|
||||
}
|
||||
}
|
||||
}
|
||||
const workflow = await runCli(["wf", "--help"]);
|
||||
for (const action of ["enum", "lint-script", "eval-script"]) expect(workflow.stdout).toContain(action);
|
||||
expect((await runCli(["help", "workflow", "not-real"])).exitCode).toBe(2);
|
||||
expect((await runCli(["help", "workflow", "constructor"])).exitCode).toBe(2);
|
||||
expect((await runCli(["help", "not-real"])).exitCode).toBe(2);
|
||||
expect((await runCli(["workflow", "help", "enum"])).stdout).toContain("枚举");
|
||||
});
|
||||
|
||||
test("handler option declarations cannot drift outside the shared flag vocabulary", () => {
|
||||
const root = join(import.meta.dir, "commands");
|
||||
function files(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") && !e.name.endsWith(".test.ts") ? [join(dir, e.name)] : []);
|
||||
}
|
||||
const missing: string[] = [];
|
||||
for (const path of files(root)) {
|
||||
const area = relative(root, path).split("/")[0].replace(/\.ts$/, "");
|
||||
const source = ts.createSourceFile(path, readFileSync(path, "utf8"), ts.ScriptTarget.Latest, true);
|
||||
function visit(node: ts.Node) {
|
||||
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && /^(booleanOption|stringOption|numberOption|listOption)$/.test(node.expression.text)) {
|
||||
const keys = node.arguments[node.expression.text === "listOption" ? 0 : 1];
|
||||
if (keys && ts.isArrayLiteralExpression(keys)) {
|
||||
for (const key of keys.elements) if (ts.isStringLiteral(key) && !commandFlags(area)[key.text]) missing.push(`${relative(root, path)}: --${key.text}`);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(source);
|
||||
}
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
+95
-185
@@ -1,202 +1,112 @@
|
||||
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||||
|
||||
const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"raw",
|
||||
"json",
|
||||
"j",
|
||||
"help",
|
||||
"h",
|
||||
"version",
|
||||
"v",
|
||||
"V",
|
||||
"force",
|
||||
"f",
|
||||
"stateless",
|
||||
"stateful",
|
||||
"check",
|
||||
"check-only",
|
||||
"changelog",
|
||||
"log",
|
||||
"l",
|
||||
"local",
|
||||
"workspace",
|
||||
"external",
|
||||
"full",
|
||||
"allow-full",
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"y",
|
||||
"confirm",
|
||||
"force-write",
|
||||
"forceWrite",
|
||||
"dry-run",
|
||||
"dryRun",
|
||||
"dryrun",
|
||||
"all",
|
||||
"a",
|
||||
"include-disabled",
|
||||
"flat",
|
||||
"flatten",
|
||||
"table",
|
||||
"specs",
|
||||
"spec",
|
||||
"fields",
|
||||
"recursive",
|
||||
"in-place",
|
||||
"inPlace",
|
||||
"value-json",
|
||||
"valueJson",
|
||||
"has-error",
|
||||
"hasError",
|
||||
"errors",
|
||||
"failed",
|
||||
"fail",
|
||||
"fail-on-alert",
|
||||
"failOnAlert",
|
||||
"includeDetail",
|
||||
"detail",
|
||||
"apply",
|
||||
"execute",
|
||||
"do",
|
||||
"refresh",
|
||||
"overwrite",
|
||||
"elevate",
|
||||
"elevate-hose",
|
||||
"as-hose",
|
||||
"no-elevate",
|
||||
"reveal",
|
||||
"plain",
|
||||
"save",
|
||||
"persist",
|
||||
"verify",
|
||||
"workbench",
|
||||
"w",
|
||||
"active-only",
|
||||
"activeOnly",
|
||||
"active",
|
||||
"read",
|
||||
"unread",
|
||||
"clear",
|
||||
"sms",
|
||||
"sync",
|
||||
"interactive",
|
||||
"i",
|
||||
"reminder",
|
||||
"remind",
|
||||
"keep-it-secret",
|
||||
"secret",
|
||||
"private",
|
||||
"mine",
|
||||
"my",
|
||||
"self",
|
||||
"distinct",
|
||||
"risk",
|
||||
"with-risk",
|
||||
"audit",
|
||||
"github",
|
||||
"gh",
|
||||
"gitea",
|
||||
"yingqing",
|
||||
"mirror",
|
||||
]);
|
||||
import { commandFlags, GLOBAL_FLAGS, localCommandFlags, type FlagKind } from "./command-metadata.js";
|
||||
import { usageError } from "./errors.js";
|
||||
|
||||
function isExplicitBooleanLiteral(val: string | undefined): boolean {
|
||||
if (!val) return false;
|
||||
const lower = val.toLowerCase();
|
||||
return lower === "true" || lower === "false";
|
||||
function explicitBoolean(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (value.toLowerCase() === "true" || value === "1") return true;
|
||||
if (value.toLowerCase() === "false" || value === "0") return false;
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
// Space-separated numeric tokens may be positional IDs. Numeric booleans use =0/=1.
|
||||
function separatedBoolean(value: string | undefined): boolean | undefined {
|
||||
return value && /^(true|false)$/i.test(value) ? explicitBoolean(value) : undefined;
|
||||
}
|
||||
|
||||
function findContext(raw: string[], areaOverride?: string): { area?: string; action?: string } {
|
||||
let area = areaOverride;
|
||||
let action: string | undefined;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const arg = raw[i];
|
||||
if (arg === "--") break;
|
||||
if (arg.startsWith("-") && arg !== "-") {
|
||||
const key = arg.replace(/^-+/, "").split("=")[0];
|
||||
const flags = commandFlags(area, action);
|
||||
const kind = flags[key] || flags[Object.keys(flags).find(k => k.toLowerCase() === key.toLowerCase()) || ""];
|
||||
if (!arg.includes("=") && ((kind === "value" && raw[i + 1] && !raw[i + 1].startsWith("-")) || (kind !== "value" && separatedBoolean(raw[i + 1]) !== undefined))) i++;
|
||||
continue;
|
||||
}
|
||||
if (!area) area = arg.toLowerCase();
|
||||
else { action = arg.toLowerCase(); break; }
|
||||
}
|
||||
return { area, action };
|
||||
}
|
||||
|
||||
function distance(left: string, right: string): number {
|
||||
let previous = Array.from({ length: right.length + 1 }, (_, i) => i);
|
||||
for (let i = 0; i < left.length; i++) {
|
||||
const row = [i + 1];
|
||||
for (let j = 0; j < right.length; j++) row.push(Math.min(row[j] + 1, previous[j + 1] + 1, previous[j] + Number(left[i] !== right[j])));
|
||||
previous = row;
|
||||
}
|
||||
return previous[right.length];
|
||||
}
|
||||
|
||||
/** Read just the global JSON switch, even when strict parsing will fail. */
|
||||
export function isJsonRequested(raw: string[]): boolean {
|
||||
let enabled = false;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const arg = raw[i];
|
||||
if (arg === "--") break;
|
||||
if (/^--(?:json|j)(?:=|$)/i.test(arg) || /^-j$/i.test(arg)) {
|
||||
const inline = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : undefined;
|
||||
enabled = (inline !== undefined ? explicitBoolean(inline) : separatedBoolean(raw[i + 1])) ?? true;
|
||||
}
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[], areaOverride?: string): CliParsedArgs {
|
||||
const options: Record<string, string | boolean | number> = {};
|
||||
const positional: string[] = [];
|
||||
const context = findContext(rawArgs, areaOverride);
|
||||
const flags = commandFlags(context.area, context.action);
|
||||
const localFlags = localCommandFlags(context.area, context.action);
|
||||
|
||||
for (let i = 0; i < rawArgs.length; i++) {
|
||||
const arg = rawArgs[i];
|
||||
if (arg === "--") { positional.push(...rawArgs.slice(i + 1)); break; }
|
||||
if (!arg.startsWith("-") || arg === "-") { positional.push(arg); continue; }
|
||||
|
||||
if (arg === "--") {
|
||||
positional.push(...rawArgs.slice(i + 1));
|
||||
break;
|
||||
const body = arg.replace(/^-+/, "");
|
||||
const eqIdx = body.indexOf("=");
|
||||
const inputKey = eqIdx === -1 ? body : body.slice(0, eqIdx);
|
||||
const key = Object.hasOwn(flags, inputKey) ? inputKey : Object.keys(flags).find(k => k.toLowerCase() === inputKey.toLowerCase());
|
||||
if (!key) {
|
||||
const nearest = Object.keys(flags).sort((a, b) => distance(inputKey, a) - distance(inputKey, b))[0];
|
||||
const suggestion = nearest && distance(inputKey, nearest) <= Math.max(1, Math.floor(inputKey.length / 3)) ? `。是否想用 --${nearest}?` : "";
|
||||
throw usageError(`未知选项: ${arg.split("=")[0]}${suggestion}`);
|
||||
}
|
||||
const globalPrefix = positional.length === 0 && Object.hasOwn(GLOBAL_FLAGS, key);
|
||||
const kind: FlagKind = globalPrefix ? GLOBAL_FLAGS[key] : flags[key];
|
||||
const inline = eqIdx === -1 ? undefined : body.slice(eqIdx + 1);
|
||||
const next = rawArgs[i + 1];
|
||||
let value: string | boolean;
|
||||
if (kind === "boolean") {
|
||||
if (inline !== undefined) {
|
||||
const parsed = explicitBoolean(inline);
|
||||
if (parsed === undefined) throw usageError(`选项 --${key} 需要布尔值 true/false 或 1/0`);
|
||||
value = parsed;
|
||||
} else if (separatedBoolean(next) !== undefined) {
|
||||
value = separatedBoolean(next)!;
|
||||
i++;
|
||||
} else value = true;
|
||||
} else if (inline !== undefined) {
|
||||
if (!inline.length) throw usageError(`选项 --${key} 缺少值`);
|
||||
value = kind === "boolean-or-value" ? explicitBoolean(inline) ?? inline : inline;
|
||||
} else if (next !== undefined && next !== "--" && (!next.startsWith("-") || /^-\d+(?:\.\d+)?$/.test(next))) {
|
||||
value = kind === "boolean-or-value" ? separatedBoolean(next) ?? next : next;
|
||||
i++;
|
||||
} else if (kind === "boolean-or-value") value = true;
|
||||
else throw usageError(`选项 --${key} 缺少值`);
|
||||
|
||||
if (arg.startsWith("--")) {
|
||||
const eqIdx = arg.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const key = arg.slice(2, eqIdx);
|
||||
const val = arg.slice(eqIdx + 1);
|
||||
options[key] = val;
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
const keyLower = key.toLowerCase();
|
||||
const next = rawArgs[i + 1];
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
if (isExplicitBooleanLiteral(next)) {
|
||||
const boolVal = next!.toLowerCase() === "true";
|
||||
options[key] = boolVal;
|
||||
if (key !== keyLower) options[keyLower] = boolVal;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
}
|
||||
} else {
|
||||
if (next && !next.startsWith("-")) {
|
||||
options[key] = next;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg.startsWith("-") && arg.length > 1) {
|
||||
const flag = arg.slice(1);
|
||||
const flagLower = flag.toLowerCase();
|
||||
if (flagLower === "h" || flag === "?") {
|
||||
options.help = true;
|
||||
} else if (flagLower === "j") {
|
||||
options.json = true;
|
||||
} else if (flagLower === "v") {
|
||||
options.version = true;
|
||||
} else if (flag === "o") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.outputFile = next;
|
||||
i++;
|
||||
} else {
|
||||
options.o = true;
|
||||
}
|
||||
} else if (flag === "c") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.c = next;
|
||||
i++;
|
||||
} else {
|
||||
options.c = true;
|
||||
}
|
||||
} else {
|
||||
options[flag] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
positional.push(arg);
|
||||
options[key] = value;
|
||||
// Preserve command-specific short names; global short names also get their semantic key.
|
||||
const globalNames: Record<string, string> = { h: "help", "?": "help", j: "json", v: "version", V: "version", c: "corp", o: "outputFile" };
|
||||
if (globalNames[key] && (globalPrefix || !Object.hasOwn(localFlags, key) || key === "j" || key === "o" || key === "V")) options[globalNames[key]] = value;
|
||||
}
|
||||
|
||||
const area = positional[0]?.toLowerCase();
|
||||
const action = positional[1]?.toLowerCase();
|
||||
const args = positional.slice(2);
|
||||
|
||||
return {
|
||||
area,
|
||||
action,
|
||||
args,
|
||||
positional,
|
||||
options,
|
||||
raw: rawArgs,
|
||||
};
|
||||
return { area: positional[0]?.toLowerCase(), action: positional[1]?.toLowerCase(), args: positional.slice(2), positional, options, raw: rawArgs };
|
||||
}
|
||||
|
||||
export function stringOption(
|
||||
|
||||
+22
-31
@@ -2,10 +2,17 @@ import { writeFileSync } from "node:fs";
|
||||
import { formatVersionLabel } from "../version.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
import { PayloadTooLargeError } from "./errors.js";
|
||||
import { renderScopedHelp } from "./help.js";
|
||||
import { renderScopedHelp, HELP_REGISTRY } from "./help.js";
|
||||
|
||||
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
/** Await the write callback so a slow terminal or pipe applies backpressure. */
|
||||
export function writeStdoutChunk(chunk: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
process.stdout.write(chunk, error => error ? reject(error) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
@@ -41,6 +48,18 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||
return json;
|
||||
}
|
||||
|
||||
export function formatCorpEnvLabel(env?: string): string {
|
||||
switch (env) {
|
||||
case "test":
|
||||
return "🧪 测试";
|
||||
case "demo":
|
||||
return "🎪 演示";
|
||||
case "prod":
|
||||
default:
|
||||
return "🏭 正式";
|
||||
}
|
||||
}
|
||||
|
||||
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
|
||||
if (persistentOpenApi || source === "openapi") {
|
||||
return "企业开放接口 (OpenAPI 密钥)";
|
||||
@@ -167,35 +186,7 @@ export function printHelp(target: string[] = []): string {
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
|
||||
核心命令域:
|
||||
context 查看全局运行上下文与身份诊断 (context, status, whoami, env)
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts, switch-account)
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, job, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
|
||||
menu 桌面端主导航菜单树与模块 (list, tree, apps)
|
||||
platform 自建应用与数据模型 (list, get, entities, schema, records [--all], record get|create|edit|batch-edit, audit, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, spec <模板ID>, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
|
||||
openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys)
|
||||
keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r])
|
||||
store 应用中心已购应用与应用商店探查 (list, search <关键词>, get <ID>)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
|
||||
mcp MCP Server 运行 (serve)
|
||||
${Object.entries(HELP_REGISTRY).map(([area, topic]) => ` ${area.padEnd(12)}${topic.summary} (${Object.keys(topic.commands).join(", ")})`).join("\n")}
|
||||
version 查看版本信息
|
||||
|
||||
全局选项:
|
||||
@@ -276,7 +267,7 @@ export function printHelp(target: string[] = []): string {
|
||||
hose-use service status # 查看守护进程运行状态与接口地址
|
||||
hose-use service poll --corp=<id> # 轮询待办/消息并持久化去重事件
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use skill install --yes # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
hose-use update --github # 强制走官方 GitHub 源升级
|
||||
hose-use update --changelog # 查看版本发布历史
|
||||
|
||||
+31
-31
@@ -26,6 +26,7 @@ import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
@@ -34,9 +35,8 @@ export type CliCommandHandler = (
|
||||
options: CliRunOptions
|
||||
) => Promise<CliResult>;
|
||||
|
||||
export interface CliCommandDefinition {
|
||||
export interface CliCommandDefinition extends CliCommandMetadata {
|
||||
area: string;
|
||||
aliases: string[];
|
||||
standing?: boolean | ((args: string[]) => boolean);
|
||||
handler: CliCommandHandler;
|
||||
}
|
||||
@@ -44,12 +44,12 @@ export interface CliCommandDefinition {
|
||||
export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "context",
|
||||
aliases: ["status", "whoami", "env"],
|
||||
...COMMAND_METADATA.context,
|
||||
handler: (parsed, runtime) => handleContextCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "aipro",
|
||||
aliases: [],
|
||||
...COMMAND_METADATA.aipro,
|
||||
handler: async (parsed) => {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
@@ -59,139 +59,139 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
aliases: ["login"],
|
||||
...COMMAND_METADATA.auth,
|
||||
handler: (parsed, runtime) => handleAuthCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "corps",
|
||||
aliases: ["corp"],
|
||||
...COMMAND_METADATA.corps,
|
||||
handler: (parsed, runtime) => handleCorpsCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "config",
|
||||
aliases: ["mode"],
|
||||
...COMMAND_METADATA.config,
|
||||
handler: (parsed, runtime) => handleConfigCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "workflow",
|
||||
aliases: ["workflows", "wf"],
|
||||
...COMMAND_METADATA.workflow,
|
||||
handler: (parsed, runtime) => handleWorkflowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "bill",
|
||||
aliases: ["bills", "fee", "fees", "invoice", "invoices"],
|
||||
...COMMAND_METADATA.bill,
|
||||
handler: (parsed, runtime) => handleBillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "flow",
|
||||
aliases: ["flows", "trace"],
|
||||
...COMMAND_METADATA.flow,
|
||||
handler: (parsed, runtime) => handleFlowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "contact",
|
||||
aliases: ["contacts", "staff", "staffs"],
|
||||
...COMMAND_METADATA.contact,
|
||||
handler: (parsed, runtime) => handleContactCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "task",
|
||||
aliases: ["tasks", "todo"],
|
||||
...COMMAND_METADATA.task,
|
||||
handler: (parsed, runtime) => handleTaskCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "dimension",
|
||||
aliases: ["dimensions", "archive", "archives"],
|
||||
...COMMAND_METADATA.dimension,
|
||||
handler: (parsed, runtime) => handleDimensionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "feetype",
|
||||
aliases: ["feetypes", "fee-type", "fee-types", "expense-type", "expense-types", "costtype"],
|
||||
...COMMAND_METADATA.feetype,
|
||||
handler: (parsed, runtime) => handleFeeTypeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "role",
|
||||
aliases: ["roles"],
|
||||
...COMMAND_METADATA.role,
|
||||
handler: (parsed, runtime) => handleRoleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "permission",
|
||||
aliases: ["permissions"],
|
||||
...COMMAND_METADATA.permission,
|
||||
handler: (parsed, runtime) => handlePermissionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "rule",
|
||||
aliases: ["rules"],
|
||||
...COMMAND_METADATA.rule,
|
||||
handler: (parsed, runtime) => handleRuleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "approval",
|
||||
aliases: ["approvals", "audit"],
|
||||
...COMMAND_METADATA.approval,
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
aliases: ["messages", "notify", "notifications"],
|
||||
...COMMAND_METADATA.message,
|
||||
handler: (parsed, runtime) => handleMessageCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "platform",
|
||||
aliases: ["platforms", "datalink", "data-link"],
|
||||
...COMMAND_METADATA.platform,
|
||||
handler: (parsed, runtime) => handlePlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "app",
|
||||
aliases: ["apps", "workbench"],
|
||||
...COMMAND_METADATA.app,
|
||||
handler: (parsed, runtime) => handleAppCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "menu",
|
||||
aliases: ["menus"],
|
||||
...COMMAND_METADATA.menu,
|
||||
handler: (parsed, runtime) => handleMenuCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "skill",
|
||||
aliases: ["skills"],
|
||||
...COMMAND_METADATA.skill,
|
||||
handler: (parsed, runtime) => handleSkillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "probe",
|
||||
aliases: ["diagnose"],
|
||||
...COMMAND_METADATA.probe,
|
||||
handler: (parsed, runtime) => handleProbeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "update",
|
||||
aliases: ["upgrade", "self-update", "changelog"],
|
||||
...COMMAND_METADATA.update,
|
||||
handler: (parsed, runtime, options) => handleUpdateCommand(parsed, runtime, options),
|
||||
},
|
||||
{
|
||||
area: "openapi",
|
||||
aliases: ["schema", "spec"],
|
||||
...COMMAND_METADATA.openapi,
|
||||
handler: (parsed, runtime) => handleOpenApiCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "keys",
|
||||
aliases: ["key", "secret", "secrets"],
|
||||
...COMMAND_METADATA.keys,
|
||||
handler: (parsed, runtime) => handleKeysCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "store",
|
||||
aliases: ["market"],
|
||||
...COMMAND_METADATA.store,
|
||||
handler: (parsed, runtime) => handleStoreCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "http",
|
||||
aliases: ["server", "web"],
|
||||
...COMMAND_METADATA.http,
|
||||
standing: true,
|
||||
handler: (parsed, runtime) => handleHttpCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "service",
|
||||
aliases: ["daemon"],
|
||||
...COMMAND_METADATA.service,
|
||||
standing: (args) => args[1]?.toLowerCase() === "run",
|
||||
handler: (parsed, runtime) => handleServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
aliases: [],
|
||||
...COMMAND_METADATA.mcp,
|
||||
standing: true,
|
||||
handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options),
|
||||
},
|
||||
|
||||
+30
-25
@@ -1,6 +1,7 @@
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions, isJsonRequested } from "./parser.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||
import { resolveCommandMetadata } from "./command-metadata.js";
|
||||
import { classifyCliError } from "./errors.js";
|
||||
import { initCorpRuntime } from "./helpers.js";
|
||||
import { findCommandByArea, isStandingCommand } from "./registry.js";
|
||||
@@ -29,7 +30,7 @@ async function runCliOnce(
|
||||
): Promise<CliResult> {
|
||||
const stdoutChunks: string[] = [];
|
||||
const stderrChunks: string[] = [];
|
||||
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
|
||||
const machineJson = isJsonRequested(rawArgs);
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
|
||||
@@ -62,7 +63,7 @@ async function runCliOnce(
|
||||
|
||||
function isHelpRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?") return true;
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?" || parsed.action === "help") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
@@ -79,6 +80,9 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
const localFlags = resolveCommandMetadata(parsed.area)?.metadata.flags;
|
||||
if (key === "v" && localFlags?.v) continue;
|
||||
if (key === "version" && localFlags?.version === "value" && typeof val !== "boolean") continue;
|
||||
if (normKey === "version" || normKey === "v") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
@@ -90,10 +94,28 @@ function resolveHelpTarget(parsed: CliParsedArgs): string[] {
|
||||
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
|
||||
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
return [parsed.area, parsed.action].filter((value): value is string => Boolean(value));
|
||||
return [parsed.area, parsed.action === "help" ? parsed.args[0] : parsed.action].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
async function dispatchCli(
|
||||
async function dispatchCli(rawArgs: string[], options: CliRunOptions = {}): Promise<CliResult> {
|
||||
try {
|
||||
return await dispatchParsedCli(rawArgs, options);
|
||||
} catch (error) {
|
||||
return cliErrorResult(error, isJsonRequested(rawArgs));
|
||||
}
|
||||
}
|
||||
|
||||
export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult {
|
||||
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
return {
|
||||
stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "",
|
||||
stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
async function dispatchParsedCli(
|
||||
rawArgs: string[],
|
||||
options: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
@@ -117,7 +139,7 @@ async function dispatchCli(
|
||||
};
|
||||
}
|
||||
|
||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||
const corpIdOption = stringOption(parsed.options, ["corp"]);
|
||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||
const outputOpts = outputOptions(parsed.options);
|
||||
@@ -136,6 +158,7 @@ async function dispatchCli(
|
||||
entryFile: options.entryFile,
|
||||
launcher: options.launcher,
|
||||
});
|
||||
runtime.writeStdout = options.writeStdout;
|
||||
|
||||
try {
|
||||
if (!parsed.area) {
|
||||
@@ -151,24 +174,6 @@ async function dispatchCli(
|
||||
}
|
||||
return await commandDef.handler(parsed, runtime, options);
|
||||
} catch (error) {
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
if (jsonMode) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
error: true,
|
||||
message: errorMsg,
|
||||
exitCode: classification.exitCode,
|
||||
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
|
||||
}, null, 2),
|
||||
stderr: "",
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
return cliErrorResult(error, jsonMode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/server";
|
||||
import { runCli } from "./runner.js";
|
||||
import { createServer, HOSE_CLI_TOOL_NAME } from "../server.js";
|
||||
import { startHttpServer } from "../http/server.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
import * as shared from "./commands/platform/shared.js";
|
||||
import * as records from "../domains/datalink/services.js";
|
||||
|
||||
describe("NDJSON output destinations across CLI, MCP and HTTP", () => {
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
let directory: string;
|
||||
let produced: number;
|
||||
let directWrite: ReturnType<typeof spyOn>;
|
||||
const command = ["platform", "records", "app", "entity", "--ndjson", "--raw"];
|
||||
beforeEach(() => {
|
||||
directory = mkdtempSync(join(tmpdir(), "hose-stream-test-"));
|
||||
produced = 0;
|
||||
spies.push(spyOn(helpers, "initCorpRuntime").mockImplementation(options => ({ selectedCorp: { id: "mock-corp" }, jsonMode: options?.jsonMode, outputOptions: options?.outputOptions }) as any));
|
||||
spies.push(spyOn(shared, "resolveAppAndEntity").mockResolvedValue({ clients: { ekbClient: {} }, corpId: "mock-corp", platform: { id: "app" }, entity: { id: "entity", fields: [] } } as any));
|
||||
spies.push(spyOn(records, "iterateAllEntityRecords").mockImplementation(async function* () {
|
||||
produced++; yield { id: "r1", secret: "mock-secret" };
|
||||
produced++; yield { id: "r2", active: true };
|
||||
}));
|
||||
directWrite = spyOn(process.stdout, "write").mockImplementation(() => true);
|
||||
spies.push(directWrite);
|
||||
});
|
||||
afterEach(() => {
|
||||
while (spies.length) spies.pop()!.mockRestore();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("waits for the terminal destination before producing the next record", async () => {
|
||||
let started!: () => void, release!: () => void;
|
||||
const firstWrite = new Promise<void>(resolve => { started = resolve; });
|
||||
const blocked = new Promise<void>(resolve => { release = resolve; });
|
||||
const chunks: string[] = [];
|
||||
const running = runCli(command, { writeStdout: async chunk => {
|
||||
chunks.push(chunk);
|
||||
if (chunks.length === 1) { started(); await blocked; }
|
||||
} });
|
||||
await firstWrite;
|
||||
expect(produced).toBe(1);
|
||||
release();
|
||||
const result = await running;
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(chunks).toHaveLength(2);
|
||||
expect(chunks[0]).not.toContain("mock-secret");
|
||||
expect(JSON.parse(chunks[0]).secret).toBe("<redacted>");
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes actual NDJSON to output-file and returns a compact summary", async () => {
|
||||
const outputFile = join(directory, "records.ndjson");
|
||||
const result = await runCli([...command, "-o", outputFile]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const summary = JSON.parse(result.stdout);
|
||||
const contents = readFileSync(outputFile, "utf8");
|
||||
expect(summary.outputFile).toBe(outputFile);
|
||||
expect(summary.records).toBe(2);
|
||||
expect(summary.bytes).toBe(Buffer.byteLength(contents));
|
||||
expect(contents.trim().split("\n").map(line => JSON.parse(line).id)).toEqual(["r1", "r2"]);
|
||||
expect(contents).not.toContain("mock-secret");
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects embedded streaming without a destination before fetching records", async () => {
|
||||
const result = await runCli([...command, "--json"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stdout).toContain("output-file");
|
||||
expect(produced).toBe(0);
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a proper MCP error rather than emitting record bytes on process stdout", async () => {
|
||||
const server = createServer({ enabled: true });
|
||||
const client = new Client({ name: "stream-test", version: "1" });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
|
||||
const result = await client.callTool({ name: HOSE_CLI_TOOL_NAME, arguments: { command: command.join(" ") } });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(JSON.stringify(result.content)).toContain("output-file");
|
||||
expect(produced).toBe(0);
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns an HTTP error response instead of a successful empty result", async () => {
|
||||
const server = await startHttpServer({ host: "127.0.0.1", port: 0, silent: true });
|
||||
try {
|
||||
const address = server.address() as { port: number };
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (process.env.HOSE_HTTP_TOKEN) headers.Authorization = `Bearer ${process.env.HOSE_HTTP_TOKEN.trim()}`;
|
||||
const response = await fetch(`http://127.0.0.1:${address.port}/api/cli`, { method: "POST", headers, body: JSON.stringify({ command: command.join(" ") }) });
|
||||
expect(response.status).toBe(400);
|
||||
const result = await response.json() as { exitCode: number; stderr: string };
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("output-file");
|
||||
expect(produced).toBe(0);
|
||||
expect(directWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,8 @@ export interface CliParsedArgs {
|
||||
}
|
||||
|
||||
export interface CliRunOptions {
|
||||
/** Only terminal entrypoints supply a protocol-safe streaming destination. */
|
||||
writeStdout?: (chunk: string) => Promise<void>;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
launcher?: {
|
||||
@@ -33,6 +35,7 @@ export interface OutputOptions {
|
||||
}
|
||||
|
||||
export interface CliRuntime {
|
||||
writeStdout?: (chunk: string) => Promise<void>;
|
||||
corpContext: CorpContext;
|
||||
selectedCorp: CorpConfig | null;
|
||||
jsonMode: boolean;
|
||||
|
||||
+13
-1
@@ -34,10 +34,16 @@ src/core/
|
||||
├── config/ # 企业配置管理
|
||||
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
||||
│ ├── manager.ts # CorpContext 多企业上下文与身份解析
|
||||
│ └── types.ts # CorpConfig / GlobalConfig Schema 与统一字段访问器
|
||||
│ └── types.ts # CorpConfig / GlobalConfig Schema 与统一字段访问器(支持 env 生产/测试/演示环境与智能推导)
|
||||
└── errors.ts # 统一异常语义(EkbError / NotLoggedInError / AuthenticationError / PermissionError / NotFoundError / ValidationError / BusinessError / EkbApiError)
|
||||
```
|
||||
|
||||
## 企业环境属性与安全兜底 (env & isTest)
|
||||
|
||||
- `CorpConfigSchema` 显式扩展 `env: "prod" | "test" | "demo"` 与 `isTest: boolean`
|
||||
- 智能初判规则(`inferCorpEnvFromName`):企业名称/标识包含“测试”或“test”归为 `test`,包含“演示”/“POC”/“demo”归为 `demo`;**未知企业一律默认且保守归为正式生产环境 `prod`**,绝不允许将生产企业误放行。
|
||||
- 归一化(`normalizeCorpConfig`):在配置加载与写入时确保 `env` 与 `isTest` 对齐,旧版未标注配置自动平滑升级并持久化。
|
||||
|
||||
## 分层约束
|
||||
|
||||
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
|
||||
@@ -46,3 +52,9 @@ src/core/
|
||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
|
||||
|
||||
|
||||
## 员工换签与默认会话
|
||||
|
||||
- `getCorpProvisionalAuthLink` 显式指定 `staffId` 时需要已配置的 OpenAPI 密钥;旧员工的 Session Token 不会伪装成目标员工。
|
||||
- 临时换签只返回独立链接,不修改默认身份、Token 或缓存。只有 `persistStaff=true` 才把目标身份、Token、有效期和员工名称一起持久化;同一身份的普通续期保持原行为。
|
||||
- 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。
|
||||
@@ -0,0 +1,80 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { getCorpProvisionalAuthLink } from "./openapi-onboard.js";
|
||||
import * as openapi from "./openapi-v1.js";
|
||||
import * as loader from "../config/loader.js";
|
||||
import * as links from "./link-import.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
describe("provisional link identity isolation", () => {
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
afterEach(() => { while (spies.length) spies.pop()!.mockRestore(); });
|
||||
function setup(uid = "corp:B") {
|
||||
const corp: CorpConfig = {
|
||||
id: "corp", name: "Mock", source: "openapi", baseUrl: "https://example.test",
|
||||
staffId: "corp:A", staffName: "A", session: { staffName: "A" },
|
||||
credentials: { accessToken: "token-A", corpId: "corp", staffId: "corp:A", appKey: "key", appSecurity: "security" },
|
||||
};
|
||||
const token = spyOn(openapi, "fetchHoseOpenApiAccessToken").mockResolvedValue("openapi");
|
||||
const sign = spyOn(openapi, "fetchHoseProvisionalAuth").mockResolvedValue({ uid, token: "token-B", url: "https://example.test/link", expiresIn: 7200, expiresAt: Date.now() + 7200000 });
|
||||
const save = spyOn(loader, "saveCorpConfig").mockReturnValue("/mock/corp.json");
|
||||
const invalidate = spyOn(links, "invalidateCorpSubdomainTokenCaches").mockImplementation(() => {});
|
||||
spies.push(token, sign, save, invalidate);
|
||||
return { corp, save, sign, invalidate };
|
||||
}
|
||||
|
||||
it("does not mutate or save the default identity for a temporary staff link", async () => {
|
||||
const { corp, save, invalidate } = setup();
|
||||
const before = structuredClone(corp);
|
||||
const result = await getCorpProvisionalAuthLink(corp, { staffId: "corp:B", staffName: "B" });
|
||||
expect(result.staffId).toBe("corp:B");
|
||||
expect(result.staffName).toBe("B");
|
||||
expect(corp).toEqual(before);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists token and normalized identity together and clears the old staff name", async () => {
|
||||
const { corp, save } = setup();
|
||||
const result = await getCorpProvisionalAuthLink(corp, { staffId: "B", persistStaff: true });
|
||||
expect(result.staffName).toBeUndefined();
|
||||
expect(corp.credentials.accessToken).toBe("token-B");
|
||||
expect(corp.credentials.staffId).toBe("corp:B");
|
||||
expect(corp.staffId).toBe("corp:B");
|
||||
expect(corp.staffName).toBeUndefined();
|
||||
expect(corp.session?.staffName).toBeUndefined();
|
||||
expect(save.mock.calls[0]?.[0].credentials.staffId).toBe("corp:B");
|
||||
});
|
||||
|
||||
it("keeps ordinary renewal of the same staff working", async () => {
|
||||
const { corp, save } = setup("corp:A");
|
||||
await getCorpProvisionalAuthLink(corp);
|
||||
expect(corp.credentials.accessToken).toBe("token-B");
|
||||
expect(corp.credentials.staffId).toBe("corp:A");
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not partly mutate memory when saving fails", async () => {
|
||||
const { corp, save } = setup();
|
||||
const before = structuredClone(corp);
|
||||
save.mockImplementation(() => { throw new Error("disk unavailable"); });
|
||||
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B", persistStaff: true })).rejects.toThrow("disk unavailable");
|
||||
expect(corp).toEqual(before);
|
||||
});
|
||||
|
||||
it("rejects a mismatched signing identity before persisting", async () => {
|
||||
const { corp, save } = setup("corp:C");
|
||||
const before = structuredClone(corp);
|
||||
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B", persistStaff: true })).rejects.toThrow("身份与目标员工不一致");
|
||||
expect(corp).toEqual(before);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not disguise an existing session as another staff without OpenAPI keys", async () => {
|
||||
const { corp, sign, save } = setup();
|
||||
delete corp.credentials.appKey;
|
||||
delete corp.credentials.appSecurity;
|
||||
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B" })).rejects.toThrow("需要已配置的 OpenAPI");
|
||||
expect(sign).not.toHaveBeenCalled();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -424,6 +424,10 @@ export async function getCorpProvisionalAuthLink(
|
||||
const targetStaffId = options.staffId || corp.staffId || corp.credentials.staffId;
|
||||
const targetStaffName = options.staffName || (options.staffId ? undefined : corp.staffName || corp.session?.staffName);
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const syncLocalSession = options.syncLocalSession !== false && (!options.staffId || options.persistStaff === true);
|
||||
if (options.staffId && !hasOpenApiPersistentCredentials(corp)) {
|
||||
throw new AuthenticationError("切换员工签发链接需要已配置的 OpenAPI 持久化密钥,现有会话不能代表其他员工。");
|
||||
}
|
||||
|
||||
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
|
||||
if (!hasOpenApiPersistentCredentials(corp)) {
|
||||
@@ -455,21 +459,26 @@ export async function getCorpProvisionalAuthLink(
|
||||
pageType,
|
||||
});
|
||||
|
||||
if (options.syncLocalSession !== false) {
|
||||
corp.credentials.accessToken = provisional.token;
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = provisional.expiresAt;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = provisional.expiresAt;
|
||||
const normalizedStaffId = targetStaffId.includes(":") ? targetStaffId : `${corpId}:${targetStaffId}`;
|
||||
if (provisional.uid !== normalizedStaffId) {
|
||||
throw new AuthenticationError("免密链接签发身份与目标员工不一致,未更新本地会话。");
|
||||
}
|
||||
if (syncLocalSession) {
|
||||
const updated = structuredClone(corp);
|
||||
updated.credentials.accessToken = provisional.token;
|
||||
if (!updated.auth) updated.auth = { refreshTtl: 300 };
|
||||
updated.auth.expiresAt = provisional.expiresAt;
|
||||
if (updated.session) {
|
||||
updated.session.expTime = provisional.expiresAt;
|
||||
}
|
||||
if (options.persistStaff && options.staffId) {
|
||||
corp.staffId = options.staffId;
|
||||
corp.credentials.staffId = options.staffId;
|
||||
if (options.staffName) {
|
||||
corp.staffName = options.staffName;
|
||||
}
|
||||
updated.staffId = normalizedStaffId;
|
||||
updated.credentials.staffId = normalizedStaffId;
|
||||
updated.staffName = options.staffName;
|
||||
if (updated.session) updated.session.staffName = options.staffName;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
saveCorpConfig(updated, options.enterprisesDir);
|
||||
Object.assign(corp, updated);
|
||||
invalidateCorpSubdomainTokenCaches(corp);
|
||||
}
|
||||
|
||||
@@ -477,7 +486,7 @@ export async function getCorpProvisionalAuthLink(
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId: provisional.uid || targetStaffId,
|
||||
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
|
||||
staffName: targetStaffName ?? undefined,
|
||||
url: provisional.url,
|
||||
token: provisional.token,
|
||||
expiresIn: provisional.expiresIn,
|
||||
@@ -504,7 +513,7 @@ export async function getCorpProvisionalAuthLink(
|
||||
);
|
||||
}
|
||||
|
||||
if (explicitDuration !== undefined && options.syncLocalSession !== false) {
|
||||
if (explicitDuration !== undefined && syncLocalSession) {
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = expMs;
|
||||
if (corp.session) {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
CorpConfig,
|
||||
CorpConfigSchema,
|
||||
getCorpEnv,
|
||||
inferCorpEnvFromName,
|
||||
isCorpProd,
|
||||
isCorpTest,
|
||||
normalizeCorpConfig,
|
||||
} from "./types.js";
|
||||
|
||||
describe("CorpConfig Environment Attributes & Deduction", () => {
|
||||
it("inferCorpEnvFromName deduces environment conservatively based on name and id", () => {
|
||||
// 包含“测试”或“test”
|
||||
expect(inferCorpEnvFromName("HAB对公测试环境", "ID01uzxB4x07fh")).toBe("test");
|
||||
expect(inferCorpEnvFromName("Finance Test Corp", "ID_TEST_01")).toBe("test");
|
||||
expect(inferCorpEnvFromName(undefined, "test-corp-id")).toBe("test");
|
||||
|
||||
// 包含“演示”或“POC”或“demo”
|
||||
expect(inferCorpEnvFromName("合思POC演示企业", "ID01demo")).toBe("demo");
|
||||
expect(inferCorpEnvFromName("Demo Corporation", "ID01")).toBe("demo");
|
||||
|
||||
// 真实生产企业一律保守识别为正式环境 prod
|
||||
expect(inferCorpEnvFromName("新转转集团", "ID01PH4Q5CJboX")).toBe("prod");
|
||||
expect(inferCorpEnvFromName("美年大健康产业控股股份有限公司", "ID01MCcOgJl1td")).toBe("prod");
|
||||
expect(inferCorpEnvFromName("北京某科技有限公司", "ID01abc")).toBe("prod");
|
||||
expect(inferCorpEnvFromName("", "")).toBe("prod");
|
||||
expect(inferCorpEnvFromName(undefined, undefined)).toBe("prod");
|
||||
});
|
||||
|
||||
it("getCorpEnv respects explicit env, falls back to isTest, and finally infers", () => {
|
||||
const explicitTest = {
|
||||
id: "c1",
|
||||
name: "普通企业名",
|
||||
env: "test" as const,
|
||||
credentials: { corpId: "c1", staffId: "s1", accessToken: "t1" },
|
||||
};
|
||||
expect(getCorpEnv(explicitTest as CorpConfig)).toBe("test");
|
||||
|
||||
const explicitProd = {
|
||||
id: "c2",
|
||||
name: "虽然名字叫测试但显式指定了正式",
|
||||
env: "prod" as const,
|
||||
credentials: { corpId: "c2", staffId: "s2", accessToken: "t2" },
|
||||
};
|
||||
expect(getCorpEnv(explicitProd as CorpConfig)).toBe("prod");
|
||||
|
||||
const legacyIsTest = {
|
||||
id: "c3",
|
||||
name: "旧企业无env",
|
||||
isTest: true,
|
||||
credentials: { corpId: "c3", staffId: "s3", accessToken: "t3" },
|
||||
};
|
||||
expect(getCorpEnv(legacyIsTest as CorpConfig)).toBe("test");
|
||||
|
||||
const legacyNoEnv = {
|
||||
id: "c4",
|
||||
name: "新转转集团",
|
||||
credentials: { corpId: "c4", staffId: "s4", accessToken: "t4" },
|
||||
};
|
||||
expect(getCorpEnv(legacyNoEnv as CorpConfig)).toBe("prod");
|
||||
});
|
||||
|
||||
it("isCorpTest and isCorpProd maintain consistent boundaries", () => {
|
||||
const testCorp: CorpConfig = {
|
||||
id: "t1",
|
||||
name: "测试企业",
|
||||
env: "test",
|
||||
isTest: true,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "t1", staffId: "s1", accessToken: "token" },
|
||||
};
|
||||
expect(isCorpTest(testCorp)).toBe(true);
|
||||
expect(isCorpProd(testCorp)).toBe(false);
|
||||
|
||||
const demoCorp: CorpConfig = {
|
||||
id: "d1",
|
||||
name: "演示企业",
|
||||
env: "demo",
|
||||
isTest: true,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "d1", staffId: "s1", accessToken: "token" },
|
||||
};
|
||||
expect(isCorpTest(demoCorp)).toBe(true);
|
||||
expect(isCorpProd(demoCorp)).toBe(false);
|
||||
|
||||
const prodCorp: CorpConfig = {
|
||||
id: "p1",
|
||||
name: "新转转集团",
|
||||
env: "prod",
|
||||
isTest: false,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "p1", staffId: "s1", accessToken: "token" },
|
||||
};
|
||||
expect(isCorpTest(prodCorp)).toBe(false);
|
||||
expect(isCorpProd(prodCorp)).toBe(true);
|
||||
});
|
||||
|
||||
it("normalizeCorpConfig injects env and isTest into legacy configs seamlessly", () => {
|
||||
const legacyRaw = {
|
||||
id: "ID01PH4Q5CJboX",
|
||||
name: "新转转集团",
|
||||
credentials: {
|
||||
accessToken: "token_123",
|
||||
corpId: "ID01PH4Q5CJboX",
|
||||
staffId: "s_123",
|
||||
},
|
||||
};
|
||||
|
||||
const parsed = CorpConfigSchema.parse(legacyRaw);
|
||||
const normalized = normalizeCorpConfig(parsed);
|
||||
|
||||
expect(normalized.env).toBe("prod");
|
||||
expect(normalized.isTest).toBe(false);
|
||||
expect(isCorpProd(normalized)).toBe(true);
|
||||
|
||||
const legacyTestRaw = {
|
||||
id: "ID01uzxB4x07fh",
|
||||
name: "HAB对公测试环境",
|
||||
credentials: {
|
||||
accessToken: "token_test",
|
||||
corpId: "ID01uzxB4x07fh",
|
||||
staffId: "s_test",
|
||||
},
|
||||
};
|
||||
const normalizedTest = normalizeCorpConfig(CorpConfigSchema.parse(legacyTestRaw));
|
||||
expect(normalizedTest.env).toBe("test");
|
||||
expect(normalizedTest.isTest).toBe(true);
|
||||
expect(isCorpTest(normalizedTest)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,12 @@
|
||||
import {
|
||||
CorpConfig,
|
||||
CorpEnv,
|
||||
getCorpEnv,
|
||||
getCorpExpiresAt,
|
||||
getCorpPhysicalId,
|
||||
getCorpStaffId,
|
||||
getCorpStaffName,
|
||||
isCorpTest,
|
||||
} from "./types.js";
|
||||
import { NotFoundError, NotLoggedInError, ValidationError } from "../errors.js";
|
||||
import { saveGlobalConfig } from "./loader.js";
|
||||
@@ -21,6 +24,8 @@ export interface CorpSummary {
|
||||
expiresAt?: number;
|
||||
persistent?: boolean;
|
||||
hasOpenApi?: boolean;
|
||||
env: CorpEnv;
|
||||
isTest: boolean;
|
||||
}
|
||||
|
||||
export function resolveCorpConfig(
|
||||
@@ -161,6 +166,8 @@ export class CorpContext {
|
||||
(corp.credentials?.appSecurity || corp.auth?.appSecurity)
|
||||
);
|
||||
const hasAccountBinding = corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
const env = getCorpEnv(corp);
|
||||
const test = isCorpTest(corp);
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
@@ -174,6 +181,8 @@ export class CorpContext {
|
||||
expiresAt: getCorpExpiresAt(corp),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
hasOpenApi: hasOpenApiKeys,
|
||||
env,
|
||||
isTest: test,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ export const CredentialSourceSchema = z.enum([
|
||||
]);
|
||||
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
|
||||
|
||||
export const CorpEnvSchema = z.enum(["prod", "test", "demo"]);
|
||||
export type CorpEnv = z.infer<typeof CorpEnvSchema>;
|
||||
|
||||
export const CorpCredentialsSchema = z.object({
|
||||
accessToken: z.string().default("").describe("主站访问令牌"),
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
@@ -50,6 +53,8 @@ export const CorpConfigSchema = z.object({
|
||||
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
|
||||
name: z.string().describe("企业名称"),
|
||||
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
|
||||
env: CorpEnvSchema.optional().describe("企业环境属性: prod(正式生产) / test(测试环境) / demo(演示/POC)"),
|
||||
isTest: z.boolean().optional().describe("是否为测试或演示企业(非正式生产)"),
|
||||
userId: z.string().optional().describe("所属用户 ID"),
|
||||
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
|
||||
staffName: z.string().optional().describe("员工真实姓名"),
|
||||
@@ -66,6 +71,48 @@ export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
|
||||
/**
|
||||
* 根据企业名称或标识智能推导企业环境属性(未命中一律保守归为正式生产 prod)
|
||||
*/
|
||||
export function inferCorpEnvFromName(name?: string, id?: string): CorpEnv {
|
||||
const text = `${name || ""} ${id || ""}`.toLowerCase();
|
||||
if (text.includes("测试") || text.includes("test")) {
|
||||
return "test";
|
||||
}
|
||||
if (text.includes("演示") || text.includes("poc") || text.includes("demo")) {
|
||||
return "demo";
|
||||
}
|
||||
return "prod";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业环境属性 (prod / test / demo)
|
||||
*/
|
||||
export function getCorpEnv(corp: CorpConfig): CorpEnv {
|
||||
if (corp.env && ["prod", "test", "demo"].includes(corp.env)) {
|
||||
return corp.env;
|
||||
}
|
||||
if (corp.isTest !== undefined) {
|
||||
return corp.isTest ? "test" : "prod";
|
||||
}
|
||||
return inferCorpEnvFromName(corp.name, corp.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断企业是否为非正式环境(测试环境或演示环境)
|
||||
*/
|
||||
export function isCorpTest(corp: CorpConfig): boolean {
|
||||
const env = getCorpEnv(corp);
|
||||
return env === "test" || env === "demo" || corp.isTest === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断企业是否为正式生产环境 (prod)
|
||||
*/
|
||||
export function isCorpProd(corp: CorpConfig): boolean {
|
||||
return !isCorpTest(corp);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业真实物理 corpId(统一收敛 corp.corpId / corp.credentials.corpId / corp.id)
|
||||
*/
|
||||
@@ -104,9 +151,13 @@ export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
|
||||
const expiresAt = getCorpExpiresAt(corp);
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
const env = getCorpEnv(corp);
|
||||
const isTest = env !== "prod";
|
||||
|
||||
return {
|
||||
...corp,
|
||||
env,
|
||||
isTest,
|
||||
corpId: physicalCorpId,
|
||||
...(staffId ? { staffId } : {}),
|
||||
...(staffName ? { staffName } : {}),
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
| `platform/` | `api / tools / services / analysis / workflow-state / workflow-alert-store / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
|
||||
| `platform/` | `api / tools / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
|
||||
| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) |
|
||||
|
||||
@@ -45,7 +45,7 @@ src/domains/bill/
|
||||
- 跨 `backlogs/search`、`flows/my`、`flows/approved`、`carbonCopy/search` 与 `backlogs/id` 多通道穿透检索单据流程实例;
|
||||
- 智能提取单据金额、提报人、提报时间、归属部门、当前驻留节点与待办审批人列表;
|
||||
- 内置待办根因诊断引擎,智能判定流转阶段(`DRAFT`、`APPROVING`、`PAYING`、`PAID`、`REJECTED`):
|
||||
- 识别“待出纳支付/打款”节点(如 `PAYING` 或节点名包含“打款/出纳/支付”),精准提示不可审批及自动化工作流调用报错 400(无待办审批事项)的根本原因与排障建议;
|
||||
- 按实际流程状态(如 `PAYING`)和节点类型判断支付阶段,显示名称不参与阶段判定;流程状态优先于 backlog 状态。缺少当前身份的实际待办证据时,`diagnostic.canApprove` 为 `null`,CLI 显示“未知”,节点配置中的审批人不构成权限保证;
|
||||
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
|
||||
|
||||
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
@@ -772,7 +772,7 @@ describe("Bill Domain", () => {
|
||||
expect(report.pendingApprovers).toHaveLength(1);
|
||||
expect(report.pendingApprovers[0].name).toBe("李主管");
|
||||
expect(report.diagnostic.stage).toBe("APPROVING");
|
||||
expect(report.diagnostic.canApprove).toBe(true);
|
||||
expect(report.diagnostic.canApprove).toBeNull();
|
||||
expect(report.diagnostic.summary).toContain("待办审批人: 李主管");
|
||||
expect(report.timeline).toHaveLength(1);
|
||||
expect(report.timeline[0].action).toBe("SUBMIT");
|
||||
@@ -824,6 +824,17 @@ describe("Bill Domain", () => {
|
||||
expect(report.timeline[0].automatic).toBe(true);
|
||||
});
|
||||
|
||||
for (const nodeName of ["出纳审批", "支付复核", "普通审批"]) {
|
||||
it(`uses actual state instead of the display name: ${nodeName}`, async () => {
|
||||
const raw = { id: "backlog", state: "APPROVING", nodeName, flowId: { id: "flow", state: "APPROVING", form: {}, plan: { nextNodeId: "node", nodes: [{ id: "node", name: nodeName, type: "APPROVAL", approverId: "staff" }] } } };
|
||||
const client = { post: async () => new Response(JSON.stringify({ value: raw })) } as any;
|
||||
const result = await traceBillFlowDetail(client, "corp", "ID01-record");
|
||||
expect(result.diagnostic.stage).toBe("APPROVING");
|
||||
expect(result.diagnostic.canApprove).toBeNull();
|
||||
expect(result.diagnostic.advice).toContain("实际待办");
|
||||
});
|
||||
}
|
||||
|
||||
it("单据不存在时返回友好未找到诊断报告", async () => {
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ items: [] })),
|
||||
|
||||
+10
-10
@@ -964,14 +964,14 @@ export async function getBillFlow(
|
||||
|
||||
function resolveFlowStage(
|
||||
rawState: string,
|
||||
nodeName?: string
|
||||
nodeType?: string
|
||||
): "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN" {
|
||||
const s = rawState.toUpperCase();
|
||||
const n = (nodeName || "").toLowerCase();
|
||||
const n = (nodeType || "").toUpperCase();
|
||||
|
||||
if (s.includes("REJECT") || s === "TERMINATED") return "REJECTED";
|
||||
if (s === "PAID" || s === "COMPLETED" || s === "PROCESSED") return "PAID";
|
||||
if (s.includes("PAY") || n.includes("打款") || n.includes("出纳") || n.includes("支付")) return "PAYING";
|
||||
if (s.includes("PAY") || ["PAYMENT", "PAY", "CASHIER"].includes(n)) return "PAYING";
|
||||
if (s.includes("APPROV") || s === "PENDING" || s === "SENDING") return "APPROVING";
|
||||
if (s.includes("DRAFT")) return "DRAFT";
|
||||
return "UNKNOWN";
|
||||
@@ -983,7 +983,7 @@ function buildDiagnosticReport(
|
||||
currentNodeName?: string,
|
||||
pendingApprovers: { id?: string; name?: string; code?: string }[] = []
|
||||
): {
|
||||
canApprove: boolean;
|
||||
canApprove: boolean | null;
|
||||
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
|
||||
stageLabel: string;
|
||||
summary: string;
|
||||
@@ -998,15 +998,15 @@ function buildDiagnosticReport(
|
||||
stage,
|
||||
stageLabel: "待支付 / 出纳打款",
|
||||
summary: `单据已通过全部分级审批流转,当前停留在【${currentNodeName || "出纳打款"}】环节`,
|
||||
advice: "该单据当前无待办审批任务,若调用自动审批接口必报 400(无待办审批事项)。出纳打款后单据即闭环;若属于自动化打款流水,请检查工作流触发器是否误推了待支付单据,建议增加条件【审批状态 等于 APPROVING】进行拦截。",
|
||||
advice: "流程处于支付环节。请先核对实际待办与操作权限;无待办时调用审批接口可能返回 400。若工作流误触发支付阶段单据,请核对触发条件与流程状态。",
|
||||
};
|
||||
case "APPROVING":
|
||||
return {
|
||||
canApprove: true,
|
||||
canApprove: null,
|
||||
stage,
|
||||
stageLabel: "审批中 (待办审批)",
|
||||
summary: `单据当前停留在【${currentNodeName || "审批"}】节点${approverNames ? `,待办审批人: ${approverNames}` : ""}`,
|
||||
advice: "单据处于正常待办审批状态,当前待办人员或工作流自动化可正常执行同意 (agree) 或驳回 (reject) 操作。",
|
||||
advice: "单据处于审批阶段;所列人员来自当前节点配置。执行同意或驳回前,仍需核对当前身份的实际待办与审批权限。",
|
||||
};
|
||||
case "REJECTED":
|
||||
return {
|
||||
@@ -1034,7 +1034,7 @@ function buildDiagnosticReport(
|
||||
};
|
||||
default:
|
||||
return {
|
||||
canApprove: false,
|
||||
canApprove: null,
|
||||
stage,
|
||||
stageLabel: rawState || "未知状态",
|
||||
summary: `单据当前处于状态: ${rawState || "未知"}`,
|
||||
@@ -1125,7 +1125,7 @@ export async function traceBillFlowDetail(
|
||||
const submitDate = typeof form.submitDate === "number" ? new Date(form.submitDate).toLocaleString("zh-CN", { hour12: false }) : undefined;
|
||||
|
||||
// 状态提取
|
||||
const rawState = String(rawFlow.state || flow.state || form.state || "").toUpperCase();
|
||||
const rawState = String(flow.state || rawFlow.state || form.state || "").toUpperCase();
|
||||
const stateLabel = translateBillFlowState(rawState);
|
||||
|
||||
// 当前驻留节点提取
|
||||
@@ -1163,7 +1163,7 @@ export async function traceBillFlowDetail(
|
||||
}
|
||||
|
||||
// 诊断规则引擎
|
||||
const stage = resolveFlowStage(rawState, currentNode?.name);
|
||||
const stage = resolveFlowStage(rawState, currentNode?.type);
|
||||
const diagnostic = buildDiagnosticReport(stage, rawState, currentNode?.name, pendingApprovers);
|
||||
|
||||
// 流转时间线
|
||||
|
||||
@@ -329,7 +329,8 @@ export interface BillFlowTraceDiagnostic {
|
||||
currentNode?: { id?: string; name?: string; type?: string };
|
||||
pendingApprovers: { id?: string; name?: string; code?: string }[];
|
||||
diagnostic: {
|
||||
canApprove: boolean;
|
||||
/** null means the current identity's actual approval task was not verified. */
|
||||
canApprove: boolean | null;
|
||||
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
|
||||
stageLabel: string;
|
||||
summary: string;
|
||||
|
||||
@@ -45,10 +45,14 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
||||
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
||||
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
||||
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
||||
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
- `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。
|
||||
- `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
calculateEntityRecordStats,
|
||||
compileRecordPredicate,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
iterateAllEntityRecords,
|
||||
@@ -26,6 +27,37 @@ import {
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
describe("record predicate and normalized projection regressions", () => {
|
||||
const entity = { id: "ent", name: "台账", fields: [
|
||||
{ name: "E_ent_seq", label: "序号", type: "number" },
|
||||
{ name: "E_ent_rent", label: "租金", type: "number" },
|
||||
{ name: "E_ent_note", label: "备注", type: "text" },
|
||||
{ name: "E_ent_name", label: "名称", type: "text" },
|
||||
] } as any;
|
||||
const records = [
|
||||
{ dataLink: { id: "r1", E_ent_seq: 1, E_ent_rent: 100, E_ent_note: "A,B && C", E_ent_name: "Name" } },
|
||||
{ dataLink: { id: "r2", E_ent_seq: 2, E_ent_rent: 200, E_ent_note: null } },
|
||||
];
|
||||
|
||||
for (const clause of ["序号 in [1]", "序号 == 1 &&", "不存在 != 1", "序号 === 1", "序号 in ()", "序号 > 1 || 序号 < 3", "备注 == 'broken", "序号 == 1&&garbage"]) {
|
||||
test(`rejects invalid predicate even with no records: ${clause}`, () => {
|
||||
expect(() => filterRecordsByPredicate([], clause, entity)).toThrow();
|
||||
});
|
||||
}
|
||||
test("validates unknown and ambiguous fields before evaluating records", () => {
|
||||
expect(() => compileRecordPredicate("租 == 1", { ...entity, fields: [...entity.fields, { name: "other", label: "租期", type: "number" }] })).toThrow("歧义");
|
||||
});
|
||||
test("honors quotes, commas and conjunctions inside values", () => {
|
||||
expect(filterRecordsByPredicate(records, "备注 in ('A,B && C','other')&&序号>=1", entity)).toEqual([records[0]]);
|
||||
expect(filterRecordsByPredicate(records, "备注 == null", entity)).toEqual([records[1]]);
|
||||
expect(filterRecordsByPredicate(records, "序号 in (1,2) && 租金 < 150", entity)).toEqual([records[0]]);
|
||||
});
|
||||
test("selects normalized business fields and system name by label or original field name", () => {
|
||||
const normalized = normalizeDatalinkRecord(records[0], entity);
|
||||
expect(selectRecordFields(normalized as any, ["租金", "E_ent_seq", "名称", "id"], entity.fields)).toEqual({ 租金: 100, 序号: 1, 名称: "Name", id: "r1" });
|
||||
});
|
||||
});
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
name: "业务应用",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import type {
|
||||
DatalinkEntity,
|
||||
DatalinkField,
|
||||
@@ -118,12 +119,22 @@ export function selectRecordFields(
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields)
|
||||
? record.fields as Record<string, unknown>
|
||||
: undefined;
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find(
|
||||
(field) => field.name === selector || field.label === selector
|
||||
);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
const label = definition?.label || selector;
|
||||
if (sourceName in dataLink) selected[label] = dataLink[sourceName];
|
||||
else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label];
|
||||
else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName];
|
||||
else if (normalizedFields) {
|
||||
const systemName = sourceName.replace(/^E_.+_/, "");
|
||||
if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName];
|
||||
}
|
||||
}
|
||||
return record.dataLink && typeof record.dataLink === "object"
|
||||
? { ...record, dataLink: selected }
|
||||
@@ -1152,76 +1163,103 @@ export function auditLedgerContinuityAndBaseline(
|
||||
/**
|
||||
* 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合)
|
||||
*/
|
||||
function splitPredicateParts(source: string, separator: string): string[] {
|
||||
const parts: string[] = [];
|
||||
let quote = "", depth = 0, start = 0;
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const char = source[i];
|
||||
if (quote) {
|
||||
if (char === "\\") i++;
|
||||
else if (char === quote) quote = "";
|
||||
continue;
|
||||
}
|
||||
if (char === "'" || char === '"') quote = char;
|
||||
else if (char === "(") depth++;
|
||||
else if (char === ")") {
|
||||
if (--depth < 0) throw new ValidationError("筛选条件括号不匹配");
|
||||
} else if (depth === 0 && source.startsWith(separator, i)) {
|
||||
parts.push(source.slice(start, i).trim());
|
||||
start = i + separator.length;
|
||||
i += separator.length - 1;
|
||||
}
|
||||
}
|
||||
if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配");
|
||||
parts.push(source.slice(start).trim());
|
||||
if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空");
|
||||
return parts;
|
||||
}
|
||||
|
||||
function predicateLiteral(raw: string): string | number | boolean | null {
|
||||
if (/^(["']).*\1$/s.test(raw)) {
|
||||
const value = raw.slice(1, -1);
|
||||
if (raw[0] === '"') {
|
||||
try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); }
|
||||
}
|
||||
if (/(?<!\\)'/.test(value)) throw new ValidationError(`筛选值引号不匹配: ${raw}`);
|
||||
return value.replace(/\\(['\\])/g, "$1");
|
||||
}
|
||||
if (raw === "null") return null;
|
||||
if (raw === "true" || raw === "false") return raw === "true";
|
||||
if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(raw) && Number.isFinite(Number(raw))) return Number(raw);
|
||||
if (/^[\p{L}\p{N}_:.$/-]+$/u.test(raw)) return raw;
|
||||
throw new ValidationError(`不支持的筛选值: ${raw};文本中的空格或符号请使用引号`);
|
||||
}
|
||||
|
||||
function predicateField(entity: DatalinkEntity, query: string): DatalinkField | string {
|
||||
const key = query.trim().toLowerCase();
|
||||
const candidates = entity.fields.filter(f =>
|
||||
f.name.toLowerCase() === key || f.label?.toLowerCase() === key ||
|
||||
f.name.toLowerCase() === `e_${entity.id.replace(/^\$/, "").toLowerCase()}_${key}`
|
||||
);
|
||||
if (!candidates.length && ["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
|
||||
const matches = candidates.length ? candidates : entity.fields.filter(f => f.label?.toLowerCase().includes(key));
|
||||
if (matches.length > 1) throw new ValidationError(`筛选字段存在歧义: ${query},请使用完整字段名`);
|
||||
if (matches.length === 1) return matches[0];
|
||||
if (["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
|
||||
throw new ValidationError(`未知筛选字段: ${query}`);
|
||||
}
|
||||
|
||||
/** 先完整校验语法和字段,再生成可复用的筛选器,空结果集也不能掩盖错误。 */
|
||||
export function compileRecordPredicate(whereClause: string, entity: DatalinkEntity): (record: DatalinkRecord) => boolean {
|
||||
const conditions = splitPredicateParts(whereClause, "&&").map(cond => {
|
||||
// 1. in 操作符: field in (v1, v2, v3)
|
||||
const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i);
|
||||
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
|
||||
const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s);
|
||||
if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`);
|
||||
const field = predicateField(entity, (inMatch ?? compMatch)![1].trim());
|
||||
const op = inMatch ? "in" : compMatch![2];
|
||||
const targets = inMatch
|
||||
? splitPredicateParts(inMatch[2], ",").map(predicateLiteral)
|
||||
: [predicateLiteral(compMatch![3].trim())];
|
||||
return (record: DatalinkRecord) => {
|
||||
const actual = extractRecordFieldValue(record, field);
|
||||
const equal = (target: string | number | boolean | null): boolean => {
|
||||
if (target === null) return actual === null || actual === undefined;
|
||||
if (typeof target === "number") return extractNumericFieldValue(record, field) === target;
|
||||
return actual !== null && actual !== undefined && String(actual) === String(target);
|
||||
};
|
||||
if (op === "in") return targets.some(equal);
|
||||
// 字符串/布尔比较
|
||||
if (op === "=" || op === "==") return equal(targets[0]);
|
||||
if (op === "!=") return !equal(targets[0]);
|
||||
// 数值比较
|
||||
const value = extractNumericFieldValue(record, field);
|
||||
const target = targets[0];
|
||||
if (value === null || typeof target !== "number") return false;
|
||||
return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target;
|
||||
};
|
||||
});
|
||||
return record => conditions.every(condition => condition(record));
|
||||
}
|
||||
|
||||
export function filterRecordsByPredicate(
|
||||
records: DatalinkRecord[],
|
||||
whereClause: string,
|
||||
entity: DatalinkEntity
|
||||
): DatalinkRecord[] {
|
||||
if (!whereClause || !whereClause.trim()) return records;
|
||||
|
||||
const conditions = whereClause
|
||||
.split(/\s+&&\s+/)
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
return records.filter((r) => {
|
||||
return conditions.every((cond) => {
|
||||
// 1. in 操作符: field in (v1, v2, v3)
|
||||
const inMatch = cond.match(/^(.+?)\s+in\s*\((.+?)\)$/i);
|
||||
if (inMatch) {
|
||||
const fieldKey = inMatch[1].trim();
|
||||
const rawValues = inMatch[2]
|
||||
.split(",")
|
||||
.map((v) => v.trim().replace(/^['"]|['"]$/g, ""));
|
||||
const actualVal = String(extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey) ?? "");
|
||||
return rawValues.some((v) => v === actualVal);
|
||||
}
|
||||
|
||||
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
|
||||
const compMatch = cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/);
|
||||
if (compMatch) {
|
||||
const fieldKey = compMatch[1].trim();
|
||||
const op = compMatch[2];
|
||||
const rawTarget = compMatch[3].trim().replace(/^['"]|['"]$/g, "");
|
||||
const actualRaw = extractRecordFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
|
||||
|
||||
// 数值比较
|
||||
const actualNum = extractNumericFieldValue(r, resolveEntityField(entity, fieldKey) ?? fieldKey);
|
||||
const targetNum = Number(rawTarget);
|
||||
if (actualNum !== null && !Number.isNaN(targetNum)) {
|
||||
switch (op) {
|
||||
case "==":
|
||||
case "=":
|
||||
return actualNum === targetNum;
|
||||
case "!=":
|
||||
return actualNum !== targetNum;
|
||||
case ">":
|
||||
return actualNum > targetNum;
|
||||
case ">=":
|
||||
return actualNum >= targetNum;
|
||||
case "<":
|
||||
return actualNum < targetNum;
|
||||
case "<=":
|
||||
return actualNum <= targetNum;
|
||||
}
|
||||
}
|
||||
|
||||
// 字符串/布尔比较
|
||||
const actualStr = String(actualRaw ?? "");
|
||||
switch (op) {
|
||||
case "==":
|
||||
case "=":
|
||||
return actualStr === rawTarget;
|
||||
case "!=":
|
||||
return actualStr !== rawTarget;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
});
|
||||
return records.filter(compileRecordPredicate(whereClause, entity));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,23 +6,31 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志、枚举类型)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验、Piper Job 端点与 EKB_ENUM 字典拉取)
|
||||
├── services.ts # 门面聚合与对外服务导出(含 resolveWorkflowEnumOptions 混合架构)
|
||||
├── workflow/ # 工作流体系子域(高内聚分层架构)
|
||||
│ ├── index.ts # 工作流能力统合导出
|
||||
│ ├── enums.ts # 单据审批事件触发器标准系统枚举(18 项内置字典与翻译器)
|
||||
│ ├── watch/ # 实时任务监听、TaskExecutionTracker 状态机与日志流 (tracker, engine, formatter)
|
||||
│ ├── nodes/ # 声明式节点树编排、树形索引定位、插入追加与重排 (tree, locator, mutations)
|
||||
│ ├── script/ # 脚本 AST 语法校验、上游依赖扫描与隔离沙箱仿真引擎 (lint, scanner, sandbox)
|
||||
│ ├── branch/ # 条件分支与规则解释诊断引擎 (explain, types)
|
||||
│ ├── analysis/ # 工作流静态吞错、审批状态死锁过滤与联动覆盖巡检 (analyzer, types)
|
||||
│ ├── state/ # 草稿版本状态机与发布乐观锁保护
|
||||
│ └── alert/ # 错误指纹告警与 SQLite 本地持久化
|
||||
└── tools.ts # MCP tool 注册
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
## 工作流使用与诊断
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
```
|
||||
CLI 命令、触发器分类、生产调试风险、节点与脚本校验、实时监听以及诊断结果契约,统一见 [Workflow 说明](./workflow/README.workflow.md)。
|
||||
|
||||
## 模块边界
|
||||
|
||||
- `workflow/{analysis,branch,nodes,script,state,watch,alert}/index.ts` 是各能力的目录出口;内部引用直接指向所属目录,不再保留根目录的一行转发文件。
|
||||
- 单元测试与对应实现放在同一目录;分层测试检查已移除路径,保留正常的模块出口文件。
|
||||
- MVEL 校验先识别字符串、转义及行/块注释,再检查有效代码中的括号、return 和节点引用;这属于轻量静态检查,不是完整的 MVEL 编译器。JavaScript 校验仍检查函数体语法,不执行脚本。
|
||||
|
||||
## 详细文档
|
||||
|
||||
|
||||
@@ -19,6 +19,11 @@ import {
|
||||
StaffSchema,
|
||||
WebhookInfoSchema,
|
||||
WorkflowSampleDataSchema,
|
||||
WorkflowSampleDataResultSchema,
|
||||
type WorkflowSampleDataResult,
|
||||
WorkflowDebugSourceResultSchema,
|
||||
WorkflowEnumItemSchema,
|
||||
type WorkflowEnumItem,
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
@@ -129,6 +134,36 @@ export async function updateWorkflow(
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
export async function copyWorkflow(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
workflow: import("./types.js").WorkflowDetail
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
const response = await client.put(`api/easo/pipelines/${pipelineId}/copy`, {
|
||||
json: workflow,
|
||||
});
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
export async function createWorkflow(
|
||||
client: KyInstance,
|
||||
workflow: Record<string, any>
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
const response = await client.post("api/easo/pipelines", {
|
||||
json: workflow,
|
||||
});
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
|
||||
export async function deleteWorkflow(
|
||||
client: KyInstance,
|
||||
pipelineId: string
|
||||
): Promise<boolean> {
|
||||
const response = await client.delete(`api/easo/pipelines/${pipelineId}`);
|
||||
await response.text().catch(() => "");
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function listWorkflowSnapshots(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
@@ -325,3 +360,73 @@ export async function sampleWorkflowData(
|
||||
return WorkflowSampleDataSchema.parse(await response.json());
|
||||
}
|
||||
|
||||
// ── 调试数据源与发起调试(Piper)─────────────────────────────────────────────
|
||||
|
||||
export async function getWorkflowDebugSource(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: { page?: number; pageSize?: number; keywords?: string } = {}
|
||||
): Promise<import("./types.js").WorkflowDebugSourceResult> {
|
||||
const response = await client.post(`api/easo/pipelines/${pipelineId}/debugSource`, {
|
||||
json: {
|
||||
number: options.page ?? 1,
|
||||
pageSize: options.pageSize ?? 20,
|
||||
...(options.keywords ? { keywords: options.keywords } : {}),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowDebugSourceResultSchema);
|
||||
}
|
||||
|
||||
export async function triggerWorkflowDebug(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
options: { entityId?: string; data?: Record<string, any>; autoPublish?: boolean; dataLimit?: number } = {}
|
||||
): Promise<string> {
|
||||
const response = await client.post("api/easo/jobs", {
|
||||
json: {
|
||||
pipelineId,
|
||||
inputs: {
|
||||
id: options.entityId ?? "",
|
||||
...(options.data !== undefined ? { data: options.data } : {}),
|
||||
$autoPublish: options.autoPublish ?? false,
|
||||
},
|
||||
dataLimit: options.dataLimit ?? 20,
|
||||
},
|
||||
});
|
||||
const data = await unwrap(response, z.union([z.string(), z.number(), z.record(z.string(), z.any())]));
|
||||
if (typeof data === "string") return data;
|
||||
if (typeof data === "number") return String(data);
|
||||
if (data && typeof data === "object" && "id" in data) return String(data.id);
|
||||
if (data && typeof data === "object" && "jobId" in data) return String(data.jobId);
|
||||
return String(data);
|
||||
}
|
||||
|
||||
export async function getWorkflowSampleData(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
type = "webhook"
|
||||
): Promise<WorkflowSampleDataResult> {
|
||||
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`, {
|
||||
json: { type },
|
||||
});
|
||||
return unwrap(response, WorkflowSampleDataResultSchema);
|
||||
}
|
||||
|
||||
// ── 工作流/Piper 条件与触发器枚举字典 ──────────────────────────────────────────
|
||||
|
||||
export async function getWorkflowEnumOptions(
|
||||
client: KyInstance,
|
||||
thirdId: string,
|
||||
platformId?: string
|
||||
): Promise<WorkflowEnumItem[]> {
|
||||
const jsonBody = platformId ? { $platformId: platformId } : {};
|
||||
const response = await client.post(
|
||||
`api/easo/dsl/condition/select/EKB_ENUM?thirdId=${encodeURIComponent(thirdId)}`,
|
||||
{
|
||||
json: jsonBody,
|
||||
}
|
||||
);
|
||||
return unwrap(response, z.array(WorkflowEnumItemSchema));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { WorkflowTaskExecution } from "./types.js";
|
||||
|
||||
export interface ExecutionContext {
|
||||
node: WorkflowTaskExecution;
|
||||
key: string;
|
||||
scope: string[];
|
||||
loopPath: string;
|
||||
}
|
||||
|
||||
/** Index real executions by parent task path, loop context and repeated occurrence. */
|
||||
export function indexExecutionContexts(tree: WorkflowTaskExecution[]): ExecutionContext[] {
|
||||
const result: ExecutionContext[] = [];
|
||||
const entries = new Map<string, { node: WorkflowTaskExecution; parentId?: string }>();
|
||||
const occurrences = new Map<string, number>();
|
||||
function collect(node: WorkflowTaskExecution, parentId?: string) {
|
||||
if (!node || !node.id || entries.has(node.id)) return;
|
||||
entries.set(node.id, { node, parentId: String(node.parentId || parentId || "") || undefined });
|
||||
for (const key of ["children", "subTasks", "items", "tasks"]) {
|
||||
const children = node[key];
|
||||
if (Array.isArray(children)) for (const child of children) collect(child, node.id);
|
||||
}
|
||||
}
|
||||
for (const node of tree) collect(node);
|
||||
const scopes = new Map<string, { parts: string[]; loopPath: string }>();
|
||||
function scopeOf(id: string, visited = new Set<string>()): { parts: string[]; loopPath: string } {
|
||||
const cached = scopes.get(id);
|
||||
if (cached) return cached;
|
||||
const entry = entries.get(id);
|
||||
if (!entry || visited.has(id)) return { parts: [JSON.stringify(["unresolved-parent", id])], loopPath: "" };
|
||||
visited.add(id);
|
||||
const parent = entry.parentId ? scopeOf(entry.parentId, visited) : { parts: [], loopPath: "" };
|
||||
const loopPath = String(entry.node.currentLoopPath ?? parent.loopPath);
|
||||
const scope = { parts: [...parent.parts, JSON.stringify([entry.node.name || entry.node.type || "unnamed", loopPath])], loopPath };
|
||||
scopes.set(id, scope);
|
||||
return scope;
|
||||
}
|
||||
for (const { node } of entries.values()) {
|
||||
const { parts, loopPath } = scopeOf(node.id);
|
||||
const base = JSON.stringify(parts);
|
||||
const occurrence = occurrences.get(base) ?? 0;
|
||||
occurrences.set(base, occurrence + 1);
|
||||
result.push({ node, key: `${base}#${occurrence}`, scope: parts.slice(0, -1), loopPath });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { diffWorkflowJobs } from "./services.js";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "./types.js";
|
||||
|
||||
const job = { id: "job", status: "COMPLETED" } as WorkflowJobDetail;
|
||||
const node = (id: string, loop: string, status = "COMPLETED", value = 1): WorkflowTaskExecution => ({ id, name: "edit", type: "code", status, currentLoopPath: loop, inputs: { value } });
|
||||
|
||||
describe("workflow diff execution identities", () => {
|
||||
it("compares every loop instance rather than only the first task name", () => {
|
||||
const result = diffWorkflowJobs(job, [node("a0", "0"), node("a1", "1", "FAILED", 2)], job, [node("b0", "0"), node("b1", "1", "COMPLETED", 3)]);
|
||||
expect(result.nodes).toHaveLength(2);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
expect(result.summary.statusDiffCount).toBe(1);
|
||||
expect(result.nodes.find(n => n.diverged)?.currentLoopPath).toBe("1");
|
||||
});
|
||||
it("preserves repeated attempts and identifies missing instances", () => {
|
||||
const result = diffWorkflowJobs(job, [node("a0", "0"), node("a1", "0", "FAILED")], job, [node("b0", "0")]);
|
||||
expect(result.nodes).toHaveLength(2);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
});
|
||||
it("uses the parent task path when repeated names occur in different branches", () => {
|
||||
const tree = (prefix: string, value: number): WorkflowTaskExecution[] => [
|
||||
{ id: prefix + "left", name: "left", type: "condition", status: "COMPLETED", children: [node(prefix + "a", "0")] },
|
||||
{ id: prefix + "right", name: "right", type: "condition", status: "COMPLETED", children: [node(prefix + "b", "0", "COMPLETED", value)] },
|
||||
];
|
||||
const result = diffWorkflowJobs(job, tree("a", 1), job, tree("b", 2));
|
||||
expect(result.nodes).toHaveLength(4);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
});
|
||||
it("counts output-only changes, including the singular output wire format", () => {
|
||||
const result = diffWorkflowJobs(job, [{ ...node("a", "0"), output: { value: 1 } }], job, [{ ...node("b", "0"), output: { value: 2 } }]);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
expect(result.nodes[0]?.outputsDiff).toEqual([{ field: "value", from: 1, to: 2 }]);
|
||||
});
|
||||
it("resolves flat parentId relationships even when siblings change order", () => {
|
||||
const tree = (prefix: string, reversed: boolean): WorkflowTaskExecution[] => {
|
||||
const children = [
|
||||
{ ...node(prefix + "childA", "0", "COMPLETED", 1), parentId: prefix + "left" },
|
||||
{ ...node(prefix + "childB", "0", "COMPLETED", 2), parentId: prefix + "right" },
|
||||
];
|
||||
return [...(reversed ? children.reverse() : children), { id: prefix + "left", name: "left", type: "condition", status: "COMPLETED" }, { id: prefix + "right", name: "right", type: "condition", status: "COMPLETED" }];
|
||||
};
|
||||
const result = diffWorkflowJobs(job, tree("a", false), job, tree("b", true));
|
||||
expect(result.summary.divergedNodesCount).toBe(0);
|
||||
expect(result.nodes).toHaveLength(4);
|
||||
});
|
||||
it("does not discard scalar output changes", () => {
|
||||
const result = diffWorkflowJobs(job, [{ ...node("a", "0"), output: 1 }], job, [{ ...node("b", "0"), output: 2 }]);
|
||||
expect(result.summary.divergedNodesCount).toBe(1);
|
||||
expect(result.nodes[0]?.outputsDiff).toEqual([{ field: "$value", from: 1, to: 2 }]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import * as api from "./api.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import { explainConditionBranches } from "./workflow/branch/index.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
import {
|
||||
Platform,
|
||||
WorkflowSummary,
|
||||
@@ -47,6 +50,151 @@ export function updateWorkflow(...args: Parameters<typeof api.updateWorkflow>) {
|
||||
return api.updateWorkflow(...args);
|
||||
}
|
||||
|
||||
export async function copyWorkflow(
|
||||
client: import("ky").KyInstance,
|
||||
pipelineId: string,
|
||||
options: { label?: string; platformId?: string } = {}
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail;
|
||||
if (options.label) {
|
||||
cloned.label = options.label;
|
||||
} else if (!cloned.label.includes("副本")) {
|
||||
cloned.label = `${cloned.label} 副本`;
|
||||
}
|
||||
if (options.platformId) {
|
||||
cloned.platformId = options.platformId;
|
||||
}
|
||||
// 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本
|
||||
if (cloned.tasks?.[0]?.type === "webhook") {
|
||||
(cloned.tasks[0] as any).urlPath = crypto.randomUUID();
|
||||
delete (cloned.tasks[0] as any).sampleId;
|
||||
}
|
||||
return api.copyWorkflow(client, pipelineId, cloned);
|
||||
}
|
||||
|
||||
export interface CreateWorkflowOptions {
|
||||
label?: string;
|
||||
platformId?: string;
|
||||
trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string;
|
||||
file?: string;
|
||||
workflow?: Record<string, any>;
|
||||
state?: number;
|
||||
desc?: string;
|
||||
}
|
||||
|
||||
export function buildInitialTriggerTask(triggerType: string): WorkflowTask {
|
||||
const norm = triggerType.toLowerCase().trim();
|
||||
switch (norm) {
|
||||
case "webhook":
|
||||
return {
|
||||
name: "trigger_webhook",
|
||||
type: "webhook",
|
||||
label: "Webhook触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: crypto.randomUUID(),
|
||||
params: [],
|
||||
};
|
||||
case "clock":
|
||||
case "schedule":
|
||||
case "timer":
|
||||
return {
|
||||
name: "trigger_clock",
|
||||
type: "clock",
|
||||
label: "定时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
cron: "0 0 * * *",
|
||||
timeZone: "Asia/Shanghai",
|
||||
};
|
||||
case "datalink":
|
||||
case "data-link":
|
||||
case "entity":
|
||||
return {
|
||||
name: "trigger_datalink_create",
|
||||
type: "ekuaibao-datalink-create-trigger",
|
||||
label: "业务对象新增时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
};
|
||||
case "flowform":
|
||||
case "flow":
|
||||
case "bill":
|
||||
return {
|
||||
name: "trigger_flowform",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
label: "单据审批事件触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
name: `trigger_${norm.replace(/-/g, "_")}`,
|
||||
type: norm,
|
||||
label: `${norm}触发`,
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWorkflow(
|
||||
client: import("ky").KyInstance,
|
||||
options: CreateWorkflowOptions = {}
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
let base: Record<string, any> = {};
|
||||
if (options.file) {
|
||||
const fs = await import("fs/promises");
|
||||
const raw = await fs.readFile(options.file, "utf-8");
|
||||
base = JSON.parse(raw);
|
||||
} else if (options.workflow) {
|
||||
base = JSON.parse(JSON.stringify(options.workflow));
|
||||
}
|
||||
|
||||
const payload: Record<string, any> = {
|
||||
...base,
|
||||
label: options.label || base.label || "未命名流程",
|
||||
state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承
|
||||
};
|
||||
|
||||
if (options.platformId || base.platformId) {
|
||||
payload.platformId = options.platformId || base.platformId;
|
||||
}
|
||||
if (options.desc || base.desc) {
|
||||
payload.desc = options.desc || base.desc;
|
||||
}
|
||||
|
||||
// 触发器节点初始化
|
||||
if (!payload.tasks || payload.tasks.length === 0) {
|
||||
if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") {
|
||||
payload.tasks = [buildInitialTriggerTask(options.trigger)];
|
||||
} else {
|
||||
payload.tasks = [];
|
||||
}
|
||||
} else if (payload.tasks[0]?.type === "webhook") {
|
||||
if (!payload.tasks[0].urlPath) {
|
||||
payload.tasks[0].urlPath = crypto.randomUUID();
|
||||
}
|
||||
}
|
||||
|
||||
return api.createWorkflow(client, payload);
|
||||
}
|
||||
|
||||
export function deleteWorkflow(...args: Parameters<typeof api.deleteWorkflow>) {
|
||||
return api.deleteWorkflow(...args);
|
||||
}
|
||||
|
||||
export function listWorkflowSnapshots(...args: Parameters<typeof api.listWorkflowSnapshots>) {
|
||||
return api.listWorkflowSnapshots(...args);
|
||||
}
|
||||
@@ -546,23 +694,22 @@ export function diffWorkflowJobs(
|
||||
jobB: WorkflowJobDetail,
|
||||
treeB: WorkflowTaskExecution[]
|
||||
): WorkflowJobDiff {
|
||||
const flatA = flattenExecutionTree(treeA);
|
||||
const flatB = flattenExecutionTree(treeB);
|
||||
|
||||
const allNames = Array.from(
|
||||
new Set([
|
||||
...flatA.map((n) => n.name).filter(Boolean),
|
||||
...flatB.map((n) => n.name).filter(Boolean),
|
||||
])
|
||||
) as string[];
|
||||
const flatA = indexExecutionContexts(treeA);
|
||||
const flatB = indexExecutionContexts(treeB);
|
||||
const byKeyA = new Map(flatA.map(context => [context.key, context]));
|
||||
const byKeyB = new Map(flatB.map(context => [context.key, context]));
|
||||
const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]);
|
||||
|
||||
const nodes: NodeExecutionDiff[] = [];
|
||||
let divergedNodesCount = 0;
|
||||
let statusDiffCount = 0;
|
||||
|
||||
for (const name of allNames) {
|
||||
const nodeA = flatA.find((n) => n.name === name);
|
||||
const nodeB = flatB.find((n) => n.name === name);
|
||||
for (const key of allKeys) {
|
||||
const contextA = byKeyA.get(key);
|
||||
const contextB = byKeyB.get(key);
|
||||
const nodeA = contextA?.node;
|
||||
const nodeB = contextB?.node;
|
||||
const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed";
|
||||
|
||||
const statusA = nodeA?.status;
|
||||
const statusB = nodeB?.status;
|
||||
@@ -571,8 +718,9 @@ export function diffWorkflowJobs(
|
||||
|
||||
// 比较 inputs
|
||||
const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
||||
const inA = (nodeA?.inputs as Record<string, unknown>) || {};
|
||||
const inB = (nodeB?.inputs as Record<string, unknown>) || {};
|
||||
const payloadFields = (value: unknown): Record<string, unknown> => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record<string, unknown> : { $value: value };
|
||||
const inA = payloadFields(nodeA?.inputs);
|
||||
const inB = payloadFields(nodeB?.inputs);
|
||||
const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)]));
|
||||
for (const k of inputKeys) {
|
||||
if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) {
|
||||
@@ -582,8 +730,8 @@ export function diffWorkflowJobs(
|
||||
|
||||
// 比较 outputs
|
||||
const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = [];
|
||||
const outA = (nodeA?.outputs as Record<string, unknown>) || {};
|
||||
const outB = (nodeB?.outputs as Record<string, unknown>) || {};
|
||||
const outA = payloadFields(nodeA?.outputs ?? nodeA?.output);
|
||||
const outB = payloadFields(nodeB?.outputs ?? nodeB?.output);
|
||||
const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)]));
|
||||
for (const k of outputKeys) {
|
||||
if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) {
|
||||
@@ -595,13 +743,15 @@ export function diffWorkflowJobs(
|
||||
!nodeA ||
|
||||
!nodeB ||
|
||||
isStatusDiff ||
|
||||
Boolean(nodeB.error && !nodeA.error) ||
|
||||
inputsDiff.length > 0;
|
||||
JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) ||
|
||||
inputsDiff.length > 0 || outputsDiff.length > 0;
|
||||
|
||||
if (isDiverged) divergedNodesCount++;
|
||||
|
||||
nodes.push({
|
||||
taskName: name,
|
||||
instanceKey: key,
|
||||
currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined,
|
||||
displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined,
|
||||
type: nodeB?.type || nodeA?.type,
|
||||
statusA,
|
||||
@@ -645,3 +795,186 @@ export function diffWorkflowJobs(
|
||||
};
|
||||
}
|
||||
|
||||
export function getWorkflowDebugSource(...args: Parameters<typeof api.getWorkflowDebugSource>) {
|
||||
return api.getWorkflowDebugSource(...args);
|
||||
}
|
||||
|
||||
export function triggerWorkflowDebug(...args: Parameters<typeof api.triggerWorkflowDebug>) {
|
||||
return api.triggerWorkflowDebug(...args);
|
||||
}
|
||||
|
||||
export async function runWorkflowDebugTest(
|
||||
client: import("ky").KyInstance,
|
||||
pipelineId: string,
|
||||
options: {
|
||||
flowCodeOrId?: string;
|
||||
data?: Record<string, any>;
|
||||
triggerCategory?: import("./types.js").WorkflowTriggerCategory;
|
||||
triggerType?: string;
|
||||
triggerLabel?: string;
|
||||
autoPublish?: boolean;
|
||||
timeoutMs?: number;
|
||||
pollIntervalMs?: number;
|
||||
} = {}
|
||||
): Promise<import("./types.js").WorkflowTestReport> {
|
||||
if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) {
|
||||
throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数");
|
||||
}
|
||||
let targetEntityId = options.flowCodeOrId ?? "";
|
||||
const code = options.flowCodeOrId;
|
||||
const isDirectCode = !code || code.includes("-") || code.startsWith("ID01");
|
||||
if (code && !isDirectCode) {
|
||||
try {
|
||||
const source = await api.getWorkflowDebugSource(client, pipelineId, {
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
keywords: code,
|
||||
});
|
||||
const matched = source.items.find(
|
||||
(item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code)
|
||||
);
|
||||
if (matched) {
|
||||
targetEntityId = matched.id;
|
||||
}
|
||||
} catch {
|
||||
// 关键字搜索超时或失败时直接回退使用传入值
|
||||
}
|
||||
}
|
||||
|
||||
const jobId = await api.triggerWorkflowDebug(client, pipelineId, {
|
||||
entityId: targetEntityId || undefined,
|
||||
data: options.data,
|
||||
autoPublish: options.autoPublish ?? false,
|
||||
});
|
||||
|
||||
const timeoutMs = options.timeoutMs ?? 15000;
|
||||
const pollIntervalMs = options.pollIntervalMs ?? 500;
|
||||
const start = Date.now();
|
||||
const diagnosticsErrors: Array<{ source: string; message: string }> = [];
|
||||
const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) });
|
||||
const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase();
|
||||
let finalJob: WorkflowJobDetail | undefined;
|
||||
let pollingFailed = false;
|
||||
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
const job = await api.getJob(client, jobId);
|
||||
finalJob = job;
|
||||
if (terminal.has(jobState(job))) break;
|
||||
} catch (error) {
|
||||
// 任务刚创建可能存在短延时,继续轮询
|
||||
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
|
||||
?? (error as { response?: { status?: number } } | null)?.response?.status;
|
||||
if (status !== 404) {
|
||||
recordError("job", error);
|
||||
pollingFailed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start)))));
|
||||
}
|
||||
|
||||
if (!finalJob && !pollingFailed) {
|
||||
try { finalJob = await api.getJob(client, jobId); }
|
||||
catch (error) { recordError("job", error); pollingFailed = true; }
|
||||
}
|
||||
const timedOut = !pollingFailed && !terminal.has(jobState(finalJob));
|
||||
const [treeResult, failuresResult] = await Promise.allSettled([
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
]);
|
||||
const tree = treeResult.status === "fulfilled" ? treeResult.value : [];
|
||||
const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : [];
|
||||
if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason);
|
||||
if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason);
|
||||
|
||||
const rawFailed = extractFailureExecutions(tree, failedItems);
|
||||
const diagnosticsComplete = diagnosticsErrors.length === 0;
|
||||
const status = jobState(finalJob);
|
||||
const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0;
|
||||
let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete";
|
||||
if (timedOut) outcome = "timed_out";
|
||||
else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
||||
else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
|
||||
return {
|
||||
jobId,
|
||||
pipelineId,
|
||||
status,
|
||||
outcome,
|
||||
timedOut,
|
||||
diagnosticsComplete,
|
||||
diagnosticsErrors,
|
||||
runType: finalJob?.runType || "DEBUG",
|
||||
durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined,
|
||||
targetEntityId,
|
||||
triggerCategory: options.triggerCategory,
|
||||
triggerType: options.triggerType,
|
||||
triggerLabel: options.triggerLabel,
|
||||
executionTree: tree,
|
||||
failedExecutions: rawFailed,
|
||||
conditionDiagnoses,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
explainConditionBranches,
|
||||
type ConditionBranchExplanation,
|
||||
type ConditionRuleExplanation,
|
||||
} from "./workflow/branch/index.js";
|
||||
|
||||
export {
|
||||
classifyWorkflowTrigger,
|
||||
type WorkflowTriggerCategory,
|
||||
type WorkflowSampleRecord,
|
||||
type WorkflowSampleDataResult,
|
||||
} from "./types.js";
|
||||
|
||||
export async function getWorkflowSampleData(
|
||||
client: import("ky").KyInstance,
|
||||
pipelineId: string,
|
||||
type = "webhook"
|
||||
): Promise<import("./types.js").WorkflowSampleDataResult> {
|
||||
return api.getWorkflowSampleData(client, pipelineId, type);
|
||||
}
|
||||
|
||||
export function getWorkflowEnumOptions(...args: Parameters<typeof api.getWorkflowEnumOptions>) {
|
||||
return api.getWorkflowEnumOptions(...args);
|
||||
}
|
||||
|
||||
export async function resolveWorkflowEnumOptions(
|
||||
client?: import("ky").KyInstance,
|
||||
thirdId = "action",
|
||||
platformId?: string
|
||||
): Promise<Array<{ code: string; label: string; name: string; description?: string }>> {
|
||||
if (client) {
|
||||
try {
|
||||
const remote = await api.getWorkflowEnumOptions(client, thirdId, platformId);
|
||||
if (remote && remote.length > 0) {
|
||||
return remote.map((item) => ({
|
||||
code: item.code,
|
||||
label: item.label,
|
||||
name: item.name || item.label,
|
||||
}));
|
||||
}
|
||||
} catch {
|
||||
// 远程调用失败(如无权限/网络异常)时 Fallback 到内置字典
|
||||
}
|
||||
}
|
||||
|
||||
if (thirdId.toLowerCase() === "action") {
|
||||
const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./workflow/enums.js");
|
||||
return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({
|
||||
code: item.code,
|
||||
label: item.label,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
}));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export * from "./workflow/index.js";
|
||||
@@ -191,14 +191,14 @@ export const FlowCreateTaskSchema = BaseTaskSchema.extend({
|
||||
// 兜底节点:遇到未收录类型时仍保留全部字段
|
||||
export const UnknownTaskSchema = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
name: z.string().default("task"),
|
||||
type: z.string(),
|
||||
label: z.string().optional(),
|
||||
desc: z.string().optional(),
|
||||
groupName: z.string(),
|
||||
orderIndex: z.number(),
|
||||
levelIndex: z.array(z.number()),
|
||||
status: z.string(),
|
||||
groupName: z.string().default("trigger"),
|
||||
orderIndex: z.number().default(0),
|
||||
levelIndex: z.array(z.number()).default([0]),
|
||||
status: z.string().default("active"),
|
||||
displayName: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
@@ -555,6 +555,8 @@ export interface WorkflowSnapshotDiff {
|
||||
|
||||
export interface NodeExecutionDiff {
|
||||
taskName: string;
|
||||
instanceKey?: string;
|
||||
currentLoopPath?: string;
|
||||
displayName?: string;
|
||||
type?: string;
|
||||
statusA?: string;
|
||||
@@ -604,4 +606,105 @@ export interface WorkflowJobDiff {
|
||||
};
|
||||
}
|
||||
|
||||
// ── 调试数据源与测试结果 ───────────────────────────────────────────────────────
|
||||
|
||||
export const WorkflowDebugSourceItemSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
title: z.string().default(""),
|
||||
flowState: z.string().default(""),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowDebugSourceResultSchema = z
|
||||
.object({
|
||||
type: z.string().default(""),
|
||||
total: z.number().default(0),
|
||||
items: z.array(WorkflowDebugSourceItemSchema).default([]),
|
||||
fields: z.array(z.object({ key: z.string(), label: z.string() })).default([]),
|
||||
label: z.string().default(""),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type WorkflowDebugSourceItem = z.infer<typeof WorkflowDebugSourceItemSchema>;
|
||||
export type WorkflowDebugSourceResult = z.infer<typeof WorkflowDebugSourceResultSchema>;
|
||||
|
||||
export interface WorkflowTestReport {
|
||||
jobId: string;
|
||||
pipelineId: string;
|
||||
status: string;
|
||||
outcome: "completed" | "failed" | "timed_out" | "incomplete";
|
||||
timedOut: boolean;
|
||||
diagnosticsComplete: boolean;
|
||||
diagnosticsErrors: Array<{ source: string; message: string }>;
|
||||
runType: string;
|
||||
durationTime?: number;
|
||||
targetEntityId: string;
|
||||
triggerCategory?: WorkflowTriggerCategory;
|
||||
triggerType?: string;
|
||||
triggerLabel?: string;
|
||||
executionTree: WorkflowTaskExecution[];
|
||||
failedExecutions: WorkflowTaskExecution[];
|
||||
conditionDiagnoses: import("./workflow/branch/index.js").ConditionBranchExplanation[];
|
||||
}
|
||||
|
||||
// ── 触发器元类型分类与智能路径路由 ───────────────────────────────────────────────
|
||||
|
||||
export type WorkflowTriggerCategory =
|
||||
| "FLOW_FORM" // 单据审批流转类 (ekuaibao-flowform-trigger, ekuaibao-ebot-trigger, other-event-trigger, flow-change-trigger)
|
||||
| "DATALINK" // 业务对象/台账变更类 (ekuaibao-datalink-create-trigger, ekuaibao-datalink-change-trigger, ekuaibao-datalink-time-trigger, datalink-button-trigger, ekuaibao-tmc-datalink-change-trigger)
|
||||
| "SCHEDULE" // 定时调度类 (clock)
|
||||
| "WEBHOOK" // 外部调用/网关集成类 (webhook, hab-trigger-task, xrxs-trigger, fxiaoke-trigger)
|
||||
| "CUSTOM"; // 其他自定义触发器 (pipeline-running-trigger, pipeline-save-trigger 等)
|
||||
|
||||
export function classifyWorkflowTrigger(triggerType?: string): WorkflowTriggerCategory {
|
||||
if (!triggerType) return "CUSTOM";
|
||||
const t = triggerType.toLowerCase();
|
||||
if (t === "clock" || t.includes("timer") || t.includes("schedule")) {
|
||||
return "SCHEDULE";
|
||||
}
|
||||
if (t.includes("flowform") || t.includes("ebot") || t.includes("flow-") || t === "other-event-trigger" || t.includes("requisition")) {
|
||||
return "FLOW_FORM";
|
||||
}
|
||||
if (t.includes("datalink") || t.includes("entity")) {
|
||||
return "DATALINK";
|
||||
}
|
||||
if (t.includes("webhook") || t.includes("hab-trigger") || t.includes("xrxs") || t.includes("fxiaoke")) {
|
||||
return "WEBHOOK";
|
||||
}
|
||||
return "CUSTOM";
|
||||
}
|
||||
|
||||
// ── Webhook 数据样本 (Sample Data) ─────────────────────────────────────────────
|
||||
|
||||
export const WorkflowSampleRecordSchema = z.object({
|
||||
id: z.string(),
|
||||
corporationId: z.string().optional(),
|
||||
pipelineId: z.string().optional(),
|
||||
taskName: z.string().optional(),
|
||||
actived: z.number().optional(),
|
||||
dataJson: z.string(),
|
||||
createTime: z.number(),
|
||||
updateTime: z.number().optional(),
|
||||
});
|
||||
|
||||
export type WorkflowSampleRecord = z.infer<typeof WorkflowSampleRecordSchema>;
|
||||
|
||||
export const WorkflowSampleDataResultSchema = z.object({
|
||||
records: z.array(WorkflowSampleRecordSchema).default([]),
|
||||
total: z.number().optional(),
|
||||
size: z.number().optional(),
|
||||
current: z.number().optional(),
|
||||
});
|
||||
|
||||
export type WorkflowSampleDataResult = z.infer<typeof WorkflowSampleDataResultSchema>;
|
||||
|
||||
// ── 工作流/Piper 枚举选项 (EKB_ENUM) ──────────────────────────────────────────
|
||||
|
||||
export const WorkflowEnumItemSchema = z.object({
|
||||
label: z.string(),
|
||||
code: z.string(),
|
||||
name: z.string().optional().default(""),
|
||||
});
|
||||
|
||||
export type WorkflowEnumItem = z.infer<typeof WorkflowEnumItemSchema>;
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runWorkflowDebugTest } from "./services.js";
|
||||
|
||||
function setup(status = "COMPLETED", errors: string[] = []) {
|
||||
const posts: string[] = [];
|
||||
const response = (data: unknown) => new Response(JSON.stringify({ code: 200, data }));
|
||||
const client = {
|
||||
post: async (path: string) => { posts.push(path); return response("job"); },
|
||||
get: async (path: string) => {
|
||||
if (path.endsWith("/level/failed")) {
|
||||
if (errors.includes("failures")) throw new Error("403 failures unavailable");
|
||||
return response([]);
|
||||
}
|
||||
if (path.endsWith("/execution")) {
|
||||
if (errors.includes("tree")) throw new Error("403 execution unavailable");
|
||||
return response([]);
|
||||
}
|
||||
if (errors.includes("job")) throw new Error("403 job unavailable");
|
||||
return response({ id: "job", status });
|
||||
},
|
||||
} as any;
|
||||
return { client, posts };
|
||||
}
|
||||
|
||||
describe("workflow debug completion evidence", () => {
|
||||
it("reports completed only when all diagnostics were fetched", async () => {
|
||||
const { client } = setup();
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.outcome).toBe("completed");
|
||||
expect(result.timedOut).toBe(false);
|
||||
expect(result.diagnosticsComplete).toBe(true);
|
||||
});
|
||||
it("reports a failed terminal job", async () => {
|
||||
const { client } = setup("FAILED");
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.outcome).toBe("failed");
|
||||
});
|
||||
it("keeps timed-out jobs queryable and exposes missing diagnostic evidence", async () => {
|
||||
const { client } = setup("RUNNING", ["tree", "failures"]);
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 });
|
||||
expect(result.jobId).toBe("job");
|
||||
expect(result.status).toBe("RUNNING");
|
||||
expect(result.outcome).toBe("timed_out");
|
||||
expect(result.timedOut).toBe(true);
|
||||
expect(result.diagnosticsComplete).toBe(false);
|
||||
expect(result.diagnosticsErrors.map(error => error.source)).toEqual(["executionTree", "failedExecutions"]);
|
||||
});
|
||||
it("marks partial diagnostic reads as incomplete rather than clean success", async () => {
|
||||
const { client } = setup("COMPLETED", ["tree"]);
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.outcome).toBe("incomplete");
|
||||
expect(result.diagnosticsErrors[0]?.message).toContain("403");
|
||||
});
|
||||
it("preserves job identity when polling fails and does not hide the error", async () => {
|
||||
const { client } = setup("RUNNING", ["job"]);
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record" });
|
||||
expect(result.jobId).toBe("job");
|
||||
expect(result.outcome).toBe("incomplete");
|
||||
expect(result.diagnosticsErrors[0]?.source).toBe("job");
|
||||
});
|
||||
it("rejects invalid timing options before creating a mutating job", async () => {
|
||||
const { client, posts } = setup();
|
||||
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
|
||||
const { client } = setup();
|
||||
const get = client.get;
|
||||
let jobReads = 0;
|
||||
client.get = async (path: string) => {
|
||||
if (path.endsWith("/job") && jobReads++ === 0) throw { response: { status: 404 } };
|
||||
return get(path);
|
||||
};
|
||||
const result = await runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 });
|
||||
expect(result.outcome).toBe("completed");
|
||||
expect(jobReads).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
# Workflow 工作流模块
|
||||
|
||||
Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
|
||||
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 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]
|
||||
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
|
||||
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
|
||||
hose-use workflow tail <pipelineId> [--job=<jobId>] [--once] [--failed-only] [--interval=2] [--json]
|
||||
hose-use workflow lint-script <pipelineId> [节点标识] [--json]
|
||||
hose-use workflow lint-script --code="<code>" [--type=code-js2|code]
|
||||
hose-use workflow eval-script <pipelineId> <节点标识> [--input='{...}'] [--sample=1] [--timeout=3000]
|
||||
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
```
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
||||
|
||||
| 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 |
|
||||
|---|---|---|---|
|
||||
| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,直接秒级派发并抓取执行树 |
|
||||
| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task`, `xrxs-trigger`, `fxiaoke-trigger` | 服务端维护最近 3 条 Sample 样本 (`/sampleData`),`inputs: { data: { ... } }` | **样本复用与 Payload 注入**:展示参数定义映射 (Key->Label),支持 `--sample=<1\|2\|3>` 直接使用历史真实样本,或 `--body='{...}'` / `--empty` |
|
||||
| **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=<ID>` 或 `--flow=<编码>` |
|
||||
| **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 |
|
||||
|
||||
|
||||
## 生产环境调试缺陷与安全防线(合思平台缺陷记录)
|
||||
|
||||
> [!WARNING] **合思后端架构缺陷:前端置灰防御,后端裸奔无防**
|
||||
> 1. **前端置灰表象**:合思 Web 控制台在工作流处于【启用中】(`state = 1`)时,会将【调试】与【保存更新】按钮置灰(disabled),给人以“生产启用态无法调试”的假象;
|
||||
> 2. **后端无状态鉴权**:合思 EASO/Piper 调度引擎后端 `POST /api/easo/jobs` 接口**完全未对工作流启用状态进行校验**,只要调用 API 即可在生产环境直接派发调试任务;
|
||||
> 3. **隐蔽快照自增污染**:每次调用 `POST /api/easo/jobs` 调试,服务端均会隐式创建一个新的 Pipeline Snapshot,并将版本号自增(如 `v26.10.10` ➔ `v26.10.13`),无声息地污染发布历史;
|
||||
> 4. **真实破坏性副作用风险**:合思后端**不具备调试沙箱(Sandbox)隔离**,调试是以真实操作员身份在生产环境真实运行。若下游包含单据自动审批、外部 HTTP 请求、修改业务对象台账或短信通知节点,一旦条件命中,将产生**不可逆的真实生产变更**!
|
||||
|
||||
### `hose-use` 生产环境调试特性与全方位风险提示
|
||||
|
||||
在合思 Web 控制台中,已发布启用的工作流【调试】按钮被置灰,人工无法直接发起测试;
|
||||
`hose-use` **保留了穿透前端限制的直达调测能力**(为线上排障与即时验证多保留了一条宝贵的高级通道),但同时提供**充分的安全提示与风险告知**:
|
||||
- **候选单据提示**:在拉取调试候选数据源时,高亮提示当前工作流处于【🟢 生产启用中】;
|
||||
- **调试执行提示**:在发起端到端调试时,置顶打印醒目的【生产启用态调试安全提醒】,提醒操作者合思无沙箱、写节点会真实生效以及快照版本会自增,确保线上调测“有路径、知风险、审慎用”。
|
||||
|
||||
## 详细文档
|
||||
|
||||
完整接口说明、认证链路、MCP tool 列表见:
|
||||
|
||||
[docs/modules/platform.md](../../../../docs/modules/platform.md)
|
||||
|
||||
## 调试与诊断结果契约
|
||||
|
||||
- 调试属于写操作:`--dry-run` 仅展示目标、发布选项和风险,不创建客户端或发起 Job;实际执行需要 `--yes` / `--confirm`。启用中的工作流仍可在确认后直接调试。
|
||||
- JSON 和预览均包含风险信息。执行结果提供 `productionEnabled`(状态未知时为 `null`)和 `warnings`。
|
||||
- `outcome` 为 `completed`、`failed`、`timed_out` 或 `incomplete`;只有完整成功才返回退出码 `0`。超时不取消已经发起的 Job,保留 `jobId` 以供 `workflow job` 续查。
|
||||
- `timedOut`、`diagnosticsComplete`、`diagnosticsErrors` 区分执行超时、读取失败与没有失败节点;权限错误不再被当成空的成功结果。
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
import { getDatabase } from "../../../../core/db/index.js";
|
||||
|
||||
export interface WorkflowErrorAlert {
|
||||
id: string;
|
||||
+132
-53
@@ -1,55 +1,12 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type {
|
||||
WorkflowAnalysis,
|
||||
WorkflowAstNode,
|
||||
WorkflowDependency,
|
||||
WorkflowDiagnostic,
|
||||
WorkflowFormSpecComponentLike,
|
||||
AnalyzeWorkflowOptions,
|
||||
} from "./types.js";
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
@@ -66,6 +23,12 @@ const KNOWN_TYPES = new Set([
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"ekuaibao-flowform-trigger",
|
||||
"ekuaibao-ebot-trigger",
|
||||
"ekuaibao-datalink-create-trigger",
|
||||
"ekuaibao-datalink-time-trigger",
|
||||
"ekuaibao-datalink-edit-trigger",
|
||||
"ekuaibao-datalink-delete-trigger",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
@@ -164,6 +127,33 @@ function getTaskFormEntries(
|
||||
return [];
|
||||
}
|
||||
|
||||
interface LeafFilterItem {
|
||||
key?: unknown;
|
||||
value?: unknown;
|
||||
compare?: unknown;
|
||||
label?: unknown;
|
||||
}
|
||||
|
||||
function extractLeafFilters(filterGroup: unknown): LeafFilterItem[] {
|
||||
if (!filterGroup || typeof filterGroup !== "object") return [];
|
||||
const items: LeafFilterItem[] = [];
|
||||
const rec = filterGroup as Record<string, unknown>;
|
||||
|
||||
if (Array.isArray(rec.filters)) {
|
||||
for (const sub of rec.filters) {
|
||||
items.push(...extractLeafFilters(sub));
|
||||
}
|
||||
} else if ("key" in rec || "value" in rec) {
|
||||
items.push({
|
||||
key: rec.key,
|
||||
value: rec.value,
|
||||
compare: rec.compare,
|
||||
label: rec.label,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
@@ -380,6 +370,96 @@ export function analyzeWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 4: 触发器节点配置了无效的单据审批状态过滤 (DEADLOCK_TRIGGER_STATE_FILTER)
|
||||
if (
|
||||
(task.type === "ekuaibao-flowform-trigger" || task.type === "ekuaibao-ebot-trigger") &&
|
||||
(task as Record<string, unknown>).combineFilters
|
||||
) {
|
||||
const rawFilters = JSON.stringify((task as Record<string, unknown>).combineFilters);
|
||||
if (
|
||||
rawFilters.includes('"key":"state"') &&
|
||||
(rawFilters.includes('"APPROVING"') ||
|
||||
rawFilters.includes('"approving"') ||
|
||||
rawFilters.includes('"REJECTED"') ||
|
||||
rawFilters.includes('"rejected"') ||
|
||||
rawFilters.includes("被驳回") ||
|
||||
rawFilters.includes("审批驳回"))
|
||||
) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "DEADLOCK_TRIGGER_STATE_FILTER",
|
||||
path,
|
||||
message: `触发器节点 [${task.label || task.name}] (${task.name}) 配置了 state 状态过滤条件。合思单据审批出站事件属于动作事件(如 backlog.approving / flow.rejected),事件载荷中单据 state 字段在事件触发初始阶段可能为空或为大写英文 REJECTED,该过滤会导致出站事件被 100% 静默丢弃,下游审批流程永久无法触发!建议移除 state 过滤,改用通知类型(action)或后置条件节点。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 5: 条件节点中单据审批状态过滤缺陷与纯文本枚举比对 (DEADLOCK_CONDITION_STATE_FILTER / INVALID_ACTION_ENUM_TEXT_VALUE)
|
||||
if (task.type === "condition") {
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? raw.conditions ?? task.inputs;
|
||||
if (filterSource) {
|
||||
const leafFilters = extractLeafFilters(filterSource);
|
||||
for (const leaf of leafFilters) {
|
||||
const keyStr = String(leaf.key || "");
|
||||
const valStr = typeof leaf.value === "string" ? leaf.value : JSON.stringify(leaf.value ?? "");
|
||||
const isStateField =
|
||||
keyStr === "state" ||
|
||||
/"key":"state"/i.test(keyStr) ||
|
||||
/"label":"[^"]*审批状态"/i.test(keyStr);
|
||||
const isActionField =
|
||||
keyStr === "action" ||
|
||||
/"key":"action"/i.test(keyStr) ||
|
||||
/"thirdId":"action"/i.test(keyStr) ||
|
||||
/"label":"[^"]*通知类型"/i.test(keyStr);
|
||||
|
||||
if (isStateField && /被驳回|审批驳回|REJECTED|reject/i.test(valStr)) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "DEADLOCK_CONDITION_STATE_FILTER",
|
||||
path,
|
||||
message: `条件节点 [${task.label || task.name}] (${task.name}) 配置了使用单据审批状态 [state] 匹配驳回状态。合思单据出站事件为动作事件(Action Event),事件载荷中单据审批状态字段在事件触发初始阶段可能为空或为大写英文 REJECTED,使用中文 [被驳回/审批驳回] 匹配会导致条件 100% 判定为 false!建议改用触发器通知类型 [action],并在下拉选项中选中标准枚举宏(对应 code: flow.rejected)。`,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
isActionField &&
|
||||
valStr &&
|
||||
!valStr.includes("@{value(") &&
|
||||
!valStr.includes("flow.") &&
|
||||
!valStr.includes("freeflow.") &&
|
||||
!valStr.includes("backlog.") &&
|
||||
!valStr.includes("timeout.") &&
|
||||
/被驳回|已支付|待审批|待支付|待收单|撤回|删除|催办/i.test(valStr)
|
||||
) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "INVALID_ACTION_ENUM_TEXT_VALUE",
|
||||
path,
|
||||
message: `条件节点 [${task.label || task.name}] (${task.name}) 中通知类型 [action] 为 ENUM 枚举字段,但比对值被配置为了纯文本 [${valStr}]。Piper 运行时会使用底层英文枚举 Code (如 flow.rejected) 进行比对,纯文本将导致条件永远不匹配。请在条件节点右侧通过下拉列表选择标准枚举项。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 6: HTTP 自动审批节点 URL 与中括号校验 (MISSING_BACKLOG_DATA_BRACKETS)
|
||||
if (task.type === "http") {
|
||||
const url = String((task as Record<string, unknown>).url || "");
|
||||
if (url.includes("api/openapi/v1/backlog/data")) {
|
||||
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
|
||||
const segment = match ? match[1] : "";
|
||||
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "MISSING_BACKLOG_DATA_BRACKETS",
|
||||
path,
|
||||
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
@@ -397,4 +477,3 @@ export function analyzeWorkflow(
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
+56
-2
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { analyzeWorkflow } from "./analysis.js";
|
||||
import { PlatformSchema } from "./types.js";
|
||||
import { analyzeWorkflow } from "./index.js";
|
||||
import { PlatformSchema } from "../../types.js";
|
||||
|
||||
describe("Workflow static analysis", () => {
|
||||
it("accepts nullable app center metadata", () => {
|
||||
@@ -111,4 +111,58 @@ describe("Workflow static analysis", () => {
|
||||
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
|
||||
});
|
||||
|
||||
it("detects DEADLOCK_TRIGGER_STATE_FILTER when trigger specifies state APPROVING", () => {
|
||||
const wf = {
|
||||
id: "wf-trigger-deadlock",
|
||||
label: "资金调拨自动审批",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_1",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
label: "单据审批事件触发器",
|
||||
combineFilters: {
|
||||
filters: [
|
||||
{
|
||||
filters: [
|
||||
{ key: "formSpecification", value: "ID01RUq5zrhZTh", compare: "eq" },
|
||||
{ key: "state", value: "APPROVING", compare: "eq" },
|
||||
],
|
||||
condition: "and",
|
||||
},
|
||||
],
|
||||
condition: "or",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("DEADLOCK_TRIGGER_STATE_FILTER");
|
||||
expect(result.diagnostics.find((d) => d.code === "DEADLOCK_TRIGGER_STATE_FILTER")?.severity).toBe("error");
|
||||
});
|
||||
|
||||
it("detects MISSING_BACKLOG_DATA_BRACKETS on backlog openapi http task", () => {
|
||||
const wf = {
|
||||
id: "wf-http-no-brackets",
|
||||
label: "自动审批",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_1",
|
||||
type: "http",
|
||||
label: "审批接口调用",
|
||||
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/ID01X4mbLfjvpt",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("MISSING_BACKLOG_DATA_BRACKETS");
|
||||
expect(result.diagnostics.find((d) => d.code === "MISSING_BACKLOG_DATA_BRACKETS")?.severity).toBe("warning");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types.js";
|
||||
export * from "./analyzer.js";
|
||||
@@ -0,0 +1,50 @@
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import { indexExecutionContexts } from "../../execution-context.js";
|
||||
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
|
||||
|
||||
export const OP_MAP: Record<string, string> = {
|
||||
eq: "等于",
|
||||
neq: "不等于",
|
||||
include: "包含",
|
||||
not_include: "不包含",
|
||||
in: "在列表中",
|
||||
not_in: "不在列表中",
|
||||
gt: "大于",
|
||||
gte: "大于等于",
|
||||
lt: "小于",
|
||||
lte: "小于等于",
|
||||
empty: "为空",
|
||||
not_empty: "不为空",
|
||||
};
|
||||
|
||||
/**
|
||||
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
|
||||
*/
|
||||
export function parseChooseTag(tag: string): {
|
||||
upstreamNode: string;
|
||||
upstreamProp: string;
|
||||
label: string;
|
||||
} | null {
|
||||
if (typeof tag !== "string") return null;
|
||||
const match = tag.match(/@\{choose\('(.*)'\)\}/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
const upstreamNode = parsed.key || "";
|
||||
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
|
||||
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
|
||||
return { upstreamNode, upstreamProp, label };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试从 @{value('...')} 中提取人类可读值
|
||||
*/
|
||||
export function parseValueTag(val: any): any {
|
||||
if (Array.isArray(val)) {
|
||||
return val.map((v) => parseValueTag(v));
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
const match = val.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
return parsed.label ? `${parsed.label} (${parsed.key})` : parsed.key || parsed.value;
|
||||
} catch {
|
||||
return val;
|
||||
}
|
||||
}
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个值是否匹配
|
||||
*/
|
||||
export function cleanRuleValue(value: any): any {
|
||||
if (Array.isArray(value)) return value.map(cleanRuleValue);
|
||||
if (typeof value === "string") {
|
||||
const match = value.match(/@\{value\('(.*)'\)\}/);
|
||||
if (match) {
|
||||
try { const parsed = JSON.parse(match[1]); return parsed.key ?? parsed.value; }
|
||||
catch { return value; }
|
||||
}
|
||||
}
|
||||
if (value && typeof value === "object" && "id" in value) return value.id;
|
||||
return value;
|
||||
}
|
||||
|
||||
export function evaluateRule(actual: any, expected: any, compare: string): boolean | null {
|
||||
const empty = actual === undefined || actual === null || actual === "" || (Array.isArray(actual) && actual.length === 0);
|
||||
if (compare === "empty") return empty;
|
||||
if (compare === "not_empty") return !empty;
|
||||
if (!Object.hasOwn(OP_MAP, compare)) return null;
|
||||
if (actual === undefined) return false;
|
||||
actual = cleanRuleValue(actual);
|
||||
expected = cleanRuleValue(expected);
|
||||
if (actual === null) return compare === "eq" ? expected === null : compare === "neq" ? expected !== null : false;
|
||||
if ([actual, expected].some(value => value !== null && typeof value === "object" && !Array.isArray(value))) return null;
|
||||
const equal = (a: any, b: any): boolean => {
|
||||
if (Array.isArray(a) && !Array.isArray(b)) return a.length === 1 && equal(a[0], b);
|
||||
if (!Array.isArray(a) && Array.isArray(b)) return b.length === 1 && equal(a, b[0]);
|
||||
return typeof a === "object" || typeof b === "object" ? JSON.stringify(a) === JSON.stringify(b) : String(a) === String(b);
|
||||
};
|
||||
switch (compare) {
|
||||
case "eq": return equal(actual, expected);
|
||||
case "neq": return !equal(actual, expected);
|
||||
case "in":
|
||||
case "not_in": {
|
||||
if (!Array.isArray(expected) || Array.isArray(actual)) return null;
|
||||
const matches = expected.some(item => equal(actual, item));
|
||||
return compare === "in" ? matches : !matches;
|
||||
}
|
||||
case "include":
|
||||
case "not_include": {
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return null;
|
||||
const values = Array.isArray(expected) ? expected : [expected];
|
||||
const matches = Array.isArray(actual)
|
||||
? values.every(value => actual.some(item => equal(item, value)))
|
||||
: typeof actual === "string" && values.every(value => actual.includes(String(value)));
|
||||
return compare === "include" ? matches : !matches;
|
||||
}
|
||||
default: {
|
||||
const numeric = (value: unknown) => typeof value === "number" || (typeof value === "string" && value.trim() !== "") ? Number(value) : NaN;
|
||||
const a = numeric(actual), b = numeric(expected);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
||||
return compare === "gt" ? a > b : compare === "gte" ? a >= b : compare === "lt" ? a < b : a <= b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析 Job 执行树中的条件节点,诊断分支是否跳过及跳过的具体字段原因
|
||||
*/
|
||||
export function explainConditionBranches(
|
||||
tree: WorkflowTaskExecution[]
|
||||
): ConditionBranchExplanation[] {
|
||||
const contexts = indexExecutionContexts(tree);
|
||||
const explanations: ConditionBranchExplanation[] = [];
|
||||
|
||||
for (const [position, context] of contexts.entries()) {
|
||||
const node = context.node;
|
||||
const rawNode = node as Record<string, any>;
|
||||
if (rawNode.type !== "condition") continue;
|
||||
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
|
||||
if (childTasks.length === 0) continue;
|
||||
|
||||
// 检查子任务是否执行过
|
||||
const childNames = childTasks.map((task: any) => task.name || task.id).filter(Boolean);
|
||||
const childContexts = contexts.filter((child, index) => {
|
||||
if (child.loopPath !== context.loopPath || !childNames.includes(child.node.name || child.node.id)) return false;
|
||||
if (child.node.parentId) return child.node.parentId === node.id;
|
||||
const nestedScope = [...context.scope, JSON.stringify([node.name || node.type || "unnamed", context.loopPath])];
|
||||
return JSON.stringify(child.scope) === JSON.stringify(nestedScope) ||
|
||||
(index > position && JSON.stringify(child.scope) === JSON.stringify(context.scope));
|
||||
});
|
||||
const anyExecuted = childContexts.some(child => child.node.status && !["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase()));
|
||||
if (anyExecuted) {
|
||||
// 子分支正常执行,无需诊断跳过
|
||||
continue;
|
||||
}
|
||||
const skippedTaskNames = childTasks.map((task: any) => `${task.name || task.id} (${task.label || task.displayName || task.type})`);
|
||||
const rules: ConditionRuleExplanation[] = [];
|
||||
|
||||
// 解析 combineFilters;保留 AND/OR 和嵌套分组语义。
|
||||
const explainFilter = (filter: any): boolean | null => {
|
||||
if (!filter || typeof filter !== "object") return null;
|
||||
if (Array.isArray(filter.filters)) {
|
||||
const values = filter.filters.map(explainFilter) as Array<boolean | null>;
|
||||
if (!values.length) return null;
|
||||
const condition = String(filter.condition ?? "AND").toUpperCase();
|
||||
if (condition === "AND") return values.includes(false) ? false : values.includes(null) ? null : true;
|
||||
if (condition === "OR") return values.includes(true) ? true : values.includes(null) ? null : false;
|
||||
return null;
|
||||
}
|
||||
const chooseInfo = parseChooseTag(filter.key);
|
||||
const rawExpected = filter.value;
|
||||
const parsedExpected = parseValueTag(rawExpected);
|
||||
const op = filter.compare || "eq";
|
||||
const upstreamNode = chooseInfo?.upstreamNode || "";
|
||||
const upstreamProp = chooseInfo?.upstreamProp || (typeof filter.key === "string" ? filter.key : "");
|
||||
const leftLabel = chooseInfo?.label || String(filter.key);
|
||||
|
||||
// 从上游节点提取真实 outputs;只使用同一次循环或祖先作用域中的执行实例。
|
||||
const candidates = contexts.slice(0, position).filter(candidate =>
|
||||
(candidate.node.name === upstreamNode || candidate.node.id === upstreamNode) &&
|
||||
(!candidate.loopPath || candidate.loopPath === context.loopPath) &&
|
||||
candidate.scope.every((part, i) => context.scope[i] === part)
|
||||
);
|
||||
candidates.sort((a, b) => a.scope.length - b.scope.length);
|
||||
const upstreamExecution = candidates.at(-1)?.node;
|
||||
const upstreamOutputs = upstreamExecution?.output ?? upstreamExecution?.outputs;
|
||||
let actualVal: any = upstreamOutputs;
|
||||
let isMissing = false;
|
||||
for (const part of upstreamProp.split(".")) {
|
||||
if (actualVal && typeof actualVal === "object" && Object.hasOwn(actualVal, part)) actualVal = actualVal[part];
|
||||
else { actualVal = undefined; isMissing = Boolean(upstreamExecution); break; }
|
||||
}
|
||||
// 提取纯净 ID 比对
|
||||
const cleanExpected = cleanRuleValue(rawExpected);
|
||||
const matched = upstreamExecution ? evaluateRule(actualVal, cleanExpected, op) : null;
|
||||
let detail: string;
|
||||
if (isMissing) {
|
||||
const availableKeys = upstreamOutputs && typeof upstreamOutputs === "object" ? Object.keys(upstreamOutputs).join(", ") : "无出参";
|
||||
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
|
||||
} else if (matched === null) {
|
||||
detail = `无法确定:缺少上游执行证据,或操作符/值类型不支持 (${op})`;
|
||||
} else {
|
||||
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
|
||||
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
|
||||
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
|
||||
}
|
||||
rules.push({ leftLabel, upstreamNode, upstreamProp, operator: op, operatorLabel: OP_MAP[op] || op, expectedValue: parsedExpected, actualValue: actualVal, isMissing, matched, detail });
|
||||
return matched;
|
||||
};
|
||||
const calculated = explainFilter(rawNode.combineFilters);
|
||||
const evaluation = node.status.toUpperCase() === "COMPLETED" ? calculated : null;
|
||||
let summary = evaluation === false
|
||||
? `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`
|
||||
: evaluation === true
|
||||
? "条件比对为 True,但未见子任务执行记录;请核对执行树是否完整"
|
||||
: "执行证据不足或条件尚未完成,无法确定子任务是否被跳过";
|
||||
const missingRule = rules.find(rule => rule.isMissing);
|
||||
if (evaluation === false && missingRule) {
|
||||
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
|
||||
}
|
||||
explanations.push({
|
||||
conditionNodeId: node.id,
|
||||
conditionNodeName: node.name || "-",
|
||||
conditionNodeLabel: node.label || rawNode.displayName || "条件节点",
|
||||
hasSkippedTasks: evaluation === false || childContexts.some(child => ["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase())),
|
||||
evaluation,
|
||||
skippedTaskNames,
|
||||
rules,
|
||||
summary,
|
||||
});
|
||||
}
|
||||
return explanations;
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { explainConditionBranches } from "./index.js";
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
|
||||
describe("Workflow Condition Branch Diagnosis", () => {
|
||||
const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`;
|
||||
const branch = (filter: any, status = "COMPLETED"): WorkflowTaskExecution => ({ id: "condition", name: "condition", type: "condition", status, tasks: [{ name: "child", type: "http" }], combineFilters: filter });
|
||||
const diagnose = (actual: unknown, compare: string, expected: unknown) => explainConditionBranches([
|
||||
{ id: "source", name: "source", type: "code", status: "COMPLETED", output: { value: actual } },
|
||||
branch({ filters: [{ key: choose(), compare, value: expected }], condition: "AND" }),
|
||||
])[0];
|
||||
|
||||
for (const [operator, actual, expected, matched] of [
|
||||
["gt", 10, 5, true], ["gte", 5, 5, true], ["lt", 1, 5, true], ["lte", 5, 5, true],
|
||||
["in", "A", ["A", "B"], true], ["not_in", "C", ["A", "B"], true],
|
||||
["include", ["A"], "AB", false], ["not_include", ["A"], "AB", true],
|
||||
["empty", false, null, false], ["empty", 0, null, false], ["empty", [], null, true],
|
||||
["not_empty", 0, null, true], ["unsupported", 1, 1, null], ["gt", "text", 1, null],
|
||||
["eq", null, null, true], ["eq", { amount: 10 }, 10, null],
|
||||
] as const) {
|
||||
it(`evaluates ${operator} without inventing a result (${JSON.stringify(actual)})`, () => {
|
||||
expect(diagnose(actual, operator, expected)?.rules[0]?.matched).toBe(matched);
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps all expected reference IDs rather than only the first", () => {
|
||||
const tag = (key: string) => `@{value('${JSON.stringify({ key, label: key })}')}`;
|
||||
expect(diagnose(["A", "B"], "eq", [tag("A"), tag("B")])?.rules[0]?.matched).toBe(true);
|
||||
});
|
||||
it("evaluates nested OR / AND groups and does not infer False from an incomplete execution tree", () => {
|
||||
const result = explainConditionBranches([
|
||||
{ id: "source", name: "source", type: "code", status: "COMPLETED", output: { value: 10 } },
|
||||
branch({ condition: "OR", filters: [{ filters: [{ key: choose(), compare: "eq", value: 1 }] }, { filters: [{ key: choose(), compare: "gt", value: 5 }] }] }),
|
||||
])[0];
|
||||
expect(result?.evaluation).toBe(true);
|
||||
expect(result?.hasSkippedTasks).toBe(false);
|
||||
expect(result?.summary).toContain("执行树是否完整");
|
||||
});
|
||||
it("does not claim skipped tasks for a still-running condition or absent upstream evidence", () => {
|
||||
const running = explainConditionBranches([branch({ filters: [{ key: choose(), compare: "eq", value: 1 }] }, "RUNNING")])[0];
|
||||
expect(running?.evaluation).toBeNull();
|
||||
expect(running?.rules[0]?.matched).toBeNull();
|
||||
expect(running?.hasSkippedTasks).toBe(false);
|
||||
expect(running?.summary).toContain("无法确定");
|
||||
});
|
||||
it("resolves nested branches against the matching loop instance", () => {
|
||||
const tree = [1, 10].map((value, index) => ({ id: `loop-${index}`, name: "loop", type: "every", status: "COMPLETED", currentLoopPath: String(index), children: [
|
||||
{ id: `source-${index}`, name: "source", type: "code", status: "COMPLETED", output: { value } },
|
||||
{ ...branch({ filters: [{ key: choose(), compare: "gt", value: 5 }] }), id: `condition-${index}` },
|
||||
] }));
|
||||
const result = explainConditionBranches(tree);
|
||||
expect(result.map(item => item.rules[0]?.actualValue)).toEqual([1, 10]);
|
||||
expect(result.map(item => item.evaluation)).toEqual([false, true]);
|
||||
});
|
||||
it("recognizes an executed child by parentId even if the flat response order differs", () => {
|
||||
const condition = branch({ filters: [] });
|
||||
const result = explainConditionBranches([
|
||||
{ id: "child", name: "child", parentId: condition.id, type: "http", status: "COMPLETED" },
|
||||
condition,
|
||||
]);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
it("diagnoses missing upstream property when property is absent from outputs", () => {
|
||||
const tree: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec-trigger",
|
||||
name: "trigger_1",
|
||||
label: "单据审批事件触发器",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
status: "COMPLETED",
|
||||
output: { code: "ZJ-001" },
|
||||
},
|
||||
{
|
||||
id: "exec-detail",
|
||||
name: "action_detail",
|
||||
label: "查询单据详情",
|
||||
type: "flow-detail",
|
||||
status: "COMPLETED",
|
||||
output: {
|
||||
approvers: ["ID_YANGJIE"],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "exec-condition",
|
||||
name: "control_1",
|
||||
label: "条件节点",
|
||||
type: "condition",
|
||||
status: "COMPLETED",
|
||||
combineFilters: {
|
||||
filters: [
|
||||
{
|
||||
filters: [
|
||||
{
|
||||
key: "@{choose('{\"key\":\"action_detail\",\"properties\":[{\"key\":\"currentApprovers\",\"label\":\"审批人\"}]}')}",
|
||||
value: ["@{value('{\"key\":\"ID_YANGJIE\",\"label\":\"杨洁\"}')}"],
|
||||
compare: "eq",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
tasks: [
|
||||
{
|
||||
name: "action_http",
|
||||
label: "自动审批",
|
||||
type: "http",
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
];
|
||||
|
||||
const res = explainConditionBranches(tree);
|
||||
expect(res).toHaveLength(1);
|
||||
expect(res[0].conditionNodeName).toBe("control_1");
|
||||
expect(res[0].hasSkippedTasks).toBe(true);
|
||||
expect(res[0].rules[0].isMissing).toBe(true);
|
||||
expect(res[0].rules[0].upstreamProp).toBe("currentApprovers");
|
||||
expect(res[0].summary).toContain("条件字段脱节");
|
||||
});
|
||||
|
||||
it("diagnoses value mismatch when upstream property exists but values differ", () => {
|
||||
const tree: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec-trigger",
|
||||
name: "trigger_1",
|
||||
label: "单据审批事件触发器",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
status: "COMPLETED",
|
||||
output: {
|
||||
userInfo: "ID_ZANGKEXIN",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "exec-condition",
|
||||
name: "control_1",
|
||||
label: "条件节点",
|
||||
type: "condition",
|
||||
status: "COMPLETED",
|
||||
combineFilters: {
|
||||
filters: [
|
||||
{
|
||||
filters: [
|
||||
{
|
||||
key: "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"userInfo\",\"label\":\"待处理人\"}]}')}",
|
||||
value: "@{value('{\"key\":\"ID_YANGJIE\",\"label\":\"杨洁\"}')}",
|
||||
compare: "eq",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
tasks: [
|
||||
{
|
||||
name: "action_http",
|
||||
label: "自动审批",
|
||||
type: "http",
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
];
|
||||
|
||||
const res = explainConditionBranches(tree);
|
||||
expect(res).toHaveLength(1);
|
||||
expect(res[0].hasSkippedTasks).toBe(true);
|
||||
expect(res[0].rules[0].isMissing).toBe(false);
|
||||
expect(res[0].rules[0].matched).toBe(false);
|
||||
expect(res[0].rules[0].actualValue).toBe("ID_ZANGKEXIN");
|
||||
});
|
||||
|
||||
it("returns empty diagnosis when child task was executed successfully", () => {
|
||||
const tree: WorkflowTaskExecution[] = [
|
||||
{
|
||||
id: "exec-condition",
|
||||
name: "control_1",
|
||||
label: "条件节点",
|
||||
type: "condition",
|
||||
status: "COMPLETED",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_http",
|
||||
label: "自动审批",
|
||||
type: "http",
|
||||
},
|
||||
],
|
||||
} as any,
|
||||
{
|
||||
id: "exec-http",
|
||||
name: "action_http",
|
||||
label: "自动审批",
|
||||
type: "http",
|
||||
status: "COMPLETED",
|
||||
},
|
||||
];
|
||||
|
||||
const res = explainConditionBranches(tree);
|
||||
expect(res).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types.js";
|
||||
export * from "./explain.js";
|
||||
@@ -0,0 +1,23 @@
|
||||
export interface ConditionRuleExplanation {
|
||||
leftLabel: string;
|
||||
upstreamNode: string;
|
||||
upstreamProp: string;
|
||||
operator: string;
|
||||
operatorLabel: string;
|
||||
expectedValue: any;
|
||||
actualValue: any;
|
||||
isMissing: boolean;
|
||||
matched: boolean | null;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ConditionBranchExplanation {
|
||||
conditionNodeId: string;
|
||||
conditionNodeName: string;
|
||||
conditionNodeLabel: string;
|
||||
hasSkippedTasks: boolean;
|
||||
evaluation: boolean | null;
|
||||
skippedTaskNames: string[];
|
||||
rules: ConditionRuleExplanation[];
|
||||
summary: string;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
SYSTEM_WORKFLOW_ACTION_ENUMS,
|
||||
translateWorkflowAction,
|
||||
isWorkflowActionCode,
|
||||
matchWorkflowAction,
|
||||
resolveWorkflowEnumOptions,
|
||||
} from "../services.js";
|
||||
import { analyzeWorkflow } from "./analysis/index.js";
|
||||
|
||||
describe("Workflow Action Enums & Diagnostics", () => {
|
||||
it("contains 18 standard system notification action enums", () => {
|
||||
expect(SYSTEM_WORKFLOW_ACTION_ENUMS).toHaveLength(18);
|
||||
const codes = SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => item.code);
|
||||
expect(codes).toContain("flow.rejected");
|
||||
expect(codes).toContain("flow.paid");
|
||||
expect(codes).toContain("backlog.approving");
|
||||
expect(codes).toContain("backlog.paying");
|
||||
expect(codes).toContain("backlog.receiving");
|
||||
expect(codes).toContain("freeflow.retract");
|
||||
});
|
||||
|
||||
it("translates workflow action codes accurately", () => {
|
||||
expect(translateWorkflowAction("flow.rejected")).toBe("被驳回");
|
||||
expect(translateWorkflowAction("flow.paid")).toBe("已支付/审批完成");
|
||||
expect(translateWorkflowAction("backlog.approving")).toBe("待审批");
|
||||
expect(translateWorkflowAction("unknown.action")).toBe("unknown.action");
|
||||
expect(translateWorkflowAction(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("checks if a code is a known workflow action", () => {
|
||||
expect(isWorkflowActionCode("flow.rejected")).toBe(true);
|
||||
expect(isWorkflowActionCode("flow.paid")).toBe(true);
|
||||
expect(isWorkflowActionCode("custom.action")).toBe(false);
|
||||
});
|
||||
|
||||
it("matches workflow action by code or label", () => {
|
||||
const matchByLabel = matchWorkflowAction("被驳回");
|
||||
expect(matchByLabel?.code).toBe("flow.rejected");
|
||||
|
||||
const matchByCode = matchWorkflowAction("flow.rejected");
|
||||
expect(matchByCode?.label).toBe("被驳回");
|
||||
|
||||
expect(matchWorkflowAction("不存在的动作")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves fallback options when client is undefined", async () => {
|
||||
const options = await resolveWorkflowEnumOptions(undefined, "action");
|
||||
expect(options).toHaveLength(18);
|
||||
expect(options.find((o) => o.code === "flow.rejected")?.label).toBe("被驳回");
|
||||
});
|
||||
|
||||
it("detects DEADLOCK_CONDITION_STATE_FILTER when condition matches state against '被驳回'", () => {
|
||||
const wf = {
|
||||
id: "wf-cond-deadlock",
|
||||
label: "单据条件判断",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_1",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
label: "单据审批事件触发器",
|
||||
},
|
||||
{
|
||||
name: "control_1",
|
||||
type: "condition",
|
||||
label: "条件节点",
|
||||
combineFilters: {
|
||||
condition: "or",
|
||||
filters: [
|
||||
{
|
||||
condition: "and",
|
||||
filters: [
|
||||
{
|
||||
key: "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"state\",\"label\":\"审批状态\",\"type\":\"TEXT\"}],\"label\":\"单据审批事件触发器.审批状态\"}')}",
|
||||
compare: "eq",
|
||||
value: "被驳回",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
tasks: [
|
||||
{
|
||||
name: "stop_1",
|
||||
type: "stop",
|
||||
label: "终止",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("DEADLOCK_CONDITION_STATE_FILTER");
|
||||
const diag = result.diagnostics.find((d) => d.code === "DEADLOCK_CONDITION_STATE_FILTER");
|
||||
expect(diag?.severity).toBe("error");
|
||||
expect(diag?.message).toContain("单据审批状态 [state]");
|
||||
expect(diag?.message).toContain("flow.rejected");
|
||||
});
|
||||
|
||||
it("detects INVALID_ACTION_ENUM_TEXT_VALUE when condition matches action with plain text '被驳回'", () => {
|
||||
const wf = {
|
||||
id: "wf-action-text",
|
||||
label: "单据通知类型错误文本比较",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "control_2",
|
||||
type: "condition",
|
||||
label: "条件节点",
|
||||
combineFilters: {
|
||||
condition: "or",
|
||||
filters: [
|
||||
{
|
||||
condition: "and",
|
||||
filters: [
|
||||
{
|
||||
key: "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"action\",\"label\":\"通知类型\",\"type\":\"ENUM\",\"thirdId\":\"action\"}],\"label\":\"单据审批事件触发器.通知类型\"}')}",
|
||||
compare: "eq",
|
||||
value: "被驳回",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
tasks: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("INVALID_ACTION_ENUM_TEXT_VALUE");
|
||||
const diag = result.diagnostics.find((d) => d.code === "INVALID_ACTION_ENUM_TEXT_VALUE");
|
||||
expect(diag?.severity).toBe("error");
|
||||
expect(diag?.message).toContain("纯文本");
|
||||
});
|
||||
|
||||
it("passes cleanly when condition correctly uses action enum macro @value(flow.rejected)", () => {
|
||||
const wf = {
|
||||
id: "wf-valid-action",
|
||||
label: "单据通知类型正确配置",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "control_3",
|
||||
type: "condition",
|
||||
label: "条件节点",
|
||||
combineFilters: {
|
||||
condition: "or",
|
||||
filters: [
|
||||
{
|
||||
condition: "and",
|
||||
filters: [
|
||||
{
|
||||
key: "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"action\",\"label\":\"通知类型\",\"type\":\"ENUM\",\"thirdId\":\"action\"}],\"label\":\"单据审批事件触发器.通知类型\"}')}",
|
||||
compare: "eq",
|
||||
value: "@{value('{\"key\":\"flow.rejected\",\"label\":\"被驳回\"}')}",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
tasks: [
|
||||
{
|
||||
name: "stop_1",
|
||||
type: "stop",
|
||||
label: "终止",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).not.toContain("DEADLOCK_CONDITION_STATE_FILTER");
|
||||
expect(codes).not.toContain("INVALID_ACTION_ENUM_TEXT_VALUE");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* 合思/易快报工作流(Piper / EASO)单据审批事件触发器通知类型标准系统枚举
|
||||
* 对应底层接口:POST /api/easo/dsl/condition/select/EKB_ENUM?thirdId=action
|
||||
*/
|
||||
|
||||
export interface WorkflowActionEnumItem {
|
||||
code: string;
|
||||
label: string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export const SYSTEM_WORKFLOW_ACTION_ENUMS: readonly WorkflowActionEnumItem[] = [
|
||||
{ code: "flow.rejected", label: "被驳回", name: "被驳回", description: "单据审批被驳回时触发" },
|
||||
{ code: "flow.paid", label: "已支付/审批完成", name: "已支付/审批完成", description: "单据已支付或终审完成时触发" },
|
||||
{ code: "backlog.approving", label: "待审批", name: "待审批", description: "单据进入审批待办节点时触发" },
|
||||
{ code: "backlog.paying", label: "待支付", name: "待支付", description: "单据进入待支付节点时触发" },
|
||||
{ code: "backlog.sending", label: "待寄送", name: "待寄送", description: "单据需要寄送发票/材料时触发" },
|
||||
{ code: "backlog.receiving", label: "待收单", name: "待收单", description: "财务待收单时触发" },
|
||||
{ code: "backlog.processed", label: "待办已处理", name: "待办已处理", description: "待办任务已处理完成时触发" },
|
||||
{ code: "backlog.payment", label: "支付中", name: "支付中", description: "银行出纳支付处理中时触发" },
|
||||
{ code: "freeflow.retract", label: "单据撤回", name: "单据撤回", description: "发起人主动撤回单据时触发" },
|
||||
{ code: "freeflow.delete", label: "单据删除", name: "单据删除", description: "单据被彻底删除时触发" },
|
||||
{ code: "freeflow.mention", label: "被@", name: "被@", description: "单据评论或流转中被@提及" },
|
||||
{ code: "freeflow.comment", label: "评论", name: "评论", description: "单据新增审批意见或评论" },
|
||||
{ code: "freeflow.remind", label: "催办", name: "催办", description: "发起人对审批人执行催办" },
|
||||
{ code: "freeflow.carbonCopy", label: "抄送", name: "抄送", description: "单据到达抄送节点或被抄送" },
|
||||
{ code: "freeflow.alter", label: "申请单变更", name: "申请单变更", description: "借款/申请单内容发生变更" },
|
||||
{ code: "freeflow.ticketReserve", label: "审批通过(已开通【差旅管理】的用户)", name: "审批通过(已开通【差旅管理】的用户)", description: "开通差旅模块的用户审批通过预订车票/酒店" },
|
||||
{ code: "freeflow.print", label: "打印提醒", name: "打印提醒", description: "单据触发打印或需要打印提醒" },
|
||||
{ code: "timeout.remind", label: "超时提醒", name: "超时提醒", description: "审批节点到达超时时限自动提醒" },
|
||||
] as const;
|
||||
|
||||
export type SystemWorkflowActionCode = (typeof SYSTEM_WORKFLOW_ACTION_ENUMS)[number]["code"];
|
||||
|
||||
export const WORKFLOW_ACTION_MAP: Record<string, string> = Object.fromEntries(
|
||||
SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => [item.code, item.label])
|
||||
);
|
||||
|
||||
export const WORKFLOW_ACTION_REVERSE_MAP: Record<string, string> = Object.fromEntries(
|
||||
SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => [item.label, item.code])
|
||||
);
|
||||
|
||||
export function translateWorkflowAction(action?: string): string | undefined {
|
||||
if (!action) return undefined;
|
||||
return WORKFLOW_ACTION_MAP[action] || action;
|
||||
}
|
||||
|
||||
export function isWorkflowActionCode(code: string): boolean {
|
||||
return code in WORKFLOW_ACTION_MAP;
|
||||
}
|
||||
|
||||
export function matchWorkflowAction(query: string): WorkflowActionEnumItem | undefined {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return undefined;
|
||||
return SYSTEM_WORKFLOW_ACTION_ENUMS.find(
|
||||
(item) => item.code.toLowerCase() === trimmed.toLowerCase() || item.label === trimmed || item.name === trimmed
|
||||
);
|
||||
}
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user