From 304a8c0d98487ac6db42e0d3d89b481ee3144a75 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:20:47 +0800 Subject: [PATCH 01/11] fix(update): relax binary download timeout to 600s and pass auth token for github assets --- src/cli/commands/update.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 058f30f..dc0399a 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -796,7 +796,17 @@ export async function downloadFile( const candidate = uniqueCandidates[i]!; try { logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`); - const res = await fetch(candidate, { signal: AbortSignal.timeout(6000) }); + const reqHeaders: Record = { + "User-Agent": `hose-use/${VERSION}`, + }; + const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; + if (token && candidate.includes("github.com")) { + reqHeaders["Authorization"] = `Bearer ${token}`; + } + const res = await fetch(candidate, { + headers: reqHeaders, + signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载 + }); if (!res.ok) { throw new Error(`HTTP ${res.status} ${res.statusText}`); } From 2f8bcb90c9f4922e1861e76f3fd9b4e300b0301a Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:26:04 +0800 Subject: [PATCH 02/11] refactor(cli): purge short hose alias and standardize on hose-use across docs, scripts, and prompts --- AGENTS.md | 2 +- README.md | 2 +- scripts/install.sh | 3 +- skills/hose-use/SKILL.md | 154 ++++++++++---------- skills/hose-use/references/bill.md | 34 ++--- skills/hose-use/references/contact.md | 26 ++-- skills/hose-use/references/dimension.md | 8 +- skills/hose-use/references/message.md | 14 +- skills/hose-use/references/role.md | 14 +- skills/hose-use/references/task.md | 18 +-- src/cli/commands/auth.ts | 4 +- src/cli/commands/bill.ts | 28 ++-- src/cli/commands/config.ts | 6 +- src/cli/commands/contact.ts | 12 +- src/cli/commands/corps.ts | 8 +- src/cli/commands/dimension.ts | 4 +- src/cli/commands/message.ts | 4 +- src/cli/commands/permission.ts | 2 +- src/cli/commands/platform.ts | 2 +- src/cli/commands/probe.ts | 2 +- src/cli/commands/role.ts | 4 +- src/cli/commands/task.ts | 2 +- src/cli/commands/workflow.ts | 10 +- src/cli/runner.ts | 2 +- src/cli/service.ts | 2 +- src/core/auth/tools.ts | 2 +- src/core/config/manager.ts | 4 +- src/domains/bill/README.bill.md | 2 +- src/domains/contact/tools.ts | 2 +- src/domains/permission/README.permission.md | 2 +- src/domains/role/README.role.md | 2 +- 31 files changed, 190 insertions(+), 191 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 84e671f..d349ca1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ 合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 适配能力): -- **CLI 工具 (`hose-use` / `hose`)**:面向运维/实施/开发者的高性能交互与自动化命令行 +- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者的高性能交互与自动化命令行 - **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务 API 与换票能力 - **MCP Server (`src/server.ts`)**:精简核心适配器(保留核心切换与扫描能力) - **Agent Skill (`skills/hose-use`)**:内嵌 AI 智能体技能标准定义(支持 `hose-use skill install` 一键分发) diff --git a/README.md b/README.md index bd8fc8d..38e63c0 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ hose-use mcp # 启动 MCP Server (默认暴露 ```text src/ -├── cli.ts # CLI 入口 (bin: hose) +├── cli.ts # CLI 入口 (bin: hose-use, hose-aipro) ├── cli/ # CLI 核心引擎 (runner, parser, printer, commands) ├── core/ # 基础设施与底层 SDK │ ├── auth/ # 认证与换票 (RSA 账密, TokenStore, AccountStore) diff --git a/scripts/install.sh b/scripts/install.sh index 6e9fed6..111a564 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -152,9 +152,8 @@ fi chmod +x "$TMP_FILE" mv "$TMP_FILE" "$TARGET_PATH" -# Create command aliases pointing at the same single binary. +# Create hose-aipro multicall alias pointing at the single binary. if [ -w "$TARGET_DIR" ]; then - ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose" 2>/dev/null || true ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true fi diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 924f456..b6f5ae5 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -16,7 +16,7 @@ metadata: ## Agent 执行原则 (First Rules) 1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。 -2. **多租户优先探查**:在需要企业参数前,优先执行 `hose corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=` 传入;不要向普通用户询问底层 `corpId`。 +2. **多租户优先探查**:在需要企业参数前,优先执行 `hose-use corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=` 传入;不要向普通用户询问底层 `corpId`。 3. **输出防护与大报文处理**: - 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o ` 本地转储或使用 `--limit` 限制分页; - 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文; @@ -29,36 +29,36 @@ metadata: | 用户意图 / 场景 | 推荐命令 | 深入参考文档 | |---|---|---| -| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose auth login`, `hose auth status`, `hose auth refresh` | [references/auth.md](references/auth.md) | -| 代客协助凭证导入 / 探针连通性诊断 | `hose auth import`, `hose probe` | [references/auth.md](references/auth.md) | -| 企业租户切换 / 查看当前企业 | `hose corps list`, `hose corps switch ` | [references/auth.md](references/auth.md) | -| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) | -| 单据审批动作(同意/驳回/转交/加签/评论) | `hose bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) | -| 单据审批历史 / 当前节点 / 后续流程 | `hose bill flow <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据风控预警 / 预算状态 / 发票风险 | `hose bill risk <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose bill refs <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据关联关系 / 冲借款与前置申请追溯 | `hose bill relations <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据预算状态 / 超预算与占用信息 | `hose bill budget <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据附件 / 发票原件标准列表 | `hose bill attachments <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据附件下载 | `hose bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) | -| 系统/自定义档案维度与档案项 | `hose dimension list`, `hose dimension items <维度>` | [references/dimension.md](references/dimension.md) | -| 企业角色、角色组与角色成员 | `hose role list`, `hose role groups`, `hose role members <角色>` | [references/role.md](references/role.md) | -| 角色权限只读快照 | `hose permission get` | [references/role.md](references/role.md) | -| 单据 Web 详情直达链接生成 | `hose bill link <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.md) | -| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose contact search`, `hose contact list`, `hose contact get` | [references/contact.md](references/contact.md) | -| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose task todo`, `hose task submitted`, `hose task records`, `hose task cc` | [references/task.md](references/task.md) | -| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose message list [--all]`, `hose message count`, `hose message read` | [references/message.md](references/message.md) | -| 跨自建应用工作流聚合检索 | `hose workflow list`, `hose platform list` | [references/workflow.md](references/workflow.md) | -| 特定任务节点扫描 (如脚本/Webhook) | `hose workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) | -| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) | -| 工作流节点树、代码依赖与静态诊断 | `hose workflow analyze ` | [references/workflow.md](references/workflow.md) | -| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) | -| 待办/消息事件轮询与去重 | `hose service poll --corp=` | [references/service.md](references/service.md) | -| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) | +| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [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 ` | [references/auth.md](references/auth.md) | +| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list`, `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) | +| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose-use bill refs <单号|ID>` | [references/bill.md](references/bill.md) | +| 单据关联关系 / 冲借款与前置申请追溯 | `hose-use bill relations <单号|ID>` | [references/bill.md](references/bill.md) | +| 单据预算状态 / 超预算与占用信息 | `hose-use bill budget <单号|ID>` | [references/bill.md](references/bill.md) | +| 单据附件 / 发票原件标准列表 | `hose-use bill attachments <单号|ID>` | [references/bill.md](references/bill.md) | +| 单据附件下载 | `hose-use bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) | +| 系统/自定义档案维度与档案项 | `hose-use dimension list`, `hose-use dimension items <维度>` | [references/dimension.md](references/dimension.md) | +| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) | +| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) | +| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) | +| 单据实体模型与字段元数据查询 | `hose-use bill schema` | [references/bill.md](references/bill.md) | +| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) | +| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) | +| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose-use message list [--all]`, `hose-use message count`, `hose-use message read` | [references/message.md](references/message.md) | +| 跨自建应用工作流聚合检索 | `hose-use workflow list`, `hose-use platform list` | [references/workflow.md](references/workflow.md) | +| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) | +| 工作流详情与开通切换 | `hose-use workflow get`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) | +| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze ` | [references/workflow.md](references/workflow.md) | +| 常驻守护进程管理 / 后台运行 | `hose-use service start`, `hose-use service status` | [references/service.md](references/service.md) | +| 待办/消息事件轮询与去重 | `hose-use service poll --corp=` | [references/service.md](references/service.md) | +| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose-use http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) | | CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) | -| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose openapi`, `hose openapi --raw` | [references/service.md](references/service.md) | -| 一键自动自更新 / 查看版本发布日志 | `hose update`, `hose update --changelog` | `hose update --help` | +| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose-use openapi`, `hose-use openapi --raw` | [references/service.md](references/service.md) | +| 一键自动自更新 / 查看版本发布日志 | `hose-use update`, `hose-use update --changelog` | `hose-use update --help` | --- @@ -66,63 +66,63 @@ metadata: ```bash # 1. 认证与企业 -hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录 -hose auth status # 查看 Token 剩余有效期与登录账号 -hose corps list # 查看企业租户列表 -hose corps switch ID01MCcOgJl1td # 切换工作企业 -hose probe # 诊断当前企业接口连通性 +hose-use auth login --phone=17718556446 --password=... # 纯 API 账密自动登录 +hose-use auth status # 查看 Token 剩余有效期与登录账号 +hose-use corps list # 查看企业租户列表 +hose-use corps switch ID01MCcOgJl1td # 切换工作企业 +hose-use probe # 诊断当前企业接口连通性 # 2. 企业通讯录与人员 (默认严格防爆限流,优先 search) -hose contact search 王硕 # 模糊搜索员工工号、邮箱与电话 -hose contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护) -hose contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆 -hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案 +hose-use contact search 王硕 # 模糊搜索员工工号、邮箱与电话 +hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护) +hose-use contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆 +hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案 # 3. 单据与费用 -hose bill list # 查看最新单据与报销记录 -hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接 -hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘 -hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射) -hose bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照 -hose bill approve S26000001 --yes # 同意当前待办 -hose bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因 -hose bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名 -hose bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签 -hose bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论 -hose bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型 -hose bill relations S26000001 # 追溯冲借款、事前申请和合同关联 -hose bill budget S26000001 # 查看单据预算超限和预算接口状态 -hose bill attachments S26000001 # 查看附件和发票原件列表 -hose bill download S26000001 --output-dir ./downloads # 下载附件到本地目录 -hose dimension list # 查看系统与自定义档案维度 -hose dimension items 项目 # 查看项目、成本中心等档案项 -hose role list # 查看企业角色定义 -hose role groups # 查看角色组及其角色 -hose role members 财务主管 # 查看指定角色成员 -hose permission get # 查看角色权限开关(只读) -hose bill schema # 查询单据实体元数据字典 +hose-use bill list # 查看最新单据与报销记录 +hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接 +hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘 +hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射) +hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照 +hose-use bill approve S26000001 --yes # 同意当前待办 +hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因 +hose-use bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名 +hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签 +hose-use bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论 +hose-use bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型 +hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联 +hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态 +hose-use bill attachments S26000001 # 查看附件和发票原件列表 +hose-use bill download S26000001 --output-dir ./downloads # 下载附件到本地目录 +hose-use dimension list # 查看系统与自定义档案维度 +hose-use dimension items 项目 # 查看项目、成本中心等档案项 +hose-use role list # 查看企业角色定义 +hose-use role groups # 查看角色组及其角色 +hose-use role members 财务主管 # 查看指定角色成员 +hose-use permission get # 查看角色权限开关(只读) +hose-use bill schema # 查询单据实体元数据字典 # 4. 待办与消息 -hose task submitted # 查看我发起的单据 -hose message list --unread # 查看未读消息 -hose message list --all # 合并查看已读和未读消息 -hose message count # 查看未读数量 -hose message read # 标记单条消息已读 +hose-use task submitted # 查看我发起的单据 +hose-use message list --unread # 查看未读消息 +hose-use message list --all # 合并查看已读和未读消息 +hose-use message count # 查看未读数量 +hose-use message read # 标记单条消息已读 # 5. 自建应用与工作流 -hose platform list # 查看自建应用列表 -hose workflow list # 聚合扫描全部应用下的工作流 -hose workflow find --task=code-js2 # 查找部署了代码节点的工作流 -hose workflow get wf_01k83y... # 查看指定工作流节点拓扑 -hose workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断 +hose-use platform list # 查看自建应用列表 +hose-use workflow list # 聚合扫描全部应用下的工作流 +hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流 +hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑 +hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断 # 6. 服务与守护进程 -hose http --port=8888 # 启动前台 HTTP 服务与交互式文档 -hose service start # 后台启动常驻守护进程服务 -hose service status # 查看常驻守护进程运行状态与端点 -hose service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘 -hose service logs # 查看常驻守护进程日志 -hose service stop # 停止后台常驻守护进程 +hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档 +hose-use service start # 后台启动常驻守护进程服务 +hose-use service status # 查看常驻守护进程运行状态与端点 +hose-use service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘 +hose-use service logs # 查看常驻守护进程日志 +hose-use service stop # 停止后台常驻守护进程 ``` --- diff --git a/skills/hose-use/references/bill.md b/skills/hose-use/references/bill.md index 3196818..f44320c 100644 --- a/skills/hose-use/references/bill.md +++ b/skills/hose-use/references/bill.md @@ -41,8 +41,8 @@ hose-use bill flow CL20260903001 在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段: ```bash -hose bill get S26000001 --risk -hose bill get S26000001 --risk --json +hose-use bill get S26000001 --risk +hose-use bill get S26000001 --risk --json ``` ### 中文字段智能映射字典 @@ -74,19 +74,19 @@ hose-use bill risk CL20260903001 ```bash # 同意:可附带纯文本审批意见 -hose bill approve S26000001 --comment "同意" --yes +hose-use bill approve S26000001 --comment "同意" --yes # 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标 -hose bill reject S26000001 --comment "请补充发票" --yes +hose-use bill reject S26000001 --comment "请补充发票" --yes # 转交:--approver-id 支持完整员工 ID、工号或唯一姓名 -hose bill transfer S26000001 --approver-id 111 --yes +hose-use bill transfer S26000001 --approver-id 111 --yes # 加签:默认前加签,--mode post 表示后加签 -hose bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes +hose-use bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes # 评论:支持 --participants 传入逗号分隔的人员 ID -hose bill comment S26000001 --comment "补充说明" --participants --yes +hose-use bill comment S26000001 --comment "补充说明" --participants --yes ``` 动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。 @@ -96,8 +96,8 @@ hose bill comment S26000001 --comment "补充说明" --participants -- 读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID: ```bash -hose bill refs S26000001 -hose bill refs S26000001 --json +hose-use bill refs S26000001 +hose-use bill refs S26000001 --json ``` JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes`、`dimensions` 和 `unresolved`。单据里出现法人实体、项目或成本中心 ID 时,会联动 `dimension` 目录补充名称与编码;目录在当前进程内按企业缓存 10 分钟。 @@ -107,8 +107,8 @@ JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTyp 从审批详情中的冲借款、前置申请、合同和费用关联字段抽取关系树: ```bash -hose bill relations S26000001 -hose bill relations S26000001 --json +hose-use bill relations S26000001 +hose-use bill relations S26000001 --json ``` 表格模式按树形缩进显示关联 ID、单号、标题和金额;JSON 模式保留每个节点的原始字段,便于继续下钻。 @@ -118,8 +118,8 @@ hose bill relations S26000001 --json 读取审批页使用的预算状态接口,查看单据是否超预算及接口返回的可用/占用金额字段: ```bash -hose bill budget S26000001 -hose bill budget S26000001 --json +hose-use bill budget S26000001 +hose-use bill budget S26000001 --json ``` ### 单据附件列表 (`bill attachments`) @@ -127,15 +127,15 @@ hose bill budget S26000001 --json 从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址: ```bash -hose bill attachments S26000001 -hose bill attachments S26000001 --json +hose-use bill attachments S26000001 +hose-use bill attachments S26000001 --json ``` 需要落盘时使用 `bill download`。命令会创建目标目录、清理文件名中的路径字符,并返回本地路径和字节数;指定 `--file-id` 可只下载一个附件: ```bash -hose bill download S26000001 --output-dir ./downloads -hose bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json +hose-use bill download S26000001 --output-dir ./downloads +hose-use bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json ``` ## 5. 单据实体元数据字典 (`bill schema`) diff --git a/skills/hose-use/references/contact.md b/skills/hose-use/references/contact.md index 8610dd8..155df13 100644 --- a/skills/hose-use/references/contact.md +++ b/skills/hose-use/references/contact.md @@ -9,8 +9,8 @@ 企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。** 因此,`hose-use` 遵循以下防爆安全原则: -1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果); -2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引; +1. **搜索优先 (Search First)**:优先使用 `hose-use contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果); +2. **列表默认限流截断 (Default Limit 20)**:`hose-use contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引; 3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据; 4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。 @@ -20,22 +20,22 @@ ```bash # 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId) -hose contact search 王硕 -hose contact search xiezihao@hosecloud.com -hose contact search 18600612659 +hose-use contact search 王硕 +hose-use contact search xiezihao@hosecloud.com +hose-use contact search 18600612659 # 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出) -hose contact list -hose contact list --limit=50 +hose-use contact list +hose-use contact list --limit=50 # 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端) -hose contact list --json -o /tmp/all_staffs.json +hose-use contact list --json -o /tmp/all_staffs.json # 4. 精确下钻查看指定人员详细档案 -hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 +hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 5. 指定特定企业租户检索 -hose contact search 李 --corp=ID01MCcOgJl1td +hose-use contact search 李 --corp=ID01MCcOgJl1td ``` --- @@ -60,6 +60,6 @@ hose contact search 李 --corp=ID01MCcOgJl1td ### 1. 查找某人发起的单据 当用户要求“帮我查一下王硕提交的报销单”时: -1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`); -2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细; -3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。 +1. 先通过 `hose-use contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`); +2. 再通过 `hose-use bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细; +3. 获得单据后,通过 `hose-use bill link <单号>` 生成官方 Web 直达链接反馈给用户。 diff --git a/skills/hose-use/references/dimension.md b/skills/hose-use/references/dimension.md index 47679b3..e949560 100644 --- a/skills/hose-use/references/dimension.md +++ b/skills/hose-use/references/dimension.md @@ -4,12 +4,12 @@ ```bash # 查看系统/自定义档案维度目录 -hose dimension list -hose dimension list --keyword=项目 +hose-use dimension list +hose-use dimension list --keyword=项目 # 查看某个维度的档案项(支持维度 ID、编码或名称) -hose dimension items 项目 -hose dimension items DA001 --json +hose-use dimension items 项目 +hose-use dimension items DA001 --json ``` 目录来源于 `/api/v1/basedata/dimensions/active`,档案项来源于 `/api/v1/basedata/dimensionItems/$`。结果在同一进程内按企业缓存 10 分钟,JSON 会保留底层 ID、编码、父项 ID 和表单字段。 diff --git a/skills/hose-use/references/message.md b/skills/hose-use/references/message.md index b5a1366..eb6dee0 100644 --- a/skills/hose-use/references/message.md +++ b/skills/hose-use/references/message.md @@ -3,13 +3,13 @@ 消息中心是 CLI-only 能力,不新增 MCP tool。命令默认查询未读消息。 ```bash -hose message list --unread -hose message list --read -hose message list --all -hose message list --type=Approve -hose message count -hose message read -hose message read-all +hose-use message list --unread +hose-use message list --read +hose-use message list --all +hose-use message list --type=Approve +hose-use message count +hose-use message read +hose-use message read-all ``` `message list --json` 返回消息 ID、标题、内容、消息类型、已读状态和原始字段;`--all` 会并行拉取已读与未读页面并去重后按时间排序;`--type` 在 CLI 层按 `messageType`、`msgType`、`msgTypeName` 或 `msgName` 做兼容过滤。`message read-all` 会分页读取全部未读消息再逐条标记,避免只处理首 100 条。 diff --git a/skills/hose-use/references/role.md b/skills/hose-use/references/role.md index 0aed91c..5bf9f1b 100644 --- a/skills/hose-use/references/role.md +++ b/skills/hose-use/references/role.md @@ -3,11 +3,11 @@ 角色页对应的只读 CLI: ```bash -hose role list -hose role list --keyword=财务 -hose role groups -hose role members 财务主管 -hose role members CODE15 --json +hose-use role list +hose-use role list --keyword=财务 +hose-use role groups +hose-use role members 财务主管 +hose-use role members CODE15 --json ``` 接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。 @@ -15,6 +15,6 @@ hose role members CODE15 --json 权限页的角色权限快照: ```bash -hose permission get -hose permission get --json +hose-use permission get +hose-use permission get --json ``` diff --git a/skills/hose-use/references/task.md b/skills/hose-use/references/task.md index 2e06131..0363390 100644 --- a/skills/hose-use/references/task.md +++ b/skills/hose-use/references/task.md @@ -3,15 +3,15 @@ ## CLI ```bash -hose task todo # 待我审批 -hose task approved # 我已审批 -hose task records # 审批记录 -hose task submitted # 我发起的单据 -hose task cc --unread # 未读抄送 -hose task cc --read # 已读抄送 -hose task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤 -hose task todo --json --count 50 -hose task records --from 2026-01-01 --to 2026-09-05 +hose-use task todo # 待我审批 +hose-use task approved # 我已审批 +hose-use task records # 审批记录 +hose-use task submitted # 我发起的单据 +hose-use task cc --unread # 未读抄送 +hose-use task cc --read # 已读抄送 +hose-use task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤 +hose-use task todo --json --count 50 +hose-use task records --from 2026-01-01 --to 2026-09-05 ``` 任务结果包含任务 ID、流程 ID、单号、标题、单据模板、提交人、金额、状态、当前节点和可用动作。分页使用 `--start` 与 `--count`。 diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index 2efd710..7973e94 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -309,7 +309,7 @@ async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promi } if (accounts.length === 0) { - return { stdout: "暂无保存的账号,请使用 hose auth login 登录\n", stderr: "", exitCode: 0 }; + return { stdout: "暂无保存的账号,请使用 hose-use auth login 登录\n", stderr: "", exitCode: 0 }; } const rows = accounts.map((acc, i) => [ @@ -327,7 +327,7 @@ async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promi async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const target = parsed.args[0] || stringOption(parsed.options, ["account", "a"]); if (!target) { - return { stdout: "", stderr: "用法: hose auth switch-account \n", exitCode: 1 }; + return { stdout: "", stderr: "用法: hose-use auth switch-account \n", exitCode: 1 }; } const success = setActiveAccount(target); diff --git a/src/cli/commands/bill.ts b/src/cli/commands/bill.ts index 0c01e34..57644ae 100644 --- a/src/cli/commands/bill.ts +++ b/src/cli/commands/bill.ts @@ -27,7 +27,7 @@ export async function handleBillCommand( const corp = runtime.selectedCorp; if (!corp) { throw new Error( - "未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose auth login 登录。" + "未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose-use auth login 登录。" ); } @@ -75,7 +75,7 @@ export async function handleBillCommand( case "agree": { await requireWriteConfirmation(); const target = actionTarget(); - if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill approve <单号|ID> --yes"); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes"); const result = await approveBill(client, corpId, target, actionOptions()); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; @@ -85,7 +85,7 @@ export async function handleBillCommand( case "deny": { await requireWriteConfirmation(); const target = actionTarget(); - if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill reject <单号|ID> --comment <原因> --yes"); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes"); const options = actionOptions(); if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因"); const result = await rejectBill(client, corpId, target, options); @@ -97,7 +97,7 @@ export async function handleBillCommand( case "shift": { await requireWriteConfirmation(); const target = actionTarget(); - if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill transfer <单号|ID> --approver-id <员工ID> --yes"); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes"); const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) }; const result = await transferBill(client, corpId, target, options); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; @@ -110,7 +110,7 @@ export async function handleBillCommand( case "counter-sign": { await requireWriteConfirmation(); const target = actionTarget(); - if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill add-node <单号|ID> --approver-id <员工ID> --yes"); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes"); const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) }; const result = await addNodeBill(client, corpId, target, options); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; @@ -121,7 +121,7 @@ export async function handleBillCommand( case "remark": { await requireWriteConfirmation(); const target = actionTarget(); - if (!target) throw new Error("请提供单号或单据 ID: hose bill comment <单号|ID> --comment <内容> --yes"); + if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes"); const result = await commentBill(client, corpId, target, actionOptions()); if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 }; @@ -326,7 +326,7 @@ export async function handleBillCommand( case "records": case "timeline": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose bill flow <单号|ID>"); + if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>"); const flow = await getBillFlow(client, corpId, target); if (!flow) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; @@ -368,7 +368,7 @@ export async function handleBillCommand( case "review": case "warnings": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose bill risk <单号|ID>"); + if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>"); const report = await getBillRisk(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; @@ -398,7 +398,7 @@ export async function handleBillCommand( case "budget": case "budgets": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose bill budget <单号|ID>"); + if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>"); const report = await getBillRisk(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; @@ -424,7 +424,7 @@ export async function handleBillCommand( case "references": case "resolve": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose bill refs <单号|ID>"); + if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>"); const report = await getBillReferences(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; @@ -453,7 +453,7 @@ export async function handleBillCommand( case "relation": case "links": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose bill relations <单号|ID>"); + if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>"); const report = await getBillRelations(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; @@ -486,7 +486,7 @@ export async function handleBillCommand( case "attachment": case "files": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose bill attachments <单号|ID>"); + if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>"); const report = await getBillAttachments(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; @@ -507,7 +507,7 @@ export async function handleBillCommand( case "download": case "file-download": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); - if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose bill download <单号|ID>"); + if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>"); const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`; const fileId = stringOption(parsed.options, ["file-id", "file"]); const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId); @@ -540,7 +540,7 @@ export async function handleBillCommand( if (!target) { return { stdout: "", - stderr: "用法: hose bill link <单号或ID>", + stderr: "用法: hose-use bill link <单号或ID>", exitCode: 1, }; } diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index bba1bd1..5fa9b43 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -67,7 +67,7 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise\n 指定企业: hose corps switch \n 更新源设置: hose config set updateSource \n`, + stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode \n 指定企业: hose-use corps switch \n 更新源设置: hose-use config set updateSource \n`, stderr: "", exitCode: 0, }; @@ -79,7 +79,7 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise\n", + stderr: "用法: hose-use config mode \n", exitCode: 1, }; } @@ -105,7 +105,7 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise (如 hose config set defaultCorpId uzU7pcWfScck00)\n", + stderr: "用法: hose-use config set (如 hose-use config set defaultCorpId uzU7pcWfScck00)\n", exitCode: 1, }; } diff --git a/src/cli/commands/contact.ts b/src/cli/commands/contact.ts index 3bfac99..1c905e6 100644 --- a/src/cli/commands/contact.ts +++ b/src/cli/commands/contact.ts @@ -16,7 +16,7 @@ export async function handleContactCommand( if (!corp) { return { stdout: "", - stderr: "未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp='", + stderr: "未指定或未找到有效企业配置。请运行 'hose-use corps list' 或指定 '--corp='", exitCode: 1, }; } @@ -24,13 +24,13 @@ export async function handleContactCommand( const action = parsed.action || parsed.args[0] || "list"; const limit = numberOption(parsed.options, ["limit", "l"]); - // 1. 搜索: hose contact search 或 hose contact find + // 1. 搜索: hose-use contact search 或 hose-use contact find if (action === "search" || action === "find") { const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k"]) || ""; if (!keyword.trim()) { return { stdout: "", - stderr: "用法: hose contact search <关键词 (姓名/邮箱/工号)>", + stderr: "用法: hose-use contact search <关键词 (姓名/邮箱/工号)>", exitCode: 1, }; } @@ -67,13 +67,13 @@ export async function handleContactCommand( }; } - // 2. 详情: hose contact get + // 2. 详情: hose-use contact get if (action === "get") { const staffId = parsed.args[0] || stringOption(parsed.options, ["id", "staff-id"]); if (!staffId) { return { stdout: "", - stderr: "用法: hose contact get ", + stderr: "用法: hose-use contact get ", exitCode: 1, }; } @@ -110,7 +110,7 @@ export async function handleContactCommand( }; } - // 3. 列表采样: hose contact list (默认限流截断防爆) + // 3. 列表采样: hose-use contact list (默认限流截断防爆) if (action === "list") { const isFull = runtime.outputOptions?.allowFull === true; const result = await listStaffsProtected(corp, { diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index 4fbd2fb..099831e 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -42,7 +42,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise [ @@ -61,7 +61,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise 切换工作企业\n`, + stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示: 使用 hose-use corps switch <企业ID> 切换工作企业\n`, stderr: "", exitCode: 0, }; @@ -70,14 +70,14 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const corpId = parsed.args[0]; if (!corpId) { - return { stdout: "", stderr: "用法: hose corps switch <企业ID>\n", exitCode: 1 }; + return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 }; } const success = runtime.corpContext.switchCorp(corpId); if (!success) { return { stdout: "", - stderr: `企业 ${corpId} 不存在或未配置。可运行 hose corps list 查看可用列表。\n`, + stderr: `企业 ${corpId} 不存在或未配置。可运行 hose-use corps list 查看可用列表。\n`, exitCode: 1, }; } diff --git a/src/cli/commands/dimension.ts b/src/cli/commands/dimension.ts index 0fa0357..004c6d2 100644 --- a/src/cli/commands/dimension.ts +++ b/src/cli/commands/dimension.ts @@ -6,7 +6,7 @@ import { searchDimensions, resolveDimension } from "../../domains/dimension/tool export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const corp = runtime.selectedCorp; - if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose auth login 登录。"); + if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose-use auth login 登录。"); const client = await createEkbClient(corp); const corpId = corp.corpId || corp.id; const action = parsed.action?.toLowerCase() || "list"; @@ -19,7 +19,7 @@ export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: Cli } if (["items", "get", "show"].includes(action)) { const target = parsed.args[0] || stringOption(parsed.options, ["dimension", "id", "code", "name"]); - if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose dimension items <维度>"); + if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose-use dimension items <维度>"); const result = await resolveDimension(client, corpId, target); if (!result) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; diff --git a/src/cli/commands/message.ts b/src/cli/commands/message.ts index b71d4fa..1e36af4 100644 --- a/src/cli/commands/message.ts +++ b/src/cli/commands/message.ts @@ -24,7 +24,7 @@ function renderItems(items: MessageItem[]): string { export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const corp = runtime.selectedCorp; - if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp="); + if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp="); const action = parsed.action || parsed.args[0] || "list"; const client = await createEkbClient(corp); const corpId = corp.corpId || corp.id; @@ -37,7 +37,7 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu if (action === "read" || action === "mark-read") { const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]); - if (!messageId) return { stdout: "", stderr: "用法: hose message read \n", exitCode: 1 }; + if (!messageId) return { stdout: "", stderr: "用法: hose-use message read \n", exitCode: 1 }; await readMessage(client, corpId, messageId); if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 }; diff --git a/src/cli/commands/permission.ts b/src/cli/commands/permission.ts index 37b200a..991adb3 100644 --- a/src/cli/commands/permission.ts +++ b/src/cli/commands/permission.ts @@ -5,7 +5,7 @@ import { getPermissions } from "../../domains/permission/tools.js"; export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const corp = runtime.selectedCorp; - if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose auth login 登录。"); + if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose-use auth login 登录。"); const action = parsed.action?.toLowerCase() || "get"; if (!["get", "list", "show"].includes(action)) throw new Error(`未知 permission 子命令: ${action}。支持: get`); const client = await createEkbClient(corp); diff --git a/src/cli/commands/platform.ts b/src/cli/commands/platform.ts index a0b10bd..966ccf3 100644 --- a/src/cli/commands/platform.ts +++ b/src/cli/commands/platform.ts @@ -11,7 +11,7 @@ export async function handlePlatformCommand( if (!currentCorp) { return { stdout: "", - stderr: "未选中企业,请先通过 hose corps switch 或 --corp 指定企业\n", + stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1, }; } diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts index ac61942..cf7bd7c 100644 --- a/src/cli/commands/probe.ts +++ b/src/cli/commands/probe.ts @@ -11,7 +11,7 @@ export async function handleProbeCommand( if (!currentCorp) { return { stdout: "", - stderr: "未配置任何企业,请先运行 hose auth login 或使用 --corp 指定\n", + stderr: "未配置任何企业,请先运行 hose-use auth login 或使用 --corp 指定\n", exitCode: 1, }; } diff --git a/src/cli/commands/role.ts b/src/cli/commands/role.ts index 2c108a7..643c13e 100644 --- a/src/cli/commands/role.ts +++ b/src/cli/commands/role.ts @@ -6,7 +6,7 @@ import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/t export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const corp = runtime.selectedCorp; - if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose auth login 登录。"); + if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose-use auth login 登录。"); const client = await createEkbClient(corp), corpId = corp.corpId || corp.id; const action = parsed.action?.toLowerCase() || "list"; if (["list", "search"].includes(action)) { @@ -26,7 +26,7 @@ export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRunti } if (["members", "member", "staffs", "staff"].includes(action)) { const target = parsed.args[0] || stringOption(parsed.options, ["role", "id", "code", "name"]); - if (!target) throw new Error("请提供角色 ID、编码或名称: hose role members <角色>"); + if (!target) throw new Error("请提供角色 ID、编码或名称: hose-use role members <角色>"); const report = await getRoleMembers(client, corpId, target); if (!report) { if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 }; diff --git a/src/cli/commands/task.ts b/src/cli/commands/task.ts index b8b53e8..aaac18f 100644 --- a/src/cli/commands/task.ts +++ b/src/cli/commands/task.ts @@ -15,7 +15,7 @@ function dateOption(value: string | undefined): number | undefined { export async function handleTaskCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const corp = runtime.selectedCorp; - if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp="); + if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp="); const action = parsed.action || parsed.args[0] || "todo"; const view: TaskView | undefined = action === "todo" || action === "pending" ? "todo" diff --git a/src/cli/commands/workflow.ts b/src/cli/commands/workflow.ts index 8632cf6..5efd3a6 100644 --- a/src/cli/commands/workflow.ts +++ b/src/cli/commands/workflow.ts @@ -17,7 +17,7 @@ export async function handleWorkflowCommand( if (!currentCorp) { return { stdout: "", - stderr: "未选中企业,请先通过 hose corps switch 或 --corp 指定企业\n", + stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1, }; } @@ -52,7 +52,7 @@ export async function handleWorkflowCommand( async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); - if (!pipelineId) return { stdout: "", stderr: "用法: hose workflow analyze \n", exitCode: 1 }; + if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze \n", exitCode: 1 }; const clients = await createClientsForCorp(runtime.selectedCorp!); const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId); const result = analyzeWorkflow(detail); @@ -110,7 +110,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); if (!pipelineId) { - return { stdout: "", stderr: "用法: hose workflow get \n", exitCode: 1 }; + return { stdout: "", stderr: "用法: hose-use workflow get \n", exitCode: 1 }; } const clients = await createClientsForCorp(runtime.selectedCorp!); @@ -152,7 +152,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise (如 code-js2, http, condition)\n", + stderr: "用法: hose-use workflow find --task=<节点类型> (如 code-js2, http, condition)\n", exitCode: 1, }; } @@ -207,7 +207,7 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise if (!pipelineId || stateArg === undefined) { return { stdout: "", - stderr: "用法: hose workflow toggle --state=<1|0> (1启用, 0停用)\n", + stderr: "用法: hose-use workflow toggle --state=<1|0> (1启用, 0停用)\n", exitCode: 1, }; } diff --git a/src/cli/runner.ts b/src/cli/runner.ts index cb97e3e..2961feb 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -229,7 +229,7 @@ async function dispatchCli( default: return { stdout: "", - stderr: `未知命令域: ${parsed.area}。运行 hose --help 查看帮助\n`, + stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`, exitCode: 1, }; } diff --git a/src/cli/service.ts b/src/cli/service.ts index f194dd5..630196f 100644 --- a/src/cli/service.ts +++ b/src/cli/service.ts @@ -39,7 +39,7 @@ export async function runServiceCommand( case undefined: return serviceStatus(config); default: - throw new Error("用法: hose service "); + throw new Error("用法: hose-use service "); } } diff --git a/src/core/auth/tools.ts b/src/core/auth/tools.ts index 1bc059c..8d1d236 100644 --- a/src/core/auth/tools.ts +++ b/src/core/auth/tools.ts @@ -47,7 +47,7 @@ export const authTools = [ if (!current) { return { authenticated: false, - message: "未配置任何企业,请先运行 hose auth login", + message: "未配置任何企业,请先运行 hose-use auth login", }; } diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index 8adb419..0b51a4d 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -45,7 +45,7 @@ export function resolveCorpConfig( if (!options.stateful) { throw new Error( "当前处于无状态模式 (Stateless Mode)。执行企业级操作必须显式指定 --corp 。\n" + - "如需设置默认企业,可执行 `hose config mode stateful` 切换为有状态模式。" + "如需设置默认企业,可执行 `hose-use config mode stateful` 切换为有状态模式。" ); } @@ -53,7 +53,7 @@ export function resolveCorpConfig( if (firstCorp) return firstCorp; const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : ""; - throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`); + throw new Error(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`); } export class CorpContext { diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index 655e364..9e3718b 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -36,4 +36,4 @@ src/domains/bill/ - `commentBill` 调用 `POST /api/flow/v1/flows/comment/$`,使用 `freeflow.comment`,保留参与人和私密评论参数; - 动作执行前从审批详情解析 backlog ID、流程 ID、当前节点 ID,并可依据 `flow.actions` 校验当前身份是否具备该动作权限。 -CLI 入口为 `hose bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。 +CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。 diff --git a/src/domains/contact/tools.ts b/src/domains/contact/tools.ts index 9d58e7d..d3eb5fe 100644 --- a/src/domains/contact/tools.ts +++ b/src/domains/contact/tools.ts @@ -24,7 +24,7 @@ export async function listStaffsProtected( limit, hasMore, hint: hasMore - ? `企业员工共 ${total} 人,当前仅展示前 ${staffs.length} 条以防止上下文溢出。可使用 'hose contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'` + ? `企业员工共 ${total} 人,当前仅展示前 ${staffs.length} 条以防止上下文溢出。可使用 'hose-use contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'` : undefined, staffs, }; diff --git a/src/domains/permission/README.permission.md b/src/domains/permission/README.permission.md index 425b4ba..a1ebd26 100644 --- a/src/domains/permission/README.permission.md +++ b/src/domains/permission/README.permission.md @@ -4,4 +4,4 @@ - `GET /api/glue/v1/organization/permissions/query?model=ROLE&corpId=...` -CLI 入口为 `hose permission get`(也支持 `hose permissions get`)。写入权限仍需通过 Web 端明确操作,CLI 不提供写操作。 +CLI 入口为 `hose-use permission get`(也支持 `hose-use permissions get`)。写入权限仍需通过 Web 端明确操作,CLI 不提供写操作。 diff --git a/src/domains/role/README.role.md b/src/domains/role/README.role.md index 4d5bfb4..da60149 100644 --- a/src/domains/role/README.role.md +++ b/src/domains/role/README.role.md @@ -6,4 +6,4 @@ - `GET /api/v1/organization/roleGroups?corpId=...`:角色组及其角色定义 - `GET /api/v1/organization/staffs/byRole?roleDefId=...&corpId=...`:指定角色的员工成员 -CLI 入口为 `hose role list`、`hose role groups` 和 `hose role members <角色 ID|编码|名称>`。 +CLI 入口为 `hose-use role list`、`hose-use role groups` 和 `hose-use role members <角色 ID|编码|名称>`。 From 62025cb6f1dee3a0e87d948a771619d0741c92f1 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:36:58 +0800 Subject: [PATCH 03/11] feat(aipro): add scopes index command and decouple points from bills --- src/aipro-cli.ts | 228 +++++++++++++++++++++++++---- src/domains/approval/db.ts | 6 + src/domains/approval/repository.ts | 10 +- src/domains/approval/service.ts | 1 + src/domains/approval/types.ts | 1 + 5 files changed, 217 insertions(+), 29 deletions(-) diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 9b924fd..5709458 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -66,27 +66,200 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; try { switch (command) { - // ── 1. 明细级规则注入(出审核要点清单)──────────────────────────────── + // ── 1. 规约场景索引列表查看 ───────────────────────────────────────── + case "scopes": + case "scope": + case "rules": + case "rule": + case "index": + case "indexes": { + const scopes = repo.listScopes(); + if (runtime.jsonMode) { + return { + stdout: printJson({ count: scopes.length, scopes }), + stderr: "", + exitCode: 0, + }; + } + const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"]; + const rows = scopes.map((s) => [ + s.index, + s.scope, + s.ruleCount, + s.ruleCodes.map((c) => `#${c}`).join(", "), + ]); + const table = printTable(headers, rows); + const title = `====== [AI PRO] 规约场景索引列表 (共 ${scopes.length} 个适用场景) ======\n`; + const tip = + `\n提示:\n` + + ` • 查看场景审核要点 (纯规则元数据,与单据无关): hose-aipro points <索引号|场景名称> (例如: hose-aipro points 1)\n` + + ` • 绑定单据发起审核: hose-aipro bind <单号> <索引号> (例如: hose-aipro bind S26000001 1)\n`; + return { stdout: title + table + tip, stderr: "", exitCode: 0 }; + } + + // ── 2. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── case "points": - case "inject": { - if (!targetSn) { - throw new Error("请提供单号: hose-aipro points <单号> [--scope <1|场景>]"); + case "clauses": { + const arg1 = positional[1] || stringOption(parsed.options, ["scope", "s", "index", "i"]); + const arg2 = positional[2]; + + // 兼容双参数调用: 如果同时提供了单号和索引号,走单据绑定流 + if (arg1 && arg2) { + const billSn = arg1; + const scopeTarget = arg2; + const context = await getClient(); + const result = await service.injectAuditPoints(context.client, context.corpId, billSn, { + scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined, + }); + + repo.logAiProAction({ + action: "bind", + documentSn: result.bill.billCode, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + decision: "PENDING", + summary: `绑定单据并挂载审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson({ + sn: result.bill.billCode, + scope: result.scope, + runId: result.run.id, + count: result.findings.length, + findings: result.findings, + }), + stderr: "", + exitCode: 0, + }; + } + + const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"]; + const rows = result.findings.map((f, i) => [ + i + 1, + `[${f.strictness}]`, + f.ruleCode ? `#${f.ruleCode}` : "-", + f.clauseText, + f.checkStatus, + ]); + + const table = printTable(headers, rows); + const title = `====== [AI PRO] 单据 ${result.bill.billCode} 已挂载场景 [${result.scope}] 审核要点 (共 ${result.findings.length} 条) ======\n`; + const tip = + `\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` + + `下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` + + `最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`; + + return { stdout: title + table + tip, stderr: "", exitCode: 0 }; + } + + // 纯规则审查要点输出(与具体单据没有任何关系!) + const targetScope = arg1; + if (!targetScope) { + const allScopes = repo.listScopes("active"); + if (allScopes.length === 0) { + return { stdout: "规约库中暂无生效规则。可使用 hose-use rule add <场景> <正文> 新增规则。\n", stderr: "", exitCode: 0 }; + } + const lines: string[] = [ + `====== [AI PRO] 规约审核要点总览 (共 ${allScopes.length} 个适用场景) ======\n` + ]; + for (const s of allScopes) { + const detail = repo.getScopeDetail(s.index); + if (!detail) continue; + lines.push(`▶ 场景 [${detail.index}] ${detail.scope} (包含 ${detail.ruleCount} 条规则):`); + let count = 0; + detail.rules.forEach((r) => { + r.parsed.clauses.forEach((c) => { + count++; + lines.push(` ${count}. [${c.strictness}] (规则 #${r.code}) ${c.action}`); + }); + }); + lines.push(""); + } + lines.push(`提示: 输入 "hose-aipro points <索引号|场景名称>" 查看指定场景要点明细。\n`); + return { stdout: lines.join("\n"), stderr: "", exitCode: 0 }; + } + + const detail = repo.getScopeDetail(targetScope); + if (!detail) { + return { + stdout: "", + stderr: `[NOT FOUND] 未找到索引号或场景为 "${targetScope}" 的规约场景。\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`, + exitCode: 1, + }; + } + + const points: Array<{ index: number; strictness: string; ruleCode: number; clauseText: string }> = []; + let count = 0; + for (const rule of detail.rules) { + for (const clause of rule.parsed.clauses) { + count++; + points.push({ + index: count, + strictness: clause.strictness, + ruleCode: rule.code, + clauseText: clause.action, + }); + } + } + + if (runtime.jsonMode) { + return { + stdout: printJson({ + index: detail.index, + scope: detail.scope, + ruleCount: detail.ruleCount, + pointsCount: points.length, + points, + }), + stderr: "", + exitCode: 0, + }; + } + + const headers = ["#", "严格程度", "归属规则", "审核要点内容 (Clause)"]; + const rows = points.map((p) => [ + p.index, + `[${p.strictness}]`, + `#${p.ruleCode}`, + p.clauseText, + ]); + + const table = printTable(headers, rows); + const title = `====== [AI PRO] 适用场景 [${detail.index}] ${detail.scope} - 审核要点清单 (共 ${points.length} 条要点) ======\n`; + const tip = + `\n说明: 审核要点为规约条款提取出的判定标准,纯规则元数据,与具体单据无关。\n` + + `绑定单据: 运行 "hose-aipro bind <单号> ${detail.index}" 将此要点清单挂载到具体单据。\n`; + + return { stdout: title + table + tip, stderr: "", exitCode: 0 }; + } + + // ── 3. 绑定单据与规则场景(激活审批运行实例)───────────────────────── + case "bind": + case "mount": + case "init": { + const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]); + const scopeTarget = positional[2] || stringOption(parsed.options, ["scope", "s", "index", "i"]); + + if (!billSn) { + throw new Error("请提供单号: hose-aipro bind <单号> [索引号|场景名称]"); } - const scopeOption = stringOption(parsed.options, ["scope", "s"]); const context = await getClient(); - const result = await service.injectAuditPoints(context.client, context.corpId, targetSn, { - scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined, + const result = await service.injectAuditPoints(context.client, context.corpId, billSn, { + scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined, }); repo.logAiProAction({ - action: "points", + action: "bind", documentSn: result.bill.billCode, operator, args: JSON.stringify(rawArgs), status: "SUCCESS", decision: "PENDING", - summary: `注入审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`, + summary: `绑定单据并挂载审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`, }); if (runtime.jsonMode) { @@ -113,7 +286,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; ]); const table = printTable(headers, rows); - const title = `====== [AI PRO] 单据 ${result.bill.billCode} 审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`; + const title = `====== [AI PRO] 单据 ${result.bill.billCode} 已挂载场景 [${result.scope}] 审核要点 (共 ${result.findings.length} 条) ======\n`; const tip = `\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` + `下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` + @@ -122,7 +295,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; return { stdout: title + table + tip, stderr: "", exitCode: 0 }; } - // ── 2. 查看审核要点清单与进度(未注入则硬阻断)──────────────────────── + // ── 4. 查看审核要点清单与进度(未绑定则硬阻断)──────────────────────── case "checklist": case "list": case "status": { @@ -139,13 +312,13 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; operator, args: JSON.stringify(rawArgs), status: "BLOCKED", - summary: "查询审核清单阻断:单据尚未注入任何审核要点", + summary: "查询审核清单阻断:单据尚未绑定任何审核要点", }); const errorMsg = - `[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` + - `网关安全卡点生效:在要点未注入前,审批链路物理不通!\n` + - `请先执行: hose-aipro points ${targetSn} 注入明细级审核要点清单。\n`; + `[审批链路阻断] 单据 [${targetSn}] 尚未绑定任何明细级审核要点(要点列表为空)!\n` + + `网关安全卡点生效:在要点未绑定前,审批链路物理不通!\n` + + `请先执行: hose-aipro bind ${targetSn} <索引号> 挂载明细级审核要点清单。\n`; return { stdout: "", stderr: errorMsg, exitCode: 1 }; } @@ -169,7 +342,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; const table = printTable(headers, rows); const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length; - const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`; + const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (适用场景: [${run.scope || "未关联"}] | 总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`; return { stdout: title + table, stderr: "", exitCode: 0 }; } @@ -382,25 +555,28 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; 一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。 核心工作流: - 1. 规则注入 (出明细级审核要点清单): - hose-aipro points <单号> [--scope <索引号|场景>] + 1. 查看规约场景索引库 (获取规则索引号): + hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数) - 2. 查看审核要点清单与核验进度 (未注入则硬阻断): - hose-aipro checklist <单号> + 2. 查看场景审核要点清单 (纯规则元数据,与单据无关): + hose-aipro points <索引号|场景名称> # 例如: hose-aipro points 1 - 3. 逐项录入事实核验打标: + 3. 显式绑定单据并挂载审核要点: + hose-aipro bind <单号> <索引号> # 例如: hose-aipro bind S26000001 1 + + 4. 查看单据审核清单与核验进度: + hose-aipro checklist <单号> # 查看当前单据要点核验进度与挂载场景 + + 5. 逐项录入事实核验打标: hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP" hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票" - 4. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支): + 6. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支): hose-aipro decide <单号> # 预审仿真 (Dry Run) hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论 - 5. 全流程监控日志流水查看: + 7. 全流程监控日志流水查看: hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水 - - 6. 查看审批规约场景: - hose-aipro rules # 查看所有场景与规则分布 `; return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 }; } diff --git a/src/domains/approval/db.ts b/src/domains/approval/db.ts index d005982..16a1822 100644 --- a/src/domains/approval/db.ts +++ b/src/domains/approval/db.ts @@ -108,6 +108,7 @@ export function initDatabaseSchema(db: Database): void { flow_id TEXT, document_sn TEXT NOT NULL, corp_id TEXT, + scope TEXT, decision TEXT NOT NULL, decision_summary TEXT, matched_rules_count INTEGER NOT NULL DEFAULT 0, @@ -117,6 +118,11 @@ export function initDatabaseSchema(db: Database): void { updated_at INTEGER NOT NULL ); `); + try { + db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); + } catch { + // column already exists + } db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);"); db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);"); diff --git a/src/domains/approval/repository.ts b/src/domains/approval/repository.ts index 7cfd844..ce51295 100644 --- a/src/domains/approval/repository.ts +++ b/src/domains/approval/repository.ts @@ -296,12 +296,13 @@ export class ApprovalRepository { this.db.run( ` UPDATE approval_runs - SET flow_id = ?, corp_id = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ? + SET flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ? WHERE id = ? `, [ (input.flowId !== undefined ? input.flowId : existing.flowId) ?? null, (input.corpId !== undefined ? input.corpId : existing.corpId) ?? null, + (input.scope !== undefined ? input.scope : existing.scope) ?? null, input.decision ?? "PENDING", (input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null, input.matchedRulesCount ?? 0, @@ -318,14 +319,15 @@ export class ApprovalRepository { this.db.run( ` INSERT INTO approval_runs ( - id, flow_id, document_sn, corp_id, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + id, flow_id, document_sn, corp_id, scope, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `, [ id, input.flowId ?? null, input.documentSn.trim(), input.corpId ?? null, + input.scope ?? null, input.decision ?? "PENDING", input.decisionSummary ?? null, input.matchedRulesCount ?? 0, @@ -515,6 +517,7 @@ export class ApprovalRepository { flowId: row.flow_id, documentSn: row.document_sn, corpId: row.corp_id, + scope: row.scope ?? null, decision: row.decision as ApprovalDecision, decisionSummary: row.decision_summary, matchedRulesCount: Number(row.matched_rules_count || 0), @@ -611,6 +614,7 @@ export interface CreateApprovalRunInput { documentSn: string; flowId?: string | null; corpId?: string | null; + scope?: string | null; decision?: ApprovalDecision; decisionSummary?: string | null; matchedRulesCount?: number; diff --git a/src/domains/approval/service.ts b/src/domains/approval/service.ts index e9348b1..60ce21c 100644 --- a/src/domains/approval/service.ts +++ b/src/domains/approval/service.ts @@ -118,6 +118,7 @@ export class ApprovalService { documentSn: actualSn, flowId: bill.billId, corpId, + scope: scopeDetail.scope, decision: "PENDING", matchedRulesCount: clauseInputs.length, failedRulesCount: 0, diff --git a/src/domains/approval/types.ts b/src/domains/approval/types.ts index e406592..3976aea 100644 --- a/src/domains/approval/types.ts +++ b/src/domains/approval/types.ts @@ -80,6 +80,7 @@ export interface ApprovalRunRecord { flowId?: string | null; documentSn: string; corpId?: string | null; + scope?: string | null; decision: ApprovalDecision; decisionSummary?: string | null; matchedRulesCount: number; From 8d203fc2303bc4a44593d35224618c092cd81b27 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:39:45 +0800 Subject: [PATCH 04/11] feat(aipro): format scopes command output as pure json with index and scope --- src/aipro-cli.ts | 43 +++++-------------------------------------- 1 file changed, 5 insertions(+), 38 deletions(-) diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 5709458..3ecb9df 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -73,28 +73,11 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; case "rule": case "index": case "indexes": { - const scopes = repo.listScopes(); - if (runtime.jsonMode) { - return { - stdout: printJson({ count: scopes.length, scopes }), - stderr: "", - exitCode: 0, - }; - } - const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"]; - const rows = scopes.map((s) => [ - s.index, - s.scope, - s.ruleCount, - s.ruleCodes.map((c) => `#${c}`).join(", "), - ]); - const table = printTable(headers, rows); - const title = `====== [AI PRO] 规约场景索引列表 (共 ${scopes.length} 个适用场景) ======\n`; - const tip = - `\n提示:\n` + - ` • 查看场景审核要点 (纯规则元数据,与单据无关): hose-aipro points <索引号|场景名称> (例如: hose-aipro points 1)\n` + - ` • 绑定单据发起审核: hose-aipro bind <单号> <索引号> (例如: hose-aipro bind S26000001 1)\n`; - return { stdout: title + table + tip, stderr: "", exitCode: 0 }; + const scopes = repo.listScopes().map((s) => ({ + index: s.index, + scope: s.scope, + })); + return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 }; } // ── 2. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── @@ -530,22 +513,6 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; return { stdout: title + table, stderr: "", exitCode: 0 }; } - // ── 6. 规约快捷查看 ─────────────────────────────────────────────────── - case "rules": - case "rule": - case "scopes": { - const scopes = repo.listScopes(); - const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"]; - const rows = scopes.map((s) => [ - s.index, - s.scope, - s.ruleCount, - s.ruleCodes.map((c) => `#${c}`).join(", "), - ]); - const table = printTable(headers, rows); - const title = `====== [AI PRO] 规约场景索引库 (共 ${scopes.length} 个场景) ======\n`; - return { stdout: title + table, stderr: "", exitCode: 0 }; - } // ── 7. 帮助 ─────────────────────────────────────────────────────────── case "help": From 950dd6d8fafedbc645b1885487a91129f2ab725c Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:44:00 +0800 Subject: [PATCH 05/11] feat(aipro): add multi-index rules command outputting matched scopes and rules --- src/aipro-cli.ts | 87 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 3ecb9df..17c0132 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -68,9 +68,6 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; switch (command) { // ── 1. 规约场景索引列表查看 ───────────────────────────────────────── case "scopes": - case "scope": - case "rules": - case "rule": case "index": case "indexes": { const scopes = repo.listScopes().map((s) => ({ @@ -80,6 +77,90 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 }; } + // ── 2. 查询命中索引关联的所有规则(支持传入一个或多个索引)────────────── + case "rules": + case "rule": + case "scope": { + const rawTargets = [ + ...positional.slice(1), + stringOption(parsed.options, ["scope", "s", "index", "i"]), + ].filter(Boolean) as string[]; + + const targets: string[] = []; + for (const raw of rawTargets) { + const trimmed = raw.trim(); + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + try { + const parsedJson = JSON.parse(trimmed); + if (Array.isArray(parsedJson)) { + targets.push(...parsedJson.map(String)); + continue; + } + } catch {} + } + if (trimmed.includes(",")) { + targets.push(...trimmed.split(",").map((s) => s.trim()).filter(Boolean)); + } else if (trimmed) { + targets.push(trimmed); + } + } + + const uniqueTargets = [...new Set(targets)]; + if (uniqueTargets.length === 0) { + // 未传入索引时,默认输出所有场景及其规则 + const allScopes = repo.listScopes("active"); + const result = allScopes.map((s) => { + const detail = repo.getScopeDetail(s.index)!; + return { + index: detail.index, + scope: detail.scope, + rules: detail.rules.map((r) => ({ + code: r.code, + text: r.body, + })), + }; + }); + return { stdout: JSON.stringify(result, null, 2) + "\n", stderr: "", exitCode: 0 }; + } + + const results: Array<{ + index: number; + scope: string; + rules: Array<{ code: number; text: string }>; + }> = []; + const notFound: string[] = []; + + for (const target of uniqueTargets) { + const detail = repo.getScopeDetail(target); + if (!detail) { + notFound.push(target); + continue; + } + results.push({ + index: detail.index, + scope: detail.scope, + rules: detail.rules.map((r) => ({ + code: r.code, + text: r.body, + })), + }); + } + + if (notFound.length > 0 && results.length === 0) { + return { + stdout: "", + stderr: `[NOT FOUND] 未找到指定索引对应的规约场景: ${notFound.join(", ")}\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`, + exitCode: 1, + }; + } + + return { + stdout: JSON.stringify(results, null, 2) + "\n", + stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: ${notFound.join(", ")}\n` : "", + exitCode: 0, + }; + } + // ── 2. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── case "points": case "clauses": { From 2afde446d2e43775d8850ba135427713b6393a93 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:46:37 +0800 Subject: [PATCH 06/11] feat(aipro): require wrapped array for rules input and flatten output by code --- src/aipro-cli.ts | 114 ++++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 56 deletions(-) diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 17c0132..44ad187 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -77,86 +77,88 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 }; } - // ── 2. 查询命中索引关联的所有规则(支持传入一个或多个索引)────────────── + // ── 2. 查询命中索引关联的所有规则(按 code 升序平铺输出纯规则)────────── case "rules": case "rule": case "scope": { - const rawTargets = [ + const rawInputs = [ ...positional.slice(1), - stringOption(parsed.options, ["scope", "s", "index", "i"]), + stringOption(parsed.options, ["scope", "s", "index", "i", "indexes"]), ].filter(Boolean) as string[]; - const targets: string[] = []; - for (const raw of rawTargets) { + const targetIndexes: number[] = []; + for (const raw of rawInputs) { const trimmed = raw.trim(); if (trimmed.startsWith("[") && trimmed.endsWith("]")) { try { const parsedJson = JSON.parse(trimmed); if (Array.isArray(parsedJson)) { - targets.push(...parsedJson.map(String)); + for (const item of parsedJson) { + const n = Number(item); + if (!isNaN(n)) targetIndexes.push(n); + } continue; } - } catch {} + } catch { + // 兼容非严格 JSON 数组,如 [1, 2] + const inner = trimmed.slice(1, -1); + const parts = inner.split(/[,,\s]+/).filter(Boolean); + for (const p of parts) { + const n = Number(p.replace(/['"]/g, "")); + if (!isNaN(n)) targetIndexes.push(n); + } + continue; + } } - if (trimmed.includes(",")) { - targets.push(...trimmed.split(",").map((s) => s.trim()).filter(Boolean)); - } else if (trimmed) { - targets.push(trimmed); + const parts = trimmed.split(/[,,\s]+/).filter(Boolean); + for (const p of parts) { + const n = Number(p.replace(/[\[\]'"]/g, "")); + if (!isNaN(n)) targetIndexes.push(n); } } - const uniqueTargets = [...new Set(targets)]; - if (uniqueTargets.length === 0) { - // 未传入索引时,默认输出所有场景及其规则 - const allScopes = repo.listScopes("active"); - const result = allScopes.map((s) => { - const detail = repo.getScopeDetail(s.index)!; - return { - index: detail.index, - scope: detail.scope, - rules: detail.rules.map((r) => ({ - code: r.code, - text: r.body, - })), - }; - }); - return { stdout: JSON.stringify(result, null, 2) + "\n", stderr: "", exitCode: 0 }; - } - - const results: Array<{ - index: number; - scope: string; - rules: Array<{ code: number; text: string }>; - }> = []; - const notFound: string[] = []; - - for (const target of uniqueTargets) { - const detail = repo.getScopeDetail(target); - if (!detail) { - notFound.push(target); - continue; - } - results.push({ - index: detail.index, - scope: detail.scope, - rules: detail.rules.map((r) => ({ - code: r.code, - text: r.body, - })), - }); - } - - if (notFound.length > 0 && results.length === 0) { + const uniqueIndexes = [...new Set(targetIndexes)].sort((a, b) => a - b); + if (uniqueIndexes.length === 0) { return { stdout: "", - stderr: `[NOT FOUND] 未找到指定索引对应的规约场景: ${notFound.join(", ")}\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`, + stderr: `请提供包裹好的索引数组,例如:\n hose-aipro rules "[2]"\n hose-aipro rules "[1, 2]"\n`, exitCode: 1, }; } + const rulesMap = new Map(); + const notFound: number[] = []; + + for (const idx of uniqueIndexes) { + const detail = repo.getScopeDetail(idx); + if (!detail) { + notFound.push(idx); + continue; + } + for (const r of detail.rules) { + if (!rulesMap.has(r.code)) { + rulesMap.set(r.code, { + code: r.code, + text: r.body, + }); + } + } + } + + if (notFound.length > 0 && rulesMap.size === 0) { + return { + stdout: "", + stderr: `[NOT FOUND] 未找到指定索引对应的规约场景: [${notFound.join(", ")}]\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`, + exitCode: 1, + }; + } + + // 按照 code 顺序平铺规则 + const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.code - b.code); + return { - stdout: JSON.stringify(results, null, 2) + "\n", - stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: ${notFound.join(", ")}\n` : "", + stdout: JSON.stringify(flattenedRules, null, 2) + "\n", + stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: [${notFound.join(", ")}]\n` : "", exitCode: 0, }; } From a16d429d440701a16058b6165d62683e3ff2cf7f Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 22:58:34 +0800 Subject: [PATCH 07/11] feat(aipro): add standalone document field translator and translate command --- src/aipro-cli.ts | 26 ++++- src/domains/bill/bill.test.ts | 42 ++++++++ src/domains/bill/tools.ts | 2 + src/domains/bill/translator.ts | 182 +++++++++++++++++++++++++++++++++ 4 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 src/domains/bill/translator.ts diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 44ad187..5907f59 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -9,6 +9,8 @@ import { ApprovalGatewayBlockedError, FindingCheckStatus, } from "./domains/approval/index.js"; +import { getRawBillFlow } from "./domains/bill/api.js"; +import { translateBillFlowToMarkdown } from "./domains/bill/translator.js"; import { VERSION } from "./version.js"; export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> { @@ -163,7 +165,29 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }; } - // ── 2. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── + // ── 3. 单据字段转译器(转译为标准 LLM / 审核视图 Markdown)───────────── + case "translate": + case "doc": + case "markdown": + case "render": { + const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]); + if (!billSn) { + throw new Error("请提供要转译的单号: hose-aipro translate <单号>"); + } + const context = await getClient(); + const raw = await getRawBillFlow(context.client, context.corpId, billSn); + if (!raw) { + throw new Error(`在当前企业下未找到单号或 ID 为 [${billSn}] 的单据`); + } + const markdown = translateBillFlowToMarkdown(raw); + return { + stdout: markdown.endsWith("\n") ? markdown : markdown + "\n", + stderr: "", + exitCode: 0, + }; + } + + // ── 4. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── case "points": case "clauses": { const arg1 = positional[1] || stringOption(parsed.options, ["scope", "s", "index", "i"]); diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index 5db4221..439c8a2 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -281,4 +281,46 @@ describe("Bill Domain", () => { } as any; await expect(resolveBillStaffIds(client, "corp-action", ["111", "谢子豪"])).resolves.toEqual(["corp:staff-2", "corp:staff-1"]); }); + + it("translates raw bill flow into standard markdown representation", () => { + const { translateBillFlowToMarkdown } = require("./translator.js"); + const rawFlow = { + flowId: { + state: "APPROVING", + form: { + code: "S26000001", + title: "我🩷吃醋", + specificationId: "ID01MCcOgJl1td:PRESET_REQUISITION_TRIP", + submitterId: { name: "谢子豪" }, + requisitionDate: 1769961600000, + submitDate: 1770284988706, + requisitionMoney: { standard: "1000.00", standardStrCode: "CNY" }, + details: [ + { + feeTypeId: "ID01MCcOgJl1td:hotel", + feeTypeForm: { + amount: { standard: "1000", standardStrCode: "CNY" }, + feeDate: 1770220800000, + city: '[{"key":"513","label":"辽宁省/大连市/大连市区"}]', + consumptionReasons: "今日在大连见客户", + detailId: "ID01QkCjK2m47Z", + detailNo: 1, + }, + }, + ], + }, + }, + }; + + const markdown = translateBillFlowToMarkdown(rawFlow); + expect(markdown).toContain("# 单据:S26000001"); + expect(markdown).toContain("- **状态**: 审批中 (approving)"); + expect(markdown).toContain("- **单据模板**: `差旅申请单`"); + expect(markdown).toContain("- **标题**: `我🩷吃醋`"); + expect(markdown).toContain("- **提交人**: 谢子豪"); + expect(markdown).toContain("- **申请金额**: CNY 1000.00"); + expect(markdown).toContain("### 费用明细(共 1 条)"); + expect(markdown).toContain("- **城市**: 辽宁省/大连市/大连市区"); + expect(markdown).toContain("- **消费事由**: `今日在大连见客户`"); + }); }); diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index a512366..db2244a 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -1270,3 +1270,5 @@ export const billTools = [ }, }, ]; + +export { translateBillFlowToMarkdown } from "./translator.js"; diff --git a/src/domains/bill/translator.ts b/src/domains/bill/translator.ts new file mode 100644 index 0000000..a8dcf19 --- /dev/null +++ b/src/domains/bill/translator.ts @@ -0,0 +1,182 @@ +import { KyInstance } from "ky"; +import { getRawBillFlow } from "./api.js"; +import { getFeeTypeTree } from "./api.js"; + +function formatDate(val: unknown): string { + if (!val) return ""; + if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) { + const d = new Date(Number(val)); + if (!isNaN(d.getTime())) { + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, "0"); + const day = String(d.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; + } + } + if (typeof val === "string") { + const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})/); + if (match) { + return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`; + } + return val; + } + return String(val); +} + +function formatDateTime(val: unknown): string { + if (!val) return ""; + if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) { + const d = new Date(Number(val)); + if (!isNaN(d.getTime())) { + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, "0"); + const day = String(d.getDate()).padStart(2, "0"); + const hours = String(d.getHours()).padStart(2, "0"); + const minutes = String(d.getMinutes()).padStart(2, "0"); + return `${year}-${month}-${day} ${hours}:${minutes}`; + } + } + return String(val); +} + +function parseCity(cityVal: unknown): string { + if (!cityVal) return ""; + if (typeof cityVal === "string") { + try { + const parsed = JSON.parse(cityVal); + if (Array.isArray(parsed) && parsed[0]?.label) { + return parsed[0].label; + } + } catch {} + return cityVal; + } + if (Array.isArray(cityVal) && cityVal[0]?.label) { + return cityVal[0].label; + } + return String(cityVal); +} + +function formatAmount(money: any): string { + if (!money) return "CNY 0.00"; + if (typeof money === "number") return `CNY ${money.toFixed(2)}`; + if (typeof money === "string") { + const n = parseFloat(money.replace(/[^0-9.-]/g, "")); + return isNaN(n) ? money : `CNY ${n.toFixed(2)}`; + } + if (typeof money === "object") { + const currency = money.standardStrCode || money.currency || "CNY"; + const amountNum = parseFloat(money.standard || money.amount || 0); + return `${currency} ${isNaN(amountNum) ? "0.00" : amountNum.toFixed(2)}`; + } + return String(money); +} + +function resolveSpecificationName(specId: unknown): string { + if (!specId || typeof specId !== "string") return "未知模板"; + if (specId.includes("REQUISITION_TRIP") || specId.includes("trip")) return "差旅申请单"; + if (specId.includes("REIMBURSEMENT") || specId.includes("expense")) return "报销单"; + if (specId.includes("LOAN") || specId.includes("loan")) return "借款单"; + if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款单"; + return specId; +} + +/** + * 将合思原始单据流对象转译为标准 LLM / 审核视图 Markdown (单据字段转译器) + */ +export function translateBillFlowToMarkdown( + rawFlow: Record, + feeTypeMap?: Map +): string { + const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record; + const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record; + + const code = form.code || flowIdObj.code || "未知单号"; + const title = form.title || flowIdObj.title || "<无标题>"; + const rawState = flowIdObj.state || "approving"; + const stateLabel = String(rawState).toUpperCase() === "APPROVING" ? "审批中" : rawState; + const submitTime = formatDate(form.submitDate || flowIdObj.createTime); + const templateName = resolveSpecificationName(form.specificationId); + const submitterName = form.submitterId?.name || (typeof form.submitterId === "string" ? form.submitterId : "未知"); + const requisitionDate = formatDate(form.requisitionDate); + const totalMoney = formatAmount(form.requisitionMoney || form.amount); + + const lines: string[] = []; + lines.push(`# 单据:${code}`); + lines.push(""); + lines.push("## 基本信息"); + lines.push(""); + lines.push(`- **状态**: ${stateLabel} (${String(rawState).toLowerCase()})`); + lines.push(`- **提交时间**: ${submitTime}`); + lines.push(""); + lines.push(`### 单据信息(${code})`); + lines.push(""); + lines.push(`- **单据模板**: \`${templateName}\``); + lines.push(`- **补充申请**: <无>`); + lines.push(`- **标题**: \`${title}\``); + lines.push(`- **提交人**: ${submitterName}`); + if (requisitionDate) { + lines.push(`- **申请日期**: ${requisitionDate}`); + } + lines.push(`- **单号**: \`${code}\``); + lines.push(`- **提交日期**: ${submitTime}`); + lines.push(`- **申请金额**: ${totalMoney}`); + lines.push(""); + + // 行程规划 + const itineraries = Array.isArray(form.itineraries) ? form.itineraries : []; + lines.push(`### 行程规划(共 ${itineraries.length} 条)`); + lines.push(""); + + // 费用明细 + const details = Array.isArray(form.details) ? form.details : []; + lines.push(`### 费用明细(共 ${details.length} 条)`); + lines.push(""); + + details.forEach((item: any, idx: number) => { + const num = idx + 1; + lines.push(`#### 明细 ${num}`); + lines.push(""); + + const feeForm = item.feeTypeForm || item; + const feeTypeId = item.feeTypeId || feeForm.feeTypeId || ""; + let feeTypeName = "住宿费"; + let feeTypePath = "差旅报销/住宿费"; + + if (feeTypeMap?.has(feeTypeId)) { + const match = feeTypeMap.get(feeTypeId)!; + feeTypeName = match.name || feeTypeName; + feeTypePath = match.path || feeTypeName; + } else if (typeof feeTypeId === "string") { + if (feeTypeId.includes("hotel") || feeTypeId.includes("住宿")) { + feeTypeName = "住宿费"; + feeTypePath = "差旅报销/住宿费"; + } else if (feeTypeId.includes("meal") || feeTypeId.includes("餐")) { + feeTypeName = "餐饮费"; + feeTypePath = "业务招待/餐饮费"; + } else if (feeTypeId.includes("traffic") || feeTypeId.includes("交通")) { + feeTypeName = "市内交通费"; + feeTypePath = "差旅报销/市内交通费"; + } + } + + lines.push(`- **费用类型**: ${feeTypePath}(name=${feeTypeName})`); + lines.push(`- **金额**: ${formatAmount(feeForm.amount)}`); + if (feeForm.feeDate) { + lines.push(`- **日期**: ${formatDateTime(feeForm.feeDate)}`); + } + const city = parseCity(feeForm.city); + if (city) { + lines.push(`- **城市**: ${city}`); + } + if (feeForm.consumptionReasons) { + lines.push(`- **消费事由**: \`${feeForm.consumptionReasons}\``); + } + if (feeForm.detailId) { + lines.push(`- **费用ID**: \`${feeForm.detailId}\``); + } + lines.push(`- **明细序号**: ${feeForm.detailNo || num}`); + lines.push(""); + }); + + return lines.join("\n"); +} From b0149ed32dd716306562047ff2cf008bc8deac5b Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 23:23:57 +0800 Subject: [PATCH 08/11] feat(aipro): introduce init session with 6-char short runId and 6h TTL, support --run audit logging in scopes, translate, rules and logs --- src/aipro-cli.ts | 259 ++++++++++++++++++++++---- src/domains/approval/approval.test.ts | 60 ++++++ src/domains/approval/db.ts | 18 +- src/domains/approval/repository.ts | 125 +++++++++---- src/domains/approval/types.ts | 3 + 5 files changed, 392 insertions(+), 73 deletions(-) diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 5907f59..3f2b0f0 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -8,6 +8,7 @@ import { ApprovalRepository, ApprovalGatewayBlockedError, FindingCheckStatus, + ApprovalRunRecord, } from "./domains/approval/index.js"; import { getRawBillFlow } from "./domains/bill/api.js"; import { translateBillFlowToMarkdown } from "./domains/bill/translator.js"; @@ -36,7 +37,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; const eqIdx = arg.indexOf("="); if (eqIdx === -1) { const flagName = arg.replace(/^--?/, "").toLowerCase(); - const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute", "run", "do"].includes(flagName); + const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute"].includes(flagName); if (!isBool && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) { i++; // skip option value } @@ -68,10 +69,83 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; try { switch (command) { - // ── 1. 规约场景索引列表查看 ───────────────────────────────────────── + // ── 1. 初始化审批实例会话(签发 6 位短 ID,有效期 6 小时)────────────── + case "init": + case "start": { + const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]); + if (!billSn) { + throw new Error("请提供单号: hose-aipro init <单号>"); + } + const context = await getClient(); + const raw = await getRawBillFlow(context.client, context.corpId, billSn); + if (!raw) { + throw new Error(`在当前企业下未找到单号为 [${billSn}] 的单据`); + } + const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record; + const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record; + const title = form.title || flowIdObj.title || "<无标题>"; + const snapshot = translateBillFlowToMarkdown(raw); + + // 创建全新独立运行实例 (永久长 ID + 6 位短 ID, 6 小时有效期) + const run = repo.createApprovalRun({ + documentSn: form.code || billSn, + corpId: context.corpId, + flowId: flowIdObj.id || raw.id, + documentSnapshot: snapshot, + }); + + repo.logAiProAction({ + action: "init", + runId: run.shortId || run.id, + documentSn: run.documentSn, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + summary: `初始化审批会话成功,签发 6 位短 ID: ${run.shortId} (有效期 6 小时)`, + }); + + return { + stdout: JSON.stringify( + { + runId: run.shortId, + documentSn: run.documentSn, + title, + corpId: run.corpId, + status: run.decision, + expiresIn: "6h", + createdAt: run.createdAt, + }, + null, + 2 + ) + "\n", + stderr: "", + exitCode: 0, + }; + } + + // ── 2. 规约场景索引列表查看(支持 --run 锚定会话)───────────── case "scopes": case "index": case "indexes": { + const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1]; + let runRecord: ApprovalRunRecord | null = null; + if (runHandle) { + runRecord = repo.getRunByHandle(runHandle); + if (!runRecord) { + throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`); + } + } + + repo.logAiProAction({ + action: "scopes", + runId: runRecord?.shortId || runRecord?.id, + documentSn: runRecord?.documentSn, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + summary: runRecord ? `在会话 [${runRecord.shortId}] 查阅规约场景索引` : "查阅规约场景索引", + }); + const scopes = repo.listScopes().map((s) => ({ index: s.index, scope: s.scope, @@ -79,15 +153,111 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 }; } - // ── 2. 查询命中索引关联的所有规则(按 code 升序平铺输出纯规则)────────── - case "rules": - case "rule": - case "scope": { - const rawInputs = [ - ...positional.slice(1), - stringOption(parsed.options, ["scope", "s", "index", "i", "indexes"]), - ].filter(Boolean) as string[]; + // ── 3. 单据字段转译器(支持 --run ,支持查主单据或跨单据)──────── + case "translate": + case "doc": + case "markdown": + case "render": { + const runHandle = stringOption(parsed.options, ["run", "r"]); + const specifiedSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]); + let runRecord: ApprovalRunRecord | null = null; + if (runHandle) { + runRecord = repo.getRunByHandle(runHandle); + if (!runRecord) { + throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`); + } + } else if (specifiedSn) { + // 如果未显式传 --run,但参数本身是 6 位 shortId + const maybeRun = repo.getRunByHandle(specifiedSn); + if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === specifiedSn.toUpperCase()) { + runRecord = maybeRun; + } + } + + // 确定要查的目标单号:若用户显式指定了单号(且不是 shortId)则查该单号;否则查会话主单据 + let targetSn: string | undefined; + let isSessionPrimary = false; + + if (runRecord) { + if (specifiedSn && specifiedSn !== runRecord.shortId) { + targetSn = specifiedSn; + } else { + targetSn = runRecord.documentSn; + isSessionPrimary = true; + } + } else { + targetSn = specifiedSn; + } + + if (!targetSn) { + throw new Error("请提供会话 ID 或单号: hose-aipro translate [单号] --run "); + } + + // 若查询的是当前会话的主单据且已缓存有快照,直接毫秒级返回 + if (isSessionPrimary && runRecord?.documentSnapshot) { + repo.logAiProAction({ + action: "translate", + runId: runRecord.shortId || runRecord.id, + documentSn: runRecord.documentSn, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + summary: `在会话 [${runRecord.shortId}] 读取主单据快照 [${runRecord.documentSn}]`, + }); + return { + stdout: runRecord.documentSnapshot.endsWith("\n") ? runRecord.documentSnapshot : runRecord.documentSnapshot + "\n", + stderr: "", + exitCode: 0, + }; + } + + // 查询其它关联单据或重新拉取 + const context = await getClient(); + const raw = await getRawBillFlow(context.client, context.corpId, targetSn); + if (!raw) { + throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`); + } + const markdown = translateBillFlowToMarkdown(raw); + + repo.logAiProAction({ + action: "translate", + runId: runRecord?.shortId || runRecord?.id, + documentSn: targetSn, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + summary: runRecord + ? `在会话 [${runRecord.shortId}] 查阅关联单据 [${targetSn}] 转译文本` + : `查阅单据 [${targetSn}] 转译文本`, + }); + + return { + stdout: markdown.endsWith("\n") ? markdown : markdown + "\n", + stderr: "", + exitCode: 0, + }; + } + + // ── 4. 查询命中索引关联的所有规则(方案二:全显式具名参数)──────────── + case "rules": + case "rule": { + const runHandle = stringOption(parsed.options, ["run", "r"]); + const rawIndexes = + stringOption(parsed.options, ["indexes", "index", "i", "scope", "s"]) || + positional[1] || + positional[2]; + + let runRecord: ApprovalRunRecord | null = null; + // 若传入了 --run,进行会话校验 + if (runHandle) { + runRecord = repo.getRunByHandle(runHandle); + if (!runRecord) { + throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`); + } + } + + const rawInputs = [rawIndexes].filter(Boolean) as string[]; const targetIndexes: number[] = []; for (const raw of rawInputs) { const trimmed = raw.trim(); @@ -102,7 +272,6 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; continue; } } catch { - // 兼容非严格 JSON 数组,如 [1, 2] const inner = trimmed.slice(1, -1); const parts = inner.split(/[,,\s]+/).filter(Boolean); for (const p of parts) { @@ -123,7 +292,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; if (uniqueIndexes.length === 0) { return { stdout: "", - stderr: `请提供包裹好的索引数组,例如:\n hose-aipro rules "[2]"\n hose-aipro rules "[1, 2]"\n`, + stderr: `请提供具名参数,例如:\n hose-aipro rules --run --indexes "[1]"\n hose-aipro rules --run --indexes "[1, 2]"\n`, exitCode: 1, }; } @@ -155,9 +324,21 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }; } - // 按照 code 顺序平铺规则 + // 按照 code 顺序平铺规则 (形态 1) const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.code - b.code); + repo.logAiProAction({ + action: "rules", + runId: runRecord?.shortId || runRecord?.id, + documentSn: runRecord?.documentSn, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + summary: runRecord + ? `在会话 [${runRecord.shortId}] 查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)` + : `查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`, + }); + return { stdout: JSON.stringify(flattenedRules, null, 2) + "\n", stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: [${notFound.join(", ")}]\n` : "", @@ -165,28 +346,6 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }; } - // ── 3. 单据字段转译器(转译为标准 LLM / 审核视图 Markdown)───────────── - case "translate": - case "doc": - case "markdown": - case "render": { - const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]); - if (!billSn) { - throw new Error("请提供要转译的单号: hose-aipro translate <单号>"); - } - const context = await getClient(); - const raw = await getRawBillFlow(context.client, context.corpId, billSn); - if (!raw) { - throw new Error(`在当前企业下未找到单号或 ID 为 [${billSn}] 的单据`); - } - const markdown = translateBillFlowToMarkdown(raw); - return { - stdout: markdown.endsWith("\n") ? markdown : markdown + "\n", - stderr: "", - exitCode: 0, - }; - } - // ── 4. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── case "points": case "clauses": { @@ -583,8 +742,30 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; case "log": case "history": case "trail": { + const runHandle = stringOption(parsed.options, ["run", "r"]); const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50; - const logs = repo.listAiProLogs(targetSn || undefined, limit); + + let runRecord: ApprovalRunRecord | null = null; + if (runHandle) { + runRecord = repo.getRunByHandle(runHandle); + } else if (targetSn) { + const maybeRun = repo.getRunByHandle(targetSn); + if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === targetSn.toUpperCase()) { + runRecord = maybeRun; + } + } + + const filter: { runId?: string; documentSn?: string } = {}; + if (runRecord) { + filter.runId = runRecord.shortId || runRecord.id; + } else if (runHandle) { + filter.runId = runHandle; + } + if (targetSn && targetSn !== runRecord?.shortId) { + filter.documentSn = targetSn; + } + + const logs = repo.listAiProLogs(filter, limit); if (runtime.jsonMode) { return { @@ -595,17 +776,19 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; } if (logs.length === 0) { + const targetDesc = filter.runId ? ` (会话: ${filter.runId})` : filter.documentSn ? ` (单号: ${filter.documentSn})` : ""; return { - stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetSn ? ` (单号: ${targetSn})` : ""}。\n`, + stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetDesc}。\n`, stderr: "", exitCode: 0, }; } - const headers = ["#", "发生时间", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"]; + const headers = ["#", "发生时间", "会话 ID", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"]; const rows = logs.map((l, i) => [ i + 1, new Date(l.createdAt).toLocaleString("zh-CN"), + l.runId || "-", l.action, l.documentSn || "-", l.operator || "-", diff --git a/src/domains/approval/approval.test.ts b/src/domains/approval/approval.test.ts index ccb70cc..0559da3 100644 --- a/src/domains/approval/approval.test.ts +++ b/src/domains/approval/approval.test.ts @@ -296,4 +296,64 @@ describe("Approval Domain - SQLite 持久化与规约仓储", () => { expect(repo.getAuditChecklist("EXEC-FAIL", "corp-a").run?.decision).toBe("ERROR"); }); + + test("审批会话 6 位 shortId 生成、6 小时 TTL 与会话级日志挂载", () => { + // 1. 同一单号多次审批,生成完全独立的运行实例 + const run1 = repo.createApprovalRun({ + documentSn: "MULTI-RUN-001", + corpId: "corp-test", + documentSnapshot: "# 单据初审快照", + }); + const run2 = repo.createApprovalRun({ + documentSn: "MULTI-RUN-001", + corpId: "corp-test", + documentSnapshot: "# 单据复审快照", + }); + + expect(run1.id).not.toBe(run2.id); + expect(run1.shortId).toHaveLength(6); + expect(run2.shortId).toHaveLength(6); + expect(run1.shortId).not.toBe(run2.shortId); + expect(run1.expiresAt).toBeGreaterThan(Date.now()); + + // 2. 通过 6 位短 ID 检索会话 + const found1 = repo.getRunByHandle(run1.shortId!); + expect(found1?.id).toBe(run1.id); + expect(found1?.documentSnapshot).toBe("# 单据初审快照"); + + // 3. 过期检测拦截 + const expiredRun = repo.createApprovalRun({ + documentSn: "EXPIRED-001", + expiresAt: Date.now() - 1000, // 过去的时间 + }); + expect(() => repo.getRunByHandle(expiredRun.shortId!)).toThrow("已过期"); + + // 4. 会话级日志挂载与检索 + repo.logAiProAction({ + action: "init", + runId: run1.shortId, + documentSn: "MULTI-RUN-001", + summary: "初始化审批会话", + }); + repo.logAiProAction({ + action: "translate", + runId: run1.shortId, + documentSn: "MULTI-RUN-001", + summary: "读取快照", + }); + repo.logAiProAction({ + action: "init", + runId: run2.shortId, + documentSn: "MULTI-RUN-001", + summary: "第二次初始化审批会话", + }); + + const run1Logs = repo.listAiProLogs({ runId: run1.shortId! }); + expect(run1Logs.length).toBe(2); + expect(run1Logs.map((l) => l.action).sort()).toEqual(["init", "translate"].sort()); + + const run2Logs = repo.listAiProLogs({ runId: run2.shortId! }); + expect(run2Logs.length).toBe(1); + expect(run2Logs[0]!.summary).toBe("第二次初始化审批会话"); + }); }); diff --git a/src/domains/approval/db.ts b/src/domains/approval/db.ts index 16a1822..8c4f45b 100644 --- a/src/domains/approval/db.ts +++ b/src/domains/approval/db.ts @@ -105,6 +105,8 @@ export function initDatabaseSchema(db: Database): void { db.run(` CREATE TABLE IF NOT EXISTS approval_runs ( id TEXT PRIMARY KEY, + short_id TEXT, + expires_at INTEGER, flow_id TEXT, document_sn TEXT NOT NULL, corp_id TEXT, @@ -120,10 +122,15 @@ export function initDatabaseSchema(db: Database): void { `); try { db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); - } catch { - // column already exists - } + } catch {} + try { + db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;"); + } catch {} + try { + db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;"); + } catch {} db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);"); + db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);"); db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);"); // 4. 审批要点事实记录表 @@ -146,6 +153,7 @@ export function initDatabaseSchema(db: Database): void { db.run(` CREATE TABLE IF NOT EXISTS aipro_logs ( id TEXT PRIMARY KEY, + run_id TEXT, action TEXT NOT NULL, document_sn TEXT, operator TEXT, @@ -156,7 +164,11 @@ export function initDatabaseSchema(db: Database): void { created_at INTEGER NOT NULL ); `); + try { + db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;"); + } catch {} db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);"); + db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);"); db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);"); // 种子数据:初始化默认偏好 diff --git a/src/domains/approval/repository.ts b/src/domains/approval/repository.ts index ce51295..c4901be 100644 --- a/src/domains/approval/repository.ts +++ b/src/domains/approval/repository.ts @@ -14,6 +14,15 @@ import { StrictnessTier } from "./types.js"; +export function generateShortRunId(): string { + const chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; + let result = ""; + for (let i = 0; i < 6; i++) { + result += chars.charAt(Math.floor(Math.random() * chars.length)); + } + return result; +} + export interface CreateRuleInput { scope: string; body: string; @@ -287,6 +296,39 @@ export class ApprovalRepository { // ===================== 审批运行与要点清单 (Runs & Findings) ===================== + public createApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord { + const id = crypto.randomUUID(); + const shortId = input.shortId ?? generateShortRunId(); + const now = Date.now(); + const expiresAt = input.expiresAt ?? (now + 6 * 3600 * 1000); // 6 小时有效期 + + this.db.run( + ` + INSERT INTO approval_runs ( + id, short_id, expires_at, flow_id, document_sn, corp_id, scope, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `, + [ + id, + shortId, + expiresAt, + input.flowId ?? null, + input.documentSn.trim(), + input.corpId ?? null, + input.scope ?? null, + input.decision ?? "PENDING", + input.decisionSummary ?? null, + input.matchedRulesCount ?? 0, + input.failedRulesCount ?? 0, + input.documentSnapshot ?? null, + now, + now, + ] + ); + + return this.getRunById(id)!; + } + public createOrResetApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord { const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined); const now = Date.now(); @@ -315,30 +357,28 @@ export class ApprovalRepository { return this.getRunById(existing.id)!; } - const id = crypto.randomUUID(); - this.db.run( - ` - INSERT INTO approval_runs ( - id, flow_id, document_sn, corp_id, scope, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `, - [ - id, - input.flowId ?? null, - input.documentSn.trim(), - input.corpId ?? null, - input.scope ?? null, - input.decision ?? "PENDING", - input.decisionSummary ?? null, - input.matchedRulesCount ?? 0, - input.failedRulesCount ?? 0, - input.documentSnapshot ?? null, - now, - now, - ] - ); + return this.createApprovalRun(input); + } - return this.getRunById(id)!; + public getRunByHandle(handle: string, corpId?: string): ApprovalRunRecord | null { + const trimmed = handle.trim(); + const now = Date.now(); + // 1. 如果符合 6 位大写短 ID 特征 + if (/^[A-Za-z0-9]{6}$/.test(trimmed)) { + const row = this.db + .query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?) AND (expires_at IS NULL OR expires_at > ?)") + .get(trimmed, now) as any; + if (row) return this.mapRunRow(row); + const expiredRow = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any; + if (expiredRow) { + throw new Error(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`); + } + } + // 2. 尝试按长 UUID 查找 + const byId = this.getRunById(trimmed); + if (byId) return byId; + // 3. 尝试按单号查找最新未过期的运行记录 + return this.getLatestRunBySn(trimmed, corpId); } public getLatestRunBySn(documentSn: string, corpId?: string): ApprovalRunRecord | null { @@ -514,6 +554,8 @@ export class ApprovalRepository { private mapRunRow(row: any): ApprovalRunRecord { return { id: row.id, + shortId: row.short_id ?? null, + expiresAt: row.expires_at ? Number(row.expires_at) : null, flowId: row.flow_id, documentSn: row.document_sn, corpId: row.corp_id, @@ -553,19 +595,20 @@ export class ApprovalRepository { public logAiProAction(input: CreateAiProLogInput): AiProLogRecord { const id = crypto.randomUUID(); const now = Date.now(); - + const status = input.status ?? "SUCCESS"; this.db.run( ` - INSERT INTO aipro_logs (id, action, document_sn, operator, args, status, decision, summary, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO aipro_logs (id, run_id, action, document_sn, operator, args, status, decision, summary, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `, [ id, + input.runId ?? null, input.action, input.documentSn ?? null, input.operator ?? null, input.args ?? null, - input.status, + status, input.decision ?? null, input.summary ?? null, now, @@ -574,30 +617,45 @@ export class ApprovalRepository { return { id, + runId: input.runId, action: input.action, documentSn: input.documentSn, operator: input.operator, args: input.args, - status: input.status, + status, decision: input.decision, summary: input.summary, createdAt: now, }; } - public listAiProLogs(documentSn?: string, limit = 50): AiProLogRecord[] { + public listAiProLogs(filter?: string | { documentSn?: string; runId?: string }, limit = 50): AiProLogRecord[] { let sql = "SELECT * FROM aipro_logs"; + const conditions: string[] = []; const params: any[] = []; - if (documentSn) { - sql += " WHERE document_sn = ?"; - params.push(documentSn.trim()); + + const f = typeof filter === "string" ? { documentSn: filter } : filter; + + if (f?.runId) { + conditions.push("run_id = ?"); + params.push(f.runId.trim()); } + if (f?.documentSn) { + conditions.push("document_sn = ?"); + params.push(f.documentSn.trim()); + } + + if (conditions.length > 0) { + sql += " WHERE " + conditions.join(" AND "); + } + sql += " ORDER BY created_at DESC LIMIT ?"; params.push(limit); const rows = this.db.query(sql).all(...params) as any[]; return rows.map((r) => ({ id: r.id, + runId: r.run_id ?? null, action: r.action, documentSn: r.document_sn, operator: r.operator, @@ -612,6 +670,8 @@ export class ApprovalRepository { export interface CreateApprovalRunInput { documentSn: string; + shortId?: string | null; + expiresAt?: number | null; flowId?: string | null; corpId?: string | null; scope?: string | null; @@ -633,6 +693,7 @@ export interface CreateFindingInput { export interface CreateAiProLogInput { action: string; + runId?: string | null; documentSn?: string | null; operator?: string | null; args?: string | null; diff --git a/src/domains/approval/types.ts b/src/domains/approval/types.ts index 3976aea..d5c5313 100644 --- a/src/domains/approval/types.ts +++ b/src/domains/approval/types.ts @@ -77,6 +77,8 @@ export type ApprovalDecision = "PENDING" | "APPROVE" | "REJECT" | "PASS_WITH_NOT export interface ApprovalRunRecord { id: string; + shortId?: string | null; + expiresAt?: number | null; flowId?: string | null; documentSn: string; corpId?: string | null; @@ -123,6 +125,7 @@ export class ApprovalGatewayBlockedError extends Error { export interface AiProLogRecord { id: string; + runId?: string | null; action: string; documentSn?: string | null; operator?: string | null; From 7e39d95b365aca186572def19bc624942c747135 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 23:32:25 +0800 Subject: [PATCH 09/11] feat(aipro): translate JSON output field names to Chinese in scopes and rules commands --- src/aipro-cli.ts | 15 ++++++++------- src/domains/approval/repository.ts | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 3f2b0f0..f7be385 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -147,8 +147,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }); const scopes = repo.listScopes().map((s) => ({ - index: s.index, - scope: s.scope, + 索引号: s.index, + 适用场景: s.scope, })); return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 }; } @@ -297,7 +297,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }; } - const rulesMap = new Map(); + const rulesMap = new Map(); const notFound: number[] = []; for (const idx of uniqueIndexes) { @@ -309,8 +309,9 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; for (const r of detail.rules) { if (!rulesMap.has(r.code)) { rulesMap.set(r.code, { - code: r.code, - text: r.body, + 编号: r.code, + 适用场景: detail.scope, + 规则明细: r.body, }); } } @@ -324,8 +325,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }; } - // 按照 code 顺序平铺规则 (形态 1) - const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.code - b.code); + // 按照 编号 顺序平铺规则 + const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.编号 - b.编号); repo.logAiProAction({ action: "rules", diff --git a/src/domains/approval/repository.ts b/src/domains/approval/repository.ts index c4901be..35aae7f 100644 --- a/src/domains/approval/repository.ts +++ b/src/domains/approval/repository.ts @@ -697,7 +697,7 @@ export interface CreateAiProLogInput { documentSn?: string | null; operator?: string | null; args?: string | null; - status: "SUCCESS" | "BLOCKED" | "ERROR"; + status?: "SUCCESS" | "BLOCKED" | "ERROR"; decision?: ApprovalDecision | null; summary?: string | null; } From ca00e9a2cc00a81fa76a0ad5a32fbce6c5cecb2b Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 6 Sep 2026 23:54:36 +0800 Subject: [PATCH 10/11] feat(aipro): implement bind, review, decide with gateway guardrail and <150 chars opinion validation --- src/aipro-cli.test.ts | 115 +++++++++ src/aipro-cli.ts | 360 +++++++++++++++++++++++------ src/domains/approval/repository.ts | 3 + 3 files changed, 412 insertions(+), 66 deletions(-) create mode 100644 src/aipro-cli.test.ts diff --git a/src/aipro-cli.test.ts b/src/aipro-cli.test.ts new file mode 100644 index 0000000..4ea96a4 --- /dev/null +++ b/src/aipro-cli.test.ts @@ -0,0 +1,115 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { runAiProCli } from "./aipro-cli.js"; +import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js"; +import { ApprovalRepository } from "./domains/approval/repository.js"; + +describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => { + beforeEach(() => { + process.env.HOSE_APPROVAL_DB = ":memory:"; + const db = getApprovalDatabase(":memory:"); + const repo = new ApprovalRepository(db); + + // 预置规约规则 + repo.createRule({ + scope: "差旅报销", + body: "差旅报销时,[必须上传真实发票]{硬性},[建议填写详细事由]{建议}。", + }); + repo.createRule({ + scope: "差旅报销", + body: "住宿费标准执行城市限额,[超标住宿必须有前置特批邮件]{硬性}。", + }); + }); + + afterEach(() => { + closeApprovalDatabase(); + delete process.env.HOSE_APPROVAL_DB; + }); + + test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => { + const db = getApprovalDatabase(":memory:"); + const repo = new ApprovalRepository(db); + + // 1. 创建审批会话 + const run = repo.createApprovalRun({ + documentSn: "TEST-SN-999", + corpId: "test-corp", + documentSnapshot: "# 单据测试快照", + }); + const runId = run.shortId!; + expect(runId).toHaveLength(6); + + // 2. bind 挂载规则并拆解为要点清单 + const bindRes = await runAiProCli(["bind", "--run", runId, "--rules", "[1, 2]"]); + expect(bindRes.exitCode).toBe(0); + const bindData = JSON.parse(bindRes.stdout); + expect(bindData.length).toBe(3); + expect(bindData[0]["要点编号"]).toBe(1); + expect(bindData[0]["严格程度"]).toBe("硬性"); + expect(bindData[0]["归属规则"]).toBe(1); + expect(bindData[0]["审核要点"]).toBe("必须上传真实发票"); + expect(bindData[0]["核验状态"]).toBe("待核验"); + + expect(bindData[1]["要点编号"]).toBe(2); + expect(bindData[1]["严格程度"]).toBe("建议"); + expect(bindData[1]["归属规则"]).toBe(1); + + expect(bindData[2]["要点编号"]).toBe(3); + expect(bindData[2]["严格程度"]).toBe("硬性"); + expect(bindData[2]["归属规则"]).toBe(2); + + // 3. 门禁测试:要点处于 PENDING 时,尝试执行 approve 必须被网关阻拦 + const block1 = await runAiProCli(["decide", "approve", "--run", runId, "--opinion", "尝试盲目放行"]); + expect(block1.exitCode).toBe(1); + expect(block1.stderr).toContain("待核验"); + + // 4. review 事实打标录入(要点 3 硬性违规,缺少特批邮件) + const reviewRes = await runAiProCli([ + "review", + "--run", + runId, + "--eval", + "1=PASS:已上传增值税普通发票; 2=PASS:已注明详细出差事由; 3=FAIL:住宿费超标500元且无特批邮件", + ]); + expect(reviewRes.exitCode).toBe(0); + const reviewData = JSON.parse(reviewRes.stdout); + expect(reviewData["要点总数"]).toBe(3); + expect(reviewData["已通过"]).toBe(2); + expect(reviewData["未通过"]).toBe(1); + expect(reviewData["待核验"]).toBe(0); + + // 5. 门禁测试:硬性违规未通过时,尝试执行 approve 必须被物理一票否决 + const block2 = await runAiProCli(["decide", "approve", "--run", runId, "--opinion", "强行同意放水"]); + expect(block2.exitCode).toBe(1); + expect(block2.stderr).toContain("硬性违规条款未通过"); + + // 6. 门禁测试:审批意见超过 150 字符时,必须被参数校验阻断 + const over150Text = "测试超长文字。".repeat(30); + const block3 = await runAiProCli(["decide", "reject", "--run", runId, "--opinion", over150Text]); + expect(block3.exitCode).toBe(1); + expect(block3.stderr).toContain("不可超过 150 字符"); + + // 7. 正确决策:执行 reject 驳回,提供小于 150 字的专业意见(Dry-run) + const rejectRes = await runAiProCli([ + "decide", + "reject", + "--run", + runId, + "--opinion", + "住宿费超标500元且未见前置特批邮件,不符合差旅规约第2条,予以驳回,请补充特批后重提。", + ]); + expect(rejectRes.exitCode).toBe(0); + const rejectData = JSON.parse(rejectRes.stdout); + expect(rejectData["会话ID"]).toBe(runId); + expect(rejectData["执行动作"]).toBe("驳回"); + expect(rejectData["网关状态"]).toBe("放行"); + + // 8. 审计监控流水验证:会话账本包含全链路记录 + const logsRes = await runAiProCli(["logs", "--run", runId, "--json"]); + expect(logsRes.exitCode).toBe(0); + const logsData = JSON.parse(logsRes.stdout); + const actions = logsData.logs.map((l: any) => l.action); + expect(actions).toContain("bind"); + expect(actions).toContain("review"); + expect(actions).toContain("decide"); + }); +}); diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index f7be385..695d556 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -9,8 +9,12 @@ import { ApprovalGatewayBlockedError, FindingCheckStatus, ApprovalRunRecord, + CreateFindingInput, + RuleRecord, + parseRuleBody, } from "./domains/approval/index.js"; import { getRawBillFlow } from "./domains/bill/api.js"; +import { approveBill, rejectBill } from "./domains/bill/tools.js"; import { translateBillFlowToMarkdown } from "./domains/bill/translator.js"; import { VERSION } from "./version.js"; @@ -347,6 +351,118 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; }; } + // ── 5. 挂载规则并拆解为待核验要点清单 (Bind Checklist) ───────────────── + case "bind": + case "mount": { + const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1]; + if (!runHandle) { + throw new Error("请提供会话 ID: hose-aipro bind --run --rules '[1, 2]'"); + } + const runRecord = repo.getRunByHandle(runHandle); + if (!runRecord) { + throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`); + } + + const rawRules = stringOption(parsed.options, ["rules", "rule", "codes", "c"]); + const rawIndexes = stringOption(parsed.options, ["indexes", "index", "i", "scopes", "scope", "s"]); + const fallbackRaw = positional.slice(1).find((p) => p !== runHandle && p.startsWith("[") && p.endsWith("]")); + + const parseIntegers = (input?: string): number[] => { + if (!input) return []; + const trimmed = input.trim(); + const list: number[] = []; + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + try { + const parsedJson = JSON.parse(trimmed); + if (Array.isArray(parsedJson)) { + for (const item of parsedJson) { + const n = Number(item); + if (!isNaN(n)) list.push(n); + } + return list; + } + } catch {} + } + const inner = trimmed.replace(/[\[\]]/g, ""); + const parts = inner.split(/[,,\s]+/).filter(Boolean); + for (const p of parts) { + const n = Number(p.replace(/['"]/g, "")); + if (!isNaN(n)) list.push(n); + } + return list; + }; + + const ruleCodes = parseIntegers(rawRules || fallbackRaw); + const indexNums = parseIntegers(rawIndexes); + + if (ruleCodes.length === 0 && indexNums.length === 0) { + throw new Error("请指定要挂载的规则或场景索引,例如: hose-aipro bind --run --rules '[1, 2]'"); + } + + const targetRulesMap = new Map(); + for (const code of ruleCodes) { + const r = repo.getRuleByCode(code); + if (r && r.status === "active") { + targetRulesMap.set(r.code, r); + } + } + for (const idx of indexNums) { + const detail = repo.getScopeDetail(idx); + if (detail) { + for (const r of detail.rules) { + if (r.status === "active") { + targetRulesMap.set(r.code, r); + } + } + } + } + + if (targetRulesMap.size === 0) { + throw new Error("未找到任何有效规则,请先运行 hose-aipro scopes 和 hose-aipro rules 查看规约"); + } + + const sortedRules = Array.from(targetRulesMap.values()).sort((a, b) => a.code - b.code); + const findingsToInject: CreateFindingInput[] = []; + + for (const r of sortedRules) { + const parsedRule = parseRuleBody(r.body); + for (const clause of parsedRule.clauses) { + findingsToInject.push({ + ruleId: r.id, + clauseText: clause.action, + strictness: clause.strictness, + checkStatus: "PENDING", + }); + } + } + + const injected = repo.injectFindings(runRecord.id, findingsToInject); + + repo.logAiProAction({ + action: "bind", + runId: runRecord.shortId || runRecord.id, + documentSn: runRecord.documentSn, + operator, + args: JSON.stringify(rawArgs), + status: "SUCCESS", + summary: `在会话 [${runRecord.shortId}] 挂载 ${injected.length} 条审核要点清单(涵盖规则: ${sortedRules.map((r) => `#${r.code}`).join(", ")})`, + }); + + const output = injected.map((f, i) => ({ + 要点编号: i + 1, + 严格程度: f.strictness, + 归属规则: f.ruleCode ?? "-", + 审核要点: f.clauseText, + 核验状态: "待核验", + })); + + return { + stdout: JSON.stringify(output, null, 2) + "\n", + stderr: "", + exitCode: 0, + }; + } + // ── 4. 查看审核要点清单(纯规则元数据,与具体单据无关)──────────────── case "points": case "clauses": { @@ -597,37 +713,56 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; return { stdout: title + table, stderr: "", exitCode: 0 }; } - // ── 3. 事实核验打标录入 ─────────────────────────────────────────────── + // ── 6. 事实核验打标录入 (Review / Fact Check) ───────────────────────── case "review": case "eval": case "evaluate": { - if (!targetSn) { - throw new Error("请提供单号: hose-aipro review <单号> --eval '...'"); + const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1]; + if (!runHandle) { + throw new Error("请提供会话 ID: hose-aipro review --run --eval '...'"); + } + const runRecord = repo.getRunByHandle(runHandle); + if (!runRecord) { + throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`); + } + + const findings = repo.getFindingsByRunId(runRecord.id); + if (findings.length === 0) { + throw new Error( + `会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何审核要点清单,请先执行 hose-aipro bind --run ${runRecord.shortId || runRecord.id} --rules '...'` + ); } const evalStr = stringOption(parsed.options, ["eval", "findings", "e"]); const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0); const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined; const evidence = stringOption(parsed.options, ["evidence", "proof"]); - const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]); + const reasoning = stringOption(parsed.options, ["reasoning", "reason"]); + + const normalizeStatus = (raw: string): FindingCheckStatus => { + const upper = raw.trim().toUpperCase(); + if (["PASS", "通过", "合规", "OK", "YES"].includes(upper)) return "PASS"; + if (["FAIL", "未通过", "不通过", "违规", "NO"].includes(upper)) return "FAIL"; + if (["SKIP", "跳过", "不适用", "NA", "N/A"].includes(upper)) return "SKIP"; + return "PENDING"; + }; const updates: Array<{ - index?: number; - id?: string; + index: number; status: FindingCheckStatus; evidence?: string; reasoning?: string; }> = []; if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) { - updates.push({ index: pointIndex, status: statusInput, evidence, reasoning }); + updates.push({ index: pointIndex, status: normalizeStatus(statusInput), evidence, reasoning }); } else if (evalStr) { - const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean); + const segments = evalStr.split(/[;\n]+/).map((s) => s.trim()).filter(Boolean); for (const seg of segments) { - const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i); + const match = seg.match(/^(\d+)\s*=\s*([A-Za-z\u4e00-\u9fa5]+)(?::(.*))?$/); if (match) { const idx = parseInt(match[1], 10); - const status = match[2].toUpperCase() as FindingCheckStatus; + const status = normalizeStatus(match[2]); const desc = match[3]?.trim(); updates.push({ index: idx, status, evidence: desc, reasoning: desc }); } @@ -637,53 +772,142 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; if (updates.length === 0) { throw new Error( `请提供核验判定参数,例如:\n` + - ` hose-aipro review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` + - ` 或: hose-aipro review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"` + ` hose-aipro review --run ${runRecord.shortId || runRecord.id} --eval "1=PASS:已上传发票; 2=FAIL:住宿超标; 3=SKIP"\n` ); } - const activeCorpId = requireCorpId(); - const updatedFindings = service.evaluateAuditPoints(targetSn, updates, activeCorpId); + for (const item of updates) { + const target = findings[item.index - 1]; + if (!target) { + throw new Error(`要点编号超出范围: #${item.index} (当前要点总数: ${findings.length})`); + } + repo.updateFinding(target.id, { + checkStatus: item.status, + evidence: item.evidence, + reasoning: item.reasoning, + }); + } + + const updatedFindings = repo.getFindingsByRunId(runRecord.id); + const passCount = updatedFindings.filter((f) => f.checkStatus === "PASS").length; + const failCount = updatedFindings.filter((f) => f.checkStatus === "FAIL").length; + const skipCount = updatedFindings.filter((f) => f.checkStatus === "SKIP").length; const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length; repo.logAiProAction({ action: "review", - documentSn: targetSn, + runId: runRecord.shortId || runRecord.id, + documentSn: runRecord.documentSn, operator, args: JSON.stringify(rawArgs), status: "SUCCESS", - summary: `已录入 ${updates.length} 处要点核验事实(待核验剩余: ${pendingCount} 项)`, + summary: `在会话 [${runRecord.shortId || runRecord.id}] 录入 ${updates.length} 项要点核验(通过: ${passCount}, 违规: ${failCount}, 待核验: ${pendingCount})`, }); - const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"]; - const rows = updatedFindings.map((f, i) => [ - i + 1, - `[${f.strictness}]`, - f.clauseText, - f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING", - [f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-", - ]); + const checklistOutput = updatedFindings.map((f, i) => ({ + 要点编号: i + 1, + 严格程度: f.strictness, + 归属规则: f.ruleCode ?? "-", + 审核要点: f.clauseText, + 核验状态: f.checkStatus === "PASS" ? "通过" : f.checkStatus === "FAIL" ? "未通过" : f.checkStatus === "SKIP" ? "已跳过" : "待核验", + 事实依据: Array.from(new Set([f.evidence, f.reasoning].filter(Boolean))).join(" - ") || "-", + })); - const table = printTable(headers, rows); - const msg = - `====== [AI PRO] 单据 ${targetSn} 事实核验已登记入库 (待核验剩余: ${pendingCount} 项) ======\n` + - table + - (pendingCount === 0 - ? `\n🎉 [事实全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-aipro decide ${targetSn} --apply --yes\n` - : `\n⏳ [待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`); + const resultObj = { + 会话ID: runRecord.shortId || runRecord.id, + 单号: runRecord.documentSn, + 要点总数: updatedFindings.length, + 已通过: passCount, + 未通过: failCount, + 已跳过: skipCount, + 待核验: pendingCount, + 核验清单: checklistOutput, + }; - return { stdout: msg, stderr: "", exitCode: 0 }; + return { + stdout: JSON.stringify(resultObj, null, 2) + "\n", + stderr: "", + exitCode: 0, + }; } - // ── 4. 确定性网关仲裁决断与执行 ─────────────────────────────────────── + // ── 7. 决断动作与网关安全阻拦 (Decide with Gateway Interception) ────── case "decide": case "approve": case "reject": { - if (!targetSn) { - throw new Error("请提供单号: hose-aipro decide <单号> [--apply] [--yes]"); + const runHandle = + stringOption(parsed.options, ["run", "r"]) || + positional.slice(1).find((p) => !["approve", "reject", "pass", "同意", "通过", "驳回", "拒绝"].includes(p.toLowerCase())); + if (!runHandle) { + throw new Error("请提供会话 ID: hose-aipro decide --run --opinion '...'"); + } + const runRecord = repo.getRunByHandle(runHandle); + if (!runRecord) { + throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`); } + let actionRaw: string | undefined = positional[1]?.toLowerCase(); + if (actionRaw === runHandle?.toLowerCase()) { + actionRaw = positional[2]?.toLowerCase(); + } + if (!actionRaw || actionRaw.startsWith("-")) { + actionRaw = stringOption(parsed.options, ["action", "a"])?.toLowerCase(); + } + if (command === "approve") { + actionRaw = "approve"; + } else if (command === "reject") { + actionRaw = "reject"; + } + + let action: "APPROVE" | "REJECT" | undefined; + if (["approve", "pass", "同意", "通过"].includes(actionRaw || "")) { + action = "APPROVE"; + } else if (["reject", "refuse", "驳回", "拒绝"].includes(actionRaw || "")) { + action = "REJECT"; + } + + if (!action) { + throw new Error("请指定要执行的审批动作: hose-aipro decide approve 或 hose-aipro decide reject"); + } + + const opinion = ( + stringOption(parsed.options, ["opinion", "comment", "message", "m", "审批意见", "意见"]) || "" + ).trim(); + + if (!opinion) { + throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'"); + } + + if (opinion.length > 150) { + throw new Error(`[参数校验阻断] 审批意见不可超过 150 字符,当前长度为 ${opinion.length} 字符,请精简。`); + } + + const findings = repo.getFindingsByRunId(runRecord.id); + if (findings.length === 0) { + throw new Error(`[网关安全阻断] 会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何规约审核要点,审批链路物理不通!请先执行 bind 挂载。`); + } + + // 网关刚性阻拦检查(它只阻拦,不决断) + if (action === "APPROVE") { + // 门禁 1: 漏检拦截 + const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING"); + if (pendingFindings.length > 0) { + const pendingIndices = pendingFindings.map((f) => `#${findings.indexOf(f) + 1}`).join(", "); + throw new Error(`[网关安全阻断] 尚有 ${pendingFindings.length} 处审核要点处于“待核验”状态(要点 ${pendingIndices}),禁止盲目放行同意!`); + } + + // 门禁 2: 硬性一票否决 + const hardFailed = findings.filter((f) => f.checkStatus === "FAIL" && f.strictness === "硬性"); + if (hardFailed.length > 0) { + const failedNames = hardFailed.map((f) => `【#${findings.indexOf(f) + 1} ${f.clauseText}】`).join("、"); + throw new Error(`[网关安全阻断] 单据存在硬性违规条款未通过(${failedNames}),物理切断“同意”流转,绝对禁止放行!`); + } + } + + // Apply execution const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]); + let executionStatus = "模拟完成(未带 --apply,未真实修改线上单据)"; + if (apply) { const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]); if (!confirmed) { @@ -691,51 +915,55 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。"); } const { prompt } = await import("./cli/helpers.js"); - const ans = await prompt("[AI PRO] 即将向合思系统真实执行审批流转/意见留痕,确认执行?输入 yes: "); + const ans = await prompt(`[AI PRO] 即将向合思系统真实执行审批流转 [${action === "APPROVE" ? "同意" : "驳回"}],确认执行?输入 yes: `); if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作"); } + + const context = await getClient(); + if (action === "APPROVE") { + await approveBill(context.client, context.corpId, runRecord.documentSn, { + comment: opinion, + }); + } else { + await rejectBill(context.client, context.corpId, runRecord.documentSn, { + comment: opinion, + }); + } + executionStatus = "已真实下发合思系统流转"; } - const requestedAction = command === "approve" ? "approve" : command === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any); - const userComment = stringOption(parsed.options, ["comment", "message", "m"]); - - const context = await getClient(); - const decisionResult = await service.decideAudit(context.client, context.corpId, targetSn, { - requestedAction, - apply, - comment: userComment, + // Update run in database + repo.updateApprovalRun(runRecord.id, { + decision: action, + decisionSummary: opinion, + failedRulesCount: findings.filter((f) => f.checkStatus === "FAIL").length, }); repo.logAiProAction({ action: "decide", - documentSn: targetSn, + runId: runRecord.shortId || runRecord.id, + documentSn: runRecord.documentSn, operator, args: JSON.stringify(rawArgs), status: "SUCCESS", - decision: decisionResult.decision, - summary: `网关仲裁完成: ${decisionResult.decision} (硬性违规: ${decisionResult.hardFailedCount}, 弹性违规: ${decisionResult.elasticFailedCount})`, + decision: action, + summary: `审批动作 [${action === "APPROVE" ? "同意" : "驳回"}] (${executionStatus})`, }); - if (runtime.jsonMode) { - return { - stdout: printJson(decisionResult), - stderr: "", - exitCode: 0, - }; - } + const resultObj = { + 会话ID: runRecord.shortId || runRecord.id, + 单号: runRecord.documentSn, + 执行动作: action === "APPROVE" ? "同意" : "驳回", + 审批意见: opinion, + 流转状态: executionStatus, + 网关状态: "放行", + }; - const outLines: string[] = []; - outLines.push(`\n====== [AI PRO] 合思确定性网关仲裁决断书 (单号: ${targetSn}) ======`); - outLines.push(`网关决策 : ${decisionResult.decision}`); - outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`); - if (apply) { - outLines.push(`下游动作 : 已安全真实执行 [${decisionResult.appliedAction}] 动作`); - } else { - outLines.push(`执行模式 : 仿真预审 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`); - } - outLines.push(`\n--- 审计意见留痕快照 ---\n${decisionResult.decisionSummary}\n`); - - return { stdout: outLines.join("\n"), stderr: "", exitCode: 0 }; + return { + stdout: JSON.stringify(resultObj, null, 2) + "\n", + stderr: "", + exitCode: 0, + }; } // ── 5. 全流程监控流水查看 (Audit Logs) ──────────────────────────────── diff --git a/src/domains/approval/repository.ts b/src/domains/approval/repository.ts index 35aae7f..150928d 100644 --- a/src/domains/approval/repository.ts +++ b/src/domains/approval/repository.ts @@ -444,6 +444,9 @@ export class ApprovalRepository { throw new Error(`审批运行记录不存在: ${runId}`); } + // 重新挂载时清空旧要点 + this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]); + const now = Date.now(); const insertStmt = this.db.prepare(` INSERT INTO approval_findings ( From 052fa77df6ef31210b2adbdc5b520cb8bdc5768d Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 7 Sep 2026 00:01:41 +0800 Subject: [PATCH 11/11] chore(release): bump version to v0.7.2 --- .zcode-plugin/plugin.json | 2 +- README.md | 2 +- dist/openapi.json | 2 +- openapi/openapi.yaml | 2 +- package.json | 2 +- skills/hose-use/SKILL.md | 8 ++++---- src/version.ts | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.zcode-plugin/plugin.json b/.zcode-plugin/plugin.json index cf1932e..9777313 100644 --- a/.zcode-plugin/plugin.json +++ b/.zcode-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.7.1", + "version": "0.7.2", "description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。", "author": { "name": "yingqing" diff --git a/README.md b/README.md index 38e63c0..65039eb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# hose-use (v0.7.1) +# hose-use (v0.7.2) 合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。 diff --git a/dist/openapi.json b/dist/openapi.json index e07b989..84a7d71 100644 --- a/dist/openapi.json +++ b/dist/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "hose-use API & MCP Tools Specification", - "version": "0.7.1", + "version": "0.7.2", "description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows." }, "servers": [ diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index 8790684..a8cc1be 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: hose-use API & MCP Tools Specification - version: 0.7.1 + version: 0.7.2 description: >- Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows. servers: diff --git a/package.json b/package.json index 9c412b9..52c7775 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.7.1", + "version": "0.7.2", "module": "src/server.ts", "type": "module", "bin": { diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index b6f5ae5..a797aad 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -1,12 +1,12 @@ --- name: hose-use -description: "v0.7.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。" +description: "v0.7.2: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。" metadata: - version: 0.7.1 - short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.1) + version: 0.7.2 + short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.2) --- -# hose-use (v0.7.1) +# hose-use (v0.7.2) 在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。 本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。 diff --git a/src/version.ts b/src/version.ts index 50a7d6d..a972ad6 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.7.1"; +export const VERSION = "0.7.2";