diff --git a/.agents/rules/README.rules.md b/.agents/rules/README.rules.md new file mode 100644 index 0000000..341e1f4 --- /dev/null +++ b/.agents/rules/README.rules.md @@ -0,0 +1,21 @@ +# 项目规则索引(rules) + +本目录保存按主题拆分的 Agent 开发与操作规则。项目总纲以根目录 [AGENTS.md](../../AGENTS.md) 为准;规则发现和技能配置见 [.agents 说明](../README.md)。 + +## 文件与适用场景 + +| 文件 | 何时查阅 | +|---|---| +| [cli-protocol.md](./cli-protocol.md) | 修改 CLI 输出、确认流程和退出码时;区分 JSON stdout 与诊断 stderr | +| [production-safety.md](./production-safety.md) | 操作真实企业前;确认只读/写入范围、预演、凭证脱敏要求 | +| [tenant-and-credential.md](./tenant-and-credential.md) | 多租户身份、协助链接和凭证导入,以及个人单据查询 | +| [testing-and-dev-hygiene.md](./testing-and-dev-hygiene.md) | 编写测试、隔离环境、处理非交互输入与提交验证 | +| [typescript-style.md](./typescript-style.md) | TypeScript、ESM 导入和运行时模型修改 | +| [windows-development.md](./windows-development.md) | 跨平台路径、分支命名、换行及文件名兼容 | + +## 维护边界 + +- 文件中的 `trigger: manual` 表示按需加载;具体客户端如何加载由其规则发现机制决定,不保证所有 Agent 自动应用。 +- 规则描述开发或操作约束,不保存企业凭证、客户数据或一次性任务记录。 +- 修改规则时同步本索引及上级索引,避免同一要求在多个文件中出现互相矛盾的版本。 +- Git/GitHub 的具体执行规范由 [repo-gh Skill](../skills/repo-gh/SKILL.md) 维护;业务功能使用说明由产品 `skills/hose-use/` 维护。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9422b2..c9404da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ jobs: - run: bun run check - run: bun test - run: bun run build:binary - - run: bun run scripts/verify-binary.ts dist/bin/hose-use + - run: bun run scripts/build/verify-binary.ts dist/bin/hose-use - run: bun run build:plugin - - run: bun run scripts/verify-binary.ts dist/mcp/server.js --plugin + - run: bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin - run: bun run package:plugin diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a5be968..cf5a22d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -50,7 +50,7 @@ jobs: - name: Verify release commit and version run: | git fetch --no-tags origin main:refs/remotes/origin/main - bun run scripts/verify-release.ts "$RELEASE_TAG" + bun run scripts/release/verify-release.ts "$RELEASE_TAG" - name: Install dependencies if: ${{ !inputs.mirror_only }} @@ -76,17 +76,17 @@ jobs: if: ${{ !inputs.mirror_only }} run: | mkdir -p dist/bin - node scripts/build-binary.mjs --all --release + node scripts/build/build-binary.mjs --all --release - name: Verify packaged MCP entrypoint if: ${{ !inputs.mirror_only }} - run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64 + run: bun run scripts/build/verify-binary.ts dist/bin/hose-use-linux-x64 - name: Verify plugin bundle runtime if: ${{ !inputs.mirror_only }} run: | bun run build:plugin - bun run scripts/verify-binary.ts dist/mcp/server.js --plugin + bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin - name: Package plugin archive if: ${{ !inputs.mirror_only }} diff --git a/AGENTS.md b/AGENTS.md index 9a054b4..4b37b92 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,8 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h - `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`) - `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表 - 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts` -- `domains/*/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入 +- 自建应用平台统一位于 `domains/platform/`,applications、datalink、workflow 分别拥有自己的模型、传输与服务出口;applications 不反向依赖另外两者,DataLink 不依赖 workflow,跨子模块不得直接调用 api。 +- `domains/**/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入 - `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/` - 所有本地 SQLite 持久化(审批引擎、多级缓存、事件轮询去重、工作流错误指纹)统一收敛至 `core/db/` 并通过版本迁移管理 @@ -65,7 +66,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h 同步更新顺序: -1. `domains/*/api.ts` — 传输层 +1. `domains/**/api.ts` — 传输层 2. `domains/*/tools.ts` / `services.ts` — 业务编排层 3. `cli/commands/*` & `cli/registry.ts` — CLI 命令层 4. 对应目录下的 `README*.md` @@ -77,14 +78,14 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h | 禁止方向 | 说明 | |---|---| -| `(cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts) -> domains/*/api.ts` | 任何入口层不得绕过 `tools.ts`/`services.ts` 直接调用 API 传输层 | +| `(cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts) -> domains/**/api.ts` | 任何入口层不得绕过 `tools.ts`/`services.ts` 直接调用 API 传输层 | | `domains/** -> (cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | 域层必须保持纯 SDK 零 UI/入口绑定 | | `core/** -> (domains/** \| cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | Core 基础设施层严禁向上反向依赖业务域或入口层 | 正确路径: -- `entrypoints -> cli/registry.ts -> cli/commands/* -> domains/*/(tools|services).ts -> domains/*/api.ts -> core/http/*` -- `domains/*/(tools|services).ts -> core/{auth,cache,config,db,errors,http}` +- `entrypoints -> cli/registry.ts -> cli/commands/* -> domains/**/(tools|services).ts -> domains/**/api.ts -> core/http/*` +- `domains/**/(tools|services).ts -> core/{auth,cache,config,db,errors,http}` ## 异常规则 diff --git a/README.md b/README.md index 35bf2d2..06b0dc3 100644 --- a/README.md +++ b/README.md @@ -124,13 +124,13 @@ hose-use mcp # 启动 MCP Server (默认暴露 | 目录 | 用途与保留依据 | |---|---| | `src/` | CLI、SDK、MCP、HTTP 与基础设施源码,分层见下方架构及各层 README。 | -| `scripts/` | 构建、安装、版本同步、开发环境检查与规范生成脚本;入口见 [package.json](./package.json) 的 `scripts`。 | +| `scripts/` | 按构建、发布、规范生成、开发维护和仓库检查分组,见 [脚本说明](./scripts/README.scripts.md);常用入口见 [package.json](./package.json) 的 `scripts`。 | | `skills/hose-use/` | 随产品分发的 [操作技能源码](./skills/hose-use/SKILL.md),由 `src/packaging/` 内嵌并安装到 `~/.agents/skills/hose-use`。 | -| `.agents/` | 本仓库的开发规则与技能发现配置,见 [.agents/README.md](./.agents/README.md);与产品分发用的 `skills/` 职责不同。 | +| `.agents/` | 本仓库的开发规则与技能发现配置,见 [.agents/README.md](.agents/README.md);与产品分发用的 `skills/` 职责不同。 | | `.github/` | CI 与 Release 工作流,负责校验、构建和发布。 | -| `.zcode-plugin/` | 受版本管理的 [IDE 插件清单](./.zcode-plugin/plugin.json),声明 Skill 路径、MCP 配置与用户开关。 | -| `specs/` | specifications(规范)的缩写,存放 API 与工作流规范:`openapi/` 是包装层 YAML 源文件,`openapi.json` 是其打包结果,`openapi.raw.json` 是独立的下游接口规范,`workflow-schema.json` 是从 Zod 导出的工作流结构。[hose-close-api/](./specs/hose-close-api/README.md) 保存从代码整理的合思内部接口清单与 Schema;本地临时抓包不纳入 Git。生成入口见下文。 | -| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [.mcp.json](./.mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 | +| `.zcode-plugin/` | 受版本管理的 [IDE 插件清单](.zcode-plugin/plugin.json),声明 Skill 路径、MCP 配置与用户开关。 | +| `specs/` | specifications(规范)的缩写,存放 API 与工作流规范:`hose-open-api/` 是 hose-use 包装层对外 API 的 YAML 源文件,`openapi.json` 是其打包结果,`openapi.raw.json` 是独立的下游接口规范,`workflow-schema.json` 是从 Zod 导出的工作流结构。[hose-close-api/](./specs/hose-close-api/README.md) 保存从代码整理的合思内部接口清单与 Schema;本地临时抓包不纳入 Git。生成入口见下文。 | +| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [.mcp.json](.mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 | | `docs/` | 跨模块参考与审阅记录;Platform 模块说明和各域 README 提供当前 CLI 与服务导航,架构总纲见 [AGENTS.md](./AGENTS.md);`reviews/` 保留历史审阅及验证证据。 | | `enterprises/` | 仅跟踪配置示例与 [目录说明](./enterprises/README.md)。实际企业配置默认放在 `~/.config/hose-use/enterprises/`,仓库内其他企业 JSON 被忽略。 | | `.git/` 或 `.git` 文件 | Git 元数据;独立工作树中通常是指向共享仓库的文件。 | @@ -141,15 +141,15 @@ hose-use mcp # 启动 MCP Server (默认暴露 根目录文件的职责: - [AGENTS.md](./AGENTS.md) 是项目开发规则总入口;`CLAUDE.md → AGENTS.md` 是兼容软链接,共享同一份内容。 -- [package.json](./package.json)、`bun.lock` 与 [tsconfig.json](./tsconfig.json) 分别管理项目入口和命令、锁定依赖、配置 TypeScript;[.env.example](./.env.example) 是环境变量示例。 -- [.mcp.json](./.mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.gitignore](./.gitignore) 声明本地数据与产物的忽略边界。 +- [package.json](./package.json)、`bun.lock` 与 [tsconfig.json](./tsconfig.json) 分别管理项目入口和命令、锁定依赖、配置 TypeScript;[.env.example](.env.example) 是环境变量示例。 +- [.mcp.json](.mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。 - `ROADMAP.local.md` 等 `*.local.md` 是已忽略的本地笔记,不是构建依赖或正式文档入口;`.DS_Store` 是已忽略的 macOS Finder 元数据,可清理。 规范生成关系与命令: -- `specs/openapi/**/*.yaml` → `specs/openapi.json`:`bun run openapi:bundle`。 -- `scripts/generate-raw-openapi.ts` → `specs/openapi.raw.json`:`bun run openapi:generate-raw`;与包装层规范描述不同接口,不是备份副本。 -- `src/domains/platform/types.ts` → `specs/workflow-schema.json`:`bun run export:workflow-schema`。 +- `specs/hose-open-api/**/*.yaml` → `specs/openapi.json`:`bun run openapi:bundle`。 +- `scripts/generate/generate-raw-openapi.ts` → `specs/openapi.raw.json`:`bun run openapi:generate-raw`;与包装层规范描述不同接口,不是备份副本。 +- `src/domains/platform/workflow/types.ts` → `specs/workflow-schema.json`:`bun run export:workflow-schema`。 两份 OpenAPI JSON 都由 [内嵌分发层](./src/packaging/README.packaging.md) 直接导入并随 Git 提交;修改规范应更新对应源文件并重新生成,避免只改生成结果。 diff --git a/docs/modules/platform.md b/docs/modules/platform.md index c4c8430..3641554 100644 --- a/docs/modules/platform.md +++ b/docs/modules/platform.md @@ -2,20 +2,13 @@ ## 整体架构 -Platform 与 DataLink 是共享 CLI、MCP、HTTP 和脚本集成的业务域。MCP 仅注册 `hose_cli`,入口统一经 `runCli` 分发;业务域不注册协议工具。代码位于: +应用平台统一包含 applications、datalink 和 workflow 子模块,共享 CLI、MCP、HTTP 和脚本集成。MCP 仅注册 `hose_cli`,入口统一经 `runCli` 分发;业务域不注册协议工具。代码位于: ```text src/domains/platform/ -├── types.ts # Zod schema 与类型定义 -├── api.ts # HTTP 传输层(EKB / EASO / Piper 接口封装) -├── services.ts # 业务编排与服务门面 -└── workflow/ # 节点、脚本、分析、草稿状态、监听与告警 - -src/domains/datalink/ -├── types.ts # 应用、业务对象、字段、记录与权限模型 -├── api.ts # DataLink HTTP 接口封装 -├── services.ts # 应用/对象解析与过滤辅助 -└── fields.ts # 读写共用的唯一字段解析 +├── applications/ # 应用元数据、基础/详情模型和目标解析 +├── datalink/ # 对象、字段、记录与台账审计 +└── workflow/ # 工作流模型、传输、编排与执行能力 src/cli/commands/ # 参数解析与展示,经域 services 调用业务 src/server.ts # 单工具 hose_cli -> runCli @@ -66,11 +59,11 @@ MCP 调用方式统一为 `hose_cli` 的 `command` 参数传入下列命令。 | `workflow check` | 扫描错误管道并持久化去重提醒 | EKB + Piper + 本地 | | `workflow toggle/publish` | 切换启停状态 | Piper | -统计、配额、DSL、员工与采样等底层能力由 `src/domains/platform/services.ts` 暴露,不存在同名的独立 MCP 工具。完整命令语义见 [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) 和 [DataLink 说明](../../src/domains/datalink/README.datalink.md)。 +统计、配额、DSL、员工与采样等工作流专属能力由 `src/domains/platform/workflow/services.ts` 暴露,不存在同名的独立 MCP 工具。完整命令语义见 [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) 和 [DataLink 说明](../../src/domains/platform/datalink/README.datalink.md)。 ## 服务层聚合能力 -`src/domains/platform/services.ts` 提供聚合服务函数: +`src/domains/platform/workflow/services.ts` 提供工作流服务出口,跨应用查询通过 applications 服务取得应用: | 函数 | 说明 | |---|---| @@ -83,7 +76,7 @@ MCP 调用方式统一为 `hose_cli` 的 `command` 参数传入下列命令。 ## 工作流 JSON Schema -`src/domains/platform/types.ts` 定义了递归、按节点类型区分的 Zod schema: +`src/domains/platform/workflow/types.ts` 定义了递归、按节点类型区分的 Zod schema: - `WorkflowTaskSchema`:按节点类型区分并递归建模,覆盖 `webhook`、`condition`、`every`、`stop`、`http`、`flow-detail`、`code`、`code-js2`、`ekuaibao-datalink-filter`、`ekuaibao-datalink-create`、`data-convert`、`flow-create-task` 以及兜底 `unknown`。 - 控制节点(`condition` / `every`)支持递归嵌套 `tasks`。 @@ -101,3 +94,12 @@ bun run export:workflow-schema - `Workflow.state = 1` 为启用,`0` 为停用。 - `levelIndex` 表示节点在流程树中的层级坐标,如 `[6, 1, 0]` 表示第 6 个顶级节点下的第 1 个子节点下的第 0 个节点。 - 控制节点(`every` / `condition`)内部有 `tasks` 子列表,需要递归遍历。 + + +## 子模块所有权与维护 + +应用基础/详情模型统一位于 [applications/types.ts](../../src/domains/platform/applications/types.ts),应用服务由 applications 提供;对象、字段、记录由 DataLink 提供;工作流的配置和执行模型由 workflow 提供。CLI 的 platform、datalink、workflow 及工作台 app 命令保留原有入口语义。 + +[Workflow 服务](../../src/domains/platform/workflow/services.ts) 是显式出口,查询、配置、执行、差异、调试及节点目录分别实现;[DataLink 服务](../../src/domains/platform/datalink/services.ts) 将记录操作、表达式和审计分开。内部实现不反向导入聚合出口,避免循环。 + +applications 不依赖 DataLink 或 workflow,DataLink 不依赖 workflow。入口层不得直接访问任意深度的域 API;平台内部跨子模块只能使用模型或业务服务。以上规则以及包含类型导入的循环检查由架构测试执行。 diff --git a/docs/reviews/2026-10-30-platform-subdomains.md b/docs/reviews/2026-10-30-platform-subdomains.md new file mode 100644 index 0000000..d3016d1 --- /dev/null +++ b/docs/reviews/2026-10-30-platform-subdomains.md @@ -0,0 +1,54 @@ +# 2026-10-30 应用平台子模块整理完成报告 + +## 范围与交付 + +以 `3345ce9` 为业务整理基线,按用户确认的三个阶段实施。应用元数据、业务对象数据和工作流统一归入 `src/domains/platform/` 的 applications、datalink、workflow 子模块。没有将工作流提升为顶层域,也没有改变 Core、工作台菜单、应用商店或协助平台的业务归属。 + +阶段 A 提交 `edf300b`,阶段 B 提交 `4e03c9b`;阶段 C 为本报告所在提交。顶层域由 15 个变为 14 个。没有发布版本、修改全局安装或执行真实企业数据操作。 + +## 实际修改及前后行为 + +| 内容 | 修改及原因 | 复查位置 | +|---|---|---| +| 应用所有权 | 两处应用列表和应用模型统一归 applications;启用应用列表共用请求实现,基础和详情投影保持各自语义 | [api.ts](../../src/domains/platform/applications/api.ts)、[types.ts](../../src/domains/platform/applications/types.ts)、[兼容测试](../../src/domains/platform/applications/application-contract.test.ts) | +| 数据能力下沉 | 原顶层 DataLink 归 platform/datalink,应用模型不再由数据子模块定义;记录、表达式和审计分开 | [DataLink 说明](../../src/domains/platform/datalink/README.datalink.md) | +| 工作流完整归位 | 原 platform 根 api/types/services、执行上下文与测试移入 workflow;配置、查询、执行、差异、调试、节点目录分别实现 | [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) | +| 入口迁移 | CLI、probe、SDK 和生成脚本使用新归属路径,保留命令、别名、确认、返回结构和公共 SDK 导出名 | [sdk.ts](../../src/sdk.ts)、[CLI 命令层](../../src/cli/commands/README.commands.md)、[Schema 导出](../../scripts/generate/export-workflow-schema.ts) | +| 分层卡点 | 禁止入口访问任意深度域 API,禁止跨子模块直接访问 API;applications 不反向依赖,DataLink 不依赖 workflow;含类型导入的文件级循环检查 | [架构边界测试](../../src/cli/architecture-boundaries.test.ts) | +| 导航与证据 | 同步总纲、域数量、活跃 README、SDK 示例路径及当前接口清单源码定位;历史报告和证据保留当时内容 | [AGENTS.md](../../AGENTS.md)、[域总览](../../src/domains/README.domains.md)、[模块说明](../modules/platform.md)、[接口清单](../../specs/hose-close-api/endpoints.md) | + +### 关键兼容行为 + +- `listBasicPlatforms` 保留基础视图,剥离未建模字段且缺少 items 时拒绝;`listPlatforms` 保留详情扩展、admin 清洗和空值兼容。没有把两种模型简单互换。 +- 公开 `hose-use/sdk` 导出名称集合与 `3345ce9` 一致,原 `DatalinkPlatformDetail` 名称由 applications 拥有并维持 SDK 同名出口。 +- 原工作流 44 个、DataLink 37 个服务函数的函数体在职责拆分前后逐字节一致;内部依赖改为直接引用所属实现,服务门面只保留显式出口。 +- 工作流的服务门面由原 1094 行变为 81 行;DataLink 由原 1426 行变为 53 行;applications 门面为 24 行。算法分散到有明确职责的文件中,没有只做路径搬迁。 +- 三份生成规范与 `3345ce9` 逐字节一致:`specs/openapi.json`、`specs/openapi.raw.json`、`specs/workflow-schema.json`。 + +## 依赖环处理与方案落实 + +新增文件级检查发现并消除了两条旧环:watch/tracker 经 services 聚合出口绕回自身,现直接依赖 execution;工作流报告类型经 branch/index 回到类型模块,现直接依赖 branch/types。保留返回结构,不删除类型约束,也不通过忽略 type import 使检查通过。 + +DataLink 内部为 predicates/audit 使用 records 的字段读取及归一化辅助,未引入记录模块反向依赖服务门面。原私有根路径不保留转发文件;仓库内调用均迁移,旧私有路径再次出现会由边界测试拦截。 + +实际实施符合三阶段范围。应用查询特征回归确认的兼容差异全部保留,包括旧全量接口收到裸数组时归为空列表的行为;本轮没有借整理修正该既有问题。阶段 B 的新增空白尾行在阶段 C 清理,最终 diff 检查通过。 + +## 实际验证 + +| 阶段 | 全量测试 | 类型与版本检查 | +|---|---|---| +| A:兼容与边界 | 943 通过、0 失败,123 文件、4544 次断言 | 通过 | +| B:归属与调用迁移 | 943 通过、0 失败,123 文件、4544 次断言 | 通过 | +| C:拆分与文件级循环检查 | 943 通过、0 失败,123 文件、4545 次断言 | 通过 | + +- 全量测试使用临时配置、账号/Token、企业目录和 SQLite 路径;未执行真实企业写入。 +- `bun run openapi:all`、`bun run export:workflow-schema` 成功,产物与原始基线一致。 +- 当前平台二进制构建与产物 CLI/MCP 验证成功;MCP bundle 构建、插件验证和归档打包成功。 +- 公共 SDK 示例编译包含在全量回归中;命令、保存版本冲突、部分成功恢复、数据安全编辑/过滤与流式输出等既有回归保持通过。 +- 活跃文档本地链接零断链;README 审计 81 个目录,27 个必需目录全部通过;`git diff --check` 和生成脚本/测试的独立严格类型检查通过;原始验证日志保存在 Git 忽略目录 `.drafts/platform-reorganization-20261030/`。 + +## 限制与需要注意的迁移 + +仅承诺已有公共 SDK 和 CLI 兼容。直接导入旧 `src/domains/datalink/*` 或 platform 根 api/services/types 的个人脚本,需要迁移到新内部路径或公共 SDK。 + +没有在 Windows/Linux 主机执行完整发布矩阵;没有重做认证基础设施、提取独立 SDK 运行时或调整数据库。工作流和对象关联仍在应用平台业务域内,API 命令并未变成通用跨产品工作流引擎。目录规模与函数体一致性是辅助证据,不替代完整的业务回归或所有租户响应变体验收。 diff --git a/docs/reviews/2026-10-30-readme-checker.md b/docs/reviews/2026-10-30-readme-checker.md new file mode 100644 index 0000000..0238c29 --- /dev/null +++ b/docs/reviews/2026-10-30-readme-checker.md @@ -0,0 +1,57 @@ +# 2026-10-30 README 权重校验器 + +## 已确认规则与实际实现 + +在 `01fcebd` 基线上增加仓库级只读校验器。没有配置文件、目录白名单或额外黑名单,也没有自动创建或重命名 README。 + +- 根目录始终检查 `README.md`。 +- 从 Git 索引的已跟踪成员推导所有父目录,包括中间目录;只统计工作区仍存在的成员。未跟踪内容不计数,已跟踪且后来匹配 `.gitignore` 的内容仍计数。 +- 每个直接子目录计 1,每个直接文件计 1,README 文件不计数。后代文件不累计到父目录;父目录未达阈值也会继续检查其子目录。 +- 同目录的唯一同名脚本和唯一 `.test.*` 测试文件合计 1,例如 `foo.ts` 与 `foo.test.ts`、`install.sh` 与 `install.test.ts`;独立测试、资源文件及歧义配对仍各计 1。 +- 权重严格大于 5 时,要求 `README.{目录名}.md`;权重恰好为 5 不要求。只在根目录或达标目录检查精确大小写、普通文件和非空正文。 +- 不跟随符号链接,README 链接不能替代普通文件;Git 子模块作为父目录的一个子目录计数,不进入其他仓库。 + +## 文件与行为 + +| 文件 | 实际修改 | +|---|---| +| [check-readme.ts](../../scripts/checks/check-readme.ts) | 权重计算、唯一配对、全仓 Git 目录审计、人类/JSON 输出与退出码 | +| [check-readme.test.ts](../../scripts/checks/check-readme.test.ts) | 使用临时 Git 仓库验证阈值边界、配对、递归、忽略行为、命名、非空、链接、只读性及 CLI | +| [package.json](../../package.json) | 新增独立入口 `bun run check:readme` | +| [README.scripts.md](../../scripts/README.scripts.md) | 说明完整算法、配对格式、调用参数与使用边界 | + +`bun run check:readme --json` 返回每个目录的权重、文件配对和预期 README;`--threshold=5` 可覆盖权重阈值,`--root=...` 可指定另一个 Git 工作区。默认定位脚本所属仓库,调用者工作目录不影响结果。退出码为 0(合规)、1(文档不合规)、2(参数/Git/读取异常)。 + +当前作为独立审计命令,没有接入 CI 门禁,也没有更改原有 `bun run check` 的类型检查语义。目录原有文档不足时返回 1 是真实审计结果,不自动忽略以使结果通过。 + +## 实际验证与仓库缺口 + +隔离配置和持久化路径执行全量测试:**938 通过、0 失败,122 文件、4489 次断言**;新增 8 项针对性测试。`bun run check`、`bun run check:version`、校验器及其测试的独立严格 TypeScript 检查、`git diff --check` 均通过。日志位于 `.drafts/readme-check-20261030/`。没有执行企业数据操作、安装或发布。 + +实际在本仓库审计 **80 个目录**,其中 **28 个要求 README,11 个通过,17 个缺失**。JSON 原始审计记录保存于 Git 忽略目录 `.drafts/readme-check-20261030/audit.json`。 + +| 目录 | 权重 | 需要补充 | +|---|---:|---| +| `.agents/rules/` | 6 | `README.rules.md` | +| `docs/reviews/` | 8 | `README.reviews.md` | +| `skills/hose-use/references/` | 13 | `README.references.md` | +| `specs/hose-open-api/paths/` | 6 | `README.paths.md` | +| `src/` | 11 | `README.src.md` | +| `src/cli/commands/` | 43 | `README.commands.md` | +| `src/cli/commands/assist-platform/` | 11 | `README.assist-platform.md` | +| `src/cli/commands/bill/` | 13 | `README.bill.md` | +| `src/cli/commands/corps/` | 10 | `README.corps.md` | +| `src/cli/commands/workflow/` | 24 | `README.workflow.md` | +| `src/core/auth/` | 8 | `README.auth.md` | +| `src/core/cache/` | 6 | `README.cache.md` | +| `src/core/http/` | 12 | `README.http.md` | +| `src/domains/platform/workflow/analysis/` | 6 | `README.analysis.md` | +| `src/domains/platform/workflow/nodes/` | 8 | `README.nodes.md` | +| `src/domains/platform/workflow/script/` | 7 | `README.script.md` | +| `src/domains/platform/workflow/watch/` | 8 | `README.watch.md` | + +## 与方案的关系及限制 + +阈值遵循用户最后确认的统一权重规则,替代早期讨论中的“文件数/目录数分别达标”方案;未保留早期的 `readme.config.json`、命名例外表或目录排除清单。 + +本轮只交付校验器和缺口清单,没有批量补写目录文档。新文件需要先进入 Git 索引,才会影响审计范围和权重;一个已纳入检查的目录中,正在编写的 README 可直接从工作区读取。非空检查不等于内容质量审查,文档是否解释清楚职责和调用方式仍需人工复核。 diff --git a/docs/reviews/2026-10-30-scripts-reorganization.md b/docs/reviews/2026-10-30-scripts-reorganization.md new file mode 100644 index 0000000..584f0a1 --- /dev/null +++ b/docs/reviews/2026-10-30-scripts-reorganization.md @@ -0,0 +1,40 @@ +# 2026-10-30 工程脚本目录整理 + +## 范围与结果 + +按用户确认的分组方案,在 `b1e9c7e` 基线上迁移 17 个文件;公开安装入口 `scripts/install.sh` 及安装测试保留原位。没有删除脚本或调整业务逻辑。 + +- `build/`:二进制构建、插件构建与打包、产物验证、插件冒烟测试。 +- `release/`:版本更新、一致性检查、发布校验及发布流程测试。 +- `generate/`:两份 OpenAPI 规范生成和工作流 Schema 导出。 +- `dev/`:开发安装覆盖、环境维护及其测试。 +- `checks/`:SDK 文档示例编译检查。 + +完整文件与命令索引见 [README.scripts.md](../../scripts/README.scripts.md)。 + +## 调整原因与行为差异 + +| 文件或模块 | 实际修改与原因 | +|---|---| +| [package.json](../../package.json) | 命令实现路径指向新子目录,保留原命令名称与参数传递 | +| [CI](../../.github/workflows/ci.yml)、[Release](../../.github/workflows/release.yml) | 更新直接执行的构建及验证脚本路径,检查顺序和发布流程保持原样 | +| [构建脚本](../../scripts/build/)、[开发脚本](../../scripts/dev/)、[发布脚本](../../scripts/release/) | 根据新增目录层级将仓库根目录定位改为上溯两级,更新脚本间调用和测试夹具路径 | +| [工作流 Schema 导出](../../scripts/generate/export-workflow-schema.ts)、[SDK 示例测试](../../scripts/checks/sdk-example.test.ts) | 修正源码导入或仓库定位,保留原有生成和检查逻辑 | +| [根 README](../../README.md)、[打包说明](../../src/packaging/README.packaging.md) | 同步当前路径,并提供脚本目录索引;保留历史审阅日志的原始路径记录 | + +原先直接运行旧内部文件路径的调用者需要改用新路径;常用 `bun run` 命令、公开安装 URL、版本 `0.8.21`、生成文件和构建产物位置保持一致。 + +## 实际验证 + +- 隔离配置、账号、Token、企业目录和 SQLite 路径执行全量测试:**929 通过、0 失败,120 文件、4392 次断言**。 +- `bun run check`、`bun run check:version`、`git diff --check` 通过。 +- `bun run openapi:all` 成功,两份 OpenAPI JSON 与基线逐字节一致。 +- 当前平台二进制构建及 `verify-binary.ts` 冒烟通过;MCP 插件构建、插件冒烟和归档打包通过。 +- 安装、发布与开发维护的既有隔离测试包含在全量测试中;没有执行真实安装、全局覆盖、清理、Tag 创建或发布。 +- 日志位于 Git 忽略目录 `.drafts/scripts-reorganization-20261030/`。 + +## 未解决问题及验证边界 + +`bun run export:workflow-schema` 因 Zod transform 无法转换为 JSON Schema 而失败。取基线提交的原始脚本在当前依赖和源码上执行,得到同一错误,确认是既有问题。失败发生在文件写入前,`specs/workflow-schema.json` 保持不变。 + +相对原计划,工作流 Schema 导出仅完成旧、新脚本失败一致性验证,没有将其记为生成成功;本轮未扩大为 Schema 导出语义修复。后续需明确输入/输出 Schema 的导出契约。未在 Windows 或 Linux 主机运行构建,也未执行跨平台完整发布矩阵。 diff --git a/docs/reviews/2026-10-30-workflow-schema-export-fix.md b/docs/reviews/2026-10-30-workflow-schema-export-fix.md new file mode 100644 index 0000000..5ffe264 --- /dev/null +++ b/docs/reviews/2026-10-30-workflow-schema-export-fix.md @@ -0,0 +1,22 @@ +# 2026-10-30 工作流 Schema 导出修复 + +## 问题与修复 + +`bun run export:workflow-schema` 原先在导出 `WorkflowDetailSchema.alarm` 时失败:Zod 默认导出解析后的输出结构,但 `alarm` 的字符串分支使用 transform 解析 JSON,无法自动推导函数结果。目录整理前后均可复现。 + +[导出脚本](../../scripts/generate/export-workflow-schema.ts) 现为详情建立仅用于导出的视图,以现有 `WorkflowAlarmSchema.nullable().optional()` 声明归一化后的告警类型。仍直接复用任务与工作流 Schema,移除 `as any`,使用 Zod 的类型化导出 API。没有修改业务域 Schema、服务端请求或运行时解析行为。 + +保持原生成文件的输出语义:数字字段已完成强制转换,带默认值的输出字段为必填;`alarm` 输出为告警对象、null 或缺省,输入的 JSON 字符串不是输出类型。未使用全局 `unrepresentable: "any"` 忽略无法表达的约束,新增不可表示类型仍会导致导出失败。 + +## 实际文件变化 + +- [export-workflow-schema.ts](../../scripts/generate/export-workflow-schema.ts):声明上述导出视图,恢复命令执行。 +- [export-workflow-schema.test.ts](../../scripts/generate/export-workflow-schema.test.ts):在临时工作目录真实执行导出两次,验证可重现、与仓库生成文件一致、递归引用可解析、默认值与输出类型契约,以及运行时字符串/对象/null/无效 JSON 的解析行为。 +- [workflow-schema.json](../../specs/workflow-schema.json):重新生成三个独立 Schema。除 `alarm` 补充 null 外,还反映当前代码已有但旧产物未同步的 `inputs`、`$snapshot`、动态延迟节点、字段映射和未知节点保留字段/默认值等结构。 +- [README.scripts.md](../../scripts/README.scripts.md):用已修复后的输出语义说明替换当前故障提示;上一轮整理报告保留当时的历史验证结果。 + +## 验证与边界 + +实际执行导出成功;回归覆盖重复生成内容一致和三个子 Schema 的本地递归引用。隔离配置和持久化路径的全量测试为 **930 通过、0 失败,121 文件、4453 次断言**;`bun run check`、`bun run check:version` 和 `git diff --check` 通过。日志保存在 Git 忽略目录 `.drafts/workflow-schema-export-fix-20261030/`。 + +本次修复限于本地导出工具、测试与生成文件;没有执行企业数据操作,也没有把导出改为原始输入契约。JSON Schema 描述可序列化输出结构,不负责执行 Zod 的数据转换函数。 diff --git a/docs/reviews/README.reviews.md b/docs/reviews/README.reviews.md new file mode 100644 index 0000000..83385a6 --- /dev/null +++ b/docs/reviews/README.reviews.md @@ -0,0 +1,22 @@ +# 审查与整改记录(reviews) + +本目录保存按日期归档的审查结论、整改范围、实际验证和未覆盖事项。它记录当时的状态;当前架构和命令契约应从根目录 [AGENTS.md](../../AGENTS.md) 与各层 README 阅读。 + +## 记录导航 + +| 记录 | 内容 | +|---|---| +| [2026-10-20 全局修复](./2026-10-20-global-fixes.md) | 全局问题的分项修复与整合结果 | +| [2026-10-25 Codex 审查修复](./2026-10-25-codex-review-fixes.md) | GitHub 审查意见、回归及兼容处理 | +| [2026-10-28 本地进度整合](./2026-10-28-local-progress-integration.md) | 旧分支进度筛选、整合范围和验证 | +| [2026-10-29 业务域契约整改](./2026-10-29-domain-contract-fixes.md) | 身份/字段歧义、单据写入、工作流部分保存与认证重放 | +| [2026-10-30 脚本整理](./2026-10-30-scripts-reorganization.md) | 脚本分组、调用路径及构建验证 | +| [2026-10-30 Schema 导出修复](./2026-10-30-workflow-schema-export-fix.md) | 告警字段导出视图与生成文件同步 | +| [2026-10-30 应用平台子模块整理](./2026-10-30-platform-subdomains.md) | 应用、业务对象与工作流的归属、服务拆分和兼容验收 | +| [2026-10-30 README 校验器](./2026-10-30-readme-checker.md) | 权重规则、首次审计与文档缺口 | + +[2026-10-25 证据目录](./2026-10-25-codex-review-evidence) 保留当次日志,日志中的旧路径和历史错误不随目录迁移改写。 + +## 新增记录约定 + +以日期和主题命名;明确基线、实际修改、验证命令及结果、限制与遗留问题。区分本地提交、推送、PR、合并与发布,不将未执行步骤写成成功。租户原始响应、凭证和临时日志应放在受忽略的本地目录,不纳入本目录。后续修复另写记录,保留原报告的历史语境。 diff --git a/package.json b/package.json index fa48196..cb77644 100644 --- a/package.json +++ b/package.json @@ -20,25 +20,26 @@ "aipro": "bun run src/aipro-cli.ts", "probe": "bun run src/cli.ts probe", "check": "tsc --noEmit", + "check:readme": "bun run scripts/checks/check-readme.ts", "typecheck": "tsc --noEmit", "test": "bun test", - "bump": "bun run scripts/bump-version.ts", - "sync:release": "bun run scripts/bump-version.ts", - "check:version": "bun run scripts/check-version-sync.ts", - "openapi:bundle": "bun run scripts/bundle-openapi.ts", - "openapi:generate-raw": "bun run scripts/generate-raw-openapi.ts", - "openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts", - "build:binary": "node scripts/build-binary.mjs", - "build:plugin": "node scripts/build-plugin.mjs", - "package:plugin": "node scripts/package-plugin.mjs", - "dev:override": "bun run scripts/dev-override.ts", - "dev:link": "bun run scripts/dev-override.ts", - "dev:status": "bun run scripts/dev-hygiene.ts status", - "dev:check": "bun run scripts/dev-hygiene.ts check", - "dev:clean": "bun run scripts/dev-hygiene.ts clean", + "bump": "bun run scripts/release/bump-version.ts", + "sync:release": "bun run scripts/release/bump-version.ts", + "check:version": "bun run scripts/release/check-version-sync.ts", + "openapi:bundle": "bun run scripts/generate/bundle-openapi.ts", + "openapi:generate-raw": "bun run scripts/generate/generate-raw-openapi.ts", + "openapi:all": "bun run scripts/generate/generate-raw-openapi.ts && bun run scripts/generate/bundle-openapi.ts", + "build:binary": "node scripts/build/build-binary.mjs", + "build:plugin": "node scripts/build/build-plugin.mjs", + "package:plugin": "node scripts/build/package-plugin.mjs", + "dev:override": "bun run scripts/dev/dev-override.ts", + "dev:link": "bun run scripts/dev/dev-override.ts", + "dev:status": "bun run scripts/dev/dev-hygiene.ts status", + "dev:check": "bun run scripts/dev/dev-hygiene.ts check", + "dev:clean": "bun run scripts/dev/dev-hygiene.ts clean", "dev": "bun run --watch src/server.ts", "start": "bun run src/server.ts", - "export:workflow-schema": "bun run scripts/export-workflow-schema.ts" + "export:workflow-schema": "bun run scripts/generate/export-workflow-schema.ts" }, "dependencies": { "@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0", diff --git a/scripts/README.scripts.md b/scripts/README.scripts.md new file mode 100644 index 0000000..9702c33 --- /dev/null +++ b/scripts/README.scripts.md @@ -0,0 +1,62 @@ +# 工程脚本(scripts) + +本目录维护构建、发布校验、规范生成与本地开发维护脚本。优先从仓库根目录运行 `package.json` 中的命令;迁移子目录不改变这些命令、参数与产物位置。 + +## 目录职责 + +| 位置 | 职责与文件 | +|---|---| +| [build/](./build) | 二进制、MCP bundle、插件归档构建,产物验证及插件冒烟测试 | +| [release/](./release) | 版本更新、一致性检查、发布 Tag 校验及发布流程测试 | +| [generate/](./generate) | 包装层 OpenAPI 打包、原生下游规范生成、工作流 Schema 导出 | +| [dev/](./dev) | 本地开发安装覆盖、环境检查与清理规划,及对应测试 | +| [checks/](./checks) | README 覆盖与命名校验、SDK README 示例编译测试 | +| [install.sh](./install.sh) | 公开安装入口,路径保持稳定;安装测试保留在同级 | + +对应脚本的测试与脚本放在同一个目录,统一由 `bun test` 发现。生成文件写入 `specs/`,构建输出写入 Git 忽略的 `dist/`。 + +## 常用入口与副作用 + +| 命令 | 实现 | 行为 | +|---|---|---| +| `bun run build:binary` | [build-binary.mjs](./build/build-binary.mjs) | 编译当前平台二进制到 `dist/bin/`;支持 `--target=...`、`--all`、`--release` | +| `bun run build:plugin` | [build-plugin.mjs](./build/build-plugin.mjs) | 生成 `dist/mcp/server.js`;支持 `--outfile=...` | +| `bun run package:plugin` | [package-plugin.mjs](./build/package-plugin.mjs) | 从当前源码重建插件并生成 `dist/bin/hose-use-plugin-v*.tar.gz`;支持 `--out-dir=...` | +| `bun run scripts/build/verify-binary.ts <产物>` | [verify-binary.ts](./build/verify-binary.ts) | 在临时目录验证 CLI/MCP;插件产物加 `--plugin` | +| `bun run check:version` | [check-version-sync.ts](./release/check-version-sync.ts) | 只读检查版本一致性 | +| `bun run check:readme` | [check-readme.ts](./checks/check-readme.ts) | 只读检查 Git 跟踪目录的 README;支持 `--json`、`--threshold=5` 和 `--root=...` | +| `bun run bump <版本>` | [bump-version.ts](./release/bump-version.ts) | 要求干净的指定发布分支;修改版本源文件并重建规范与插件;`sync:release` 为同一入口 | +| `bun run scripts/release/verify-release.ts ` | [verify-release.ts](./release/verify-release.ts) | 只读验证发布 Tag、当前提交、主分支祖先关系与版本 | +| `bun run openapi:bundle` | [bundle-openapi.ts](./generate/bundle-openapi.ts) | `specs/hose-open-api/` YAML → `specs/openapi.json` | +| `bun run openapi:generate-raw` | [generate-raw-openapi.ts](./generate/generate-raw-openapi.ts) | 生成 `specs/openapi.raw.json`;`openapi:all` 依次生成两份规范 | +| `bun run export:workflow-schema` | [export-workflow-schema.ts](./generate/export-workflow-schema.ts) | 从 Zod 导出归一化后的工作流结构到 `specs/workflow-schema.json` | +| `bun run dev:status` / `dev:check` | [dev-hygiene.ts](./dev/dev-hygiene.ts) | 检查开发环境、安装与技能同步状态 | +| `bun run dev:clean` | [dev-hygiene.ts](./dev/dev-hygiene.ts) | 默认给出清理计划;执行清理前检查参数与计划 | +| `bun run dev:override` | [dev-override.ts](./dev/dev-override.ts) | 构建并覆盖本机全局命令,同步个人 `~/.agents/skills/hose-use`;`dev:link` 为同一入口 | +| `bash scripts/install.sh` | [install.sh](./install.sh) | 下载并校验发布产物,安装到本机并安装产品技能 | + +发布规则见根目录 [AGENTS.md](../AGENTS.md)。构建、升级版本和安装是不同步骤,发布 Tag 与推送由发布流程单独执行。 + +## 维护与验证 + +- 移动脚本时同步检查 `package.json`、`.github/workflows/`、脚本间调用与文档引用。 +- 子目录内脚本以自身路径定位仓库根目录时,需要上溯两级;规范生成入口沿用从仓库根目录执行的约定。 +- `scripts/install.sh` 被公开安装 URL 引用,不随内部脚本分组迁移。 +- 不在本目录保存业务工作流脚本、客户载荷或临时生成文件;产品 Skill 中的 `./scripts/*.mvel` 等是调用者工作目录示例。 +- 提交前执行 `bun test`、`bun run check`、`bun run check:version`;构建相关调整还需验证二进制和插件的实际产物。 + +## 工作流 Schema 的语义 + +`workflow-schema.json` 的 `schemas` 分别保存 WorkflowDetail、WorkflowTask 和 Workflow 的独立 JSON Schema,描述 Zod 解析完成后的输出,不是服务端原始输入;每份 Schema 的递归引用相对于该份 Schema 解析。带默认值的输出字段保持必填,数字转换后仍为 number。 + +`alarm` 可从 JSON 字符串归一化为告警对象,也可为 null 或缺省。导出视图显式使用同一个 `WorkflowAlarmSchema` 描述对象输出;不会尝试把字符串解析函数转换为 JSON Schema,也不会改动域层的输入兼容和解析行为。新增其他无法表示的转换时仍会报错,避免默默丢失约束。 + +## README 校验规则 + +- 从 Git 索引中的已跟踪文件推导目录;只统计工作区仍存在的成员。不纳入未跟踪文件或空目录,也不自行扫描依赖和本地草稿。新文件需先 `git add` 才会影响目录权重;已跟踪的文件后来匹配 `.gitignore`,仍然计入。 +- 根目录始终要求 `README.md`;其他目录的权重**严格大于 5**时,要求 `README.{当前目录名}.md`。默认阈值为 5,可通过 `--threshold` 覆盖;没有配置文件、目录白名单或额外黑名单。 +- 每个直接子目录计 1,每个直接文件计 1,README 文件不计权重。后代内容不累计到父目录,未达阈值的父目录不会阻止对子目录的检查。 +- 同目录、同名的脚本与唯一的 `名称.test.*` 测试合计 1;例如 `foo.ts` + `foo.test.ts`、`build.mjs` + `build.test.ts`、`install.sh` + `install.test.ts`。支持 TS/JS(含 JSX、TSX、MJS、CJS)、Shell、Python、PowerShell 源文件;测试采用 `.test.ts/js/tsx/jsx/mjs/cjs`。只有唯一源文件和唯一测试能配对,独立测试、资源文件或歧义配对各自计数;不跨目录合并。 +- 只在要求 README 的目录检查命名、精确大小写、普通文件与非空内容;已有 README 不会被自动创建、改名或修改。符号链接按文件计但不跟随,README 符号链接不合规;子模块只作为父目录的一个子目录计数,不进入另一个仓库。 +- 默认定位脚本所属仓库,从其他工作目录调用结果相同;`--root` 可指定其他 Git 工作区(指向其子目录时会定位到该仓库根目录)。JSON 结果包含每个目录的权重、文件配对明细及预期 README,便于复查。 +- 退出码:`0` 全部合规,`1` 存在缺失、错名、空文档或无效文档,`2` 为参数、Git 或读取错误。当前作为独立审计入口,不接入 CI 门禁,也不修改通用类型检查命令。 diff --git a/scripts/build-binary.mjs b/scripts/build/build-binary.mjs similarity index 99% rename from scripts/build-binary.mjs rename to scripts/build/build-binary.mjs index 9042ee6..c669b45 100644 --- a/scripts/build-binary.mjs +++ b/scripts/build/build-binary.mjs @@ -3,7 +3,7 @@ import { spawnSync } from "node:child_process"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const bun = process.env.BUN_BIN || "bun"; const TARGET_MAP = { diff --git a/scripts/build-plugin.mjs b/scripts/build/build-plugin.mjs similarity index 99% rename from scripts/build-plugin.mjs rename to scripts/build/build-plugin.mjs index 79be680..ef9bf97 100644 --- a/scripts/build-plugin.mjs +++ b/scripts/build/build-plugin.mjs @@ -3,7 +3,7 @@ import { spawnSync } from "node:child_process"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const bun = process.env.BUN_BIN || "bun"; const args = process.argv.slice(2); if (args.some(arg => !arg.startsWith("--outfile="))) { diff --git a/scripts/package-plugin.mjs b/scripts/build/package-plugin.mjs similarity index 92% rename from scripts/package-plugin.mjs rename to scripts/build/package-plugin.mjs index f3c2868..e1e7c33 100644 --- a/scripts/package-plugin.mjs +++ b/scripts/build/package-plugin.mjs @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const args = process.argv.slice(2); if (args.some(arg => !arg.startsWith("--out-dir="))) { throw new Error("Usage: package-plugin.mjs [--out-dir=]"); @@ -26,7 +26,7 @@ try { cpSync(join(root, path), join(stage, path), { recursive: true }); } // Always build from current source; never package a stale local dist/ bundle. - run(process.execPath, [join(root, "scripts/build-plugin.mjs"), `--outfile=${join(stage, "dist/mcp/server.js")}`]); + run(process.execPath, [join(root, "scripts/build/build-plugin.mjs"), `--outfile=${join(stage, "dist/mcp/server.js")}`]); mkdirSync(outputDir, { recursive: true }); run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", ".mcp.json", "skills", "dist"]); console.log(`✓ Packaged plugin: ${archive}`); diff --git a/scripts/plugin-review-smoke.test.ts b/scripts/build/plugin-review-smoke.test.ts similarity index 93% rename from scripts/plugin-review-smoke.test.ts rename to scripts/build/plugin-review-smoke.test.ts index 36bd99f..8632a54 100644 --- a/scripts/plugin-review-smoke.test.ts +++ b/scripts/build/plugin-review-smoke.test.ts @@ -4,11 +4,11 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; test("source and freshly packaged plugin preserve offline review and MCP contracts without a prebuilt dist", () => { - const root = resolve(import.meta.dir, ".."); + const root = resolve(import.meta.dir, "../.."); const temp = mkdtempSync(join(tmpdir(), "hose review plugin ")); try { const packaged = Bun.spawnSync([ - process.execPath, join(root, "scripts/package-plugin.mjs"), `--out-dir=${join(temp, "artifacts")}`, + process.execPath, join(root, "scripts/build/package-plugin.mjs"), `--out-dir=${join(temp, "artifacts")}`, ], { cwd: temp, env: { ...process.env, BUN_BIN: process.execPath }, timeout: 30_000 }); expect(packaged.exitCode, packaged.stderr.toString()).toBe(0); const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version; @@ -29,7 +29,7 @@ test("source and freshly packaged plugin preserve offline review and MCP contrac expect(existsSync(join(pluginRoot, "skills", file))).toBe(true); } const protocol = Bun.spawnSync([ - process.execPath, join(root, "scripts/verify-binary.ts"), bundle, "--plugin", + process.execPath, join(root, "scripts/build/verify-binary.ts"), bundle, "--plugin", ], { cwd: temp, timeout: 30_000 }); expect(protocol.exitCode, protocol.stderr.toString()).toBe(0); const enterprises = join(temp, "enterprises"); diff --git a/scripts/verify-binary.ts b/scripts/build/verify-binary.ts similarity index 100% rename from scripts/verify-binary.ts rename to scripts/build/verify-binary.ts diff --git a/scripts/checks/check-readme.test.ts b/scripts/checks/check-readme.test.ts new file mode 100644 index 0000000..1095294 --- /dev/null +++ b/scripts/checks/check-readme.test.ts @@ -0,0 +1,133 @@ +import { afterEach, expect, test } from "bun:test"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { checkReadmes, fileUnits } from "./check-readme.js"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +function fixture(readme = true) { + const root = mkdtempSync(join(tmpdir(), "hose readme 检查 ")); + roots.push(root); + const git = (...args: string[]) => execFileSync("git", ["-C", root, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + git("init", "--quiet"); + const write = (path: string, content = "fixture", tracked = true) => { + const target = join(root, path); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, content); + if (tracked) git("add", "--", path); + }; + if (readme) write("README.md", "# Fixture"); + const files = (dir: string, count: number) => { for (let i = 0; i < count; i++) write(`${dir}/file-${i}.ts`); }; + const cli = (...args: string[]) => spawnSync(process.execPath, [resolve(import.meta.dir, "check-readme.ts"), `--root=${root}`, ...args], { encoding: "utf8" }); + return { root, git, write, files, cli, result: (path: string) => checkReadmes(root).results.find(item => item.directory === path)! }; +} + +test("脚本与唯一同名 .test.* 合并,独立测试和资源文件不误配", () => { + expect(fileUnits(["foo.ts", "foo.test.ts", "install.sh", "install.test.ts", "build.mjs", "build.test.ts"])).toEqual([ + ["build.mjs", "build.test.ts"], ["foo.ts", "foo.test.ts"], ["install.sh", "install.test.ts"], + ]); + expect(fileUnits(["foo.json", "foo.test.ts", "bar.test.ts", "foo.spec.ts"])).toHaveLength(4); + expect(fileUnits(["foo.ts", "foo.js", "foo.test.ts"])).toHaveLength(3); + expect(fileUnits(["README.md", "README.foo.md", "readme.markdown", "README", "foo.ts"])).toEqual([["foo.ts"]]); +}); + +test("根目录不受阈值影响,5 不要求,6 要求;测试对只算 1", () => { + const f = fixture(false); + expect(checkReadmes(f.root).results[0]?.status).toBe("missing"); + f.write("README.md", "# Root"); + f.files("src", 4); + f.write("src/example.ts"); + f.write("src/example.test.ts"); + expect(f.result("src")).toMatchObject({ weight: 5, required: false, status: "not-required" }); + f.write("src/sixth.ts"); + expect(f.result("src")).toMatchObject({ weight: 6, required: true, status: "missing", expectedReadme: "README.src.md" }); + f.write("src/README.src.md", "# Source"); + expect(f.result("src")).toMatchObject({ weight: 6, status: "ok" }); +}); + +test("直接子目录各计 1,不累计后代文件,低权重父目录不阻止向下检查", () => { + const f = fixture(); + f.files("parent/child", 8); + f.write("parent/other/example.ts"); + expect(f.result("parent")).toMatchObject({ weight: 2, directoryWeight: 2, required: false }); + expect(f.result("parent/child")).toMatchObject({ weight: 8, status: "missing" }); + f.files("mixed", 4); + f.write("mixed/child/a.ts"); + f.write("mixed/other/b.ts"); + expect(f.result("mixed")).toMatchObject({ weight: 6, directoryWeight: 2, status: "missing" }); +}); + +test("配对只在同一目录内进行", () => { + const f = fixture(); + f.write("a/foo.ts"); + f.write("b/foo.test.ts"); + expect(f.result("a").fileUnits).toEqual([["foo.ts"]]); + expect(f.result("b").fileUnits).toEqual([["foo.test.ts"]]); +}); + +test("只检查 Git 跟踪成员;未跟踪、嵌套忽略内容不计数,已跟踪的忽略项仍计数", () => { + const f = fixture(); + f.write(".gitignore", "ignored/\n"); + f.write("src/.gitignore", "local/\n"); + f.write("ignored/a.ts", "ignored", false); + f.write("src/local/a.ts", "ignored", false); + f.write("untracked/a.ts", "untracked", false); + f.files("src", 4); + expect(f.result("src").weight).toBe(5); + expect(checkReadmes(f.root).results.map(item => item.directory)).toEqual([".", "src"]); + f.write("ignored/tracked.ts", "tracked", false); + f.git("add", "-f", "--", "ignored/tracked.ts"); + expect(f.result("ignored").weight).toBe(1); +}); + +test("校验真实大小写、错名、空文档和符号链接;检查不写文件", () => { + const f = fixture(); + f.files("src", 6); + f.write("src/README.md", "# Wrong name"); + expect(f.result("src").status).toBe("misnamed"); + rmSync(join(f.root, "src/README.md")); + f.write("src/readme.src.md", "# Wrong case"); + expect(f.result("src").status).toBe("misnamed"); + rmSync(join(f.root, "src/readme.src.md")); + f.write("src/README.src.md", " \n\t "); + expect(f.result("src").status).toBe("empty"); + rmSync(join(f.root, "src/README.src.md")); + symlinkSync(join(f.root, "README.md"), join(f.root, "src/README.src.md")); + expect(f.result("src").status).toBe("invalid-file"); + const before = f.git("status", "--porcelain"); + checkReadmes(f.root); + expect(f.git("status", "--porcelain")).toBe(before); +}); + +test("符号链接目录不展开,工作区中已删除的文件不计权重", () => { + const f = fixture(); + f.files("src", 6); + rmSync(join(f.root, "src/file-0.ts")); + expect(f.result("src").weight).toBe(5); + mkdirSync(join(f.root, "outside")); + writeFileSync(join(f.root, "outside/secret.txt"), "fixture"); + symlinkSync(join(f.root, "outside"), join(f.root, "link")); + f.git("add", "--", "link"); + expect(checkReadmes(f.root).results.map(item => item.directory)).not.toContain("link"); +}); + +test("CLI 支持 JSON、阈值与稳定退出码,非 Git 路径或无效参数返回 2", () => { + const f = fixture(); + expect(f.cli().status).toBe(0); + f.files("src", 6); + const failed = f.cli("--json"); + expect(failed.status).toBe(1); + expect(JSON.parse(failed.stdout)).toMatchObject({ threshold: 5, failed: 1 }); + expect(f.cli("--threshold", "6").status).toBe(0); + expect(f.cli("--threshold=5").status).toBe(1); + for (const arg of ["--threshold=-1", "--threshold=1.5", "--threshold=9007199254740992", "--unknown", "--threshold"]) { + expect(f.cli("--json", arg).status).toBe(2); + } + const dir = mkdtempSync(join(tmpdir(), "hose-non-git-")); roots.push(dir); + const invalid = f.cli("--json", `--root=${dir}`); + expect(invalid.status).toBe(2); + expect(JSON.parse(invalid.stdout).error).toBeString(); + expect(f.cli("--help").status).toBe(0); +}); diff --git a/scripts/checks/check-readme.ts b/scripts/checks/check-readme.ts new file mode 100644 index 0000000..f5a58cf --- /dev/null +++ b/scripts/checks/check-readme.ts @@ -0,0 +1,134 @@ +import { execFileSync } from "node:child_process"; +import { lstatSync, readFileSync, readdirSync } from "node:fs"; +import { posix, resolve } from "node:path"; + +const isReadme = (name: string) => /^readme(?:\..*)?$/i.test(name); +const scriptPattern = /\.(?:[cm]?js|jsx|tsx?|sh|bash|py|ps1)$/; +const testPattern = /^(.*)\.test\.(?:[cm]?js|jsx|tsx?)$/; + +/** 只合并同目录内唯一的同名脚本/测试对,资源文件和独立测试各计 1。 */ +export function fileUnits(names: string[]): string[][] { + const files = [...new Set(names)].filter(name => !isReadme(name)).sort(); + const sources = new Map(); + const tests = new Map(); + for (const name of files) { + const test = name.match(testPattern); + const key = test?.[1] ?? (scriptPattern.test(name) ? name.replace(scriptPattern, "") : undefined); + if (key === undefined) continue; + const target = test ? tests : sources; + target.set(key, [...(target.get(key) ?? []), name]); + } + const paired = new Map(); + for (const [stem, source] of sources) { + const test = tests.get(stem); + if (source.length === 1 && test?.length === 1) paired.set(source[0]!, test[0]!); + } + const consumed = new Set(paired.values()); + return files.filter(name => !consumed.has(name)).map(name => paired.has(name) ? [name, paired.get(name)!] : [name]); +} + +export interface DirectoryResult { + directory: string; + expectedReadme: string; + fileUnits: string[][]; + directoryWeight: number; + weight: number; + required: boolean; + status: "ok" | "not-required" | "missing" | "misnamed" | "empty" | "invalid-file"; + foundReadmes: string[]; +} + +export function checkReadmes(directory: string, threshold = 5) { + if (!Number.isSafeInteger(threshold) || threshold < 0) throw new Error("threshold 必须为非负安全整数"); + const git = (args: string[]) => execFileSync("git", ["-C", resolve(directory), ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + const root = git(["rev-parse", "--show-toplevel"]).trim(); + const tracked = execFileSync("git", ["-C", root, "ls-files", "--cached", "-z"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + const tree = new Map; directories: Set }>(); + const ensure = (path: string) => { + if (!tree.has(path)) tree.set(path, { files: new Set(), directories: new Set() }); + return tree.get(path)!; + }; + ensure("."); + for (const path of new Set(tracked.split("\0").filter(Boolean))) { + let stat; + try { + stat = lstatSync(resolve(root, path)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + throw error; + } + let parent = posix.dirname(path); + // 子模块只计为直接子目录;不进入另一个 Git 仓库。符号链接按文件计,不跟随。 + if (stat.isDirectory()) ensure(parent).directories.add(posix.basename(path)); + else ensure(parent).files.add(posix.basename(path)); + while (parent !== ".") { + const ancestor = posix.dirname(parent); + ensure(ancestor).directories.add(posix.basename(parent)); + parent = ancestor; + } + } + + const results: DirectoryResult[] = [...tree.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, members]) => { + const units = fileUnits([...members.files]); + const weight = units.length + members.directories.size; + const required = path === "." || weight > threshold; + const expectedReadme = path === "." ? "README.md" : `README.${posix.basename(path)}.md`; + const result: DirectoryResult = { directory: path, expectedReadme, fileUnits: units, directoryWeight: members.directories.size, weight, required, status: "not-required", foundReadmes: [] }; + if (!required) return result; + const absolute = resolve(root, path); + // 必须比较目录条目的真实大小写,不能依赖 macOS 的大小写不敏感路径查询。 + result.foundReadmes = readdirSync(absolute).filter(isReadme).sort(); + if (!result.foundReadmes.includes(expectedReadme)) { + result.status = result.foundReadmes.length ? "misnamed" : "missing"; + } else if (!lstatSync(resolve(absolute, expectedReadme)).isFile()) { + result.status = "invalid-file"; + } else { + result.status = readFileSync(resolve(absolute, expectedReadme), "utf8").trim() ? "ok" : "empty"; + } + return result; + }); + const required = results.filter(result => result.required); + return { root, threshold, directories: results.length, required: required.length, failed: required.filter(result => result.status !== "ok").length, results }; +} + +export function main(args: string[]): number { + const json = args.includes("--json"); + try { + let root = resolve(import.meta.dir, "../.."); + let threshold = 5; + for (let i = 0; i < args.length; i++) { + const arg = args[i]!; + if (arg === "--json") continue; + if (arg === "--help" || arg === "-h") { + console.log("用法:bun run check:readme [--threshold=5] [--root=] [--json]\n根目录始终检查;其余目录的直接文件单位 + 直接子目录数 > threshold 时要求 README.{目录名}.md。\n只统计 Git 已跟踪且工作区仍存在的成员;同名脚本与唯一的 .test.* 测试文件合计 1。只读检查。"); + return 0; + } + const match = arg.match(/^--(threshold|root)(?:=(.*))?$/); + if (!match) throw new Error(`未知参数:${arg}`); + const value = match[2] ?? args[++i]; + if (!value || value.startsWith("--")) throw new Error(`参数缺少值:${arg}`); + if (match[1] === "root") root = resolve(value); + else { + if (!/^\d+$/.test(value)) throw new Error("threshold 必须为非负安全整数"); + threshold = Number(value); + } + } + const report = checkReadmes(root, threshold); + if (json) console.log(JSON.stringify(report, null, 2)); + else { + const labels = { missing: "缺失", misnamed: "错名", empty: "空文档", "invalid-file": "不是普通文件", ok: "通过", "not-required": "未达阈值" }; + for (const result of report.results.filter(item => item.required && item.status !== "ok")) { + console.log(`${labels[result.status]} ${result.directory}/ 权重 ${result.weight},预期 ${result.expectedReadme}${result.foundReadmes.length ? `,发现 ${result.foundReadmes.join("、")}` : ""}`); + } + console.log(`检查 ${report.directories} 个目录;要求 README ${report.required} 个,通过 ${report.required - report.failed} 个,失败 ${report.failed} 个;其余 ${report.directories - report.required} 个未达阈值。`); + } + return report.failed ? 1 : 0; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (json) console.log(JSON.stringify({ error: message })); + else console.error(`README 校验失败:${message}`); + return 2; + } +} + +if (import.meta.main) process.exitCode = main(process.argv.slice(2)); diff --git a/scripts/sdk-example.test.ts b/scripts/checks/sdk-example.test.ts similarity index 87% rename from scripts/sdk-example.test.ts rename to scripts/checks/sdk-example.test.ts index c0b407c..0e82e7e 100644 --- a/scripts/sdk-example.test.ts +++ b/scripts/checks/sdk-example.test.ts @@ -4,8 +4,8 @@ import { resolve } from "node:path"; import ts from "typescript"; test("DataLink 公共 SDK 的 README 示例与实际导出一同编译", () => { - const root = resolve(import.meta.dir, ".."); - const readme = readFileSync(resolve(root, "src/domains/datalink/README.datalink.md"), "utf8"); + const root = resolve(import.meta.dir, "../.."); + const readme = readFileSync(resolve(root, "src/domains/platform/datalink/README.datalink.md"), "utf8"); const code = readme.split("## 公共 SDK")[1]?.match(/```typescript\n([\s\S]*?)\n```/)?.[1]; expect(code).toBeDefined(); const file = resolve(root, "src/__sdk-readme-example__.ts"); diff --git a/scripts/dev-hygiene.test.ts b/scripts/dev/dev-hygiene.test.ts similarity index 100% rename from scripts/dev-hygiene.test.ts rename to scripts/dev/dev-hygiene.test.ts diff --git a/scripts/dev-hygiene.ts b/scripts/dev/dev-hygiene.ts similarity index 99% rename from scripts/dev-hygiene.ts rename to scripts/dev/dev-hygiene.ts index 009b6bf..15bf864 100644 --- a/scripts/dev-hygiene.ts +++ b/scripts/dev/dev-hygiene.ts @@ -7,7 +7,7 @@ import { homedir } from "node:os"; import { dirname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const PACKAGE = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string }; const CANONICAL_SKILL_DIR = join(homedir(), ".agents", "skills", "hose-use"); const NON_CANONICAL_SKILL_DIRS = [ diff --git a/scripts/dev-override.test.ts b/scripts/dev/dev-override.test.ts similarity index 100% rename from scripts/dev-override.test.ts rename to scripts/dev/dev-override.test.ts diff --git a/scripts/dev-override.ts b/scripts/dev/dev-override.ts similarity index 98% rename from scripts/dev-override.ts rename to scripts/dev/dev-override.ts index a3bfcbf..2894a55 100644 --- a/scripts/dev-override.ts +++ b/scripts/dev/dev-override.ts @@ -6,7 +6,7 @@ import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); export interface DevOverrideOptions { dryRun: boolean; @@ -50,7 +50,7 @@ export function resolveTargetBinaryPath(commandName = "hose-use"): string { } function runBuild(): string { - const result = spawnSync("node", ["scripts/build-binary.mjs"], { + const result = spawnSync("node", ["scripts/build/build-binary.mjs"], { cwd: ROOT, stdio: ["ignore", "inherit", "inherit"], }); diff --git a/scripts/bundle-openapi.ts b/scripts/generate/bundle-openapi.ts similarity index 97% rename from scripts/bundle-openapi.ts rename to scripts/generate/bundle-openapi.ts index a99257b..ea98ffc 100644 --- a/scripts/bundle-openapi.ts +++ b/scripts/generate/bundle-openapi.ts @@ -6,7 +6,7 @@ import YAML from "yaml"; type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; -const inputFile = resolve("specs/openapi/openapi.yaml"); +const inputFile = resolve("specs/hose-open-api/openapi.yaml"); const outputFile = resolve("specs/openapi.json"); const bundled = bundle(inputFile, new Set()); diff --git a/scripts/generate/export-workflow-schema.test.ts b/scripts/generate/export-workflow-schema.test.ts new file mode 100644 index 0000000..49744a0 --- /dev/null +++ b/scripts/generate/export-workflow-schema.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { WorkflowDetailSchema } from "../../src/domains/platform/workflow/types.js"; + +test("工作流 Schema 导出可重现,保留归一化输出与有效递归引用", () => { + const dir = mkdtempSync(join(tmpdir(), "hose-workflow-schema-")); + try { + const script = resolve(import.meta.dir, "export-workflow-schema.ts"); + const generate = () => { + const result = spawnSync(process.execPath, [script], { cwd: dir, encoding: "utf8" }); + expect(result.status, result.stderr).toBe(0); + return readFileSync(join(dir, "specs/workflow-schema.json"), "utf8"); + }; + const first = generate(); + expect(generate()).toBe(first); + expect(first).toBe(readFileSync(resolve(import.meta.dir, "../../specs/workflow-schema.json"), "utf8")); + const document = JSON.parse(first); + expect(Object.keys(document.schemas)).toEqual(["WorkflowDetail", "WorkflowTask", "Workflow"]); + const detail = document.schemas.WorkflowDetail; + expect(detail.properties.state.type).toBe("number"); + expect(detail.required).toContain("tasks"); + expect(detail.required).toContain("state"); + expect(detail.required).not.toContain("alarm"); + const alarm = detail.properties.alarm.anyOf; + expect(alarm.map((branch: { type: string }) => branch.type)).toEqual(["object", "null"]); + expect(alarm[0].properties.active.type).toBe("boolean"); + expect(alarm[0].required).toContain("alarmUser"); + for (const input of [{ active: false }, '{"active":false}']) { + const normalized = WorkflowDetailSchema.parse({ id: "fixture", state: "1", alarm: input }); + expect(normalized.state).toBe(1); + expect(normalized.alarm).toEqual({ active: false, alarmUser: [], alarmType: [], alarmScope: "" }); + } + expect(WorkflowDetailSchema.parse({ id: "fixture", alarm: null }).alarm).toBeNull(); + expect(WorkflowDetailSchema.parse({ id: "fixture", alarm: "invalid JSON" }).alarm).toBeUndefined(); + for (const schema of Object.values(document.schemas)) { + let refs = 0; + const visit = (node: any): void => { + if (!node || typeof node !== "object") return; + if (typeof node.$ref === "string") { + expect(node.$ref === "#" || node.$ref.startsWith("#/")).toBe(true); + const target = node.$ref === "#" ? schema : node.$ref.slice(2).split("/").reduce((value: any, key: string) => value?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], schema); + expect(target).toBeDefined(); + refs++; + } + Object.values(node).forEach(visit); + }; + visit(schema); + expect(refs).toBeGreaterThan(0); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/scripts/export-workflow-schema.ts b/scripts/generate/export-workflow-schema.ts similarity index 54% rename from scripts/export-workflow-schema.ts rename to scripts/generate/export-workflow-schema.ts index 14b3c95..2babae5 100644 --- a/scripts/export-workflow-schema.ts +++ b/scripts/generate/export-workflow-schema.ts @@ -1,10 +1,12 @@ import { writeFileSync, mkdirSync } from "fs"; import { join, dirname } from "path"; +import { z } from "zod"; import { + WorkflowAlarmSchema, WorkflowDetailSchema, WorkflowTaskSchema, WorkflowSchema, -} from "../src/domains/platform/types.js"; +} from "../../src/domains/platform/workflow/types.js"; const OUTPUT_DIR = join(process.cwd(), "specs"); const OUTPUT_FILE = join(OUTPUT_DIR, "workflow-schema.json"); @@ -14,9 +16,14 @@ function writeJson(path: string, data: unknown): void { writeFileSync(path, JSON.stringify(data, null, 2)); } -const workflowDetailJsonSchema = (WorkflowDetailSchema as any).toJSONSchema(); -const workflowTaskJsonSchema = (WorkflowTaskSchema as any).toJSONSchema(); -const workflowJsonSchema = (WorkflowSchema as any).toJSONSchema(); +// 导出运行时归一化后的结构:alarm 的 JSON 字符串已解析为对象或 undefined。 +// JSON Schema 无法推导 transform 函数,因而只在导出视图中声明其输出,保留域层解析逻辑。 +const workflowDetailOutputSchema = WorkflowDetailSchema.extend({ + alarm: WorkflowAlarmSchema.nullable().optional(), +}); +const workflowDetailJsonSchema = z.toJSONSchema(workflowDetailOutputSchema); +const workflowTaskJsonSchema = z.toJSONSchema(WorkflowTaskSchema); +const workflowJsonSchema = z.toJSONSchema(WorkflowSchema); writeJson(OUTPUT_FILE, { $schema: "https://json-schema.org/draft/2020-12/schema", diff --git a/scripts/generate-raw-openapi.ts b/scripts/generate/generate-raw-openapi.ts similarity index 100% rename from scripts/generate-raw-openapi.ts rename to scripts/generate/generate-raw-openapi.ts diff --git a/scripts/bump-version.ts b/scripts/release/bump-version.ts similarity index 94% rename from scripts/bump-version.ts rename to scripts/release/bump-version.ts index 04d0939..e025c6a 100644 --- a/scripts/bump-version.ts +++ b/scripts/release/bump-version.ts @@ -37,7 +37,7 @@ export function bumpVersion(ROOT: string, input: string, rebuild = () => { if (git(["tag", "--list", `v${nextVersion}`])) throw new Error(`Tag v${nextVersion} already exists`); // Read all versioned sources before writing any of them. for (const file of ["README.md", "skills/hose-use/SKILL.md"]) readFileSync(join(ROOT, file), "utf8"); - for (const file of ["specs/openapi/openapi.yaml", ".zcode-plugin/plugin.json"]) { + for (const file of ["specs/hose-open-api/openapi.yaml", ".zcode-plugin/plugin.json"]) { if (existsSync(join(ROOT, file))) { const content = readFileSync(join(ROOT, file), "utf8"); if (file.endsWith(".json")) JSON.parse(content); @@ -68,13 +68,13 @@ export function bumpVersion(ROOT: string, input: string, rebuild = () => { writeFileSync(skillPath, skillContent); console.log("✓ Updated skills/hose-use/SKILL.md"); - // 4. specs/openapi/openapi.yaml - const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml"); + // 4. specs/hose-open-api/openapi.yaml + const openapiPath = join(ROOT, "specs", "hose-open-api", "openapi.yaml"); if (existsSync(openapiPath)) { let openapiContent = readFileSync(openapiPath, "utf-8"); openapiContent = openapiContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`); writeFileSync(openapiPath, openapiContent); - console.log("✓ Updated specs/openapi/openapi.yaml"); + console.log("✓ Updated specs/hose-open-api/openapi.yaml"); } // 4.5 .zcode-plugin/plugin.json @@ -113,7 +113,7 @@ export function isReleaseVersion(value: string): boolean { if (import.meta.main) { try { - bumpVersion(join(import.meta.dirname, ".."), process.argv[2]?.trim() || ""); + bumpVersion(join(import.meta.dirname, "../.."), process.argv[2]?.trim() || ""); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; diff --git a/scripts/check-version-sync.ts b/scripts/release/check-version-sync.ts similarity index 86% rename from scripts/check-version-sync.ts rename to scripts/release/check-version-sync.ts index 1376e9f..e5c5e0e 100644 --- a/scripts/check-version-sync.ts +++ b/scripts/release/check-version-sync.ts @@ -2,12 +2,12 @@ import { readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; -const root = join(import.meta.dirname, ".."); +const root = join(import.meta.dirname, "../.."); const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version; const expected: Array<[string, string | undefined]> = [ ["package.json", packageVersion], [".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")], - ["specs/openapi/openapi.yaml", readFileSync(join(root, "specs/openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]], + ["specs/hose-open-api/openapi.yaml", readFileSync(join(root, "specs/hose-open-api/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]], ["specs/openapi.json", readJsonVersion("specs/openapi.json", ["info", "version"])], ]; diff --git a/scripts/release-validation.test.ts b/scripts/release/release-validation.test.ts similarity index 95% rename from scripts/release-validation.test.ts rename to scripts/release/release-validation.test.ts index 409c56e..d55f5e0 100644 --- a/scripts/release-validation.test.ts +++ b/scripts/release/release-validation.test.ts @@ -22,11 +22,11 @@ function repository() { git("config", "core.hooksPath", "/dev/null"); git("config", "commit.gpgsign", "false"); git("config", "tag.gpgsign", "false"); - for (const dir of ["skills/hose-use", "specs/openapi", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true }); + for (const dir of ["skills/hose-use", "specs/hose-open-api", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true }); writeFileSync(join(root, "package.json"), '{"version":"1.0.0"}\n'); writeFileSync(join(root, "README.md"), "# hose-use (v1.0.0)\n"); writeFileSync(join(root, "skills/hose-use/SKILL.md"), "version: 1.0.0\n# hose-use (v1.0.0)\n"); - writeFileSync(join(root, "specs/openapi/openapi.yaml"), "info:\n version: 1.0.0\n"); + writeFileSync(join(root, "specs/hose-open-api/openapi.yaml"), "info:\n version: 1.0.0\n"); writeFileSync(join(root, ".zcode-plugin/plugin.json"), '{"version":"1.0.0"}\n'); git("add", "."); git("commit", "-m", "fixture"); @@ -71,7 +71,7 @@ case "$url" in *) exit 22 ;; esac `, { mode: 0o755 }); - const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8")); + const workflow = parse(readFileSync(join(import.meta.dir, "../../.github/workflows/release.yml"), "utf8")); const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release"); return { ...f, files, run: () => spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0", MIRROR_ONLY: String(mirrorOnly), GITHUB_REPOSITORY: "test/repo", MIRROR_FIXTURE: f.root, MIRROR_MODE: mode }, encoding: "utf8", timeout: 30_000 }) }; } @@ -97,7 +97,7 @@ describe("release preparation and publication guards", () => { expect(rebuilt).toBe(true); expect(f.version()).toBe("1.0.1"); expect(readFileSync(join(f.root, "skills/hose-use/SKILL.md"), "utf8")).toContain("version: 1.0.1"); - expect(parse(readFileSync(join(f.root, "specs/openapi/openapi.yaml"), "utf8")).info.version).toBe("1.0.1"); + expect(parse(readFileSync(join(f.root, "specs/hose-open-api/openapi.yaml"), "utf8")).info.version).toBe("1.0.1"); }, 60_000); test("an existing release tag cannot be reused during bump", () => { @@ -124,7 +124,7 @@ describe("release preparation and publication guards", () => { }, 60_000); test("workflows validate committed versions before generation and ship the checksum manifest", () => { - const root = join(import.meta.dir, ".."); + const root = join(import.meta.dir, "../.."); const ci = parse(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8")); const release = parse(readFileSync(join(root, ".github/workflows/release.yml"), "utf8")); expect(ci.on.pull_request.branches).toContain("main"); @@ -147,7 +147,7 @@ describe("release preparation and publication guards", () => { test("a failed background Gitea upload makes the Release step fail", () => { const f = repository(); - const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8")); + const workflow = parse(readFileSync(join(import.meta.dir, "../../.github/workflows/release.yml"), "utf8")); const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release"); mkdirSync(join(f.root, "tools")); mkdirSync(join(f.root, "dist/bin"), { recursive: true }); writeFileSync(join(f.root, "dist/bin/hose-use-linux-x64"), "fixture"); diff --git a/scripts/verify-release.ts b/scripts/release/verify-release.ts similarity index 94% rename from scripts/verify-release.ts rename to scripts/release/verify-release.ts index 525b5ee..33fadcf 100644 --- a/scripts/verify-release.ts +++ b/scripts/release/verify-release.ts @@ -19,6 +19,6 @@ export function verifyReleaseTag(root: string, tag: string): void { } if (import.meta.main) { - verifyReleaseTag(resolve(import.meta.dir, ".."), process.argv[2] || ""); + verifyReleaseTag(resolve(import.meta.dir, "../.."), process.argv[2] || ""); console.log("Release tag, HEAD, main ancestry and package version verified."); } diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index b7e8139..66fcd48 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -83,7 +83,7 @@ metadata: 17. **循环筛选与付款明细映射**: - 原生 `every` 的筛选字段物理键与右值选择器是两种结构:左侧保留 `feeTypeId`,右侧固定费用类型需保留前端 `value()` 描述符的真实 `key` 和 `label`;裸 ID 运行成功不代表设计器正常显示; - 金额来源、费用类型与明细对应关系须按用户确认的业务规则和实际字段元数据确定;创单引用循环聚合结果,空明细不得继续创单或回写成功; - - 回读用户手工保存的 JSON 时,同时检查 `batch` / `batchSize`;并行配置会改变执行方式,不得当作显示修复自动覆盖。完整结构、金额类型与空列表兼容方案见 [references/workflow.md §20](references/workflow.md#20-原生循环筛选选择器与费用明细)。 + - 回读用户手工保存的 JSON 时,同时检查 `batch` / `batchSize`;并行配置会改变执行方式,不得当作显示修复自动覆盖。完整结构、金额类型与空列表兼容方案见 [references/workflow.md §20](./references/workflow.md#20-原生循环筛选选择器与费用明细)。 --- @@ -91,59 +91,59 @@ metadata: | 用户意图 / 场景 | 推荐命令 | 深入参考文档 | |---|---|---| -| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](references/auth.md) | -| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) | -| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) | -| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) | -| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) | -| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) | -| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) | -| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](references/auth.md) | -| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通/权限转交 | `hose-use assist-platform login/search/detail/tickets/staff/apply/enter/transfer` | [references/assist-platform.md](references/assist-platform.md) | -| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys ` | [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 [--since=7d] [--code=<单号>]`, `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 feetype list`, `hose-use feetype create`, `hose-use feetype get ` | [references/feetype.md](references/feetype.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`, `hose-use bill spec ` | [references/bill.md](references/bill.md) | -| 草稿字段一致性校验(金额/币种/发票总额/明细草稿状态) | `hose-use bill validate <单号|ID>` | [references/bill.md](references/bill.md) | -| 单据模板列表(默认仅启用,与页面快速新建同源) | `hose-use bill templates [--all] [--keyword=...]` | [references/bill.md](references/bill.md) | -| 按模板创建单据草稿(不提交) | `hose-use bill create --template <模板ID> [--title] [--amount] [--reason] --yes` | [references/bill.md](references/bill.md) | -| 提交单据送审 | `hose-use bill submit <单号|ID> [--approver=<员工>] --yes` | [references/bill.md](references/bill.md) | -| 复制单据为新草稿(清空发票绑定,不提交) | `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] --yes` | [references/bill.md](references/bill.md) | -| 删除草稿单据(仅 draft 状态) | `hose-use bill delete <单号|ID> --yes` | [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 app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) | -| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](references/workflow.md) | -| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record ` | [references/workflow.md](references/workflow.md) | -| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) | -| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) | -| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) | -| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) | -| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job `, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) | -| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze [--fail]` | [references/workflow.md](references/workflow.md) | -| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant ` | [references/workflow.md](references/workflow.md) | -| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) | -| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) | -| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) | -| 常驻守护进程管理 / 后台运行 | `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-use openapi`, `hose-use openapi --raw` | [references/service.md](references/service.md) | +| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](./references/auth.md) | +| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](./references/approval.md) | +| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](./references/approval.md) | +| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](./references/approval.md) | +| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](./references/approval.md) | +| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](./references/auth.md) | +| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](./references/auth.md) | +| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](./references/auth.md) | +| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通/权限转交 | `hose-use assist-platform login/search/detail/tickets/staff/apply/enter/transfer` | [references/assist-platform.md](./references/assist-platform.md) | +| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys ` | [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 [--since=7d] [--code=<单号>]`, `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 feetype list`, `hose-use feetype create`, `hose-use feetype get ` | [references/feetype.md](./references/feetype.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`, `hose-use bill spec ` | [references/bill.md](./references/bill.md) | +| 草稿字段一致性校验(金额/币种/发票总额/明细草稿状态) | `hose-use bill validate <单号|ID>` | [references/bill.md](./references/bill.md) | +| 单据模板列表(默认仅启用,与页面快速新建同源) | `hose-use bill templates [--all] [--keyword=...]` | [references/bill.md](./references/bill.md) | +| 按模板创建单据草稿(不提交) | `hose-use bill create --template <模板ID> [--title] [--amount] [--reason] --yes` | [references/bill.md](./references/bill.md) | +| 提交单据送审 | `hose-use bill submit <单号|ID> [--approver=<员工>] --yes` | [references/bill.md](./references/bill.md) | +| 复制单据为新草稿(清空发票绑定,不提交) | `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] --yes` | [references/bill.md](./references/bill.md) | +| 删除草稿单据(仅 draft 状态) | `hose-use bill delete <单号|ID> --yes` | [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 app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](./references/workflow.md) | +| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](./references/workflow.md) | +| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record ` | [references/workflow.md](./references/workflow.md) | +| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](./references/workflow.md) | +| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](./references/workflow.md) | +| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](./references/auth.md) | +| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](./references/workflow.md) | +| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job `, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](./references/workflow.md) | +| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze [--fail]` | [references/workflow.md](./references/workflow.md) | +| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant ` | [references/workflow.md](./references/workflow.md) | +| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](./references/workflow.md) | +| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](./references/store.md) | +| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](./references/store.md) | +| 常驻守护进程管理 / 后台运行 | `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-use openapi`, `hose-use openapi --raw` | [references/service.md](./references/service.md) | | 一键自动自更新 / 查看版本发布日志 | `hose-use update`, `hose-use update --changelog` | `hose-use update --help` | --- diff --git a/skills/hose-use/multi/ekuaibao-nodes/SKILL.md b/skills/hose-use/multi/ekuaibao-nodes/SKILL.md index 0c6e7d2..4ed4681 100644 --- a/skills/hose-use/multi/ekuaibao-nodes/SKILL.md +++ b/skills/hose-use/multi/ekuaibao-nodes/SKILL.md @@ -9,7 +9,7 @@ description: | 批量开通合思工作流节点。 -节点名称与 type 对照见 [灰度节点清单](references/gray-nodes.md)。 **`nodes` 参数填清单中的 `type` 列值(如 `code`、`risk`),不是中文名。** 遇到同名节点或用户只提供模糊名称时,先根据 type 核对并向用户确认。 +节点名称与 type 对照见 [灰度节点清单](./references/gray-nodes.md)。 **`nodes` 参数填清单中的 `type` 列值(如 `code`、`risk`),不是中文名。** 遇到同名节点或用户只提供模糊名称时,先根据 type 核对并向用户确认。 ## 参数提取 diff --git a/skills/hose-use/references/README.references.md b/skills/hose-use/references/README.references.md new file mode 100644 index 0000000..c0e0644 --- /dev/null +++ b/skills/hose-use/references/README.references.md @@ -0,0 +1,28 @@ +# 产品技能参考索引(references) + +本目录是随 hose-use 分发的业务操作参考,供 [产品 Skill 入口](../SKILL.md) 按任务读取。它面向使用 CLI/MCP 的 Agent;项目开发规则位于根目录 `.agents/` 与 `AGENTS.md`。 + +## 按业务选择参考 + +| 文档 | 主题 | +|---|---| +| [auth.md](./auth.md) | 登录、企业身份与运行模式 | +| [assist-platform.md](./assist-platform.md) | 协助平台、工单及代客登录 | +| [bill.md](./bill.md) | 单据、费用明细、复制与写入操作 | +| [approval.md](./approval.md) | AI PRO 确定性审批与规则 | +| [workflow.md](./workflow.md) | 自建应用、工作流、节点、调试和恢复 | +| [contact.md](./contact.md) | 通讯录与员工档案 | +| [dimension.md](./dimension.md) | 自定义档案和核算维度 | +| [feetype.md](./feetype.md) | 费用类型及表单字段规格 | +| [role.md](./role.md) | 角色与角色组 | +| [task.md](./task.md) | 待办与审批任务 | +| [message.md](./message.md) | 消息中心 | +| [store.md](./store.md) | 应用中心与 OpenAPI 密钥 | +| [service.md](./service.md) | 守护进程与 HTTP 网关 | + +## 使用与维护 + +- 通过 `hose-use <命令> --help` 核对当前参数;MCP 统一使用 `hose_cli` 调用同一命令体系。 +- 写操作说明需明确目标企业、预演与确认参数,不在示例中加入真实凭证或企业业务载荷。 +- 修改命令行为时同步对应参考和 Skill 路由;工作流 MVEL 与节点开通的专门技能由上级 Skill 分流。 +- 文档属于插件与技能分发输入;构建与安装方式见 [打包说明](../../../src/packaging/README.packaging.md)。 diff --git a/specs/hose-close-api/README.md b/specs/hose-close-api/README.md index d344930..d816e6e 100644 --- a/specs/hose-close-api/README.md +++ b/specs/hose-close-api/README.md @@ -31,7 +31,7 @@ specs/hose-close-api/ | 域 | 代码接口数 | 主要来源 | |---|---:|---| | auth / corps | 19 | `src/core/auth/login.ts`、`openapi-v1.ts`、`link-import.ts`、`src/core/http/*` | -| platform / workflow | 30 | `src/domains/platform/api.ts` | +| platform / workflow | 30 | `src/domains/platform/workflow/api.ts` | | bill / specifications | 5 | `src/domains/bill/api.ts`、`templates.ts`、`src/domains/feetype/api.ts` | | assist-platform | 12 | `src/domains/assist-platform/api.ts` | | **合计** | **66** | | @@ -40,7 +40,7 @@ specs/hose-close-api/ ## 来源 -- `src/domains/platform/api.ts` + `src/domains/platform/types.ts` +- `src/domains/platform/workflow/api.ts` + `src/domains/platform/workflow/types.ts` - `src/domains/bill/api.ts` + `src/domains/bill/types.ts` + `src/domains/bill/templates.ts` - `src/domains/feetype/api.ts` - `src/domains/assist-platform/api.ts` @@ -62,7 +62,7 @@ specs/hose-close-api/ ## 响应包装约定 -- **Piper / EASO 业务接口**:常见 `{ "code": 200, "msg": "...", "data": ... }`。`code` 是数字;`src/domains/platform/api.ts` 把非 200 的 `code` 当错误。 +- **Piper / EASO 业务接口**:常见 `{ "code": 200, "msg": "...", "data": ... }`。`code` 是数字;`src/domains/platform/workflow/api.ts` 把非 200 的 `code` 当错误。 - **主站列表接口**:常见裸 `{ "items": [...] }`、`{ "value": ... }` 或直接数组。 - **快照接口**:`inputs` / `outputs` 在响应里是 JSON 编码字符串,不是数组;`WorkflowSnapshotSchema` 兼容字符串和数组。 - **Job 执行接口**:`/execution`、`/execution/level/failed` 的 `data` 可能是数组,也可能是 `{number,size,totalPages,totalItems,items}` 分页对象。 diff --git a/specs/hose-close-api/endpoints.md b/specs/hose-close-api/endpoints.md index 98889b1..7dd9689 100644 --- a/specs/hose-close-api/endpoints.md +++ b/specs/hose-close-api/endpoints.md @@ -45,38 +45,38 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth? | # | Method | Path | 请求 | 响应 | 来源 | 抓包 | |---|---|---|---|---|---|---| -| P01 | GET | `EKB /api/v2/datalink/platform/search` | Query `{scope:"enable",corpId}` | `{items:[Platform]}` | `src/domains/platform/api.ts:82`、`src/domains/datalink/api.ts:55` | 否 | -| P02 | GET | `PIPER /api/easo/pipelines/logs` | Query `{platformId,number,pageSize}` | `{code,msg,data:{pipelineNum,runningNum,allRunCount,errorCount,number,size,totalPages,totalItems,pipelineList:[Workflow]}}` | `src/domains/platform/api.ts:98` | legacy | -| P03 | GET | `PIPER /api/easo/stats` | Query `{platformId}` | `{code,msg,data:{total,completed,failed,started,pipelineOpenCount,pipelineCloseCount,pipelineAllCount}}` | `src/domains/platform/api.ts:112` | 否 | -| P04 | GET | `PIPER /api/easo/charge` | 无 | `{code,msg,data:{corporationId,status,orderType,total,used,remaining}}` | `src/domains/platform/api.ts:121` | 否 | -| P05 | GET | `PIPER /api/easo/pipelines/{pipelineId}` | 无 | `{code,msg,data:WorkflowDetail}`;结构见 `schemas/workflow-detail.schema.json` | `src/domains/platform/api.ts:131` | legacy | -| P06 | PUT | `PIPER /api/easo/pipelines/{id}` | body 为完整 `WorkflowDetail`;Web 保存会带 `inputs:[{key:"$platformId",value:}]` | `{code:200,msg:"修改成功",data:WorkflowDetail}`;响应 `data` 不含 `inputs` | `src/domains/platform/api.ts:141`、`src/domains/platform/services.ts:68` | 见 `_tmp-captured` | -| P07 | PUT | `PIPER /api/easo/pipelines/{id}/chooses` | 无 body | `{code,msg,data:[{key,label,displayName,choose}]}`;`choose` 为递归选择器树 | `src/domains/platform/api.ts:155`、`services.ts:79` | 见 `_tmp-captured` | -| P08 | PUT | `PIPER /api/easo/pipelines/{id}/copy` | body 为 `WorkflowDetail`(复制后的详情) | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/api.ts:163` | 否 | -| P09 | POST | `PIPER /api/easo/pipelines` | body 为工作流对象 | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/api.ts:173` | 否 | -| P10 | DELETE | `PIPER /api/easo/pipelines/{id}` | 无 | 读取并丢弃响应文本;代码视为成功 | `src/domains/platform/api.ts:183` | 否 | -| P11 | GET | `PIPER /api/easo/pipelines/{id}/snapshots` | Query `{number,pageSize}` | `{code,msg,data:{number,size,totalPages,totalItems,items:[WorkflowSnapshot]}}` | `src/domains/platform/api.ts:194` | 否 | -| P12 | GET | `PIPER /api/easo/pipelines/snapshot/{snapshotId}` | 无 | `{code,msg,data:WorkflowSnapshot}`;`inputs`/`outputs` 为 JSON 字符串 | `src/domains/platform/api.ts:207` | 见 `_tmp-captured` | -| P13 | GET | `PIPER /api/easo/snapshots/{snapshotId}` | 无 | 同 P12;P12 失败后的 fallback | `src/domains/platform/api.ts:208` | 否 | -| P14 | GET | `PIPER /api/easo/pipelines/{pipelineId}/snapshots/{snapshotId}` | 无 | 同 P12;P12/P13 失败后的 fallback | `src/domains/platform/api.ts:209` | 否 | -| P15 | GET | `PIPER /api/easo/pipelines/{id}/log` | Query `{state,number,pageSize,startTime?,endTime?}` | `{code,msg,data:{number,size,totalPages,totalItems,items,jobList,executeCount,successCount,errorCount}}` | `src/domains/platform/api.ts:234` | 否 | -| P16 | PUT | `PIPER /api/easo/pipelines/state/{pipelineId}` | Query `{state:"0"|"1"}` | 2xx 即成功;响应体忽略 | `src/domains/platform/api.ts:253` | legacy | -| P17 | GET | `PIPER /api/easo/jobs/running` | Query `{pipelineId,runType:"DEBUG"|"PROD"}` | `{code,msg,data:WorkflowJob|WorkflowJob[]}` | `src/domains/platform/api.ts:266` | legacy | -| P18 | GET | `PIPER /api/easo/jobs/{jobId}` | 无 | `{code,msg,data:JobDetail}`;Job 字段见 `schemas/workflow-job-execution.schema.json` | `src/domains/platform/api.ts:285` | 见 `_tmp-captured`(CLI 聚合) | -| P19 | GET | `PIPER /api/easo/jobs/{jobId}/execution` | Query `{number,pageSize}` | `{code,msg,data:TaskExecution[]|ExecutionPage}` | `src/domains/platform/api.ts:294` | 见 `_tmp-captured`(CLI 聚合) | -| P20 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level/failed` | 无 | `{code,msg,data:ExecutionPage|TaskExecution[]}` | `src/domains/platform/api.ts:311` | 见 `_tmp-captured`(CLI 聚合) | -| P21 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level` | Query `{parentId,number,pageSize}` | `{code,msg,data:ExecutionPage}` | `src/domains/platform/api.ts:333` | 否 | -| P22 | GET | `PIPER /api/easo/executions/{executionId}/logs` | 无 | `{code,msg,data:ExecutionLog[]|{items:[ExecutionLog]}}` | `src/domains/platform/api.ts:347` | 否 | -| P23 | GET | `PIPER /api/easo/dsl/all` | 无 | `{data:NodeDef[]}` 或 `{data:{action:[],control:[],trigger:[]}}`;NodeDef 见下 | `src/domains/platform/api.ts:363`、`:381` | legacy | -| P24 | GET | `PIPER /api/easo/common/staffs` | Query `{external:"true"|"false"}` | `{code,msg,data:[{id,name,email?,department?}]}` | `src/domains/platform/api.ts:400` | legacy | -| P25 | GET | `PIPER /api/webhook/{pipelineId}` | 无 | `{code,msg,data:{id,pipelineId,url,active}}` | `src/domains/platform/api.ts:412` | legacy | -| P26 | POST | `PIPER /api/easo/pipelines/{id}/sampleData` | 无 body(`sampleWorkflowData`)或 `{type:"webhook"}`(`getWorkflowSampleData`) | 无 body 时:采样对象;带 type 时:`{records:[{id,corporationId?,pipelineId?,taskName?,actived?,dataJson,createTime,updateTime?}],total?,size?,current?}` | `src/domains/platform/api.ts:422`、`:472` | legacy | -| P27 | POST | `PIPER /api/easo/pipelines/{id}/debugSource` | `{number,pageSize,keywords?}` | `{code,msg,data:{type,total,items:[{id,title,flowState}],fields:[{key,label}],label}}` | `src/domains/platform/api.ts:433` | 否 | -| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:|{id}|{jobId}}` | `src/domains/platform/api.ts:448` | 否 | -| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/api.ts:486` | 否 | -| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/api.ts:511` | 否 | +| P01 | GET | `EKB /api/v2/datalink/platform/search` | Query `{scope:"enable",corpId}` | `{items:[Platform]}` | `src/domains/platform/applications/api.ts:9`、`src/domains/platform/applications/api.ts:15`、`src/domains/platform/applications/api.ts:37` | 否 | +| P02 | GET | `PIPER /api/easo/pipelines/logs` | Query `{platformId,number,pageSize}` | `{code,msg,data:{pipelineNum,runningNum,allRunCount,errorCount,number,size,totalPages,totalItems,pipelineList:[Workflow]}}` | `src/domains/platform/workflow/api.ts:92` | legacy | +| P03 | GET | `PIPER /api/easo/stats` | Query `{platformId}` | `{code,msg,data:{total,completed,failed,started,pipelineOpenCount,pipelineCloseCount,pipelineAllCount}}` | `src/domains/platform/workflow/api.ts:108` | 否 | +| P04 | GET | `PIPER /api/easo/charge` | 无 | `{code,msg,data:{corporationId,status,orderType,total,used,remaining}}` | `src/domains/platform/workflow/api.ts:118` | 否 | +| P05 | GET | `PIPER /api/easo/pipelines/{pipelineId}` | 无 | `{code,msg,data:WorkflowDetail}`;结构见 `schemas/workflow-detail.schema.json` | `src/domains/platform/workflow/api.ts:127` | legacy | +| P06 | PUT | `PIPER /api/easo/pipelines/{id}` | body 为完整 `WorkflowDetail`;Web 保存会带 `inputs:[{key:"$platformId",value:}]` | `{code:200,msg:"修改成功",data:WorkflowDetail}`;响应 `data` 不含 `inputs` | `src/domains/platform/workflow/api.ts:137`、`src/domains/platform/workflow/configuration.ts:26` | 见 `_tmp-captured` | +| P07 | PUT | `PIPER /api/easo/pipelines/{id}/chooses` | 无 body | `{code,msg,data:[{key,label,displayName,choose}]}`;`choose` 为递归选择器树 | `src/domains/platform/workflow/api.ts:151`、`src/domains/platform/workflow/configuration.ts:26` | 见 `_tmp-captured` | +| P08 | PUT | `PIPER /api/easo/pipelines/{id}/copy` | body 为 `WorkflowDetail`(复制后的详情) | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/workflow/api.ts:159` | 否 | +| P09 | POST | `PIPER /api/easo/pipelines` | body 为工作流对象 | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/workflow/api.ts:170` | 否 | +| P10 | DELETE | `PIPER /api/easo/pipelines/{id}` | 无 | 检查 HTTP 状态与业务码;兼容空成功响应 | `src/domains/platform/workflow/api.ts:180` | 否 | +| P11 | GET | `PIPER /api/easo/pipelines/{id}/snapshots` | Query `{number,pageSize}` | `{code,msg,data:{number,size,totalPages,totalItems,items:[WorkflowSnapshot]}}` | `src/domains/platform/workflow/api.ts:189` | 否 | +| P12 | GET | `PIPER /api/easo/pipelines/snapshot/{snapshotId}` | 无 | `{code,msg,data:WorkflowSnapshot}`;`inputs`/`outputs` 为 JSON 字符串 | `src/domains/platform/workflow/api.ts:201` | 见 `_tmp-captured` | +| P13 | GET | `PIPER /api/easo/snapshots/{snapshotId}` | 无 | 同 P12;P12 失败后的 fallback | `src/domains/platform/workflow/api.ts:201` | 否 | +| P14 | GET | `PIPER /api/easo/pipelines/{pipelineId}/snapshots/{snapshotId}` | 无 | 同 P12;P12/P13 失败后的 fallback | `src/domains/platform/workflow/api.ts:201` | 否 | +| P15 | GET | `PIPER /api/easo/pipelines/{id}/log` | Query `{state,number,pageSize,startTime?,endTime?}` | `{code,msg,data:{number,size,totalPages,totalItems,items,jobList,executeCount,successCount,errorCount}}` | `src/domains/platform/workflow/api.ts:224` | 否 | +| P16 | PUT | `PIPER /api/easo/pipelines/state/{pipelineId}` | Query `{state:"0"|"1"}` | 2xx 即成功;响应体忽略 | `src/domains/platform/workflow/api.ts:249` | legacy | +| P17 | GET | `PIPER /api/easo/jobs/running` | Query `{pipelineId,runType:"DEBUG"|"PROD"}` | `{code,msg,data:WorkflowJob|WorkflowJob[]}` | `src/domains/platform/workflow/api.ts:262` | legacy | +| P18 | GET | `PIPER /api/easo/jobs/{jobId}` | 无 | `{code,msg,data:JobDetail}`;Job 字段见 `schemas/workflow-job-execution.schema.json` | `src/domains/platform/workflow/api.ts:282` | 见 `_tmp-captured`(CLI 聚合) | +| P19 | GET | `PIPER /api/easo/jobs/{jobId}/execution` | Query `{number,pageSize}` | `{code,msg,data:TaskExecution[]|ExecutionPage}` | `src/domains/platform/workflow/api.ts:290` | 见 `_tmp-captured`(CLI 聚合) | +| P20 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level/failed` | 无 | `{code,msg,data:ExecutionPage|TaskExecution[]}` | `src/domains/platform/workflow/api.ts:308` | 见 `_tmp-captured`(CLI 聚合) | +| P21 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level` | Query `{parentId,number,pageSize}` | `{code,msg,data:ExecutionPage}` | `src/domains/platform/workflow/api.ts:329` | 否 | +| P22 | GET | `PIPER /api/easo/executions/{executionId}/logs` | 无 | `{code,msg,data:ExecutionLog[]|{items:[ExecutionLog]}}` | `src/domains/platform/workflow/api.ts:344` | 否 | +| P23 | GET | `PIPER /api/easo/dsl/all` | 无 | `{data:NodeDef[]}` 或 `{data:{action:[],control:[],trigger:[]}}`;NodeDef 见下 | `src/domains/platform/workflow/api.ts:361`、`src/domains/platform/workflow/api.ts:379` | legacy | +| P24 | GET | `PIPER /api/easo/common/staffs` | Query `{external:"true"|"false"}` | `{code,msg,data:[{id,name,email?,department?}]}` | `src/domains/platform/workflow/api.ts:397` | legacy | +| P25 | GET | `PIPER /api/webhook/{pipelineId}` | 无 | `{code,msg,data:{id,pipelineId,url,active}}` | `src/domains/platform/workflow/api.ts:409` | legacy | +| P26 | POST | `PIPER /api/easo/pipelines/{id}/sampleData` | 无 body(`sampleWorkflowData`)或 `{type:"webhook"}`(`getWorkflowSampleData`) | 无 body 时:采样对象;带 type 时:`{records:[{id,corporationId?,pipelineId?,taskName?,actived?,dataJson,createTime,updateTime?}],total?,size?,current?}` | `src/domains/platform/workflow/api.ts:419`、`src/domains/platform/workflow/api.ts:468` | legacy | +| P27 | POST | `PIPER /api/easo/pipelines/{id}/debugSource` | `{number,pageSize,keywords?}` | `{code,msg,data:{type,total,items:[{id,title,flowState}],fields:[{key,label}],label}}` | `src/domains/platform/workflow/api.ts:429` | 否 | +| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:|{id}|{jobId}}` | `src/domains/platform/workflow/api.ts:444` | 否 | +| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/workflow/api.ts:481` | 否 | +| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/workflow/api.ts:498` | 否 | -`Platform` 代码字段(`src/domains/platform/types.ts:5`): +`Platform` 代码字段(`src/domains/platform/workflow/types.ts:5`): ```text id, name, nameSpell, enName?, code, corporationId, active, type, groupType, diff --git a/specs/hose-close-api/schemas/workflow-chooses.schema.json b/specs/hose-close-api/schemas/workflow-chooses.schema.json index 181bc02..e3fc59a 100644 --- a/specs/hose-close-api/schemas/workflow-chooses.schema.json +++ b/specs/hose-close-api/schemas/workflow-chooses.schema.json @@ -4,7 +4,7 @@ "title": "Workflow chooses response", "description": "PUT /api/easo/pipelines/{id}/chooses 的响应 data。请求无 body;服务端按当前 pipeline 每个任务节点重新生成 choose 选择器树。", "x-source": [ - "code-derived: src/domains/platform/api.ts:151", + "code-derived: src/domains/platform/workflow/api.ts:151", "reference: _tmp-captured/raw/PUT-api-easo-pipelines-id-chooses.json" ], "type": "array", diff --git a/specs/hose-close-api/schemas/workflow-detail.schema.json b/specs/hose-close-api/schemas/workflow-detail.schema.json index 8b5cea4..9d64dea 100644 --- a/specs/hose-close-api/schemas/workflow-detail.schema.json +++ b/specs/hose-close-api/schemas/workflow-detail.schema.json @@ -4,7 +4,7 @@ "title": "Workflow detail (EASO/Piper pipeline)", "description": "工作流详情。GET /api/easo/pipelines/{id} 与 PUT /api/easo/pipelines/{id} 使用。PUT 请求体带 inputs,抓包中的响应 data 不返回 inputs。", "x-source": [ - "code-derived: src/domains/platform/types.ts:273 (WorkflowDetailSchema)", + "code-derived: src/domains/platform/workflow/types.ts:252 (WorkflowDetailSchema)", "reference: _tmp-captured/raw/PUT-api-easo-pipelines-id.json" ], "type": "object", diff --git a/specs/hose-close-api/schemas/workflow-job-execution.schema.json b/specs/hose-close-api/schemas/workflow-job-execution.schema.json index 0c46ab0..1d3f0b7 100644 --- a/specs/hose-close-api/schemas/workflow-job-execution.schema.json +++ b/specs/hose-close-api/schemas/workflow-job-execution.schema.json @@ -4,7 +4,7 @@ "title": "Workflow job execution", "description": "Piper 任务实例与节点执行数据。/execution 与 /execution/level/failed 的 data 可能是数组,也可能是分页对象 {number,size,totalPages,totalItems,items}。", "x-source": [ - "code-derived: src/domains/platform/types.ts:360", + "code-derived: src/domains/platform/workflow/types.ts:339", "reference: _tmp-captured/raw/GET-api-easo-jobs-id-execution.json", "reference: _tmp-captured/raw/GET-api-easo-jobs-id-execution-completed.json" ], diff --git a/specs/hose-close-api/schemas/workflow-snapshot.schema.json b/specs/hose-close-api/schemas/workflow-snapshot.schema.json index 0301817..5d2f616 100644 --- a/specs/hose-close-api/schemas/workflow-snapshot.schema.json +++ b/specs/hose-close-api/schemas/workflow-snapshot.schema.json @@ -4,7 +4,7 @@ "title": "Workflow snapshot", "description": "工作流快照。前端使用 GET /api/easo/pipelines/snapshot/{snapshotId};代码还兼容 /api/easo/snapshots/{id} 与 /api/easo/pipelines/{pipelineId}/snapshots/{id}。", "x-source": [ - "code-derived: src/domains/platform/types.ts:307 (WorkflowSnapshotSchema)", + "code-derived: src/domains/platform/workflow/types.ts:286 (WorkflowSnapshotSchema)", "reference: _tmp-captured/raw/GET-api-easo-pipelines-snapshot-id.json" ], "type": "object", diff --git a/specs/openapi/components/schemas/index.yaml b/specs/hose-open-api/components/schemas/index.yaml similarity index 100% rename from specs/openapi/components/schemas/index.yaml rename to specs/hose-open-api/components/schemas/index.yaml diff --git a/specs/openapi/openapi.yaml b/specs/hose-open-api/openapi.yaml similarity index 100% rename from specs/openapi/openapi.yaml rename to specs/hose-open-api/openapi.yaml diff --git a/specs/hose-open-api/paths/README.paths.md b/specs/hose-open-api/paths/README.paths.md new file mode 100644 index 0000000..fa56e2e --- /dev/null +++ b/specs/hose-open-api/paths/README.paths.md @@ -0,0 +1,20 @@ +# 包装层 API 路径组件(paths) + +本目录按命令主题拆分 hose-use 包装层 OpenAPI 的路径定义,由 [openapi.yaml](../openapi.yaml) 通过相对 `$ref` 引用。文件是规范片段,不是独立运行的 HTTP 路由实现。 + +## 文件分工 + +| 文件 | 规范主题 | +|---|---| +| [auth.yaml](./auth.yaml) | 认证登录、状态与续期 | +| [corps.yaml](./corps.yaml) | 企业列表与切换 | +| [platform.yaml](./platform.yaml) | 自建应用列表 | +| [workflow.yaml](./workflow.yaml) | 工作流列表、查找、详情与状态操作 | +| [bill.yaml](./bill.yaml) | 单据查询、详情与结构 | +| [probe.yaml](./probe.yaml) | 会话及认证连通性探测 | + +## 修改与验证 + +从仓库根目录执行 `bun run openapi:bundle`,将完整规范写入 `specs/openapi.json`。新增路径时,同时更新入口文件的引用;共享模型放在 [components/schemas/index.yaml](../components/schemas/index.yaml)。打包脚本只读取 YAML 引用,因此新增 README 不参与打包。 + +API 实际行为需与 [CLI 命令](../../../src/cli/README.cli.md) 和 [HTTP 网关](../../../src/http/README.http.md) 核对;不能仅凭 YAML 判断某条路由已经实现。原生下游接口规范 `specs/openapi.raw.json` 与这里的包装层规范分别维护。 diff --git a/specs/openapi/paths/auth.yaml b/specs/hose-open-api/paths/auth.yaml similarity index 100% rename from specs/openapi/paths/auth.yaml rename to specs/hose-open-api/paths/auth.yaml diff --git a/specs/openapi/paths/bill.yaml b/specs/hose-open-api/paths/bill.yaml similarity index 100% rename from specs/openapi/paths/bill.yaml rename to specs/hose-open-api/paths/bill.yaml diff --git a/specs/openapi/paths/corps.yaml b/specs/hose-open-api/paths/corps.yaml similarity index 100% rename from specs/openapi/paths/corps.yaml rename to specs/hose-open-api/paths/corps.yaml diff --git a/specs/openapi/paths/platform.yaml b/specs/hose-open-api/paths/platform.yaml similarity index 100% rename from specs/openapi/paths/platform.yaml rename to specs/hose-open-api/paths/platform.yaml diff --git a/specs/openapi/paths/probe.yaml b/specs/hose-open-api/paths/probe.yaml similarity index 100% rename from specs/openapi/paths/probe.yaml rename to specs/hose-open-api/paths/probe.yaml diff --git a/specs/openapi/paths/workflow.yaml b/specs/hose-open-api/paths/workflow.yaml similarity index 100% rename from specs/openapi/paths/workflow.yaml rename to specs/hose-open-api/paths/workflow.yaml diff --git a/specs/workflow-schema.json b/specs/workflow-schema.json index f3d26f6..d17705f 100644 --- a/specs/workflow-schema.json +++ b/specs/workflow-schema.json @@ -101,36 +101,79 @@ } }, "alarm": { - "type": "object", - "properties": { - "alarmUser": { - "default": [], - "type": "array", - "items": {} + "anyOf": [ + { + "type": "object", + "properties": { + "alarmUser": { + "default": [], + "type": "array", + "items": {} + }, + "alarmType": { + "default": [], + "type": "array", + "items": { + "type": "string" + } + }, + "active": { + "default": true, + "type": "boolean" + }, + "alarmScope": { + "default": "", + "type": "string" + } + }, + "required": [ + "alarmUser", + "alarmType", + "active", + "alarmScope" + ], + "additionalProperties": false }, - "alarmType": { - "default": [], - "type": "array", - "items": { + { + "type": "null" + } + ] + }, + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "value": {} + }, + "required": [ + "key", + "value" + ], + "additionalProperties": false + } + }, + "$snapshot": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "value": { "type": "string" } }, - "active": { - "default": true, - "type": "boolean" - }, - "alarmScope": { - "default": "", - "type": "string" - } - }, - "required": [ - "alarmUser", - "alarmType", - "active", - "alarmScope" - ], - "additionalProperties": false + "required": [ + "key", + "value" + ], + "additionalProperties": false + } } }, "required": [ @@ -148,7 +191,7 @@ "tasksVersion", "tasks" ], - "additionalProperties": false, + "additionalProperties": {}, "$defs": { "__schema0": { "anyOf": [ @@ -768,36 +811,17 @@ "fields": { "type": "array", "items": { - "anyOf": [ - { - "type": "object", - "properties": { - "key": { - "type": "string" - } - }, - "required": [ - "key" - ], - "additionalProperties": false + "type": "object", + "properties": { + "key": { + "type": "string" }, - { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - }, - "required": [ - "key", - "value" - ], - "additionalProperties": false - } - ] + "value": {} + }, + "required": [ + "key" + ], + "additionalProperties": {} } }, "filters": { @@ -896,36 +920,17 @@ "fields": { "type": "array", "items": { - "anyOf": [ - { - "type": "object", - "properties": { - "key": { - "type": "string" - } - }, - "required": [ - "key" - ], - "additionalProperties": false + "type": "object", + "properties": { + "key": { + "type": "string" }, - { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - }, - "required": [ - "key", - "value" - ], - "additionalProperties": false - } - ] + "value": {} + }, + "required": [ + "key" + ], + "additionalProperties": {} } }, "filters": { @@ -1148,7 +1153,8 @@ "type": "string" }, "type": { - "type": "string" + "type": "string", + "const": "task-dynamic-delay" }, "label": { "type": "string" @@ -1171,6 +1177,68 @@ "status": { "type": "string" }, + "displayName": { + "type": "string" + }, + "sleepTime": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + } + }, + "required": [ + "name", + "type", + "label", + "groupName", + "orderIndex", + "levelIndex", + "status" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "name": { + "default": "task", + "type": "string" + }, + "type": { + "type": "string" + }, + "label": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "groupName": { + "default": "trigger", + "type": "string" + }, + "orderIndex": { + "default": 0, + "type": "number" + }, + "levelIndex": { + "default": [ + 0 + ], + "type": "array", + "items": { + "type": "number" + } + }, + "status": { + "default": "active", + "type": "string" + }, "displayName": { "type": "string" } @@ -1848,36 +1916,17 @@ "fields": { "type": "array", "items": { - "anyOf": [ - { - "type": "object", - "properties": { - "key": { - "type": "string" - } - }, - "required": [ - "key" - ], - "additionalProperties": false + "type": "object", + "properties": { + "key": { + "type": "string" }, - { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - }, - "required": [ - "key", - "value" - ], - "additionalProperties": false - } - ] + "value": {} + }, + "required": [ + "key" + ], + "additionalProperties": {} } }, "filters": { @@ -1976,36 +2025,17 @@ "fields": { "type": "array", "items": { - "anyOf": [ - { - "type": "object", - "properties": { - "key": { - "type": "string" - } - }, - "required": [ - "key" - ], - "additionalProperties": false + "type": "object", + "properties": { + "key": { + "type": "string" }, - { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - }, - "required": [ - "key", - "value" - ], - "additionalProperties": false - } - ] + "value": {} + }, + "required": [ + "key" + ], + "additionalProperties": {} } }, "filters": { @@ -2228,7 +2258,8 @@ "type": "string" }, "type": { - "type": "string" + "type": "string", + "const": "task-dynamic-delay" }, "label": { "type": "string" @@ -2251,6 +2282,68 @@ "status": { "type": "string" }, + "displayName": { + "type": "string" + }, + "sleepTime": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + } + }, + "required": [ + "name", + "type", + "label", + "groupName", + "orderIndex", + "levelIndex", + "status" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "name": { + "default": "task", + "type": "string" + }, + "type": { + "type": "string" + }, + "label": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "groupName": { + "default": "trigger", + "type": "string" + }, + "orderIndex": { + "default": 0, + "type": "number" + }, + "levelIndex": { + "default": [ + 0 + ], + "type": "array", + "items": { + "type": "number" + } + }, + "status": { + "default": "active", + "type": "string" + }, "displayName": { "type": "string" } @@ -3003,36 +3096,17 @@ "fields": { "type": "array", "items": { - "anyOf": [ - { - "type": "object", - "properties": { - "key": { - "type": "string" - } - }, - "required": [ - "key" - ], - "additionalProperties": false + "type": "object", + "properties": { + "key": { + "type": "string" }, - { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - }, - "required": [ - "key", - "value" - ], - "additionalProperties": false - } - ] + "value": {} + }, + "required": [ + "key" + ], + "additionalProperties": {} } }, "filters": { @@ -3131,36 +3205,17 @@ "fields": { "type": "array", "items": { - "anyOf": [ - { - "type": "object", - "properties": { - "key": { - "type": "string" - } - }, - "required": [ - "key" - ], - "additionalProperties": false + "type": "object", + "properties": { + "key": { + "type": "string" }, - { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - }, - "required": [ - "key", - "value" - ], - "additionalProperties": false - } - ] + "value": {} + }, + "required": [ + "key" + ], + "additionalProperties": {} } }, "filters": { @@ -3383,7 +3438,8 @@ "type": "string" }, "type": { - "type": "string" + "type": "string", + "const": "task-dynamic-delay" }, "label": { "type": "string" @@ -3406,6 +3462,68 @@ "status": { "type": "string" }, + "displayName": { + "type": "string" + }, + "sleepTime": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ] + } + }, + "required": [ + "name", + "type", + "label", + "groupName", + "orderIndex", + "levelIndex", + "status" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "name": { + "default": "task", + "type": "string" + }, + "type": { + "type": "string" + }, + "label": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "groupName": { + "default": "trigger", + "type": "string" + }, + "orderIndex": { + "default": 0, + "type": "number" + }, + "levelIndex": { + "default": [ + 0 + ], + "type": "array", + "items": { + "type": "number" + } + }, + "status": { + "default": "active", + "type": "string" + }, "displayName": { "type": "string" } diff --git a/src/README.src.md b/src/README.src.md new file mode 100644 index 0000000..15a63d3 --- /dev/null +++ b/src/README.src.md @@ -0,0 +1,28 @@ +# 源码导航(src) + +本目录包含 CLI、AI PRO、MCP、HTTP 入口、业务域、基础设施和分发内嵌层。架构总纲及强制约束见根目录 [AGENTS.md](../AGENTS.md)。 + +## 顶层文件 + +| 文件 | 职责 | +|---|---| +| [cli.ts](./cli.ts) | 命令行进程入口,识别 hose-aipro 别名并输出执行结果 | +| [aipro-cli.ts](./aipro-cli.ts) | AI PRO 参数分发及审批服务上下文装配 | +| [server.ts](./server.ts) | 单工具 MCP 协议适配,`hose_cli` 委托共享 `runCli` | +| [sdk.ts](./sdk.ts) | 公共 `hose-use/sdk` 导出,目前主要提供运行时装配与 DataLink 能力 | +| [version.ts](./version.ts) | 版本与构建信息;相关测试检查入口一致性 | +| [declarations.d.ts](./declarations.d.ts) | 编译期补充声明 | + +## 分层入口 + +- [cli/](./cli/README.cli.md):解析、注册、确认、输出及 [命令处理器](./cli/commands/README.commands.md)。 +- [domains/](./domains/README.domains.md):业务编排、传输与模型,按业务子域组织。 +- [core/](./core/README.core.md):认证、配置、数据库、缓存、HTTP 与统一错误。 +- [http/](./http/README.http.md):本地网关和文档服务。 +- [packaging/](./packaging/README.packaging.md):内嵌规范与产品技能、构建态自省。 + +## 依赖与维护边界 + +入口处理器通过域层 services/tools 调用业务,不能直接导入域层 `api.ts`;domains 不依赖 CLI/HTTP 入口,core 不反向依赖业务域。`sdk.ts` 目前复用 CLI helper 装配运行时,不能据此声称整个公共 SDK 已与 CLI 完全解耦。 + +新增命令先确定业务域,再接入 CLI 注册表,最后同步层级说明。分层规则由 `cli/architecture-boundaries.test.ts` 校验;提交前执行 `bun test`、`bun run check`。目录文档覆盖另用 `bun run check:readme` 检查。 diff --git a/src/cli/architecture-boundaries.test.ts b/src/cli/architecture-boundaries.test.ts index 091682e..a6d0963 100644 --- a/src/cli/architecture-boundaries.test.ts +++ b/src/cli/architecture-boundaries.test.ts @@ -39,6 +39,30 @@ function resolveImportRelativeToSrc(fromFile: string, specifier: string): string return path ? relative(SRC_ROOT, path.replace(/\.[jt]s$/, "")).replaceAll("\\", "/") : null; } +function platformModule(path: string): string | undefined { + return path.match(/^domains\/platform\/(applications|datalink|workflow)\//)?.[1]; +} + +function platformDependencyViolation(from: string, to: string): boolean { + const source = platformModule(from), target = platformModule(to); + if (!source || !target || source === target) return false; + return /\/api$/.test(to) || source === "applications" || (source === "datalink" && target === "workflow"); +} + +function findCycles(graph: Map>): string[][] { + const done = new Set(), active: string[] = [], cycles: string[][] = []; + const visit = (node: string) => { + const index = active.indexOf(node); + if (index >= 0) { cycles.push([...active.slice(index), node]); return; } + if (done.has(node)) return; + active.push(node); + for (const next of graph.get(node) ?? []) visit(next); + active.pop(); done.add(node); + }; + for (const node of graph.keys()) visit(node); + return cycles; +} + describe("Architecture Layering Boundaries", () => { test("dependency extraction covers aliases, re-exports and literal dynamic/type imports", () => { const imports = extractImportSpecifiers(` @@ -52,6 +76,42 @@ describe("Architecture Layering Boundaries", () => { expect(resolveImportRelativeToSrc(join(SRC_ROOT, "cli", "example.ts"), imports[1])).toBe("domains/bill/api"); }); + test("nested APIs and platform dependency directions cannot bypass boundaries", () => { + const api = /^domains\/(?:[^/]+\/)+api$/; + expect(api.test("domains/platform/workflow/api")).toBe(true); + expect(api.test("domains/bill/api")).toBe(true); + expect(api.test("domains/platform/workflow/services")).toBe(false); + expect(platformDependencyViolation("domains/platform/workflow/services", "domains/platform/applications/services")).toBe(false); + expect(platformDependencyViolation("domains/platform/workflow/services", "domains/platform/applications/api")).toBe(true); + expect(platformDependencyViolation("domains/platform/applications/types", "domains/platform/datalink/types")).toBe(true); + expect(platformDependencyViolation("domains/platform/datalink/services", "domains/platform/workflow/services")).toBe(true); + expect(findCycles(new Map([["a", new Set(["b"])], ["b", new Set(["a"])]]))).toEqual([["a", "b", "a"]]); + expect(findCycles(new Map([["a", new Set(["b"])], ["b", new Set()]]))).toEqual([]); + }); + + test("platform submodules respect ownership and have no cross-module cycles", () => { + const graph = new Map>(), fileGraph = new Map>(), violations: string[] = []; + for (const file of collectTsFiles(join(SRC_ROOT, "domains", "platform"))) { + const from = relative(SRC_ROOT, file).replaceAll("\\", "/").replace(/\.ts$/, ""); + const source = platformModule(from); + fileGraph.set(from, new Set()); + for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) { + const target = resolveImportRelativeToSrc(file, specifier); + if (!target) continue; + if (target.startsWith("domains/platform/")) fileGraph.get(from)!.add(target); + if (platformDependencyViolation(from, target)) violations.push(`${from} -> ${target}`); + const destination = platformModule(target); + if (source && destination && source !== destination) { + if (!graph.has(source)) graph.set(source, new Set()); + graph.get(source)!.add(destination); + } + } + } + expect(violations).toEqual([]); + expect(findCycles(graph)).toEqual([]); + expect(findCycles(fileGraph)).toEqual([]); + }); + test("bill Session HTTP calls stay in the transport module", () => { const violations: string[] = []; for (const file of collectTsFiles(join(SRC_ROOT, "domains", "bill"))) { @@ -74,8 +134,8 @@ describe("Architecture Layering Boundaries", () => { } expect(violations).toEqual([]); }); - test("workflow imports use the module directories after the platform migration", () => { - const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/; + test("platform imports use owned submodules and reject retired private paths", () => { + const legacy = /^(?:domains\/datalink(?:\/|$)|domains\/platform\/(?:api|services|types|execution-context|analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$)/; const violations: string[] = []; for (const file of collectTsFiles(SRC_ROOT, true)) { for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) { @@ -85,7 +145,7 @@ describe("Architecture Layering Boundaries", () => { } expect(violations).toEqual([]); }); - test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => { + test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/**/api directly", () => { const entrypointFiles = [ ...collectTsFiles(join(SRC_ROOT, "cli")), ...collectTsFiles(join(SRC_ROOT, "http")), @@ -100,7 +160,7 @@ describe("Architecture Layering Boundaries", () => { const specifiers = extractImportSpecifiers(content); for (const spec of specifiers) { const targetRel = resolveImportRelativeToSrc(file, spec); - if (targetRel && /^domains\/[^/]+\/api$/.test(targetRel)) { + if (targetRel && /^domains\/(?:[^/]+\/)+api$/.test(targetRel)) { violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`); } } diff --git a/src/cli/commands/README.commands.md b/src/cli/commands/README.commands.md new file mode 100644 index 0000000..465e8f7 --- /dev/null +++ b/src/cli/commands/README.commands.md @@ -0,0 +1,25 @@ +# CLI 命令处理器(commands) + +本目录将已解析参数与企业运行时转换为业务调用和 `CliResult`。顶层命令、别名与常驻属性统一由 [registry.ts](../registry.ts) 和命令元数据声明,执行流程见 [CLI 层说明](../README.cli.md)。 + +## 按命令查找实现 + +| 位置 | 主要职责 | +|---|---| +| [bill/](./bill/README.bill.md) | 单据检索、草稿、提交和审批动作 | +| [workflow/](./workflow/README.workflow.md) | 工作流配置、节点、分析、调试与监听 | +| [corps/](./corps/README.corps.md) | 企业名录、身份、凭证导入和切换 | +| [assist-platform/](./assist-platform/README.assist-platform.md) | 协助平台登录、工单与代客身份 | +| [platform/](./platform) | 自建应用及业务对象命令 | +| [aipro/](./aipro) | AI PRO 会话、规则与状态处理 | +| [update/](./update) | 更新检查与执行 | +| `auth.ts`、`context.ts`、`config.ts`、`probe.ts` | 认证、当前上下文、配置与诊断 | +| `contact.ts`、`dimension.ts`、`feetype.ts`、`role.ts`、`permission.ts` | 员工、档案、费用类型及权限相关业务 | +| `task.ts`、`message.ts`、`store.ts`、`keys.ts` | 待办、消息、应用中心与密钥 | +| `service.ts`、`http.ts`、`mcp.ts`、`openapi.ts`、`skill.ts` | 本地服务、协议入口、规范与技能分发 | + +## 修改约定 + +命令层负责参数和确认语义、输出格式与退出码;业务规则进入对应域,不直接调用 `domains/*/api.ts`。复用 `parser.ts`、`mutation.ts`、`printer.ts` 及企业 helper,避免每个处理器自建确认或认证逻辑。 + +数据类命令的 JSON 输出保持机器可解析,诊断信息放入 stderr。非交互测试不能等待终端输入。测试与实现同级;跨命令兼容、确认及错误行为可由本层的独立集成测试覆盖。 diff --git a/src/cli/commands/app.ts b/src/cli/commands/app.ts index 0b36ba1..9cce398 100644 --- a/src/cli/commands/app.ts +++ b/src/cli/commands/app.ts @@ -1,5 +1,5 @@ import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js"; -import { getPlatform } from "../../domains/datalink/services.js"; +import { getPlatform } from "../../domains/platform/applications/services.js"; import { createClientsForCorp } from "../helpers.js"; import { stringOption, booleanOption } from "../parser.js"; import { printJson, printTable } from "../printer.js"; diff --git a/src/cli/commands/assist-platform/README.assist-platform.md b/src/cli/commands/assist-platform/README.assist-platform.md new file mode 100644 index 0000000..64fda79 --- /dev/null +++ b/src/cli/commands/assist-platform/README.assist-platform.md @@ -0,0 +1,22 @@ +# 协助平台命令(assist-platform) + +[index.ts](./index.ts) 分发 `hose-use assist-platform` 命令,处理参数、确认和展示;业务编排位于 [协助平台域](../../../domains/assist-platform/README.assist-platform.md)。 + +## 文件分工 + +| 文件 | 功能 | +|---|---| +| [common.ts](./common.ts) | 从显式 token 或协助平台会话缓存创建客户端,缺少凭证时抛认证错误 | +| [login.ts](./login.ts) | 协助平台登录与状态 | +| [search.ts](./search.ts)、[detail.ts](./detail.ts) | 企业搜索与详情 | +| [tickets.ts](./tickets.ts)、[staff.ts](./staff.ts) | 工单与员工检索 | +| [enter.ts](./enter.ts) | 选择代客身份、获取会话并按选项导入本地企业配置 | +| [apply.ts](./apply.ts)、[approve.ts](./approve.ts)、[transfer.ts](./transfer.ts) | 工单申请、授权及转交 | + +## 身份与写操作 + +协助平台凭证和目标企业会话是不同上下文,不用普通企业身份替代运营平台登录。代客身份可明确使用 `--staff-id`;同名员工歧义由业务层拒绝,不取首个搜索结果。管理员模式和员工选项冲突时应保持拒绝行为。 + +写入和会话导入沿用各处理器的预演与确认流程,输出不得泄露 token、完整授权链接或会话凭证。具体参数先查 `hose-use assist-platform --help` 和对应子命令帮助。 + +确认、员工选择及客户端协议的回归在上级 `assist-platform*.test.ts` 等测试中。改动时同步 [产品使用参考](../../../../skills/hose-use/references/assist-platform.md)。 diff --git a/src/cli/commands/bill/README.bill.md b/src/cli/commands/bill/README.bill.md new file mode 100644 index 0000000..535e666 --- /dev/null +++ b/src/cli/commands/bill/README.bill.md @@ -0,0 +1,23 @@ +# 单据命令(bill) + +[index.ts](./index.ts) 分发 `hose-use bill` 子命令与别名;[context.ts](./context.ts) 为每次调用构造企业、懒加载 Session 客户端、目标解析和写确认上下文。业务规则见 [单据域说明](../../../domains/bill/README.bill.md)。 + +## 文件与流程 + +| 文件 | 功能 | +|---|---| +| [search.ts](./search.ts) | 列表、详情和定位诊断 | +| [templates.ts](./templates.ts)、[meta.ts](./meta.ts) | 可用模板、字段规格、结构与链接 | +| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[delete.ts](./delete.ts) | 草稿创建、复制与删除 | +| [validate.ts](./validate.ts)、[submit.ts](./submit.ts) | 现有草稿校验及提交 | +| [approve.ts](./approve.ts) | 同意、驳回、转交、加签、评论的命令适配 | +| [flow.ts](./flow.ts)、[related.ts](./related.ts) | 审批时间线、风险预算、关联记录与附件 | + +## 契约与边界 + +- 命令层向域层 tools/services 及公开业务函数传参,不绕过业务层导入传输 API。 +- 创建和复制的预演展示准备结果;真实写入需要确认。非交互环境未确认时应返回确认错误,不能阻塞等待输入。 +- 使用域层统一的模板字段校验、员工解析与业务响应判断,CLI 不重复实现租户字段规则。 +- 提交、审批与删除是不同动作,不把复制草稿当作送审;错误必须保留真实退出状态。 + +从 `hose-use bill --help` 查当前命令;读写行为说明见 [产品参考](../../../../skills/hose-use/references/bill.md)。目录内创建测试和上级 `flow.test.ts` 等回归共同覆盖入口行为,域层测试负责请求和业务契约。 diff --git a/src/cli/commands/corps/README.corps.md b/src/cli/commands/corps/README.corps.md new file mode 100644 index 0000000..1667cab --- /dev/null +++ b/src/cli/commands/corps/README.corps.md @@ -0,0 +1,24 @@ +# 企业与身份命令(corps) + +[index.ts](./index.ts) 分发 `hose-use corps`。本层负责名录展示、当前企业选择、凭证导入及诊断;认证协议和配置落盘由 core 提供。 + +## 实现导航 + +| 文件 | 职责 | +|---|---| +| [query.ts](./query.ts) | 本地企业列表和搜索 | +| [context.ts](./context.ts) | 当前企业与工作企业切换 | +| [whoami.ts](./whoami.ts) | 在线/离线身份核验,显式 `--corp` 时限制到指定企业 | +| [tag.ts](./tag.ts) | 企业标签和环境标识 | +| [link.ts](./link.ts) | 协助链接导入、目标身份解析和链接生成 | +| [credentials.ts](./credentials.ts) | 持久化凭证建档、密钥提取、提权和 seal-use 同步 | +| [probe.ts](./probe.ts) | 合思连通性与员工接口探测 | +| [shared.ts](./shared.ts) | 企业参数及上下文解析辅助函数 | + +## 维护边界 + +显式目标和当前上下文应可区分;不能让单企业身份核验退回全企业在线遍历。`whoami --offline` 保持无网络查询行为,不带企业参数保留全企业身份视图。 + +企业标签和凭证、默认企业属于持久状态;导入、覆盖和切换按处理器的预演/确认契约执行。只用 CLI 输出的脱敏信息定位问题,不将凭证文件内容或授权直链写进说明和测试快照。 + +上级 `corps*.test.ts`、`context.test.ts` 与本目录 [身份范围测试](./whoami-scope.test.ts) 覆盖命令行为。认证实现见 [core/auth](../../../core/auth/README.auth.md),使用参考见 [auth.md](../../../../skills/hose-use/references/auth.md)。 diff --git a/src/cli/commands/platform.test.ts b/src/cli/commands/platform.test.ts index c2f111d..966347b 100644 --- a/src/cli/commands/platform.test.ts +++ b/src/cli/commands/platform.test.ts @@ -1,7 +1,9 @@ +import * as servicesApplications from "../../domains/platform/applications/services.js"; +import * as apiApplications from "../../domains/platform/applications/api.js"; import { describe, expect, it, spyOn, afterEach } from "bun:test"; import { handlePlatformCommand } from "./platform/index.js"; -import * as api from "../../domains/datalink/api.js"; -import * as services from "../../domains/datalink/services.js"; +import * as api from "../../domains/platform/datalink/api.js"; +import * as services from "../../domains/platform/datalink/services.js"; import * as helpers from "../helpers.js"; import type { CliRuntime } from "../types.js"; import type { CorpConfig } from "../../core/config/types.js"; @@ -75,7 +77,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("records 正确解析嵌套 dataLink 的停启用状态和更新时间", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({ total: 2, @@ -107,7 +109,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("record get 获取记录详情", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); spies.push(spyOn(api, "getRecordDetail").mockResolvedValue({ dataLink: { @@ -134,7 +136,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("record toggle 切换停启用状态", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); const toggleSpy = spyOn(api, "toggleRecordState").mockResolvedValue({ recordId: "r-1", active: true }); spies.push(toggleSpy); @@ -151,7 +153,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("record edit 编辑字段", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any); spies.push(editSpy); @@ -182,7 +184,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("record recompute 触发台账重算", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); const recomputeSpy = spyOn(api, "recomputeRecordLedger").mockResolvedValue({ id: "ok" }); spies.push(recomputeSpy); @@ -210,7 +212,7 @@ describe("CLI - platform 命令与 record 动作", () => { }, }) ); - spies.push(spyOn(api, "listPlatforms").mockResolvedValue([mockPlatform] as any)); + spies.push(spyOn(apiApplications, "listPlatforms").mockResolvedValue([mockPlatform] as any)); spies.push(spyOn(api, "listPlatformEntities").mockResolvedValue([mockEntity] as any)); const res = await handlePlatformCommand( @@ -225,7 +227,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("record batch-edit --dry-run 生成安全合并预览且不发送真实写请求", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); spies.push( spyOn(api, "getRecordDetail").mockResolvedValue({ @@ -258,7 +260,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform records 支持 --sum 数学核算与 --group-by 分组统计", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue({ ...mockEntity, fields: [ @@ -301,7 +303,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform audit 支持 --check-continuous 与 --expect 基线离群诊断", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue({ ...mockEntity, fields: [ @@ -344,7 +346,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform update 支持 --where 声明式筛选与 --set 原地修改(含 --dry-run 与 --yes)", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue({ ...mockEntity, fields: [ @@ -408,7 +410,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform records 支持 --stats 画像统计(计算状态、重名与编码聚类)", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); spies.push( spyOn(api, "searchEntityRecords").mockResolvedValue({ @@ -463,7 +465,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform records 支持 --ndjson 流式逐行下发与 --flat 归一化", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); spies.push( spyOn(api, "searchEntityRecords").mockResolvedValue({ @@ -516,7 +518,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform records --all 拒绝直接全量输出,要求分页或流式文件", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); await expect( handlePlatformCommand( @@ -528,7 +530,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("rejects malformed batch predicates before fetching all records or calling the writer", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any)); const fetch = spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ data: [], total: 0 } as any); const write = spyOn(services, "batchSafeEditRecords").mockResolvedValue([]); @@ -540,7 +542,7 @@ describe("CLI - platform 命令与 record 动作", () => { it("platform gen-props 生成 MVEL 和 JS 格式的字段模板", async () => { spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any)); - spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any)); + spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any)); spies.push(spyOn(services, "resolveEntity").mockResolvedValue({ id: "E_contract", name: "合同", diff --git a/src/cli/commands/platform/app-info.ts b/src/cli/commands/platform/app-info.ts index 63d8b31..e116e3b 100644 --- a/src/cli/commands/platform/app-info.ts +++ b/src/cli/commands/platform/app-info.ts @@ -1,10 +1,5 @@ -import { - getImportResult, - listImportJobs, - listAllPlatforms, - listPlatformEntities, - listPlatforms, -} from "../../../domains/datalink/services.js"; +import { getImportResult, listImportJobs, listPlatformEntities } from "../../../domains/platform/datalink/services.js"; +import { listAllPlatforms, listPlatforms } from "../../../domains/platform/applications/services.js"; import { createClientsForCorp } from "../../helpers.js"; import { booleanOption, stringOption } from "../../parser.js"; import { printJson, printTable } from "../../printer.js"; diff --git a/src/cli/commands/platform/record-actions.ts b/src/cli/commands/platform/record-actions.ts index e53c590..cc415da 100644 --- a/src/cli/commands/platform/record-actions.ts +++ b/src/cli/commands/platform/record-actions.ts @@ -11,7 +11,7 @@ import { toggleRecordState, type BatchEditTargetItem, type SafeRecordEditOptions, -} from "../../../domains/datalink/services.js"; +} from "../../../domains/platform/datalink/services.js"; import { createClientsForCorp } from "../../helpers.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; import { printJson, printTable } from "../../printer.js"; diff --git a/src/cli/commands/platform/records.ts b/src/cli/commands/platform/records.ts index fe882b3..f4c0b65 100644 --- a/src/cli/commands/platform/records.ts +++ b/src/cli/commands/platform/records.ts @@ -12,9 +12,9 @@ import { parseExpectClause, searchEntityRecords, selectRecordFields, -} from "../../../domains/datalink/services.js"; -import type { DatalinkRecord } from "../../../domains/datalink/types.js"; -import type { LedgerContinuityReport } from "../../../domains/datalink/types.js"; +} from "../../../domains/platform/datalink/services.js"; +import type { DatalinkRecord } from "../../../domains/platform/datalink/types.js"; +import type { LedgerContinuityReport } from "../../../domains/platform/datalink/types.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js"; import { usageError } from "../../errors.js"; diff --git a/src/cli/commands/platform/shared.ts b/src/cli/commands/platform/shared.ts index f91125b..3261c8d 100644 --- a/src/cli/commands/platform/shared.ts +++ b/src/cli/commands/platform/shared.ts @@ -1,4 +1,5 @@ -import { resolveEntity, resolvePlatform } from "../../../domains/datalink/services.js"; +import { resolveEntity } from "../../../domains/platform/datalink/services.js"; +import { resolvePlatform } from "../../../domains/platform/applications/services.js"; import { createClientsForCorp } from "../../helpers.js"; import type { CliParsedArgs, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts index d43a8fa..80c52eb 100644 --- a/src/cli/commands/probe.ts +++ b/src/cli/commands/probe.ts @@ -1,6 +1,7 @@ +import * as apiApplications from "../../domains/platform/applications/services.js"; import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js"; import { createSessionClient, getEasoClient } from "../../core/http/index.js"; -import * as api from "../../domains/platform/services.js"; +import * as api from "../../domains/platform/workflow/services.js"; import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt, formatCorpEnvLabel } from "../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; @@ -93,7 +94,7 @@ export async function handleProbeCommand( let platforms: any[] = []; if (sessionClient) { try { - platforms = await api.listPlatforms(sessionClient, currentCorp.credentials.corpId); + platforms = await apiApplications.listBasicPlatforms(sessionClient, currentCorp.credentials.corpId); results.platformAccess = { status: "ok", totalPlatforms: platforms.length, diff --git a/src/cli/commands/review-compatibility.test.ts b/src/cli/commands/review-compatibility.test.ts index f71967e..1f832ab 100644 --- a/src/cli/commands/review-compatibility.test.ts +++ b/src/cli/commands/review-compatibility.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, spyOn } from "bun:test"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import * as services from "../../domains/platform/services.js"; +import * as services from "../../domains/platform/workflow/services.js"; import * as billApi from "../../domains/bill/api.js"; import * as cache from "../../core/cache/index.js"; import * as session from "../../core/http/session-client.js"; diff --git a/src/cli/commands/workflow-debug.test.ts b/src/cli/commands/workflow-debug.test.ts index 8b5d7f5..f17c5de 100644 --- a/src/cli/commands/workflow-debug.test.ts +++ b/src/cli/commands/workflow-debug.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, it, spyOn } from "bun:test"; import { handleWorkflowTest } from "./workflow/test.js"; import * as shared from "./workflow/shared.js"; -import * as services from "../../domains/platform/services.js"; +import * as services from "../../domains/platform/workflow/services.js"; import type { CliParsedArgs, CliRuntime } from "../types.js"; -import type { WorkflowTestReport } from "../../domains/platform/types.js"; +import type { WorkflowTestReport } from "../../domains/platform/workflow/types.js"; const runtime = { selectedCorp: { id: "mock-corp", name: "Mock测试企业", env: "test", isTest: true } as any, diff --git a/src/cli/commands/workflow-nodes-confirmation.test.ts b/src/cli/commands/workflow-nodes-confirmation.test.ts index 3af7628..9df0b07 100644 --- a/src/cli/commands/workflow-nodes-confirmation.test.ts +++ b/src/cli/commands/workflow-nodes-confirmation.test.ts @@ -1,7 +1,7 @@ import { expect, spyOn, test } from "bun:test"; import { parseArgs } from "../parser.js"; import { handleWorkflowCommand } from "./workflow/index.js"; -import * as services from "../../domains/platform/services.js"; +import * as services from "../../domains/platform/workflow/services.js"; test("node grant previews without a gateway call and requires explicit confirmation", async () => { const runtime = { selectedCorp: { id: "corp", credentials: { corpId: "corp" } }, jsonMode: true } as any; diff --git a/src/cli/commands/workflow-nodes-failure.test.ts b/src/cli/commands/workflow-nodes-failure.test.ts index 74b97d7..9cd9f47 100644 --- a/src/cli/commands/workflow-nodes-failure.test.ts +++ b/src/cli/commands/workflow-nodes-failure.test.ts @@ -1,7 +1,7 @@ import { expect, spyOn, test } from "bun:test"; import { handleWorkflowCommand } from "./workflow/index.js"; import { parseArgs } from "../parser.js"; -import * as services from "../../domains/platform/services.js"; +import * as services from "../../domains/platform/workflow/services.js"; test("failed grants retain gateway details and never report success", async () => { const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: false, saved: [], skipped: [], rawMessage: "permission denied" }); try { diff --git a/src/cli/commands/workflow-nodes.test.ts b/src/cli/commands/workflow-nodes.test.ts index bcb0df0..4748842 100644 --- a/src/cli/commands/workflow-nodes.test.ts +++ b/src/cli/commands/workflow-nodes.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test"; import { handleWorkflowCommand } from "./workflow/index.js"; -import * as services from "../../domains/platform/services.js"; -import * as api from "../../domains/platform/api.js"; +import * as services from "../../domains/platform/workflow/services.js"; +import * as api from "../../domains/platform/workflow/api.js"; import * as helpers from "../helpers.js"; import type { CliRuntime } from "../types.js"; import type { CorpConfig } from "../../core/config/types.js"; diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 9ca205d..2099fd5 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test"; import { handleWorkflowCommand } from "./workflow/index.js"; import * as helpers from "../helpers.js"; -import * as platformServices from "../../domains/platform/services.js"; +import * as platformServices from "../../domains/platform/workflow/services.js"; import type { CliRuntime } from "../types.js"; import type { CorpConfig } from "../../core/config/types.js"; diff --git a/src/cli/commands/workflow/README.workflow.md b/src/cli/commands/workflow/README.workflow.md new file mode 100644 index 0000000..2a1c52b --- /dev/null +++ b/src/cli/commands/workflow/README.workflow.md @@ -0,0 +1,24 @@ +# 工作流命令(workflow) + +[index.ts](./index.ts) 分发工作流及节点命令;[shared.ts](./shared.ts) 统一平台参数别名、客户端装配和代码节点摘要。业务实现由 [Platform 域](../../../domains/platform/README.platform.md) 与 [工作流子域](../../../domains/platform/workflow/README.workflow.md) 提供。 + +## 实现导航 + +| 文件 | 功能 | +|---|---| +| [list.ts](./list.ts)、[history.ts](./history.ts)、[job.ts](./job.ts) | 列表/详情/查找、版本历史、日志与执行详情 | +| [lifecycle.ts](./lifecycle.ts) | 启停与发布 | +| [draft.ts](./draft.ts) | 本地 patch、版本校验、保存及定向刷新 chooses | +| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[delete.ts](./delete.ts) | 创建、复制与删除 | +| [node.ts](./node.ts) | 节点操作和节点目录命令适配 | +| [analyze.ts](./analyze.ts)、[check.ts](./check.ts)、[diff.ts](./diff.ts) | 静态分析、健康检查与配置/执行差异 | +| [script.ts](./script.ts)、[test.ts](./test.ts) | 脚本校验、求值与工作流测试 | +| [tail.ts](./tail.ts)、[webhook.ts](./webhook.ts)、[enum.ts](./enum.ts) | 执行监听、Webhook 与业务枚举 | + +## 保存和执行契约 + +保存必须保留版本校验。主保存成功但 chooses 刷新失败时返回非零和 `remoteSaved: true`,`--in-place` 同步已保存版本;按返回的 `refresh-chooses` 命令恢复,避免重复主 PUT。 + +启用、发布、测试运行及 Webhook 可能产生业务副作用,沿用各子命令的预演和确认要求。`tail` 的超时、取消、快照与完成状态分别表达,不能把监听停止视为执行成功。 + +参数以 `hose-use workflow --help` 及子命令帮助为准;用户侧操作见 [workflow.md](../../../../skills/hose-use/references/workflow.md)。本目录测试和上级 `workflow*.test.ts` 覆盖入口、确认、错误及摘要契约。 diff --git a/src/cli/commands/workflow/analyze.ts b/src/cli/commands/workflow/analyze.ts index a9e5591..cd32c39 100644 --- a/src/cli/commands/workflow/analyze.ts +++ b/src/cli/commands/workflow/analyze.ts @@ -1,4 +1,4 @@ -import { getWorkflowDetail, getWorkflowAvailableNodes } from "../../../domains/platform/services.js"; +import { getWorkflowDetail, getWorkflowAvailableNodes } from "../../../domains/platform/workflow/services.js"; import { analyzeWorkflow, extractWorkflowSpecificationIds, diff --git a/src/cli/commands/workflow/check.ts b/src/cli/commands/workflow/check.ts index 0d82a45..f27ba95 100644 --- a/src/cli/commands/workflow/check.ts +++ b/src/cli/commands/workflow/check.ts @@ -1,4 +1,4 @@ -import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/services.js"; +import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/workflow/services.js"; import { WorkflowAlertStore } from "../../../domains/platform/workflow/alert/index.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; diff --git a/src/cli/commands/workflow/copy.ts b/src/cli/commands/workflow/copy.ts index 3444f90..55ba7c4 100644 --- a/src/cli/commands/workflow/copy.ts +++ b/src/cli/commands/workflow/copy.ts @@ -1,4 +1,4 @@ -import { copyWorkflow, getWorkflowDetail } from "../../../domains/platform/services.js"; +import { copyWorkflow, getWorkflowDetail } from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { printJson, printKeyValue } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; diff --git a/src/cli/commands/workflow/create.ts b/src/cli/commands/workflow/create.ts index 622c775..e673853 100644 --- a/src/cli/commands/workflow/create.ts +++ b/src/cli/commands/workflow/create.ts @@ -1,4 +1,4 @@ -import { createWorkflow } from "../../../domains/platform/services.js"; +import { createWorkflow } from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { printJson, printKeyValue } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; diff --git a/src/cli/commands/workflow/delete.ts b/src/cli/commands/workflow/delete.ts index 7c7d034..6b58ff1 100644 --- a/src/cli/commands/workflow/delete.ts +++ b/src/cli/commands/workflow/delete.ts @@ -1,4 +1,4 @@ -import { deleteWorkflow, getWorkflowDetail } from "../../../domains/platform/services.js"; +import { deleteWorkflow, getWorkflowDetail } from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { printJson } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; diff --git a/src/cli/commands/workflow/diff.ts b/src/cli/commands/workflow/diff.ts index 633f7f5..0bbe811 100644 --- a/src/cli/commands/workflow/diff.ts +++ b/src/cli/commands/workflow/diff.ts @@ -4,7 +4,7 @@ import { getJob, getJobExecutionTree, getWorkflowSnapshot, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { printJson, printTable } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/draft.ts b/src/cli/commands/workflow/draft.ts index c0a5614..5328cc9 100644 --- a/src/cli/commands/workflow/draft.ts +++ b/src/cli/commands/workflow/draft.ts @@ -1,8 +1,8 @@ import { readFileSync, writeFileSync } from "node:fs"; import { EkbError } from "../../../core/errors.js"; -import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/services.js"; +import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/workflow/services.js"; import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js"; -import { WorkflowDetailSchema } from "../../../domains/platform/types.js"; +import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js"; import { applyWorkflowPathPatch, beginWorkflowSave, diff --git a/src/cli/commands/workflow/enum.ts b/src/cli/commands/workflow/enum.ts index 79c03bf..068413a 100644 --- a/src/cli/commands/workflow/enum.ts +++ b/src/cli/commands/workflow/enum.ts @@ -1,7 +1,7 @@ import { resolveWorkflowEnumOptions, SYSTEM_WORKFLOW_ACTION_ENUMS, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/history.ts b/src/cli/commands/workflow/history.ts index 7cb3901..daea04f 100644 --- a/src/cli/commands/workflow/history.ts +++ b/src/cli/commands/workflow/history.ts @@ -1,4 +1,4 @@ -import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js"; +import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/job.ts b/src/cli/commands/workflow/job.ts index 8fb3716..d7629be 100644 --- a/src/cli/commands/workflow/job.ts +++ b/src/cli/commands/workflow/job.ts @@ -1,18 +1,6 @@ -import { - extractFailureExecutions, - findExecutionNode, - flattenExecutionTree, - getExecutionLogs, - getJob, - getJobExecutionLevel, - getJobExecutionTree, - getJobFailedExecutions, - getWorkflowDetail, - isTaskExecutionFailed, - listPlatforms, - explainConditionBranches, -} from "../../../domains/platform/services.js"; -import type { WorkflowTaskExecution } from "../../../domains/platform/types.js"; +import { extractFailureExecutions, findExecutionNode, flattenExecutionTree, getExecutionLogs, getJob, getJobExecutionLevel, getJobExecutionTree, getJobFailedExecutions, getWorkflowDetail, isTaskExecutionFailed, explainConditionBranches } from "../../../domains/platform/workflow/services.js"; +import { listBasicPlatforms as listPlatforms } from "../../../domains/platform/applications/services.js"; +import type { WorkflowTaskExecution } from "../../../domains/platform/workflow/types.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; diff --git a/src/cli/commands/workflow/lifecycle.ts b/src/cli/commands/workflow/lifecycle.ts index 13b2d0a..a30a381 100644 --- a/src/cli/commands/workflow/lifecycle.ts +++ b/src/cli/commands/workflow/lifecycle.ts @@ -1,4 +1,4 @@ -import { toggleWorkflow } from "../../../domains/platform/services.js"; +import { toggleWorkflow } from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { printJson } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; diff --git a/src/cli/commands/workflow/list.ts b/src/cli/commands/workflow/list.ts index e07c3d2..bdf17bc 100644 --- a/src/cli/commands/workflow/list.ts +++ b/src/cli/commands/workflow/list.ts @@ -2,7 +2,7 @@ import { findWorkflowsByTaskType, getWorkflowDetail, listAllWorkflows, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { createClientsForCorp } from "../../helpers.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; diff --git a/src/cli/commands/workflow/node.ts b/src/cli/commands/workflow/node.ts index d8bb95d..74a4b39 100644 --- a/src/cli/commands/workflow/node.ts +++ b/src/cli/commands/workflow/node.ts @@ -9,7 +9,7 @@ import { applyNodeMapping, getWorkflowAvailableNodes, grantWorkflowNodes, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { GRAY_NODES_CATALOG, findGrayNode, diff --git a/src/cli/commands/workflow/save-partial.test.ts b/src/cli/commands/workflow/save-partial.test.ts index 77fe256..c555b36 100644 --- a/src/cli/commands/workflow/save-partial.test.ts +++ b/src/cli/commands/workflow/save-partial.test.ts @@ -8,7 +8,7 @@ import { parseArgs } from "../../parser.js"; import { cliErrorResult } from "../../runner.js"; import { normalizeCliArgs, tokenizeCommand } from "../../../server.js"; import { handleWorkflowCommand } from "./index.js"; -import { WorkflowDetailSchema } from "../../../domains/platform/types.js"; +import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js"; import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js"; import type { CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/script-json.test.ts b/src/cli/commands/workflow/script-json.test.ts index 874e787..57e7f9d 100644 --- a/src/cli/commands/workflow/script-json.test.ts +++ b/src/cli/commands/workflow/script-json.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { parseArgs } from "../../parser.js"; import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"; import * as shared from "./shared.js"; -import * as services from "../../../domains/platform/services.js"; +import * as services from "../../../domains/platform/workflow/services.js"; test("all local and remote script JSON branches return reports and honor output files", async () => { const client = spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any); diff --git a/src/cli/commands/workflow/script.ts b/src/cli/commands/workflow/script.ts index f364192..c1635b6 100644 --- a/src/cli/commands/workflow/script.ts +++ b/src/cli/commands/workflow/script.ts @@ -8,7 +8,7 @@ import { lintMvelCode, executeJavaScriptSandbox, executeMvelSandbox, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { stringOption, booleanOption } from "../../parser.js"; import { printJson, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/shared.ts b/src/cli/commands/workflow/shared.ts index 6267531..457403e 100644 --- a/src/cli/commands/workflow/shared.ts +++ b/src/cli/commands/workflow/shared.ts @@ -1,4 +1,4 @@ -import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/services.js"; +import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/workflow/services.js"; import { stringOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import type { CliParsedArgs, CliRuntime } from "../../types.js"; @@ -31,7 +31,7 @@ export async function createWorkflowDetailClient( if (!platformId) { try { const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id; - const { listPlatforms } = await import("../../../domains/platform/services.js"); + const { listBasicPlatforms: listPlatforms } = await import("../../../domains/platform/applications/services.js"); const platforms = await listPlatforms(clients.ekbClient, corpId); const firstActive = platforms.find((p) => p.active) ?? platforms[0]; platformId = firstActive?.id; @@ -58,7 +58,7 @@ export async function createJobPiperClient( const clients = await createClientsForCorp(corp); try { const corpId = corp.corpId || corp.id; - const { listPlatforms } = await import("../../../domains/platform/services.js"); + const { listBasicPlatforms: listPlatforms } = await import("../../../domains/platform/applications/services.js"); const platforms = await listPlatforms(clients.ekbClient, corpId); const firstActive = platforms.find((p) => p.active) ?? platforms[0]; if (firstActive?.id) { diff --git a/src/cli/commands/workflow/summaries.test.ts b/src/cli/commands/workflow/summaries.test.ts index e1caada..9e75e2b 100644 --- a/src/cli/commands/workflow/summaries.test.ts +++ b/src/cli/commands/workflow/summaries.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { extractCodeNodeSummaries } from "./shared.js"; -import { flattenExecutionTree } from "../../../domains/platform/services.js"; +import { flattenExecutionTree } from "../../../domains/platform/workflow/services.js"; test("test and job summaries retain nested execution containers and repeated loop executions", () => { const tree = [{ id: "loop", type: "every", children: [ diff --git a/src/cli/commands/workflow/tail.ts b/src/cli/commands/workflow/tail.ts index d9c1b29..7e1e057 100644 --- a/src/cli/commands/workflow/tail.ts +++ b/src/cli/commands/workflow/tail.ts @@ -2,7 +2,7 @@ import { watchWorkflowPipeline, formatWatchEvent, type WorkflowWatchEvent, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { stringOption, numberOption, booleanOption } from "../../parser.js"; import { printJson } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/test.ts b/src/cli/commands/workflow/test.ts index 252e234..4638311 100644 --- a/src/cli/commands/workflow/test.ts +++ b/src/cli/commands/workflow/test.ts @@ -7,7 +7,7 @@ import { getWorkflowSampleData, runWorkflowDebugTest, type WorkflowTriggerCategory, -} from "../../../domains/platform/services.js"; +} from "../../../domains/platform/workflow/services.js"; import { stringOption, booleanOption, numberOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; diff --git a/src/cli/commands/workflow/webhook.test.ts b/src/cli/commands/workflow/webhook.test.ts index 9698aeb..f936add 100644 --- a/src/cli/commands/workflow/webhook.test.ts +++ b/src/cli/commands/workflow/webhook.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test"; import { handleWebhookCommand } from "./webhook.js"; import * as shared from "./shared.js"; -import * as services from "../../../domains/platform/services.js"; +import * as services from "../../../domains/platform/workflow/services.js"; import type { CliParsedArgs, CliRuntime } from "../../types.js"; function createMockRuntime(overrides: Partial = {}): CliRuntime { diff --git a/src/cli/commands/workflow/webhook.ts b/src/cli/commands/workflow/webhook.ts index 06da932..c78e20f 100644 --- a/src/cli/commands/workflow/webhook.ts +++ b/src/cli/commands/workflow/webhook.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from "node:fs"; import ky from "ky"; -import { getWorkflowDetail } from "../../../domains/platform/services.js"; +import { getWorkflowDetail } from "../../../domains/platform/workflow/services.js"; import { getBillByCodeOrId } from "../../../domains/bill/tools.js"; import { stringOption } from "../../parser.js"; import { printJson, printKeyValue } from "../../printer.js"; diff --git a/src/cli/stream-output.test.ts b/src/cli/stream-output.test.ts index d882daa..4c1bbe7 100644 --- a/src/cli/stream-output.test.ts +++ b/src/cli/stream-output.test.ts @@ -9,7 +9,7 @@ import { createServer, HOSE_CLI_TOOL_NAME } from "../server.js"; import { startHttpServer } from "../http/server.js"; import * as helpers from "./helpers.js"; import * as shared from "./commands/platform/shared.js"; -import * as records from "../domains/datalink/services.js"; +import * as records from "../domains/platform/datalink/services.js"; describe("NDJSON output destinations across CLI, MCP and HTTP", () => { const spies: Array<{ mockRestore(): void }> = []; diff --git a/src/core/auth/README.auth.md b/src/core/auth/README.auth.md new file mode 100644 index 0000000..3249e9d --- /dev/null +++ b/src/core/auth/README.auth.md @@ -0,0 +1,24 @@ +# 认证与凭证存储(auth) + +本目录提供认证协议、账号与企业换票、凭证导入及跨进程 Token 存储。它属于 [Core 基础设施](../README.core.md),不负责业务命令解析和 UI 输出。 + +## 文件分工 + +| 文件 | 职责 | +|---|---| +| [login.ts](./login.ts) | 账密、短信、浏览器登录,账号企业枚举、切换和续期 | +| [openapi-v1.ts](./openapi-v1.ts) | 应用凭证换票、临时授权、密钥选择和标准域名探测 | +| [openapi-onboard.ts](./openapi-onboard.ts) | OpenAPI 持久化建档、seal-use 同步与企业提权 | +| [link-import.ts](./link-import.ts) | 协助链接、Headers/cURL 解析导入与相关 Token 失效 | +| [account-store.ts](./account-store.ts) | 主账号和企业关联信息持久化 | +| [token-store.ts](./token-store.ts) | 按企业保存子域 Token,支持跨进程复用 | +| [assist-platform-store.ts](./assist-platform-store.ts) | 协助平台会话的独立存取 | +| [types.ts](./types.ts) | 认证数据的 Zod 模型与类型 | + +## 依赖与身份边界 + +Session 续期可使用主账号或企业持久化 OpenAPI 凭证;HTTP 客户端负责请求时的认证衔接,见 [http/](../http/README.http.md)。企业配置结构与加载由 [config/](../config) 管理,通用数据库由 [db/](../db) 管理。 + +不要混用不同企业、账号或子域的 Token。凭证变更和导入需要同步处理相关 Token 缓存失效,不能只替换内存对象。路径由各 store 的解析函数及 `HOSE_*` 环境变量控制,测试使用临时文件与企业目录,不接触个人真实凭证。 + +新增协议应维持基础设施依赖方向,不从本层导入业务域或 CLI。持久化内容不进入日志、README 示例和版本库;对外错误沿用统一错误体系。 diff --git a/src/core/cache/README.cache.md b/src/core/cache/README.cache.md new file mode 100644 index 0000000..de61199 --- /dev/null +++ b/src/core/cache/README.cache.md @@ -0,0 +1,23 @@ +# 多级数据缓存(cache) + +本目录为业务查询提供可复用的数据缓存,与 [auth/token-store](../auth/token-store.ts) 的认证 Token 存储分开。上级职责见 [Core 说明](../README.core.md)。 + +## 实现层次 + +| 文件 | 职责 | +|---|---| +| [types.ts](./types.ts) | `ICache`、条目、命名空间与 TTL 选项 | +| [memory.ts](./memory.ts) | L1 内存缓存 | +| [sqlite.ts](./sqlite.ts) | L2 SQLite 缓存,复用 core/db 的连接 | +| [multi-level.ts](./multi-level.ts) | 读写两级缓存和 `withCache` 并发请求合并 | +| [index.ts](./index.ts) | 统一导出、全局单例及独立实例工厂 | + +## 行为与调用约定 + +读取先查 L1,再查 L2;命中 L2 时回填 L1 并保留到期时间。写入同步两级;默认 TTL 为 10 分钟,可按调用配置。命名空间与 key 共同区分条目,业务方需要在 key 中表达企业、查询条件等身份维度,不能跨企业复用同一个业务键。 + +`withCache` 合并同命名空间和 key 的在途请求;`forceRefresh` 绕过已有缓存读取,但仍可能复用同键正在执行的请求。需要纯内存实例时可传入 `l2: null`。 + +`clear(namespace)` 可限定命名空间;无参数清空缓存。`resetGlobalCache` 会清空已有实例并重置单例,隔离测试应使用临时数据库,不能把它当作只清内存的操作。 + +[cache.test.ts](./cache.test.ts) 覆盖 TTL、命名空间、持久化协同与并发行为。新增持久化表仍由 [core/db](../db) 的迁移管理,不在缓存构造函数中另建私有数据库体系。 diff --git a/src/core/http/README.http.md b/src/core/http/README.http.md new file mode 100644 index 0000000..172d49b --- /dev/null +++ b/src/core/http/README.http.md @@ -0,0 +1,25 @@ +# HTTP 客户端与认证衔接(http) + +本目录封装语义化 HTTP 客户端、指纹、换票和鉴权续期,是 [Core](../README.core.md) 的传输基础设施。业务 URL、响应模型与业务错误校验由各域 `api.ts` 管理,不放进通用工厂。 + +## 客户端选择 + +| 文件 | 使用场景 | +|---|---| +| [factory.ts](./factory.ts) | Ky 底层客户端和带鉴权恢复的工厂 | +| [session-client.ts](./session-client.ts) | 合思用户 Session 请求与续期 | +| [openapi-client.ts](./openapi-client.ts) | 应用凭证换取 OpenAPI Token 并构造请求 | +| [unity-client.ts](./unity-client.ts) | 应用中心、Unity/EASO 换票及企业集群寻址 | +| [script-engine-client.ts](./script-engine-client.ts) | Piper 脚本引擎客户端与认证缓存 | +| [assist-platform-client.ts](./assist-platform-client.ts) | 协助平台客户端 | +| [sso-client.ts](./sso-client.ts) | SSO 登录请求与二维码状态查询 | +| [fingerprint.ts](./fingerprint.ts) | 统一浏览器指纹和请求头配置 | +| [index.ts](./index.ts) | 对外导出入口 | + +## 重放与错误边界 + +鉴权失效时按工厂配置续期并重放一次,重放响应仍检查 HTTP 状态与鉴权错误头,包括 HTTP 200 携带鉴权错误标记的情况。持续鉴权失败应抛认证异常,不递归换票;普通 HTTP 失败保留客户端原有错误语义。 + +客户端依据目标企业与协议创建,不能跨企业复用带身份的实例或 Token。缓存失效与凭证存储衔接见 [auth/](../auth/README.auth.md)。日志不得输出认证头或完整会话链接。 + +[replay-contract.test.ts](./replay-contract.test.ts)、[clients.test.ts](./clients.test.ts)、Session 与续期测试共同验证客户端协议。变更恢复逻辑时同时检查重放次数、请求体保留和最终响应,避免把传输成功误当作业务成功。 diff --git a/src/domains/README.domains.md b/src/domains/README.domains.md index 391ba16..98e9c22 100644 --- a/src/domains/README.domains.md +++ b/src/domains/README.domains.md @@ -2,12 +2,11 @@ 本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。 -## 当前域(共 15 个) +## 当前域(共 14 个) | 域 | 内部形态 | 说明 | 详细文档 | |---|---|---|---| -| `platform/` | `api / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) | -| `datalink/` | `api / services / fields / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) | +| `platform/` | `applications / datalink / workflow` | 自建应用平台:应用元数据、业务对象与记录、工作流配置与执行 | [README.platform.md](./platform/README.platform.md) | | `bill/` | `api / tools / create / copy / submit / templates / write / draft-validation / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) | | `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) | | `assist-platform/` | `api / services / types` | 合思协助平台(Unity 运营中心)多租户检索、工单匹配、指定代客员工免密直通与落盘提权 | [README.assist-platform.md](./assist-platform/README.assist-platform.md) | @@ -29,12 +28,12 @@ - `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用 - `types.ts`:Zod schema 与类型定义 2. **扩展复合形态**(有明确职责拆分理由): - - `platform/` 与 `datalink/`:使用 `services.ts` 提供跨应用聚合、台账健康度审计、批量安全编辑与对 `api.ts` 的服务级门面封装 + - `platform/` 的 applications、datalink 与 workflow 子模块:使用 `services.ts` 提供跨应用聚合、台账健康度审计、批量安全编辑与对 `api.ts` 的服务级门面封装 - `bill/`:独立拆分 `translator.ts` 负责复杂单据/审批流到结构化 Markdown 的纯函数转译 - `approval/`:采用 `parser.ts`(DSL 解析)+ `gateway.ts`(确定性仲裁门禁)+ `repository.ts`(基于 `core/db` 的数据访问)+ `service.ts`(业务编排) - `events/`:组合 `task/` 与 `message/` 域的 `tools.ts` 实现轮询(`poller.ts`),并通过 `store.ts` 落盘至 `core/db` - `assist-platform/`:使用 `services.ts` 封装合思运营平台多租户检索、工单匹配、指定代客员工定位、免密直通换票及与租户存储的联动落盘提权 3. **边界与异常约束**(由 `src/cli/architecture-boundaries.test.ts` 强制校验): - - 任何入口层(`src/cli/**`, `src/http/**`, `src/server.ts`, `src/cli.ts`, `src/aipro-cli.ts`)严禁直接导入 `domains/*/api.ts` + - 任何入口层(`src/cli/**`, `src/http/**`, `src/server.ts`, `src/cli.ts`, `src/aipro-cli.ts`)严禁直接导入 `domains/**/api.ts` - `domains/*` 严禁反向导入 `cli/`、`http/` 或顶层入口文件 - `domains/*` 统一抛出 `EkbError` 子类(定义在 `src/core/errors.ts`) diff --git a/src/domains/datalink/services.ts b/src/domains/datalink/services.ts deleted file mode 100644 index ce78c2d..0000000 --- a/src/domains/datalink/services.ts +++ /dev/null @@ -1,1426 +0,0 @@ -import type { KyInstance } from "ky"; -import * as api from "./api.js"; -import { ValidationError } from "../../core/errors.js"; -import { resolveDatalinkField } from "./fields.js"; -import type { - DatalinkEntity, - DatalinkField, - DatalinkPlatformDetail, - DatalinkRecord, - DatalinkRecordEditPayload, - DatalinkRecordPage, - AggregateFieldStats, - GroupAggregateResult, - LedgerAggregateReport, - ContinuityIssue, - LedgerContinuityReport, - NormalizedDatalinkRecord, - DatalinkRecordStats, -} from "./types.js"; - -export type { SafeRecordEditOptions } from "./api.js"; - -export function listPlatforms(...args: Parameters) { - return api.listPlatforms(...args); -} - -export function listAllPlatforms(...args: Parameters) { - return api.listAllPlatforms(...args); -} - -export function getPlatform(...args: Parameters) { - return api.getPlatform(...args); -} - -export function listPlatformEntities(...args: Parameters) { - return api.listPlatformEntities(...args); -} - -export function searchEntityRecords(...args: Parameters) { - return api.searchEntityRecords(...args); -} - -export function listImportJobs(...args: Parameters) { - return api.listImportJobs(...args); -} - -export function getImportResult(...args: Parameters) { - return api.getImportResult(...args); -} - -export function toggleRecordState(...args: Parameters) { - return api.toggleRecordState(...args); -} - -export function getRecordDetail(...args: Parameters) { - return api.getRecordDetail(...args); -} - -export function getRecordFormSchema(...args: Parameters) { - return api.getRecordFormSchema(...args); -} - -export function editRecord(...args: Parameters) { - return api.editRecord(...args); -} - -export function buildSafeRecordEditPayload(...args: Parameters) { - return api.buildSafeRecordEditPayload(...args); -} - -export function safeEditRecord(...args: Parameters) { - return api.safeEditRecord(...args); -} - -export function recomputeRecordLedger(...args: Parameters) { - return api.recomputeRecordLedger(...args); -} - -function matches(value: unknown, target: string): boolean { - return typeof value === "string" && value.toLowerCase() === target.toLowerCase(); -} - -export async function resolvePlatform( - client: KyInstance, - corpId: string, - target: string -): Promise { - const platforms = await api.listPlatforms(client, corpId); - const found = platforms.find((platform) => - [platform.id, platform.name, platform.code].some((value) => matches(value, target)) - ); - return found ? api.getPlatform(client, corpId, found.id) : undefined; -} - -export async function resolveEntity( - client: KyInstance, - corpId: string, - platform: DatalinkPlatformDetail, - target: string -): Promise { - const entities = await api.listPlatformEntities(client, corpId, platform.id); - return entities.find((entity) => - [entity.id, entity.name, entity.code].some((value) => matches(value, target)) - ); -} - -export interface BuildKeywordFilterOptions { - entity?: DatalinkEntity; - searchFields?: string[]; -} - -/** - * 格式化服务端 filterBy 字段表达式。 - * 针对 DataLink 特性: - * - 动态业务字段(E_ 前缀)自动附加 form. 命名空间 - * - money 货币复合对象自动下钻到 .standard 标准字符串 - * - number 数值字段支持比较运算符 - */ -export function formatServerFieldExpr( - fieldKey: string, - op: string, - rawVal: string, - entity?: DatalinkEntity -): string { - const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined; - const targetKey = resolved?.name || fieldKey; - const isCustom = targetKey.startsWith("E_"); - const serverPath = isCustom ? `form.${targetKey}` : targetKey; - const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); - const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== ""; - - // Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... }) - if (resolved?.type === "money") { - const moneyPath = `${serverPath}.standard`; - const num = Number(rawVal); - const withDec = !Number.isNaN(num) && !rawVal.includes(".") ? `${rawVal}.00` : rawVal; - if (op === "=" || op === "==") { - if (withDec !== rawVal) { - return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`; - } - return `${moneyPath}=="${escaped}"`; - } - if (op === "!=") { - return `${moneyPath}!="${escaped}"`; - } - return `${moneyPath}.containsIgnoreCase("${escaped}")`; - } - - // Number 字段 - if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) { - if (op === "~" || op === "=~" || op === ":") { - return `${serverPath}.containsIgnoreCase("${escaped}")`; - } - const cmp = op === "=" ? "==" : op; - return `${serverPath}${cmp}${rawVal}`; - } - - // Text / Ref / Other 字段 - if (op === "~" || op === "=~" || op === ":") { - return `${serverPath}.containsIgnoreCase("${escaped}")`; - } - if (op === "!=") { - return `${serverPath}!="${escaped}"`; - } - return `${serverPath}=="${escaped}"`; -} - -export function buildKeywordFilter( - keyword: string, - options?: BuildKeywordFilterOptions -): string { - const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); - const conds: string[] = [ - `name.containsIgnoreCase("${escaped}")`, - `code.containsIgnoreCase("${escaped}")`, - ]; - - if (options?.entity && options.searchFields && options.searchFields.length > 0) { - for (const searchField of options.searchFields) { - const resolved = resolveEntityField(options.entity, searchField); - const targetName = resolved?.name || searchField; - if (targetName && targetName !== "name" && targetName !== "code") { - const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity); - conds.push(expr); - } - } - } - - return `(${conds.join("||")})&&(active.in(true,false))`; -} - -/** - * 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。 - * 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。 - */ -export function buildServerFieldFilter( - filterInput: string, - entity?: DatalinkEntity -): string { - const trimmed = filterInput.trim(); - if ( - trimmed.startsWith("(") || - trimmed.includes(".containsIgnoreCase(") || - trimmed.includes(".in(") || - trimmed.includes("==") - ) { - return trimmed; - } - - // 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用" - const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/); - if (!match) return trimmed; - - const rawKey = match[1].trim(); - const op = match[2]; - const rawVal = match[3].trim().replace(/^["']|["']$/g, ""); - - const expr = formatServerFieldExpr(rawKey, op, rawVal, entity); - return expr ? `(${expr})&&(active.in(true,false))` : trimmed; -} - -export function selectRecordFields( - record: Record, - fields: string[], - definitions: DatalinkField[] = [] -): Record { - if (fields.length === 0) return record; - const dataLink = - record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) - ? (record.dataLink as Record) - : record; - const selected: Record = {}; - const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields) - ? record.fields as Record - : undefined; - for (const selector of fields) { - const definition = definitions.find( - (field) => field.name === selector || field.label === selector - ); - const sourceName = definition?.name ?? selector; - const label = definition?.label || selector; - if (sourceName in dataLink) selected[label] = dataLink[sourceName]; - else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label]; - else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName]; - else if (normalizedFields) { - const systemName = sourceName.replace(/^E_.+_/, ""); - if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName]; - } - } - return record.dataLink && typeof record.dataLink === "object" - ? { ...record, dataLink: selected } - : selected; -} - -/** - * 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。 - */ -export async function fetchAllEntityRecords( - client: KyInstance, - corpId: string, - entityId: string, - options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} -): Promise { - const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); - let start = 0; - let total = 0; - const allData: DatalinkRecord[] = []; - let firstPage: DatalinkRecordPage | undefined; - - while (true) { - const page = await api.searchEntityRecords(client, corpId, entityId, { - start, - count: pageSize, - filterBy: options.filterBy, - orderBy: options.orderBy, - }); - firstPage ??= page; - total = page.total; - if (page.data.length === 0) break; - allData.push(...page.data); - start += page.data.length; - if (allData.length >= total || page.data.length < pageSize) { - break; - } - } - - return { - total: Math.max(total, allData.length), - data: allData, - actions: firstPage?.actions ?? [], - components: firstPage?.components ?? [], - path: firstPage?.path, - template: firstPage?.template, - }; -} - -/** - * 流式异步迭代器:逐页拉取并逐条产出业务对象记录。 - * 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。 - */ -export async function* iterateAllEntityRecords( - client: KyInstance, - corpId: string, - entityId: string, - options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} -): AsyncGenerator { - const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); - let start = 0; - let total = 0; - let yielded = 0; - - while (true) { - const page = await api.searchEntityRecords(client, corpId, entityId, { - start, - count: pageSize, - filterBy: options.filterBy, - orderBy: options.orderBy, - }); - total = page.total; - if (page.data.length === 0) break; - for (const record of page.data) { - yield record; - yielded++; - } - start += page.data.length; - if (yielded >= total || page.data.length < pageSize) { - break; - } - } -} - -/** - * 将数据互联原始报文规范化为标准、扁平、脱敏于动态前缀的结构。 - * 彻底消除 r.id vs r.dataLink.id 以及 E__ 动态前缀的困扰。 - */ -export function normalizeDatalinkRecord( - rawRecord: DatalinkRecord, - entity?: DatalinkEntity, - options: { includeRaw?: boolean } = {} -): NormalizedDatalinkRecord { - const dl = - rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink) - ? (rawRecord.dataLink as Record) - : (rawRecord as Record); - - const entityId = String(entity?.id ?? dl.entityId ?? rawRecord.entityId ?? ""); - const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId; - - const id = String(dl.id ?? rawRecord.id ?? ""); - const active = (dl.active ?? rawRecord.active) !== false; - const createTime = (dl.createTime ?? rawRecord.createTime ?? null) as number | null; - const updateTime = (dl.updateTime ?? rawRecord.updateTime ?? null) as number | null; - - const nameField = entity?.fields.find( - (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") - ); - const codeField = entity?.fields.find( - (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") - ); - - const name = String( - dl.name ?? - dl["名称"] ?? - (nameField ? dl[nameField.name] : undefined) ?? - (bareEntityId ? dl[`E_${bareEntityId}_name`] : undefined) ?? - "" - ); - - const code = String( - dl.code ?? - dl["编码"] ?? - (codeField ? dl[codeField.name] : undefined) ?? - (bareEntityId ? dl[`E_${bareEntityId}_code`] : undefined) ?? - "" - ); - - const fields: Record = {}; - if (entity?.fields) { - for (const field of entity.fields) { - if (field.name === nameField?.name || field.name === codeField?.name) continue; - const keyCandidates = [ - field.name, - bareEntityId ? `E_${bareEntityId}_${field.name}` : undefined, - field.label, - ].filter(Boolean) as string[]; - - let val: unknown = undefined; - for (const key of keyCandidates) { - if (key in dl) { - val = dl[key]; - break; - } - } - - if (val !== undefined && val !== null) { - if (typeof val === "object" && !Array.isArray(val)) { - const obj = val as Record; - if ("standard" in obj) { - val = obj.standard; - } else if ("name" in obj && typeof obj.name === "string" && obj.name) { - val = obj.name; - } else { - let targetDataLink: Record | undefined = undefined; - if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) { - targetDataLink = obj.dataLink as Record; - } else if ("data" in obj && typeof obj.data === "object" && obj.data && "dataLink" in (obj.data as Record)) { - targetDataLink = (obj.data as Record).dataLink as Record; - } - - if (targetDataLink) { - const form = (targetDataLink.form && typeof targetDataLink.form === "object" ? targetDataLink.form : {}) as Record; - const combined = { ...targetDataLink, ...form }; - let subDisplay: string | undefined = undefined; - for (const [k, v] of Object.entries(combined)) { - if (typeof v === "string" && v.trim() && (k === "name" || k === "title" || k === "名称" || k === "标题" || k.endsWith("_name") || k.endsWith("_title"))) { - subDisplay = v; - break; - } - } - if (!subDisplay) { - for (const [k, v] of Object.entries(combined)) { - if (typeof v === "string" && v.trim() && (k === "code" || k === "编码" || k.endsWith("_code") || k.includes("编号"))) { - subDisplay = v; - break; - } - } - } - val = subDisplay || (targetDataLink.id ? String(targetDataLink.id) : undefined) || (obj.id ? String(obj.id) : undefined); - } else if (obj.id && typeof obj.id === "string") { - val = obj.id; - } - } - } - fields[field.label || field.name] = val; - } - } - } - - return { - id, - code, - name, - active, - createTime, - updateTime, - fields, - ...(options.includeRaw ? { raw: rawRecord } : {}), - }; -} - -/** - * 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。 - * 既可接收全量内存数组,也可配合流式生成器在 O(1) 内存下在线累加计算。 - */ -export function calculateEntityRecordStats( - records: Iterable, - entity?: DatalinkEntity, - explicitTotal?: number -): DatalinkRecordStats { - let total = 0; - let activeCount = 0; - let inactiveCount = 0; - - const namesMap = new Map(); - const patternsMap = new Map(); - - let earliestCreate: number | null = null; - let latestUpdate: number | null = null; - - for (const raw of records) { - total++; - const norm = normalizeDatalinkRecord(raw, entity); - if (norm.active) activeCount++; - else inactiveCount++; - - if (norm.createTime && typeof norm.createTime === "number") { - if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime; - } - if (norm.updateTime && typeof norm.updateTime === "number") { - if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime; - } - - // 统计名称重名与状态交叉 - if (norm.name) { - if (!namesMap.has(norm.name)) { - namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 }); - } - const nStats = namesMap.get(norm.name)!; - nStats.total++; - if (norm.active) nStats.active++; - else nStats.inactive++; - } - - // 统计编码结构聚类 - const code = norm.code || "EMPTY"; - const pattern = code - .replace(/\d{8}/g, "YYYYMMDD") - .replace(/\d{6}/g, "SEQ6") - .replace(/\d+/g, "N"); - - if (!patternsMap.has(pattern)) { - patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 }); - } - const pStats = patternsMap.get(pattern)!; - pStats.count++; - if (norm.active) pStats.activeCount++; - else pStats.inactiveCount++; - } - - const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total; - const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%"; - - let duplicateNamesCount = 0; - let mixedStatusNamesCount = 0; - for (const n of namesMap.values()) { - if (n.total > 1) duplicateNamesCount++; - if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++; - } - - const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count); - - const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null); - - return { - total: finalTotal, - activeCount, - inactiveCount, - activeRate, - uniqueNames: namesMap.size, - duplicateNamesCount, - mixedStatusNamesCount, - codePatterns, - earliestCreateTime: formatDate(earliestCreate), - latestUpdateTime: formatDate(latestUpdate), - }; -} - -export interface DatalinkAuditIssue { - recordId: string; - recordCode: string; - recordName: string; - active: boolean; - type: - | "MISSING_FIELD" - | "DISABLED_REFERENCE" - | "CROSS_LEDGER_MISSING_SYNC" - | "CROSS_LEDGER_MISMATCH"; - field: string; - fieldLabel: string; - message: string; - linkedField?: string; - linkedFieldLabel?: string; - linkedRecordId?: string; - actualId?: string; - actualName?: string; - expectedId?: string; - expectedName?: string; -} - -export interface DatalinkAuditReport { - entityId: string; - entityName: string; - totalRecords: number; - auditedRecords: number; - healthyRecords: number; - affectedRecordCount: number; - issueCount: number; - summary: { - missingFieldCount: number; - disabledReferenceCount: number; - crossLedgerMissingSyncCount: number; - crossLedgerMismatchCount: number; - }; - issues: DatalinkAuditIssue[]; - suggestedPatches: Array<{ - id: string; - code: string; - name: string; - form: Record; - reason: string; - }>; -} - -function isEmptyFieldValue(value: unknown): boolean { - if (value === undefined || value === null || value === "") return true; - if (Array.isArray(value)) return value.length === 0; - if (typeof value === "object") { - const obj = value as Record; - if ("id" in obj) { - return obj.id === undefined || obj.id === null || obj.id === ""; - } - if ("standard" in obj) { - return obj.standard === undefined || obj.standard === null || obj.standard === ""; - } - return Object.keys(obj).length === 0; - } - return false; -} - -function extractRefIdAndName(value: unknown): { - id?: string; - name?: string; - active?: boolean; -} { - if (typeof value === "string" && value.trim()) { - return { id: value.trim() }; - } - if (!value || typeof value !== "object" || Array.isArray(value)) { - return {}; - } - const obj = value as Record; - const nestedData = - obj.data && typeof obj.data === "object" - ? (obj.data as Record) - : undefined; - const nestedDl = - nestedData?.dataLink && typeof nestedData.dataLink === "object" - ? (nestedData.dataLink as Record) - : obj.dataLink && typeof obj.dataLink === "object" - ? (obj.dataLink as Record) - : undefined; - const id = - typeof obj.id === "string" && obj.id.trim() - ? obj.id.trim() - : typeof nestedDl?.id === "string" && nestedDl.id.trim() - ? nestedDl.id.trim() - : undefined; - const name = - typeof obj.name === "string" && obj.name.trim() - ? obj.name.trim() - : typeof nestedDl?.name === "string" && nestedDl.name.trim() - ? nestedDl.name.trim() - : undefined; - const active = - typeof obj.active === "boolean" - ? obj.active - : typeof nestedDl?.active === "boolean" - ? nestedDl.active - : undefined; - return { id, name, active }; -} - -/** - * 对业务对象记录集合执行数据健康度体检: - * 1. 必填/关键字段缺失检查 (MISSING_FIELD) - * 2. 关联对象/档案停用检查 (DISABLED_REFERENCE) - * 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH) - */ -export function auditEntityRecords( - records: DatalinkRecord[], - entity: DatalinkEntity, - options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {} -): DatalinkAuditReport { - const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id; - const nameField = entity.fields.find( - (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") - ); - const codeField = entity.fields.find( - (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") - ); - - // 解析需要检查缺失的字段集合 - const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean); - const fieldsToCheck: DatalinkField[] = - explicitSelectors.length > 0 - ? explicitSelectors.map((selector) => { - const found = entity.fields.find( - (f) => - f.name === selector || - f.label === selector || - f.name === `E_${bareEntityId}_${selector}` - ); - return ( - found ?? { - name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`, - label: selector, - type: "text", - } - ); - }) - : entity.fields.filter( - (f) => - f.optional === false || - f.type === "dimension" || - f.type === "dataLink" - ); - - const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink"); - const dimensionFields = entity.fields.filter((f) => f.type === "dimension"); - - const issues: DatalinkAuditIssue[] = []; - const suggestedPatchesMap = new Map< - string, - { id: string; code: string; name: string; form: Record; reasons: string[] } - >(); - const affectedRecordIds = new Set(); - let auditedRecords = 0; - - let missingFieldCount = 0; - let disabledReferenceCount = 0; - let crossLedgerMissingSyncCount = 0; - let crossLedgerMismatchCount = 0; - - for (const rawRecord of records) { - const dl = - rawRecord.dataLink && - typeof rawRecord.dataLink === "object" && - !Array.isArray(rawRecord.dataLink) - ? (rawRecord.dataLink as Record) - : (rawRecord as Record); - const recordId = String(dl.id ?? rawRecord.id ?? ""); - const active = (dl.active ?? rawRecord.active) !== false; - if (options.activeOnly && !active) continue; - - auditedRecords++; - const recordName = String( - dl.name ?? - dl["名称"] ?? - (nameField ? dl[nameField.name] : undefined) ?? - dl[`E_${bareEntityId}_name`] ?? - "" - ); - const recordCode = String( - dl.code ?? - dl["编码"] ?? - (codeField ? dl[codeField.name] : undefined) ?? - dl[`E_${bareEntityId}_code`] ?? - "" - ); - - const getFieldVal = (field: DatalinkField): unknown => - dl[field.name] ?? - dl[`E_${bareEntityId}_${field.name}`] ?? - (dl.form && typeof dl.form === "object" - ? (dl.form as Record)[field.name] - : undefined) ?? - dl[field.label]; - - // 1. 必填/关键字段缺失检查 - for (const field of fieldsToCheck) { - const val = getFieldVal(field); - if (isEmptyFieldValue(val)) { - missingFieldCount++; - affectedRecordIds.add(recordId); - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "MISSING_FIELD", - field: field.name, - fieldLabel: field.label || field.name, - message: `字段 [${field.label || field.name}] (${field.name}) 为空`, - }); - } - } - - // 2. 关联对象/档案停用检查 - for (const field of entity.fields) { - if (field.type !== "dimension" && field.type !== "dataLink") continue; - const val = getFieldVal(field); - const items = Array.isArray(val) ? val : val ? [val] : []; - for (const item of items) { - const refInfo = extractRefIdAndName(item); - if (refInfo.active === false) { - disabledReferenceCount++; - affectedRecordIds.add(recordId); - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "DISABLED_REFERENCE", - field: field.name, - fieldLabel: field.label || field.name, - actualId: refInfo.id, - actualName: refInfo.name, - message: `字段 [${field.label || field.name}] 引用的${ - field.type === "dataLink" ? "业务对象记录" : "维度档案" - } [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`, - }); - } - } - } - - // 3. 跨表关联同名维度一致性检查 - for (const linkField of dataLinkFields) { - const linkVal = getFieldVal(linkField); - if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue; - const linkObj = linkVal as Record; - const parentDl = - linkObj.data && - typeof linkObj.data === "object" && - (linkObj.data as Record).dataLink && - typeof (linkObj.data as Record).dataLink === "object" - ? ((linkObj.data as Record).dataLink as Record) - : linkObj.dataLink && typeof linkObj.dataLink === "object" - ? (linkObj.dataLink as Record) - : linkObj; - const linkedRecordId = String(parentDl.id ?? linkObj.id ?? ""); - - for (const dimField of dimensionFields) { - const entityPrefix = `E_${bareEntityId}_`; - const suffix = dimField.name.startsWith(entityPrefix) - ? dimField.name.slice(entityPrefix.length) - : dimField.name.replace(/^E_[^_]+_/, ""); - const parentKey = Object.keys(parentDl).find( - (k) => - k === dimField.label || - k === suffix || - k.endsWith(`_${suffix}`) || - (Boolean(dimField.label) && k.endsWith(`_${dimField.label}`)) - ); - if (!parentKey) continue; - - const parentRef = extractRefIdAndName(parentDl[parentKey]); - if (!parentRef.id) continue; - - const childRef = extractRefIdAndName(getFieldVal(dimField)); - if (!childRef.id) { - crossLedgerMissingSyncCount++; - affectedRecordIds.add(recordId); - const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${ - linkField.label || linkField.name - }] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${ - parentRef.id - }),建议回填修复`; - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "CROSS_LEDGER_MISSING_SYNC", - field: dimField.name, - fieldLabel: dimField.label || dimField.name, - linkedField: linkField.name, - linkedFieldLabel: linkField.label || linkField.name, - linkedRecordId, - expectedId: parentRef.id, - expectedName: parentRef.name, - message: reason, - }); - - const existingPatch = suggestedPatchesMap.get(recordId) ?? { - id: recordId, - code: recordCode, - name: recordName, - form: {}, - reasons: [], - }; - existingPatch.form[dimField.name] = parentRef.id; - existingPatch.reasons.push( - `${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})` - ); - suggestedPatchesMap.set(recordId, existingPatch); - } else if (childRef.id !== parentRef.id) { - crossLedgerMismatchCount++; - affectedRecordIds.add(recordId); - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "CROSS_LEDGER_MISMATCH", - field: dimField.name, - fieldLabel: dimField.label || dimField.name, - linkedField: linkField.name, - linkedFieldLabel: linkField.label || linkField.name, - linkedRecordId, - actualId: childRef.id, - actualName: childRef.name, - expectedId: parentRef.id, - expectedName: parentRef.name, - message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${ - childRef.name || childRef.id - }] (${childRef.id}) 与关联 [${ - linkField.label || linkField.name - }] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${ - parentRef.id - }) 不一致`, - }); - } - } - } - } - - const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({ - id: item.id, - code: item.code, - name: item.name, - form: item.form, - reason: item.reasons.join("; "), - })); - - return { - entityId: entity.id, - entityName: entity.name, - totalRecords: options.total ?? records.length, - auditedRecords, - healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size), - affectedRecordCount: affectedRecordIds.size, - issueCount: issues.length, - summary: { - missingFieldCount, - disabledReferenceCount, - crossLedgerMissingSyncCount, - crossLedgerMismatchCount, - }, - issues, - suggestedPatches, - }; -} - -export interface BatchEditTargetItem { - recordId: string; - patchForm: Record; - active?: boolean; -} - -export interface BatchEditItemResult { - recordId: string; - status: "preview" | "updated" | "failed"; - payload?: DatalinkRecordEditPayload; - result?: Record; - error?: string; -} - -export async function batchSafeEditRecords( - client: KyInstance, - corpId: string, - entity: DatalinkEntity, - targets: BatchEditTargetItem[], - options: { concurrency?: number; dryRun?: boolean } = {} -): Promise { - const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32)); - const results: BatchEditItemResult[] = new Array(targets.length); - let cursor = 0; - - const worker = async () => { - while (true) { - const idx = cursor++; - if (idx >= targets.length) break; - const target = targets[idx]; - try { - const detail = await api.getRecordDetail(client, corpId, target.recordId); - const payload = api.buildSafeRecordEditPayload({ - entityId: entity.id, - recordId: target.recordId, - detail, - fields: entity.fields, - patchForm: target.patchForm, - active: target.active, - }); - if (options.dryRun) { - results[idx] = { - recordId: target.recordId, - status: "preview", - payload, - }; - } else { - const res = await api.editRecord(client, corpId, payload); - results[idx] = { - recordId: target.recordId, - status: "updated", - payload, - result: res, - }; - } - } catch (error) { - results[idx] = { - recordId: target.recordId, - status: "failed", - error: error instanceof Error ? error.message : String(error), - }; - } - } - }; - - await Promise.all( - Array.from({ length: Math.min(concurrency, targets.length) }, () => worker()) - ); - return results; -} - -// ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ─────────────────── - -/** - * 根据字段名或标签模糊解析实体字段元数据 - */ -export function resolveEntityField( - entity: DatalinkEntity, - query: string -): DatalinkField | undefined { - return resolveDatalinkField(entity.fields, entity.id, query); -} - -/** - * 通用提取记录中某一字段的原始值 - */ -export function extractRecordFieldValue( - record: DatalinkRecord, - field: DatalinkField | string -): unknown { - const source = - record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) - ? (record.dataLink as Record) - : record; - const fieldName = typeof field === "string" ? field : field.name; - const fieldLabel = typeof field === "string" ? undefined : field.label; - - let val = source[fieldName] ?? record[fieldName]; - if (val === undefined && fieldLabel) { - val = source[fieldLabel] ?? record[fieldLabel]; - } - if (val === undefined && record.form && typeof record.form === "object") { - val = (record.form as Record)[fieldName]; - if (val === undefined && fieldLabel) { - val = (record.form as Record)[fieldLabel]; - } - } - return val; -} - -/** - * 提取记录中某一字段的数值(兼容数值、货币对象与格式化字符串) - */ -export function extractNumericFieldValue( - record: DatalinkRecord, - field: DatalinkField | string -): number | null { - const val = extractRecordFieldValue(record, field); - if (val === null || val === undefined || val === "") return null; - if (typeof val === "number" && !Number.isNaN(val)) return val; - if (typeof val === "object" && !Array.isArray(val)) { - const std = (val as any).standard ?? (val as any).amount; - if (typeof std === "number" && !Number.isNaN(std)) return std; - if (typeof std === "string") { - const parsed = parseFloat(std); - if (!Number.isNaN(parsed)) return parsed; - } - } - if (typeof val === "string") { - const clean = val.replace(/^[¥$¥\s,]+/, "").replace(/,/g, ""); - const parsed = parseFloat(clean); - if (!Number.isNaN(parsed)) return parsed; - } - return null; -} - -/** - * 对记录进行聚合统计(COUNT, SUM, AVG, MIN, MAX,可选分组) - */ -export function aggregateRecordFields( - records: DatalinkRecord[], - entity: DatalinkEntity, - options: { - fields: string[]; - groupBy?: string; - } -): LedgerAggregateReport { - const resolvedFields = options.fields.map((f) => { - const resolved = resolveEntityField(entity, f); - return { - query: f, - field: resolved ?? { name: f, label: f, type: "number" }, - }; - }); - - const calcStats = (list: DatalinkRecord[]): Record => { - const stats: Record = {}; - for (const { query, field } of resolvedFields) { - let count = 0; - let sum = 0; - let min = Infinity; - let max = -Infinity; - - for (const r of list) { - const num = extractNumericFieldValue(r, field); - if (num !== null) { - count++; - sum += num; - if (num < min) min = num; - if (num > max) max = num; - } - } - - stats[query] = { - field: field.name, - fieldLabel: field.label || field.name, - count, - sum: Math.round(sum * 100) / 100, - avg: count > 0 ? Math.round((sum / count) * 100) / 100 : 0, - min: count > 0 ? min : 0, - max: count > 0 ? max : 0, - }; - } - return stats; - }; - - const overall = calcStats(records); - - let groups: GroupAggregateResult[] | undefined; - if (options.groupBy) { - const groupField = resolveEntityField(entity, options.groupBy) ?? { - name: options.groupBy, - label: options.groupBy, - type: "text", - }; - const groupMap = new Map(); - for (const r of records) { - const gVal = String(extractRecordFieldValue(r, groupField) ?? "(未填写)"); - const existing = groupMap.get(gVal); - if (existing) existing.push(r); - else groupMap.set(gVal, [r]); - } - - groups = Array.from(groupMap.entries()).map(([groupValue, groupRecords]) => ({ - groupValue, - count: groupRecords.length, - aggregates: calcStats(groupRecords), - })); - } - - return { - totalRecords: records.length, - overall, - groups, - }; -} - -/** - * 台账序号连续性检查与期望基线数学核对 - */ -export function auditLedgerContinuityAndBaseline( - records: DatalinkRecord[], - entity: DatalinkEntity, - options: { - sequenceField?: string; - expectedValues?: Array<{ - field: string; - targetValue: number; - tolerance?: number; - }>; - } -): LedgerContinuityReport { - const issues: ContinuityIssue[] = []; - const outliers: LedgerContinuityReport["outliers"] = []; - - let sequenceSummary: LedgerContinuityReport["sequenceSummary"] | undefined; - - // 1. 序号连续性核查 - if (options.sequenceField) { - const resolvedSeqField = resolveEntityField(entity, options.sequenceField) ?? { - name: options.sequenceField, - label: options.sequenceField, - type: "number", - }; - - const seqMap = new Map(); - const numbers: number[] = []; - - for (const r of records) { - const num = extractNumericFieldValue(r, resolvedSeqField); - if (num !== null) { - const intVal = Math.round(num); - numbers.push(intVal); - const existing = seqMap.get(intVal); - const rId = r.id || String(r.recordId || ""); - if (existing) existing.push(rId); - else seqMap.set(intVal, [rId]); - } - } - - if (numbers.length > 0) { - const min = Math.min(...numbers); - const max = Math.max(...numbers); - const missing: number[] = []; - const duplicates: number[] = []; - - for (let i = min; i <= max; i++) { - const count = seqMap.get(i)?.length ?? 0; - if (count === 0) { - missing.push(i); - issues.push({ - type: "MISSING_SEQUENCE", - field: resolvedSeqField.name, - message: `台账序号断层:缺少第 [${i}] 期记录`, - expected: i, - actual: null, - }); - } else if (count > 1) { - duplicates.push(i); - issues.push({ - type: "DUPLICATE_SEQUENCE", - field: resolvedSeqField.name, - message: `台账序号重号:第 [${i}] 期存在 ${count} 条重复记录 (${seqMap.get(i)?.join(", ")})`, - expected: 1, - actual: count, - }); - } - } - - sequenceSummary = { - field: resolvedSeqField.name, - fieldLabel: resolvedSeqField.label || resolvedSeqField.name, - min, - max, - expectedCount: max - min + 1, - actualCount: numbers.length, - missing, - duplicates, - }; - } - } - - // 2. 基线离群异常核对 - if (options.expectedValues && options.expectedValues.length > 0) { - for (const exp of options.expectedValues) { - const field = resolveEntityField(entity, exp.field) ?? { - name: exp.field, - label: exp.field, - type: "number", - }; - const tolerance = exp.tolerance ?? 0.05; - - for (const r of records) { - const val = extractNumericFieldValue(r, field); - if (val !== null) { - const diff = Math.abs(val - exp.targetValue); - if (diff > tolerance) { - const rId = r.id || String(r.recordId || ""); - outliers.push({ - recordId: rId, - field: field.name, - fieldLabel: field.label || field.name, - value: val, - expectedValue: exp.targetValue, - diff: Math.round(diff * 100) / 100, - }); - issues.push({ - type: "VALUE_OUTLIER", - recordId: rId, - field: field.name, - message: `记录 [${rId}] 字段 [${field.label || field.name}] 数值 [${val}] 偏离基线期望 [${exp.targetValue}] (差额: ${diff > 0 ? "+" : ""}${Math.round(diff * 100) / 100})`, - expected: exp.targetValue, - actual: val, - }); - } - } - } - } - } - - return { - totalRecords: records.length, - sequenceSummary, - issues, - outliers, - }; -} - -/** - * 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合) - */ -function splitPredicateParts(source: string, separator: string): string[] { - const parts: string[] = []; - let quote = "", depth = 0, start = 0; - for (let i = 0; i < source.length; i++) { - const char = source[i]; - if (quote) { - if (char === "\\") i++; - else if (char === quote) quote = ""; - continue; - } - if (char === "'" || char === '"') quote = char; - else if (char === "(") depth++; - else if (char === ")") { - if (--depth < 0) throw new ValidationError("筛选条件括号不匹配"); - } else if (depth === 0 && source.startsWith(separator, i)) { - parts.push(source.slice(start, i).trim()); - start = i + separator.length; - i += separator.length - 1; - } - } - if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配"); - parts.push(source.slice(start).trim()); - if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空"); - return parts; -} - -function predicateLiteral(raw: string): string | number | boolean | null { - if (/^(["']).*\1$/s.test(raw)) { - const value = raw.slice(1, -1); - if (raw[0] === '"') { - try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); } - } - if (/(? boolean { - const conditions = splitPredicateParts(whereClause, "&&").map(cond => { - // 1. in 操作符: field in (v1, v2, v3) - const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i); - // 2. 比较操作符: ==, !=, >=, <=, >, <, = - const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s); - if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`); - const field = predicateField(entity, (inMatch ?? compMatch)![1].trim()); - const op = inMatch ? "in" : compMatch![2]; - const targets = inMatch - ? splitPredicateParts(inMatch[2], ",").map(predicateLiteral) - : [predicateLiteral(compMatch![3].trim())]; - return (record: DatalinkRecord) => { - const actual = extractRecordFieldValue(record, field); - const equal = (target: string | number | boolean | null): boolean => { - if (target === null) return actual === null || actual === undefined; - if (typeof target === "number") return extractNumericFieldValue(record, field) === target; - return actual !== null && actual !== undefined && String(actual) === String(target); - }; - if (op === "in") return targets.some(equal); - // 字符串/布尔比较 - if (op === "=" || op === "==") return equal(targets[0]); - if (op === "!=") return !equal(targets[0]); - // 数值比较 - const value = extractNumericFieldValue(record, field); - const target = targets[0]; - if (value === null || typeof target !== "number") return false; - return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target; - }; - }); - return record => conditions.every(condition => condition(record)); -} - -export function filterRecordsByPredicate( - records: DatalinkRecord[], - whereClause: string, - entity: DatalinkEntity -): DatalinkRecord[] { - if (!whereClause || !whereClause.trim()) return records; - return records.filter(compileRecordPredicate(whereClause, entity)); -} - -/** - * 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销" - */ -export function parseSetClause( - setClause: string, - entity: DatalinkEntity -): Record { - const result: Record = {}; - let assignments: string[]; - try { assignments = splitPredicateParts(setClause, ","); } - catch { throw new ValidationError("赋值表达式引号或括号不匹配,且赋值项不能为空"); } - - for (const assign of assignments) { - const eqIdx = assign.indexOf("="); - if (eqIdx === -1) throw new ValidationError(`赋值项缺少等号: ${assign}`); - const rawKey = assign.slice(0, eqIdx).trim(); - if (!rawKey) throw new ValidationError("赋值字段不能为空"); - let rawVal = assign.slice(eqIdx + 1).trim(); - - // 去除外层引号,同时保留显式字符串的类型与转义语义。 - const quoted = (rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'")); - const literal = quoted ? predicateLiteral(rawVal) : undefined; - - const field = resolveEntityField(entity, rawKey); - const targetKey = field ? field.name : rawKey; - - // 类型智能转换 - if (quoted) { - result[targetKey] = literal; - } else if (rawVal === "true") { - result[targetKey] = true; - } else if (rawVal === "false") { - result[targetKey] = false; - } else if (rawVal === "null") { - result[targetKey] = null; - } else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") { - result[targetKey] = Number(rawVal); - } else { - result[targetKey] = rawVal; - } - } - - return result; -} - -/** - * 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05" - */ -export function parseExpectClause( - expectClause: string -): Array<{ field: string; targetValue: number; tolerance?: number }> { - if (!expectClause || !expectClause.trim()) return []; - const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean); - const results: Array<{ field: string; targetValue: number; tolerance?: number }> = []; - - for (const part of parts) { - const match = part.match( - /^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/ - ); - if (match) { - const field = match[1].trim(); - const targetValue = parseFloat(match[2]); - const tolerance = match[3] ? parseFloat(match[3]) : undefined; - if (!Number.isNaN(targetValue)) { - results.push({ field, targetValue, tolerance }); - } - } - } - return results; -} diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index 5f32587..26b5607 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -1,39 +1,17 @@ -# Platform 域说明 +# 自建应用平台(platform) -Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能力。自建应用下的业务对象、字段、记录和权限查询统一放在 [DataLink 域](../datalink/README.datalink.md)。 +本域以自建应用为共同业务根,包含应用元数据、业务对象数据与工作流三个子模块。CLI 命令按使用场景组织,源码归属按业务职责组织。 -## 代码结构 +| 子模块 | 所有权 | 入口 | +|---|---|---| +| applications | 应用基础/详情模型、列表、全量列表、名称解析及应用级权限元数据 | [README.applications.md](./applications/README.applications.md) | +| datalink | 业务对象、字段、记录、导入、数据编辑与台账审计 | [README.datalink.md](./datalink/README.datalink.md) | +| workflow | 工作流模型、传输、配置保存、节点、执行、诊断与监听 | [README.workflow.md](./workflow/README.workflow.md) | -```text -src/domains/platform/ -├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志、枚举类型) -├── api.ts # HTTP 传输层(含 unwrap 空安全校验、Piper Job 端点与 EKB_ENUM 字典拉取) -├── services.ts # 门面聚合与对外服务导出(含 resolveWorkflowEnumOptions 混合架构) -├── workflow/ # 工作流体系子域(高内聚分层架构) -│ ├── index.ts # 工作流能力统合导出 -│ ├── enums.ts # 单据审批事件触发器标准系统枚举(18 项内置字典与翻译器) -│ ├── watch/ # 实时任务监听、TaskExecutionTracker 状态机与日志流 (tracker, engine, formatter) -│ ├── nodes/ # 声明式节点树编排、树形索引定位、插入追加与重排 (tree, locator, mutations) -│ ├── script/ # 脚本 AST 语法校验、上游依赖扫描与隔离沙箱仿真引擎 (lint, scanner, sandbox) -│ ├── branch/ # 条件分支与规则解释诊断引擎 (explain, types) -│ ├── analysis/ # 工作流静态吞错、审批状态死锁过滤与联动覆盖巡检 (analyzer, types) -│ ├── state/ # 草稿版本状态机与发布乐观锁保护 -│ └── alert/ # 错误指纹告警与 SQLite 本地持久化 -└── execution-context.ts # 执行树与节点输出上下文辅助 -``` +## 依赖与入口 -## 工作流使用与诊断 +applications 不依赖另外两个模块;DataLink 可使用应用模型和服务,不能依赖工作流;工作流跨应用查询通过 applications 服务获取应用。跨子模块调用使用 services,不直接导入其他子模块的 api。共享认证和数据库仍使用 core。 -CLI 命令、触发器分类、生产调试风险、节点与脚本校验、实时监听以及诊断结果契约,统一见 [Workflow 说明](./workflow/README.workflow.md)。 +各子模块拥有自己的 api、services 与 types。platform 根目录只保留总览,不保留混合的 api/services/types 门面。内部私有源码路径已经调整,公共 `hose-use/sdk` 名称和 CLI 命令继续保持兼容。 -## 模块边界 - -- `workflow/{analysis,branch,nodes,script,state,watch,alert}/index.ts` 是各能力的目录出口;内部引用直接指向所属目录,不再保留根目录的一行转发文件。 -- 单元测试与对应实现放在同一目录;分层测试检查已移除路径,保留正常的模块出口文件。 -- MVEL 校验先识别字符串、转义及行/块注释,再检查有效代码中的括号、return 和节点引用;这属于轻量静态检查,不是完整的 MVEL 编译器。JavaScript 校验仍检查函数体语法,不执行脚本。 - -## 详细文档 - -接口职责、认证链路与 CLI 能力导航见(MCP 统一使用 `hose_cli`): - -[docs/modules/platform.md](../../../docs/modules/platform.md) +具体 CLI 与认证链路见 [模块说明](../../../docs/modules/platform.md),强制导入规则见 [架构边界测试](../../cli/architecture-boundaries.test.ts)。 diff --git a/src/domains/platform/applications/README.applications.md b/src/domains/platform/applications/README.applications.md new file mode 100644 index 0000000..37b192c --- /dev/null +++ b/src/domains/platform/applications/README.applications.md @@ -0,0 +1,16 @@ +# 自建应用元数据(applications) + +本模块拥有应用基础模型、详情模型、应用级权限元数据及目标解析。业务对象与工作流分别由 [DataLink](../datalink/README.datalink.md) 和 [Workflow](../workflow/README.workflow.md) 管理。 + +| 文件 | 职责 | +|---|---| +| [api.ts](./api.ts) | 应用 HTTP 请求和响应投影,共用启用应用列表请求 | +| [types.ts](./types.ts) | PlatformSchema、应用详情与公开兼容类型 DatalinkPlatformDetail | +| [services.ts](./services.ts) | 基础/详情列表、全量列表、详情与唯一目标解析出口 | +| [application-contract.test.ts](./application-contract.test.ts) | 迁移前后两种投影、缺省与包装兼容回归 | + +`listBasicPlatforms` 保留原工作流基础投影:剥离未建模字段,缺少 items 时拒绝。`listPlatforms` 保留详情投影:保留扩展字段、清洗 admin 信息、兼容空列表。两者共用请求实现,不强行混同既有错误及空值行为。 + +`listAllPlatforms` 与 `getPlatform` 保留原有全量及详情契约;当前全量列表原始数组仍被归为空列表,这属于已锁定的既有兼容行为,本轮不借迁移改变。`resolvePlatform` 按 ID、名称或编码做不区分大小写的精确匹配,再读取详情。 + +CLI 的 platform/app 详情及公共 SDK 的原函数名继续可用。不得从本模块反向依赖 DataLink 或工作流,不在应用模型中复制节点或记录结构。 diff --git a/src/domains/platform/applications/api.ts b/src/domains/platform/applications/api.ts new file mode 100644 index 0000000..9ffc7d1 --- /dev/null +++ b/src/domains/platform/applications/api.ts @@ -0,0 +1,73 @@ +import { z } from "zod"; +import type { KyInstance } from "ky"; +import { PlatformSchema, DatalinkPlatformDetailSchema, type DatalinkPlatformDetail } from "./types.js"; + +function asRecord(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +async function fetchEnabledPlatforms(client: KyInstance, corpId: string): Promise { + const response = await client.get("api/v2/datalink/platform/search", { searchParams: { scope: "enable", corpId } }); + return response.json(); +} + +/** 工作流使用的基础投影:保留缺少 items 时拒绝的既有契约。 */ +export async function listBasicPlatforms(client: KyInstance, corpId: string) { + const json = await fetchEnabledPlatforms(client, corpId) as { items: unknown[] }; + return z.array(PlatformSchema).parse(json.items); +} + +function sanitizePlatformDetail(value: unknown): Record { + const platform = asRecord(value); + const admin = Array.isArray(platform.admin) + ? platform.admin.map((item) => { + const staff = asRecord(item); + return { + id: staff.id, + name: staff.name, + code: staff.code, + active: staff.active, + }; + }) + : platform.admin; + return { ...platform, admin }; +} + +/** 列出当前企业可见的启用自建应用。 */ +export async function listPlatforms(client: KyInstance, corpId: string) { + const json = asRecord(await fetchEnabledPlatforms(client, corpId)); + const items = Array.isArray(json.items) ? json.items.map(sanitizePlatformDetail) : []; + return z.array(DatalinkPlatformDetailSchema).parse(items); +} + +/** 列出当前企业全量自建应用与模板平台(包含 HAB 模板与全部自建应用)。 */ +export async function listAllPlatforms(client: KyInstance, corpId: string) { + const response = await client.get("api/v2/datalink/platform", { + searchParams: { corpId }, + }); + const json = asRecord(await response.json()); + const rawList = Array.isArray(json) ? json : Array.isArray(json.items) ? json.items : []; + const items = rawList.map(sanitizePlatformDetail); + return z.array(DatalinkPlatformDetailSchema).parse(items); +} + +/** 获取单个应用详情以及应用级人员/角色/部门权限。 */ +export async function getPlatform( + client: KyInstance, + corpId: string, + platformId: string +): Promise { + const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`; + const bareId = platformId.startsWith("$") ? platformId.slice(1) : platformId; + const response = await client.get(`api/v2/datalink/platform/${normalizedId}`, { + // 前端实际使用两个 join,并且详情接口要求同时传 id。 + searchParams: new URLSearchParams([ + ["id", bareId], + ["join", "icon.fileId,fileId,/v1/attachment/attachments"], + ["corpId", corpId], + ["join", "adminIds,admin,/v1/organization/staffs"], + ]), + }); + const json = asRecord(await response.json()); + return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json)); +} diff --git a/src/domains/platform/applications/application-contract.test.ts b/src/domains/platform/applications/application-contract.test.ts new file mode 100644 index 0000000..3d259f7 --- /dev/null +++ b/src/domains/platform/applications/application-contract.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import type { KyInstance } from "ky"; +import { listBasicPlatforms as listBasic } from "./api.js"; +import { listPlatforms as listDetailed, listAllPlatforms, getPlatform } from "./api.js"; + +function client(body: unknown) { + const calls: Array<{ path: string; options: any }> = []; + return { calls, http: { get: async (path: string, options: unknown) => { + calls.push({ path, options }); + return Response.json(body); + } } as unknown as KyInstance }; +} +const platform = { id: "app", name: "Fixture", corporationId: "corp", adminIds: null, importMethod: null, + extra: "preserve", staffIds: null, admin: [{ id: "s", name: "Staff", code: "S", active: true, secret: "omit" }] }; + +test("应用基础与详情查询共享请求形状,但保持不同投影和脱敏", async () => { + const a = client({ items: [platform] }), b = client({ items: [platform] }); + const basic = (await listBasic(a.http, "corp"))[0]!; + const detail = (await listDetailed(b.http, "corp"))[0]!; + expect(a.calls).toEqual(b.calls); + expect(a.calls[0]).toEqual({ path: "api/v2/datalink/platform/search", options: { searchParams: { scope: "enable", corpId: "corp" } } }); + expect(basic.adminIds).toEqual([]); + expect(basic.importMethod).toEqual([]); + expect(basic).not.toHaveProperty("extra"); + expect(basic).not.toHaveProperty("admin"); + expect(detail.extra).toBe("preserve"); + expect(detail.staffIds).toEqual([]); + expect(detail.admin).toEqual([{ id: "s", name: "Staff", code: "S", active: true }]); +}); + +test("应用查询保留缺失 items 和无效响应的既有差异", async () => { + for (const body of [{}, { items: {} }, { code: 403, msg: "fixture" }]) { + await expect(listBasic(client(body).http, "corp")).rejects.toThrow(); + expect(await listDetailed(client(body).http, "corp")).toEqual([]); + } + for (const query of [listBasic, listDetailed]) { + await expect(query(client({ items: [{ name: "missing id" }] }).http, "corp")).rejects.toThrow(); + } +}); + +test("全量应用及详情保留响应包装、ID 与 join 参数兼容", async () => { + expect(await listAllPlatforms(client([platform]).http, "corp")).toEqual([]); + expect((await listAllPlatforms(client({ items: [platform] }).http, "corp"))[0]?.id).toBe("app"); + for (const body of [platform, { data: platform }, { value: platform }]) { + for (const id of ["app", "$app"]) { + const f = client(body); + expect((await getPlatform(f.http, "corp", id)).id).toBe("app"); + expect(f.calls[0]?.path).toBe("api/v2/datalink/platform/$app"); + const params = f.calls[0]?.options.searchParams as URLSearchParams; + expect(params.get("id")).toBe("app"); + expect(params.getAll("join")).toEqual(["icon.fileId,fileId,/v1/attachment/attachments", "adminIds,admin,/v1/organization/staffs"]); + } + } +}); diff --git a/src/domains/platform/applications/services.ts b/src/domains/platform/applications/services.ts new file mode 100644 index 0000000..af2d623 --- /dev/null +++ b/src/domains/platform/applications/services.ts @@ -0,0 +1,24 @@ +import type { KyInstance } from "ky"; +import * as api from "./api.js"; +import type { DatalinkPlatformDetail } from "./types.js"; + +export function listBasicPlatforms(...args: Parameters) { return api.listBasicPlatforms(...args); } +export function listPlatforms(...args: Parameters) { return api.listPlatforms(...args); } +export function listAllPlatforms(...args: Parameters) { return api.listAllPlatforms(...args); } +export function getPlatform(...args: Parameters) { return api.getPlatform(...args); } + +function matches(value: unknown, target: string): boolean { + return typeof value === "string" && value.toLowerCase() === target.toLowerCase(); +} + +export async function resolvePlatform( + client: KyInstance, + corpId: string, + target: string +): Promise { + const platforms = await api.listPlatforms(client, corpId); + const found = platforms.find((platform) => + [platform.id, platform.name, platform.code].some((value) => matches(value, target)) + ); + return found ? api.getPlatform(client, corpId, found.id) : undefined; +} diff --git a/src/domains/platform/applications/types.ts b/src/domains/platform/applications/types.ts new file mode 100644 index 0000000..bd01547 --- /dev/null +++ b/src/domains/platform/applications/types.ts @@ -0,0 +1,32 @@ +import { z } from "zod"; + +// ── 自建应用(DataLink Platform)───────────────────────────── + +export const PlatformSchema = z.object({ + id: z.string(), + name: z.string(), + nameSpell: z.string().default(""), + enName: z.string().nullable().optional(), + code: z.string().default(""), + corporationId: z.string(), + active: z.boolean().default(true), + type: z.string().default(""), + groupType: z.string().default(""), + platformType: z.string().default(""), + source: z.string().default(""), + adminIds: z.array(z.string()).nullish().transform((value) => value ?? []), + desc: z.string().nullable().optional(), + importMethod: z.array(z.string()).nullish().transform((value) => value ?? []), + createTime: z.number().default(0), + updateTime: z.number().default(0), +}); + +export const DatalinkPlatformDetailSchema = PlatformSchema.passthrough().extend({ + staffIds: z.array(z.string()).nullish().transform((value) => value ?? []), + roleIds: z.array(z.string()).nullish().transform((value) => value ?? []), + departmentIds: z.array(z.string()).nullish().transform((value) => value ?? []), + departmentsIncludeChildren: z.boolean().nullish().transform((value) => value ?? false), +}); + +export type Platform = z.infer; +export type DatalinkPlatformDetail = z.infer; diff --git a/src/domains/datalink/README.datalink.md b/src/domains/platform/datalink/README.datalink.md similarity index 88% rename from src/domains/datalink/README.datalink.md rename to src/domains/platform/datalink/README.datalink.md index 72ac2f2..11269c1 100644 --- a/src/domains/datalink/README.datalink.md +++ b/src/domains/platform/datalink/README.datalink.md @@ -1,15 +1,18 @@ # DataLink 域说明 -DataLink 域负责跨企业查询当前账号可见的自建应用、业务对象、字段定义、业务记录、权限快照和导入状态。 +DataLink 是应用平台的数据子模块,负责业务对象、字段定义、业务记录、对象级权限快照和导入状态。应用列表、详情与名称解析由 [applications](../applications/README.applications.md) 拥有;公共 SDK 保留原调用名称。 ## 代码结构 ```text -src/domains/datalink/ -├── types.ts # 应用详情、对象字段、记录分页与权限模型 -├── api.ts # DataLink HTTP 传输层 -├── services.ts # 应用/对象名称解析与查询表达式辅助、SDK 门面 -└── fields.ts # 读取与写入共用的唯一字段解析 +src/domains/platform/datalink/ +├── types.ts # 业务对象、字段、记录与对象级权限模型 +├── api.ts # 对象/记录 HTTP 传输与响应校验 +├── services.ts # 显式业务出口,不反向参与内部依赖 +├── records.ts # 对象解析、分页/流式记录、归一化与安全批量编辑 +├── predicates.ts # 服务端过滤表达式、客户端谓词和声明式赋值解析 +├── audit.ts # 统计、台账审计、聚合与连续性检查 +└── fields.ts # 读写共用的唯一字段解析 ``` ## 查询链路 @@ -21,7 +24,7 @@ platform/search └─ searchPlatformDataLinkWithChild/{entityId} 业务记录 ``` -应用列表和应用详情使用 EKB client。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。 +应用列表、详情和应用级权限元数据由 applications 模块通过 EKB client 提供。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。 ## CLI diff --git a/src/domains/datalink/api.ts b/src/domains/platform/datalink/api.ts similarity index 86% rename from src/domains/datalink/api.ts rename to src/domains/platform/datalink/api.ts index ccda9fe..1bdf874 100644 --- a/src/domains/datalink/api.ts +++ b/src/domains/platform/datalink/api.ts @@ -3,12 +3,10 @@ import type { KyInstance } from "ky"; import { resolveDatalinkField } from "./fields.js"; import { DatalinkEntitySchema, - DatalinkPlatformDetailSchema, enrichDatalinkField, type DatalinkEntity, type DatalinkField, type DatalinkImportJob, - type DatalinkPlatformDetail, type DatalinkRecord, type DatalinkRecordDetail, type DatalinkRecordEditPayload, @@ -35,64 +33,6 @@ function parseEntity(value: unknown): DatalinkEntity { }; } -function sanitizePlatformDetail(value: unknown): Record { - const platform = asRecord(value); - const admin = Array.isArray(platform.admin) - ? platform.admin.map((item) => { - const staff = asRecord(item); - return { - id: staff.id, - name: staff.name, - code: staff.code, - active: staff.active, - }; - }) - : platform.admin; - return { ...platform, admin }; -} - -/** 列出当前企业可见的启用自建应用。 */ -export async function listPlatforms(client: KyInstance, corpId: string) { - const response = await client.get("api/v2/datalink/platform/search", { - searchParams: { scope: "enable", corpId }, - }); - const json = asRecord(await response.json()); - const items = Array.isArray(json.items) ? json.items.map(sanitizePlatformDetail) : []; - return z.array(DatalinkPlatformDetailSchema).parse(items); -} - -/** 列出当前企业全量自建应用与模板平台(包含 HAB 模板与全部自建应用)。 */ -export async function listAllPlatforms(client: KyInstance, corpId: string) { - const response = await client.get("api/v2/datalink/platform", { - searchParams: { corpId }, - }); - const json = asRecord(await response.json()); - const rawList = Array.isArray(json) ? json : Array.isArray(json.items) ? json.items : []; - const items = rawList.map(sanitizePlatformDetail); - return z.array(DatalinkPlatformDetailSchema).parse(items); -} - -/** 获取单个应用详情以及应用级人员/角色/部门权限。 */ -export async function getPlatform( - client: KyInstance, - corpId: string, - platformId: string -): Promise { - const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`; - const bareId = platformId.startsWith("$") ? platformId.slice(1) : platformId; - const response = await client.get(`api/v2/datalink/platform/${normalizedId}`, { - // 前端实际使用两个 join,并且详情接口要求同时传 id。 - searchParams: new URLSearchParams([ - ["id", bareId], - ["join", "icon.fileId,fileId,/v1/attachment/attachments"], - ["corpId", corpId], - ["join", "adminIds,admin,/v1/organization/staffs"], - ]), - }); - const json = asRecord(await response.json()); - return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json)); -} - /** 获取应用下的业务对象目录及完整字段定义。 */ export async function listPlatformEntities( client: KyInstance, diff --git a/src/domains/platform/datalink/audit.ts b/src/domains/platform/datalink/audit.ts new file mode 100644 index 0000000..8a7d6dc --- /dev/null +++ b/src/domains/platform/datalink/audit.ts @@ -0,0 +1,641 @@ +import type { DatalinkEntity, DatalinkField, DatalinkRecord, AggregateFieldStats, GroupAggregateResult, LedgerAggregateReport, ContinuityIssue, LedgerContinuityReport, DatalinkRecordStats } from "./types.js"; +import { normalizeDatalinkRecord, extractRefIdAndName, resolveEntityField, extractRecordFieldValue, extractNumericFieldValue } from "./records.js"; + + +/** + * 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。 + * 既可接收全量内存数组,也可配合流式生成器在 O(1) 内存下在线累加计算。 + */ +export function calculateEntityRecordStats( + records: Iterable, + entity?: DatalinkEntity, + explicitTotal?: number +): DatalinkRecordStats { + let total = 0; + let activeCount = 0; + let inactiveCount = 0; + + const namesMap = new Map(); + const patternsMap = new Map(); + + let earliestCreate: number | null = null; + let latestUpdate: number | null = null; + + for (const raw of records) { + total++; + const norm = normalizeDatalinkRecord(raw, entity); + if (norm.active) activeCount++; + else inactiveCount++; + + if (norm.createTime && typeof norm.createTime === "number") { + if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime; + } + if (norm.updateTime && typeof norm.updateTime === "number") { + if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime; + } + + // 统计名称重名与状态交叉 + if (norm.name) { + if (!namesMap.has(norm.name)) { + namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 }); + } + const nStats = namesMap.get(norm.name)!; + nStats.total++; + if (norm.active) nStats.active++; + else nStats.inactive++; + } + + // 统计编码结构聚类 + const code = norm.code || "EMPTY"; + const pattern = code + .replace(/\d{8}/g, "YYYYMMDD") + .replace(/\d{6}/g, "SEQ6") + .replace(/\d+/g, "N"); + + if (!patternsMap.has(pattern)) { + patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 }); + } + const pStats = patternsMap.get(pattern)!; + pStats.count++; + if (norm.active) pStats.activeCount++; + else pStats.inactiveCount++; + } + + const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total; + const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%"; + + let duplicateNamesCount = 0; + let mixedStatusNamesCount = 0; + for (const n of namesMap.values()) { + if (n.total > 1) duplicateNamesCount++; + if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++; + } + + const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count); + + const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null); + + return { + total: finalTotal, + activeCount, + inactiveCount, + activeRate, + uniqueNames: namesMap.size, + duplicateNamesCount, + mixedStatusNamesCount, + codePatterns, + earliestCreateTime: formatDate(earliestCreate), + latestUpdateTime: formatDate(latestUpdate), + }; +} + + +export interface DatalinkAuditIssue { + recordId: string; + recordCode: string; + recordName: string; + active: boolean; + type: + | "MISSING_FIELD" + | "DISABLED_REFERENCE" + | "CROSS_LEDGER_MISSING_SYNC" + | "CROSS_LEDGER_MISMATCH"; + field: string; + fieldLabel: string; + message: string; + linkedField?: string; + linkedFieldLabel?: string; + linkedRecordId?: string; + actualId?: string; + actualName?: string; + expectedId?: string; + expectedName?: string; +} + + +export interface DatalinkAuditReport { + entityId: string; + entityName: string; + totalRecords: number; + auditedRecords: number; + healthyRecords: number; + affectedRecordCount: number; + issueCount: number; + summary: { + missingFieldCount: number; + disabledReferenceCount: number; + crossLedgerMissingSyncCount: number; + crossLedgerMismatchCount: number; + }; + issues: DatalinkAuditIssue[]; + suggestedPatches: Array<{ + id: string; + code: string; + name: string; + form: Record; + reason: string; + }>; +} + + +function isEmptyFieldValue(value: unknown): boolean { + if (value === undefined || value === null || value === "") return true; + if (Array.isArray(value)) return value.length === 0; + if (typeof value === "object") { + const obj = value as Record; + if ("id" in obj) { + return obj.id === undefined || obj.id === null || obj.id === ""; + } + if ("standard" in obj) { + return obj.standard === undefined || obj.standard === null || obj.standard === ""; + } + return Object.keys(obj).length === 0; + } + return false; +} + + +/** + * 对业务对象记录集合执行数据健康度体检: + * 1. 必填/关键字段缺失检查 (MISSING_FIELD) + * 2. 关联对象/档案停用检查 (DISABLED_REFERENCE) + * 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH) + */ +export function auditEntityRecords( + records: DatalinkRecord[], + entity: DatalinkEntity, + options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {} +): DatalinkAuditReport { + const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id; + const nameField = entity.fields.find( + (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") + ); + const codeField = entity.fields.find( + (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") + ); + + // 解析需要检查缺失的字段集合 + const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean); + const fieldsToCheck: DatalinkField[] = + explicitSelectors.length > 0 + ? explicitSelectors.map((selector) => { + const found = entity.fields.find( + (f) => + f.name === selector || + f.label === selector || + f.name === `E_${bareEntityId}_${selector}` + ); + return ( + found ?? { + name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`, + label: selector, + type: "text", + } + ); + }) + : entity.fields.filter( + (f) => + f.optional === false || + f.type === "dimension" || + f.type === "dataLink" + ); + + const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink"); + const dimensionFields = entity.fields.filter((f) => f.type === "dimension"); + + const issues: DatalinkAuditIssue[] = []; + const suggestedPatchesMap = new Map< + string, + { id: string; code: string; name: string; form: Record; reasons: string[] } + >(); + const affectedRecordIds = new Set(); + let auditedRecords = 0; + + let missingFieldCount = 0; + let disabledReferenceCount = 0; + let crossLedgerMissingSyncCount = 0; + let crossLedgerMismatchCount = 0; + + for (const rawRecord of records) { + const dl = + rawRecord.dataLink && + typeof rawRecord.dataLink === "object" && + !Array.isArray(rawRecord.dataLink) + ? (rawRecord.dataLink as Record) + : (rawRecord as Record); + const recordId = String(dl.id ?? rawRecord.id ?? ""); + const active = (dl.active ?? rawRecord.active) !== false; + if (options.activeOnly && !active) continue; + + auditedRecords++; + const recordName = String( + dl.name ?? + dl["名称"] ?? + (nameField ? dl[nameField.name] : undefined) ?? + dl[`E_${bareEntityId}_name`] ?? + "" + ); + const recordCode = String( + dl.code ?? + dl["编码"] ?? + (codeField ? dl[codeField.name] : undefined) ?? + dl[`E_${bareEntityId}_code`] ?? + "" + ); + + const getFieldVal = (field: DatalinkField): unknown => + dl[field.name] ?? + dl[`E_${bareEntityId}_${field.name}`] ?? + (dl.form && typeof dl.form === "object" + ? (dl.form as Record)[field.name] + : undefined) ?? + dl[field.label]; + + // 1. 必填/关键字段缺失检查 + for (const field of fieldsToCheck) { + const val = getFieldVal(field); + if (isEmptyFieldValue(val)) { + missingFieldCount++; + affectedRecordIds.add(recordId); + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "MISSING_FIELD", + field: field.name, + fieldLabel: field.label || field.name, + message: `字段 [${field.label || field.name}] (${field.name}) 为空`, + }); + } + } + + // 2. 关联对象/档案停用检查 + for (const field of entity.fields) { + if (field.type !== "dimension" && field.type !== "dataLink") continue; + const val = getFieldVal(field); + const items = Array.isArray(val) ? val : val ? [val] : []; + for (const item of items) { + const refInfo = extractRefIdAndName(item); + if (refInfo.active === false) { + disabledReferenceCount++; + affectedRecordIds.add(recordId); + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "DISABLED_REFERENCE", + field: field.name, + fieldLabel: field.label || field.name, + actualId: refInfo.id, + actualName: refInfo.name, + message: `字段 [${field.label || field.name}] 引用的${ + field.type === "dataLink" ? "业务对象记录" : "维度档案" + } [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`, + }); + } + } + } + + // 3. 跨表关联同名维度一致性检查 + for (const linkField of dataLinkFields) { + const linkVal = getFieldVal(linkField); + if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue; + const linkObj = linkVal as Record; + const parentDl = + linkObj.data && + typeof linkObj.data === "object" && + (linkObj.data as Record).dataLink && + typeof (linkObj.data as Record).dataLink === "object" + ? ((linkObj.data as Record).dataLink as Record) + : linkObj.dataLink && typeof linkObj.dataLink === "object" + ? (linkObj.dataLink as Record) + : linkObj; + const linkedRecordId = String(parentDl.id ?? linkObj.id ?? ""); + + for (const dimField of dimensionFields) { + const entityPrefix = `E_${bareEntityId}_`; + const suffix = dimField.name.startsWith(entityPrefix) + ? dimField.name.slice(entityPrefix.length) + : dimField.name.replace(/^E_[^_]+_/, ""); + const parentKey = Object.keys(parentDl).find( + (k) => + k === dimField.label || + k === suffix || + k.endsWith(`_${suffix}`) || + (Boolean(dimField.label) && k.endsWith(`_${dimField.label}`)) + ); + if (!parentKey) continue; + + const parentRef = extractRefIdAndName(parentDl[parentKey]); + if (!parentRef.id) continue; + + const childRef = extractRefIdAndName(getFieldVal(dimField)); + if (!childRef.id) { + crossLedgerMissingSyncCount++; + affectedRecordIds.add(recordId); + const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${ + linkField.label || linkField.name + }] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${ + parentRef.id + }),建议回填修复`; + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "CROSS_LEDGER_MISSING_SYNC", + field: dimField.name, + fieldLabel: dimField.label || dimField.name, + linkedField: linkField.name, + linkedFieldLabel: linkField.label || linkField.name, + linkedRecordId, + expectedId: parentRef.id, + expectedName: parentRef.name, + message: reason, + }); + + const existingPatch = suggestedPatchesMap.get(recordId) ?? { + id: recordId, + code: recordCode, + name: recordName, + form: {}, + reasons: [], + }; + existingPatch.form[dimField.name] = parentRef.id; + existingPatch.reasons.push( + `${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})` + ); + suggestedPatchesMap.set(recordId, existingPatch); + } else if (childRef.id !== parentRef.id) { + crossLedgerMismatchCount++; + affectedRecordIds.add(recordId); + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "CROSS_LEDGER_MISMATCH", + field: dimField.name, + fieldLabel: dimField.label || dimField.name, + linkedField: linkField.name, + linkedFieldLabel: linkField.label || linkField.name, + linkedRecordId, + actualId: childRef.id, + actualName: childRef.name, + expectedId: parentRef.id, + expectedName: parentRef.name, + message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${ + childRef.name || childRef.id + }] (${childRef.id}) 与关联 [${ + linkField.label || linkField.name + }] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${ + parentRef.id + }) 不一致`, + }); + } + } + } + } + + const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({ + id: item.id, + code: item.code, + name: item.name, + form: item.form, + reason: item.reasons.join("; "), + })); + + return { + entityId: entity.id, + entityName: entity.name, + totalRecords: options.total ?? records.length, + auditedRecords, + healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size), + affectedRecordCount: affectedRecordIds.size, + issueCount: issues.length, + summary: { + missingFieldCount, + disabledReferenceCount, + crossLedgerMissingSyncCount, + crossLedgerMismatchCount, + }, + issues, + suggestedPatches, + }; +} + + +/** + * 对记录进行聚合统计(COUNT, SUM, AVG, MIN, MAX,可选分组) + */ +export function aggregateRecordFields( + records: DatalinkRecord[], + entity: DatalinkEntity, + options: { + fields: string[]; + groupBy?: string; + } +): LedgerAggregateReport { + const resolvedFields = options.fields.map((f) => { + const resolved = resolveEntityField(entity, f); + return { + query: f, + field: resolved ?? { name: f, label: f, type: "number" }, + }; + }); + + const calcStats = (list: DatalinkRecord[]): Record => { + const stats: Record = {}; + for (const { query, field } of resolvedFields) { + let count = 0; + let sum = 0; + let min = Infinity; + let max = -Infinity; + + for (const r of list) { + const num = extractNumericFieldValue(r, field); + if (num !== null) { + count++; + sum += num; + if (num < min) min = num; + if (num > max) max = num; + } + } + + stats[query] = { + field: field.name, + fieldLabel: field.label || field.name, + count, + sum: Math.round(sum * 100) / 100, + avg: count > 0 ? Math.round((sum / count) * 100) / 100 : 0, + min: count > 0 ? min : 0, + max: count > 0 ? max : 0, + }; + } + return stats; + }; + + const overall = calcStats(records); + + let groups: GroupAggregateResult[] | undefined; + if (options.groupBy) { + const groupField = resolveEntityField(entity, options.groupBy) ?? { + name: options.groupBy, + label: options.groupBy, + type: "text", + }; + const groupMap = new Map(); + for (const r of records) { + const gVal = String(extractRecordFieldValue(r, groupField) ?? "(未填写)"); + const existing = groupMap.get(gVal); + if (existing) existing.push(r); + else groupMap.set(gVal, [r]); + } + + groups = Array.from(groupMap.entries()).map(([groupValue, groupRecords]) => ({ + groupValue, + count: groupRecords.length, + aggregates: calcStats(groupRecords), + })); + } + + return { + totalRecords: records.length, + overall, + groups, + }; +} + + +/** + * 台账序号连续性检查与期望基线数学核对 + */ +export function auditLedgerContinuityAndBaseline( + records: DatalinkRecord[], + entity: DatalinkEntity, + options: { + sequenceField?: string; + expectedValues?: Array<{ + field: string; + targetValue: number; + tolerance?: number; + }>; + } +): LedgerContinuityReport { + const issues: ContinuityIssue[] = []; + const outliers: LedgerContinuityReport["outliers"] = []; + + let sequenceSummary: LedgerContinuityReport["sequenceSummary"] | undefined; + + // 1. 序号连续性核查 + if (options.sequenceField) { + const resolvedSeqField = resolveEntityField(entity, options.sequenceField) ?? { + name: options.sequenceField, + label: options.sequenceField, + type: "number", + }; + + const seqMap = new Map(); + const numbers: number[] = []; + + for (const r of records) { + const num = extractNumericFieldValue(r, resolvedSeqField); + if (num !== null) { + const intVal = Math.round(num); + numbers.push(intVal); + const existing = seqMap.get(intVal); + const rId = r.id || String(r.recordId || ""); + if (existing) existing.push(rId); + else seqMap.set(intVal, [rId]); + } + } + + if (numbers.length > 0) { + const min = Math.min(...numbers); + const max = Math.max(...numbers); + const missing: number[] = []; + const duplicates: number[] = []; + + for (let i = min; i <= max; i++) { + const count = seqMap.get(i)?.length ?? 0; + if (count === 0) { + missing.push(i); + issues.push({ + type: "MISSING_SEQUENCE", + field: resolvedSeqField.name, + message: `台账序号断层:缺少第 [${i}] 期记录`, + expected: i, + actual: null, + }); + } else if (count > 1) { + duplicates.push(i); + issues.push({ + type: "DUPLICATE_SEQUENCE", + field: resolvedSeqField.name, + message: `台账序号重号:第 [${i}] 期存在 ${count} 条重复记录 (${seqMap.get(i)?.join(", ")})`, + expected: 1, + actual: count, + }); + } + } + + sequenceSummary = { + field: resolvedSeqField.name, + fieldLabel: resolvedSeqField.label || resolvedSeqField.name, + min, + max, + expectedCount: max - min + 1, + actualCount: numbers.length, + missing, + duplicates, + }; + } + } + + // 2. 基线离群异常核对 + if (options.expectedValues && options.expectedValues.length > 0) { + for (const exp of options.expectedValues) { + const field = resolveEntityField(entity, exp.field) ?? { + name: exp.field, + label: exp.field, + type: "number", + }; + const tolerance = exp.tolerance ?? 0.05; + + for (const r of records) { + const val = extractNumericFieldValue(r, field); + if (val !== null) { + const diff = Math.abs(val - exp.targetValue); + if (diff > tolerance) { + const rId = r.id || String(r.recordId || ""); + outliers.push({ + recordId: rId, + field: field.name, + fieldLabel: field.label || field.name, + value: val, + expectedValue: exp.targetValue, + diff: Math.round(diff * 100) / 100, + }); + issues.push({ + type: "VALUE_OUTLIER", + recordId: rId, + field: field.name, + message: `记录 [${rId}] 字段 [${field.label || field.name}] 数值 [${val}] 偏离基线期望 [${exp.targetValue}] (差额: ${diff > 0 ? "+" : ""}${Math.round(diff * 100) / 100})`, + expected: exp.targetValue, + actual: val, + }); + } + } + } + } + } + + return { + totalRecords: records.length, + sequenceSummary, + issues, + outliers, + }; +} diff --git a/src/domains/datalink/datalink.test.ts b/src/domains/platform/datalink/datalink.test.ts similarity index 99% rename from src/domains/datalink/datalink.test.ts rename to src/domains/platform/datalink/datalink.test.ts index e3eef5a..48eb9a2 100644 --- a/src/domains/datalink/datalink.test.ts +++ b/src/domains/platform/datalink/datalink.test.ts @@ -1,15 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { - buildSafeRecordEditPayload, - editRecord, - getPlatform, - getRecordDetail, - listPlatformEntities, - listPlatforms, - recomputeRecordLedger, - searchEntityRecords, - toggleRecordState, -} from "./api.js"; +import { buildSafeRecordEditPayload, editRecord, getRecordDetail, listPlatformEntities, recomputeRecordLedger, searchEntityRecords, toggleRecordState } from "./api.js"; +import { getPlatform, listPlatforms } from "../applications/api.js"; import { aggregateRecordFields, auditEntityRecords, diff --git a/src/domains/datalink/field-target.test.ts b/src/domains/platform/datalink/field-target.test.ts similarity index 100% rename from src/domains/datalink/field-target.test.ts rename to src/domains/platform/datalink/field-target.test.ts diff --git a/src/domains/datalink/fields.ts b/src/domains/platform/datalink/fields.ts similarity index 95% rename from src/domains/datalink/fields.ts rename to src/domains/platform/datalink/fields.ts index a6322dc..245243a 100644 --- a/src/domains/datalink/fields.ts +++ b/src/domains/platform/datalink/fields.ts @@ -1,4 +1,4 @@ -import { ValidationError } from "../../core/errors.js"; +import { ValidationError } from "../../../core/errors.js"; import type { DatalinkField } from "./types.js"; /** 物理键优先;标签和模糊匹配必须指向唯一物理字段。未知字段由调用方决定是否透传。 */ diff --git a/src/domains/platform/datalink/predicates.ts b/src/domains/platform/datalink/predicates.ts new file mode 100644 index 0000000..9605115 --- /dev/null +++ b/src/domains/platform/datalink/predicates.ts @@ -0,0 +1,295 @@ +import { ValidationError } from "../../../core/errors.js"; +import type { DatalinkEntity, DatalinkField, DatalinkRecord } from "./types.js"; +import { resolveEntityField, extractRecordFieldValue, extractNumericFieldValue } from "./records.js"; + + +export interface BuildKeywordFilterOptions { + entity?: DatalinkEntity; + searchFields?: string[]; +} + + +/** + * 格式化服务端 filterBy 字段表达式。 + * 针对 DataLink 特性: + * - 动态业务字段(E_ 前缀)自动附加 form. 命名空间 + * - money 货币复合对象自动下钻到 .standard 标准字符串 + * - number 数值字段支持比较运算符 + */ +export function formatServerFieldExpr( + fieldKey: string, + op: string, + rawVal: string, + entity?: DatalinkEntity +): string { + const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined; + const targetKey = resolved?.name || fieldKey; + const isCustom = targetKey.startsWith("E_"); + const serverPath = isCustom ? `form.${targetKey}` : targetKey; + const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== ""; + + // Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... }) + if (resolved?.type === "money") { + const moneyPath = `${serverPath}.standard`; + const num = Number(rawVal); + const withDec = !Number.isNaN(num) && !rawVal.includes("../../datalink") ? `${rawVal}.00` : rawVal; + if (op === "=" || op === "==") { + if (withDec !== rawVal) { + return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`; + } + return `${moneyPath}=="${escaped}"`; + } + if (op === "!=") { + return `${moneyPath}!="${escaped}"`; + } + return `${moneyPath}.containsIgnoreCase("${escaped}")`; + } + + // Number 字段 + if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) { + if (op === "~" || op === "=~" || op === ":") { + return `${serverPath}.containsIgnoreCase("${escaped}")`; + } + const cmp = op === "=" ? "==" : op; + return `${serverPath}${cmp}${rawVal}`; + } + + // Text / Ref / Other 字段 + if (op === "~" || op === "=~" || op === ":") { + return `${serverPath}.containsIgnoreCase("${escaped}")`; + } + if (op === "!=") { + return `${serverPath}!="${escaped}"`; + } + return `${serverPath}=="${escaped}"`; +} + + +export function buildKeywordFilter( + keyword: string, + options?: BuildKeywordFilterOptions +): string { + const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const conds: string[] = [ + `name.containsIgnoreCase("${escaped}")`, + `code.containsIgnoreCase("${escaped}")`, + ]; + + if (options?.entity && options.searchFields && options.searchFields.length > 0) { + for (const searchField of options.searchFields) { + const resolved = resolveEntityField(options.entity, searchField); + const targetName = resolved?.name || searchField; + if (targetName && targetName !== "name" && targetName !== "code") { + const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity); + conds.push(expr); + } + } + } + + return `(${conds.join("||")})&&(active.in(true,false))`; +} + + +/** + * 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。 + * 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。 + */ +export function buildServerFieldFilter( + filterInput: string, + entity?: DatalinkEntity +): string { + const trimmed = filterInput.trim(); + if ( + trimmed.startsWith("(") || + trimmed.includes(".containsIgnoreCase(") || + trimmed.includes(".in(") || + trimmed.includes("==") + ) { + return trimmed; + } + + // 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用" + const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/); + if (!match) return trimmed; + + const rawKey = match[1].trim(); + const op = match[2]; + const rawVal = match[3].trim().replace(/^["']|["']$/g, ""); + + const expr = formatServerFieldExpr(rawKey, op, rawVal, entity); + return expr ? `(${expr})&&(active.in(true,false))` : trimmed; +} + + +/** + * 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合) + */ +function splitPredicateParts(source: string, separator: string): string[] { + const parts: string[] = []; + let quote = "", depth = 0, start = 0; + for (let i = 0; i < source.length; i++) { + const char = source[i]; + if (quote) { + if (char === "\\") i++; + else if (char === quote) quote = ""; + continue; + } + if (char === "'" || char === '"') quote = char; + else if (char === "(") depth++; + else if (char === ")") { + if (--depth < 0) throw new ValidationError("筛选条件括号不匹配"); + } else if (depth === 0 && source.startsWith(separator, i)) { + parts.push(source.slice(start, i).trim()); + start = i + separator.length; + i += separator.length - 1; + } + } + if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配"); + parts.push(source.slice(start).trim()); + if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空"); + return parts; +} + + +function predicateLiteral(raw: string): string | number | boolean | null { + if (/^(["']).*\1$/s.test(raw)) { + const value = raw.slice(1, -1); + if (raw[0] === '"') { + try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); } + } + if (/(? boolean { + const conditions = splitPredicateParts(whereClause, "&&").map(cond => { + // 1. in 操作符: field in (v1, v2, v3) + const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i); + // 2. 比较操作符: ==, !=, >=, <=, >, <, = + const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s); + if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`); + const field = predicateField(entity, (inMatch ?? compMatch)![1].trim()); + const op = inMatch ? "in" : compMatch![2]; + const targets = inMatch + ? splitPredicateParts(inMatch[2], ",").map(predicateLiteral) + : [predicateLiteral(compMatch![3].trim())]; + return (record: DatalinkRecord) => { + const actual = extractRecordFieldValue(record, field); + const equal = (target: string | number | boolean | null): boolean => { + if (target === null) return actual === null || actual === undefined; + if (typeof target === "number") return extractNumericFieldValue(record, field) === target; + return actual !== null && actual !== undefined && String(actual) === String(target); + }; + if (op === "in") return targets.some(equal); + // 字符串/布尔比较 + if (op === "=" || op === "==") return equal(targets[0]); + if (op === "!=") return !equal(targets[0]); + // 数值比较 + const value = extractNumericFieldValue(record, field); + const target = targets[0]; + if (value === null || typeof target !== "number") return false; + return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target; + }; + }); + return record => conditions.every(condition => condition(record)); +} + + +export function filterRecordsByPredicate( + records: DatalinkRecord[], + whereClause: string, + entity: DatalinkEntity +): DatalinkRecord[] { + if (!whereClause || !whereClause.trim()) return records; + return records.filter(compileRecordPredicate(whereClause, entity)); +} + + +/** + * 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销" + */ +export function parseSetClause( + setClause: string, + entity: DatalinkEntity +): Record { + const result: Record = {}; + let assignments: string[]; + try { assignments = splitPredicateParts(setClause, ","); } + catch { throw new ValidationError("赋值表达式引号或括号不匹配,且赋值项不能为空"); } + + for (const assign of assignments) { + const eqIdx = assign.indexOf("="); + if (eqIdx === -1) throw new ValidationError(`赋值项缺少等号: ${assign}`); + const rawKey = assign.slice(0, eqIdx).trim(); + if (!rawKey) throw new ValidationError("赋值字段不能为空"); + let rawVal = assign.slice(eqIdx + 1).trim(); + + // 去除外层引号,同时保留显式字符串的类型与转义语义。 + const quoted = (rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'")); + const literal = quoted ? predicateLiteral(rawVal) : undefined; + + const field = resolveEntityField(entity, rawKey); + const targetKey = field ? field.name : rawKey; + + // 类型智能转换 + if (quoted) { + result[targetKey] = literal; + } else if (rawVal === "true") { + result[targetKey] = true; + } else if (rawVal === "false") { + result[targetKey] = false; + } else if (rawVal === "null") { + result[targetKey] = null; + } else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") { + result[targetKey] = Number(rawVal); + } else { + result[targetKey] = rawVal; + } + } + + return result; +} + + +/** + * 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05" + */ +export function parseExpectClause( + expectClause: string +): Array<{ field: string; targetValue: number; tolerance?: number }> { + if (!expectClause || !expectClause.trim()) return []; + const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean); + const results: Array<{ field: string; targetValue: number; tolerance?: number }> = []; + + for (const part of parts) { + const match = part.match( + /^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/ + ); + if (match) { + const field = match[1].trim(); + const targetValue = parseFloat(match[2]); + const tolerance = match[3] ? parseFloat(match[3]) : undefined; + if (!Number.isNaN(targetValue)) { + results.push({ field, targetValue, tolerance }); + } + } + } + return results; +} diff --git a/src/domains/platform/datalink/records.ts b/src/domains/platform/datalink/records.ts new file mode 100644 index 0000000..1f50e2a --- /dev/null +++ b/src/domains/platform/datalink/records.ts @@ -0,0 +1,497 @@ +import type { KyInstance } from "ky"; +import * as api from "./api.js"; +import { resolveDatalinkField } from "./fields.js"; +import type { DatalinkEntity, DatalinkField, DatalinkRecord, DatalinkRecordEditPayload, DatalinkRecordPage, NormalizedDatalinkRecord } from "./types.js"; +import type { DatalinkPlatformDetail } from "../applications/types.js"; + + +export function listPlatformEntities(...args: Parameters) { + return api.listPlatformEntities(...args); +} + + +export function searchEntityRecords(...args: Parameters) { + return api.searchEntityRecords(...args); +} + + +export function listImportJobs(...args: Parameters) { + return api.listImportJobs(...args); +} + + +export function getImportResult(...args: Parameters) { + return api.getImportResult(...args); +} + + +export function toggleRecordState(...args: Parameters) { + return api.toggleRecordState(...args); +} + + +export function getRecordDetail(...args: Parameters) { + return api.getRecordDetail(...args); +} + + +export function getRecordFormSchema(...args: Parameters) { + return api.getRecordFormSchema(...args); +} + + +export function editRecord(...args: Parameters) { + return api.editRecord(...args); +} + + +export function buildSafeRecordEditPayload(...args: Parameters) { + return api.buildSafeRecordEditPayload(...args); +} + + +export function safeEditRecord(...args: Parameters) { + return api.safeEditRecord(...args); +} + + +export function recomputeRecordLedger(...args: Parameters) { + return api.recomputeRecordLedger(...args); +} + + +function matches(value: unknown, target: string): boolean { + return typeof value === "string" && value.toLowerCase() === target.toLowerCase(); +} + + +export async function resolveEntity( + client: KyInstance, + corpId: string, + platform: DatalinkPlatformDetail, + target: string +): Promise { + const entities = await api.listPlatformEntities(client, corpId, platform.id); + return entities.find((entity) => + [entity.id, entity.name, entity.code].some((value) => matches(value, target)) + ); +} + + +export function selectRecordFields( + record: Record, + fields: string[], + definitions: DatalinkField[] = [] +): Record { + if (fields.length === 0) return record; + const dataLink = + record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) + ? (record.dataLink as Record) + : record; + const selected: Record = {}; + const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields) + ? record.fields as Record + : undefined; + for (const selector of fields) { + const definition = definitions.find( + (field) => field.name === selector || field.label === selector + ); + const sourceName = definition?.name ?? selector; + const label = definition?.label || selector; + if (sourceName in dataLink) selected[label] = dataLink[sourceName]; + else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label]; + else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName]; + else if (normalizedFields) { + const systemName = sourceName.replace(/^E_.+_/, ""); + if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName]; + } + } + return record.dataLink && typeof record.dataLink === "object" + ? { ...record, dataLink: selected } + : selected; +} + + +/** + * 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。 + */ +export async function fetchAllEntityRecords( + client: KyInstance, + corpId: string, + entityId: string, + options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} +): Promise { + const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); + let start = 0; + let total = 0; + const allData: DatalinkRecord[] = []; + let firstPage: DatalinkRecordPage | undefined; + + while (true) { + const page = await api.searchEntityRecords(client, corpId, entityId, { + start, + count: pageSize, + filterBy: options.filterBy, + orderBy: options.orderBy, + }); + firstPage ??= page; + total = page.total; + if (page.data.length === 0) break; + allData.push(...page.data); + start += page.data.length; + if (allData.length >= total || page.data.length < pageSize) { + break; + } + } + + return { + total: Math.max(total, allData.length), + data: allData, + actions: firstPage?.actions ?? [], + components: firstPage?.components ?? [], + path: firstPage?.path, + template: firstPage?.template, + }; +} + + +/** + * 流式异步迭代器:逐页拉取并逐条产出业务对象记录。 + * 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。 + */ +export async function* iterateAllEntityRecords( + client: KyInstance, + corpId: string, + entityId: string, + options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} +): AsyncGenerator { + const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); + let start = 0; + let total = 0; + let yielded = 0; + + while (true) { + const page = await api.searchEntityRecords(client, corpId, entityId, { + start, + count: pageSize, + filterBy: options.filterBy, + orderBy: options.orderBy, + }); + total = page.total; + if (page.data.length === 0) break; + for (const record of page.data) { + yield record; + yielded++; + } + start += page.data.length; + if (yielded >= total || page.data.length < pageSize) { + break; + } + } +} + + +/** + * 将数据互联原始报文规范化为标准、扁平、脱敏于动态前缀的结构。 + * 彻底消除 r.id vs r.dataLink.id 以及 E__ 动态前缀的困扰。 + */ +export function normalizeDatalinkRecord( + rawRecord: DatalinkRecord, + entity?: DatalinkEntity, + options: { includeRaw?: boolean } = {} +): NormalizedDatalinkRecord { + const dl = + rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink) + ? (rawRecord.dataLink as Record) + : (rawRecord as Record); + + const entityId = String(entity?.id ?? dl.entityId ?? rawRecord.entityId ?? ""); + const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId; + + const id = String(dl.id ?? rawRecord.id ?? ""); + const active = (dl.active ?? rawRecord.active) !== false; + const createTime = (dl.createTime ?? rawRecord.createTime ?? null) as number | null; + const updateTime = (dl.updateTime ?? rawRecord.updateTime ?? null) as number | null; + + const nameField = entity?.fields.find( + (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") + ); + const codeField = entity?.fields.find( + (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") + ); + + const name = String( + dl.name ?? + dl["名称"] ?? + (nameField ? dl[nameField.name] : undefined) ?? + (bareEntityId ? dl[`E_${bareEntityId}_name`] : undefined) ?? + "" + ); + + const code = String( + dl.code ?? + dl["编码"] ?? + (codeField ? dl[codeField.name] : undefined) ?? + (bareEntityId ? dl[`E_${bareEntityId}_code`] : undefined) ?? + "" + ); + + const fields: Record = {}; + if (entity?.fields) { + for (const field of entity.fields) { + if (field.name === nameField?.name || field.name === codeField?.name) continue; + const keyCandidates = [ + field.name, + bareEntityId ? `E_${bareEntityId}_${field.name}` : undefined, + field.label, + ].filter(Boolean) as string[]; + + let val: unknown = undefined; + for (const key of keyCandidates) { + if (key in dl) { + val = dl[key]; + break; + } + } + + if (val !== undefined && val !== null) { + if (typeof val === "object" && !Array.isArray(val)) { + const obj = val as Record; + if ("standard" in obj) { + val = obj.standard; + } else if ("name" in obj && typeof obj.name === "string" && obj.name) { + val = obj.name; + } else { + let targetDataLink: Record | undefined = undefined; + if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) { + targetDataLink = obj.dataLink as Record; + } else if ("data" in obj && typeof obj.data === "object" && obj.data && "dataLink" in (obj.data as Record)) { + targetDataLink = (obj.data as Record).dataLink as Record; + } + + if (targetDataLink) { + const form = (targetDataLink.form && typeof targetDataLink.form === "object" ? targetDataLink.form : {}) as Record; + const combined = { ...targetDataLink, ...form }; + let subDisplay: string | undefined = undefined; + for (const [k, v] of Object.entries(combined)) { + if (typeof v === "string" && v.trim() && (k === "name" || k === "title" || k === "名称" || k === "标题" || k.endsWith("_name") || k.endsWith("_title"))) { + subDisplay = v; + break; + } + } + if (!subDisplay) { + for (const [k, v] of Object.entries(combined)) { + if (typeof v === "string" && v.trim() && (k === "code" || k === "编码" || k.endsWith("_code") || k.includes("编号"))) { + subDisplay = v; + break; + } + } + } + val = subDisplay || (targetDataLink.id ? String(targetDataLink.id) : undefined) || (obj.id ? String(obj.id) : undefined); + } else if (obj.id && typeof obj.id === "string") { + val = obj.id; + } + } + } + fields[field.label || field.name] = val; + } + } + } + + return { + id, + code, + name, + active, + createTime, + updateTime, + fields, + ...(options.includeRaw ? { raw: rawRecord } : {}), + }; +} + + +export function extractRefIdAndName(value: unknown): { + id?: string; + name?: string; + active?: boolean; +} { + if (typeof value === "string" && value.trim()) { + return { id: value.trim() }; + } + if (!value || typeof value !== "object" || Array.isArray(value)) { + return {}; + } + const obj = value as Record; + const nestedData = + obj.data && typeof obj.data === "object" + ? (obj.data as Record) + : undefined; + const nestedDl = + nestedData?.dataLink && typeof nestedData.dataLink === "object" + ? (nestedData.dataLink as Record) + : obj.dataLink && typeof obj.dataLink === "object" + ? (obj.dataLink as Record) + : undefined; + const id = + typeof obj.id === "string" && obj.id.trim() + ? obj.id.trim() + : typeof nestedDl?.id === "string" && nestedDl.id.trim() + ? nestedDl.id.trim() + : undefined; + const name = + typeof obj.name === "string" && obj.name.trim() + ? obj.name.trim() + : typeof nestedDl?.name === "string" && nestedDl.name.trim() + ? nestedDl.name.trim() + : undefined; + const active = + typeof obj.active === "boolean" + ? obj.active + : typeof nestedDl?.active === "boolean" + ? nestedDl.active + : undefined; + return { id, name, active }; +} + + +export interface BatchEditTargetItem { + recordId: string; + patchForm: Record; + active?: boolean; +} + + +export interface BatchEditItemResult { + recordId: string; + status: "preview" | "updated" | "failed"; + payload?: DatalinkRecordEditPayload; + result?: Record; + error?: string; +} + + +export async function batchSafeEditRecords( + client: KyInstance, + corpId: string, + entity: DatalinkEntity, + targets: BatchEditTargetItem[], + options: { concurrency?: number; dryRun?: boolean } = {} +): Promise { + const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32)); + const results: BatchEditItemResult[] = new Array(targets.length); + let cursor = 0; + + const worker = async () => { + while (true) { + const idx = cursor++; + if (idx >= targets.length) break; + const target = targets[idx]; + try { + const detail = await api.getRecordDetail(client, corpId, target.recordId); + const payload = api.buildSafeRecordEditPayload({ + entityId: entity.id, + recordId: target.recordId, + detail, + fields: entity.fields, + patchForm: target.patchForm, + active: target.active, + }); + if (options.dryRun) { + results[idx] = { + recordId: target.recordId, + status: "preview", + payload, + }; + } else { + const res = await api.editRecord(client, corpId, payload); + results[idx] = { + recordId: target.recordId, + status: "updated", + payload, + result: res, + }; + } + } catch (error) { + results[idx] = { + recordId: target.recordId, + status: "failed", + error: error instanceof Error ? error.message : String(error), + }; + } + } + }; + + await Promise.all( + Array.from({ length: Math.min(concurrency, targets.length) }, () => worker()) + ); + return results; +} + + +// ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ─────────────────── + +/** + * 根据字段名或标签模糊解析实体字段元数据 + */ +export function resolveEntityField( + entity: DatalinkEntity, + query: string +): DatalinkField | undefined { + return resolveDatalinkField(entity.fields, entity.id, query); +} + + +/** + * 通用提取记录中某一字段的原始值 + */ +export function extractRecordFieldValue( + record: DatalinkRecord, + field: DatalinkField | string +): unknown { + const source = + record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) + ? (record.dataLink as Record) + : record; + const fieldName = typeof field === "string" ? field : field.name; + const fieldLabel = typeof field === "string" ? undefined : field.label; + + let val = source[fieldName] ?? record[fieldName]; + if (val === undefined && fieldLabel) { + val = source[fieldLabel] ?? record[fieldLabel]; + } + if (val === undefined && record.form && typeof record.form === "object") { + val = (record.form as Record)[fieldName]; + if (val === undefined && fieldLabel) { + val = (record.form as Record)[fieldLabel]; + } + } + return val; +} + + +/** + * 提取记录中某一字段的数值(兼容数值、货币对象与格式化字符串) + */ +export function extractNumericFieldValue( + record: DatalinkRecord, + field: DatalinkField | string +): number | null { + const val = extractRecordFieldValue(record, field); + if (val === null || val === undefined || val === "") return null; + if (typeof val === "number" && !Number.isNaN(val)) return val; + if (typeof val === "object" && !Array.isArray(val)) { + const std = (val as any).standard ?? (val as any).amount; + if (typeof std === "number" && !Number.isNaN(std)) return std; + if (typeof std === "string") { + const parsed = parseFloat(std); + if (!Number.isNaN(parsed)) return parsed; + } + } + if (typeof val === "string") { + const clean = val.replace(/^[¥$¥\s,]+/, "").replace(/,/g, ""); + const parsed = parseFloat(clean); + if (!Number.isNaN(parsed)) return parsed; + } + return null; +} diff --git a/src/domains/platform/datalink/services.ts b/src/domains/platform/datalink/services.ts new file mode 100644 index 0000000..60665b4 --- /dev/null +++ b/src/domains/platform/datalink/services.ts @@ -0,0 +1,53 @@ +// datalink 业务服务出口;具体实现按职责拆分,内部模块避免反向导入此门面。 +export { + listPlatformEntities, + searchEntityRecords, + listImportJobs, + getImportResult, + toggleRecordState, + getRecordDetail, + getRecordFormSchema, + editRecord, + buildSafeRecordEditPayload, + safeEditRecord, + recomputeRecordLedger, + resolveEntity, + selectRecordFields, + fetchAllEntityRecords, + iterateAllEntityRecords, + normalizeDatalinkRecord, + batchSafeEditRecords, + resolveEntityField, + extractRecordFieldValue, + extractNumericFieldValue, +} from "./records.js"; +export type { + BatchEditTargetItem, + BatchEditItemResult, +} from "./records.js"; +export { + formatServerFieldExpr, + buildKeywordFilter, + buildServerFieldFilter, + compileRecordPredicate, + filterRecordsByPredicate, + parseSetClause, + parseExpectClause, +} from "./predicates.js"; +export type { + BuildKeywordFilterOptions, +} from "./predicates.js"; +export { + calculateEntityRecordStats, + auditEntityRecords, + aggregateRecordFields, + auditLedgerContinuityAndBaseline, +} from "./audit.js"; +export type { + DatalinkAuditIssue, + DatalinkAuditReport, +} from "./audit.js"; + +export type { + SafeRecordEditOptions, +} from "./api.js"; diff --git a/src/domains/datalink/set-literals.test.ts b/src/domains/platform/datalink/set-literals.test.ts similarity index 100% rename from src/domains/datalink/set-literals.test.ts rename to src/domains/platform/datalink/set-literals.test.ts diff --git a/src/domains/datalink/set-separators.test.ts b/src/domains/platform/datalink/set-separators.test.ts similarity index 100% rename from src/domains/datalink/set-separators.test.ts rename to src/domains/platform/datalink/set-separators.test.ts diff --git a/src/domains/datalink/types.ts b/src/domains/platform/datalink/types.ts similarity index 92% rename from src/domains/datalink/types.ts rename to src/domains/platform/datalink/types.ts index 647b9e5..45cd46e 100644 --- a/src/domains/datalink/types.ts +++ b/src/domains/platform/datalink/types.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { PlatformSchema } from "../platform/types.js"; +import type { DatalinkPlatformDetail } from "../applications/types.js"; const NullableBoolean = z.boolean().nullable().optional(); @@ -68,13 +68,6 @@ export const DatalinkEntitySchema = z }) .passthrough(); -export const DatalinkPlatformDetailSchema = PlatformSchema.passthrough().extend({ - staffIds: z.array(z.string()).nullish().transform((value) => value ?? []), - roleIds: z.array(z.string()).nullish().transform((value) => value ?? []), - departmentIds: z.array(z.string()).nullish().transform((value) => value ?? []), - departmentsIncludeChildren: z.boolean().nullish().transform((value) => value ?? false), -}); - export interface DatalinkRecordQuery { start?: number; count?: number; @@ -114,7 +107,7 @@ export interface DatalinkImportJob { export type DatalinkField = z.infer; export type DatalinkEntity = z.infer; -export type DatalinkPlatformDetail = z.infer; +export type { DatalinkPlatformDetail } from "../applications/types.js"; export interface DatalinkPermissionSnapshot { platform: DatalinkPlatformDetail; diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts deleted file mode 100644 index 06f1bae..0000000 --- a/src/domains/platform/services.ts +++ /dev/null @@ -1,1094 +0,0 @@ -import { KyInstance } from "ky"; -import { CorpConfig } from "../../core/config/types.js"; -import { WorkflowSavePartialError } from "./workflow/save-error.js"; -import * as api from "./api.js"; -import { PermissionError, ValidationError } from "../../core/errors.js"; -import { explainConditionBranches } from "./workflow/branch/index.js"; -import { indexExecutionContexts } from "./execution-context.js"; -import { - Platform, - WorkflowSummary, - WorkflowListAllError, - WorkflowTask, - WorkflowTaskExecution, - WorkflowWithMatches, - TaskMatch, - WorkflowSnapshot, - WorkflowSnapshotDiff, - TaskConfigDiff, - WorkflowJobDetail, - WorkflowJobDiff, - NodeExecutionDiff, -} from "./types.js"; - -export interface PlatformClients { - corp: CorpConfig; - ekbClient: KyInstance; - easoClient: KyInstance; -} - -export function listPlatforms(...args: Parameters) { - return api.listPlatforms(...args); -} - -export function listWorkflows(...args: Parameters) { - return api.listWorkflows(...args); -} - -export function getWorkflowStats(...args: Parameters) { - return api.getWorkflowStats(...args); -} - -export function getWorkflowCharge(...args: Parameters) { - return api.getWorkflowCharge(...args); -} - -export function getWorkflowDetail(...args: Parameters) { - return api.getWorkflowDetail(...args); -} - -export function sanitizeWorkflowSnapshot( - detail: import("./types.js").WorkflowDetail -): import("./types.js").WorkflowDetail { - const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; - if (Array.isArray(cloned.$snapshot)) { - cloned.$snapshot = cloned.$snapshot.map((entry) => { - if (typeof entry.value === "string" && entry.value.includes("docs.ekuaibao.com")) { - return { - ...entry, - value: entry.value.replaceAll("docs.ekuaibao.com", "app.ekuaibao.com"), - }; - } - return entry; - }); - } - return cloned; -} - -export async function updateWorkflow( - client: KyInstance, - workflow: import("./types.js").WorkflowDetail, - platformId?: string -) { - // 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。 - const payload: import("./types.js").WorkflowDetail = platformId && !workflow.inputs?.length - ? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] } - : workflow; - const sanitized = sanitizeWorkflowSnapshot(payload); - const updated = await api.updateWorkflow(client, sanitized); - // 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。 - try { - await api.updateWorkflowChooses(client, updated.id || workflow.id); - } catch (error) { - throw new WorkflowSavePartialError(updated, error); - } - return updated; -} - -/** 只重试元数据刷新,不重新提交完整工作流快照。 */ -export function refreshWorkflowChooses(client: KyInstance, pipelineId: string): Promise { - return api.updateWorkflowChooses(client, pipelineId); -} - -export async function copyWorkflow( - client: import("ky").KyInstance, - pipelineId: string, - options: { label?: string; platformId?: string } = {} -): Promise { - const detail = await api.getWorkflowDetail(client, pipelineId); - const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; - if (options.label) { - cloned.label = options.label; - } else if (!cloned.label.includes("副本")) { - cloned.label = `${cloned.label} 副本`; - } - if (options.platformId) { - cloned.platformId = options.platformId; - } - // 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本 - if (cloned.tasks?.[0]?.type === "webhook") { - (cloned.tasks[0] as any).urlPath = crypto.randomUUID(); - delete (cloned.tasks[0] as any).sampleId; - } - const result = await api.copyWorkflow(client, pipelineId, cloned); - if (options.label && result.label !== options.label) { - result.label = options.label; - return updateWorkflow(client, result, options.platformId ?? (result as any).platformId); - } - return result; -} - -export interface CreateWorkflowOptions { - label?: string; - platformId?: string; - trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string; - file?: string; - workflow?: Record; - state?: number; - desc?: string; -} - -export function buildInitialTriggerTask(triggerType: string): WorkflowTask { - const norm = triggerType.toLowerCase().trim(); - switch (norm) { - case "webhook": - return { - name: "trigger_webhook", - type: "webhook", - label: "Webhook触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - urlPath: crypto.randomUUID(), - params: [], - }; - case "clock": - case "schedule": - case "timer": - return { - name: "trigger_clock", - type: "clock", - label: "定时触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - cron: "0 0 * * *", - timeZone: "Asia/Shanghai", - }; - case "datalink": - case "data-link": - case "entity": - return { - name: "trigger_datalink_create", - type: "ekuaibao-datalink-create-trigger", - label: "业务对象新增时触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - }; - case "flowform": - case "flow": - case "bill": - return { - name: "trigger_flowform", - type: "ekuaibao-flowform-trigger", - label: "单据审批事件触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - }; - default: - return { - name: `trigger_${norm.replace(/-/g, "_")}`, - type: norm, - label: `${norm}触发`, - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - }; - } -} - -export async function createWorkflow( - client: import("ky").KyInstance, - options: CreateWorkflowOptions = {} -): Promise { - let base: Record = {}; - if (options.file) { - const fs = await import("fs/promises"); - const raw = await fs.readFile(options.file, "utf-8"); - base = JSON.parse(raw); - } else if (options.workflow) { - base = JSON.parse(JSON.stringify(options.workflow)); - } - - const payload: Record = { - ...base, - label: options.label || base.label || "未命名流程", - state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承 - }; - - if (options.platformId || base.platformId) { - payload.platformId = options.platformId || base.platformId; - } - if (options.desc || base.desc) { - payload.desc = options.desc || base.desc; - } - - // 触发器节点初始化 - if (!payload.tasks || payload.tasks.length === 0) { - if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") { - payload.tasks = [buildInitialTriggerTask(options.trigger)]; - } else { - payload.tasks = []; - } - } else if (payload.tasks[0]?.type === "webhook") { - if (!payload.tasks[0].urlPath) { - payload.tasks[0].urlPath = crypto.randomUUID(); - } - } - - return api.createWorkflow(client, payload); -} - -export function deleteWorkflow(...args: Parameters) { - return api.deleteWorkflow(...args); -} - -export function listWorkflowSnapshots(...args: Parameters) { - return api.listWorkflowSnapshots(...args); -} - -export function getWorkflowSnapshot(...args: Parameters) { - return api.getWorkflowSnapshot(...args); -} - -export function listWorkflowLogs(...args: Parameters) { - return api.listWorkflowLogs(...args); -} - -export function toggleWorkflow(...args: Parameters) { - return api.toggleWorkflow(...args); -} - -export function listRunningJobs(...args: Parameters) { - return api.listRunningJobs(...args); -} - -export function getJob(...args: Parameters) { - return api.getJob(...args); -} - -export function getJobExecutionTree(...args: Parameters) { - return api.getJobExecutionTree(...args); -} - -export function getJobFailedExecutions(...args: Parameters) { - return api.getJobFailedExecutions(...args); -} - -export function getJobExecutionLevel(...args: Parameters) { - return api.getJobExecutionLevel(...args); -} - -export function getExecutionLogs(...args: Parameters) { - return api.getExecutionLogs(...args); -} - -export function listDsl(...args: Parameters) { - return api.listDsl(...args); -} - -export function listStaffs(...args: Parameters) { - return api.listStaffs(...args); -} - -export function getWebhookInfo(...args: Parameters) { - return api.getWebhookInfo(...args); -} - -export function sampleWorkflowData(...args: Parameters) { - return api.sampleWorkflowData(...args); -} - -// ── 服务层:跨应用聚合 ─────────────────────────────────────────────────────── - -export interface ListAllWorkflowsOptions { - page?: number; - pageSize?: number; -} - -export interface ListAllWorkflowsResult { - workflows: WorkflowSummary[]; - errors: WorkflowListAllError[]; -} - -export async function listAllWorkflows( - clients: PlatformClients, - options: ListAllWorkflowsOptions = {} -): Promise { - const { ekbClient, easoClient, corp } = clients; - const page = options.page ?? 1; - const pageSize = options.pageSize ?? 20; - - const platforms = await api.listPlatforms(ekbClient, corp.credentials.corpId); - const enabledPlatforms = platforms.filter((p) => p.active !== false); - - const workflows: WorkflowSummary[] = []; - const errors: WorkflowListAllError[] = []; - - await Promise.all( - enabledPlatforms.map(async (platform) => { - try { - const pageResult = await api.listWorkflows( - easoClient, - platform.id, - page, - pageSize - ); - for (const workflow of pageResult.pipelineList) { - workflows.push({ - ...workflow, - platformId: platform.id, - platformName: platform.name, - }); - } - } catch (err) { - errors.push({ - platformId: platform.id, - platformName: platform.name, - error: err instanceof Error ? err.message : String(err), - }); - } - }) - ); - - return { workflows, errors }; -} - -function collectTasksByType( - tasks: WorkflowTask[], - taskType: string, - matches: TaskMatch[] = [] -): TaskMatch[] { - for (const task of tasks) { - if (task.type === taskType) { - matches.push({ - taskName: task.name, - taskType: task.type, - levelIndex: task.levelIndex, - }); - } - if ("tasks" in task && Array.isArray(task.tasks)) { - collectTasksByType(task.tasks as WorkflowTask[], taskType, matches); - } - } - return matches; -} - -export interface FindWorkflowsByTaskTypeOptions extends ListAllWorkflowsOptions { - includeDetail?: boolean; -} - -export interface FindWorkflowsByTaskTypeResult { - workflows: WorkflowWithMatches[]; - errors: WorkflowListAllError[]; -} - -export async function findWorkflowsByTaskType( - clients: PlatformClients, - taskType: string, - options: FindWorkflowsByTaskTypeOptions = {} -): Promise { - const { easoClient } = clients; - const { includeDetail, ...listOptions } = options; - - const all = await listAllWorkflows(clients, listOptions); - const matched: WorkflowWithMatches[] = []; - const detailErrors: WorkflowListAllError[] = []; - - for (const workflow of all.workflows) { - let tasks = workflow.tasks; - - if (includeDetail) { - try { - const detail = await api.getWorkflowDetail(easoClient, workflow.id); - tasks = detail.tasks; - } catch (err) { - detailErrors.push({ - platformId: workflow.platformId, - platformName: workflow.platformName, - error: err instanceof Error ? err.message : String(err), - }); - continue; - } - } - - const matchedTasks = collectTasksByType(tasks, taskType); - if (matchedTasks.length > 0) { - matched.push({ ...workflow, matchedTasks }); - } - } - - return { workflows: matched, errors: [...all.errors, ...detailErrors] }; -} - -/** - * 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组) - */ -export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] { - const result: WorkflowTaskExecution[] = []; - - function visit(node: any) { - if (!node || typeof node !== "object") return; - result.push(node as WorkflowTaskExecution); - - const children = node.children || node.tasks || node.subTasks || node.items; - if (Array.isArray(children)) { - for (const child of children) { - visit(child); - } - } - } - - for (const node of nodes) { - visit(node); - } - - return result; -} - -/** - * 精准判定某个节点是否执行异常或报错 - */ -export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean { - if (!node) return false; - const anyNode = node as any; - - if (node.error?.message || anyNode.errorMessage) return true; - if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true; - if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true; - if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true; - if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true; - - return false; -} - -/** - * 提取并去重执行树中的全部异常失败节点 - */ -export function extractFailureExecutions( - tree: WorkflowTaskExecution[], - failedItems: WorkflowTaskExecution[] = [] -): WorkflowTaskExecution[] { - const flattened = flattenExecutionTree(tree); - const map = new Map(); - - for (const item of failedItems) { - if (item?.id) { - map.set(item.id, item); - } - } - - for (const node of flattened) { - if (node?.id && isTaskExecutionFailed(node)) { - const existing = map.get(node.id); - if (!existing) { - map.set(node.id, node); - } else { - map.set(node.id, { - ...node, - ...existing, - error: existing.error ?? node.error, - inputs: existing.inputs ?? (node as any).inputs, - outputs: existing.outputs ?? (node as any).outputs, - }); - } - } - } - - return Array.from(map.values()); -} - -/** - * 按 ID、name、displayName 或 label 查找节点 - */ -export function findExecutionNode( - tree: WorkflowTaskExecution[], - query: string -): WorkflowTaskExecution | undefined { - const flattened = flattenExecutionTree(tree); - const q = query.trim().toLowerCase(); - if (!q) return undefined; - - // 1. 精确匹配 ID 或 name - const exact = flattened.find( - (n) => - n.id?.toLowerCase() === q || - n.name?.toLowerCase() === q || - n.displayName?.toLowerCase() === q - ); - if (exact) return exact; - - // 2. 包含匹配 name、label、displayName - return flattened.find( - (n) => - n.name?.toLowerCase().includes(q) || - n.label?.toLowerCase().includes(q) || - n.displayName?.toLowerCase().includes(q) - ); -} - -// ── 工作流快照与 Job 差异比对核心算法 ────────────────────────────────────────── - -/** - * 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点) - */ -export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] { - if (!tasks || !Array.isArray(tasks)) return []; - const result: WorkflowTask[] = []; - - function walk(list: WorkflowTask[]) { - for (const t of list) { - if (!t) continue; - result.push(t); - if (Array.isArray(t.tasks) && t.tasks.length > 0) { - walk(t.tasks); - } - } - } - - walk(tasks); - return result; -} - -/** - * 快速生成标准 Unified Diff 文本 - */ -export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string { - if (a === b) return ""; - const linesA = a.split(/\r?\n/); - const linesB = b.split(/\r?\n/); - const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`]; - - let start = 0; - while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) { - start++; - } - let endA = linesA.length - 1; - let endB = linesB.length - 1; - while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) { - endA--; - endB--; - } - - const hunkStart = Math.max(0, start - 2); - const hunkEndA = Math.min(linesA.length, endA + 3); - const hunkEndB = Math.min(linesB.length, endB + 3); - - output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`); - for (let i = hunkStart; i < start; i++) { - output.push(` ${linesA[i]}`); - } - for (let i = start; i <= endA; i++) { - output.push(`- ${linesA[i]}`); - } - for (let i = start; i <= endB; i++) { - output.push(`+ ${linesB[i]}`); - } - for (let i = endA + 1; i < hunkEndA; i++) { - output.push(` ${linesA[i]}`); - } - return output.join("\n"); -} - -/** - * 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异 - */ -export function diffWorkflowSnapshots( - snapshotA: WorkflowSnapshot, - snapshotB: WorkflowSnapshot -): WorkflowSnapshotDiff { - const tasksA = flattenWorkflowTasks(snapshotA.tasks); - const tasksB = flattenWorkflowTasks(snapshotB.tasks); - const indexPaths = (tasks: WorkflowTask[] = [], prefix = "tasks", paths = new Map()): Map => { - tasks.forEach((task, i) => { - const path = `${prefix}.${i}`; - if (task.name) paths.set(task.name, path); - if (task.tasks) indexPaths(task.tasks, `${path}.tasks`, paths); - }); - return paths; - }; - const pathsA = indexPaths(snapshotA.tasks || []); - const pathsB = indexPaths(snapshotB.tasks || []); - - const mapA = new Map(); - for (const t of tasksA) { - if (t?.name) mapA.set(t.name, t); - } - - const mapB = new Map(); - for (const t of tasksB) { - if (t?.name) mapB.set(t.name, t); - } - - const addedTasks: string[] = []; - const removedTasks: string[] = []; - const modifiedTasks: TaskConfigDiff[] = []; - - // 1. 查找新增节点 - for (const [name, tB] of mapB) { - if (!mapA.has(name)) { - addedTasks.push(name); - modifiedTasks.push({ - taskName: name, - displayName: tB.displayName || tB.label, - type: tB.type, - changeType: "ADDED", - configChanges: [], - }); - } - } - - // 2. 查找删除与修改节点 - for (const [name, tA] of mapA) { - const tB = mapB.get(name); - if (!tB) { - removedTasks.push(name); - modifiedTasks.push({ - taskName: name, - displayName: tA.displayName || tA.label, - type: tA.type, - changeType: "REMOVED", - configChanges: [], - }); - continue; - } - - // 两者均存在,深度比较配置与代码 - const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = []; - let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined; - let filterDiff: { from?: unknown; to?: unknown } | undefined; - - // 代码脚本比较 - const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined; - const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined; - if (codeA !== codeB) { - codeDiff = { - from: codeA, - to: codeB, - unifiedDiff: generateTextDiff( - codeA || "", - codeB || "", - `${snapshotA.version || snapshotA.id}`, - `${snapshotB.version || snapshotB.id}` - ), - }; - } - - // 过滤条件比较 (combineFilters / filters) - const filtersA = (tA as any).combineFilters ?? (tA as any).filters; - const filtersB = (tB as any).combineFilters ?? (tB as any).filters; - if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) { - filterDiff = { from: filtersA, to: filtersB }; - } - - // 关键字段变动比较 - const checkFields = [...new Set([...Object.keys(tA), ...Object.keys(tB)])] - .filter(field => !["name", "tasks", "code", "combineFilters", "filters"].includes(field)); - if (pathsA.get(name) !== pathsB.get(name)) { - configChanges.push({ field: "$path", from: pathsA.get(name), to: pathsB.get(name) }); - } - for (const f of checkFields) { - const valA = (tA as any)[f]; - const valB = (tB as any)[f]; - if (JSON.stringify(valA) !== JSON.stringify(valB)) { - configChanges.push({ field: f, from: valA, to: valB }); - } - } - - if (codeDiff || filterDiff || configChanges.length > 0) { - modifiedTasks.push({ - taskName: name, - displayName: tB.displayName || tB.label || tA.displayName || tA.label, - type: tB.type || tA.type, - changeType: "MODIFIED", - codeDiff, - filterDiff, - configChanges, - }); - } - } - - return { - snapshotA: { - id: snapshotA.id, - version: snapshotA.version, - updateTime: snapshotA.updateTime, - staffName: snapshotA.staffName || snapshotA.staffId || undefined, - }, - snapshotB: { - id: snapshotB.id, - version: snapshotB.version, - updateTime: snapshotB.updateTime, - staffName: snapshotB.staffName || snapshotB.staffId || undefined, - }, - addedTasks, - removedTasks, - modifiedTasks, - summary: { - totalA: tasksA.length, - totalB: tasksB.length, - changedCount: modifiedTasks.length, - }, - }; -} - -/** - * 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息 - */ -export function diffWorkflowJobs( - jobA: WorkflowJobDetail, - treeA: WorkflowTaskExecution[], - jobB: WorkflowJobDetail, - treeB: WorkflowTaskExecution[] -): WorkflowJobDiff { - const flatA = indexExecutionContexts(treeA); - const flatB = indexExecutionContexts(treeB); - const byKeyA = new Map(flatA.map(context => [context.key, context])); - const byKeyB = new Map(flatB.map(context => [context.key, context])); - const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]); - - const nodes: NodeExecutionDiff[] = []; - let divergedNodesCount = 0; - let statusDiffCount = 0; - - for (const key of allKeys) { - const contextA = byKeyA.get(key); - const contextB = byKeyB.get(key); - const nodeA = contextA?.node; - const nodeB = contextB?.node; - const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed"; - - const statusA = nodeA?.status; - const statusB = nodeB?.status; - const isStatusDiff = statusA !== statusB; - if (isStatusDiff) statusDiffCount++; - - // 比较 inputs - const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; - const payloadFields = (value: unknown): Record => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record : { $value: value }; - const inA = payloadFields(nodeA?.inputs); - const inB = payloadFields(nodeB?.inputs); - const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)])); - for (const k of inputKeys) { - if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) { - inputsDiff.push({ field: k, from: inA[k], to: inB[k] }); - } - } - - // 比较 outputs - const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; - const outA = payloadFields(nodeA?.outputs ?? nodeA?.output); - const outB = payloadFields(nodeB?.outputs ?? nodeB?.output); - const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)])); - for (const k of outputKeys) { - if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) { - outputsDiff.push({ field: k, from: outA[k], to: outB[k] }); - } - } - - const isDiverged = - !nodeA || - !nodeB || - isStatusDiff || - JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) || - inputsDiff.length > 0 || outputsDiff.length > 0; - - if (isDiverged) divergedNodesCount++; - - nodes.push({ - taskName: name, - instanceKey: key, - currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined, - displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined, - type: nodeB?.type || nodeA?.type, - statusA, - statusB, - durationMsA: nodeA?.executionTime, - durationMsB: nodeB?.executionTime, - errorA: nodeA?.error, - errorB: nodeB?.error, - inputsDiff, - outputsDiff, - diverged: isDiverged, - }); - } - - return { - jobA: { - id: jobA.id, - pipelineId: jobA.pipelineId, - state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined, - startTime: jobA.startTime ? String(jobA.startTime) : undefined, - durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined, - hasError: Boolean(jobA.hasError), - errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined, - }, - jobB: { - id: jobB.id, - pipelineId: jobB.pipelineId, - state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined, - startTime: jobB.startTime ? String(jobB.startTime) : undefined, - durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined, - hasError: Boolean(jobB.hasError), - errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined, - }, - nodes, - summary: { - totalNodesA: flatA.length, - totalNodesB: flatB.length, - divergedNodesCount, - statusDiffCount, - }, - }; -} - -export function getWorkflowDebugSource(...args: Parameters) { - return api.getWorkflowDebugSource(...args); -} - -export function triggerWorkflowDebug(...args: Parameters) { - return api.triggerWorkflowDebug(...args); -} - -export async function runWorkflowDebugTest( - client: import("ky").KyInstance, - pipelineId: string, - options: { - flowCodeOrId?: string; - data?: Record; - triggerCategory?: import("./types.js").WorkflowTriggerCategory; - triggerType?: string; - triggerLabel?: string; - autoPublish?: boolean; - timeoutMs?: number; - pollIntervalMs?: number; - } = {} -): Promise { - if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) { - throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数"); - } - let targetEntityId = options.flowCodeOrId ?? ""; - const code = options.flowCodeOrId; - const isDirectCode = !code || code.includes("-") || code.startsWith("ID01"); - if (code && !isDirectCode) { - try { - const source = await api.getWorkflowDebugSource(client, pipelineId, { - page: 1, - pageSize: 10, - keywords: code, - }); - const matched = source.items.find( - (item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code) - ); - if (matched) { - targetEntityId = matched.id; - } - } catch { - // 关键字搜索超时或失败时直接回退使用传入值 - } - } - - const jobId = await api.triggerWorkflowDebug(client, pipelineId, { - entityId: targetEntityId || undefined, - data: options.data, - autoPublish: options.autoPublish ?? false, - }); - - const timeoutMs = options.timeoutMs ?? 15000; - const pollIntervalMs = options.pollIntervalMs ?? 500; - const start = Date.now(); - const diagnosticsErrors: Array<{ source: string; message: string }> = []; - const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) }); - const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); - const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase(); - let finalJob: WorkflowJobDetail | undefined; - let pollingFailed = false; - - while (Date.now() - start < timeoutMs) { - try { - const job = await api.getJob(client, jobId); - finalJob = job; - if (terminal.has(jobState(job))) break; - } catch (error) { - // 任务刚创建可能存在短延时,继续轮询 - const status = (error as { status?: number; response?: { status?: number } } | null)?.status - ?? (error as { response?: { status?: number } } | null)?.response?.status; - if (status !== 404) { - recordError("job", error); - pollingFailed = true; - break; - } - } - await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start))))); - } - - if (!finalJob && !pollingFailed) { - try { finalJob = await api.getJob(client, jobId); } - catch (error) { recordError("job", error); pollingFailed = true; } - } - const timedOut = !pollingFailed && !terminal.has(jobState(finalJob)); - const [treeResult, failuresResult] = await Promise.allSettled([ - api.getJobExecutionTree(client, jobId), - api.getJobFailedExecutions(client, jobId), - ]); - const tree = treeResult.status === "fulfilled" ? treeResult.value : []; - const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : []; - if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason); - if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason); - - const rawFailed = extractFailureExecutions(tree, failedItems); - const diagnosticsComplete = diagnosticsErrors.length === 0; - const status = jobState(finalJob); - const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0; - let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete"; - if (timedOut) outcome = "timed_out"; - else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed"; - else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed"; - const conditionDiagnoses = explainConditionBranches(tree); - - return { - jobId, - pipelineId, - status, - outcome, - timedOut, - diagnosticsComplete, - diagnosticsErrors, - runType: finalJob?.runType || "DEBUG", - durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined, - targetEntityId, - triggerCategory: options.triggerCategory, - triggerType: options.triggerType, - triggerLabel: options.triggerLabel, - executionTree: tree, - failedExecutions: rawFailed, - conditionDiagnoses, - }; -} - -export { - explainConditionBranches, - type ConditionBranchExplanation, - type ConditionRuleExplanation, -} from "./workflow/branch/index.js"; - -export { - classifyWorkflowTrigger, - type WorkflowTriggerCategory, - type WorkflowSampleRecord, - type WorkflowSampleDataResult, -} from "./types.js"; - -export async function getWorkflowSampleData( - client: import("ky").KyInstance, - pipelineId: string, - type = "webhook" -): Promise { - return api.getWorkflowSampleData(client, pipelineId, type); -} - -export function getWorkflowEnumOptions(...args: Parameters) { - return api.getWorkflowEnumOptions(...args); -} - -export async function resolveWorkflowEnumOptions( - client?: import("ky").KyInstance, - thirdId = "action", - platformId?: string -): Promise> { - if (client) { - try { - const remote = await api.getWorkflowEnumOptions(client, thirdId, platformId); - if (remote && remote.length > 0) { - return remote.map((item) => ({ - code: item.code, - label: item.label, - name: item.name || item.label, - })); - } - } catch { - // 远程调用失败(如无权限/网络异常)时 Fallback 到内置字典 - } - } - - if (thirdId.toLowerCase() === "action") { - const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./workflow/enums.js"); - return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({ - code: item.code, - label: item.label, - name: item.name, - description: item.description, - })); - } - - return []; -} - -// ── 工作流企业可用节点探针与灰度开通 ────────────────────────────────────────── - -export async function getWorkflowAvailableNodes( - client: KyInstance -): Promise { - const catalog = await api.listDslCatalog(client); - const allTypes = new Set(); - - for (const item of catalog.action) { - if (item.type) allTypes.add(item.type); - } - for (const item of catalog.control) { - if (item.type) allTypes.add(item.type); - } - for (const item of catalog.trigger) { - if (item.type) allTypes.add(item.type); - } - - return { - allTypes, - actionNodes: catalog.action, - controlNodes: catalog.control, - triggerNodes: catalog.trigger, - }; -} - -export async function grantWorkflowNodes( - corp: CorpConfig, - options: import("./types.js").GrantWorkflowNodesOptions -): Promise { - if (!options.nodes || options.nodes.length === 0) { - throw new ValidationError("必须指定至少一个需要开通的节点名称或类型"); - } - - // 1. 管理员密码保护预留设计 - const adminPassword = process.env.HOSE_ADMIN_PASSWORD; - if (adminPassword) { - if (!options.password || options.password !== adminPassword) { - throw new PermissionError( - "灰度节点开通功能已启用管理员保护,请通过 --password 或配置输入正确的管理员密码" - ); - } - } - - // 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type) - const { findGrayNode } = await import("./workflow/nodes/gray-nodes-catalog.js"); - const normalizedNodes = options.nodes.map((node) => { - const matched = findGrayNode(node); - return matched ? matched.type : node.trim(); - }); - - const token = corp.credentials?.accessToken; - const corpId = corp.corpId || corp.credentials?.corpId || corp.id; - const baseUrl = corp.baseUrl; - - if (!token) { - throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请"); - } - - // 3. 调用开通 API - const result = await api.grantWorkflowNodesApi({ - token, - corpId, - nodes: normalizedNodes, - baseUrl, - }); - - return result; -} - -export * from "./workflow/index.js"; diff --git a/src/domains/platform/workflow/README.workflow.md b/src/domains/platform/workflow/README.workflow.md index 079db59..e6bef85 100644 --- a/src/domains/platform/workflow/README.workflow.md +++ b/src/domains/platform/workflow/README.workflow.md @@ -1,3 +1,5 @@ +> 本模块归属自建应用平台;工作流模型、传输与编排现位于同级 `types.ts`、`api.ts`、`services.ts`,跨应用查询使用 applications 服务。上级入口见 [Platform 总览](../README.platform.md)。 + # Workflow 工作流模块 Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。 @@ -193,3 +195,26 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 ` 2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析; 3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退; 4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。 + + +## 模块内部职责 + +工作流的模型、传输和服务出口都位于本目录,具体编排按职责分开: + +| 文件 | 职责 | +|---|---| +| [api.ts](./api.ts)、[types.ts](./types.ts) | HTTP 请求/响应校验与工作流 Zod 模型 | +| [services.ts](./services.ts) | 显式业务出口及既有能力目录的统一导出 | +| [queries.ts](./queries.ts) | 列表、历史、执行读取和跨应用工作流检索 | +| [configuration.ts](./configuration.ts) | 创建、复制、保存、启停、快照清洗与部分成功恢复 | +| [execution.ts](./execution.ts)、[execution-context.ts](./execution-context.ts) | 执行树展开、失败节点提取及执行实例上下文 | +| [diff.ts](./diff.ts) | 配置快照与执行结果差异 | +| [debug.ts](./debug.ts) | 调试、输入采样和结果汇总 | +| [catalog.ts](./catalog.ts) | DSL、节点权限、枚举字典与回退 | + +内部实现直接导入所属模块,不反向导入 services 门面。watch 的 tracker 使用 execution,工作流报告类型直接引用 branch/types,避免通过聚合出口形成循环。跨应用查询只通过 applications 的公开业务服务取得应用;各子模块禁止绕过服务直接调用兄弟模块 api。 + + +## 空历史快照兼容 + +Piper 对没有快照的新工作流可能返回 `items: null`。快照列表 API 将该字段归一化为 `[]`,保留分页数据;其他错误类型、无效条目、空详情及业务错误仍拒绝。该兼容仅在传输层处理,不改变工作流结构导出的模型。 diff --git a/src/domains/platform/workflow/analysis/README.analysis.md b/src/domains/platform/workflow/analysis/README.analysis.md new file mode 100644 index 0000000..a54f0b2 --- /dev/null +++ b/src/domains/platform/workflow/analysis/README.analysis.md @@ -0,0 +1,18 @@ +# 工作流静态分析(analysis) + +本目录将工作流配置转换为 AST、依赖关系、诊断与摘要,供 Platform 服务和 CLI 分析命令使用。父级能力见 [工作流说明](../README.workflow.md)。 + +## 文件与入口 + +- [index.ts](./index.ts):统一导出。 +- [analyzer.ts](./analyzer.ts):`analyzeWorkflow(detail, options)` 与关联表单规格 ID 提取。 +- [types.ts](./types.ts):AST、依赖、诊断分类、统计摘要和外部分析上下文。 +- 同级测试覆盖条件/循环、选择器引用、公式边界和诊断行为。 + +## 分析边界 + +本层分析传入的工作流与上下文,不自行请求租户服务、保存配置或启用流程。可用节点类型、开通权限及表单规格由调用者通过 options 提供;分析是否有足够证据取决于调用者提供的信息。 + +诊断区分 `hard_block` 与 `soft_advice`:阻断性配置错误与风险建议需分别展示;流程停用不能直接等同于配置错误。扫描覆盖嵌套任务、选择器与引用,不能仅检索顶层脚本字符串。 + +新增规则时补充正反例,说明检测证据、误报边界及诊断级别;保持纯业务分析,不导入 CLI 输出层。命令的展示和失败退出策略由 [workflow 命令层](../../../../cli/commands/workflow/README.workflow.md) 负责。 diff --git a/src/domains/platform/workflow/analysis/analyzer.ts b/src/domains/platform/workflow/analysis/analyzer.ts index 2269925..d0ce337 100644 --- a/src/domains/platform/workflow/analysis/analyzer.ts +++ b/src/domains/platform/workflow/analysis/analyzer.ts @@ -1,4 +1,4 @@ -import type { WorkflowDetail, WorkflowTask } from "../../types.js"; +import type { WorkflowDetail, WorkflowTask } from "../types.js"; import type { WorkflowAnalysis, WorkflowAstNode, diff --git a/src/domains/platform/workflow/analysis/every-selectors.test.ts b/src/domains/platform/workflow/analysis/every-selectors.test.ts index d81d04a..15293d3 100644 --- a/src/domains/platform/workflow/analysis/every-selectors.test.ts +++ b/src/domains/platform/workflow/analysis/every-selectors.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import type { WorkflowDetail, WorkflowTask } from "../../types.js"; +import type { WorkflowDetail, WorkflowTask } from "../types.js"; import { analyzeWorkflow } from "./analyzer.js"; const selector = (key: unknown, label?: unknown) => `@{value('${JSON.stringify({ key, label })}')}`; diff --git a/src/domains/platform/workflow/analysis/index.test.ts b/src/domains/platform/workflow/analysis/index.test.ts index 7eb2b9c..bab79a0 100644 --- a/src/domains/platform/workflow/analysis/index.test.ts +++ b/src/domains/platform/workflow/analysis/index.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "bun:test"; import { analyzeWorkflow } from "./index.js"; -import { PlatformSchema } from "../../types.js"; +import { PlatformSchema } from "../../applications/types.js"; describe("Workflow static analysis", () => { it("accepts nullable app center metadata", () => { diff --git a/src/domains/platform/api.test.ts b/src/domains/platform/workflow/api.test.ts similarity index 53% rename from src/domains/platform/api.test.ts rename to src/domains/platform/workflow/api.test.ts index fd68ba1..31f99d0 100644 --- a/src/domains/platform/api.test.ts +++ b/src/domains/platform/workflow/api.test.ts @@ -1,7 +1,22 @@ import { describe, expect, it } from "bun:test"; -import { getWorkflowSnapshot, updateWorkflowChooses } from "./api.js"; +import { getWorkflowSnapshot, updateWorkflowChooses, listWorkflowSnapshots } from "./api.js"; describe("workflow snapshot API", () => { + it("normalizes null or missing snapshot items without losing pagination", async () => { + for (const items of [null, undefined, []]) { + const client = { get: async () => Response.json({ code: 200, data: { number: 2, size: 10, totalItems: 0, items } }) } as any; + expect(await listWorkflowSnapshots(client, "fixture")).toEqual({ number: 2, size: 10, totalPages: 0, totalItems: 0, items: [] }); + } + }); + + it("keeps snapshot entries and rejects malformed items or business failures", async () => { + const query = (body: unknown) => listWorkflowSnapshots({ get: async () => Response.json(body) } as any, "fixture"); + expect((await query({ code: 200, data: { items: [{ id: "snapshot", pipelineId: "fixture" }] } })).items[0]?.id).toBe("snapshot"); + for (const items of ["bad", {}, [{}]]) await expect(query({ code: 200, data: { items } })).rejects.toThrow(); + await expect(query({ code: 403, msg: "denied", data: { items: null } })).rejects.toThrow("denied"); + await expect(query({ code: 200, data: null })).rejects.toThrow(); + }); + it("uses the piper pipelines/snapshot endpoint first", async () => { const calls: string[] = []; const client = { diff --git a/src/domains/platform/api.ts b/src/domains/platform/workflow/api.ts similarity index 96% rename from src/domains/platform/api.ts rename to src/domains/platform/workflow/api.ts index 3bc5f92..b058751 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/workflow/api.ts @@ -1,8 +1,7 @@ import { z } from "zod"; import ky, { KyInstance } from "ky"; -import { AuthenticationError, BusinessError, EkbApiError } from "../../core/errors.js"; +import { AuthenticationError, BusinessError, EkbApiError } from "../../../core/errors.js"; import { - PlatformSchema, WorkflowPageSchema, WorkflowStatsSchema, WorkflowChargeSchema, @@ -87,19 +86,6 @@ async function ok(response: Response): Promise<{ success: boolean }> { return { success: response.status === 200 }; } -// ── 自建应用 ────────────────────────────────────────────────────────────────── - -export async function listPlatforms( - client: KyInstance, - corpId: string -): Promise { - const response = await client.get("api/v2/datalink/platform/search", { - searchParams: { scope: "enable", corpId }, - }); - const json = (await response.json()) as { items: unknown[] }; - return z.array(PlatformSchema).parse(json.items); -} - // ── 工作流(EASO)───────────────────────────────────────────────────────────── // 注意:EASO 客户端已自动注入 corpId,无需再传 @@ -209,7 +195,10 @@ export async function listWorkflowSnapshots( const response = await client.get(`api/easo/pipelines/${pipelineId}/snapshots`, { searchParams: { number: String(page), pageSize: String(pageSize) }, }); - return unwrap(response, WorkflowSnapshotPageSchema); + // 新工作流没有历史快照时,Piper 将 items 返回为 null;仅归一化空集合,保留其他校验。 + return unwrap(response, WorkflowSnapshotPageSchema.extend({ + items: WorkflowSnapshotPageSchema.shape.items.nullable().transform(items => items ?? []), + })); } export async function getWorkflowSnapshot( diff --git a/src/domains/platform/workflow/branch/explain.ts b/src/domains/platform/workflow/branch/explain.ts index 50cca28..48602eb 100644 --- a/src/domains/platform/workflow/branch/explain.ts +++ b/src/domains/platform/workflow/branch/explain.ts @@ -1,5 +1,5 @@ -import type { WorkflowTaskExecution } from "../../types.js"; -import { indexExecutionContexts } from "../../execution-context.js"; +import type { WorkflowTaskExecution } from "../types.js"; +import { indexExecutionContexts } from "../execution-context.js"; import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js"; export const OP_MAP: Record = { diff --git a/src/domains/platform/workflow/branch/index.test.ts b/src/domains/platform/workflow/branch/index.test.ts index 5097a1f..d942bd6 100644 --- a/src/domains/platform/workflow/branch/index.test.ts +++ b/src/domains/platform/workflow/branch/index.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "bun:test"; import { explainConditionBranches } from "./index.js"; -import type { WorkflowTaskExecution } from "../../types.js"; +import type { WorkflowTaskExecution } from "../types.js"; describe("Workflow Condition Branch Diagnosis", () => { const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`; diff --git a/src/domains/platform/workflow/catalog.ts b/src/domains/platform/workflow/catalog.ts new file mode 100644 index 0000000..a910698 --- /dev/null +++ b/src/domains/platform/workflow/catalog.ts @@ -0,0 +1,125 @@ +import { KyInstance } from "ky"; +import { CorpConfig } from "../../../core/config/types.js"; +import * as api from "./api.js"; +import { PermissionError, ValidationError } from "../../../core/errors.js"; + + +export function listDsl(...args: Parameters) { + return api.listDsl(...args); +} + + +export function listStaffs(...args: Parameters) { + return api.listStaffs(...args); +} + + +export function getWorkflowEnumOptions(...args: Parameters) { + return api.getWorkflowEnumOptions(...args); +} + + +export async function resolveWorkflowEnumOptions( + client?: import("ky").KyInstance, + thirdId = "action", + platformId?: string +): Promise> { + if (client) { + try { + const remote = await api.getWorkflowEnumOptions(client, thirdId, platformId); + if (remote && remote.length > 0) { + return remote.map((item) => ({ + code: item.code, + label: item.label, + name: item.name || item.label, + })); + } + } catch { + // 远程调用失败(如无权限/网络异常)时 Fallback 到内置字典 + } + } + + if (thirdId.toLowerCase() === "action") { + const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./enums.js"); + return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({ + code: item.code, + label: item.label, + name: item.name, + description: item.description, + })); + } + + return []; +} + + +// ── 工作流企业可用节点探针与灰度开通 ────────────────────────────────────────── + +export async function getWorkflowAvailableNodes( + client: KyInstance +): Promise { + const catalog = await api.listDslCatalog(client); + const allTypes = new Set(); + + for (const item of catalog.action) { + if (item.type) allTypes.add(item.type); + } + for (const item of catalog.control) { + if (item.type) allTypes.add(item.type); + } + for (const item of catalog.trigger) { + if (item.type) allTypes.add(item.type); + } + + return { + allTypes, + actionNodes: catalog.action, + controlNodes: catalog.control, + triggerNodes: catalog.trigger, + }; +} + + +export async function grantWorkflowNodes( + corp: CorpConfig, + options: import("./types.js").GrantWorkflowNodesOptions +): Promise { + if (!options.nodes || options.nodes.length === 0) { + throw new ValidationError("必须指定至少一个需要开通的节点名称或类型"); + } + + // 1. 管理员密码保护预留设计 + const adminPassword = process.env.HOSE_ADMIN_PASSWORD; + if (adminPassword) { + if (!options.password || options.password !== adminPassword) { + throw new PermissionError( + "灰度节点开通功能已启用管理员保护,请通过 --password 或配置输入正确的管理员密码" + ); + } + } + + // 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type) + const { findGrayNode } = await import("./nodes/gray-nodes-catalog.js"); + const normalizedNodes = options.nodes.map((node) => { + const matched = findGrayNode(node); + return matched ? matched.type : node.trim(); + }); + + const token = corp.credentials?.accessToken; + const corpId = corp.corpId || corp.credentials?.corpId || corp.id; + const baseUrl = corp.baseUrl; + + if (!token) { + throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请"); + } + + // 3. 调用开通 API + const result = await api.grantWorkflowNodesApi({ + token, + corpId, + nodes: normalizedNodes, + baseUrl, + }); + + return result; +} diff --git a/src/domains/platform/workflow/configuration.ts b/src/domains/platform/workflow/configuration.ts new file mode 100644 index 0000000..3a5a043 --- /dev/null +++ b/src/domains/platform/workflow/configuration.ts @@ -0,0 +1,210 @@ +import { KyInstance } from "ky"; +import { WorkflowSavePartialError } from "./save-error.js"; +import * as api from "./api.js"; +import { WorkflowTask } from "./types.js"; + + +export function sanitizeWorkflowSnapshot( + detail: import("./types.js").WorkflowDetail +): import("./types.js").WorkflowDetail { + const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; + if (Array.isArray(cloned.$snapshot)) { + cloned.$snapshot = cloned.$snapshot.map((entry) => { + if (typeof entry.value === "string" && entry.value.includes("docs.ekuaibao.com")) { + return { + ...entry, + value: entry.value.replaceAll("docs.ekuaibao.com", "app.ekuaibao.com"), + }; + } + return entry; + }); + } + return cloned; +} + + +export async function updateWorkflow( + client: KyInstance, + workflow: import("./types.js").WorkflowDetail, + platformId?: string +) { + // 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。 + const payload: import("./types.js").WorkflowDetail = platformId && !workflow.inputs?.length + ? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] } + : workflow; + const sanitized = sanitizeWorkflowSnapshot(payload); + const updated = await api.updateWorkflow(client, sanitized); + // 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。 + try { + await api.updateWorkflowChooses(client, updated.id || workflow.id); + } catch (error) { + throw new WorkflowSavePartialError(updated, error); + } + return updated; +} + + +/** 只重试元数据刷新,不重新提交完整工作流快照。 */ +export function refreshWorkflowChooses(client: KyInstance, pipelineId: string): Promise { + return api.updateWorkflowChooses(client, pipelineId); +} + + +export async function copyWorkflow( + client: import("ky").KyInstance, + pipelineId: string, + options: { label?: string; platformId?: string } = {} +): Promise { + const detail = await api.getWorkflowDetail(client, pipelineId); + const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; + if (options.label) { + cloned.label = options.label; + } else if (!cloned.label.includes("副本")) { + cloned.label = `${cloned.label} 副本`; + } + if (options.platformId) { + cloned.platformId = options.platformId; + } + // 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本 + if (cloned.tasks?.[0]?.type === "webhook") { + (cloned.tasks[0] as any).urlPath = crypto.randomUUID(); + delete (cloned.tasks[0] as any).sampleId; + } + const result = await api.copyWorkflow(client, pipelineId, cloned); + if (options.label && result.label !== options.label) { + result.label = options.label; + return updateWorkflow(client, result, options.platformId ?? (result as any).platformId); + } + return result; +} + + +export interface CreateWorkflowOptions { + label?: string; + platformId?: string; + trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string; + file?: string; + workflow?: Record; + state?: number; + desc?: string; +} + + +export function buildInitialTriggerTask(triggerType: string): WorkflowTask { + const norm = triggerType.toLowerCase().trim(); + switch (norm) { + case "webhook": + return { + name: "trigger_webhook", + type: "webhook", + label: "Webhook触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + urlPath: crypto.randomUUID(), + params: [], + }; + case "clock": + case "schedule": + case "timer": + return { + name: "trigger_clock", + type: "clock", + label: "定时触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + cron: "0 0 * * *", + timeZone: "Asia/Shanghai", + }; + case "datalink": + case "data-link": + case "entity": + return { + name: "trigger_datalink_create", + type: "ekuaibao-datalink-create-trigger", + label: "业务对象新增时触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }; + case "flowform": + case "flow": + case "bill": + return { + name: "trigger_flowform", + type: "ekuaibao-flowform-trigger", + label: "单据审批事件触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }; + default: + return { + name: `trigger_${norm.replace(/-/g, "_")}`, + type: norm, + label: `${norm}触发`, + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }; + } +} + + +export async function createWorkflow( + client: import("ky").KyInstance, + options: CreateWorkflowOptions = {} +): Promise { + let base: Record = {}; + if (options.file) { + const fs = await import("fs/promises"); + const raw = await fs.readFile(options.file, "utf-8"); + base = JSON.parse(raw); + } else if (options.workflow) { + base = JSON.parse(JSON.stringify(options.workflow)); + } + + const payload: Record = { + ...base, + label: options.label || base.label || "未命名流程", + state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承 + }; + + if (options.platformId || base.platformId) { + payload.platformId = options.platformId || base.platformId; + } + if (options.desc || base.desc) { + payload.desc = options.desc || base.desc; + } + + // 触发器节点初始化 + if (!payload.tasks || payload.tasks.length === 0) { + if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") { + payload.tasks = [buildInitialTriggerTask(options.trigger)]; + } else { + payload.tasks = []; + } + } else if (payload.tasks[0]?.type === "webhook") { + if (!payload.tasks[0].urlPath) { + payload.tasks[0].urlPath = crypto.randomUUID(); + } + } + + return api.createWorkflow(client, payload); +} + + +export function deleteWorkflow(...args: Parameters) { + return api.deleteWorkflow(...args); +} + + +export function toggleWorkflow(...args: Parameters) { + return api.toggleWorkflow(...args); +} diff --git a/src/domains/platform/workflow/debug.ts b/src/domains/platform/workflow/debug.ts new file mode 100644 index 0000000..682ee80 --- /dev/null +++ b/src/domains/platform/workflow/debug.ts @@ -0,0 +1,151 @@ +import * as api from "./api.js"; +import { ValidationError } from "../../../core/errors.js"; +import { explainConditionBranches } from "./branch/index.js"; +import { WorkflowJobDetail } from "./types.js"; +import { extractFailureExecutions } from "./execution.js"; + + +export function getWebhookInfo(...args: Parameters) { + return api.getWebhookInfo(...args); +} + + +export function sampleWorkflowData(...args: Parameters) { + return api.sampleWorkflowData(...args); +} + + +export function getWorkflowDebugSource(...args: Parameters) { + return api.getWorkflowDebugSource(...args); +} + + +export function triggerWorkflowDebug(...args: Parameters) { + return api.triggerWorkflowDebug(...args); +} + + +export async function runWorkflowDebugTest( + client: import("ky").KyInstance, + pipelineId: string, + options: { + flowCodeOrId?: string; + data?: Record; + triggerCategory?: import("./types.js").WorkflowTriggerCategory; + triggerType?: string; + triggerLabel?: string; + autoPublish?: boolean; + timeoutMs?: number; + pollIntervalMs?: number; + } = {} +): Promise { + if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) { + throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数"); + } + let targetEntityId = options.flowCodeOrId ?? ""; + const code = options.flowCodeOrId; + const isDirectCode = !code || code.includes("-") || code.startsWith("ID01"); + if (code && !isDirectCode) { + try { + const source = await api.getWorkflowDebugSource(client, pipelineId, { + page: 1, + pageSize: 10, + keywords: code, + }); + const matched = source.items.find( + (item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code) + ); + if (matched) { + targetEntityId = matched.id; + } + } catch { + // 关键字搜索超时或失败时直接回退使用传入值 + } + } + + const jobId = await api.triggerWorkflowDebug(client, pipelineId, { + entityId: targetEntityId || undefined, + data: options.data, + autoPublish: options.autoPublish ?? false, + }); + + const timeoutMs = options.timeoutMs ?? 15000; + const pollIntervalMs = options.pollIntervalMs ?? 500; + const start = Date.now(); + const diagnosticsErrors: Array<{ source: string; message: string }> = []; + const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) }); + const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); + const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase(); + let finalJob: WorkflowJobDetail | undefined; + let pollingFailed = false; + + while (Date.now() - start < timeoutMs) { + try { + const job = await api.getJob(client, jobId); + finalJob = job; + if (terminal.has(jobState(job))) break; + } catch (error) { + // 任务刚创建可能存在短延时,继续轮询 + const status = (error as { status?: number; response?: { status?: number } } | null)?.status + ?? (error as { response?: { status?: number } } | null)?.response?.status; + if (status !== 404) { + recordError("job", error); + pollingFailed = true; + break; + } + } + await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start))))); + } + + if (!finalJob && !pollingFailed) { + try { finalJob = await api.getJob(client, jobId); } + catch (error) { recordError("job", error); pollingFailed = true; } + } + const timedOut = !pollingFailed && !terminal.has(jobState(finalJob)); + const [treeResult, failuresResult] = await Promise.allSettled([ + api.getJobExecutionTree(client, jobId), + api.getJobFailedExecutions(client, jobId), + ]); + const tree = treeResult.status === "fulfilled" ? treeResult.value : []; + const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : []; + if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason); + if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason); + + const rawFailed = extractFailureExecutions(tree, failedItems); + const diagnosticsComplete = diagnosticsErrors.length === 0; + const status = jobState(finalJob); + const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0; + let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete"; + if (timedOut) outcome = "timed_out"; + else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed"; + else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed"; + const conditionDiagnoses = explainConditionBranches(tree); + + return { + jobId, + pipelineId, + status, + outcome, + timedOut, + diagnosticsComplete, + diagnosticsErrors, + runType: finalJob?.runType || "DEBUG", + durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined, + targetEntityId, + triggerCategory: options.triggerCategory, + triggerType: options.triggerType, + triggerLabel: options.triggerLabel, + executionTree: tree, + failedExecutions: rawFailed, + conditionDiagnoses, + }; +} + + +export async function getWorkflowSampleData( + client: import("ky").KyInstance, + pipelineId: string, + type = "webhook" +): Promise { + return api.getWorkflowSampleData(client, pipelineId, type); +} diff --git a/src/domains/platform/workflow/diff.ts b/src/domains/platform/workflow/diff.ts new file mode 100644 index 0000000..94c49b2 --- /dev/null +++ b/src/domains/platform/workflow/diff.ts @@ -0,0 +1,298 @@ +import { indexExecutionContexts } from "./execution-context.js"; +import { WorkflowTask, WorkflowTaskExecution, WorkflowSnapshot, WorkflowSnapshotDiff, TaskConfigDiff, WorkflowJobDetail, WorkflowJobDiff, NodeExecutionDiff } from "./types.js"; +import { flattenWorkflowTasks } from "./execution.js"; + + +/** + * 快速生成标准 Unified Diff 文本 + */ +export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string { + if (a === b) return ""; + const linesA = a.split(/\r?\n/); + const linesB = b.split(/\r?\n/); + const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`]; + + let start = 0; + while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) { + start++; + } + let endA = linesA.length - 1; + let endB = linesB.length - 1; + while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) { + endA--; + endB--; + } + + const hunkStart = Math.max(0, start - 2); + const hunkEndA = Math.min(linesA.length, endA + 3); + const hunkEndB = Math.min(linesB.length, endB + 3); + + output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`); + for (let i = hunkStart; i < start; i++) { + output.push(` ${linesA[i]}`); + } + for (let i = start; i <= endA; i++) { + output.push(`- ${linesA[i]}`); + } + for (let i = start; i <= endB; i++) { + output.push(`+ ${linesB[i]}`); + } + for (let i = endA + 1; i < hunkEndA; i++) { + output.push(` ${linesA[i]}`); + } + return output.join("\n"); +} + + +/** + * 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异 + */ +export function diffWorkflowSnapshots( + snapshotA: WorkflowSnapshot, + snapshotB: WorkflowSnapshot +): WorkflowSnapshotDiff { + const tasksA = flattenWorkflowTasks(snapshotA.tasks); + const tasksB = flattenWorkflowTasks(snapshotB.tasks); + const indexPaths = (tasks: WorkflowTask[] = [], prefix = "tasks", paths = new Map()): Map => { + tasks.forEach((task, i) => { + const path = `${prefix}.${i}`; + if (task.name) paths.set(task.name, path); + if (task.tasks) indexPaths(task.tasks, `${path}.tasks`, paths); + }); + return paths; + }; + const pathsA = indexPaths(snapshotA.tasks || []); + const pathsB = indexPaths(snapshotB.tasks || []); + + const mapA = new Map(); + for (const t of tasksA) { + if (t?.name) mapA.set(t.name, t); + } + + const mapB = new Map(); + for (const t of tasksB) { + if (t?.name) mapB.set(t.name, t); + } + + const addedTasks: string[] = []; + const removedTasks: string[] = []; + const modifiedTasks: TaskConfigDiff[] = []; + + // 1. 查找新增节点 + for (const [name, tB] of mapB) { + if (!mapA.has(name)) { + addedTasks.push(name); + modifiedTasks.push({ + taskName: name, + displayName: tB.displayName || tB.label, + type: tB.type, + changeType: "ADDED", + configChanges: [], + }); + } + } + + // 2. 查找删除与修改节点 + for (const [name, tA] of mapA) { + const tB = mapB.get(name); + if (!tB) { + removedTasks.push(name); + modifiedTasks.push({ + taskName: name, + displayName: tA.displayName || tA.label, + type: tA.type, + changeType: "REMOVED", + configChanges: [], + }); + continue; + } + + // 两者均存在,深度比较配置与代码 + const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = []; + let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined; + let filterDiff: { from?: unknown; to?: unknown } | undefined; + + // 代码脚本比较 + const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined; + const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined; + if (codeA !== codeB) { + codeDiff = { + from: codeA, + to: codeB, + unifiedDiff: generateTextDiff( + codeA || "", + codeB || "", + `${snapshotA.version || snapshotA.id}`, + `${snapshotB.version || snapshotB.id}` + ), + }; + } + + // 过滤条件比较 (combineFilters / filters) + const filtersA = (tA as any).combineFilters ?? (tA as any).filters; + const filtersB = (tB as any).combineFilters ?? (tB as any).filters; + if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) { + filterDiff = { from: filtersA, to: filtersB }; + } + + // 关键字段变动比较 + const checkFields = [...new Set([...Object.keys(tA), ...Object.keys(tB)])] + .filter(field => !["name", "tasks", "code", "combineFilters", "filters"].includes(field)); + if (pathsA.get(name) !== pathsB.get(name)) { + configChanges.push({ field: "$path", from: pathsA.get(name), to: pathsB.get(name) }); + } + for (const f of checkFields) { + const valA = (tA as any)[f]; + const valB = (tB as any)[f]; + if (JSON.stringify(valA) !== JSON.stringify(valB)) { + configChanges.push({ field: f, from: valA, to: valB }); + } + } + + if (codeDiff || filterDiff || configChanges.length > 0) { + modifiedTasks.push({ + taskName: name, + displayName: tB.displayName || tB.label || tA.displayName || tA.label, + type: tB.type || tA.type, + changeType: "MODIFIED", + codeDiff, + filterDiff, + configChanges, + }); + } + } + + return { + snapshotA: { + id: snapshotA.id, + version: snapshotA.version, + updateTime: snapshotA.updateTime, + staffName: snapshotA.staffName || snapshotA.staffId || undefined, + }, + snapshotB: { + id: snapshotB.id, + version: snapshotB.version, + updateTime: snapshotB.updateTime, + staffName: snapshotB.staffName || snapshotB.staffId || undefined, + }, + addedTasks, + removedTasks, + modifiedTasks, + summary: { + totalA: tasksA.length, + totalB: tasksB.length, + changedCount: modifiedTasks.length, + }, + }; +} + + +/** + * 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息 + */ +export function diffWorkflowJobs( + jobA: WorkflowJobDetail, + treeA: WorkflowTaskExecution[], + jobB: WorkflowJobDetail, + treeB: WorkflowTaskExecution[] +): WorkflowJobDiff { + const flatA = indexExecutionContexts(treeA); + const flatB = indexExecutionContexts(treeB); + const byKeyA = new Map(flatA.map(context => [context.key, context])); + const byKeyB = new Map(flatB.map(context => [context.key, context])); + const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]); + + const nodes: NodeExecutionDiff[] = []; + let divergedNodesCount = 0; + let statusDiffCount = 0; + + for (const key of allKeys) { + const contextA = byKeyA.get(key); + const contextB = byKeyB.get(key); + const nodeA = contextA?.node; + const nodeB = contextB?.node; + const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed"; + + const statusA = nodeA?.status; + const statusB = nodeB?.status; + const isStatusDiff = statusA !== statusB; + if (isStatusDiff) statusDiffCount++; + + // 比较 inputs + const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; + const payloadFields = (value: unknown): Record => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record : { $value: value }; + const inA = payloadFields(nodeA?.inputs); + const inB = payloadFields(nodeB?.inputs); + const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)])); + for (const k of inputKeys) { + if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) { + inputsDiff.push({ field: k, from: inA[k], to: inB[k] }); + } + } + + // 比较 outputs + const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; + const outA = payloadFields(nodeA?.outputs ?? nodeA?.output); + const outB = payloadFields(nodeB?.outputs ?? nodeB?.output); + const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)])); + for (const k of outputKeys) { + if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) { + outputsDiff.push({ field: k, from: outA[k], to: outB[k] }); + } + } + + const isDiverged = + !nodeA || + !nodeB || + isStatusDiff || + JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) || + inputsDiff.length > 0 || outputsDiff.length > 0; + + if (isDiverged) divergedNodesCount++; + + nodes.push({ + taskName: name, + instanceKey: key, + currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined, + displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined, + type: nodeB?.type || nodeA?.type, + statusA, + statusB, + durationMsA: nodeA?.executionTime, + durationMsB: nodeB?.executionTime, + errorA: nodeA?.error, + errorB: nodeB?.error, + inputsDiff, + outputsDiff, + diverged: isDiverged, + }); + } + + return { + jobA: { + id: jobA.id, + pipelineId: jobA.pipelineId, + state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined, + startTime: jobA.startTime ? String(jobA.startTime) : undefined, + durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined, + hasError: Boolean(jobA.hasError), + errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined, + }, + jobB: { + id: jobB.id, + pipelineId: jobB.pipelineId, + state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined, + startTime: jobB.startTime ? String(jobB.startTime) : undefined, + durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined, + hasError: Boolean(jobB.hasError), + errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined, + }, + nodes, + summary: { + totalNodesA: flatA.length, + totalNodesB: flatB.length, + divergedNodesCount, + statusDiffCount, + }, + }; +} diff --git a/src/domains/platform/workflow/enums.test.ts b/src/domains/platform/workflow/enums.test.ts index fbf40d8..b61d886 100644 --- a/src/domains/platform/workflow/enums.test.ts +++ b/src/domains/platform/workflow/enums.test.ts @@ -5,7 +5,7 @@ import { isWorkflowActionCode, matchWorkflowAction, resolveWorkflowEnumOptions, -} from "../services.js"; +} from "./services.js"; import { analyzeWorkflow } from "./analysis/index.js"; describe("Workflow Action Enums & Diagnostics", () => { diff --git a/src/domains/platform/execution-context.ts b/src/domains/platform/workflow/execution-context.ts similarity index 100% rename from src/domains/platform/execution-context.ts rename to src/domains/platform/workflow/execution-context.ts diff --git a/src/domains/platform/execution-diff.test.ts b/src/domains/platform/workflow/execution-diff.test.ts similarity index 100% rename from src/domains/platform/execution-diff.test.ts rename to src/domains/platform/workflow/execution-diff.test.ts diff --git a/src/domains/platform/workflow/execution.ts b/src/domains/platform/workflow/execution.ts new file mode 100644 index 0000000..b43a7e3 --- /dev/null +++ b/src/domains/platform/workflow/execution.ts @@ -0,0 +1,135 @@ +import { WorkflowTask, WorkflowTaskExecution } from "./types.js"; + + +/** + * 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组) + */ +export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] { + const result: WorkflowTaskExecution[] = []; + + function visit(node: any) { + if (!node || typeof node !== "object") return; + result.push(node as WorkflowTaskExecution); + + const children = node.children || node.tasks || node.subTasks || node.items; + if (Array.isArray(children)) { + for (const child of children) { + visit(child); + } + } + } + + for (const node of nodes) { + visit(node); + } + + return result; +} + + +/** + * 精准判定某个节点是否执行异常或报错 + */ +export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean { + if (!node) return false; + const anyNode = node as any; + + if (node.error?.message || anyNode.errorMessage) return true; + if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true; + if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true; + if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true; + if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true; + + return false; +} + + +/** + * 提取并去重执行树中的全部异常失败节点 + */ +export function extractFailureExecutions( + tree: WorkflowTaskExecution[], + failedItems: WorkflowTaskExecution[] = [] +): WorkflowTaskExecution[] { + const flattened = flattenExecutionTree(tree); + const map = new Map(); + + for (const item of failedItems) { + if (item?.id) { + map.set(item.id, item); + } + } + + for (const node of flattened) { + if (node?.id && isTaskExecutionFailed(node)) { + const existing = map.get(node.id); + if (!existing) { + map.set(node.id, node); + } else { + map.set(node.id, { + ...node, + ...existing, + error: existing.error ?? node.error, + inputs: existing.inputs ?? (node as any).inputs, + outputs: existing.outputs ?? (node as any).outputs, + }); + } + } + } + + return Array.from(map.values()); +} + + +/** + * 按 ID、name、displayName 或 label 查找节点 + */ +export function findExecutionNode( + tree: WorkflowTaskExecution[], + query: string +): WorkflowTaskExecution | undefined { + const flattened = flattenExecutionTree(tree); + const q = query.trim().toLowerCase(); + if (!q) return undefined; + + // 1. 精确匹配 ID 或 name + const exact = flattened.find( + (n) => + n.id?.toLowerCase() === q || + n.name?.toLowerCase() === q || + n.displayName?.toLowerCase() === q + ); + if (exact) return exact; + + // 2. 包含匹配 name、label、displayName + return flattened.find( + (n) => + n.name?.toLowerCase().includes(q) || + n.label?.toLowerCase().includes(q) || + n.displayName?.toLowerCase().includes(q) + ); +} + + +// ── 工作流快照与 Job 差异比对核心算法 ────────────────────────────────────────── + +/** + * 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点) + */ +export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] { + if (!tasks || !Array.isArray(tasks)) return []; + const result: WorkflowTask[] = []; + + function walk(list: WorkflowTask[]) { + for (const t of list) { + if (!t) continue; + result.push(t); + if (Array.isArray(t.tasks) && t.tasks.length > 0) { + walk(t.tasks); + } + } + } + + walk(tasks); + return result; +} diff --git a/src/domains/platform/workflow/nodes/README.nodes.md b/src/domains/platform/workflow/nodes/README.nodes.md new file mode 100644 index 0000000..8217459 --- /dev/null +++ b/src/domains/platform/workflow/nodes/README.nodes.md @@ -0,0 +1,21 @@ +# 工作流节点树操作(nodes) + +本目录负责节点定位、树展开、摘要与本地配置修改,是 [工作流子域](../README.workflow.md) 的节点工具层。函数操作传入的数据;远端持久化由 Platform 服务和 CLI 保存流程负责。 + +## 文件分工 + +| 文件 | 职责 | +|---|---| +| [locator.ts](./locator.ts) | 按节点 name、字符串层级编号或数字全局序号查找位置 | +| [tree.ts](./tree.ts) | 节点配置摘要和递归展开 | +| [mutations.ts](./mutations.ts) | 构造、添加、编辑、删除、重新编号及字段映射应用 | +| [gray-nodes-catalog.ts](./gray-nodes-catalog.ts) | 灰度节点参考目录与类型查找 | +| [types.ts](./types.ts)、[index.ts](./index.ts) | 定位/展开结果类型与统一导出 | + +## 修改与定位约定 + +定位参数保留类型语义:字符串用于节点名或层级编号,number 用于全局序号。嵌套控制节点修改后,需要保持层级编号、次序与树结构一致;删除触发器和更新映射须保留各自的约束及回归。 + +静态灰度目录不等于当前企业已经开通的节点,企业可用性仍需从服务端读取。不要在这里加入换票、HTTP 保存或终端提示,避免纯节点操作绑定到某个入口。 + +[index.test.ts](./index.test.ts)、[locator-index.test.ts](./locator-index.test.ts) 和 [trigger-removal.test.ts](./trigger-removal.test.ts) 验证本地修改。外部调用参数与保存流程见 [workflow 命令层](../../../../cli/commands/workflow/README.workflow.md)。 diff --git a/src/domains/platform/workflow/nodes/index.test.ts b/src/domains/platform/workflow/nodes/index.test.ts index c103803..428cec3 100644 --- a/src/domains/platform/workflow/nodes/index.test.ts +++ b/src/domains/platform/workflow/nodes/index.test.ts @@ -12,7 +12,7 @@ import { displayNameLength, isDisplayNameTooLong, } from "./index.js"; -import type { WorkflowDetail, WorkflowTask } from "../../types.js"; +import type { WorkflowDetail, WorkflowTask } from "../types.js"; const mockWorkflow: WorkflowDetail = { id: "wf_test_100", diff --git a/src/domains/platform/workflow/nodes/locator.ts b/src/domains/platform/workflow/nodes/locator.ts index 8c696e8..262b83e 100644 --- a/src/domains/platform/workflow/nodes/locator.ts +++ b/src/domains/platform/workflow/nodes/locator.ts @@ -1,4 +1,4 @@ -import type { WorkflowTask } from "../../types.js"; +import type { WorkflowTask } from "../types.js"; import type { LocatedWorkflowTask } from "./types.js"; /** diff --git a/src/domains/platform/workflow/nodes/mutations.ts b/src/domains/platform/workflow/nodes/mutations.ts index 06fa703..d3fa566 100644 --- a/src/domains/platform/workflow/nodes/mutations.ts +++ b/src/domains/platform/workflow/nodes/mutations.ts @@ -1,4 +1,4 @@ -import type { WorkflowDetail, WorkflowTask } from "../../types.js"; +import type { WorkflowDetail, WorkflowTask } from "../types.js"; import { NotFoundError, ValidationError } from "../../../../core/errors.js"; import { findWorkflowTask } from "./locator.js"; diff --git a/src/domains/platform/workflow/nodes/tree.ts b/src/domains/platform/workflow/nodes/tree.ts index 6d32cae..52356ed 100644 --- a/src/domains/platform/workflow/nodes/tree.ts +++ b/src/domains/platform/workflow/nodes/tree.ts @@ -1,4 +1,4 @@ -import type { WorkflowTask } from "../../types.js"; +import type { WorkflowTask } from "../types.js"; import type { FlattenedWorkflowTask } from "./types.js"; /** diff --git a/src/domains/platform/workflow/nodes/types.ts b/src/domains/platform/workflow/nodes/types.ts index 2d5d280..ec3dcf8 100644 --- a/src/domains/platform/workflow/nodes/types.ts +++ b/src/domains/platform/workflow/nodes/types.ts @@ -1,4 +1,4 @@ -import type { WorkflowTask } from "../../types.js"; +import type { WorkflowTask } from "../types.js"; export interface FlattenedWorkflowTask { task: WorkflowTask; diff --git a/src/domains/platform/workflow/queries.ts b/src/domains/platform/workflow/queries.ts new file mode 100644 index 0000000..0cdf8b2 --- /dev/null +++ b/src/domains/platform/workflow/queries.ts @@ -0,0 +1,206 @@ +import { listBasicPlatforms } from "../applications/services.js"; +import { KyInstance } from "ky"; +import { CorpConfig } from "../../../core/config/types.js"; +import * as api from "./api.js"; +import { WorkflowSummary, WorkflowListAllError, WorkflowTask, WorkflowWithMatches, TaskMatch } from "./types.js"; + + +export interface WorkflowClients { + corp: CorpConfig; + ekbClient: KyInstance; + easoClient: KyInstance; +} + + +export function listWorkflows(...args: Parameters) { + return api.listWorkflows(...args); +} + + +export function getWorkflowStats(...args: Parameters) { + return api.getWorkflowStats(...args); +} + + +export function getWorkflowCharge(...args: Parameters) { + return api.getWorkflowCharge(...args); +} + + +export function getWorkflowDetail(...args: Parameters) { + return api.getWorkflowDetail(...args); +} + + +export function listWorkflowSnapshots(...args: Parameters) { + return api.listWorkflowSnapshots(...args); +} + + +export function getWorkflowSnapshot(...args: Parameters) { + return api.getWorkflowSnapshot(...args); +} + + +export function listWorkflowLogs(...args: Parameters) { + return api.listWorkflowLogs(...args); +} + + +export function listRunningJobs(...args: Parameters) { + return api.listRunningJobs(...args); +} + + +export function getJob(...args: Parameters) { + return api.getJob(...args); +} + + +export function getJobExecutionTree(...args: Parameters) { + return api.getJobExecutionTree(...args); +} + + +export function getJobFailedExecutions(...args: Parameters) { + return api.getJobFailedExecutions(...args); +} + + +export function getJobExecutionLevel(...args: Parameters) { + return api.getJobExecutionLevel(...args); +} + + +export function getExecutionLogs(...args: Parameters) { + return api.getExecutionLogs(...args); +} + + +// ── 服务层:跨应用聚合 ─────────────────────────────────────────────────────── + +export interface ListAllWorkflowsOptions { + page?: number; + pageSize?: number; +} + + +export interface ListAllWorkflowsResult { + workflows: WorkflowSummary[]; + errors: WorkflowListAllError[]; +} + + +export async function listAllWorkflows( + clients: WorkflowClients, + options: ListAllWorkflowsOptions = {} +): Promise { + const { ekbClient, easoClient, corp } = clients; + const page = options.page ?? 1; + const pageSize = options.pageSize ?? 20; + + const platforms = await listBasicPlatforms(ekbClient, corp.credentials.corpId); + const enabledPlatforms = platforms.filter((p) => p.active !== false); + + const workflows: WorkflowSummary[] = []; + const errors: WorkflowListAllError[] = []; + + await Promise.all( + enabledPlatforms.map(async (platform) => { + try { + const pageResult = await api.listWorkflows( + easoClient, + platform.id, + page, + pageSize + ); + for (const workflow of pageResult.pipelineList) { + workflows.push({ + ...workflow, + platformId: platform.id, + platformName: platform.name, + }); + } + } catch (err) { + errors.push({ + platformId: platform.id, + platformName: platform.name, + error: err instanceof Error ? err.message : String(err), + }); + } + }) + ); + + return { workflows, errors }; +} + + +function collectTasksByType( + tasks: WorkflowTask[], + taskType: string, + matches: TaskMatch[] = [] +): TaskMatch[] { + for (const task of tasks) { + if (task.type === taskType) { + matches.push({ + taskName: task.name, + taskType: task.type, + levelIndex: task.levelIndex, + }); + } + if ("tasks" in task && Array.isArray(task.tasks)) { + collectTasksByType(task.tasks as WorkflowTask[], taskType, matches); + } + } + return matches; +} + + +export interface FindWorkflowsByTaskTypeOptions extends ListAllWorkflowsOptions { + includeDetail?: boolean; +} + + +export interface FindWorkflowsByTaskTypeResult { + workflows: WorkflowWithMatches[]; + errors: WorkflowListAllError[]; +} + + +export async function findWorkflowsByTaskType( + clients: WorkflowClients, + taskType: string, + options: FindWorkflowsByTaskTypeOptions = {} +): Promise { + const { easoClient } = clients; + const { includeDetail, ...listOptions } = options; + + const all = await listAllWorkflows(clients, listOptions); + const matched: WorkflowWithMatches[] = []; + const detailErrors: WorkflowListAllError[] = []; + + for (const workflow of all.workflows) { + let tasks = workflow.tasks; + + if (includeDetail) { + try { + const detail = await api.getWorkflowDetail(easoClient, workflow.id); + tasks = detail.tasks; + } catch (err) { + detailErrors.push({ + platformId: workflow.platformId, + platformName: workflow.platformName, + error: err instanceof Error ? err.message : String(err), + }); + continue; + } + } + + const matchedTasks = collectTasksByType(tasks, taskType); + if (matchedTasks.length > 0) { + matched.push({ ...workflow, matchedTasks }); + } + } + + return { workflows: matched, errors: [...all.errors, ...detailErrors] }; +} diff --git a/src/domains/platform/running-jobs.test.ts b/src/domains/platform/workflow/running-jobs.test.ts similarity index 95% rename from src/domains/platform/running-jobs.test.ts rename to src/domains/platform/workflow/running-jobs.test.ts index 30d843d..411bba7 100644 --- a/src/domains/platform/running-jobs.test.ts +++ b/src/domains/platform/workflow/running-jobs.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from "bun:test"; import type { KyInstance } from "ky"; import { z } from "zod"; -import { AuthenticationError, EkbApiError } from "../../core/errors.js"; -import { classifyCliError } from "../../cli/errors.js"; +import { AuthenticationError, EkbApiError } from "../../../core/errors.js"; +import { classifyCliError } from "../../../cli/errors.js"; import { listRunningJobs, unwrap } from "./api.js"; -import { watchWorkflowPipeline } from "./workflow/watch/pipeline-watcher.js"; +import { watchWorkflowPipeline } from "./watch/pipeline-watcher.js"; const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance; diff --git a/src/domains/platform/workflow/save-error.ts b/src/domains/platform/workflow/save-error.ts index 2e1b05c..c0dc9d0 100644 --- a/src/domains/platform/workflow/save-error.ts +++ b/src/domains/platform/workflow/save-error.ts @@ -1,5 +1,5 @@ import { EkbError } from "../../../core/errors.js"; -import type { WorkflowDetail } from "../types.js"; +import type { WorkflowDetail } from "./types.js"; /** 主保存已经提交,后续元数据刷新失败。调用方必须保留已保存版本。 */ export class WorkflowSavePartialError extends EkbError { diff --git a/src/domains/platform/workflow/script/README.script.md b/src/domains/platform/workflow/script/README.script.md new file mode 100644 index 0000000..d319775 --- /dev/null +++ b/src/domains/platform/workflow/script/README.script.md @@ -0,0 +1,22 @@ +# 工作流脚本校验与本地求值(script) + +本目录为代码节点提供静态检查、工作流脚本扫描和本地沙箱求值。它属于 [工作流子域](../README.workflow.md),不负责保存节点或触发真实工作流。 + +## 实现导航 + +| 文件 | 功能 | +|---|---| +| [lint-js.ts](./lint-js.ts) | JavaScript 检查及 return 识别 | +| [lint-mvel.ts](./lint-mvel.ts) | MVEL 检查和工作流节点名收集 | +| [scanner.ts](./scanner.ts) | 遍历工作流,汇总节点脚本问题 | +| [mvel-subset.ts](./mvel-subset.ts) | 支持的 MVEL 子集转换与末尾表达式识别 | +| [sandbox.ts](./sandbox.ts) | QuickJS 隔离运行时、输入注入、日志和求值结果 | +| [types.ts](./types.ts)、[index.ts](./index.ts) | 问题/求值结果模型及统一导出 | + +## 行为与能力边界 + +JavaScript 在独立 QuickJS 运行时中执行,设置超时、内存及输入/输出、日志限制;输入同时提供变量和 `inputs` 命名空间。求值仅支持同步结果,不共享宿主构造器,不把本地求值视为服务端脚本执行的完整替代。 + +MVEL 本地支持范围以 `mvel-subset.ts` 为准,不等价完整 Java/MVEL 运行时。静态检查与本地求值分别报告问题和结果;不能用“本地通过”推断租户权限、服务端上下文或业务写入一定成功。 + +修改语法支持时增加支持/拒绝的回归案例,并保持沙箱资源释放。测试见 [index.test.ts](./index.test.ts)、[mvel-subset.test.ts](./mvel-subset.test.ts);命令适配在 [script.ts](../../../../cli/commands/workflow/script.ts),业务脚本编写参考位于 [MVEL 产品技能](../../../../../skills/hose-use/multi/ekuaibao-mvel/SKILL.md)。 diff --git a/src/domains/platform/workflow/script/index.test.ts b/src/domains/platform/workflow/script/index.test.ts index 6fc5298..d8901be 100644 --- a/src/domains/platform/workflow/script/index.test.ts +++ b/src/domains/platform/workflow/script/index.test.ts @@ -7,7 +7,7 @@ import { executeJavaScriptSandbox, executeMvelSandbox, } from "./index.js"; -import type { WorkflowDetail } from "../../types.js"; +import type { WorkflowDetail } from "../types.js"; describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => { describe("hasReturnStatement", () => { diff --git a/src/domains/platform/workflow/script/lint-mvel.ts b/src/domains/platform/workflow/script/lint-mvel.ts index 52a5253..d84b55d 100644 --- a/src/domains/platform/workflow/script/lint-mvel.ts +++ b/src/domains/platform/workflow/script/lint-mvel.ts @@ -1,4 +1,4 @@ -import type { WorkflowTask } from "../../types.js"; +import type { WorkflowTask } from "../types.js"; import type { ScriptIssue } from "./types.js"; import { hasMvelFinalExpression } from "./mvel-subset.js"; diff --git a/src/domains/platform/workflow/script/scanner.ts b/src/domains/platform/workflow/script/scanner.ts index e374d85..6ef79c4 100644 --- a/src/domains/platform/workflow/script/scanner.ts +++ b/src/domains/platform/workflow/script/scanner.ts @@ -1,4 +1,4 @@ -import type { WorkflowDetail, WorkflowTask } from "../../types.js"; +import type { WorkflowDetail, WorkflowTask } from "../types.js"; import type { NodeScriptLintReport, WorkflowScriptLintReport, ScriptIssue } from "./types.js"; import { lintJavaScriptCode } from "./lint-js.js"; import { lintMvelCode, collectAllWorkflowNodeNames } from "./lint-mvel.js"; diff --git a/src/domains/platform/workflow/services.ts b/src/domains/platform/workflow/services.ts new file mode 100644 index 0000000..3e4d01a --- /dev/null +++ b/src/domains/platform/workflow/services.ts @@ -0,0 +1,81 @@ +// workflow 业务服务出口;具体实现按职责拆分,内部模块避免反向导入此门面。 +export { + listWorkflows, + getWorkflowStats, + getWorkflowCharge, + getWorkflowDetail, + listWorkflowSnapshots, + getWorkflowSnapshot, + listWorkflowLogs, + listRunningJobs, + getJob, + getJobExecutionTree, + getJobFailedExecutions, + getJobExecutionLevel, + getExecutionLogs, + listAllWorkflows, + findWorkflowsByTaskType, +} from "./queries.js"; +export type { + WorkflowClients, + ListAllWorkflowsOptions, + ListAllWorkflowsResult, + FindWorkflowsByTaskTypeOptions, + FindWorkflowsByTaskTypeResult, +} from "./queries.js"; +export { + sanitizeWorkflowSnapshot, + updateWorkflow, + refreshWorkflowChooses, + copyWorkflow, + buildInitialTriggerTask, + createWorkflow, + deleteWorkflow, + toggleWorkflow, +} from "./configuration.js"; +export type { + CreateWorkflowOptions, +} from "./configuration.js"; +export { + listDsl, + listStaffs, + getWorkflowEnumOptions, + resolveWorkflowEnumOptions, + getWorkflowAvailableNodes, + grantWorkflowNodes, +} from "./catalog.js"; +export { + getWebhookInfo, + sampleWorkflowData, + getWorkflowDebugSource, + triggerWorkflowDebug, + runWorkflowDebugTest, + getWorkflowSampleData, +} from "./debug.js"; +export { + flattenExecutionTree, + isTaskExecutionFailed, + extractFailureExecutions, + findExecutionNode, + flattenWorkflowTasks, +} from "./execution.js"; +export { + generateTextDiff, + diffWorkflowSnapshots, + diffWorkflowJobs, +} from "./diff.js"; + +export { + explainConditionBranches, + type ConditionBranchExplanation, + type ConditionRuleExplanation, +} from "./branch/index.js"; + +export { + classifyWorkflowTrigger, + type WorkflowTriggerCategory, + type WorkflowSampleRecord, + type WorkflowSampleDataResult, +} from "./types.js"; + +export * from "./index.js"; diff --git a/src/domains/platform/snapshot-config-diff.test.ts b/src/domains/platform/workflow/snapshot-config-diff.test.ts similarity index 100% rename from src/domains/platform/snapshot-config-diff.test.ts rename to src/domains/platform/workflow/snapshot-config-diff.test.ts diff --git a/src/domains/platform/workflow/state/index.test.ts b/src/domains/platform/workflow/state/index.test.ts index d762a1d..ad3e50c 100644 --- a/src/domains/platform/workflow/state/index.test.ts +++ b/src/domains/platform/workflow/state/index.test.ts @@ -8,8 +8,8 @@ import { hasWorkflowVersionConflict, patchWorkflowDraft, } from "./index.js"; -import { WorkflowDetailSchema } from "../../types.js"; -import type { WorkflowDetail } from "../../types.js"; +import { WorkflowDetailSchema } from "../types.js"; +import type { WorkflowDetail } from "../types.js"; import { getExecutionLogs, getJob, @@ -20,7 +20,7 @@ import { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, -} from "../../api.js"; +} from "../api.js"; import { extractFailureExecutions, findExecutionNode, @@ -28,7 +28,7 @@ import { isTaskExecutionFailed, updateWorkflow, sanitizeWorkflowSnapshot, -} from "../../services.js"; +} from "../services.js"; import { AuthenticationError, EkbApiError } from "../../../../core/errors.js"; import { WorkflowAlertStore } from "../alert/index.js"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; diff --git a/src/domains/platform/workflow/state/index.ts b/src/domains/platform/workflow/state/index.ts index 7a34379..df7086b 100644 --- a/src/domains/platform/workflow/state/index.ts +++ b/src/domains/platform/workflow/state/index.ts @@ -1,5 +1,5 @@ import { NotFoundError, ValidationError } from "../../../../core/errors.js"; -import type { WorkflowDetail } from "../../types.js"; +import type { WorkflowDetail } from "../types.js"; export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "partial" | "failed"; diff --git a/src/domains/platform/types.test.ts b/src/domains/platform/workflow/types.test.ts similarity index 100% rename from src/domains/platform/types.test.ts rename to src/domains/platform/workflow/types.test.ts diff --git a/src/domains/platform/types.ts b/src/domains/platform/workflow/types.ts similarity index 96% rename from src/domains/platform/types.ts rename to src/domains/platform/workflow/types.ts index 0a16985..78ce4fd 100644 --- a/src/domains/platform/types.ts +++ b/src/domains/platform/workflow/types.ts @@ -1,26 +1,5 @@ import { z } from "zod"; -// ── 自建应用(DataLink Platform)───────────────────────────── - -export const PlatformSchema = z.object({ - id: z.string(), - name: z.string(), - nameSpell: z.string().default(""), - enName: z.string().nullable().optional(), - code: z.string().default(""), - corporationId: z.string(), - active: z.boolean().default(true), - type: z.string().default(""), - groupType: z.string().default(""), - platformType: z.string().default(""), - source: z.string().default(""), - adminIds: z.array(z.string()).nullish().transform((value) => value ?? []), - desc: z.string().nullable().optional(), - importMethod: z.array(z.string()).nullish().transform((value) => value ?? []), - createTime: z.number().default(0), - updateTime: z.number().default(0), -}); - // ── 工作流任务节点(递归、按类型区分)───────────────────────────────────────── export const BaseTaskSchema = z.object({ @@ -561,7 +540,6 @@ export const WorkflowWithMatchesSchema = WorkflowSummarySchema.extend({ // ── 类型导出 ────────────────────────────────────────────────────────────────── -export type Platform = z.infer; export type FilterGroup = z.infer; export type WorkflowState = z.infer; export type Workflow = z.infer; @@ -727,7 +705,7 @@ export interface WorkflowTestReport { triggerLabel?: string; executionTree: WorkflowTaskExecution[]; failedExecutions: WorkflowTaskExecution[]; - conditionDiagnoses: import("./workflow/branch/index.js").ConditionBranchExplanation[]; + conditionDiagnoses: import("./branch/types.js").ConditionBranchExplanation[]; } // ── 触发器元类型分类与智能路径路由 ─────────────────────────────────────────────── diff --git a/src/domains/platform/workflow/watch/README.watch.md b/src/domains/platform/workflow/watch/README.watch.md new file mode 100644 index 0000000..0ef22d4 --- /dev/null +++ b/src/domains/platform/workflow/watch/README.watch.md @@ -0,0 +1,22 @@ +# 工作流执行监听(watch) + +本目录轮询工作流与 Job 状态,将节点变化转换为事件和汇总结果,供 CLI tail/watch 等入口使用。父级能力见 [工作流说明](../README.workflow.md)。 + +## 文件分工 + +| 文件 | 职责 | +|---|---| +| [pipeline-watcher.ts](./pipeline-watcher.ts) | `watchWorkflowPipeline`,发现和跟踪工作流执行,管理监听范围 | +| [single-job.ts](./single-job.ts) | `watchSingleJob`,读取单个 Job 与节点执行变化 | +| [tracker.ts](./tracker.ts) | 节点执行变化跟踪和事件去重,直接使用上级 execution 模块 | +| [helpers.ts](./helpers.ts) | 状态归一化、终态判断和错误提取 | +| [formatter.ts](./formatter.ts) | 将事件格式化为文本 | +| [types.ts](./types.ts)、[index.ts](./index.ts) | 事件、监听选项、结果类型及统一导出 | + +## 生命周期契约 + +监听选项包括轮询间隔、超时、最大 Job 数、单次快照、失败过滤、事件回调和取消信号。`once` 表示快照,不因为主动停止就标记超时;超时和取消分别返回,只有真实终态才报告 Job 完成。 + +鉴权失败不能作为“没有新执行”吞掉;其他日志回退沿用服务已有兼容行为。事件消费方应保留执行实例、循环路径和错误语义,不仅按节点名称判断是否同一次执行。 + +本层可以通过域 API 获取执行状态,但不导入 CLI、不自行写 stdout 或启用工作流;文本格式化与事件数据分别使用。测试见 [index.test.ts](./index.test.ts)、[timeout.test.ts](./timeout.test.ts),命令侧退出与输出在 [tail.ts](../../../../cli/commands/workflow/tail.ts) 处理。 diff --git a/src/domains/platform/workflow/watch/helpers.ts b/src/domains/platform/workflow/watch/helpers.ts index 881da1b..14a7d0b 100644 --- a/src/domains/platform/workflow/watch/helpers.ts +++ b/src/domains/platform/workflow/watch/helpers.ts @@ -1,4 +1,4 @@ -import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js"; +import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js"; export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); diff --git a/src/domains/platform/workflow/watch/index.test.ts b/src/domains/platform/workflow/watch/index.test.ts index d851104..866ca35 100644 --- a/src/domains/platform/workflow/watch/index.test.ts +++ b/src/domains/platform/workflow/watch/index.test.ts @@ -9,7 +9,7 @@ import { watchWorkflowPipeline, type WorkflowWatchEvent, } from "./index.js"; -import type { WorkflowTaskExecution } from "../../types.js"; +import type { WorkflowTaskExecution } from "../types.js"; describe("workflow-watch - 实时监控与日志流跟踪引擎", () => { describe("TaskExecutionTracker", () => { diff --git a/src/domains/platform/workflow/watch/pipeline-watcher.ts b/src/domains/platform/workflow/watch/pipeline-watcher.ts index 33fd249..0247673 100644 --- a/src/domains/platform/workflow/watch/pipeline-watcher.ts +++ b/src/domains/platform/workflow/watch/pipeline-watcher.ts @@ -1,6 +1,6 @@ import type { KyInstance } from "ky"; import { AuthenticationError } from "../../../../core/errors.js"; -import * as api from "../../api.js"; +import * as api from "../api.js"; import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js"; import { normalizeJobStatus, isJobTerminal } from "./helpers.js"; import { watchSingleJob } from "./single-job.js"; diff --git a/src/domains/platform/workflow/watch/single-job.ts b/src/domains/platform/workflow/watch/single-job.ts index 7aa05ba..a820430 100644 --- a/src/domains/platform/workflow/watch/single-job.ts +++ b/src/domains/platform/workflow/watch/single-job.ts @@ -1,6 +1,6 @@ import type { KyInstance } from "ky"; -import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js"; -import * as api from "../../api.js"; +import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js"; +import * as api from "../api.js"; import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js"; import { normalizeJobStatus, isJobTerminal } from "./helpers.js"; import { TaskExecutionTracker } from "./tracker.js"; diff --git a/src/domains/platform/workflow/watch/tracker.ts b/src/domains/platform/workflow/watch/tracker.ts index ed1cd9c..aa54e87 100644 --- a/src/domains/platform/workflow/watch/tracker.ts +++ b/src/domains/platform/workflow/watch/tracker.ts @@ -1,5 +1,5 @@ -import type { WorkflowTaskExecution } from "../../types.js"; -import { flattenExecutionTree, isTaskExecutionFailed } from "../../services.js"; +import type { WorkflowTaskExecution } from "../types.js"; +import { flattenExecutionTree, isTaskExecutionFailed } from "../execution.js"; import type { WorkflowWatchEvent } from "./types.js"; import { extractTaskErrorMessage } from "./helpers.js"; diff --git a/src/domains/platform/workflow/watch/types.ts b/src/domains/platform/workflow/watch/types.ts index d415942..cf9d639 100644 --- a/src/domains/platform/workflow/watch/types.ts +++ b/src/domains/platform/workflow/watch/types.ts @@ -1,4 +1,4 @@ -import type { WorkflowJobDetail } from "../../types.js"; +import type { WorkflowJobDetail } from "../types.js"; export type WorkflowWatchEventType = | "pipeline_watch_start" diff --git a/src/domains/platform/workflow-debug.test.ts b/src/domains/platform/workflow/workflow-debug.test.ts similarity index 100% rename from src/domains/platform/workflow-debug.test.ts rename to src/domains/platform/workflow/workflow-debug.test.ts diff --git a/src/domains/platform/write-result.test.ts b/src/domains/platform/workflow/write-result.test.ts similarity index 95% rename from src/domains/platform/write-result.test.ts rename to src/domains/platform/workflow/write-result.test.ts index 4ec071c..bc0b499 100644 --- a/src/domains/platform/write-result.test.ts +++ b/src/domains/platform/workflow/write-result.test.ts @@ -3,8 +3,8 @@ import ky from "ky"; import { deleteWorkflow, updateWorkflowChooses } from "./api.js"; import { refreshWorkflowChooses, updateWorkflow } from "./services.js"; import { WorkflowDetailSchema } from "./types.js"; -import { WorkflowSavePartialError } from "./workflow/save-error.js"; -import { AuthenticationError } from "../../core/errors.js"; +import { WorkflowSavePartialError } from "./save-error.js"; +import { AuthenticationError } from "../../../core/errors.js"; test("Piper 无返回值写操作兼容空成功,拒绝业务失败与无效 JSON", async () => { for (const action of [deleteWorkflow, updateWorkflowChooses]) { diff --git a/src/packaging/README.packaging.md b/src/packaging/README.packaging.md index caec481..12ae210 100644 --- a/src/packaging/README.packaging.md +++ b/src/packaging/README.packaging.md @@ -4,7 +4,7 @@ ## 文件职责 -- `embedded-openapi.ts`:内嵌 `specs/openapi.json`(包装层)与 `specs/openapi.raw.json`(原生下游)两份 OpenAPI 规范,供 `hose-use openapi` 命令与 HTTP 文档页读取;产物由 `scripts/bundle-openapi.ts` / `scripts/generate-raw-openapi.ts` 生成。 +- `embedded-openapi.ts`:内嵌 `specs/openapi.json`(包装层)与 `specs/openapi.raw.json`(原生下游)两份 OpenAPI 规范,供 `hose-use openapi` 命令与 HTTP 文档页读取;产物由 `scripts/generate/bundle-openapi.ts` / `scripts/generate/generate-raw-openapi.ts` 生成。 - `embedded-skill.ts`:内嵌 `skills/hose-use/` 全量 Skill 文件(`EMBEDDED_SKILL_FILES`),支持 `hose-use skill install --yes` 一键安装到全局目录,并在编译二进制运行时自动同步(`syncGlobalSkillIfPresent`)。 - `runtime.ts`:二进制运行态自省——`isCompiledBinary` 判定编译态、`resolveAppRoot` 解析应用根目录、`resolveDefaultLauncher` 解析启动配置。 @@ -50,8 +50,8 @@ Skill 初始化明确执行 `skill install --yes`;失败会报告二进制已 ## 构建与发布验证 - PR/main CI:冻结依赖安装、版本一致性、类型检查、全套测试、独立二进制和插件 bundle 的构建及 MCP 协议验证,以及完整插件包构建。测试会解包临时插件,核对包内清单和 Skill,并在独立目录验证离线脚本与 MCP 协议。 -- 独立二进制:`bun run build:binary`;`bun run scripts/verify-binary.ts dist/bin/hose-use` 在空工作目录和没有 Bun 的 PATH 下验证版本、单工具发现、真实调用与错误返回。 -- 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。 +- 独立二进制:`bun run build:binary`;`bun run scripts/build/verify-binary.ts dist/bin/hose-use` 在空工作目录和没有 Bun 的 PATH 下验证版本、单工具发现、真实调用与错误返回。 +- 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。 - Release:构建前检查 tag 版本、实际 HEAD 和 main 祖先关系;手动触发也必须输入 tag。正式构建显式使用 `--release`,两个发布源都上传校验清单,后台镜像上传失败会使任务失败。 Gitea 同时最多传输两个资产,每个资产最多尝试三次;已有文件经 SHA-256 验证一致时直接保留。镜像传输中断后,可在 main 上手动运行 Release workflow,传入原 tag 并启用 `mirror_only`:该模式下载并核对 GitHub 已发布资产(含插件包),只修复 Gitea,不重建或替换 GitHub 产物,也不移动 tag。 diff --git a/src/sdk.ts b/src/sdk.ts index 5c6dd31..e2a9410 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -7,39 +7,13 @@ export { initCorpRuntime, createClientsForCorp, requireSelectedCorp } from "./cl export { resolveCorpConfig } from "./core/config/manager.js"; // DataLink / 自建应用与业务对象能力 -export { - listPlatforms, - listAllPlatforms, - getPlatform, - resolvePlatform, - listPlatformEntities, - resolveEntity, - searchEntityRecords, - fetchAllEntityRecords, - iterateAllEntityRecords, - normalizeDatalinkRecord, - calculateEntityRecordStats, - auditEntityRecords, - aggregateRecordFields, - filterRecordsByPredicate, - batchSafeEditRecords, - editRecord, - safeEditRecord, - getRecordDetail, - toggleRecordState, -} from "./domains/datalink/services.js"; +export { listPlatforms, listAllPlatforms, getPlatform, resolvePlatform } from "./domains/platform/applications/services.js"; +export { listPlatformEntities, resolveEntity, searchEntityRecords, fetchAllEntityRecords, iterateAllEntityRecords, normalizeDatalinkRecord, calculateEntityRecordStats, auditEntityRecords, aggregateRecordFields, filterRecordsByPredicate, batchSafeEditRecords, editRecord, safeEditRecord, getRecordDetail, toggleRecordState } from "./domains/platform/datalink/services.js"; -export type { - DatalinkPlatformDetail, - DatalinkEntity, - DatalinkField, - DatalinkRecord, - NormalizedDatalinkRecord, - DatalinkRecordStats, - LedgerAggregateReport, -} from "./domains/datalink/types.js"; +export type { DatalinkPlatformDetail } from "./domains/platform/applications/types.js"; +export type { DatalinkEntity, DatalinkField, DatalinkRecord, NormalizedDatalinkRecord, DatalinkRecordStats, LedgerAggregateReport } from "./domains/platform/datalink/types.js"; export type { DatalinkAuditReport, BatchEditTargetItem, -} from "./domains/datalink/services.js"; +} from "./domains/platform/datalink/services.js";