diff --git a/.agents/README.md b/.agents/README.md index f2a015d..fb7b970 100644 --- a/.agents/README.md +++ b/.agents/README.md @@ -10,12 +10,15 @@ This directory (`.agents/`) maintains modular configuration, skills, and guideli .agents/ ├── README.md # This document: architecture & trigger policy ├── skills.json # Declarative skill path and exclusion filters +├── skills/ # Project-scoped Agent skills +│ └── repo-gh/SKILL.md # Markdown 实体文件驱动 GitHub CLI 与 Git 操作规范 └── rules/ # Modular, domain-specific rule definitions (trigger: "manual") ├── production-safety.md # 生产环境安全红线、免读源码与写操作防护原则 ├── cli-protocol.md # CLI stdout/stderr stream contract & exit codes ├── tenant-and-credential.md # 多租户凭据管理、协助链接与单据检索最佳实践 ├── testing-and-dev-hygiene.md # 单元测试规范、非交互环境防护与发布流程 - └── typescript-style.md # ESM, explicit .js imports, and TypeScript styles + ├── typescript-style.md # ESM, explicit .js imports, and TypeScript styles + └── windows-development.md # Windows 跨平台协作、全小写分支、LF换行与大文件拦截守则 ``` --- @@ -40,7 +43,9 @@ trigger: "manual" --- -## 3. Modular Rules Inventory +## 3. Modular Rules & Skills Inventory + +### Rules (`.agents/rules/`) | Rule File | Domain / Scope | Key Responsibilities | | :--- | :--- | :--- | @@ -49,12 +54,20 @@ trigger: "manual" | [`rules/cli-protocol.md`](./rules/cli-protocol.md) | `src/cli/**/*.ts` | 严格 `stdout` JSON vs `stderr` 诊断输出契约、200KB 大报文防爆拦截、退出码规范。 | | [`rules/testing-and-dev-hygiene.md`](./rules/testing-and-dev-hygiene.md) | 测试与流程 | `bun:test` 规范、测试环境禁止阻塞交互输入、`bun run check` + `bun test` 门禁与发布更新规范。 | | [`rules/typescript-style.md`](./rules/typescript-style.md) | `src/**/*.ts` | ES Modules、强制携带 `.js` 后缀、Zod 运行时校验与代码规范。 | +| [`rules/windows-development.md`](./rules/windows-development.md) | 全局 / 跨平台 | Windows 跨平台协作、全小写分支强校验、换行符 LF、符号链接开启与大文件/保留字拦截守则。 | + +### Skills (`.agents/skills/`) + +| Skill Directory | Target Tool | Key Responsibilities | +| :--- | :--- | :--- | +| [`skills/repo-gh/`](./skills/repo-gh/SKILL.md) | `gh` / `git` | **Markdown 实体先行(Markdown-First)**、`.drafts/` 隐藏草稿驱动、杜绝内联长文本、统一简体中文规范。 | --- ## 4. Usage Instructions for AI Agents - **Production Operations**: Always consult [`rules/production-safety.md`](./rules/production-safety.md) and [`rules/tenant-and-credential.md`](./rules/tenant-and-credential.md) before interacting with configured enterprise tenants. +- **Git & GitHub Operations**: Always consult [`skills/repo-gh/SKILL.md`](./skills/repo-gh/SKILL.md) and [`rules/windows-development.md`](./rules/windows-development.md) for branch naming, commits, PR creation, and issue management. - **CLI Development**: When adding or refactoring CLI commands under `src/cli/`, consult [`rules/cli-protocol.md`](./rules/cli-protocol.md). - **Writing Tests**: When creating or modifying tests, consult [`rules/testing-and-dev-hygiene.md`](./rules/testing-and-dev-hygiene.md). - **TypeScript & Modules**: When adding new TypeScript files or resolving local imports, refer to [`rules/typescript-style.md`](./rules/typescript-style.md). diff --git a/.agents/rules/windows-development.md b/.agents/rules/windows-development.md new file mode 100644 index 0000000..6fa2ee6 --- /dev/null +++ b/.agents/rules/windows-development.md @@ -0,0 +1,107 @@ +--- +name: windows-development +description: Windows 开发者与 Agent 在本项目中的跨平台协作规范与避坑守则。 +globs: "**/*" +trigger: "manual" +--- + +# Windows 环境协作与开发守则 + +本守则面向在 Windows 系统上进行开发的人类工程师与 AI Agent。由于 Windows 操作系统(NTFS 文件系统、换行符机制、路径长度限制)与 GitHub Linux 服务器及 macOS 存在底层行为差异,参与本项目的所有开发者及 Agent 必须严格遵守以下守则。 + +--- + +## 1. 首次克隆与 Hooks 强制激活 + +拉取或克隆项目后,**必须第一时间激活 Git Hooks**: + +```powershell +# 在 Windows 终端(PowerShell / CMD / Git Bash 均可)执行: +git config core.hooksPath .githooks +# 或直接运行配套初始化脚本: +powershell -ExecutionPolicy Bypass -File .githooks/setup.ps1 +``` + +> **说明**:此命令为原生 Git 配置,不依赖任何第三方脚本,且跨平台通用。 + +--- + +## 2. 分支命名铁律:必须且只能全小写 + +* **核心背景**: + Windows NTFS 文件系统与 Windows Git 对大小写**不敏感**(认为 `feat/UserLogin` 和 `feat/userlogin` 是同一个),但 GitHub 远程服务器(Linux)**严格区分大小写**。若分支名混用大写字母,极易在团队拉取、合并及检出时触发致命的引用混乱。 +* **规则要求**: + 1. 所有新建分支必须**一律全小写**,使用短横线 `-` 或斜杠 `/` 分隔单词。 + 2. 合法示例:`feat/user-login`、`fix/token-expired`、`chore/update-deps`。 + 3. 违规示例:`feat/UserLogin`、`fix/TokenExpired`、`FEAT/add-rule`(**将被本地 Git Hook 直接拦截并阻止 commit 和 push**)。 +* **快速修正**: + 若不慎创建了包含大写字母的分支,在提交前直接重命名即可: + ```bash + git branch -m feat/your-lowercase-branch-name + ``` + +--- + +## 3. 长路径支持开启 (Long Paths) + +* **核心背景**: + Windows 传统 Win32 API 存在 260 字符最大路径限制(MAX_PATH)。深度嵌套的目录或依赖文件极易触发 `Filename too long` 导致检出/拉取代码崩溃。 +* **规则要求**: + 建议每位 Windows 开发者在全局开启 Git 的长路径支持(将限制提升至 32,767 字符): + ```powershell + git config --global core.longpaths true + ``` + +--- + +## 4. 换行符统一与防护 (LF vs CRLF) + +* **核心背景**: + 项目根目录已配置 `.gitattributes`,强制所有 Git Hooks、Shell 脚本及源码文本保持 `LF` 换行符。Windows Git 常见的自动转回车行为(`core.autocrlf = true`)会导致 Shell 脚本被篡改为 CRLF,从而在运行时报出 `\r: command not found`。 +* **激活与防护命令**: + 1. **关闭 Git 自动转回车(防患于未然)**: + ```powershell + # 针对当前仓库关闭自动转回车: + git config core.autocrlf false + # (可选)也可以全局关闭:git config --global core.autocrlf false + ``` + 2. **一键重正规化本地工作区(针对已有 Clone)**: + 若你在 `.gitattributes` 生效前就已克隆代码,执行此命令可强制 Git 依据最新规则将本地文件重新正规化为 LF: + ```powershell + git add --renormalize . + ``` + 3. **编辑器规范**: + IDE/编辑器(VS Code、Cursor、Windsurf 等)默认换行符请设置为 `LF`,严禁通过格式化插件或脚本将仓库文件批量转为 CRLF。 + +--- + +## 5. 符号链接支持开启 (Symlinks) + +* **核心背景**: + Windows 默认安全限制要求必须具有特殊权限才允许创建软链接,否则 Git 会将符号链接检出为普通纯文本文件,导致路径读取失败。 +* **规则要求**: + 1. 打开 Windows 设置 -> 系统 -> 开发者选项,开启 **“开发者模式”**(无需管理员提权)。 + 2. 在仓库中开启 Git 软链接支持: + ```powershell + git config core.symlinks true + ``` + +--- + +## 6. 文件名合法性与大文件防护 + +* **文件名字符与保留字限制**: + 严禁创建包含 Windows 非法字符(`:`, `*`, `?`, `"`, `<`, `>`, `|`)以及 Windows 保留设备名称(`CON`, `PRN`, `AUX`, `NUL`, `COM1-9`, `LPT1-9`)的文件。本地 `pre-commit` 会进行全量拦截。 +* **单文件体积限制(15MB)**: + 为防止 Git 仓库历史体积不可逆膨胀,严禁提交单文件超过 **15MB** 的大文件。编译后的安装包或大体积资源请通过 GitHub Releases 附件发布。 +* **敏感信息与密钥防护**: + 项目根目录 `.gitignore` 已强制忽略 `.env`、`*.pem`、`*.key`、`enterprises/*.json` 等敏感凭据与密钥文件。严禁使用 `git add -f` 强制提交凭据。 + +--- + +## 7. 主分支保护与合并路径 + +* **规则要求**: + 1. 严禁直接在 `main` / `master` 分支上进行开发与 commit。 + 2. 严禁向远程 `origin/main` 直接执行 push 操作。 + 3. 唯一合法的代码合入路径:在全小写特性分支上开发 -> 推送到远程特性分支 -> 发起 Pull Request (PR) -> 经由 CI 校验与审查后,通过 GitHub PR 流程(例如使用 `gh pr merge` 或自动化机制)完成远端合入。严禁绕过 PR 直推主分支。 diff --git a/.agents/skills/repo-gh/SKILL.md b/.agents/skills/repo-gh/SKILL.md new file mode 100644 index 0000000..2e03e4b --- /dev/null +++ b/.agents/skills/repo-gh/SKILL.md @@ -0,0 +1,101 @@ +--- +name: repo-gh +description: 本项目专用的 GitHub CLI 与 Git 操作规范。强调 Markdown 实体文件驱动(--body-file / -F),杜绝命令行内联多行长文本,统一使用简体中文。 +--- + +# repo-gh 项目级 GitHub 操作规范 + +本 Skill 为当前项目下 Agent 和开发者调用 `gh` CLI 及 `git` 命令的标准行为准则。核心原则:**Markdown 实体先行(Markdown-First)、杜绝命令行内联长文本、统一简体中文规范**。 + +--- + +## 1. 核心铁律:Markdown 文件先行 (Markdown-First) + +在所有涉及多行文本的 GitHub 操作中,**绝对禁止**在命令行中直接使用内联长字符串拼接(如 `--body "..."` 或多次 `-m "..."`)。必须一律先在本地落盘 `.md` 实体文件,再通过文件路径参数传递。 + +所有中间 Markdown 实体文件**统一落盘至项目根目录的 `.drafts/` 隐藏目录**(该目录已被 `.gitignore` 自动忽略,不污染远程代码库): +- Commit 说明:`.drafts/commit-msg.md` +- PR 正文说明:`.drafts/pr-body.md` +- Issue 描述草稿:`.drafts/issue-.md` + +### 违规做法(严禁): +```bash +# 错误:易触发 shell 引号转义冲突、换行丢失及日志排版混乱 +gh issue create --title "..." --body "第一行\n第二行..." +git commit -m "feat: ..." -m "详细多行说明..." +gh pr create --title "..." --body "多行长文本..." +``` + +### 标准做法(强制): +```bash +# 正确:本地在 .drafts/ 落盘 Markdown 文件,通过文件参数传参 +gh issue create --title "..." --body-file .drafts/issue.md +git commit -F .drafts/commit-msg.md +gh pr create --title "..." --body-file .drafts/pr-body.md +``` + +--- + +## 2. Issue 创建规范 + +创建 GitHub Issue 时,必须遵循以下步骤: + +1. **本地编写 Markdown 文件**: + 在 `.drafts/` 目录下创建结构化文档(包含:问题描述、复现步骤、报错信息、原因分析、修复建议)。 +2. **规范语言**: + 必须使用专业清晰的**简体中文**撰写标题与正文。 +3. **执行创建**: + ```bash + gh issue create --title "<简明中文标题>" --body-file .drafts/issue.md + ``` +4. **清理临时文件**: + 创建完成后,及时清理或在 `.drafts/` 中归档。 + +--- + +## 3. Git Commit 规范 + +提交 Git 变更说明时: + +1. **单行提交**:常规简要改动直接使用 `git commit -m "type: 简述"`(遵循 Conventional Commits:`feat:`、`fix:`、`ci:`、`docs:`、`refactor:`、`chore:`)。 +2. **多行详细提交**:凡包含背景阐述、破坏性变动说明或详细清单的多行 Commit,必须先将内容写入 `.drafts/` 目录中的文本文件,再通过文件参数提交: + ```bash + git commit -F .drafts/commit-msg.md + ``` + +--- + +## 4. Pull Request 规范 + +发起 Pull Request 时: + +1. **对齐 PR 模板**: + 参考仓库中的 `.github/pull_request_template.md` 结构组织正文(关联 Issue、变更背景与概述、分类、影响范围、验证测试记录)。 +2. **本地落盘 PR 说明文件**: + 在 `.drafts/` 下编写本地 `pr-body.md`。 +3. **执行创建**: + ```bash + gh pr create --title "type: 简明中文标题" --body-file .drafts/pr-body.md + ``` +4. **合并与清理分支**: + PR 评审通过且 CI 门禁检查全绿后,通过命令行执行自动化合入并删除远端与本地分支: + ```bash + gh pr checks --watch + gh pr merge --merge --delete-branch + ``` + +--- + +## 5. 自动化数据查询规范 + +在非交互式或脚本化调用 `gh` 读取数据时: + +- 避免解析面向人类的终端表格文本,优先追加 `--json <字段1,字段2,...>` 获取结构化数据。 +- 结合 `--jq '<表达式>'` 进行原地过滤,提升调用效率与稳定性。 + +--- + +## 6. 语言与沟通规范 + +- 本仓库所有 Issue、PR、Commit 说明及技术讨论统一使用**简体中文**。 +- 描述客观清晰,涉及代码改动时附带明确的文件路径或复现步骤。 diff --git a/.drafts/.gitkeep b/.drafts/.gitkeep new file mode 100644 index 0000000..847173a --- /dev/null +++ b/.drafts/.gitkeep @@ -0,0 +1 @@ +# Local drafts placeholder diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4bf3dda --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# 统一跨平台换行符规范 +* text=auto + +# Git Hooks 与 Shell 脚本必须强制使用 LF 换行符(防止 Windows 下报 '\r: command not found') +.githooks/* text eol=lf +*.sh text eol=lf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..5e37a3e --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,124 @@ +#!/bin/sh +# 跨平台 pre-commit 钩子: +# 1. 禁止在主分支 (main/master) 直接提交代码 +# 2. 强制分支命名全小写(规避 Windows NTFS 大小写不敏感冲突) +# 3. 拦截暂存区单文件超过 15MB 的超大文件提交(防仓库体积膨胀) +# 4. 拦截 Windows 非法文件名与系统保留设备名(保护 Windows 检出兼容性) + +current_branch=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null) + +# 1. 校验受保护的主分支 +if [ "$current_branch" = "main" ] || [ "$current_branch" = "master" ]; then + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 严禁直接在主分支 ($current_branch) 上进行 commit!" + echo "======================================================================" + echo "📌 团队协作规范:" + echo " 1. 主分支受保护,禁止直接开发与提交代码。" + echo " 2. 所有新功能与 Bug 修复必须在特性分支(如 feat/*, fix/*, chore/*)进行。" + echo " 3. 代码合并必须通过 GitHub Pull Request (PR) 经由审查后在远端合入。" + echo "" + echo "💡 快速解决指引:" + echo " 创建并切换到新特性分支(工作区现有改动会自动带入):" + echo " git checkout -b feat/your-feature-name" + echo " 然后重新执行 git commit 即可。" + echo "======================================================================" + echo "" + exit 1 +fi + +# 2. 校验分支名是否包含大写字母(Windows/macOS 大小写不敏感安全策略) +if echo "$current_branch" | grep -q '[A-Z]'; then + lowercase_branch=$(echo "$current_branch" | tr '[:upper:]' '[:lower:]') + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 分支名必须全小写,禁止包含大写字母!" + echo "======================================================================" + echo "📌 当前分支: $current_branch" + echo "📌 规范说明:" + echo " Windows 系统文件与 Git 分支大小写不敏感,而 Linux/GitHub 严格敏感。" + echo " 为彻底杜绝跨平台引用冲突,所有分支命名必须统一采用全小写 + 短横线格式。" + echo "" + echo "💡 快速解决指引(执行以下命令将当前分支重命名为全小写):" + echo " git branch -m $lowercase_branch" + echo " 然后重新执行 git commit 即可(暂存区与代码改动均完全保留)。" + echo "======================================================================" + echo "" + exit 1 +fi + +# 3. 校验暂存区文件(文件体积与 Windows 文件名合规性) +MAX_FILE_SIZE=15728640 # 15MB in bytes + +staged_files=$(git diff --cached --name-only --diff-filter=ACM) + +if [ -n "$staged_files" ]; then + OLD_IFS="$IFS" + IFS=' +' + for file in $staged_files; do + # 3.1 校验单文件体积上限 (15MB) + if [ -f "$file" ]; then + file_size=$(wc -c < "$file" 2>/dev/null | tr -d ' ') + if [ -n "$file_size" ] && [ "$file_size" -gt "$MAX_FILE_SIZE" ]; then + size_mb=$(awk "BEGIN {printf \"%.2f\", $file_size/1048576}") + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 暂存区存在超过 15MB 的超大文件!" + echo "======================================================================" + echo "📌 违规文件: $file (${size_mb} MB > 15 MB)" + echo "📌 规范说明:为避免仓库体积永久膨胀,严禁在源码仓库中提交超大文件。" + echo "💡 解决办法:" + echo " 1. 将大文件移出代码仓库,并在 .gitignore 中声明忽略;" + echo " 2. 安装包或可执行二进制产物请通过 GitHub Releases 附件发布。" + echo "======================================================================" + echo "" + IFS="$OLD_IFS" + exit 1 + fi + fi + + # 3.2 校验 Windows 文件名合法性(字符与设备保留字) + filename=$(basename "$file") + + # 校验 Windows 非法特殊字符: : * ? " < > | + case "$filename" in + *[\:\*\?\"\<\>\|]*) + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 文件名包含 Windows 非法字符!" + echo "======================================================================" + echo "📌 违规文件: $file" + echo "📌 规范说明:Windows 文件系统严禁在文件名中使用 : * ? \" < > | 字符。" + echo " 在 macOS/Linux 提交此类文件会导致 Windows 用户克隆或拉取时发生崩溃。" + echo "💡 请重命名该文件后重新提交。" + echo "======================================================================" + echo "" + IFS="$OLD_IFS" + exit 1 + ;; + esac + + # 校验 Windows 设备保留名: con, prn, aux, nul, com1-com9, lpt1-lpt9 + base_no_ext=$(echo "$filename" | sed -E 's/\.[^.]*$//' | tr '[:upper:]' '[:lower:]') + case "$base_no_ext" in + con|prn|aux|nul|com[1-9]|lpt[1-9]) + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 文件名使用了 Windows 系统保留设备名 ($filename)!" + echo "======================================================================" + echo "📌 违规文件: $file" + echo "📌 规范说明:CON, PRN, AUX, NUL, COM1-9, LPT1-9 是 Windows 遗留设备保留字。" + echo " 提交此类文件会导致 Windows 用户在检出代码时直接报错失败。" + echo "💡 请重命名该文件后重新提交。" + echo "======================================================================" + echo "" + IFS="$OLD_IFS" + exit 1 + ;; + esac + done + IFS="$OLD_IFS" +fi + +exit 0 diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..f9da492 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,59 @@ +#!/bin/sh +# 跨平台 pre-push 钩子: +# 1. 禁止直接向远程主分支 (main/master) 推送代码(强制走 GitHub PR) +# 2. 禁止向远程推送含大写字母的分支名(规避 Windows NTFS 大小写不敏感冲突) + +remote="$1" +url="$2" + +zero_oid="0000000000000000000000000000000000000000" + +while read -r local_ref local_oid remote_ref remote_oid; do + # 1. 拦截直接向主分支推送 + if [ "$remote_ref" = "refs/heads/main" ] || [ "$remote_ref" = "refs/heads/master" ]; then + # 兼容双远端镜像同步:如果是向 home (Gitea) 同步,且本地 commit 没有领先于 origin/main,允许同步 + if [ "$remote" = "home" ]; then + unpushed=$(git log origin/main.."$local_oid" --oneline 2>/dev/null) + if [ -z "$unpushed" ]; then + continue + fi + fi + + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 严禁直接向远程主分支 ($remote_ref) 推送代码!" + echo "======================================================================" + echo "📌 团队协作规范:" + echo " 1. 远程主分支代码只允许在 GitHub 上通过 Pull Request (PR) 审查合并。" + echo " 2. 严禁通过本地直接 push 到远程主分支(即使本地已完成 merge)。" + echo "" + echo "💡 推荐操作流:" + echo " 1. 将当前分支推送到远程特性分支:" + echo " git push -u origin " + echo " 2. 在终端发起 Pull Request (例如: gh pr create --body-file .drafts/pr-body.md)" + echo " 3. 经由 CI 校验与评审后完成合入 (例如: gh pr merge --merge --delete-branch)" + echo "======================================================================" + echo "" + exit 1 + fi + + # 2. 拦截推送包含大写字母的远程分支引用(跳过删除远程分支的情况) + if [ "$local_oid" != "$zero_oid" ] && echo "$remote_ref" | grep -q 'refs/heads/.*[A-Z]'; then + branch_name=${remote_ref#refs/heads/} + lowercase_branch=$(echo "$branch_name" | tr '[:upper:]' '[:lower:]') + echo "" + echo "======================================================================" + echo "❌ [Git Hook 拦截] 严禁推送包含大写字母的分支名到远端!" + echo "======================================================================" + echo "📌 目标分支: $branch_name" + echo "📌 规范说明:为规避 Windows 与 Linux 远端大小写冲突,远程分支必须为全小写。" + echo "💡 请重命名本地分支后再推送:" + echo " git branch -m $lowercase_branch" + echo " git push -u origin $lowercase_branch" + echo "======================================================================" + echo "" + exit 1 + fi +done + +exit 0 diff --git a/.githooks/setup.ps1 b/.githooks/setup.ps1 new file mode 100644 index 0000000..7bf5a8a --- /dev/null +++ b/.githooks/setup.ps1 @@ -0,0 +1,27 @@ +# 跨平台一键启用 Git Hooks 配置 (Windows PowerShell) + +Write-Host "⚙️ 正在配置 Git 协作规范..." -ForegroundColor Cyan + +# 1. 配置 Hooks 路径 +git config core.hooksPath .githooks + +# 2. 关闭当前仓库的 autocrlf,防止误转 CRLF +git config core.autocrlf false + +# 3. 开启符号链接支持 (Symlinks) +git config core.symlinks true + +if ($LASTEXITCODE -eq 0) { + Write-Host "✅ Git Hooks 与 Windows 规范配置成功!" -ForegroundColor Green + Write-Host "📌 保护规则已生效:" -ForegroundColor Yellow + Write-Host " - 禁止在 main 分支直接开发与 commit" + Write-Host " - 强制分支名称全小写(杜绝 Windows 大小写冲突)" + Write-Host " - 拦截超过 15MB 的单文件提交" + Write-Host " - 拦截包含 Windows 非法字符与保留设备名的文件" + Write-Host " - 禁止直接向远程 main 分支 push 代码(强制 GitHub PR 合并)" + Write-Host " - 换行符保持 LF (core.autocrlf = false)" + Write-Host " - 启用软链接支持 (core.symlinks = true)" +} else { + Write-Host "❌ 配置失败,请检查 git 是否已安装并加入 PATH。" -ForegroundColor Red + exit 1 +} diff --git a/.githooks/setup.sh b/.githooks/setup.sh new file mode 100755 index 0000000..4b8621d --- /dev/null +++ b/.githooks/setup.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# 跨平台一键启用 Git Hooks 配置 +# 适用环境:macOS / Linux / Windows Git Bash + +echo "⚙️ 正在配置 Git 协作规范..." +git config core.hooksPath .githooks +git config core.autocrlf false + +if [ $? -eq 0 ]; then + echo "✅ Git Hooks 与换行符配置成功!当前生效路径: $(git config core.hooksPath)" + echo "📌 保护规则已生效:" + echo " - 禁止在 main 分支直接开发与 commit" + echo " - 强制分支名称全小写(杜绝 Windows 大小写冲突)" + echo " - 拦截超过 15MB 的单文件提交" + echo " - 拦截包含 Windows 非法字符与保留设备名的文件" + echo " - 禁止直接向远程 main 分支 push 代码(强制 GitHub PR 合并)" + echo " - 换行符保持 LF (core.autocrlf = false)" +else + echo "❌ 配置失败,请检查 git 运行环境。" + exit 1 +fi diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..5b60a65 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,46 @@ +name: 功能建议 (Feature Request) +description: 为合思 / 易快报 CLI (hose-use) 与底层 SDK 提出新的功能建议或优化方案 +title: "[需求建议]: " +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + ### 欢迎提出功能建议 + 感谢为 **合思 / 易快报 CLI (hose-use) 与底层 SDK** 贡献想法! + > **语言规范**:本仓库统一使用**简体中文**进行需求交流与讨论。 + + - type: textarea + id: summary + attributes: + label: 功能建议概述 + description: 请用简洁清晰的简体中文概述该功能建议或期望改进点。 + placeholder: 例如:希望单据检索支持按金额区间过滤,或新增工作流执行明细导出... + validations: + required: true + + - type: textarea + id: context + attributes: + label: 业务背景与使用场景 + description: 该建议在什么具体业务场景下产生?(如单据检索与批量审批、工作流诊断与 MVEL 节点开通、自建应用治理、OpenAPI 鉴权与 HTTP 网关等) + placeholder: 描述当前操作流程中的痛点或不便之处... + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: 期望的实现方案或交互设计 + description: 您期望命令行或 SDK 如何运作?如果有 CLI 命令格式、参数设计、接口契约或逻辑思路,请在此说明。 + placeholder: 建议的命令格式(如 hose-use bill list --amount-min 1000)、接口入参或设计思路... + validations: + required: false + + - type: textarea + id: additional + attributes: + label: 补充信息与参考截图 + description: 可在此附上相关的设计草图、命令输出、脱敏日志或额外说明。 + validations: + required: false diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..49bb016 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,36 @@ +## 变更说明 + +> **语言规范提醒**:本仓库统一使用**简体中文**进行技术交流、Commit 记录与 PR 评审,请使用简体中文填写以下内容。 + +### 关联 Issue +- Fixes # +- Closes # + +### 变更背景与内容概述 + + +- + +### 变更分类 +- [ ] 🚀 新功能 (Feature) +- [ ] 🐛 缺陷修复 (Bugfix) +- [ ] 🛠️ 工程化基建与 CI/CD (Infra/CI) +- [ ] 📝 文档补充或更新 (Docs) +- [ ] 🎨 代码风格或性能重构 (Refactor) + +### 影响范围 +- [ ] CLI 命令行与交互命令 (`src/cli/`) +- [ ] 业务子域编排与 API 传输 (`src/domains/`) +- [ ] 核心基础设施与认证 (`src/core/`) +- [ ] 本地 HTTP Daemon 与 OpenAPI (`src/http/`) +- [ ] MCP Server 单工具网关 (`src/server.ts`) +- [ ] 打包分发与 Agent Skill (`src/packaging/`, `skills/hose-use`) +- [ ] 工程脚本与测试套件 (`scripts/`, `test/`) + +### 验证与测试记录 + + +- [ ] `bun test` 完整测试套件全部通过 +- [ ] `bun run check` 静态类型检查零错误 +- [ ] 架构分层约束测试通过 (`src/cli/architecture-boundaries.test.ts`) +- [ ] CLI / MCP / HTTP 实际运行验证通过 diff --git a/.gitignore b/.gitignore index 508c13f..9c047f2 100644 --- a/.gitignore +++ b/.gitignore @@ -48,3 +48,11 @@ data/ # Exports exports/ + +# Secrets & Private keys +*.pem +*.key + +# Local drafts for repo-gh & AI Agents +.drafts/* +!.drafts/.gitkeep diff --git a/AGENTS.md b/AGENTS.md index 5a22738..312c361 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -101,19 +101,24 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h ## 分支管理与 PR 合并规范(严格对标 seal-use) -为了保证代码变更可追溯、CI 校验完备与版本安全,本仓库实施**硬性约束(通过 Git pre-push hook 与 PR 流程双重卡点)**: +为了保证代码变更可追溯、CI 校验完备与版本安全,本仓库实施**硬性约束(通过 Git Hooks 与 PR 流程双重卡点)**: -1. **严禁直接推送到 `main` 分支**: - - 仓库已内置 `.git/hooks/pre-push` 钩子,本地直接执行 `git push origin main` 将被直接拦截拒绝; - - 日常功能开发、Bug 修复和版本发布必须且只能走独立分支; -2. **分支命名规范**: +1. **统一 Git Hooks 托管与主分支保护**: + - 仓库在 `.githooks/` 目录维护版本受控的跨平台 Git Hooks,首次克隆后请第一时间执行 `git config core.hooksPath .githooks` 或运行 `.githooks/setup.sh`(Windows 下运行 `.githooks/setup.ps1`); + - `pre-commit`:严禁在 `main`/`master` 分支直接 commit;强制分支命名全小写;拦截暂存区 >15MB 大文件;拦截 Windows 非法字符与系统保留设备名; + - `pre-push`:严禁直接向远程 `origin/main` 分支执行 push;严禁推送包含大写字母的分支名;日常功能开发、Bug 修复和版本发布必须且只能走特性分支与 PR; +2. **分支命名铁律(必须且只能全小写)**: - 特性分支:`feat/` 或 `codex/issue--` - - 发布分支:`codex/release-v` 或 `release/v` + - 发布分支:`release/v` 或 `codex/release-v` - 维护优化:`chore/`、`refactor/` 或 `fix/` -3. **Pull Request 提交流程**: + - **严禁包含大写字母**(Windows NTFS 大小写不敏感会导致与 Linux/GitHub 引用混乱,违规将被 Git Hooks 拦截拒绝); +3. **Pull Request 提交流程(Markdown 实体先行与统一简体中文)**: - 本地必须验证:`bun test && bun run check`(全绿方可提交); + - **Markdown-First 铁律**:严禁在命令行中使用内联多行字符串拼接(杜绝 `--body "..."` 与多重 `-m`),所有说明统一落盘至根目录隐藏草稿目录 `.drafts/`; + - 编写 Commit 说明:多行详细 Commit 写入 `.drafts/commit-msg.md`,执行 `git commit -F .drafts/commit-msg.md`; + - 编写 PR 说明:在 `.drafts/pr-body.md` 编写(对齐 `.github/pull_request_template.md`,统一**简体中文**); - 推送分支至远端:`git push origin `; - - 发起 PR:`gh pr create --base main --head --title "..." --body "..."`(如有对应 Issue 需关联 `Fixes #...`); + - 发起 PR:`gh pr create --base main --head --title "type: 简明中文标题" --body-file .drafts/pr-body.md`(如有对应 Issue 需关联 `Fixes #...`); - 等待 CI 检查:`gh pr checks --watch`; - 审查通过后合入:`gh pr merge --merge --delete-branch`; 4. **版本发布与 Tag 推送标准流程(严格对齐 seal-use)**: diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index 6c406b6..278d267 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record = { "dictionary": "enum", "dict": "enum" }, - flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } + flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } }, "bill": { "summary": "单据检索、表单规格诊断与审批动作", @@ -597,7 +597,7 @@ export const COMMAND_METADATA: Record = { "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 lang language limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") } + 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 lang language limit name offset page page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") } }, "app": { "summary": "桌面端工作台应用管理", diff --git a/src/cli/commands/platform.test.ts b/src/cli/commands/platform.test.ts index 5e010c3..c2f111d 100644 --- a/src/cli/commands/platform.test.ts +++ b/src/cli/commands/platform.test.ts @@ -514,6 +514,18 @@ describe("CLI - platform 命令与 record 动作", () => { expect(row1.fields["自定义字段"]).toBe("测试值"); }); + it("platform records --all 拒绝直接全量输出,要求分页或流式文件", 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)); + await expect( + handlePlatformCommand( + { area: "platform", action: "records", args: ["platform-1", "entity-1"], options: { all: true }, raw: ["platform", "records", "platform-1", "entity-1", "--all"] }, + dummyRuntime + ) + ).rejects.toThrow("--all 不再直接返回全量"); + }); + 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)); diff --git a/src/cli/commands/platform/app-info.ts b/src/cli/commands/platform/app-info.ts index b04f9ff..63d8b31 100644 --- a/src/cli/commands/platform/app-info.ts +++ b/src/cli/commands/platform/app-info.ts @@ -11,6 +11,14 @@ import { printJson, printTable } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { cell, resolveAppAndEntity } from "./shared.js"; +const SYSTEM_FIELD_INFO = [ + { fieldKey: "ownerId", label: "负责人", type: "staff", role: "system" }, + { fieldKey: "submitterId", label: "提交人", type: "staff", role: "system" }, + { fieldKey: "createTime", label: "创建时间", type: "date", role: "system" }, + { fieldKey: "updateTime", label: "更新时间", type: "date", role: "system" }, + { fieldKey: "active", label: "启停状态", type: "boolean", role: "system" }, +]; + export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const clients = await createClientsForCorp(runtime.selectedCorp!); const isAll = booleanOption(parsed.options, ["all", "a"], false); @@ -60,7 +68,7 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): ) : entity.fields, })); - if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 }; + if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, systemFields: SYSTEM_FIELD_INFO, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 }; const rows = output.flatMap((entity) => entity.fields.map((field): Array => { const roleTag = @@ -86,16 +94,21 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): ["业务对象", "物理字段键 (fieldKey / 接口参数名)", "界面名称 (label)", "类型", "角色说明", "必填性", "引用对象"], rows ); + const systemTable = printTable( + ["系统字段键", "界面名称", "类型", "说明"], + SYSTEM_FIELD_INFO.map((field) => [field.fieldKey, field.label, field.type, "系统字段,不在业务 fields 列表中"]) + ); const tips = [ "", "💡 字段命名与工作流配置避坑提示:", " 1. 物理字段键 (fieldKey / 接口参数名): 在工作流节点映射 (如 ekuaibao-datalink-create) 和 API 请求中,必须使用此键 (例如 E_..._费用金额),切勿使用中文显示名。", " 2. 结尾 _name: 代表实体的业务主名称/标题 (界面通常显示为单据/计划名称);", " 3. 结尾 _code: 代表业务编号/单号 (界面通常显示为单据/计划编码);若设置了 autoNumber 规则,创建时会自动生成流水号。", + " 4. 系统字段不在业务字段列表中:ownerId = 负责人/记录所有者,submitterId = 提交人;工作流创建/修改节点的字段映射可直接使用 ownerId,不能把自定义「人员」当作负责人。", "", ].join("\n"); return { - stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个字段) ======\n${table}\n${tips}`, + stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个业务字段) ======\n${table}\n\n── 系统字段(不在业务 fields 中) ──\n${systemTable}\n${tips}`, stderr: "", exitCode: 0, }; diff --git a/src/cli/commands/platform/records.ts b/src/cli/commands/platform/records.ts index 2ad95e3..fe882b3 100644 --- a/src/cli/commands/platform/records.ts +++ b/src/cli/commands/platform/records.ts @@ -54,11 +54,21 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): const isAll = booleanOption(parsed.options, ["all", "a"], false); const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]); const fetchAll = isAll || Boolean(sumOption || isProfileStats); - const start = numberOption(parsed.options, ["start", "offset"], 0); - const count = numberOption(parsed.options, ["count", "limit"], 20); - const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500); + const count = numberOption(parsed.options, ["count", "limit"], 20) ?? 20; + const page = Math.max(1, numberOption(parsed.options, ["page"], 1) ?? 1); + const start = numberOption(parsed.options, ["start", "offset"], (page - 1) * count) ?? 0; + const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500) ?? 500; const fields = splitFields(stringOption(parsed.options, ["fields", "select"])); + // 全量 JSON/表格很容易把几十万条记录倒进 stdout 或内存;全量导出必须显式走文件流。 + if (isAll && !isProfileStats && !sumOption) { + if (!isStream || !runtime.outputOptions?.outputFile) { + throw usageError( + "--all 不再直接返回全量 JSON/表格。请使用 --page/--count 分页查询,或使用 --ndjson --output-file 流式导出;大范围检索建议交给脚本处理。" + ); + } + } + // 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计) if (isStream) { let streamCount = 0; diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 7cd0cd7..0ac5616 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1522,6 +1522,9 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { return { json: async () => ({ code: 200, data: null }) }; }, put: (url: string, opts: any) => { + if (url.endsWith("/chooses")) { + return { json: async () => ({ code: 200, data: [] }) }; + } if (url.includes("api/easo/pipelines/pipe_node_test")) { savedWorkflowPayload = opts.json; return { diff --git a/src/cli/commands/workflow/draft.ts b/src/cli/commands/workflow/draft.ts index cea1f4d..157b579 100644 --- a/src/cli/commands/workflow/draft.ts +++ b/src/cli/commands/workflow/draft.ts @@ -14,7 +14,7 @@ import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js import { printJson } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; -import { PLATFORM_ID_OPTION_KEYS } from "./shared.js"; +import { PLATFORM_ID_OPTION_KEYS, formatWorkflowVersion } from "./shared.js"; export async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); @@ -78,7 +78,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr if (!pipelineId || !file) { return { stdout: "", - stderr: "用法: hose-use workflow save --file= [--force-write]\n", + stderr: "用法: hose-use workflow save --file= [--force-write] [--in-place]\n", exitCode: 1, }; } @@ -96,6 +96,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr } const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]); + const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]); requireMutationConfirmation( parsed, runtime, @@ -105,8 +106,10 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, { file, + version: parsedWorkflow.version, tasksVersion: parsedWorkflow.tasksVersion, forceWrite, + syncFile, }); } @@ -124,28 +127,48 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr if (!forceWrite && hasWorkflowVersionConflict(state, remote)) { throw new Error( - `工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。` + `工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。请重新导出最新工作流后再改;后续保存可加 --in-place 自动同步本地文件版本。确认要覆盖时使用 --force-write。` ); } state = beginWorkflowSave(state); + const localWorkflowForSync = state.workflow; try { const payload = state.workflow.inputs?.length ? state.workflow : { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] }; const saved = await updateWorkflow(piperClient, payload); state = commitWorkflowSave(state, saved); + let fileSynced = false; + let fileSyncWarning = ""; + if (syncFile) { + try { + const syncedWorkflow = { + ...localWorkflowForSync, + version: saved.version, + tasksVersion: saved.tasksVersion, + updateTime: saved.updateTime, + }; + writeFileSync(file, `${JSON.stringify(syncedWorkflow, null, 2)}\n`, "utf8"); + fileSynced = true; + } catch (error) { + fileSyncWarning = `本地文件同步失败: ${error instanceof Error ? error.message : String(error)}`; + } + } const result = { success: true, pipelineId, status: state.status, + version: saved.version, tasksVersion: saved.tasksVersion, updateTime: saved.updateTime, + fileSynced, + ...(fileSyncWarning ? { fileSyncWarning } : {}), }; - if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: 0 }; return { - stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`, - stderr: "", + stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功:${formatWorkflowVersion(saved)}。${fileSynced ? "\n📝 已同步更新本地文件。" : ""}${fileSyncWarning ? `\n⚠️ ${fileSyncWarning}` : ""}\n`, + stderr: fileSyncWarning, exitCode: 0, }; } catch (error) { diff --git a/src/cli/commands/workflow/node.ts b/src/cli/commands/workflow/node.ts index 93e9ff7..d8bb95d 100644 --- a/src/cli/commands/workflow/node.ts +++ b/src/cli/commands/workflow/node.ts @@ -14,12 +14,13 @@ import { GRAY_NODES_CATALOG, findGrayNode, } from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js"; +import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js"; import { stringOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { createPiperClientForCorp } from "../../helpers.js"; -import { createWorkflowDetailClient } from "./shared.js"; +import { createWorkflowDetailClient, formatWorkflowVersion } from "./shared.js"; const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]); const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]); @@ -133,7 +134,7 @@ async function handleListNodes( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const detail = await getWorkflowDetail(client, pipelineId); const tasks = detail.tasks || []; const flattened = flattenWorkflowTaskTree(tasks); @@ -158,13 +159,13 @@ async function handleListNodes( item.hierarchicalIndex, item.task.name, item.task.type, - item.task.label || "-", + item.task.displayName || item.task.label || "-", item.task.groupName || "-", item.summary, ]); const table = printTable( - ["#", "节点标识 (name)", "类型 (type)", "标题 (label)", "分组", "配置摘要"], + ["#", "节点标识 (name)", "类型 (type)", "标题", "分组", "配置摘要"], rows ); @@ -190,7 +191,7 @@ async function handleGetNode( }; } - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const detail = await getWorkflowDetail(client, pipelineId); const located = findWorkflowTask(detail.tasks || [], nodeTarget); @@ -219,6 +220,7 @@ async function handleGetNode( "父容器节点": parentName || "顶级节点 (root)", "节点类型 (type)": task.type, "节点标题 (label)": task.label || "-", + "节点显示名 (displayName)": (task as any).displayName || "-", "节点分组 (group)": task.groupName || "-", "状态 (status)": task.status || "active", }; @@ -228,7 +230,7 @@ async function handleGetNode( } const outLines = [ - `====== 节点详情 [${task.name}] (${task.label || task.type}) ======`, + `====== 节点详情 [${task.name}] (${(task as any).displayName || task.label || task.type}) ======`, printKeyValue(kv), ]; @@ -255,7 +257,8 @@ async function handleAddNode( "", "常用选项:", " --type= 节点类型 (如 code-js2 / code)", - " --label=<标题> 节点显示名称", + " --label=<标题> 节点类型标题", + " --display-name=<名称> 设计器节点标题(displayName,最多 20 字符)", " --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费", " --code=<代码片段> 传入代码字符串(仅限简短代码)", " --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)", @@ -269,6 +272,7 @@ async function handleAddNode( } const label = stringOption(parsed.options, ["label", "name", "l"]); + const displayName = stringOption(parsed.options, ["display-name", "displayName", "display"]); const parent = stringOption(parsed.options, ["parent", "container", "p"]); const after = stringOption(parsed.options, ["after", "insert-after"]); const desc = stringOption(parsed.options, ["desc", "description", "d"]); @@ -284,15 +288,16 @@ async function handleAddNode( parsed, runtime, "追加工作流节点", - `hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes` + `hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes` ); - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const detail = await getWorkflowDetail(client, pipelineId); const { workflow: updatedWorkflow, newTask } = addWorkflowTask(detail, { type, label, + displayName, desc, code, parent, @@ -305,12 +310,13 @@ async function handleAddNode( newNodeName: newTask.name, type: newTask.type, label: newTask.label, + displayName: newTask.displayName, targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾", totalTasksCount: updatedWorkflow.tasks?.length || 0, }); } - const saveResult = await updateWorkflow(client, updatedWorkflow); + const saveResult = await updateWorkflow(client, updatedWorkflow, platformId); if (runtime.jsonMode) { return { @@ -321,13 +327,15 @@ async function handleAddNode( } const out = [ - `✨ 节点 [${newTask.name}] (${newTask.label}) 已成功添加至工作流 [${pipelineId}]:`, + `✨ 节点 [${newTask.name}] (${newTask.displayName || newTask.label}) 已成功添加至工作流 [${pipelineId}]:`, printKeyValue({ "节点标识 (name)": newTask.name, "节点类型 (type)": newTask.type, "节点标题 (label)": newTask.label || "-", + "节点显示名 (displayName)": newTask.displayName || "-", "所属位置": parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流顶级末尾", "节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0), + "工作流版本": formatWorkflowVersion(saveResult), }), ].join("\n"); @@ -347,7 +355,8 @@ async function handleEditNode( "请提供节点标识 (name 或层级序号): hose-use workflow node edit [选项]", "", "常用选项:", - " --label=<新名称> 更新节点显示标题", + " --label=<类型标题> 更新节点类型标题(服务端保存时可能重新生成)", + " --display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)", " --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费", " --code=<行内代码> 直接传入代码片段(短脚本)", " --desc=<描述> 更新节点描述", @@ -363,6 +372,7 @@ async function handleEditNode( } const label = stringOption(parsed.options, ["label", "l"]); + const displayName = stringOption(parsed.options, ["display-name", "displayName", "display"]); const desc = stringOption(parsed.options, ["desc", "description", "d"]); const codeFile = stringOption(parsed.options, ["code-file", "file"]); let code = stringOption(parsed.options, ["code", "c"]); @@ -399,18 +409,20 @@ async function handleEditNode( parsed, runtime, "修改工作流节点", - `hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""} --yes` + `hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""} --yes` ); - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const detail = await getWorkflowDetail(client, pipelineId); const { workflow: updatedWorkflow, editedTask } = editWorkflowTask(detail, nodeTarget, { label, + displayName, desc, code, set: Object.keys(customSet).length > 0 ? customSet : undefined, }); + const descManaged = desc !== undefined && isServerManagedDescType(editedTask.type); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${editedTask.name}`, { @@ -419,18 +431,20 @@ async function handleEditNode( label: editedTask.label, updatedFields: { ...(label ? { label } : {}), - ...(desc ? { desc } : {}), + ...(displayName !== undefined ? { displayName } : {}), + ...(desc && !descManaged ? { desc } : {}), + ...(descManaged ? { desc: "服务端托管,已跳过" } : {}), ...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file= 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}), ...customSet, }, }); } - const saveResult = await updateWorkflow(client, updatedWorkflow); + const saveResult = await updateWorkflow(client, updatedWorkflow, platformId); if (runtime.jsonMode) { return { - stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult }, runtime.outputOptions), + stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult, descIgnored: descManaged }, runtime.outputOptions), stderr: "", exitCode: 0, }; @@ -440,9 +454,15 @@ async function handleEditNode( if (!codeFile && code && code.length > 300) { codeTip = `\n💡 提示: 检测到通过命令行行内传入大段代码 (${code.length} 字符)。建议将脚本落地为本地文件并通过 --code-file=<路径> 传入,避免 Token 浪费与 Shell 转义风险。\n`; } + const labelTip = label + ? "\n💡 提示: --label 是节点类型标题,服务端保存时可能重新生成;要修改设计器标题请使用 --display-name。\n" + : ""; + const descTip = descManaged + ? "\n💡 提示: 该节点描述由服务端按配置自动生成,--desc 已忽略;如需稳定说明,请使用代码节点或在创建节点上写业务说明。\n" + : ""; return { - stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}`, + stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n${codeTip}${labelTip}${descTip}`, stderr: "", exitCode: 0, }; @@ -503,7 +523,7 @@ async function handleMapNode( `hose-use workflow node map ${pipelineId} ${nodeTarget} --yes` ); - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const detail = await getWorkflowDetail(client, pipelineId); const { workflow: updatedWorkflow, editedTask, changedKeys } = applyNodeMapping(detail, nodeTarget, mappingData); @@ -521,7 +541,7 @@ async function handleMapNode( }); } - const saveResult = await updateWorkflow(client, updatedWorkflow); + const saveResult = await updateWorkflow(client, updatedWorkflow, platformId); if (runtime.jsonMode) { return { @@ -532,7 +552,7 @@ async function handleMapNode( } return { - stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n`, + stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n`, stderr: "", exitCode: 0, }; @@ -559,7 +579,7 @@ async function handleRemoveNode( `hose-use workflow node rm ${pipelineId} ${nodeTarget} --yes` ); - const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); + const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const detail = await getWorkflowDetail(client, pipelineId); const { workflow: updatedWorkflow, removedTask } = removeWorkflowTask(detail, nodeTarget); @@ -574,7 +594,7 @@ async function handleRemoveNode( }); } - const saveResult = await updateWorkflow(client, updatedWorkflow); + const saveResult = await updateWorkflow(client, updatedWorkflow, platformId); if (runtime.jsonMode) { return { @@ -585,7 +605,7 @@ async function handleRemoveNode( } return { - stdout: `🗑️ 节点 [${removedTask.name}] (${removedTask.label || removedTask.type}) 已从工作流 [${pipelineId}] 中安全移除。\n`, + stdout: `🗑️ 节点 [${removedTask.name}] (${removedTask.label || removedTask.type}) 已从工作流 [${pipelineId}] 中安全移除。\n📌 ${formatWorkflowVersion(saveResult)}\n`, stderr: "", exitCode: 0, }; diff --git a/src/cli/commands/workflow/shared.ts b/src/cli/commands/workflow/shared.ts index b9266a2..6267531 100644 --- a/src/cli/commands/workflow/shared.ts +++ b/src/cli/commands/workflow/shared.ts @@ -5,6 +5,17 @@ import type { CliParsedArgs, CliRuntime } from "../../types.js"; export const PLATFORM_ID_OPTION_KEYS = ["platform", "platform-id", "platformId", "app", "app-id", "appId"]; +export function formatWorkflowVersion(workflow: { + version?: string | null; + tasksVersion?: number | null; + updateTime?: string | null; +}): string { + const version = workflow.version || "-"; + const tasksVersion = workflow.tasksVersion ?? "-"; + const updateTime = workflow.updateTime ? `,更新时间 ${workflow.updateTime}` : ""; + return `版本 ${version}(tasksVersion ${tasksVersion})${updateTime}`; +} + export async function createWorkflowDetailClient( parsed: CliParsedArgs, runtime: CliRuntime, @@ -12,6 +23,7 @@ export async function createWorkflowDetailClient( ): Promise<{ client: Awaited>; clients: Awaited>; + platformId?: string; }> { const clients = await createClientsForCorp(runtime.selectedCorp!); const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS); @@ -30,6 +42,7 @@ export async function createWorkflowDetailClient( return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient, clients, + platformId, }; } diff --git a/src/domains/assist-platform/README.assist-platform.md b/src/domains/assist-platform/README.assist-platform.md index e21b8a1..2a66ffa 100644 --- a/src/domains/assist-platform/README.assist-platform.md +++ b/src/domains/assist-platform/README.assist-platform.md @@ -19,12 +19,14 @@ ## 关键 API -- `searchCorporations`: 全量企业库检索(按关键词/企业 ID) +- `searchCorporations`: 全量企业库检索(企业 ID 精确匹配、企业名称忽略大小写包含匹配;服务端过滤并分页) - `getCorporationDetail`: 查询企业详细画像与开通版本 - `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人) - `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位) - `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证 +企业检索的关键词和状态通过 JSON 字符串字面量转义后构造过滤表达式,支持中文、引号及反斜线。协助工单在保留既有字段优先级的基础上,将平台原始字段 `userId`、`responsibleUserName`、`responsibleUserId`、`applyMessage` 分别映射为 `applicantId`、`principal`、`principalId`、`matter`;`assistTime` 从毫秒换算为小时 `duration`,仅在缺少旧字段 `duration` / `hours` 时使用。空申请事由保留为空字符串。 + ## 会话生成、导入与身份完整度 - `assist-platform enter --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。 diff --git a/src/domains/assist-platform/api.ts b/src/domains/assist-platform/api.ts index b77c278..9e8674e 100644 --- a/src/domains/assist-platform/api.ts +++ b/src/domains/assist-platform/api.ts @@ -38,12 +38,12 @@ export async function searchCorporationsApi( const conditions: string[] = []; if (params.keyword?.trim()) { - const kw = params.keyword.trim().replace(/"/g, '\\"'); - conditions.push(`(id == "${kw}" || name == "${kw}")`); + const kw = JSON.stringify(params.keyword.trim()); + conditions.push(`(id == ${kw} || name.containsIgnoreCase(${kw}))`); } if (params.state?.trim()) { - const st = params.state.trim().replace(/"/g, '\\"'); - conditions.push(`state == "${st}"`); + const st = JSON.stringify(params.state.trim()); + conditions.push(`state == ${st}`); } if (conditions.length > 0) { requestBody.filterBy = conditions.join(" && "); @@ -127,20 +127,27 @@ export async function searchAssistTicketsApi( const rawStatus = item.state ?? item.status; const stateStr = rawStatus !== undefined && rawStatus !== null ? String(rawStatus) : "未知状态"; + const applicantId = item.applicantId || item.userId; + const principal = item.principal || item.operationUserName || item.responsibleUserName; + const principalId = item.principalId || item.responsibleUserId; + const matter = item.matter ?? item.applyMessage; return { id: String(item.id || item.ticketId || ""), ticketId: String(item.ticketId || item.id || item.authCode || ""), applicant: String(item.applicant || item.applyUserName || item.userName || "未知申请人"), - applicantId: item.applicantId ? String(item.applicantId) : undefined, - principal: item.principal ? String(item.principal) : (item.operationUserName ? String(item.operationUserName) : undefined), - principalId: item.principalId ? String(item.principalId) : undefined, + applicantId: applicantId ? String(applicantId) : undefined, + principal: principal ? String(principal) : undefined, + principalId: principalId ? String(principalId) : undefined, state: stateStr, - duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : undefined), + duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : ( + typeof item.assistTime === "number" && Number.isFinite(item.assistTime) && item.assistTime >= 0 + ? item.assistTime / 3600000 : undefined + )), startTime, endTime, usePeriodDesc, - matter: item.matter ? String(item.matter) : undefined, + matter: matter !== undefined && matter !== null ? String(matter) : undefined, createTime: typeof item.createTime === "number" ? item.createTime : undefined, }; }); diff --git a/src/domains/assist-platform/assist-platform.test.ts b/src/domains/assist-platform/assist-platform.test.ts index f54bd49..f6392a7 100644 --- a/src/domains/assist-platform/assist-platform.test.ts +++ b/src/domains/assist-platform/assist-platform.test.ts @@ -38,7 +38,7 @@ describe("domains/assist-platform - 协助平台业务编排", () => { expect(req.url).toContain("corporation/search"); const body = (await req.json()) as any; expect(body.limit.count).toBe(10); - expect(body.filterBy).toContain('name == "CSM"'); + expect(body.filterBy).toBe('(id == "CSM" || name.containsIgnoreCase("CSM"))'); return Response.json({ count: 1, items: [ @@ -63,6 +63,20 @@ describe("domains/assist-platform - 协助平台业务编排", () => { expect(res.items[0].name).toBe("CSM"); }); + it("searchCorporations 转义关键词和状态并保留分页条件", async () => { + const keyword = ' 齐齐"哈\\尔 '; + const state = ' 可"用\\ '; + const client = createMockClient(async (req) => { + const body = await req.json() as any; + const kw = JSON.stringify(keyword.trim()); + expect(body.filterBy).toBe(`(id == ${kw} || name.containsIgnoreCase(${kw})) && state == ${JSON.stringify(state.trim())}`); + expect(body.limit).toEqual({ start: 3, count: 5 }); + return Response.json({ count: 0, items: [] }); + }); + expect(await searchCorporations(client, { keyword, state, limit: { start: 3, count: 5 } })) + .toEqual({ count: 0, items: [] }); + }); + it("getCorporationDetail 返回企业详细配置", async () => { const client = createMockClient(async (req) => { expect(req.url).toContain("corporation/$Cxa3oOtQi2eS$g/getCorporationDetail"); @@ -108,6 +122,31 @@ describe("domains/assist-platform - 协助平台业务编排", () => { expect(tickets[0].usePeriodDesc).toContain("至"); }); + it("listAssistTickets 映射平台原始字段并保留旧字段优先级", async () => { + const raw = { + id: "ticket-raw", userName: "申请人", userId: "applicant-raw", + responsibleUserName: "负责人", responsibleUserId: "principal-raw", + status: 1, assistTime: 86400000, applyMessage: "", + }; + const client = createMockClient(() => Response.json({ items: [ + raw, + { ...raw, applicant: "旧申请人", applicantId: "applicant-old", principal: "旧负责人", + principalId: "principal-old", operationUserName: "旧经办人", state: "已提供", + duration: 12, hours: 48, matter: "旧事由" }, + { ...raw, operationUserName: "旧经办人", hours: 6 }, + ] })); + const tickets = await listAssistTickets(client, "corp-test"); + expect(tickets[0]).toMatchObject({ + ticketId: "ticket-raw", applicant: "申请人", applicantId: "applicant-raw", + principal: "负责人", principalId: "principal-raw", state: "1", duration: 24, matter: "", + }); + expect(tickets[1]).toMatchObject({ + applicant: "旧申请人", applicantId: "applicant-old", principal: "旧负责人", + principalId: "principal-old", state: "已提供", duration: 12, matter: "旧事由", + }); + expect(tickets[2]).toMatchObject({ principal: "旧经办人", duration: 6 }); + }); + it("findStaff 正确检索企业员工工号与角色", async () => { const client = createMockClient(async (req) => { expect(req.url).toContain("assistPlatform/getStaff"); diff --git a/src/domains/datalink/README.datalink.md b/src/domains/datalink/README.datalink.md index 9a59072..8e84674 100644 --- a/src/domains/datalink/README.datalink.md +++ b/src/domains/datalink/README.datalink.md @@ -30,7 +30,7 @@ hose-use platform list hose-use platform get <应用 ID|名称> hose-use platform entities <应用 ID|名称> hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>] -hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats] +hose-use platform records <应用 ID|名称> <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats] hose-use platform record get [<应用> <业务对象>] <记录ID> hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes] hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes] @@ -47,6 +47,8 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称> - `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。 - 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o ` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。 - MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。 +- `records --page=<页码> --count=<每页>`:分页查询,默认 `count=20`;用于替代无边界全量拉取。 +- `records --all`:不再直接返回全量 JSON/表格。普通查询请用 `--page/--count`;确实需要全量时只允许 `--ndjson --output-file ` 流式导出,避免几十万条记录进入 stdout 或一次性载入内存。大范围检索建议由 Agent 编写脚本处理。 - `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。 - `records --flat`:自动剥离底层动态物理前缀(如 `E__`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。 - `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。 diff --git a/src/domains/platform/api.test.ts b/src/domains/platform/api.test.ts new file mode 100644 index 0000000..fd68ba1 --- /dev/null +++ b/src/domains/platform/api.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "bun:test"; +import { getWorkflowSnapshot, updateWorkflowChooses } from "./api.js"; + +describe("workflow snapshot API", () => { + it("uses the piper pipelines/snapshot endpoint first", async () => { + const calls: string[] = []; + const client = { + get: async (path: string) => { + calls.push(path); + if (path === "api/easo/pipelines/snapshot/snap-1") { + return new Response(JSON.stringify({ + code: 200, + data: { id: "snap-1", pipelineId: "pipe-1", version: "26.10.7" }, + }), { status: 200, headers: { "content-type": "application/json" } }); + } + throw new Error("unexpected path"); + }, + } as any; + + const snapshot = await getWorkflowSnapshot(client, "snap-1", "pipe-1"); + + expect(calls).toEqual(["api/easo/pipelines/snapshot/snap-1"]); + expect(snapshot.id).toBe("snap-1"); + expect(snapshot.version).toBe("26.10.7"); + }); + + it("refreshes chooses after the pipeline save", async () => { + const calls: string[] = []; + const client = { + put: async (path: string) => { + calls.push(path); + return new Response(JSON.stringify({ code: 200, data: [] }), { status: 200, headers: { "content-type": "application/json" } }); + }, + } as any; + + await updateWorkflowChooses(client, "pipe-1"); + + expect(calls).toEqual(["api/easo/pipelines/pipe-1/chooses"]); + }); +}); diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index 1ea81f4..747fc00 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -144,6 +144,17 @@ export async function updateWorkflow( return unwrap(response, WorkflowDetailSchema); } +/** + * 前端“保存更新”在主线 PUT 之后还会调用该接口(无 body), + * 由平台重新生成 choose/描述元数据;CLI 保存必须保持一致,否则内置节点 desc 会变成「」。 + */ +export async function updateWorkflowChooses( + client: KyInstance, + pipelineId: string +): Promise { + await client.put(`api/easo/pipelines/${pipelineId}/chooses`); +} + export async function copyWorkflow( client: KyInstance, pipelineId: string, @@ -191,16 +202,22 @@ export async function getWorkflowSnapshot( snapshotId: string, pipelineId?: string ): Promise { - try { - const response = await client.get(`api/easo/snapshots/${snapshotId}`); - return unwrap(response, WorkflowSnapshotSchema); - } catch (err) { - if (pipelineId) { - const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots/${snapshotId}`); + const paths = [ + // 前端实际使用的快照接口:pipelines/snapshot/{id} + `api/easo/pipelines/snapshot/${snapshotId}`, + `api/easo/snapshots/${snapshotId}`, + ...(pipelineId ? [`api/easo/pipelines/${pipelineId}/snapshots/${snapshotId}`] : []), + ]; + let lastError: unknown; + for (const path of paths) { + try { + const response = await client.get(path); return unwrap(response, WorkflowSnapshotSchema); + } catch (error) { + lastError = error; } - throw err; } + throw lastError instanceof Error ? lastError : new Error(String(lastError)); } export async function listWorkflowLogs( diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index a324549..d31e794 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -64,12 +64,20 @@ export function sanitizeWorkflowSnapshot( return cloned; } -export function updateWorkflow( +export async function updateWorkflow( client: KyInstance, - workflow: import("./types.js").WorkflowDetail + workflow: import("./types.js").WorkflowDetail, + platformId?: string ) { - const sanitized = sanitizeWorkflowSnapshot(workflow); - return api.updateWorkflow(client, sanitized); + // 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。 + const payload: import("./types.js").WorkflowDetail = platformId && !workflow.inputs?.length + ? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] } + : workflow; + const sanitized = sanitizeWorkflowSnapshot(payload); + const updated = await api.updateWorkflow(client, sanitized); + // 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。 + await api.updateWorkflowChooses(client, updated.id || workflow.id); + return updated; } export async function copyWorkflow( @@ -95,7 +103,7 @@ export async function copyWorkflow( const result = await api.copyWorkflow(client, pipelineId, cloned); if (options.label && result.label !== options.label) { result.label = options.label; - return api.updateWorkflow(client, result); + return updateWorkflow(client, result, options.platformId ?? (result as any).platformId); } return result; } diff --git a/src/domains/platform/workflow/README.workflow.md b/src/domains/platform/workflow/README.workflow.md index 7f56fea..b41c09c 100644 --- a/src/domains/platform/workflow/README.workflow.md +++ b/src/domains/platform/workflow/README.workflow.md @@ -23,8 +23,8 @@ hose-use workflow nodes [list] [--all] hose-use workflow nodes grant [--password=] [--dry-run|--yes] hose-use workflow node list hose-use workflow node get <节点name或#序号> -hose-use workflow node add --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes] -hose-use workflow node edit <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes] +hose-use workflow node add --type=code-js2 --label="清洗" --display-name="清洗节点" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes] +hose-use workflow node edit <节点name或#序号> --display-name="新标题" [--code="..."] [--dry-run|--yes] hose-use workflow node rm <节点name或#序号> [--dry-run|--yes] hose-use workflow tail [--job=] [--once] [--failed-only] [--interval=2] [--json] hose-use workflow lint-script [节点标识] [--json] @@ -145,6 +145,8 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 ` `node edit --file=<脚本>` 是 `--code-file` 的兼容别名;编辑字段映射使用 `--mapping-file=`,或独立的 `node map --file=`。不根据文件扩展名猜测用途。 +节点卡片标题保存在 `displayName`,用 `--display-name` 修改;`--label` 是节点类型标题,服务端保存时可能按节点类型重新生成,不能可靠地用于重命名已有节点。设计器前端把节点标题限制为 20 个字符;后端本身不校验该长度(实测 21 字仍可保存),本地 CLI 按前端上限强制校验,超过 20 个 Unicode 字符会在写入前抛出 `ValidationError`。条件/内置节点类型的 `desc` 也由平台按配置重新生成,自定义 `--desc` 可能不会持久化。 + 灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。管理员密码用于额外授权,不能替代写操作确认。 节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。 @@ -165,7 +167,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 ` ## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting) -字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。`body` 等上下文根不按节点处理,来源无法静态确定或无法解析的表达式给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。 +字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form`、`combineFilters`、`filters`、`conditions`、`flowCode`、`list`、`details` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。明确为 JSON 描述符但 JSON 损坏(例如多余 `}`)或缺少有效节点 key 时产生 `INVALID_CHOOSE_DESCRIPTOR` 硬门禁。`body` 等上下文根不按节点处理,来源无法静态确定或使用不支持的表达式时仍给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。 + +业务对象查询的 `gte/lte` 会产生 `DATALINK_FILTER_COMPARISON_COMPATIBILITY` 软提示:本地条件解释器支持通用比较符,不代表真实设计器的日期字段支持同一枚举。分析器不会自动改为 `gt/lt`,因为这会改变端点是否包含的业务语义;采用严格比较时需同时核对月初、下月月初等毫秒边界。保存成功及静态门禁通过均不等于前端配置校验或租户实际运行通过。 1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`; 2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析; diff --git a/src/domains/platform/workflow/analysis/analyzer.ts b/src/domains/platform/workflow/analysis/analyzer.ts index 44bd492..681bed2 100644 --- a/src/domains/platform/workflow/analysis/analyzer.ts +++ b/src/domains/platform/workflow/analysis/analyzer.ts @@ -58,6 +58,7 @@ interface ChooseReference { key?: string; descriptor?: boolean; problem?: string; + invalidDescriptor?: boolean; } /** 只解析 choose 参数,不执行表达式;引号内的括号不参与标签边界匹配。 */ @@ -90,6 +91,7 @@ function extractChooseTags(val: unknown): ChooseReference[] { marker.lastIndex = end + 1 + close[0].length; const raw = val.slice(match.index, marker.lastIndex); const argument = val.slice(from, end).trim(); + let isDescriptor = false; try { let value = argument; if (argument.startsWith('"')) value = JSON.parse(argument); @@ -100,6 +102,7 @@ function extractChooseTags(val: unknown): ChooseReference[] { } if (typeof value !== "string") throw new Error("参数应为节点描述或路径"); if (value.trim().startsWith("{")) { + isDescriptor = true; const descriptor: unknown = JSON.parse(value); if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) || typeof (descriptor as Record).key !== "string" || !(descriptor as { key: string }).key.trim()) throw new Error("节点描述缺少 key"); results.push({ raw, key: (descriptor as { key: string }).key.trim(), descriptor: true }); @@ -107,7 +110,8 @@ function extractChooseTags(val: unknown): ChooseReference[] { results.push({ raw, key: value.trim(), descriptor: false }); } else throw new Error("参数不是可静态识别的节点路径"); } catch { - results.push({ raw, problem: "choose 参数不是可静态识别的节点描述或路径" }); + results.push({ raw, invalidDescriptor: isDescriptor, + problem: isDescriptor ? "choose 节点描述不是有效 JSON 对象或缺少有效 key" : "choose 参数不是可静态识别的节点描述或路径" }); } } return results; @@ -245,6 +249,7 @@ interface LeafFilterItem { } function extractLeafFilters(filterGroup: unknown): LeafFilterItem[] { + if (Array.isArray(filterGroup)) return filterGroup.flatMap(extractLeafFilters); if (!filterGroup || typeof filterGroup !== "object") return []; const items: LeafFilterItem[] = []; const rec = filterGroup as Record; @@ -496,6 +501,19 @@ export function analyzeWorkflow( // 诊断:DataLink 字段误填表单公式硬校验 checkMisplacedFormulasInDatalink(task, path, diagnostics); + // 本地条件解释器支持的通用比较符,不等于真实设计器对应字段的枚举。 + if (task.type === "ekuaibao-datalink-filter") { + const raw = task as Record; + for (const filter of extractLeafFilters(raw.combineFilters ?? raw.filters)) { + if (filter.compare === "gte" || filter.compare === "lte") { + addDiagnostic(diagnostics, { + severity: "warning", code: "DATALINK_FILTER_COMPARISON_COMPATIBILITY", path, + message: `业务对象筛选字段 [${String(filter.key || "未知")}] 使用通用比较符 '${filter.compare}'。合思前端日期字段可能不识别该枚举,请在设计器核对支持的比较符;直接替换为 gt/lt 会改变等号边界,月份范围需同时核对月初及下月月初时间戳。`, + }); + } + } + } + // 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit if (insideEvery && task.type === "flow-create-task") { const onError = (task as Record).onError as @@ -753,7 +771,7 @@ export function analyzeWorkflow( // 诊断 5: 字段变量引用失效校验 (BROKEN_CHOOSE_REFERENCE / BROKEN_LOOP_ITEM_REFERENCE) const inspectFields: Array<{ key: string; value: string }> = []; const rawTask = task as Record; - for (const key of ["inputs", "fields", "mapping", "form"]) collectExpressionValues(rawTask[key], key, inspectFields); + for (const key of ["inputs", "fields", "mapping", "form", "combineFilters", "filters", "conditions", "flowCode", "list", "details"]) collectExpressionValues(rawTask[key], key, inspectFields); for (const field of inspectFields) { if (typeof field.value === "string") { @@ -762,8 +780,11 @@ export function analyzeWorkflow( const chooseKey = item.key; if (!chooseKey) { addDiagnostic(diagnostics, { - severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path, - message: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`, + severity: item.invalidDescriptor ? "error" : "warning", + code: item.invalidDescriptor ? "INVALID_CHOOSE_DESCRIPTOR" : "UNRESOLVED_CHOOSE_REFERENCE", path, + message: item.invalidDescriptor + ? `字段 [${field.key}] 的 choose 节点描述损坏:${item.problem}。请检查多余括号、JSON 转义和节点 key。` + : `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`, }); continue; } diff --git a/src/domains/platform/workflow/analysis/choose-references.test.ts b/src/domains/platform/workflow/analysis/choose-references.test.ts index ef7983d..50c3218 100644 --- a/src/domains/platform/workflow/analysis/choose-references.test.ts +++ b/src/domains/platform/workflow/analysis/choose-references.test.ts @@ -70,8 +70,8 @@ describe("choose reference containers and source classification", () => { } }); - test("warns for unknown bare roots and unsupported or malformed expressions without blocking", () => { - for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')", "@{choose('{bad json}')}"]) { + test("warns for unknown bare roots and unsupported or incomplete expressions without blocking", () => { + for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')"]) { const result = analyze({ form: { title: tag } }); expect(result.summary.passed).toBe(true); expect(result.diagnostics.map(item => item.code)).toContain("UNRESOLVED_CHOOSE_REFERENCE"); @@ -79,6 +79,51 @@ describe("choose reference containers and source classification", () => { } }); + test.each([ + "@{choose('{bad json}')}", + `@{choose('${JSON.stringify({ key: "trigger_actual", properties: [{ key: "startTime", type: "NUMBER" }] })}}')}`, + `@{choose('${JSON.stringify({ properties: [] })}')}`, + ])("blocks an explicitly damaged JSON descriptor in %s", tag => { + const result = analyze({ combineFilters: { condition: "and", filters: [{ key: "日期", compare: "gt", value: tag }] } }); + expect(result.summary.passed).toBe(false); + expect(result.diagnostics).toMatchObject([{ code: "INVALID_CHOOSE_DESCRIPTOR", category: "hard_block", severity: "error" }]); + expect(result.diagnostics[0].message).toContain("日期"); + }); + + test("checks runtime expressions in filters, lookup codes, loops and nested details", () => { + const missing = descriptor("action_missing"); + for (const config of [ + { combineFilters: { filters: [{ filters: [{ key: "日期", value: missing, compare: "gt" }], condition: "and" }], condition: "or" } }, + { filters: [{ key: "日期", value: missing }] }, + { conditions: { value: missing } }, + { flowCode: missing }, + { list: missing }, + { details: { fixed: [{ amount: missing }] } }, + ]) { + const result = analyze(config); + expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_CHOOSE_REFERENCE"); + expect(result.summary.passed).toBe(false); + } + }); + + test("warns about DataLink inclusive comparison compatibility without rewriting boundaries", () => { + const config = { type: "ekuaibao-datalink-filter", combineFilters: { filters: [ + { key: "日期", compare: "gte", value: descriptor("trigger_actual") }, + { key: "日期", compare: "lte", value: descriptor("trigger_actual") }, + ] } }; + const original = JSON.stringify(config); + const result = analyze(config); + expect(result.diagnostics).toHaveLength(2); + expect(result.diagnostics.every(item => item.code === "DATALINK_FILTER_COMPARISON_COMPATIBILITY" && item.category === "soft_advice")).toBe(true); + expect(result.diagnostics[0].message).toContain("边界"); + expect(JSON.stringify(config)).toBe(original); + expect(analyze({ type: "ekuaibao-datalink-filter", filters: config.combineFilters.filters }).diagnostics).toHaveLength(2); + for (const compare of ["gt", "lt"]) { + expect(analyze({ ...config, combineFilters: { filters: [{ key: "日期", compare, value: descriptor("trigger_actual") }] } }).diagnostics).toEqual([]); + } + expect(analyze({ ...config, type: "condition", tasks: [{ name: "child", type: "http" }] }).diagnostics).toEqual([]); + }); + test.each(["@{choose(control_loop.$item)}", "@{choose('control_loop.$item.data')}", descriptor("control_loop.$item")])("blocks old loop item paths in %s", tag => { const result = analyze({ fields: [{ key: "value", value: tag }] }); expect(result.summary.passed).toBe(false); diff --git a/src/domains/platform/workflow/nodes/index.test.ts b/src/domains/platform/workflow/nodes/index.test.ts index 7641004..f855fe8 100644 --- a/src/domains/platform/workflow/nodes/index.test.ts +++ b/src/domains/platform/workflow/nodes/index.test.ts @@ -8,6 +8,9 @@ import { removeWorkflowTask, buildWorkflowTask, summarizeTask, + MAX_NODE_DISPLAY_NAME_LENGTH, + displayNameLength, + isDisplayNameTooLong, } from "./index.js"; import type { WorkflowDetail, WorkflowTask } from "../../types.js"; @@ -240,6 +243,39 @@ describe("workflow-nodes - 任务节点声明式编排纯函数", () => { expect(mockWorkflow.tasks[1].tasks![0].label).toBe("数据清洗"); }); + it("enforces the 20-character designer display name limit", () => { + expect(MAX_NODE_DISPLAY_NAME_LENGTH).toBe(20); + expect(displayNameLength("选核销单号")).toBe(5); + expect(isDisplayNameTooLong("一".repeat(20))).toBe(false); + expect(isDisplayNameTooLong("一".repeat(21))).toBe(true); + + const built = buildWorkflowTask("code", { displayName: " 选核销单号 " }); + expect((built as any).displayName).toBe("选核销单号"); + + const { newTask } = addWorkflowTask(mockWorkflow, { type: "code", displayName: "新节点" }); + expect((newTask as any).displayName).toBe("新节点"); + + const { editedTask } = editWorkflowTask(mockWorkflow, "action_js_1", { + displayName: " 清洗节点 ", + }); + expect((editedTask as any).displayName).toBe("清洗节点"); + expect(() => buildWorkflowTask("code", { displayName: "一".repeat(21) })).toThrow("最多 20 个字符"); + expect(() => editWorkflowTask(mockWorkflow, "action_js_1", { displayName: "一".repeat(21) })).toThrow("最多 20 个字符"); + expect(() => editWorkflowTask(mockWorkflow, "action_js_1", { set: { displayName: "一".repeat(21) } })).toThrow("最多 20 个字符"); + }); + + it("skips desc for server-managed nodes while allowing code node descriptions", () => { + const { editedTask: managedTask } = editWorkflowTask(mockWorkflow, "control_every_1", { + desc: "服务端会覆盖这段描述", + }); + expect(managedTask.desc).toBe("依次遍历每张发票"); + + const { editedTask: codeTask } = editWorkflowTask(mockWorkflow, "action_js_1", { + desc: "Agent 生成的数据清洗脚本", + }); + expect(codeTask.desc).toBe("Agent 生成的数据清洗脚本"); + }); + it("removeWorkflowTask safely removes task and guards trigger node", () => { // 1. Remove child task in container const { workflow: wfRemoved, removedTask } = removeWorkflowTask(mockWorkflow, "action_js_1"); diff --git a/src/domains/platform/workflow/nodes/mutations.ts b/src/domains/platform/workflow/nodes/mutations.ts index 56c253b..06fa703 100644 --- a/src/domains/platform/workflow/nodes/mutations.ts +++ b/src/domains/platform/workflow/nodes/mutations.ts @@ -36,9 +36,31 @@ export function generateNodeName(type: string): string { return `action_${rand}`; } +export const MAX_NODE_DISPLAY_NAME_LENGTH = 20; + +/** + * 服务端会按节点配置重建 desc 的节点类型。只有代码节点的 desc 可以稳定保留; + * 其它节点的描述写入后会在保存时被服务端覆盖,因此本地直接跳过,避免无效修改。 + */ +const CODE_DESC_TYPES = new Set(["code", "code-js2"]); + +export function isServerManagedDescType(type: string): boolean { + return !CODE_DESC_TYPES.has(type); +} + +/** 设计器节点标题按 Unicode 字符计数(中文与 emoji 均算 1 个字符)。 */ +export function displayNameLength(name: string): number { + return Array.from(name.trim()).length; +} + +export function isDisplayNameTooLong(name: string): boolean { + return displayNameLength(name) > MAX_NODE_DISPLAY_NAME_LENGTH; +} + export interface AddTaskOptions { type: string; label?: string; + displayName?: string; code?: string; desc?: string; parent?: string | number; @@ -49,7 +71,7 @@ export interface AddTaskOptions { /** * 构建规范的新节点对象 */ -export function buildWorkflowTask(type: string, options: Partial = {}): WorkflowTask { +function buildWorkflowTaskBase(type: string, options: Partial = {}): WorkflowTask { const normType = type.trim(); const name = generateNodeName(normType); @@ -205,6 +227,30 @@ export function buildWorkflowTask(type: string, options: Partial } } +function applyDisplayName(task: WorkflowTask, displayName?: string): void { + if (displayName === undefined) return; + const trimmed = displayName.trim(); + if (!trimmed) { + delete (task as any).displayName; + return; + } + if (isDisplayNameTooLong(trimmed)) { + throw new ValidationError( + `节点显示名称最多 ${MAX_NODE_DISPLAY_NAME_LENGTH} 个字符(前端设计器上限),当前 ${displayNameLength(trimmed)} 个字符: ${trimmed}` + ); + } + (task as any).displayName = trimmed; +} + +/** + * 构建规范的新节点对象 + */ +export function buildWorkflowTask(type: string, options: Partial = {}): WorkflowTask { + const task = buildWorkflowTaskBase(type, options); + applyDisplayName(task, options.displayName); + return task; +} + /** * 向工作流声明式追加或插入任务节点 */ @@ -243,6 +289,7 @@ export function addWorkflowTask( export interface EditTaskOptions { label?: string; + displayName?: string; code?: string; desc?: string; set?: Record; @@ -266,11 +313,16 @@ export function editWorkflowTask( const { task } = target; if (updates.label !== undefined) task.label = updates.label; - if (updates.desc !== undefined) task.desc = updates.desc; + if (updates.displayName !== undefined) applyDisplayName(task, updates.displayName); + if (updates.desc !== undefined && !isServerManagedDescType(task.type)) task.desc = updates.desc; if (updates.code !== undefined) (task as any).code = updates.code; if (updates.set && typeof updates.set === "object") { for (const [k, v] of Object.entries(updates.set)) { + if (k === "displayName") { + applyDisplayName(task, typeof v === "string" ? v : v == null ? "" : String(v)); + continue; + } (task as any)[k] = v; } } @@ -339,7 +391,14 @@ export function applyNodeMapping( } else if (mapping && typeof mapping === "object") { // 对象格式:合并/设置每个顶层键 for (const [key, value] of Object.entries(mapping)) { - (task as any)[key] = value; + if (key === "displayName") { + applyDisplayName(task, typeof value === "string" ? value : value == null ? "" : String(value)); + } else if (key === "desc" && isServerManagedDescType(task.type)) { + changedKeys.push("desc (服务端托管,已跳过)"); + continue; + } else { + (task as any)[key] = value; + } if (Array.isArray(value)) { changedKeys.push(`${key} (${value.length} 项)`); } else { diff --git a/src/domains/platform/workflow/state/index.test.ts b/src/domains/platform/workflow/state/index.test.ts index 7a0eb76..9b29a25 100644 --- a/src/domains/platform/workflow/state/index.test.ts +++ b/src/domains/platform/workflow/state/index.test.ts @@ -67,6 +67,7 @@ describe("workflow draft state machine", () => { let request: { url: string; json: WorkflowDetail } | undefined; const client = { put: async (url: string, options: { json: WorkflowDetail }) => { + if (url.endsWith("/chooses")) return { json: async () => ({ data: [] }) }; request = { url, json: options.json }; return { json: async () => ({ data: options.json }) }; }, @@ -82,6 +83,7 @@ describe("workflow draft state machine", () => { let sentWorkflow: WorkflowDetail | undefined; const client = { put: async (url: string, options: { json: WorkflowDetail }) => { + if (url.endsWith("/chooses")) return { json: async () => ({ data: [] }) }; sentWorkflow = options.json; return { json: async () => ({ data: options.json }) }; },