Compare commits

...
Author SHA1 Message Date
gitea d7a7203eeb fix(workflow): 纠正终止节点groupName契约,补齐凭证通道与节点契约规范
- workflow: 修正终止节点 (stop) 模板 groupName 为 action,杜绝 Piper 前端 fallback 降级为灰色扳手图标
- skill: 补充三大凭证通道矩阵规范,明确 OpenAPI 永久凭证与动态直通链接机制
- skill: 补充工作流节点 Schema 契约与图标降级防范原则,更新 workflow node inspect/sample-save 参考文档
2026-11-24 16:57:04 +08:00
gitea 86a02b82b7 feat(workflow): 支持节点只读透视与样本固化,规范企业切换上下文持久化
- skill: 补充终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning) 最佳实践
- config: 修复 switchCorp / enter --switch 持久化写入 defaultCorpId 与激活 stateful 模式
- workflow node: 新增 inspect (探针透视配置/样本/执行) 与 sample-save (一键固化出参至 sampleData 并刷新选择树)
- workflow test: 新增 --save-sample 选项,调测通过后自动将产生出参的节点固化为 sampleData
- parser/metadata: 注册 save-sample 选项词汇表,补充单测 workflow-node-sample-inspect.test.ts
2026-11-24 11:45:46 +08:00
yunyingk 5e59c835f1 Merge pull request #204 from yunyingk/feat/global-timeout-support
feat: 全局支持 --timeout 和 -T 参数限制运行时间
2026-11-18 19:20:26 +08:00
gitea f9422ee431 feat: 全局支持 --timeout 和 -T 参数限制运行时间,并明确扫码登录自动交互规范
1. 为所有 hose-use 命令增加全局参数 --timeout (或 -T),允许通过命令行参数直接指定进程运行的最长时限。
2. 在 Agent 执行原则中明确扫码登录后的二维码自动渲染交互规范,确保 Agent 主动展示二维码而非被动等待。
2026-11-18 19:16:34 +08:00
gitea 41503917ce feat: 全局支持 --timeout 和 -T 参数限制运行时间
为所有 hose-use 命令增加全局参数 --timeout (或 -T),允许通过命令行参数直接指定进程运行的最长时限,超过时自动终止。适用于自动化脚本与 CI 环境的防阻塞防护。
2026-11-18 19:14:32 +08:00
yunyingk 6f60803c66 Merge pull request #203 from yunyingk/feat/login-qr-auto-save
feat: 协助平台登录支持自动保存钉钉二维码
2026-11-18 19:10:07 +08:00
gitea c63ec24344 feat: 协助平台登录支持自动保存钉钉二维码
在钉钉扫码登录流程中,自动将生成的登录二维码图片保存到本地 `~/Downloads/dingtalk-login.png`,方便用户在终端无法直接识别或使用二维码时,直接从下载目录打开图片进行扫码。
2026-11-18 19:08:35 +08:00
yunyingk 35a118c456 Merge pull request #202 from yunyingk/fix/mcp-manifest-collision
CI / validate (push) Canceled after 0s
fix(mcp): 拆分插件 MCP 清单与 Claude Code 项目配置
2026-11-18 18:55:48 +08:00
giteaandClaude 0e8d844f3f fix(mcp): 拆分插件 MCP 清单与 Claude Code 项目配置
- 根因:.mcp.json 同时被 ZCode 插件清单和 Claude Code 项目配置读取;
  项目上下文没有 ${CLAUDE_PLUGIN_ROOT} / ${user_config.*},bun 找不到
  /dist/mcp/server.js,stdio 进程立即退出并表现为 Connection closed
- 将插件清单改名为 mcp.json,plugin.json 指向 ./mcp.json,打包脚本、
  插件冒烟测试与发布校验同步更新
- 新增项目级 .mcp.json:bun src/server.ts + HOSE_USE_MCP_ENABLED=true,
  不再包含任何插件变量
- README 与打包说明区分插件清单和项目配置;发布校验增加回归断言

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 18:50:35 +08:00
yunyingk d65a906fb3 Merge pull request #201 from yunyingk/release/v0.9.9
CI / validate (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Canceled after 0s
chore(release): v0.9.9
2026-11-18 17:47:54 +08:00
giteaandClaude df25d7b187 chore(release): v0.9.9
- 统一生产环境确认协议:--allow-prod 为唯一显式覆盖参数,--force 兼容
- 两处生产门禁统一 PROD_OVERRIDE_REQUIRED 结构与提示格式
- 预览 --dry-run 始终放行,成功结果统一 productionOverride
- Skill 澄清生产企业写操作需用户授权,不再暗示禁止

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 17:47:33 +08:00
yunyingk adebbcfffb Merge pull request #200 from yunyingk/docs/clarify-production-writes
CI / validate (push) Canceled after 0s
docs(skill): 澄清生产企业写操作需授权而非禁止
2026-11-18 17:01:54 +08:00
giteaandClaude b0b23f0c23 docs(skill): 澄清生产企业写操作需授权而非禁止
- 修正 SKILL.md 中“仅在测试企业中进行写操作”的表述,明确正式
  生产企业不禁止:用户明确指令 + 两阶段确认(workflow 敏感命令
  再加 --allow-prod)即可执行
- 同步 assist-platform 参考中的协助工单写操作说明
- 将“严格禁止擅自发布”改为“未经用户明确指令不得发布”,保留
  未授权保护,避免被误读为生产环境一律禁止
- 回应 Agent 误把生产环境当作不可操作的文档歧义

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 16:52:17 +08:00
yunyingk 9e191f2ef8 Merge pull request #199 from yunyingk/fix/prod-confirmation-consistency
CI / validate (push) Canceled after 0s
fix(cli): 统一生产环境确认协议与预览行为
2026-11-18 16:50:53 +08:00
giteaandClaude 5be2bd5432 fix(cli): 统一生产环境确认协议与预览行为
- 新增 src/cli/production.ts:--allow-prod 为唯一生产覆盖参数,
  --allow-production / --force 仅作兼容别名;JSON 阻断统一为
  PROD_OVERRIDE_REQUIRED,并携带 nextAction 与 details.operation
- workflow test 与 workflow nodes grant 统一提示文案、错误结构与
  nextAction 生成;workflow test 的 JSON 阻断不再返回空 stdout
- 预览 --dry-run 始终放行,实际执行才要求覆盖参数;nodes grant
  参数校验前置,缺少节点类型时不再先报生产阻断
- 两个命令的成功结果统一携带 productionOverride / productionWarning
- corps tag 将企业从 prod 降级为 test/demo 时输出显著警告
- 同步 CLI 帮助、CLI/workflow README 与 Skill;补充对应单测

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 16:44:57 +08:00
yunyingk 038aca10fb Merge pull request #198 from yunyingk/release/v0.9.8
CI / validate (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Canceled after 0s
chore(release): v0.9.8
2026-11-18 16:23:59 +08:00
gitea 9b780c345d chore(release): v0.9.8 2026-11-18 16:23:48 +08:00
yunyingk d38eaecc12 Merge pull request #197 from yunyingk/feat/bill-draft-query
CI / validate (push) Canceled after 0s
feat(bill): 支持未提交草稿查询与 flowId 直读
2026-11-18 16:09:57 +08:00
giteaandClaude 4b4a7049a0 feat(bill): 支持未提交草稿查询与 flowId 直读
- bill list --state=draft/草稿 改走 flows/my 草稿列表,修复草稿不在
  invoice/search 台账索引中导致 --state=draft 返回空的问题
- 新增 --template/--title/--staff/--page 过滤与分页;服务端 RQL 结合
  客户端兜底匹配,模板版本化 ID 自动剥离哈希
- bill get 新增 flowId 直读通道,工作流/他人创建的草稿无需 flows/my 可见
- 补充域层与 CLI 单测、bill 文档、Skill 与 OpenAPI 参数说明

Fixes #153

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 16:06:34 +08:00
47 changed files with 2408 additions and 206 deletions

No files matched your search

+2 -2
View File
@@ -4,10 +4,10 @@
"type": "stdio",
"command": "bun",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
"src/server.ts"
],
"env": {
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
"HOSE_USE_MCP_ENABLED": "true"
},
"timeoutMs": 120000
}
+2 -2
View File
@@ -1,13 +1,13 @@
{
"name": "hose-use",
"version": "0.9.7",
"version": "0.9.9",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
},
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json",
"mcpServers": "./mcp.json",
"userConfig": {
"enable_mcp": {
"type": "boolean",
+4 -4
View File
@@ -1,4 +1,4 @@
# hose-use (v0.9.7)
# hose-use (v0.9.9)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -138,7 +138,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
- **多文件 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 开关;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `mcp.json` 插件清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;仓库根目录的 `.mcp.json` 是 Claude Code 项目级 MCP 配置,直接以 `bun src/server.ts` 启动当前源码;
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,整个 `dist/` 不纳入 Git。源码方式加载插件须先安装依赖并执行此构建;插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
- **完整插件包**:`bun run package:plugin` 从当前源码构建并生成 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,内含清单、MCP 配置、Skill 与 bundle。Release 发布此包并纳入 `checksums.txt` 和 Gitea 镜像;解包目录可作为本地插件根目录,无需源码或 `node_modules/`,仍需 Bun。打包命令需要 `tar`;详细用法见 [构建与分发说明](./src/packaging/README.packaging.md)。
@@ -155,7 +155,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
| `.github/` | CI 与 Release 工作流,负责校验、构建和发布。 |
| `.zcode-plugin/` | 受版本管理的 [IDE 插件清单](.zcode-plugin/plugin.json),声明 Skill 路径、MCP 配置与用户开关。 |
| `specs/` | specifications(规范)的缩写,存放 API 与工作流规范:`hose-open-api/` 是 hose-use 包装层对外 API 的 YAML 源文件,`openapi.json` 是其打包结果,`openapi.raw.json` 是独立的下游接口规范,`workflow-schema.json` 是从 Zod 导出的工作流结构。[hose-close-api/](./specs/hose-close-api/README.md) 保存从代码整理的合思内部接口清单与 Schema;本地临时抓包不纳入 Git。生成入口见下文。 |
| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [.mcp.json](.mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 |
| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [mcp.json](mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 |
| `docs/` | 跨模块参考与审阅记录;Platform 模块说明和各域 README 提供当前 CLI 与服务导航,架构总纲见 [AGENTS.md](./AGENTS.md);`reviews/` 保留历史审阅及验证证据。 |
| `enterprises/` | 仅跟踪配置示例与 [目录说明](./enterprises/README.md)。实际企业配置默认放在 `~/.config/hose-use/enterprises/`,仓库内其他企业 JSON 被忽略。 |
| `.git/` 或 `.git` 文件 | Git 元数据;独立工作树中通常是指向共享仓库的文件。 |
@@ -167,7 +167,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
- [AGENTS.md](./AGENTS.md) 是项目开发规则总入口;`CLAUDE.md → AGENTS.md` 是兼容软链接,共享同一份内容。
- [package.json](./package.json)、`bun.lock` 与 [tsconfig.json](./tsconfig.json) 分别管理项目入口和命令、锁定依赖、配置 TypeScript;[.env.example](.env.example) 是环境变量示例。
- [.mcp.json](.mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。
- [mcp.json](mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.mcp.json](.mcp.json) 是 Claude Code 项目级 MCP 配置,避免把插件变量 `${CLAUDE_PLUGIN_ROOT}` 带到项目上下文;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。
- `ROADMAP.local.md` 等 `*.local.md` 是已忽略的本地笔记,不是构建依赖或正式文档入口;`.DS_Store` 是已忽略的 macOS Finder 元数据,可清理。
规范生成关系与命令:
+62
View File
@@ -9,6 +9,7 @@
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0",
"quickjs-emscripten-core": "0.32.0",
"yaml": "^2.9.0",
@@ -17,6 +18,7 @@
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
"typescript": "^5.9.3",
},
@@ -37,42 +39,102 @@
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
"@types/qrcode": ["@types/qrcode@1.5.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
"@types/qrcode-terminal": ["@types/qrcode-terminal@0.12.2", "", {}, "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q=="],
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"camelcase": ["camelcase@5.3.1", "", {}, "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg=="],
"cliui": ["cliui@6.0.0", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="],
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
"dijkstrajs": ["dijkstrajs@1.0.3", "", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
"find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
"locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
"p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
"p-locate": ["p-locate@4.1.0", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
"p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
"qrcode": ["qrcode@1.5.4", "", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
"qrcode-terminal": ["qrcode-terminal@0.12.0", "", { "bin": { "qrcode-terminal": "./bin/qrcode-terminal.js" } }, "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ=="],
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
"require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"require-main-filename": ["require-main-filename@2.0.0", "", {}, "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="],
"set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"which-module": ["which-module@2.0.1", "", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
"wrap-ansi": ["wrap-ansi@6.2.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
"y18n": ["y18n@4.0.3", "", {}, "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"yargs": ["yargs@15.4.1", "", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="],
"yargs-parser": ["yargs-parser@18.1.3", "", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
}
}
@@ -0,0 +1,205 @@
# 生产环境门禁系统性审计(2026-11-18)
## 结论摘要
1. 全仓库真正按企业环境(`prod`)做**硬拦截**的只有两处,都在 `workflow` 命令族:
- `workflow test`:生产调试需 `--force`
- `workflow nodes grant`:生产开通灰度节点需 `--allow-prod`
2. 其余所有写操作(工作流增删改发、单据审批、DataLink 记录编辑、费用类型、审批规则等)**没有环境级硬拦截**,只受统一的 `--dry-run` / `--yes` 两阶段确认保护。
3. 因此“生产环境被大面积禁用”不成立。此前客户侧遇到的问题,是 `workflow nodes grant` 在 PR #174(`8375445`)中被单独加成了“默认拒绝且明确不提供逃生口”,属于一次性的过度加固,而不是全局策略。
4. 当前两处门禁都有逃生口,但存在协议不一致:逃生参数命名不同、JSON 错误形状不同、预览行为不同、成功结果的可观测标记不同。
## 审计范围
- `src/core/config/`:环境属性判定与配置归一化
- `src/cli/`:所有命令的环境分支、确认机制与输出
- `src/domains/`、`src/server.ts`、`src/http/`:是否存在域层或网关层的环境拦截
- `skills/`、各层 README:文档与实际行为是否一致
- Git 历史:每个门禁的引入时间、背景与是否带逃生口
## 一、生产环境硬拦截清单(整改前)
| 命令 | 拦截动作 | 判定 | 逃生口 | 预览是否需要逃生口 | 确认要求 | JSON 错误 |
|---|---|---|---|---|---|---|
| `workflow test` | 在正式企业执行端到端调试(可能产生真实单据、外部调用、快照发布) | `isCorpProd(selectedCorp)` | `--force`(同时接受 `--allow-prod` / `--allow-production` 别名) | 否,`--dry-run` 先返回 | `--yes` / `--confirm` | ❌ `stdout` 为空,只有文本 `stderr` |
| `workflow nodes grant` | 为正式企业开通灰度节点(企业级不可逆能力变更) | `isCorpProd(selectedCorp)` | `--allow-prod` / `--allow-production` | 是,`--dry-run` 也必须带 `--allow-prod` | `--yes` / `--confirm` | ✅ `PROD_GRANT_BLOCKED` + `nextAction` |
关键代码:
- `src/cli/commands/workflow/test.ts:67`(判定)、`:393`(阻断)
- `src/cli/commands/workflow/node-catalog.ts:116`(判定)、`:122`(阻断)
- 环境判定:`src/core/config/types.ts:83-121`
## 二、确认机制覆盖(非环境门禁)
所有业务数据写操作都走 `requireMutationConfirmation` 或 `bill` 命令族自己的 `requireWriteConfirmation`,要求 `--dry-run` 预览后追加 `--yes`:
- 工作流:创建、复制、删除、启停、发布、草稿保存、节点增改删、节点映射、Webhook 发送、调试
- 单据:创建、复制、提交、删除、同意、驳回、转交、加签、评论
- 平台:DataLink 记录切换、编辑、批量编辑、重算
- 费用类型:新建、修改、启停、移动
- 审批规则:新增、删除
- 其他:登录、换票、密钥持久化、企业切换、环境打标、消息已读、协助平台动作
结论:写操作的安全基线是“两阶段确认”,不是“生产环境禁止”。
## 三、环境判定与打标机制
`src/core/config/types.ts`:
- 优先级:显式 `env` > `isTest` > 按名称/ID 推导 `inferCorpEnvFromName`
- 推导规则:名称或 ID 含“测试 / test” → `test`;含“演示 / POC / demo” → `demo`;否则 → `prod`
- `isCorpTest = env in (test, demo) || isTest === true`
- `isCorpProd = !isCorpTest`(保守默认:未标记一律视为生产)
- 配置加载时 `normalizeCorpConfig` 会把推导结果写回内存对象,因此所有显示路径拿到的 `corp.env` 实际已归一化
打标与筛选:
- `hose-use corps tag <企业> --test|--prod|--demo|--env=<env>` 持久化环境属性
- `--migrate-all` 按名称批量推导并持久化
- `corps list` 支持 `--test` / `--prod` / `--demo` / `--env` 筛选
- 当前本机配置的 29 家企业中,21 家判为 `prod`(包含未显式打标、按默认归为 `prod` 的),5 家 `test`,3 家 `demo`
## 四、发现的问题
### P1:`workflow test` 的生产阻断在 JSON 模式下不可解析
`src/cli/commands/workflow/test.ts:393-416` 在阻断时无条件返回:
- `stdout: ""`
- `stderr: "🛑 生产环境安全阻断 ..."`
当 `--json` / MCP / HTTP 调用时,Agent 拿到的是空 stdout 和文本 stderr,无法读取 `code`、`nextAction`、当前企业与逃生命令。这与 `workflow nodes grant` 的结构化 `PROD_GRANT_BLOCKED` 不一致,也是此前 `platform records --all` 同类问题的翻版。
建议:JSON 模式返回统一结构:
```json
{
"error": true,
"code": "PROD_WORKFLOW_TEST_BLOCKED",
"message": "正式生产企业执行工作流调试需显式追加 --force",
"exitCode": 1,
"nextAction": "hose-use workflow test <pipelineId> --yes --force",
"details": { "corpId": "...", "env": "prod" }
}
```
### P1:预览行为不一致
- `workflow test --dry-run` 在生产环境可以直接预览,不需要 `--force`。
- `workflow nodes grant --dry-run` 在生产环境仍会被门禁挡住,必须先加 `--allow-prod`。
预览不产生写操作,不应要求先接受生产风险。建议统一为“预览永远放行,执行才要求逃生口”,并让预览的 `nextAction` 带上逃生参数。
### P2:逃生参数命名与文档漂移
- `workflow test` 代码接受 `--force`、`--allow-prod`、`--allow-production`,但帮助只写 `--force`(`src/cli/help.ts:54`、`test.ts:50`)。
- `workflow nodes grant` 只使用 `--allow-prod`。
- 全仓没有统一的“生产覆盖”术语。
建议统一以 `--allow-prod` 作为跨命令的显式覆盖参数,`--force` 保留为兼容别名,并在帮助、README、Skill 中一致说明。
### P2:成功结果的可观测标记不一致
- `nodes grant` 在 JSON 与文本结果中标记 `productionOverride: true` 并打印风险提示。
- `workflow test` 只有 `warnings` 文本数组,没有机器可读的覆盖标记。
建议统一在成功结果中加入 `productionOverride: true` 与 `productionWarning`,便于自动化和审计。
### P2:`nodes grant` 门禁顺序
`node-catalog.ts:122` 的门禁发生在参数解析与 `--dry-run` 判断之前。生产环境下即使没有提供节点类型,也会先返回“生产阻断”,而不是“缺少节点类型”;同时导致上面的预览不一致。
建议顺序:参数校验 → `--dry-run` 预览放行 → 生产门禁 → 确认 → 执行。
### P2:`corps tag` 从生产改为测试缺少强化提示
`corps tag --test` 是解除两处生产门禁的唯一途径,但目前只有通用确认,没有“这会关闭该企业的生产保护”的显著警告,也没有审计记录。
建议:
- 当 `currentEnv === "prod"` 且目标是 `test` / `demo` 时,输出显著警告并要求再次确认;
- 可选:把打标变更写入本地审计日志(企业、旧值、新值、时间、操作人)。
### P3:名称推导存在双向误判
- 测试企业名称不含“测试 / test” → 被当作 `prod`(保守,但会误拦)。
- 正式企业名称或 ID 恰好含“test / 测试” → 被当作 `test`,跳过两处生产门禁(危险方向)。
建议在 `auth login` / `corps link` / OpenAPI 导入等新建配置的路径上,显式展示推导结果并提示使用 `corps tag` 固化;或导入时要求用户确认环境。
### P3:策略只在 CLI 层生效
两处门禁都在 `src/cli/commands/`。MCP 与 HTTP 网关都委托 `runCli`,因此自动继承;但直接使用 `hose-use/sdk` 或 `domains/*` 的调用方会绕过门禁。这是分层设计的结果,需要在 SDK 文档中明确“安全策略属于 CLI 层,SDK 调用方自行承担”。
### P3:文档残留
- `skills/hose-use/references/workflow.md:191` 仍以“生产企业默认被硬拦截”示范不带逃生口的命令,后两行才给出 `--allow-prod`。
- `src/cli/help.ts:54` 只描述 `--force`。
- `src/cli/README.cli.md:17` 与 `src/domains/platform/workflow/README.workflow.md:106,164` 已正确描述当前行为。
## 五、历史回溯
| 提交 | 日期 | 内容 | 评价 |
|---|---|---|---|
| `af1e11c` | 2026-10-16 | 引入 `env` / `isTest` 环境属性、`corps tag`、`workflow test` 生产阻断(带 `--force`) | 设计内的初始安全机制 |
| `103ead0` | 2026-10-17 | 为 workflow 命令补充 `allow-prod` / `allow-production` 参数词表 | 说明当时已考虑统一命名,但帮助文档未跟进 |
| `8375445` | 2026-11-05 | PR #174 给 `nodes grant` 加生产硬拦截,提交说明明确写着“不提供 `--force` 逃生口” | **本次问题的根因:一次性过度加固** |
| `8b03462` | 2026-11-18 | 增加 `--allow-prod` 逃生口、结构化 JSON、两阶段确认与 6 条单测 | 已修复,合并为 `d6d5d2d` |
结论:不是历史遗留的全局设计,而是一次 review 修复中夹带的单点硬编码。
## 六、整改建议(按优先级)
1. **统一生产门禁协议**
- `--allow-prod` 作为唯一显式覆盖参数,`--force` 兼容保留;
- JSON 错误统一 `{ error, code, message, exitCode, nextAction, details }`;
- 每个命令使用独立错误码(如 `PROD_WORKFLOW_TEST_BLOCKED`、`PROD_GRANT_BLOCKED`)。
2. **预览永远放行**
- `--dry-run` 不要求覆盖参数,且预览的 `nextAction` 自带 `--allow-prod` / `--force`。
3. **成功结果统一标记**
- `productionOverride: true` + `productionWarning`,文本与 JSON 一致。
4. **修正门禁顺序**
- 参数校验 → 预览 → 生产门禁 → 确认 → 执行。
5. **强化环境打标**
- `corps tag` 生产降级为测试时增加显著警告;
- 新建企业配置时展示推导环境并提示固化;
- 可选审计日志。
6. **文档统一**
- `help.ts`、`references/workflow.md`、README 统一到 `--allow-prod` 术语。
## 七、复核命令
```bash
# 环境分布与打标
hose-use corps list --json
hose-use corps list --test
hose-use corps list --prod
# 当前企业环境
hose-use context --json
hose-use probe --json
# 两处门禁的帮助
hose-use workflow test --help
hose-use workflow nodes --help
```
## 八、整改结果(2026-11-18,同批 PR)
本次审计发现的不一致已按“生产企业只多做一次显式确认,不禁止功能”的原则统一整改:
- 新增 `src/cli/production.ts`:`--allow-prod` 为唯一覆盖参数,`--allow-production` / `--force` 为兼容别名;阻断提示与 JSON 错误统一为 `PROD_OVERRIDE_REQUIRED`,包含 `nextAction` 与 `details.operation`。
- `workflow test`:JSON 模式返回结构化错误;生产阻断前移到任何网络请求之前;`--dry-run` 不要求覆盖参数;成功结果带 `productionOverride` / `productionWarning`。
- `workflow nodes grant`:参数校验前置;`--dry-run` 预览不再要求 `--allow-prod`;阻断结构与 `workflow test` 完全一致;成功结果同样带覆盖标记。
- `src/cli/mutation.ts` 新增 `buildConfirmedCommand`,所有预览与确认的 `nextAction` 统一生成,生产覆盖参数自动补齐。
- `corps tag` 将企业从 `prod` 降级为 `test` / `demo` 时输出显著警告,提示生产确认门禁将不再触发。
- 帮助、CLI README、workflow 域 README、Skill 与节点命令示例同步为 `--allow-prod` 术语。
- 单测覆盖:两命令的文本/JSON 阻断、预览免覆盖、`--force` 兼容、缺少参数优先报错、成功结果覆盖标记、降级警告。
整改后,生产企业执行敏感命令的行为是:
1. 预览永远可用;
2. 实际执行多一个显式 `--allow-prod`(或兼容的 `--force`),让用户确认“知道自己在操作生产企业”;
3. 仍然需要 `--yes` 确认;
4. CLI 不再替用户决定“生产环境不能做”。
+15
View File
@@ -0,0 +1,15 @@
{
"mcpServers": {
"hose-use": {
"type": "stdio",
"command": "bun",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"env": {
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
},
"timeoutMs": 120000
}
}
}
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.9.7",
"version": "0.9.9",
"module": "src/server.ts",
"type": "module",
"exports": {
@@ -49,6 +49,7 @@
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0",
"quickjs-emscripten-core": "0.32.0",
"yaml": "^2.9.0",
@@ -57,6 +58,7 @@
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
"typescript": "^5.9.3"
}
+2 -2
View File
@@ -22,13 +22,13 @@ function run(command, commandArgs) {
try {
// Explicit package inputs keep credentials, local notes and dependencies out of the archive.
for (const path of [".zcode-plugin/plugin.json", ".mcp.json", "skills"]) {
for (const path of [".zcode-plugin/plugin.json", "mcp.json", "skills"]) {
cpSync(join(root, path), join(stage, path), { recursive: true });
}
// Always build from current source; never package a stale local dist/ bundle.
run(process.execPath, [join(root, "scripts/build/build-plugin.mjs"), `--outfile=${join(stage, "dist/mcp/server.js")}`]);
mkdirSync(outputDir, { recursive: true });
run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", ".mcp.json", "skills", "dist"]);
run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", "mcp.json", "skills", "dist"]);
console.log(`✓ Packaged plugin: ${archive}`);
} finally {
rmSync(stage, { recursive: true, force: true });
+1 -1
View File
@@ -17,7 +17,7 @@ test("source and freshly packaged plugin preserve offline review and MCP contrac
mkdirSync(pluginRoot);
const extracted = Bun.spawnSync(["tar", "-xzf", archive, "-C", pluginRoot]);
expect(extracted.exitCode, extracted.stderr.toString()).toBe(0);
expect(readdirSync(pluginRoot).sort()).toEqual([".mcp.json", ".zcode-plugin", "dist", "skills"]);
expect(readdirSync(pluginRoot).sort()).toEqual([".zcode-plugin", "dist", "mcp.json", "skills"]);
const manifest = JSON.parse(readFileSync(join(pluginRoot, ".zcode-plugin/plugin.json"), "utf8"));
expect(manifest.version).toBe(version);
expect(manifest.skills).toBe("skills");
+123
View File
@@ -0,0 +1,123 @@
// ==============================================================================
// 合思代码节点 (MVEL): 单据日期/日期范围字段转化为具体时间字符串与时间戳
// ==============================================================================
// ── 1. 配置区(按需修改)───────────────────────────────────────────────────────
// (1) 前置工作流节点 ID(例如:第2步单据详情节点 action_pfsq28)
upstreamNode = action_pfsq28;
// (2) 需要转化的单据层面字段 ID(例如标准起止日期 "feeDatePeriod",或自定义字段 "u_出差起止日期")
dateFieldKey = "feeDatePeriod";
// ── 2. 字段取值与防御提取 ──────────────────────────────────────────────────────
fieldVal = null;
if (upstreamNode != null) {
fieldVal = upstreamNode.get(dateFieldKey);
if (fieldVal == null && upstreamNode.get("form") != null) {
fieldVal = upstreamNode.get("form").get(dateFieldKey);
}
}
rawStart = null;
rawEnd = null;
if (fieldVal != null) {
if (fieldVal instanceof java.util.Map) {
rawStart = fieldVal.get("start");
rawEnd = fieldVal.get("end");
} else {
rawStart = fieldVal;
}
}
// ── 3. 初始化日期格式化器(强制北京时间 GMT+8) ────────────────────────────────
tz = java.util.TimeZone.getTimeZone("GMT+8");
sdfSecond = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfSecond.setTimeZone(tz);
sdfMinute = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
sdfMinute.setTimeZone(tz);
sdfDay = new java.text.SimpleDateFormat("yyyy-MM-dd");
sdfDay.setTimeZone(tz);
// ── 4. 转换开始时间 (start) ───────────────────────────────────────────────────
startStr = "";
startMinute = "";
startDay = "";
startMs = 0L;
startSec = 0L;
dStart = null;
if (rawStart != null && String.valueOf(rawStart).trim() != "") {
startMs = java.lang.Long.parseLong(String.valueOf(rawStart).trim());
if (startMs < 10000000000L) {
startMs = startMs * 1000L;
}
startSec = startMs / 1000L;
dStart = new java.util.Date(startMs);
startStr = sdfSecond.format(dStart);
startMinute = sdfMinute.format(dStart);
startDay = sdfDay.format(dStart);
}
// ── 5. 转换结束时间 (end) ─────────────────────────────────────────────────────
endStr = "";
endMinute = "";
endDay = "";
endMs = 0L;
endSec = 0L;
dEnd = null;
if (rawEnd != null && String.valueOf(rawEnd).trim() != "") {
endMs = java.lang.Long.parseLong(String.valueOf(rawEnd).trim());
if (endMs < 10000000000L) {
endMs = endMs * 1000L;
}
endSec = endMs / 1000L;
dEnd = new java.util.Date(endMs);
endStr = sdfSecond.format(dEnd);
endMinute = sdfMinute.format(dEnd);
endDay = sdfDay.format(dEnd);
}
// ── 6. 组合区间显示文本 ───────────────────────────────────────────────────────
rangeMinuteStr = "";
rangeSecondStr = "";
if (startMinute != "" && endMinute != "") {
rangeMinuteStr = startMinute + " ~ " + endMinute;
rangeSecondStr = startStr + " ~ " + endStr;
} else if (startMinute != "") {
rangeMinuteStr = startMinute;
rangeSecondStr = startStr;
}
// ── 7. 组装返回结果 ───────────────────────────────────────────────────────────
result = new java.util.HashMap();
// 开始时间 / 单个时间
result.put("startTimeStr", startStr); // 如: "2026-11-19 20:59:00"
result.put("startTimeMinute", startMinute); // 如: "2026-11-19 20:59"
result.put("startDate", startDay); // 如: "2026-11-19"
result.put("startTimestampMs", startMs); // 毫秒时间戳 (Long)
result.put("startTimestampSec", startSec); // 秒时间戳 (Long)
// 结束时间
result.put("endTimeStr", endStr); // 如: "2026-11-20 16:55:00"
result.put("endTimeMinute", endMinute); // 如: "2026-11-20 16:55"
result.put("endDate", endDay); // 如: "2026-11-20"
result.put("endTimestampMs", endMs); // 毫秒时间戳 (Long)
result.put("endTimestampSec", endSec); // 秒时间戳 (Long)
// 区间文本(方便下游直接放入 comment 或通知)
result.put("rangeMinuteStr", rangeMinuteStr); // 如: "2026-11-19 20:59 ~ 2026-11-20 16:55"
result.put("rangeSecondStr", rangeSecondStr); // 如: "2026-11-19 20:59:00 ~ 2026-11-20 16:55:00"
// 兼容单日期直接取用别名
result.put("formattedTime", startStr);
result.put("formattedMinute", startMinute);
result.put("timestampMs", startMs);
result.put("timestampSec", startSec);
return result;
+8 -1
View File
@@ -136,7 +136,14 @@ describe("release preparation and publication guards", () => {
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");
const pluginMcp = JSON.parse(readFileSync(join(root, "mcp.json"), "utf8")).mcpServers["hose-use"];
expect(pluginMcp.command).toBe("bun");
expect(pluginMcp.args[0]).toContain("${CLAUDE_PLUGIN_ROOT}");
const projectMcp = JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"];
expect(projectMcp.command).toBe("bun");
expect(projectMcp.args).toEqual(["src/server.ts"]);
expect(JSON.stringify(projectMcp)).not.toContain("${CLAUDE_PLUGIN_ROOT}");
expect(JSON.stringify(projectMcp)).not.toContain("${user_config");
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
for (const name of ["Compile multi-target binaries", "Package plugin archive", "Package release archives", "Publish GitHub Release"]) {
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
+2 -2
View File
@@ -2,11 +2,11 @@
name: hose-aipro
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
metadata:
version: 0.9.7
version: 0.9.9
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
---
# hose-aipro (v0.9.7)
# hose-aipro (v0.9.9)
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
+20 -6
View File
@@ -2,11 +2,11 @@
name: hose-use
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.9.7
version: 0.9.9
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.9.7)
# hose-use (v0.9.9)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
@@ -39,6 +39,7 @@ metadata:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
- **扫码登录交互**:在执行扫码登录 (`login --qr`) 时,Agent 必须主动监控终端输出。一旦识别出二维码已保存(如提示 “💡 二维码已自动保存至: ...”),Agent **必须立即且自动**调用 `SendUserFile` 将该二维码图片渲染给用户查看,严禁等待用户主动提示。
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
@@ -60,12 +61,12 @@ metadata:
11. **本地企业名录最高可信度与合思 payType 混淆防范(Local Config as Source of Truth & PayType Trap)**:
- **本地配置具有最高权威性**:本地企业名录(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)经过人工审核确认,是判断企业真实性质的唯一权威来源;
- **合思云端 payType 极度混乱陷阱**:合思数据库中的元数据 `payType`(如 `TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式客户租户在系统底层依然被标记为 `TRYOUT`(试用)**;
- **严禁仅凭云端标记臆断测试沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"`、或企业名称简短/包含英文就盲目认定为测试沙箱。任何写操作(包括发起协助工单 `assist-platform apply`、单据或配置变更)必须严格核对本地企业环境,仅在明确标记为 🧪 测试 的企业中进行,正式企业必须有用户显式指令与二次确认。
- **严禁仅凭云端标记臆断测试沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"`、或企业名称简短/包含英文就盲目认定为测试沙箱。任何写操作(包括发起协助工单 `assist-platform apply`、单据或配置变更)必须严格核对本地企业环境。测试/演示企业按正常两阶段确认执行;正式生产企业**不禁止**,但必须同时满足:① 用户已明确指令对该企业执行;② 完成 `--dry-run` 预览与 `--yes` 确认(涉及 `workflow test` / `workflow nodes grant` 时追加 `--allow-prod`)。Agent 不得仅因企业是正式生产环境而自行拒绝用户已明确授权的操作。
12. **工作流草稿非隔离副本与生产介入明确知情权(Draft != Isolated Clone & Explicit Awareness)**:
- **草稿绝非独立副本**:合思工作流处于草稿态(`state: 0`)仅代表“修改尚未发布生效”,它与生产流程是**同一个实体**。若直接在原流程上修改草稿,一旦点击发布就会直接覆盖生产运行逻辑,绝不可将其误认为互不影响的沙箱副本;
- **排障或改造的知情选择权**:客户现场常存在“原本有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。Agent 介入排障或调整前,**必须向用户明确揭示实体归属与当前状态**,并提供两条明确路径供用户决策:
1. **克隆独立副本(推荐稳健路径)**:使用 `hose-use workflow copy <pipelineId>` 创建真正的独立工作流副本(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改;**未经用户明确指令不得点击发布(publish)**,完成全链路验证并获得用户确认后即可上线。
13. **协助会话人员身份角色穿透与高管权限防误用守则 (Assist Identity Profile & Executive Privilege Guard)**:
- **身份与角色权限第一时间穿透呈现**:通过协助链接进入企业(`hose-use assist-platform enter`)或生成免密会话时,系统自动穿透解析并输出当前获得的员工姓名、工号、所属部门、所配角色清单以及核心系统权限;并自动将该人员画像与风控等级持久化落盘至本地企业配置(`enterprises/<corpId>.json`);
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
@@ -97,6 +98,15 @@ metadata:
2. 关键词检索:`hose-use docs search <关键词> [--category=<分类>] [--json]`(毫秒级获取接口清单与废弃标记);
3. 单篇精细查阅:`hose-use docs show <Path|URL|名称> [--json]`(获取官方完整参数规格、类型约束与 CURL 示例);
- 细节查阅专属参考文档:[references/docs.md](./references/docs.md)。
19. **三大凭证通道矩阵与人工直通链接守则 (Three-Tier Credential Channels & Passwordless Direct Links)**:
- **通道 A:企业 OpenAPI 持久化凭证 (`appKey` + `appSecurity`)**:企业级永久凭证,永不过期。当用户/开发者提出“生成免密链接 / 去界面人工 review / 看看画布”等直达需求时,**第一首选动作**是调用 `hose-use corps link <corpId>` 或 `hose-use workflow link <pipelineId>`。底层通过 `getProvisionalAuth` 动态签发带安全签名的 Web 直达 URL(`thirdparty.html?accessToken=...` 或直接带 EASO JWT 的 Piper 画布链接),任意浏览器点开即免密登录!
- **通道 B:用户个人会话凭证 (`userAuthToken` / `cloudAuthToken`)**:个人会话凭证(手机验证码/密码),存在 TTL。供 CLI 在终端执行 API 读写、单据查询、调测。
- **通道 C:协助运营平台工单会话 (`assist-platform`)**:合思官方技术支持(实施/客服)跨企业工单流转平台(Unity)。仅限在处理客户授权工单流转时使用(`assist-platform transfer` / `assist-platform list`),**严禁**直接向用户丢出未签名的 Unity 运营平台登录页让用户手动登录。
- **非冲突双轨共存**:企业即便通过用户个人凭证登录,如果本地已配置过自建应用的 `appKey` / `appSecurity`,两者完全互不冲突、协同工作。
20. **工作流节点 Schema 规范与前端图标降级防范 (Workflow Node Schema & Fallback Trap)**:
- 合思前端微前端设计器(Piper)将节点图标分为 `action`(基础通用)与 `control`(控制节点:仅包含 condition、every、while、loop、if)两套硬编码字典;
- **终止节点 (`stop`) 必须标记为 `groupName: "action"`**(归属基础通用);若错误标记为 `control`,前端在控制字典查无此项时会触发 Fallback 降级,被强行渲染为灰色通用工具扳手(`[🔧]` `OutlinedGeneralTool`);只有保持 `groupName: "action"` 才会正常渲染为官方红色禁止标(`[⛔]` `OutlinedTipsNo`)。
- **代码节点 (`code` / `code-js2`)** 同样归属于 `action`。
---
@@ -116,7 +126,7 @@ metadata:
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](./references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](./references/auth.md) |
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](./references/auth.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>] [--state=draft]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) |
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](./references/bill.md) |
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](./references/bill.md) |
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](./references/bill.md) |
@@ -191,7 +201,10 @@ hose-use bill list --keyword=打车 # 单据关键字跨
hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等)
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose-use bill list --state=draft --json # 查询我发起的未提交草稿(flows/my 数据源)
hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 # 草稿模板/标题/提交人过滤
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose-use bill get <单号|flowId> # 草稿也支持按 flowId 直读(工作流 Job 输出)
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
hose-use bill approve S26000001 --yes # 同意当前待办
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
@@ -266,7 +279,7 @@ hose-use workflow publish wf_01k83y... --yes # 将保存后的工
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
hose-use workflow nodes grant code-js2 --dry-run # 预览灰度开通变更(含固定附带开关)
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业默认硬拦截,需 --allow-prod
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业需追加 --allow-prod
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 webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
@@ -313,6 +326,7 @@ hose-use docs sync # 强制与 docs.ekuaib
## 全局选项
- `--timeout`, `-T <seconds>`:命令全局超时时间,超时后自动终止运行。
- `--corp=<id>`:临时指定操作的企业 ID(单次覆盖默认企业)
- `--json`, `-j`:以标准 JSON 结构化输出结果
- `--output-file, -o <path>`:将结果直接安全写入本地文件,仅返回精简摘要
@@ -158,3 +158,22 @@ Treat tenant-specific behavior as evidence, not a universal rule. Say what assum
- **Deploy to workflow node**: `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/node_calc.mvel --yes`
- **End-to-end cloud simulation test**: `hose-use workflow test <pipelineId> --flow <billCode> --yes --force`
## 沙箱调试绝佳技巧:终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning)
在真实业务流程(尤其包含单据驳回、审批通过、企微/钉钉消息推送、台账更新等危险副作用)中调测新增的代码节点时,强烈建议采用**紧随终止节点 (Stop Node Barrier)** 模式:
```text
[前置查询/触发节点] ──> [新代码节点 (MVEL)] ──> [临时终止节点 (stop)] ──x (下游循环/驳回/审批被彻底物理隔离)
```
### 1. 为什么必须紧随终止节点?
1. **防止业务穿透与脏数据(安全第一)**:调试执行由云端真实引擎运行。若不设断点,引擎向下执行一旦命中驳回 HTTP 节点或审批同意,会向真实系统发起调用;紧随插入一个 `stop` 节点可形成绝对安全隔离,执行到代码节点后即刻安全着陆。
2. **纯净捕获真实出参**:在安全阻断的同时,当次调试 Job 的 `executionTree` 产物中能完整记录新代码节点的实际返回值(`output`),验证数据精度与格式。
### 2. 保存样本数据 (Sample Pinning) 赋能设计器下拉树
代码节点在没有样本数据(`sampleData`)前,下游节点在合思设计器中打开「引用字段」下拉菜单时**无法识别其输出属性**。
- **固化样本**:调试成功后,将当次执行的 `output` 一键回写为该节点的 `sampleData`(如使用 `hose-use workflow test ... --save-sample` 或 `workflow node sample-save`);
- **设计器自动解析**:一旦保存样本,合思工作流会自动为该代码节点生成选择器树(chooses),后续人工在配置下游驳回、条件或消息节点时,即可在界面下拉树中直接点选其格式化变量(如 `startTimeMinute`, `rangeMinuteStr`);
- **调试后清理**:业务验证并完成下游表达式配置后,在界面上手动删除该临时的终止节点即可。
@@ -28,8 +28,8 @@ CLI 使用本地企业配置中的 `accessToken`、员工 ID 和 `baseUrl` 完
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
hose-use workflow nodes grant code risk --corp=<corpId> --yes
# 正式生产企业:默认被硬拦截,需显式追加 --allow-prod
hose-use workflow nodes grant code risk --corp=<corpId> --allow-prod --dry-run
# 正式生产企业:执行前需显式追加 --allow-prod 确认环境(--force 兼容;预览可省略)
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
hose-use workflow nodes grant code risk --corp=<corpId> --allow-prod --yes
```
@@ -39,7 +39,7 @@ hose-use workflow nodes grant code risk --corp=<corpId> --allow-prod --yes
`--dry-run` 只预览操作,不会探测企业对应的 Piper 环境。成功开通可以确认所选环境;请求失败本身不能单独证明环境选错,还应检查认证错误和 Piper 返回的业务错误。确认目标使用测试 Piper 后,才在原命令上加 `--is-test`;该选项不会根据企业信息自动开启。
**生产企业默认硬拦截**:CLI 用 `isCorpProd` 判定企业,正式生产环境(含未标记、按名称保守推断为 prod 的企业)默认拒绝。灰度节点开通是不可逆的企业级写操作;确需在生产环境执行时,必须显式追加 `--allow-prod` 承担风险,并继续遵守 `--dry-run` 预览 → `--yes` 执行的两阶段确认。`--is-test` 仅切换 Piper 域名,不构成对生产企业的授权。`--dry-run` 预览会展示 Piper 固定附带开关(`recalculate-the-approval-flow`、`ui-notification`、`start`),与实际 payload 一致。
**生产企业需显式确认,但不禁止**:CLI 用 `isCorpProd` 判定企业,正式生产环境(含未标记、按名称保守推断为 prod 的企业)实际执行时必须追加 `--allow-prod`(`--force` 为兼容别名),表明操作者已知晓目标为生产企业;预览 `--dry-run` 始终放行。灰度节点开通仍是不可逆的企业级写操作,执行仍遵守 `--dry-run` 预览 → `--yes` 确认的两阶段约束。`--is-test` 仅切换 Piper 域名,不构成对生产企业的授权。`--dry-run` 预览会展示 Piper 固定附带开关(`recalculate-the-approval-flow`、`ui-notification`、`start`),与实际 payload 一致。
## 结果处理
@@ -64,7 +64,7 @@ hose-use assist-platform tickets <企业ID> --all --limit 20
> [!WARNING] 合思底层 payType 混淆与本地企业名录可信度原则
> 1. **合思付费模式混乱**:合思数据库中的 `payType`(`TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式生产客户在系统中依然被标记为 `TRYOUT`(试用)**。
> 2. **严禁仅凭云端标记臆断沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"` 擅自推断企业为测试沙箱!
> 3. **本地配置权威优先**:判断企业性质必须以本地企业配置(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)为准,本地配置具有最高权威性。任何写操作(如发起协助工单 `apply`)严禁在未经授权的正式企业上执行。
> 3. **本地配置权威优先**:判断企业性质必须以本地企业配置(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)为准,本地配置具有最高权威性。任何写操作(如发起协助工单 `apply`)在正式企业上必须先获得用户明确授权,并完成 `--dry-run` → `--yes` 确认;用户明确授权后,不得仅因环境为生产而拒绝执行。
---
@@ -84,7 +84,7 @@ hose-use assist-platform staff <企业ID> --mobile "13800000000"
## 5. 发起协助申请工单 (`apply`)
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作仅限在本地确认的 🧪 测试企业中进行,正式企业必须获得用户明确指示。**
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作在测试企业按正常两阶段确认执行;正式企业必须获得用户明确指示,并在 `--dry-run` → `--yes` 确认后执行,不得仅因环境为生产而自行拒绝。**
> [!IMPORTANT] 协助时长服务端硬性上限与 24 小时限制
> 合思协助平台服务端(`POST /api/assistPlatform/create`)实施了底层的硬性安全管控:
+13 -2
View File
@@ -22,9 +22,10 @@ hose-use bill list --corp=uzU7pcWfScck00 --json
- `--since=<duration>` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时;
- `--start-date=<date>` / `--end-date=<date>`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳);
- `--stage=<stage>`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款);
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中, `draft` 草稿);
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中)。`--state=draft`(或 `草稿`)使用专用草稿列表:草稿尚未进入台账索引,数据源为「我发起」的 `flows/my`;
- 草稿专用过滤:`--template=<模板ID>`、`--title=<标题关键字>`、`--staff=<姓名|工号|员工ID>`、`--page=<页码>`(与 `--count` 配合分页);
- `--count=<number>` / `--limit` / `-n`: 单页拉取数量(默认 20);
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`);
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`;`--state=draft` 时仍走草稿列表);
- `--select=<fields>`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`);
- `--distinct`: 是否对单据记录去重。
@@ -40,8 +41,18 @@ hose-use bill list --code=CL20260901001
# 查询近 30 天已支付的报销单
hose-use bill list --since=30d --stage=expense --state=paid --limit=50
# 查询我发起的未提交草稿(支持模板、标题、提交人与分页过滤)
hose-use bill list --state=draft
hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 --count=20
# 草稿详情:支持单号或 flowId(工作流创建的草稿可用 Job 输出里的 flowId 查询)
hose-use bill get <单号|flowId>
```
> 草稿列表只覆盖当前身份可见的「我发起」流程。他人或系统创建的草稿可能不在 `flows/my` 中;
> 已知单号时用 `bill get <单号>`,已知 flowId 时用 `bill get <flowId>` 直读详情。
---
## 2. 单据详情精准下钻 (`bill get`)
+14 -4
View File
@@ -187,12 +187,15 @@ hose-use workflow nodes
hose-use workflow nodes --all
# 3. 申请开通灰度节点(支持中文名归一化;同名节点需改用明确的 type)
hose-use workflow nodes grant code-js2 --dry-run # 预览变更,含 Piper 固定附带开关
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业默认被硬拦截
hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:显式承担风险后预览
hose-use workflow nodes grant code-js2 --dry-run # 预览变更,含 Piper 固定附带开关(生产企业也放行)
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业需补 --allow-prod
hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:预览(覆盖参数可省略)
hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行
```
> 生产企业执行敏感命令时,CLI 只要求显式 `--allow-prod` 表明已知晓目标环境,不禁止功能;
> `--force` 为兼容别名。JSON 模式下的阻断统一为 `PROD_OVERRIDE_REQUIRED`,并带 `nextAction`。
## 8. 工作流单次运行实例排障 (`workflow job`)
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
@@ -284,7 +287,7 @@ hose-use workflow publish <pipelineId>
> - **草稿态实质**:合思工作流的草稿状态(`state: 0`)仅表示“改动尚未发布对线上生效”,它与线上流程是**同一个实体**。直接在生产工作流上改草稿,一旦点击发布就会直接覆盖线上运行逻辑,绝不可将其误认为独立的沙箱副本;
> - **生产排障与改造的知情权**:客户现场常存在“原有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。介入排障或调整前,**必须向用户明确说明当前实体性质**,并提供清晰决策路径:
> 1. **克隆独立副本(推荐稳健路径)**:使用 `workflow copy` 克隆出新流水线(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
> 2. **就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并同意直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
> 2. **就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并同意直接修复当前草稿,则就地修改;**未经用户明确指令不得点击发布(publish)**,完成全链路验证并获得用户确认后即可上线。
```bash
# 1. 从零新建工作流(支持自动初始化 Webhook、定时 Clock、业务对象 DataLink 或单据 Flowform 首节点)
@@ -349,6 +352,13 @@ hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
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
# 6. 只读探针与样本数据固化 (inspect / sample-save)
# 定向透视指定节点的固化样本数据 (sampleData) 以及最近一次调试执行出参 (execution output)
hose-use workflow node inspect <pipelineId> <nodeName>
# 将最近一次调测出参一键固化为 sampleData,使设计器下游节点可自动解析其选择器树 (chooses)
hose-use workflow node sample-save <pipelineId> <nodeName> --yes
```
---
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.9.7
version: 0.9.9
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+28 -1
View File
@@ -27,9 +27,36 @@ list:
- name: state
in: query
required: false
description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)
description: >-
按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用
「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。
schema:
type: string
- name: template
in: query
required: false
description: 草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希
schema:
type: string
- name: title
in: query
required: false
description: 草稿模式下按标题关键字过滤
schema:
type: string
- name: staff
in: query
required: false
description: 草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤
schema:
type: string
- name: page
in: query
required: false
description: 页码,与 count 配合分页(从 1 开始)
schema:
type: integer
default: 1
- name: count
in: query
required: false
+39 -2
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.9.7",
"version": "0.9.9",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
@@ -662,11 +662,48 @@
"name": "state",
"in": "query",
"required": false,
"description": "按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)",
"description": "按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用 「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。",
"schema": {
"type": "string"
}
},
{
"name": "template",
"in": "query",
"required": false,
"description": "草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希",
"schema": {
"type": "string"
}
},
{
"name": "title",
"in": "query",
"required": false,
"description": "草稿模式下按标题关键字过滤",
"schema": {
"type": "string"
}
},
{
"name": "staff",
"in": "query",
"required": false,
"description": "草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤",
"schema": {
"type": "string"
}
},
{
"name": "page",
"in": "query",
"required": false,
"description": "页码,与 count 配合分页(从 1 开始)",
"schema": {
"type": "integer",
"default": 1
}
},
{
"name": "count",
"in": "query",
+19 -2
View File
@@ -15,6 +15,23 @@ process.stderr.on("error", (err: any) => {
const entryFile = fileURLToPath(import.meta.url);
const appRoot = dirname(dirname(entryFile));
// 命令行参数超时处理:--timeout [秒] / -T [秒]
const args = process.argv.slice(2);
for (let i = args.length - 1; i >= 0; i--) {
if (args[i] === "--timeout" || args[i] === "-T") {
if (i + 1 < args.length) {
const timeoutSec = parseInt(args[i + 1], 10);
if (!isNaN(timeoutSec) && timeoutSec > 0) {
setTimeout(() => {
console.error(`[ERROR] 命令执行超时 (${timeoutSec}秒)`);
process.exit(1);
}, timeoutSec * 1000);
}
args.splice(i, 2);
}
}
}
// Unix Multicall Binary Pattern: 检测是否通过 hose-aipro 符号链接/别名唤起
const candidates = [process.argv0, process.argv[1], process.argv[0]].filter(Boolean) as string[];
const isAiPro = candidates.some((c) => {
@@ -23,8 +40,8 @@ const isAiPro = candidates.some((c) => {
});
const result = isAiPro
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
: await runCli(process.argv.slice(2), {
? await (await import("./aipro-cli.js")).runAiProCli(args)
: await runCli(args, {
appRoot,
entryFile,
writeStdout: writeStdoutChunk,
+1 -1
View File
@@ -14,7 +14,7 @@
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感命令,在正式生产企业 (`env === "prod"`) 执行时触发硬阻断。`workflow test` 需显式带 `--force` 确认生产风险;`workflow nodes grant` 需显式带 `--allow-prod`,并继续遵守 `--dry-run`/`--yes` 两阶段确认。自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `生产环境确认 (Production Safeguard)`:`src/cli/production.ts` 统一策略。正式生产企业 (`env === "prod"`) 执行敏感命令时,只要求显式追加 `--allow-prod` 表明操作者已知晓目标为生产企业,不禁止功能;`--force` 保留为兼容别名。预览 (`--dry-run`) 始终放行,不要求覆盖参数;实际执行仍遵守 `--dry-run`/`--yes` 两阶段确认。阻断统一返回文本提示或 JSON 错误 `PROD_OVERRIDE_REQUIRED`(含 `nextAction` 与 `details.operation`)。自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
- `help.ts`:帮助文本组织。
+4 -3
View File
@@ -340,7 +340,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"outbound-message": "outbound"
},
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 is-test 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 choose-serialization 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 max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit 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 seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start 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 is-test json none once publish save-sample saveSample save-samples saveSamples 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 choose-serialization 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 max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit 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 seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start 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": {
@@ -376,6 +376,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"--dry-run 只预览审批动作",
"--yes/--confirm 确认执行审批动作",
"--comment=<原因> 驳回或评论内容",
"--state=draft/草稿 查询未提交草稿(数据源为 flows/my),支持 --template/--title/--staff/--page 过滤",
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
],
"aliases": [
@@ -415,7 +416,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"url": "link",
"specification": "spec"
},
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice 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 template title to amount reason fee-type feeType", "value") }
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice 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 page 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 template title to amount reason fee-type feeType", "value") }
},
"flow": {
"summary": "审批流全域透视与穿透诊断",
@@ -447,7 +448,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"show": "get",
"find": "get"
},
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice 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") }
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice 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 page 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": "企业通讯录与人员检索",
+15
View File
@@ -11,6 +11,9 @@ import {
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
// ... other imports ...
import os from "os";
import path from "path";
export async function handleLogin(
parsed: CliParsedArgs,
@@ -184,6 +187,18 @@ export async function handleLogin(
process.stdout.write(`\n====== 合思协助平台钉钉扫码登录 ======\n`);
process.stdout.write(`请使用钉钉 App 扫描下方二维码确认登录(有效期 60 秒):\n\n`);
process.stdout.write(`${qrText}\n\n`);
// 自动保存二维码
const downloadsDir = path.join(os.homedir(), "Downloads");
const qrPath = path.join(downloadsDir, "dingtalk-login.png");
(async () => {
const QRCode = await import("qrcode");
await QRCode.toFile(qrPath, dingUrl);
process.stdout.write(`💡 二维码已自动保存至: ${qrPath}\n\n`);
})().catch((e: Error) => {
process.stdout.write(`[WARN] 自动保存二维码失败: ${e.message}\n\n`);
});
process.stdout.write(`🔗 快捷授权链接: ${dingUrl}\n\n`);
process.stdout.write(`等待钉钉扫码并确认中... (最长等待 60 秒)\n`);
}
+106
View File
@@ -0,0 +1,106 @@
import { afterEach, describe, expect, it, spyOn } from "bun:test";
import * as session from "../../../core/http/hose-web-session-client.js";
import { parseArgs } from "../../parser.js";
import { createBillActionContext } from "./context.js";
import { handleList } from "./search.js";
const spies: Array<{ mockRestore(): void }> = [];
afterEach(() => {
for (const spy of spies.splice(0).reverse()) spy.mockRestore();
});
function json(value: unknown): Response {
return new Response(JSON.stringify(value));
}
function draftClient(corpId: string) {
const flowsPosts: any[] = [];
const client = {
get: async (url: string) => {
if (url.includes("staffs/actives")) {
return json({ items: [{ id: "staff-1", name: "张三", code: "1001" }] });
}
return json({});
},
post: async (url: string, payload: any) => {
if (url.includes("datalink/entity/search")) return json({ items: [] });
if (url.endsWith("/flows/my")) {
flowsPosts.push({ url, payload, corpId });
return json({
count: 1,
items: [{
flow: {
id: "flow-cli-draft",
state: "draft",
formType: "payment",
createTime: 1781682826000,
updateTime: 1781682870000,
},
form: {
code: "FK26000009",
title: "付款草稿CLI",
specificationId: { id: "spec-pay", name: "对公付款单" },
submitterId: { id: "staff-1", name: "张三", code: "1001" },
payMoney: { standard: "10.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
}],
});
}
return json({});
},
};
return { client, flowsPosts };
}
function context(args: string[], corpId: string, jsonMode: boolean) {
const corp = { id: corpId, name: "测试企业", credentials: { corpId } };
return createBillActionContext(parseArgs(args), { jsonMode, selectedCorp: corp } as any);
}
describe("bill list draft mode", () => {
it("routes --state=draft to flows/my with template, title, submitter and page filters", async () => {
const { client, flowsPosts } = draftClient("cli-draft-corp-json");
spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any));
const args = [
"bill", "list", "--state=draft", "--mine",
`--template=spec-pay:${"a".repeat(32)}`,
"--title=付款", "--staff=张三",
"--page=2", "--count=10", "--json",
];
const result = await handleList(context(args, "cli-draft-corp-json", true));
expect(result.exitCode).toBe(0);
const output = JSON.parse(result.stdout);
expect(output.total).toBe(1);
expect(output.items[0]).toMatchObject({
billId: "flow-cli-draft",
billCode: "FK26000009",
billName: "付款草稿CLI",
state: "draft",
});
expect(output.items[0].amount).toContain("10.00");
expect(flowsPosts).toHaveLength(1);
const filterBy = flowsPosts[0].payload.json.filterBy as string;
expect(filterBy).toContain('(state.in("draft"))');
expect(filterBy).toContain('INSTR(form.title, "付款")');
expect(filterBy).toContain('INSTR(form.specificationId, "spec-pay")');
expect(filterBy).not.toContain("a".repeat(32));
expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")');
expect(flowsPosts[0].payload.json.limit).toEqual({ start: 10, count: 10 });
expect(flowsPosts[0].payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]);
});
it("renders a draft-specific text header for --state=草稿", async () => {
const { client } = draftClient("cli-draft-corp-text");
spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any));
const result = await handleList(context(["bill", "list", "--state=草稿"], "cli-draft-corp-text", false));
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("单据草稿列表");
expect(result.stdout).toContain("FK26000009");
expect(result.stdout).toContain("bill submit");
});
});
+75 -24
View File
@@ -1,4 +1,10 @@
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js";
import {
getBillByCodeOrId,
getBillRisk,
searchAndFormatBills,
searchAndFormatDraftBills,
traceBillFlowDetail,
} from "../../../domains/bill/tools.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliResult } from "../../types.js";
@@ -6,8 +12,10 @@ import type { BillActionContext } from "./context.js";
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const state = stringOption(parsed.options, ["state", "s"]);
const isDraft = state ? /^(draft|草稿)$/i.test(state.trim()) : false;
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
if (mine) {
if (mine && !isDraft) {
const { handleTaskCommand } = await import("./../task.js");
return handleTaskCommand(
{
@@ -23,8 +31,9 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
const page = Math.max(1, numberOption(parsed.options, ["page"], 1) ?? 1);
const start = (page - 1) * count;
const since = stringOption(parsed.options, ["since", "days", "d"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
@@ -34,21 +43,54 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
const select = stringOption(parsed.options, ["select", "fields"]);
const distinct = booleanOption(parsed.options, ["distinct"]);
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
code,
keyword,
searchFields,
stage,
state,
count,
since,
startDate,
endDate,
order,
filterBy,
select,
distinct,
});
const title = stringOption(parsed.options, ["title"]);
const rawTemplate = stringOption(parsed.options, [
"template",
"spec",
"specification",
"specification-id",
"specificationId",
]);
const templateId = rawTemplate
? rawTemplate
.trim()
.replace(/^\[|\]$/g, "")
.replace(/:[0-9a-f]{32,64}$/i, "")
: undefined;
const staffValues = ctx.listOption(["staff", "staff-id"]);
const submitterIds =
isDraft && staffValues?.length ? await ctx.resolveApproverIds(staffValues) : undefined;
const result = isDraft
? await searchAndFormatDraftBills(await ctx.getClient(), corpId, {
code,
keyword,
title,
templateId,
submitterIds,
start,
count,
since,
startDate,
endDate,
order,
})
: await searchAndFormatBills(await ctx.getClient(), corpId, {
code,
keyword,
searchFields,
stage,
state,
start,
count,
since,
startDate,
endDate,
order,
filterBy,
select,
distinct,
});
if (runtime.jsonMode) {
return {
@@ -67,7 +109,7 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
};
}
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", isDraft ? "创建时间" : "提交时间"];
const rows = result.items.map((b, idx) => [
idx + 1,
b.billCode,
@@ -75,7 +117,7 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
b.stage || "-",
b.state || "-",
b.amount || "-",
b.submitDate || b.createTime || "-",
isDraft ? b.createTime || b.submitDate || "-" : b.submitDate || b.createTime || "-",
]);
const filterSummary: string[] = [];
@@ -87,14 +129,23 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
}
if (stage) filterSummary.push(`阶段: ${stage}`);
if (state) filterSummary.push(`状态: ${state}`);
if (isDraft) {
if (templateId) filterSummary.push(`模板: ${templateId}`);
if (title) filterSummary.push(`标题: ${title}`);
if (staffValues?.length) filterSummary.push(`提交人: ${staffValues.join(", ")}`);
if (page > 1) filterSummary.push(`第 ${page} 页`);
}
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
const tableOutput = printTable(headers, rows);
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
const listLabel = isDraft ? "单据草稿列表" : "单据与费用明细列表";
const titleLine = `====== ${listLabel} (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = isDraft
? `\n提示: 运行 hose-use bill get <单号|flowId> 查看草稿详情;提交使用 hose-use bill submit <单号|flowId> --yes\n`
: `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
return {
stdout: title + tableOutput + tip,
stdout: titleLine + tableOutput + tip,
stderr: "",
exitCode: 0,
};
+19
View File
@@ -159,6 +159,25 @@ describe("CLI - corps environment attributes & filtering", () => {
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("设置企业环境属性");
expect(res.stdout).toContain("newEnv: test");
expect(res.stdout).toContain("将不再触发生产环境确认");
});
it("corps tag dry-run from production to demo includes the same downgrade warning", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "tag",
args: ["corp_prod"],
options: { demo: true, "dry-run": true },
raw: ["corps", "tag", "corp_prod", "--demo", "--dry-run"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("将不再触发生产环境确认");
expect(res.stdout).toContain("newEnv: demo");
});
it("corps current displays environment attribute label", async () => {
+12 -2
View File
@@ -6,6 +6,12 @@ import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mu
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
/** 生产降级为测试/演示会关闭该企业的生产确认门禁,必须显著提示。 */
function productionDowngradeWarning(currentEnv: CorpEnv, targetEnv: CorpEnv): string | undefined {
if (currentEnv !== "prod" || targetEnv === "prod") return undefined;
return "该企业原为正式生产环境;改为测试/演示后,workflow test 与 workflow nodes grant 将不再触发生产环境确认。";
}
export async function handleTagCorp(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -154,12 +160,15 @@ export async function handleTagCorp(
};
}
const currentEnv = getCorpEnv(targetCorp);
const downgradeWarning = productionDowngradeWarning(currentEnv, targetEnv);
const changes = {
corpId: targetCorp.id,
name: targetCorp.name,
currentEnv: targetCorp.env,
currentEnv,
newEnv: targetEnv,
newIsTest: targetEnv !== "prod",
...(downgradeWarning ? { warning: downgradeWarning } : {}),
};
if (isDryRun(parsed, runtime)) {
@@ -192,6 +201,7 @@ export async function handleTagCorp(
env: updatedCorp.env,
isTest: updatedCorp.isTest,
configFile: filePath,
...(downgradeWarning ? { warning: downgradeWarning } : {}),
},
runtime.outputOptions
),
@@ -209,7 +219,7 @@ export async function handleTagCorp(
});
return {
stdout: `[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
stdout: `${downgradeWarning ? `⚠️ ${downgradeWarning}\n\n` : ""}[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
stderr: "",
exitCode: 0,
};
+48 -1
View File
@@ -106,11 +106,58 @@ describe("workflow debug mutation and result contract", () => {
} as any;
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
expect(blocked.exitCode).toBe(1);
expect(blocked.stderr).toContain("生产环境安全阻断");
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);
});
it("reports a structured production confirmation error in JSON mode", async () => {
const { client, run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: true,
} as any;
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
expect(blocked.exitCode).toBe(1);
expect(blocked.stderr).toBe("");
const payload = JSON.parse(blocked.stdout);
expect(payload.code).toBe("PROD_OVERRIDE_REQUIRED");
expect(payload.details.operation).toBe("workflow.test");
expect(payload.nextAction).toContain("--allow-prod");
expect(client).not.toHaveBeenCalled();
expect(run).not.toHaveBeenCalled();
});
it("allows production dry-run without the override and teaches --allow-prod", async () => {
const { client, run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: true,
} as any;
const preview = await handleWorkflowTest(args({ "dry-run": true }), prodRuntime);
expect(preview.exitCode).toBe(0);
const payload = JSON.parse(preview.stdout);
expect(payload.dryRun).toBe(true);
expect(payload.changes.productionOverride).toBe(false);
expect(payload.nextAction).toContain("--allow-prod");
expect(client).not.toHaveBeenCalled();
expect(run).not.toHaveBeenCalled();
});
it("marks production execution results when --allow-prod is used", async () => {
const { run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: true,
} as any;
const result = await handleWorkflowTest(args({ yes: true, "allow-prod": true }), prodRuntime);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout);
expect(payload.productionOverride).toBe(true);
expect(payload.productionWarning).toContain("正式生产企业");
expect(run).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,478 @@
import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { handleWorkflowCommand } from "./workflow/index.js";
import * as helpers from "./workflow/shared.js";
import { CorpContext } from "../../core/config/manager.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { CliRuntime } from "../types.js";
const mockCorp: CorpConfig = {
id: "ID01ofWoOC1wiX",
name: "沈玥妍测试企业",
baseUrl: "https://app.ekuaibao.com",
cluster: "app",
source: "link",
credentials: {
accessToken: "test-token",
corpId: "ID01ofWoOC1wiX",
staffId: "ID01ofWoOC1wiX:ID01KsDgHaH5nN",
},
env: "test",
isTest: true,
};
describe("CLI - workflow node inspect 与 sample-save (只读探针与样本一键固化)", () => {
let spies: any[] = [];
let mockRuntime: CliRuntime;
beforeEach(() => {
spies = [];
const corpContext = new CorpContext([mockCorp], { stateful: true, defaultCorpId: mockCorp.id });
mockRuntime = {
corpContext,
selectedCorp: mockCorp,
jsonMode: false,
outputOptions: {},
};
});
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("workflow node inspect: 成功透视节点配置、已存样本与历史调试出参", async () => {
const mockTasks = [
{
name: "trigger_1",
type: "ekuaibao-ebot-trigger",
label: "EBOT触发",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_calc_1",
type: "code",
label: "代码节点",
displayName: "时间转换节点",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "result = ['minute': '2026-11-19 20:59'];\nreturn result;",
sampleData: {
minute: "2026-11-19 20:59",
},
},
];
const mockDetail = {
id: "wf_inspect_test",
label: "测试工作流",
state: 0,
tasks: mockTasks,
};
const mockExecutionTree = [
{
id: "exec_1",
name: "action_calc_1",
status: "COMPLETED",
executionTime: 8,
output: {
minute: "2026-11-19 20:59",
timestampMs: 1795093140000,
},
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/wf_inspect_test/log")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({
code: 200,
data: {
totalCount: 1,
items: [{ id: "job_test_100", status: "COMPLETED" }],
},
}),
};
}
if (url.includes("api/easo/pipelines/wf_inspect_test")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: mockDetail }),
};
}
if (url.includes("api/easo/jobs/job_test_100/execution")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: mockExecutionTree }),
};
}
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
// 1. 终端文本透视
const resText = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["inspect", "wf_inspect_test", "action_calc_1"],
options: {},
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1"],
},
mockRuntime
);
expect(resText.exitCode).toBe(0);
expect(resText.stdout).toContain("工作流节点只读探针");
expect(resText.stdout).toContain("action_calc_1");
expect(resText.stdout).toContain("时间转换节点");
expect(resText.stdout).toContain("已固化样本");
expect(resText.stdout).toContain("最近一次调试执行出参");
expect(resText.stdout).toContain("job_test_100");
expect(resText.stdout).toContain("1795093140000");
// 2. JSON 模式结构化输出
mockRuntime.jsonMode = true;
const resJson = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["inspect", "wf_inspect_test", "action_calc_1"],
options: {},
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1", "--json"],
},
mockRuntime
);
expect(resJson.exitCode).toBe(0);
const parsedJson = JSON.parse(resJson.stdout);
expect(parsedJson.sampleData.minute).toBe("2026-11-19 20:59");
expect(parsedJson.executionProbe.jobId).toBe("job_test_100");
expect(parsedJson.executionProbe.output.timestampMs).toBe(1795093140000);
});
it("workflow node sample-save: 支持 dry-run 预览并一键固化出参至节点 sampleData", async () => {
let savedTasks: any = null;
let choosesRefreshed = false;
const mockTasks = [
{
name: "action_target_node",
type: "code",
label: "代码节点",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
];
const mockDetail = {
id: "wf_save_sample_test",
label: "样本固化测试流",
version: "1.0.0",
tasksVersion: 1,
state: 0,
tasks: mockTasks,
};
const mockExecutionTree = [
{
id: "exec_node_target",
name: "action_target_node",
status: "COMPLETED",
output: {
formattedDate: "2026-11-24 11:30",
rangeSec: "2026-11-24 11:30:00 ~ 2026-11-24 12:00:00",
},
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
return { json: async () => ({ code: 200, data: mockDetail }) };
}
if (url.includes("api/easo/jobs/job_custom_999/execution")) {
return { json: async () => ({ code: 200, data: mockExecutionTree }) };
}
return { json: async () => ({ code: 200, data: null }) };
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
choosesRefreshed = true;
return {
text: async () => JSON.stringify({ code: 200, data: [] }),
json: async () => ({ code: 200, data: [] }),
};
}
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
savedTasks = opts.json.tasks;
return {
text: async () =>
JSON.stringify({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
json: async () => ({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
};
}
return {
text: async () => JSON.stringify({ code: 200, data: null }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
// 1. Dry-run 预览
const dryRes = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
options: { dryRun: true, job: "job_custom_999" },
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--dry-run"],
},
mockRuntime
);
expect(dryRes.exitCode).toBe(0);
expect(dryRes.stdout).toContain("[DRY-RUN]");
expect(dryRes.stdout).toContain("固化节点样本数据 (sampleData)");
expect(savedTasks).toBeNull();
// 2. 确认执行
const execRes = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
options: { yes: true, job: "job_custom_999" },
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--yes"],
},
mockRuntime
);
expect(execRes.exitCode).toBe(0);
expect(execRes.stdout).toContain("样本数据 (sampleData) 固化成功");
expect(execRes.stdout).toContain("固化字段数 : 2 个属性");
expect(savedTasks).not.toBeNull();
expect(savedTasks[0].sampleData.formattedDate).toBe("2026-11-24 11:30");
expect(choosesRefreshed).toBe(true);
});
it("workflow test --save-sample: 调试通过后自动固化执行出参为节点 sampleData", async () => {
let savedTasks: any = null;
let choosesRefreshed = false;
const mockTasks = [
{
name: "trigger_1",
type: "ekuaibao-flowform-trigger",
label: "单据触发",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_code_date",
type: "code",
label: "代码节点",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "return ['minute': '2026-11-24 11:35'];",
},
];
const mockDetail = {
id: "wf_test_save_sample",
label: "自动保存样本流程",
version: "1.0.0",
tasksVersion: 1,
state: 0,
tasks: mockTasks,
};
const mockClient = {
post: (url: string) => {
if (url.includes("debugSource")) {
return {
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
items: [{ id: "S26000001", title: "测试单据", flowState: "审批中" }],
},
}),
};
}
if (url.includes("api/easo/jobs")) {
return {
json: async () => ({
code: 200,
data: "job_auto_sample_123",
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
get: (url: string) => {
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
if (url.includes("execution")) {
return {
json: async () => ({
code: 200,
data: [
{
id: "e1",
name: "trigger_1",
label: "单据触发",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
executionTime: 10,
},
{
id: "e2",
name: "action_code_date",
label: "代码节点",
type: "code",
status: "COMPLETED",
executionTime: 5,
output: {
minute: "2026-11-24 11:35",
timestampMs: 1795093140000,
},
},
],
}),
};
}
if (url.includes("api/easo/jobs/job_auto_sample_123")) {
return {
json: async () => ({
code: 200,
data: {
id: "job_auto_sample_123",
pipelineId: "wf_test_save_sample",
status: "COMPLETED",
startTime: 1795490000000,
endTime: 1795490001000,
executionTime: 1000,
},
}),
};
}
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
return {
json: async () => ({
code: 200,
data: mockDetail,
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
choosesRefreshed = true;
return {
text: async () => JSON.stringify({ code: 200, data: [] }),
json: async () => ({ code: 200, data: [] }),
};
}
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
savedTasks = opts.json.tasks;
return {
text: async () =>
JSON.stringify({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
json: async () => ({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
};
}
return {
text: async () => JSON.stringify({ code: 200, data: null }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
const testRes = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_save_sample"],
options: { flow: "S26000001", saveSample: true, yes: true },
raw: ["workflow", "test", "wf_test_save_sample", "--flow=S26000001", "--save-sample", "--yes"],
},
mockRuntime
);
expect(testRes.exitCode).toBe(0);
expect(testRes.stdout).toContain("工作流自动化调测报告");
expect(testRes.stdout).toContain("样本数据自动固化");
expect(testRes.stdout).toContain("action_code_date");
expect(savedTasks).not.toBeNull();
expect(savedTasks[1].sampleData.minute).toBe("2026-11-24 11:35");
expect(savedTasks[1].sampleData.timestampMs).toBe(1795093140000);
expect(choosesRefreshed).toBe(true);
});
});
@@ -26,7 +26,7 @@ test("production corp is blocked before any grant request or confirmation", asyn
);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("生产环境安全阻断");
expect(result.stderr).toContain("生产环境确认");
expect(result.stderr).toContain("--allow-prod");
expect(grant).not.toHaveBeenCalled();
} finally {
@@ -45,8 +45,48 @@ test("env-unmarked corp is conservatively treated as production", async () => {
);
expect(result.exitCode).toBe(1);
const parsed = JSON.parse(result.stdout);
expect(parsed.code).toBe("PROD_GRANT_BLOCKED");
expect(parsed.code).toBe("PROD_OVERRIDE_REQUIRED");
expect(parsed.nextAction).toContain("--allow-prod");
expect(parsed.details.operation).toBe("workflow.nodes.grant");
expect(grant).not.toHaveBeenCalled();
} finally {
grant.mockRestore();
}
});
test("production dry-run is allowed without --allow-prod and teaches the override", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
});
try {
const result = await handleWorkflowCommand(
parseArgs(["workflow", "nodes", "grant", "code", "--dry-run"]),
prodRuntime()
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("productionOverride: false");
expect(result.stdout).toContain("实际执行需追加 --allow-prod");
expect(result.stdout).toContain("--allow-prod");
expect(grant).not.toHaveBeenCalled();
} finally {
grant.mockRestore();
}
});
test("missing node types is reported before the production confirmation", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: [], skipped: [], rawMessage: "ok", isTest: false,
});
try {
const result = await handleWorkflowCommand(
parseArgs(["workflow", "nodes", "grant", "--yes"]),
prodRuntime()
);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("请指定要开通的节点类型");
expect(result.stderr).not.toContain("生产环境确认");
expect(grant).not.toHaveBeenCalled();
} finally {
grant.mockRestore();
@@ -65,7 +105,7 @@ test("--allow-prod dry-run previews the production grant without writing", async
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("productionOverride: true");
expect(result.stdout).toContain("生产环境逃生口已启用");
expect(result.stdout).toContain("生产环境覆盖已启用");
expect(result.stdout).toContain("--allow-prod --yes");
expect(grant).not.toHaveBeenCalled();
} finally {
@@ -101,7 +141,7 @@ test("--allow-prod --yes executes the production grant and marks the result", as
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("生产环境逃生口已启用");
expect(result.stdout).toContain("生产环境覆盖已启用");
expect(result.stdout).toContain("灰度节点开通结果");
expect(grant).toHaveBeenCalledTimes(1);
} finally {
@@ -109,6 +149,24 @@ test("--allow-prod --yes executes the production grant and marks the result", as
}
});
test("--force remains a compatible production override alias", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
});
try {
const result = await handleWorkflowCommand(
parseArgs(["workflow", "nodes", "grant", "code", "--force", "--yes"]),
prodRuntime()
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("生产环境覆盖已启用");
expect(grant).toHaveBeenCalledTimes(1);
} finally {
grant.mockRestore();
}
});
test("--allow-prod --yes JSON result exposes productionOverride", async () => {
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
success: true, saved: ["code"], skipped: [], rawMessage: "新开通的节点:code", isTest: false,
+50 -54
View File
@@ -3,7 +3,8 @@ import { GRAY_NODES_CATALOG, normalizeGrayNodes } from "../../../domains/platfor
import { isCorpProd } from "../../../core/config/types.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { buildConfirmedCommand, isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { hasProductionOverride, productionGuard, productionOverrideMeta } from "../../production.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createPiperClientForCorp } from "../../helpers.js";
@@ -113,40 +114,6 @@ export async function handleGrantNodes(
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp!;
const isProd = isCorpProd(corp);
const allowProd = booleanOption(parsed.options, ["allow-prod", "allow-production"]);
const prodNextAction = "hose-use workflow nodes grant <type...> --allow-prod --yes";
// 生产环境默认硬拦截:灰度节点开通属于不可逆企业级写操作。
// 逃生口必须显式追加 --allow-prod,且仍受 --dry-run / --yes 两阶段确认约束。
if (isProd && !allowProd) {
return {
stdout: runtime.jsonMode
? printJson({
error: true,
code: "PROD_GRANT_BLOCKED",
message: "对正式生产企业开通灰度节点需显式追加 --allow-prod",
exitCode: 1,
nextAction: prodNextAction,
}) + "\n"
: "",
stderr: runtime.jsonMode
? ""
: [
"🛑 生产环境安全阻断 (Production Safeguard):",
`当前工作企业 [${corp.name || corp.id}] 被判定为【正式生产环境】。`,
"灰度节点开通是不可逆的企业级写操作,默认禁止对生产企业执行。",
"",
"如确需在生产环境开通,必须显式追加 --allow-prod 承担风险,并先预览再执行:",
" hose-use workflow nodes grant <type...> --allow-prod --dry-run",
` ${prodNextAction}`,
"",
"若企业环境标记有误,请检查 ~/.config/hose-use/enterprises/ 下的 env / isTest 字段。",
].join("\n") + "\n",
exitCode: 1,
};
}
const rawNodes = parsed.args.slice(1);
const optionNodes = stringOption(parsed.options, ["nodes", "node", "type", "types"]);
const collected: string[] = [];
@@ -170,27 +137,51 @@ export async function handleGrantNodes(
};
}
const isProd = isCorpProd(corp);
const allowProd = hasProductionOverride(parsed);
const isTest = booleanOption(parsed.options, ["is-test"]);
const confirmNextAction = buildConfirmedCommand(parsed);
const prodNextAction = buildConfirmedCommand(parsed, ["--allow-prod"]);
// 预览不产生写操作,始终放行;生产环境只在 nextAction 中补上覆盖参数。
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"开通企业工作流灰度节点",
corp.corpId || corp.credentials.corpId || corp.id,
{
nodes: normalizeGrayNodes(targetNodes),
isTest,
attachedOptions: GRANT_ATTACHED_OPTIONS,
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
...(isProd
? {
productionOverride: allowProd,
productionWarning: allowProd
? "生产环境覆盖已启用:实际执行会变更正式生产企业,请再次核对企业与节点类型。"
: "当前为正式生产企业:实际执行需追加 --allow-prod 确认。",
}
: {}),
},
{ extraArgs: isProd && !allowProd ? ["--allow-prod"] : [] }
);
}
const blocked = productionGuard(parsed, runtime, {
operation: "开通企业工作流灰度节点",
operationCode: "workflow.nodes.grant",
risk: "灰度节点开通是不可逆的企业级写操作,会改变正式生产企业的可用节点能力。",
nextAction: prodNextAction,
});
if (blocked) return blocked;
requireMutationConfirmation(
parsed,
runtime,
"开通企业工作流灰度节点",
isProd ? prodNextAction : "hose-use workflow nodes grant <type...> --yes"
isProd ? prodNextAction : confirmNextAction
);
const isTest = booleanOption(parsed.options, ["is-test"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
nodes: normalizeGrayNodes(targetNodes),
isTest,
attachedOptions: GRANT_ATTACHED_OPTIONS,
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
...(isProd
? {
productionOverride: true,
productionWarning: "生产环境逃生口已启用:实际执行会变更正式生产企业,请再次核对企业与节点类型。",
}
: {}),
});
}
const password = stringOption(parsed.options, ["password", "pwd", "admin-key"]);
@@ -200,9 +191,14 @@ export async function handleGrantNodes(
isTest,
});
const overrideMeta = productionOverrideMeta(
parsed,
runtime,
"生产环境覆盖已启用 (--allow-prod):本次对正式生产企业执行了灰度节点开通。"
);
if (runtime.jsonMode) {
return {
stdout: printJson(isProd ? { ...result, productionOverride: true } : result, runtime.outputOptions),
stdout: printJson({ ...result, ...overrideMeta }, runtime.outputOptions),
stderr: "",
exitCode: result.success ? 0 : 1,
};
@@ -212,8 +208,8 @@ export async function handleGrantNodes(
}
const lines = [
...(isProd
? ["⚠️ 生产环境逃生口已启用 (--allow-prod):本次对正式生产企业执行了灰度节点开通。", ""]
...(overrideMeta.productionOverride
? [`⚠️ ${overrideMeta.productionWarning}`, ""]
: []),
`====== 灰度节点开通结果 [${corp.name}] ======`,
printKeyValue({
+274 -10
View File
@@ -7,6 +7,9 @@ import {
editWorkflowTask,
removeWorkflowTask,
applyNodeMapping,
getJobExecutionTree,
listWorkflowLogs,
refreshWorkflowChooses,
} from "../../../domains/platform/workflow/services.js";
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
import { ValidationError } from "../../../core/errors.js";
@@ -26,7 +29,11 @@ async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0],
});
}
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
const SUB_ACTIONS = new Set([
"list", "ls", "get", "show", "info", "add", "append", "insert",
"edit", "update", "set", "map", "rm", "remove", "delete", "del",
"inspect", "probe", "examine", "sample-save", "save-sample",
]);
export async function handleNodeCommand(
parsed: CliParsedArgs,
@@ -79,24 +86,26 @@ export async function handleNodeCommand(
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
"",
"子命令 (工作流级别):",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" inspect <pipelineId> <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)",
" sample-save <pipelineId> <节点标识> 固化指定 Job 或最新调测出参为 sampleData",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
"",
"子命令 (企业灰度节点级别):",
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产环境需显式 --allow-prod)",
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产企业执行需显式 --allow-prod)",
"",
"示例:",
" hose-use workflow nodes",
" hose-use workflow nodes --all",
" hose-use workflow nodes grant code-js2",
" hose-use workflow nodes grant code-js2 --is-test # 仅用于工作流位于测试 Piper 的企业",
" hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:先预览",
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行",
" hose-use workflow nodes grant code-js2 --dry-run # 生产企业:预览(无需覆盖参数)",
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行(--force 兼容)",
" hose-use workflow node list 896398895352487950",
].join("\n") + "\n",
exitCode: 1,
@@ -107,6 +116,13 @@ export async function handleNodeCommand(
case "list":
case "ls":
return handleListNodes(pipelineId, parsed, runtime);
case "inspect":
case "probe":
case "examine":
return handleInspectNode(pipelineId, nodeTarget, parsed, runtime);
case "sample-save":
case "save-sample":
return handleSaveNodeSample(pipelineId, nodeTarget, parsed, runtime);
case "get":
case "show":
case "info":
@@ -677,3 +693,251 @@ async function handleRemoveNode(
exitCode: 0,
};
}
async function handleInspectNode(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect <pipelineId> <nodeNameOrIndex>\n",
exitCode: 1,
};
}
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
const { task, hierarchicalIndex, path, parentName } = located;
const sampleData = (task as any).sampleData ?? null;
let executionProbe: {
jobId: string;
status: string;
executionTime?: number;
output?: any;
error?: any;
} | null = null;
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
try {
let jobIdToProbe = targetJobId;
if (!jobIdToProbe) {
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
if (firstItem && firstItem.id) {
jobIdToProbe = firstItem.id;
}
}
if (jobIdToProbe) {
const tree = await getJobExecutionTree(client, jobIdToProbe);
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
if (matchExecution) {
executionProbe = {
jobId: jobIdToProbe,
status: matchExecution.status || "UNKNOWN",
executionTime: (matchExecution as any).durationTime ?? matchExecution.executionTime,
output: matchExecution.output,
error: matchExecution.error,
};
}
}
} catch {
// 探针容错
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
pipelineId,
node: located,
sampleData,
executionProbe,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [
`====== 工作流节点只读探针 [${detail.label || pipelineId}] · ${task.displayName || task.label || task.name} ======`,
`节点标识 (name) : ${task.name}`,
`层级编号 (#) : ${hierarchicalIndex}`,
`节点类型 (type) : ${task.type}`,
`节点标题 (label) : ${task.label || "-"}`,
`节点显示名 (display): ${(task as any).displayName || "-"}`,
`父容器节点 : ${parentName || "顶级节点 (root)"}`,
`JSON 路径 : ${path}`,
];
if ((task as any).code !== undefined) {
outLines.push(`脚本代码行数 : ${(task as any).code.split("\n").length} 行`);
}
if ((task as any).url) {
outLines.push(`请求 URL : ${(task as any).url}`);
}
if ((task as any).specificationId) {
outLines.push(`单据模板 ID : ${JSON.stringify((task as any).specificationId)}`);
}
outLines.push("");
outLines.push("── 📦 节点固化样本数据 (sampleData) ──");
if (sampleData && typeof sampleData === "object" && Object.keys(sampleData).length > 0) {
const keys = Object.keys(sampleData);
outLines.push(`状态: ✅ 已固化样本 (${keys.length} 个字段)`);
outLines.push(printJson(sampleData, runtime.outputOptions));
} else {
outLines.push("状态: ⚪ 暂无样本数据 (设计器下拉菜单将无法自动解析其结构化变量)");
outLines.push("💡 提示: 可运行 hose-use workflow node sample-save <pipelineId> <nodeName> 固化最近调测出参");
}
outLines.push("");
outLines.push("── 🧪 最近一次调试执行出参 (Execution Output Probe) ──");
if (executionProbe) {
outLines.push(`来源 Job ID : ${executionProbe.jobId}`);
outLines.push(`执行状态 (status) : ${executionProbe.status}`);
outLines.push(`执行耗时 (ms) : ${executionProbe.executionTime ?? "-"}`);
if (executionProbe.output && typeof executionProbe.output === "object") {
outLines.push(`出参全貌 (output):`);
outLines.push(printJson(executionProbe.output, runtime.outputOptions));
} else {
outLines.push(`出参: ${JSON.stringify(executionProbe.output ?? null)}`);
}
} else {
outLines.push("未找到或无匹配的最近调试执行记录。");
}
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
async function handleSaveNodeSample(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "用法: hose-use workflow node sample-save <pipelineId> <nodeNameOrIndex> [--job=<jobId>]\n",
exitCode: 1,
};
}
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
const { task } = located;
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
let jobIdToProbe = targetJobId;
if (!jobIdToProbe) {
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
if (firstItem && firstItem.id) {
jobIdToProbe = firstItem.id;
}
}
if (!jobIdToProbe) {
return {
stdout: "",
stderr: `未指定 Job ID 且未查询到工作流 [${pipelineId}] 的历史运行日志,无法提取样本数据。请先执行调试或通过 --job=<id> 指定。\n`,
exitCode: 1,
};
}
const tree = await getJobExecutionTree(client, jobIdToProbe);
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
if (!matchExecution || matchExecution.output === undefined) {
return {
stdout: "",
stderr: `在 Job [${jobIdToProbe}] 中未找到节点 [${task.name}] 的有效执行出参 (output)。\n`,
exitCode: 1,
};
}
const samplePayload = matchExecution.output;
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "固化节点样本数据 (sampleData)", `${pipelineId}:${task.name}`, {
pipelineId,
nodeName: task.name,
jobId: jobIdToProbe,
samplePayload,
});
}
requireMutationConfirmation(
parsed,
runtime,
"固化节点样本数据 (sampleData)",
`hose-use workflow node sample-save ${pipelineId} ${nodeTarget} --job=${jobIdToProbe} --yes`
);
(task as any).sampleData = samplePayload;
const saveResult = await saveNodeChanges(client, detail, detail, platformId);
try {
await refreshWorkflowChooses(client, pipelineId);
} catch {}
const fieldCount = typeof samplePayload === "object" && samplePayload !== null ? Object.keys(samplePayload).length : 1;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: true,
pipelineId,
nodeName: task.name,
jobId: jobIdToProbe,
fieldsSaved: fieldCount,
sampleData: samplePayload,
workflow: saveResult,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: [
`✨ 节点 [${task.name}] (${task.displayName || task.label || task.type}) 样本数据 (sampleData) 固化成功!`,
` • 来源 Job ID : ${jobIdToProbe}`,
` • 固化字段数 : ${fieldCount} 个属性`,
` • 设计器联动 : 已刷新选择器 (chooses) 树,下游节点现在可在下拉列表中直接点选其输出变量。`,
`📌 ${formatWorkflowVersion(saveResult)}`,
].join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
+103 -44
View File
@@ -6,13 +6,17 @@ import {
getWorkflowDetail,
getWorkflowSampleData,
runWorkflowDebugTest,
updateWorkflow,
refreshWorkflowChooses,
flattenWorkflowTaskTree,
type WorkflowTriggerCategory,
} from "../../../domains/platform/workflow/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, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { buildConfirmedCommand, isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { hasProductionOverride, productionGuard, productionOverrideMeta } from "../../production.js";
export async function handleWorkflowTest(
parsed: CliParsedArgs,
@@ -45,9 +49,10 @@ export async function handleWorkflowTest(
" 4. 外部调用 (webhook): --body='{...}' 或 --file=<path.json> 传入事件请求体",
"",
"通用选项:",
" --save-sample 调试通过后自动将执行节点的真实出参保存为样本数据 (sampleData)",
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
" --auto-publish 是否自动发布测试快照 (默认 false)",
" --force, -f 允许在正式生产环境 (env: prod) 下执行调试",
" --allow-prod 确认在正式生产环境 (env: prod) 下执行调试(--force 为兼容别名)",
" --dry-run 只预览,不发起调试",
" --yes/--confirm 确认执行真实工作流节点",
"",
@@ -58,43 +63,58 @@ export async function handleWorkflowTest(
}
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
const saveSample = booleanOption(parsed.options, ["save-sample", "saveSample", "save-samples", "saveSamples"]);
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
const filePath = stringOption(parsed.options, ["file", "path"]);
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 allowProd = hasProductionOverride(parsed);
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 参数。`);
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --allow-prod。`);
}
const nextActionCmd = isProductionCorp
? `hose-use workflow test ${pipelineId} --yes --force`
: `hose-use workflow test ${pipelineId} --yes`;
const nextActionCmd = buildConfirmedCommand(parsed, isProductionCorp ? ["--allow-prod"] : []);
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd);
if (isDryRun(parsed, runtime)) {
const previewResult = mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
if (isProductionCorp) {
if (runtime.jsonMode) {
try {
const parsedJson = JSON.parse(previewResult.stdout);
if (parsedJson.nextAction && !parsedJson.nextAction.includes("--force")) {
parsedJson.nextAction = `${parsedJson.nextAction} --force`;
previewResult.stdout = `${JSON.stringify(parsedJson, null, 2)}\n`;
}
} catch {
// ignore
}
} else {
previewResult.stdout = previewResult.stdout.replace(/--yes/g, "--yes --force");
}
}
return previewResult;
return mutationPreview(
parsed,
runtime,
"执行工作流调试",
pipelineId,
{
flowCodeOrId,
rawBody,
filePath,
empty: isEmpty,
autoPublish,
timeoutMs,
warnings,
...(isProductionCorp
? {
productionOverride: allowProd,
productionWarning: allowProd
? "生产环境覆盖已启用:实际执行会在正式生产企业产生真实业务变更。"
: "当前为正式生产企业:实际执行需追加 --allow-prod 确认。",
}
: {}),
},
{ extraArgs: isProductionCorp && !allowProd ? ["--allow-prod"] : [] }
);
}
// 生产确认只要求“用户明确知道在操作生产企业”,不做功能禁止;预览已在上面放行。
const blocked = productionGuard(parsed, runtime, {
operation: "执行工作流调试",
operationCode: "workflow.test",
risk: "调试会真实执行工作流节点,可能产生单据流转、第三方调用、通知与快照发布等不可逆业务变更。",
nextAction: nextActionCmd,
});
if (blocked) return blocked;
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
// 1. 获取工作流详情与触发器元数据
const detail = await getWorkflowDetail(client, pipelineId).catch(() => {
@@ -390,24 +410,6 @@ export async function handleWorkflowTest(
// 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,
@@ -417,7 +419,55 @@ export async function handleWorkflowTest(
autoPublish,
timeoutMs,
});
const report = { ...execution, productionEnabled: detail ? isEnabled : null, warnings };
const savedSampleNodes: Array<{ name: string; label: string; fieldCount: number }> = [];
if (saveSample && execution.outcome === "completed" && execution.executionTree?.length > 0) {
try {
const latestDetail = await getWorkflowDetail(client, pipelineId);
const flattened = flattenWorkflowTaskTree(latestDetail.tasks || []);
let updatedCount = 0;
for (const execNode of execution.executionTree) {
if (!execNode.name || execNode.output === undefined || execNode.output === null) continue;
if (typeof execNode.output !== "object" || Object.keys(execNode.output).length === 0) continue;
const matched = flattened.find((f) => f.task.name === execNode.name);
if (matched) {
(matched.task as any).sampleData = execNode.output;
savedSampleNodes.push({
name: matched.task.name,
label: (matched.task as any).displayName || matched.task.label || matched.task.type,
fieldCount: Object.keys(execNode.output).length,
});
updatedCount++;
}
}
if (updatedCount > 0) {
await updateWorkflow(client, latestDetail, {
platformId,
expectedVersion: { version: latestDetail.version, tasksVersion: latestDetail.tasksVersion },
});
try {
await refreshWorkflowChooses(client, pipelineId);
} catch {}
}
} catch (sampleErr: any) {
warnings.push(`自动固化样本数据警告: ${sampleErr.message || String(sampleErr)}`);
}
}
const report = {
...execution,
productionEnabled: detail ? isEnabled : null,
savedSampleNodes: savedSampleNodes.length > 0 ? savedSampleNodes : undefined,
warnings,
...productionOverrideMeta(
parsed,
runtime,
"生产环境覆盖已启用 (--allow-prod):本次调试在正式生产企业真实执行。"
),
};
const exitCode = report.outcome === "completed" ? 0 : 1;
if (runtime.jsonMode) {
@@ -508,6 +558,15 @@ export async function handleWorkflowTest(
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
}
if (savedSampleNodes.length > 0) {
outLines.push("");
outLines.push("── ✨ 样本数据自动固化 (Sample Data Saved) ──");
outLines.push(`已自动将 ${savedSampleNodes.length} 个节点的真实调试出参固化为 sampleData 并刷新设计器选择树:`);
for (const sn of savedSampleNodes) {
outLines.push(` • [${sn.name}] (${sn.label}): 固化 ${sn.fieldCount} 个属性`);
}
}
if (category === "WEBHOOK" && report.outcome !== "completed") {
outLines.push("");
outLines.push("💡 [Webhook 流程调试提示]");
+1 -1
View File
@@ -51,7 +51,7 @@ const SUB_ACTION_HELP: Record<string, SubActionHelp> = {
"--sample=<1|2|3> 直接选用服务器最近接收的数据样本发起测试",
"--timeout=<ms> 轮询超时时间 (毫秒,默认 15000)",
"--auto-publish 调试通过后是否自动发布测试快照 (默认 false)",
"--force, -f 生产环境安全放行 (正式企业 env: prod 调试必须加)",
"--allow-prod 确认在正式生产企业 (env: prod) 执行调试(--force 为兼容别名)",
"--dry-run 只预览测试配置,不发起调用",
"--yes/--confirm 确认执行真实调试",
],
+22 -9
View File
@@ -45,21 +45,34 @@ export function requireMutationConfirmation(
throw new MutationConfirmationRequired(operation, nextAction);
}
/**
* 基于当前原始参数构造「确认执行」命令,并补齐缺失的附加参数。
* 所有命令的 nextAction 都走这里,避免各自拼接造成格式漂移。
*/
export function buildConfirmedCommand(parsed: CliParsedArgs, extraArgs: string[] = []): string {
const strip = new Set([
"--dry-run", "--dryRun", "--dryrun",
"--yes", "-y", "--confirm", "--force-write", "--forceWrite",
]);
const args = (parsed.raw ?? []).filter((arg) => !strip.has(arg));
const isAiPro = args[0] === "hose-aipro" || args[0] === "aipro";
const cleanArgs =
args[0] === "hose-aipro" || args[0] === "hose-use" || args[0] === "aipro"
? args.slice(1)
: args;
const extra = extraArgs.filter((arg) => arg && !cleanArgs.includes(arg));
return `${isAiPro ? "hose-aipro" : "hose-use"} ${[...cleanArgs, ...extra].join(" ")} --yes`;
}
export function mutationPreview(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
target: string,
changes: Record<string, unknown>
changes: Record<string, unknown>,
options: { extraArgs?: string[] } = {}
): CliResult {
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
const isAiPro = confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "aipro";
const binaryPrefix = isAiPro ? "hose-aipro" : "hose-use";
const cleanArgs =
confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "hose-use" || confirmedArgs[0] === "aipro"
? confirmedArgs.slice(1)
: confirmedArgs;
const nextAction = `${binaryPrefix} ${cleanArgs.join(" ")} --yes`;
const nextAction = buildConfirmedCommand(parsed, options.extraArgs);
const payload = {
dryRun: true,
operation,
+91
View File
@@ -0,0 +1,91 @@
import { isCorpProd } from "../core/config/types.js";
import { booleanOption } from "./parser.js";
import { printJson } from "./printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
/**
* 生产环境确认策略(CLI 统一入口)。
*
* 约定:
* - `--allow-prod` 是唯一的显式生产覆盖参数;`--allow-production` 与历史 `--force` 仅作兼容别名。
* - 覆盖参数只负责让用户明确知道“当前在操作正式生产企业”,不替代 `--dry-run` / `--yes` 两阶段确认。
* - 预览(`--dry-run`)永远放行,不要求覆盖参数;预览的 nextAction 会自动补上覆盖参数。
* - 所有命令的阻断提示与 JSON 错误使用同一结构与同一个错误码 `PROD_OVERRIDE_REQUIRED`。
*/
export const PRODUCTION_OVERRIDE_FLAGS = ["allow-prod", "allow-production", "force"] as const;
export function hasProductionOverride(parsed: CliParsedArgs): boolean {
return booleanOption(parsed.options, [...PRODUCTION_OVERRIDE_FLAGS]);
}
export interface ProductionGuardOptions {
/** 人类可读动作名,如「执行工作流调试」 */
operation: string;
/** 机器可读动作标识,如 `workflow.test` */
operationCode: string;
/** 一行风险说明 */
risk: string;
/** 补齐覆盖参数后的完整恢复命令 */
nextAction: string;
}
/**
* 正式生产企业且未显式追加覆盖参数时,返回统一的阻断结果;否则返回 null。
*/
export function productionGuard(
parsed: CliParsedArgs,
runtime: CliRuntime,
options: ProductionGuardOptions
): CliResult | null {
const corp = runtime.selectedCorp;
if (!corp || !isCorpProd(corp) || hasProductionOverride(parsed)) return null;
const corpId = corp.corpId || corp.id;
const message = `当前企业 [${corp.name || corp.id}] 为正式生产环境,${options.operation}需显式追加 --allow-prod 确认`;
const text = [
"🛑 生产环境确认 (Production Safeguard):",
`当前工作企业 [${corp.name || corp.id}] 被判定为【🏭 正式生产环境】。`,
options.risk,
"",
"确认继续请显式追加 --allow-prod(--force 为兼容别名),并继续遵守 --dry-run / --yes 两阶段确认:",
` ${options.nextAction}`,
"",
"如企业环境标记有误,可使用: hose-use corps tag <企业ID> --test",
].join("\n") + "\n";
return {
stdout: runtime.jsonMode
? printJson(
{
error: true,
code: "PROD_OVERRIDE_REQUIRED",
message,
exitCode: 1,
nextAction: options.nextAction,
details: {
corpId,
corpName: corp.name || corp.id,
env: "prod",
operation: options.operationCode,
},
},
runtime.outputOptions
) + "\n"
: "",
stderr: runtime.jsonMode ? "" : text,
exitCode: 1,
};
}
/**
* 生产覆盖生效时的统一结果标记;非生产或未覆盖返回空对象。
*/
export function productionOverrideMeta(
parsed: CliParsedArgs,
runtime: CliRuntime,
warning: string
): { productionOverride?: true; productionWarning?: string } {
const corp = runtime.selectedCorp;
if (!corp || !isCorpProd(corp) || !hasProductionOverride(parsed)) return {};
return { productionOverride: true, productionWarning: warning };
}
+3 -2
View File
@@ -149,8 +149,9 @@ export class CorpContext {
if (!corp) return false;
this.current = corp;
this.defaultCorpId = corp.id;
if (persist && this.stateful) {
saveGlobalConfig({ defaultCorpId: corp.id });
if (persist) {
this.stateful = true;
saveGlobalConfig({ defaultCorpId: corp.id, stateful: true });
}
return true;
}
+5
View File
@@ -86,6 +86,11 @@ src/domains/bill/
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
15. **未提交草稿列表 (`searchAndFormatDraftBills`)**:
- 草稿未进入 `POST /api/v2/invoice/search` 台账索引,`bill list --state=draft` 改走 `POST /api/flow/v1/flows/my`;
- 服务端过滤 `state.in("draft")`,支持 `--template`、`--title`、`--staff`、`--code`、`--keyword`、时间范围与 `--page/--count` 分页,按流程 `createTime` 排序;
- 客户端再按模板、标题、提交人做兜底匹配,避免 RQL 对对象字段的差异造成漏筛;
- 列表只覆盖当前身份可见的「我发起」草稿。他人/系统或工作流创建的草稿按已知单号查询;`getRawBillFlow` 新增 flowId 直读通道,`bill get <flowId>` 不依赖 `flows/my` 可见性。
### 草稿写入前校验
+95
View File
@@ -120,6 +120,25 @@ export async function getRawBillFlow(
// 通道 0 失败时继续走既有回溯通道
}
// 通道 0.2: 已知 flowId 时直接读取流程详情。
// 工作流或其他身份创建的草稿可能不在当前身份的 flows/my 中,但 Job 输出/页面链接会给出 flowId;
// 该通道不依赖列表可见性,也避免回退到「最近 N 条」本地匹配。
if (/^ID01/i.test(cleanTarget)) {
try {
const detail = await client.post(`api/flow/v1/flows/flowId/$${cleanTarget}`, {
searchParams: { id: cleanTarget, corpId },
json: {
filterBy: `(id==${quoted(cleanTarget)})`,
select: "id,state,form,logs",
},
});
const json = (await detail.json()) as { value?: Record<string, unknown> };
if (json.value) return { flowId: json.value };
} catch {
// 非流程 ID 或不可见时继续走既有回溯通道
}
}
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
const searchFilters = [
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
@@ -496,6 +515,82 @@ export async function searchRawBills(
return RawBillSearchResponseSchema.parse(json);
}
export interface RawDraftFlowSearchOptions {
start?: number;
count?: number;
code?: string;
keyword?: string;
title?: string;
templateId?: string;
submitterIds?: string[];
from?: number;
to?: number;
order?: "ASC" | "DESC";
}
/**
* 查询「我发起」的未提交草稿流程。
*
* 草稿尚未进入单据台账索引(`api/v2/invoice/search`),因此列表必须走
* `api/flow/v1/flows/my`。服务端过滤字段与 task 域提交列表保持一致:
* state 使用小写 `draft`,模板/标题用 `INSTR(form.*, ...)`,时间用流程 `createTime`。
*/
export async function searchMyDraftFlows(
client: KyInstance,
corpId: string,
options: RawDraftFlowSearchOptions = {}
): Promise<{ count: number; items: Record<string, unknown>[] }> {
const filters: string[] = [
'(state.in("draft"))',
// 与 task submitted 一致:对账单流程不是费控单据草稿,避免混入列表。
`(INSTR(form.specificationId, ${quoted(`${corpId}:system:对账单`)})==0)`,
];
const code = options.code?.trim();
if (code) filters.push(`(form.code.in(${quoted(code)}))`);
const title = options.title?.trim();
if (title) filters.push(`(INSTR(form.title, ${quoted(title)}) > 0)`);
const templateId = options.templateId?.trim();
if (templateId) filters.push(`(INSTR(form.specificationId, ${quoted(templateId)}) > 0)`);
const submitterIds = (options.submitterIds ?? []).map((id) => id.trim()).filter(Boolean);
if (submitterIds.length > 0) {
const submitterFilters = submitterIds.map((id) => `(INSTR(form.submitterId, ${quoted(id)}) > 0)`);
filters.push(submitterFilters.length === 1 ? submitterFilters[0]! : `(${submitterFilters.join(" || ")})`);
}
const keyword = options.keyword?.trim();
if (keyword) {
filters.push(
`((INSTR(form.title, ${quoted(keyword)}) > 0) || (INSTR(form.code, ${quoted(keyword)}) > 0))`
);
}
if (options.from !== undefined) filters.push(`(createTime > ${options.from})`);
if (options.to !== undefined) filters.push(`(createTime < ${options.to})`);
const response = await client.post("api/flow/v1/flows/my", {
searchParams: {
type: "home5",
delegatedFilter: "DELEGATE_TO_ME",
corpId,
},
json: {
filterBy: filters.join("&&"),
limit: { start: options.start ?? 0, count: options.count ?? 20 },
orderBy: [{ value: "createTime", order: options.order ?? "DESC" }],
},
});
const json = (await response.json()) as { count?: number; items?: unknown[] };
const items = Array.isArray(json.items)
? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"))
: [];
return { count: json.count ?? items.length, items };
}
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
export async function getRawBillsByIds(
+180
View File
@@ -1,6 +1,9 @@
import { describe, it, expect } from "bun:test";
import {
formatSingleBill,
formatFlowAsBill,
searchAndFormatDraftBills,
getBillByCodeOrId,
getBillReferences,
getBillRelations,
getBillAttachments,
@@ -714,6 +717,183 @@ describe("Bill Domain", () => {
});
});
describe("Bill Draft Listing", () => {
const draftItems = [
{
flow: {
id: "flow-draft-1",
state: "draft",
formType: "payment",
createTime: 1781682826000,
updateTime: 1781682870000,
},
form: {
code: "FK26000001",
title: "付款草稿",
specificationId: { id: "spec-pay", name: "对公付款单" },
submitterId: { id: "staff-1", name: "张三", code: "1001" },
payMoney: { standard: "1200.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
},
{
flow: {
id: "flow-draft-2",
state: "draft",
formType: "expense",
createTime: 1781682926000,
updateTime: 1781682970000,
},
form: {
code: "BX26000002",
title: "报销草稿",
specificationId: { id: "spec-exp", name: "报销单" },
submitterId: { id: "staff-2", name: "李四", code: "1002" },
expenseMoney: { standard: "88.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
},
];
it("formats flows/my items that carry top-level form separately from flow", () => {
const bill = formatFlowAsBill(draftItems[0]!, new Map());
expect(bill.billId).toBe("flow-draft-1");
expect(bill.billCode).toBe("FK26000001");
expect(bill.billName).toBe("付款草稿");
expect(bill.state).toBe("draft");
expect(bill.stage).toBe("payment");
expect(bill.amount).toContain("1200.00");
expect(bill.submitterId).toContain("张三");
expect(bill.createTime).not.toBe("");
});
it("queries flows/my for drafts and applies server plus client filters", async () => {
const posts: Array<{ url: string; payload: any }> = [];
const client = {
post: async (url: string, payload: any) => {
posts.push({ url, payload });
if (url.includes("datalink/entity/search")) {
return new Response(JSON.stringify({ items: [] }));
}
if (url.endsWith("/flows/my")) {
return new Response(JSON.stringify({ count: 2, items: draftItems }));
}
return new Response(JSON.stringify({}));
},
} as any;
const result = await searchAndFormatDraftBills(client, "corp-draft-list", {
title: "付款",
templateId: "spec-pay",
submitterIds: ["staff-1"],
start: 20,
count: 10,
since: "7d",
});
expect(result.total).toBe(2);
expect(result.returned).toBe(1);
expect(result.items[0]?.billId).toBe("flow-draft-1");
expect(result.items[0]?.billCode).toBe("FK26000001");
const draftRequest = posts.find((post) => post.url.endsWith("/flows/my"));
expect(draftRequest).toBeDefined();
const filterBy = draftRequest!.payload.json.filterBy as string;
expect(filterBy).toContain('(state.in("draft"))');
expect(filterBy).toContain('INSTR(form.title, "付款")');
expect(filterBy).toContain('INSTR(form.specificationId, "spec-pay")');
expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")');
expect(filterBy).toContain("createTime >");
expect(draftRequest!.payload.json.limit).toEqual({ start: 20, count: 10 });
expect(draftRequest!.payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]);
expect(draftRequest!.payload.searchParams).toMatchObject({
corpId: "corp-draft-list",
type: "home5",
delegatedFilter: "DELEGATE_TO_ME",
});
});
it("supports the compact flows/my shape: specification field and submitDate as createTime", async () => {
const client = {
post: async (url: string) => {
if (url.includes("datalink/entity/search")) {
return new Response(JSON.stringify({ items: [] }));
}
if (url.endsWith("/flows/my")) {
return new Response(JSON.stringify({
count: 1,
items: [{
flow: { id: "flow-compact", state: "draft" },
form: {
code: "BX26000009",
title: "紧凑草稿",
type: "expense",
specification: { id: "spec-exp:0123456789abcdef0123456789abcdef", name: "报销单" },
submitterId: { id: "staff-1", name: "张三", code: "1001" },
amount: { standard: "5.00", standardSymbol: "¥", standardStrCode: "CNY" },
submitDate: 1794989105307,
},
}],
}));
}
return new Response(JSON.stringify({}));
},
} as any;
const result = await searchAndFormatDraftBills(client, "corp-draft-compact", {
templateId: "spec-exp",
});
expect(result.returned).toBe(1);
expect(result.items[0]).toMatchObject({
billId: "flow-compact",
billCode: "BX26000009",
stage: "expense",
state: "draft",
});
expect(result.items[0]?.createTime).not.toBe("");
expect(result.items[0]?.amount).toContain("5.00");
});
it("reads a workflow-created draft by flowId even when flows/my is empty", async () => {
const posts: string[] = [];
const client = {
post: async (url: string) => {
posts.push(url);
if (url.includes("datalink/entity/search")) {
return new Response(JSON.stringify({ items: [] }));
}
if (url.includes("flows/flowId/")) {
return new Response(JSON.stringify({
value: {
id: "ID01DRAFTFLOW",
state: "draft",
form: {
code: "FD26000001",
title: "工作流付款草稿",
specificationId: { id: "spec-pay", name: "对公付款单" },
payMoney: { standard: "66.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
},
}));
}
if (url.includes("flows/my") || url.includes("flows/approved")) {
return new Response(JSON.stringify({ items: [] }));
}
return new Response(JSON.stringify({ items: [] }));
},
} as any;
const bills = await getBillByCodeOrId(client, "corp-draft-flow", "ID01DRAFTFLOW");
expect(posts.some((url) => url.includes("flows/flowId/$ID01DRAFTFLOW"))).toBe(true);
expect(bills).toHaveLength(1);
expect(bills[0]?.billId).toBe("ID01DRAFTFLOW");
expect(bills[0]?.billCode).toBe("FD26000001");
expect(bills[0]?.state).toBe("draft");
expect(bills[0]?.amount).toContain("66.00");
});
});
describe("traceBillFlowDetail 全域穿透诊断与待办根因分析", () => {
it("待审批状态:精准解析提报人、金额、当前节点与待办审批人,判定可审批", async () => {
const mockRawFlow = {
+153 -5
View File
@@ -12,6 +12,7 @@ import {
} from "../../core/errors.js";
import {
searchRawBills,
searchMyDraftFlows,
getRawBillsByIds,
listEntitySchemas,
getRawBillFlow,
@@ -44,6 +45,7 @@ import {
type BillPageResult,
type EntityMeta,
type BillQueryParams,
type BillDraftQueryParams,
type BillFlowEntry,
type BillFlowNode,
type BillFlowTimeline,
@@ -678,12 +680,20 @@ export function formatFlowAsBill(
raw: Record<string, unknown>,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record<string, unknown>;
const flow = (raw.flowId && typeof raw.flowId === "object"
? raw.flowId
: raw.flow && typeof raw.flow === "object"
? raw.flow
: {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object"
? flow.form
: raw.form && typeof raw.form === "object"
? raw.form
: {}) as Record<string, unknown>;
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
const stage = typeof flow.formType === "string" ? flow.formType : typeof form.type === "string" ? form.type : "flow";
const state = raw.nodeName
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
@@ -714,8 +724,24 @@ export function formatFlowAsBill(
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
}
const createTimeNum = typeof flow.createTime === "number" ? flow.createTime : typeof raw.createTime === "number" ? raw.createTime : 0;
const updateTimeNum = typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : 0;
// flows/my 的精简响应不一定带流程 createTime;草稿没有 submitDate 语义上的提交时间,
// 服务端仍会写入该字段,可作为创建时间兜底,避免列表展示为空。
const createTimeNum = typeof flow.createTime === "number"
? flow.createTime
: typeof raw.createTime === "number"
? raw.createTime
: typeof form.createTime === "number"
? form.createTime
: typeof form.submitDate === "number"
? form.submitDate
: 0;
const updateTimeNum = typeof flow.updateTime === "number"
? flow.updateTime
: typeof raw.updateTime === "number"
? raw.updateTime
: typeof form.updateTime === "number"
? form.updateTime
: 0;
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
@@ -1631,6 +1657,128 @@ export async function searchAndFormatBills(
};
}
function draftFlowParts(item: Record<string, unknown>): {
flow: Record<string, unknown>;
form: Record<string, unknown>;
} {
const flow = (item.flow && typeof item.flow === "object"
? item.flow
: item.flowId && typeof item.flowId === "object"
? item.flowId
: {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object"
? flow.form
: item.form && typeof item.form === "object"
? item.form
: {}) as Record<string, unknown>;
return { flow, form };
}
/**
* 查询未提交草稿列表。
*
* 草稿不在 `api/v2/invoice/search` 台账索引中,数据源改为 `api/flow/v1/flows/my`;
* 服务端过滤之外再做一次客户端兜底匹配,避免 RQL 对对象字段的差异造成漏筛。
* 该列表只覆盖当前身份可见的「我发起」草稿;他人/系统创建的草稿按已知单号或 flowId
* 使用 `bill get` 查询(`getRawBillFlow` 的 flowId 直读通道)。
*/
export async function searchAndFormatDraftBills(
client: KyInstance,
corpId: string,
params: BillDraftQueryParams = {}
): Promise<BillPageResult> {
const { dictionary } = await getFieldDictionary(client, corpId);
let fromTime = params.from ?? parseDateFilter(params.startDate);
if (params.since) {
const duration = parseSinceDuration(params.since);
if (duration !== undefined) fromTime = Math.max(fromTime ?? 0, Date.now() - duration);
}
const toTime = params.to ?? parseDateFilter(params.endDate, true);
const page = await searchMyDraftFlows(client, corpId, {
start: params.start ?? 0,
count: params.count ?? 20,
code: params.code,
keyword: params.keyword,
title: params.title,
templateId: params.templateId,
submitterIds: params.submitterIds,
from: fromTime,
to: toTime,
order: (params.order ?? "DESC").toUpperCase() as "ASC" | "DESC",
});
let items = page.items;
const code = params.code?.trim();
if (code) {
items = items.filter((item) => {
const { flow, form } = draftFlowParts(item);
return form.code === code || flow.id === code;
});
}
const title = params.title?.trim().toLowerCase();
if (title) {
items = items.filter((item) => {
const { form } = draftFlowParts(item);
return typeof form.title === "string" && form.title.toLowerCase().includes(title);
});
}
const templateId = params.templateId?.trim();
if (templateId) {
items = items.filter((item) => {
const { form } = draftFlowParts(item);
// flows/my 返回精简表单时字段名为 specification;创建/详情接口则常用 specificationId。
const specification = form.specificationId ?? form.specification;
if (typeof specification === "string") return specification.includes(templateId);
if (specification && typeof specification === "object") {
const record = specification as Record<string, unknown>;
return ["id", "originalId", "name"].some((key) => {
const value = record[key];
return typeof value === "string" && (value === templateId || value.includes(templateId));
});
}
return false;
});
}
const submitterIds = (params.submitterIds ?? []).map((id) => id.trim()).filter(Boolean);
if (submitterIds.length > 0) {
items = items.filter((item) => {
const { form } = draftFlowParts(item);
const submitter = form.submitterId;
if (typeof submitter === "string") {
return submitterIds.some((id) => submitter === id || submitter.includes(id));
}
if (submitter && typeof submitter === "object") {
const record = submitter as Record<string, unknown>;
return submitterIds.some((id) =>
[record.id, record.userId].some(
(value) => typeof value === "string" && (value === id || value.endsWith(`:${id}`))
)
);
}
return false;
});
}
const keyword = params.keyword?.trim().toLowerCase();
if (keyword) {
items = items.filter((item) => {
const { form } = draftFlowParts(item);
return [form.title, form.code].some(
(value) => typeof value === "string" && value.toLowerCase().includes(keyword)
);
});
}
const formatted = items.map((item) => formatFlowAsBill(item, dictionary));
return { total: page.count, returned: formatted.length, items: formatted };
}
export async function getTranslatorContext(
client: KyInstance,
corpId: string,
+16
View File
@@ -192,6 +192,22 @@ export interface BillQueryParams {
join?: string | string[];
}
export interface BillDraftQueryParams {
code?: string;
keyword?: string;
title?: string;
templateId?: string;
submitterIds?: string[];
start?: number;
count?: number;
since?: string;
from?: number;
to?: number;
startDate?: string;
endDate?: string;
order?: "ASC" | "DESC" | "asc" | "desc";
}
export interface BillFlowEntry {
id?: string;
time?: number;
@@ -103,7 +103,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
- 执行 `hose-use workflow nodes` 查看当前租户已开通的节点字典;
- 执行 `hose-use workflow nodes --all` 查看当前企业与官方全量 108 个灰度节点清单的开通状态对照;
- 执行 `hose-use workflow nodes grant <type...>` 申请开通灰度节点(内置管理员密码预留设计:未配置环境变量 `HOSE_ADMIN_PASSWORD` 时为免密便捷模式;配置后强制要求 `--password` 授权)。
- 正式生产企业默认被硬拦截;确需在生产环境开通时,必须显式追加 `--allow-prod`,并继续遵守 `--dry-run` → `--yes` 两阶段确认。`--is-test` 只切换 Piper 域名,不构成生产授权。
- 正式生产企业执行开通前需显式追加 `--allow-prod` 表明已知晓目标环境(`--force` 为兼容别名),并继续遵守 `--dry-run` → `--yes` 两阶段确认;`--dry-run` 预览不要求覆盖参数。`--is-test` 只切换 Piper 域名,不构成生产授权。
## 静态分析器:诊断边界显式化(硬门禁 vs 软建议)
@@ -161,7 +161,7 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
节点卡片标题保存在 `displayName`,用 `--display-name` 修改;`--label` 是节点类型标题,服务端保存时可能按节点类型重新生成,不能可靠地用于重命名已有节点。设计器前端把节点标题限制为 20 个字符;后端本身不校验该长度(实测 21 字仍可保存),本地 CLI 按前端上限强制校验,超过 20 个 Unicode 字符会在写入前抛出 `ValidationError`。条件/内置节点类型的 `desc` 也由平台按配置重新生成,自定义 `--desc` 可能不会持久化。
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。生产企业额外要求显式 `--allow-prod`。管理员密码用于额外授权,不能替代写操作确认。
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。生产企业额外要求显式 `--allow-prod`(预览不要求)。管理员密码用于额外授权,不能替代写操作确认。
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
@@ -125,9 +125,9 @@ function buildWorkflowTaskBase(type: string, options: Partial<AddTaskOptions> =
return {
name,
type: "stop",
label: options.label || "终止流程",
desc: options.desc || "如果满足条件终止流程",
groupName: "control",
label: options.label || "终止节点",
desc: options.desc,
groupName: "action",
orderIndex: 0,
levelIndex: [0],
status: "active",
+3 -3
View File
@@ -51,7 +51,7 @@ bun install --frozen-lockfile
bun run build:plugin
```
`.mcp.json` 保持使用 `${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js`,由 Bun 1.3.14+ 启动。清理 `dist/` 后需要重新构建;普通 `bun test` 会在临时目录自行构建测试插件,不依赖预先存在的 bundle。
插件清单 `mcp.json` 保持使用 `${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js`,由 Bun 1.3.14+ 启动;仓库根目录的 `.mcp.json` 是 Claude Code 项目级配置,使用 `bun src/server.ts` 运行当前源码,不包含插件变量。清理 `dist/` 后需要重新构建插件 bundle;普通 `bun test` 会在临时目录自行构建测试插件,不依赖预先存在的 bundle。
完整插件包通过以下命令生成(需要系统 `tar`):
@@ -59,7 +59,7 @@ bun run build:plugin
bun run package:plugin
```
输出为 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,只包含 `.zcode-plugin/plugin.json`、`.mcp.json`、`skills/` 和新构建的 `dist/mcp/server.js`,不会复用仓库本地的旧 bundle。归档根目录即插件根目录,不包含企业凭据、本地笔记、源码或 `node_modules/`。解压后的插件仍需 Bun 1.3.14+,无需再次安装项目依赖。
输出为 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,只包含 `.zcode-plugin/plugin.json`、`mcp.json`、`skills/` 和新构建的 `dist/mcp/server.js`,不会复用仓库本地的旧 bundle。归档根目录即插件根目录,不包含企业凭据、本地笔记、源码或 `node_modules/`。解压后的插件仍需 Bun 1.3.14+,无需再次安装项目依赖。
从 Release 下载插件包和同版本的 `checksums.txt`,核对对应资产的 SHA-256 后解压到独立目录,将该目录作为本地插件根目录加载。MCP 默认关闭,按插件配置启用后连接。
@@ -79,7 +79,7 @@ Skill 初始化明确执行 `skill install --yes`;失败会报告二进制已
- PR/main CI:冻结依赖安装、版本一致性、类型检查、全套测试、独立二进制和插件 bundle 的构建及 MCP 协议验证,以及完整插件包构建。测试会解包临时插件,核对包内清单和 Skill,并在独立目录验证离线脚本与 MCP 协议。
- 独立二进制:`bun run build:binary`;`bun run scripts/build/verify-binary.ts dist/bin/hose-use` 在空工作目录和没有 Bun 的 PATH 下验证版本、单工具发现、真实调用与错误返回。
- 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。
- 插件 bundle:`bun run build:plugin`;`mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。
- Release:构建前检查 tag 版本、实际 HEAD 和 main 祖先关系;手动触发也必须输入 tag。正式构建显式使用 `--release`,两个发布源都上传校验清单,后台镜像上传失败会使任务失败。
Gitea 同时最多传输两个资产,每个资产最多尝试三次;已有文件经 SHA-256 验证一致时直接保留。镜像传输中断后,可在 main 上手动运行 Release workflow,传入原 tag 并启用 `mirror_only`:该模式下载并核对 GitHub 已发布资产(含插件包),只修复 Gitea,不重建或替换 GitHub 产物,也不移动 tag。